text
stringlengths 54
60.6k
|
|---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: image.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-11-09 13:28:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_CANVAS_IMAGE_HXX
#define INCLUDED_CANVAS_IMAGE_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP_
#include <com/sun/star/rendering/XCanvas.hpp>
#endif
#ifndef INCLUDED_CANVAS_ICOLORBUFFER_HXX
#include <canvas/rendering/icolorbuffer.hxx>
#endif
#ifndef INCLUDED_CANVAS_PARAMETRICPOLYPOLYGON_HXX
#include <canvas/parametricpolypolygon.hxx>
#endif
#ifndef INCLUDED_CANVAS_IMAGECACHEDPRIMITIVE_HXX
#include "imagecachedprimitive.hxx"
#endif
#include <canvas/elapsedtime.hxx>
#include <agg/agg_rendering_buffer.h>
struct BitmapSystemData;
class BitmapEx;
namespace canvas
{
class Image : public IColorBuffer
{
public:
/// The description of the image
struct Description
{
IColorBuffer::Format eFormat;
sal_uInt32 nWidth;
sal_uInt32 nHeight;
sal_uInt32 nStride;
sal_uInt8* pBuffer;
};
/** Create a new image with the attributes passed as argument.
*/
explicit Image( const Description& desc );
/** Create a new image from the XBitmap passed as argument
*/
explicit Image( const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XBitmap >& xBitmap );
virtual ~Image();
/** Retrieve desciption of image layout
*/
const Description& getDescription() const { return maDesc; }
/** Clear image with uniform color
*/
void clear( sal_uInt8 a,
sal_uInt8 r,
sal_uInt8 g,
sal_uInt8 b );
void fillB2DPolyPolygon(
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
// IColorBuffer interface implementation
// =====================================
virtual sal_uInt8* lock() const;
virtual void unlock() const;
virtual sal_uInt32 getWidth() const;
virtual sal_uInt32 getHeight() const;
virtual sal_uInt32 getStride() const;
virtual Format getFormat() const;
// High-level drawing operations (from the XCanvas interface)
// ==========================================================
void drawPoint( const ::com::sun::star::geometry::RealPoint2D& aPoint,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
void drawLine( const ::com::sun::star::geometry::RealPoint2D& aStartPoint,
const ::com::sun::star::geometry::RealPoint2D& aEndPoint,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
void drawBezier( const ::com::sun::star::geometry::RealBezierSegment2D& aBezierSegment,
const ::com::sun::star::geometry::RealPoint2D& aEndPoint,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr drawPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr strokePolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::rendering::StrokeAttributes& strokeAttributes );
ImageCachedPrimitiveSharedPtr strokeTexturedPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::uno::Sequence<
::com::sun::star::rendering::Texture >& textures,
const ::std::vector< ::boost::shared_ptr<Image> >& textureAnnotations,
const ::com::sun::star::rendering::StrokeAttributes& strokeAttributes );
ImageCachedPrimitiveSharedPtr strokeTextureMappedPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::uno::Sequence<
::com::sun::star::rendering::Texture >& textures,
const ::std::vector< ::boost::shared_ptr<Image> >& textureAnnotations,
const ::com::sun::star::uno::Reference<
::com::sun::star::geometry::XMapping2D >& xMapping,
const ::com::sun::star::rendering::StrokeAttributes& strokeAttributes );
ImageCachedPrimitiveSharedPtr fillPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr fillTexturedPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::uno::Sequence<
::com::sun::star::rendering::Texture >& textures,
const ::std::vector< ::boost::shared_ptr<Image> >& textureAnnotations );
ImageCachedPrimitiveSharedPtr fillTextureMappedPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::uno::Sequence<
::com::sun::star::rendering::Texture >& textures,
const ::std::vector< ::boost::shared_ptr<Image> >& textureAnnotations,
const ::com::sun::star::uno::Reference<
::com::sun::star::geometry::XMapping2D >& xMapping );
ImageCachedPrimitiveSharedPtr drawBitmap(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XBitmap >& xBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr drawBitmap(
const ::boost::shared_ptr<Image>& rImage,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr drawBitmapModulated(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XBitmap >& xBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr drawBitmapModulated(
const ::boost::shared_ptr<Image>& rImage,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
private:
void drawLinePolyPolygon( const ::basegfx::B2DPolyPolygon& rPoly,
double fStrokeWidth,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr implDrawBitmap(
const Image& rBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr fillTexturedPolyPolygon(
const Image& rTexture,
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::basegfx::B2DHomMatrix& rOverallTransform,
const ::basegfx::B2DHomMatrix& rViewTransform,
const ::com::sun::star::rendering::Texture& texture );
void fillGradient( const ParametricPolyPolygon::Values& rValues,
const ::com::sun::star::uno::Sequence< double >& rColor1,
const ::com::sun::star::uno::Sequence< double >& rColor2,
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::basegfx::B2DHomMatrix& rOverallTransform,
const ::com::sun::star::rendering::Texture& texture );
bool fromVCLBitmap( ::BitmapEx& rBmpEx );
template<class pixel_format>
void drawLinePolyPolygonImpl( const ::basegfx::B2DPolyPolygon& rPoly,
double fStrokeWidth,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
template<class pixel_format,class span_gen_type>
ImageCachedPrimitiveSharedPtr fillTexturedPolyPolygonImpl(
const Image& rTexture,
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::basegfx::B2DHomMatrix& rOverallTransform,
const ::basegfx::B2DHomMatrix& rViewTransform,
const ::com::sun::star::rendering::Texture& texture );
template<class pixel_format>
void fillGradientImpl( const ParametricPolyPolygon::Values& rValues,
const ::com::sun::star::uno::Sequence< double >& rUnoColor1,
const ::com::sun::star::uno::Sequence< double >& rUnoColor2,
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::basegfx::B2DHomMatrix& rOverallTransform,
const ::com::sun::star::rendering::Texture& texture );
template<class pixel_format>
ImageCachedPrimitiveSharedPtr fillPolyPolygonImpl(
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
template<class pixel_format> void clearImpl( sal_uInt8 a,
sal_uInt8 r,
sal_uInt8 g,
sal_uInt8 b );
/** Image description
*/
Description maDesc;
/** the graphics buffer is a simple array
where each element points to the start
of a scanline in consecutive order.
*/
agg::rendering_buffer maRenderingBuffer;
/// Whether maRenderingBuffer is owned by the client of this object
bool mbBufferHasUserOwnership;
#if defined(PROFILER)
enum constant
{
TIMER_FILLTEXTUREDPOLYPOLYGON,
TIMER_FILLB2DPOLYPOLYGON,
TIMER_DRAWPOLYPOLYGON,
TIMER_FILLPOLYPOLYGON,
TIMER_DRAWBITMAP,
TIMER_MAX
};
double maElapsedTime[TIMER_MAX];
struct ScopeTimer
{
ScopeTimer( constant aConstant, Image *pImage ) :
maConstant(aConstant),mpImage(pImage)
{}
~ScopeTimer()
{
mpImage->maElapsedTime[maConstant] += maTimer.getElapsedTime();
}
constant maConstant;
Image* mpImage;
::canvas::tools::ElapsedTime maTimer;
};
#endif
};
typedef ::boost::shared_ptr< Image > ImageSharedPtr;
}
#endif /* INCLUDED_CANVAS_IMAGE_HXX */
<commit_msg>INTEGRATION: CWS systemagg (1.3.6); FILE MERGED 2005/11/23 10:58:30 rene 1.3.6.1: #i58336# add --with-system-agg<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: image.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-12-14 11:16:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_CANVAS_IMAGE_HXX
#define INCLUDED_CANVAS_IMAGE_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP_
#include <com/sun/star/rendering/XCanvas.hpp>
#endif
#ifndef INCLUDED_CANVAS_ICOLORBUFFER_HXX
#include <canvas/rendering/icolorbuffer.hxx>
#endif
#ifndef INCLUDED_CANVAS_PARAMETRICPOLYPOLYGON_HXX
#include <canvas/parametricpolypolygon.hxx>
#endif
#ifndef INCLUDED_CANVAS_IMAGECACHEDPRIMITIVE_HXX
#include "imagecachedprimitive.hxx"
#endif
#include <canvas/elapsedtime.hxx>
#include <agg2/agg_rendering_buffer.h>
struct BitmapSystemData;
class BitmapEx;
namespace canvas
{
class Image : public IColorBuffer
{
public:
/// The description of the image
struct Description
{
IColorBuffer::Format eFormat;
sal_uInt32 nWidth;
sal_uInt32 nHeight;
sal_uInt32 nStride;
sal_uInt8* pBuffer;
};
/** Create a new image with the attributes passed as argument.
*/
explicit Image( const Description& desc );
/** Create a new image from the XBitmap passed as argument
*/
explicit Image( const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XBitmap >& xBitmap );
virtual ~Image();
/** Retrieve desciption of image layout
*/
const Description& getDescription() const { return maDesc; }
/** Clear image with uniform color
*/
void clear( sal_uInt8 a,
sal_uInt8 r,
sal_uInt8 g,
sal_uInt8 b );
void fillB2DPolyPolygon(
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
// IColorBuffer interface implementation
// =====================================
virtual sal_uInt8* lock() const;
virtual void unlock() const;
virtual sal_uInt32 getWidth() const;
virtual sal_uInt32 getHeight() const;
virtual sal_uInt32 getStride() const;
virtual Format getFormat() const;
// High-level drawing operations (from the XCanvas interface)
// ==========================================================
void drawPoint( const ::com::sun::star::geometry::RealPoint2D& aPoint,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
void drawLine( const ::com::sun::star::geometry::RealPoint2D& aStartPoint,
const ::com::sun::star::geometry::RealPoint2D& aEndPoint,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
void drawBezier( const ::com::sun::star::geometry::RealBezierSegment2D& aBezierSegment,
const ::com::sun::star::geometry::RealPoint2D& aEndPoint,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr drawPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr strokePolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::rendering::StrokeAttributes& strokeAttributes );
ImageCachedPrimitiveSharedPtr strokeTexturedPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::uno::Sequence<
::com::sun::star::rendering::Texture >& textures,
const ::std::vector< ::boost::shared_ptr<Image> >& textureAnnotations,
const ::com::sun::star::rendering::StrokeAttributes& strokeAttributes );
ImageCachedPrimitiveSharedPtr strokeTextureMappedPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::uno::Sequence<
::com::sun::star::rendering::Texture >& textures,
const ::std::vector< ::boost::shared_ptr<Image> >& textureAnnotations,
const ::com::sun::star::uno::Reference<
::com::sun::star::geometry::XMapping2D >& xMapping,
const ::com::sun::star::rendering::StrokeAttributes& strokeAttributes );
ImageCachedPrimitiveSharedPtr fillPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr fillTexturedPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::uno::Sequence<
::com::sun::star::rendering::Texture >& textures,
const ::std::vector< ::boost::shared_ptr<Image> >& textureAnnotations );
ImageCachedPrimitiveSharedPtr fillTextureMappedPolyPolygon(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState,
const ::com::sun::star::uno::Sequence<
::com::sun::star::rendering::Texture >& textures,
const ::std::vector< ::boost::shared_ptr<Image> >& textureAnnotations,
const ::com::sun::star::uno::Reference<
::com::sun::star::geometry::XMapping2D >& xMapping );
ImageCachedPrimitiveSharedPtr drawBitmap(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XBitmap >& xBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr drawBitmap(
const ::boost::shared_ptr<Image>& rImage,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr drawBitmapModulated(
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XBitmap >& xBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr drawBitmapModulated(
const ::boost::shared_ptr<Image>& rImage,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
private:
void drawLinePolyPolygon( const ::basegfx::B2DPolyPolygon& rPoly,
double fStrokeWidth,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr implDrawBitmap(
const Image& rBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
ImageCachedPrimitiveSharedPtr fillTexturedPolyPolygon(
const Image& rTexture,
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::basegfx::B2DHomMatrix& rOverallTransform,
const ::basegfx::B2DHomMatrix& rViewTransform,
const ::com::sun::star::rendering::Texture& texture );
void fillGradient( const ParametricPolyPolygon::Values& rValues,
const ::com::sun::star::uno::Sequence< double >& rColor1,
const ::com::sun::star::uno::Sequence< double >& rColor2,
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::basegfx::B2DHomMatrix& rOverallTransform,
const ::com::sun::star::rendering::Texture& texture );
bool fromVCLBitmap( ::BitmapEx& rBmpEx );
template<class pixel_format>
void drawLinePolyPolygonImpl( const ::basegfx::B2DPolyPolygon& rPoly,
double fStrokeWidth,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
template<class pixel_format,class span_gen_type>
ImageCachedPrimitiveSharedPtr fillTexturedPolyPolygonImpl(
const Image& rTexture,
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::basegfx::B2DHomMatrix& rOverallTransform,
const ::basegfx::B2DHomMatrix& rViewTransform,
const ::com::sun::star::rendering::Texture& texture );
template<class pixel_format>
void fillGradientImpl( const ParametricPolyPolygon::Values& rValues,
const ::com::sun::star::uno::Sequence< double >& rUnoColor1,
const ::com::sun::star::uno::Sequence< double >& rUnoColor2,
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::basegfx::B2DHomMatrix& rOverallTransform,
const ::com::sun::star::rendering::Texture& texture );
template<class pixel_format>
ImageCachedPrimitiveSharedPtr fillPolyPolygonImpl(
const ::basegfx::B2DPolyPolygon& rPolyPolygon,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
template<class pixel_format> void clearImpl( sal_uInt8 a,
sal_uInt8 r,
sal_uInt8 g,
sal_uInt8 b );
/** Image description
*/
Description maDesc;
/** the graphics buffer is a simple array
where each element points to the start
of a scanline in consecutive order.
*/
agg::rendering_buffer maRenderingBuffer;
/// Whether maRenderingBuffer is owned by the client of this object
bool mbBufferHasUserOwnership;
#if defined(PROFILER)
enum constant
{
TIMER_FILLTEXTUREDPOLYPOLYGON,
TIMER_FILLB2DPOLYPOLYGON,
TIMER_DRAWPOLYPOLYGON,
TIMER_FILLPOLYPOLYGON,
TIMER_DRAWBITMAP,
TIMER_MAX
};
double maElapsedTime[TIMER_MAX];
struct ScopeTimer
{
ScopeTimer( constant aConstant, Image *pImage ) :
maConstant(aConstant),mpImage(pImage)
{}
~ScopeTimer()
{
mpImage->maElapsedTime[maConstant] += maTimer.getElapsedTime();
}
constant maConstant;
Image* mpImage;
::canvas::tools::ElapsedTime maTimer;
};
#endif
};
typedef ::boost::shared_ptr< Image > ImageSharedPtr;
}
#endif /* INCLUDED_CANVAS_IMAGE_HXX */
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "paddle/framework/eigen.h"
#include <gtest/gtest.h>
namespace paddle {
namespace framework {
TEST(EigenDim, From) {
EigenDim<3>::Type ed = EigenDim<3>::From(make_ddim({1, 2, 3}));
EXPECT_EQ(1, ed[0]);
EXPECT_EQ(2, ed[1]);
EXPECT_EQ(3, ed[2]);
}
TEST(Eigen, Tensor) {
Tensor t;
float* p = t.mutable_data<float>(make_ddim({1, 2, 3}), platform::CPUPlace());
for (int i = 0; i < 1 * 2 * 3; i++) {
p[i] = static_cast<float>(i);
}
EigenTensor<float, 3>::Type et = EigenTensor<float, 3>::From(t);
for (int i = 0; i < 1 * 2 * 3; i++) {
EXPECT_EQ(et(i), i);
}
// TODO: check the content of et.
}
TEST(Eigen, Vector) {}
TEST(Eigen, Matrix) {}
} // namespace framework
} // namespace paddle
<commit_msg>add more uinttest for EigenTensor<commit_after>/*
Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "paddle/framework/eigen.h"
#include <gtest/gtest.h>
namespace paddle {
namespace framework {
TEST(EigenDim, From) {
EigenDim<3>::Type ed = EigenDim<3>::From(make_ddim({1, 2, 3}));
EXPECT_EQ(1, ed[0]);
EXPECT_EQ(2, ed[1]);
EXPECT_EQ(3, ed[2]);
}
TEST(Eigen, Tensor) {
Tensor t;
float* p = t.mutable_data<float>(make_ddim({1, 2, 3}), platform::CPUPlace());
for (int i = 0; i < 1 * 2 * 3; i++) {
p[i] = static_cast<float>(i);
}
EigenTensor<float, 3>::Type et = EigenTensor<float, 3>::From(t);
EXPECT_EQ(1, et.dimension(0));
EXPECT_EQ(2, et.dimension(1));
EXPECT_EQ(3, et.dimension(2));
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
EXPECT_EQ((i * 2 + j) * 3 + k, et(i, j, k));
}
}
}
for (int i = 0; i < 1 * 2 * 3; i++) {
EXPECT_EQ(i, et(i));
}
}
TEST(Eigen, VectorFrom) {
Tensor t;
float* p = t.mutable_data<float>(make_ddim({6}), platform::CPUPlace());
for (int i = 0; i < 6; i++) {
p[i] = static_cast<float>(i);
}
EigenVector<float>::Type ev = EigenVector<float>::From(t);
EXPECT_EQ(6, ev.dimension(0));
for (int i = 0; i < 6; i++) {
EXPECT_EQ(i, ev(i));
}
}
TEST(Eigen, VectorFlatten) {
Tensor t;
float* p = t.mutable_data<float>(make_ddim({1, 2, 3}), platform::CPUPlace());
for (int i = 0; i < 1 * 2 * 3; i++) {
p[i] = static_cast<float>(i);
}
EigenVector<float>::Type ev = EigenVector<float>::Flatten(t);
EXPECT_EQ(1 * 2 * 3, ev.dimension(0));
for (int i = 0; i < 1 * 2 * 3; i++) {
EXPECT_EQ(i, ev(i));
}
}
TEST(Eigen, Matrix) {
Tensor t;
float* p = t.mutable_data<float>(make_ddim({2, 3}), platform::CPUPlace());
for (int i = 0; i < 2 * 3; i++) {
p[i] = static_cast<float>(i);
}
EigenMatrix<float>::Type em = EigenMatrix<float>::From(t);
EXPECT_EQ(2, em.dimension(0));
EXPECT_EQ(3, em.dimension(1));
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
EXPECT_EQ(i * 3 + j, em(i, j));
}
}
}
} // namespace framework
} // namespace paddle
<|endoftext|>
|
<commit_before>#include "common.hh"
#include <algorithm>
#include <cinttypes>
#include <iostream>
#include <memory>
#include <string>
#include "auth.hh"
// #include "cookies.hh"
#include "cgi.hh"
#include "config.hh"
#include "db.hh"
#include "event.hh"
#include "event_utils.hh"
#include "http.hh"
#include "sender_client.hh"
using namespace stuff;
namespace {
std::unique_ptr<Config> g_cfg;
std::unique_ptr<SenderClient> g_sender;
class Page;
Page* g_page;
class Page {
public:
Page(const std::string& channel)
: channel_(channel) {
assert(!g_page);
g_page = this;
header();
}
~Page() {
footer();
assert(g_page == this);
g_page = nullptr;
std::map<std::string, std::string> headers;
headers.insert(
std::make_pair("Content-Type", "text/html; charset=utf-8"));
Http::response(200, headers, content_);
}
void write(const std::string& text) {
content_.append(text);
}
void write_safe(const std::string& text) {
auto last = text.begin();
std::string tmp;
for (auto it = last; it != text.end(); ++it) {
if (!is_safe(*it, &tmp)) {
content_.append(last, it);
content_.push_back('&');
content_.append(tmp);
content_.push_back(';');
last = it + 1;
}
}
content_.append(last, text.end());
}
private:
static bool is_safe(char c, std::string* out) {
switch (c) {
case '<':
out->assign("lt");
return false;
case '>':
out->assign("gt");
return false;
case '&':
out->assign("amp");
return false;
case '"':
out->assign("quot");
return false;
default:
return true;
}
}
void header() {
write("<!doctype html>");
write("<html>");
write("<head>");
write("<title>Event for ");
write_safe(channel_);
write("</title>");
std::string stylesheet;
if (g_cfg) stylesheet = g_cfg->get("stylesheet", "");
if (!stylesheet.empty()) {
write("<link rel=\"stylesheet\" href=\"");
write_safe(stylesheet);
write("\">");
}
write("</head>");
write("<body>");
write("<div id=\"content\">");
}
void footer() {
write("</div>");
write("</body>");
write("</html>");
}
std::string channel_;
std::string content_;
};
void error_response(const std::string& message) {
g_page->write("<h2>Error</h2>");
g_page->write("<p>");
g_page->write_safe(message);
g_page->write("</p>");
}
std::string get_channel(CGI* cgi) {
auto path = cgi->request_path();
if (path.empty()) return path;
size_t end = path.size();
if (path.back() == '/') end--;
size_t start = 0;
if (path.front() == '/') start++;
return path.substr(start, end - start);
}
bool show(CGI* cgi, EventUtils* utils, const std::string& user) {
Page page(utils->channel());
auto event = utils->next();
if (!utils->good()) return true;
if (!event) {
page.write("<h2>No event scheduled</h2>");
return true;
}
page.write("<h1>");
page.write_safe(event->name());
page.write(" @ ");
page.write_safe(EventUtils::format_date(event->start()));
page.write("</h1>");
std::vector<Event::Going> going;
event->going(&going);
int8_t state = 0;
std::string note;
if (going.empty()) {
page.write("<p>Expect no-one</p>");
} else {
page.write("<p id=\"going\">");
auto it = going.begin();
for (; it != going.end(); ++it) {
if (!it->is_going) break;
if (it->name == user) {
state = 1;
note = it->note;
}
page.write("<span class=\"name\">");
page.write_safe(it->name);
page.write("</span>");
if (!it->note.empty()) {
page.write(" <span class=\"note\">");
page.write_safe(it->note);
page.write("</span>");
}
page.write("<br>");
}
if (it != going.end()) {
page.write("</p><h3>Not going</h3><p id=\"not_going\">");
for (; it != going.end(); ++it) {
if (it->name == user) {
state = -1;
note = it->note;
}
page.write("<span class=\"name\">");
page.write_safe(it->name);
page.write("</span>");
if (!it->note.empty()) {
page.write(" <span class=\"note\">");
page.write_safe(it->note);
page.write("</span>");
}
page.write("<br>");
}
}
}
page.write("</p>");
page.write("<form action=\"");
page.write_safe(cgi->request_uri());
page.write("\" method=\"post\">");
page.write("<input type=\"hidden\" name=\"id\" value=\"");
char tmp[100];
snprintf(tmp, sizeof(tmp), "%" PRId64, event->id());
page.write_safe(tmp);
page.write("\">");
page.write("<p>");
if (state == 0) {
page.write("<input type=\"submit\" name=\"going\" value=\"Going\">");
page.write("<input type=\"submit\" name=\"not_going\" value=\"Not going\">");
page.write("<br>");
page.write("<input type=\"text\" name=\"note\" value=\"\">");
} else if (state < 0) {
page.write("<input type=\"submit\" name=\"going\" value=\"Going\">");
page.write("<br>");
page.write("<input type=\"text\" name=\"note\" value=\"");
page.write_safe(note);
page.write("\">");
} else /* if (state > 0) */ {
page.write("<input type=\"submit\" name=\"not_going\" value=\"Not going\">");
page.write("<br>");
page.write("<input type=\"text\" name=\"note\" value=\"");
page.write_safe(note);
page.write("\">");
}
page.write("</p>");
page.write("</form>");
return true;
}
bool going(CGI* cgi, EventUtils* utils, const std::string& user,
const std::map<std::string, std::string>& data) {
bool const is_going = !data.at("going").empty();
std::string note;
auto it = data.find("note");
if (it != data.end()) note = it->second;
char* end = nullptr;
long long tmp;
it = data.find("id");
if (it != data.end()) {
errno = 0;
tmp = strtoll(it->second.c_str(), &end, 10);
}
if (errno == 0 && end && !*end) {
auto events = utils->all();
if (!utils->good()) return true;
for (auto& event : events) {
if (event->id() == tmp) {
event->update_going(user, is_going, note);
if (event->store()) {
utils->going(event.get(), is_going, user,
cgi->remote_addr());
}
}
}
}
// Redirect the POST response to a GET request
auto link = cgi->request_uri();
std::map<std::string, std::string> headers;
headers.insert(std::make_pair("Content-Type", "text/plain"));
headers.insert(std::make_pair("Location", link));
Http::response(303, headers, link);
return true;
}
bool handle_request(CGI* cgi) {
switch (cgi->request_type()) {
case CGI::GET:
case CGI::POST:
break;
default:
Http::response(500, "Unsupported request");
return true;
}
auto channel = get_channel(cgi);
if (channel.empty()) {
Http::response(500, "Bad channel");
return true;
}
std::string passwd;
bool ok_passwd = false;
if (g_cfg) {
passwd = g_cfg->get(channel, "bad");
if (passwd != "bad") {
ok_passwd = true;
} else {
passwd = g_cfg->get(channel, "bad2");
if (passwd != "bad2") {
ok_passwd = true;
}
}
}
if (!ok_passwd) {
Http::response(500, "Bad channel");
return true;
}
std::string user;
if (!Auth::auth(cgi, "Event for " + channel, passwd, &user)) {
return true;
}
auto utils = EventUtils::create(channel, error_response, g_cfg.get(),
g_sender.get());
std::map<std::string, std::string> data;
cgi->get_data(&data);
if (!data["going"].empty() || !data["not_going"].empty()) {
return going(cgi, utils.get(), user, data);
}
return show(cgi, utils.get(), user);
}
} // namespace
int main() {
g_cfg = Config::create();
if (!g_cfg->load("./page.config")) {
g_cfg->load(SYSCONFDIR "/page.config");
}
g_sender = SenderClient::create(g_cfg.get());
int ret = CGI::run(handle_request);
g_sender.reset();
g_cfg.reset();
return ret;
}
<commit_msg>Include event text<commit_after>#include "common.hh"
#include <algorithm>
#include <cinttypes>
#include <iostream>
#include <memory>
#include <string>
#include "auth.hh"
#include "cgi.hh"
#include "config.hh"
#include "db.hh"
#include "event.hh"
#include "event_utils.hh"
#include "http.hh"
#include "sender_client.hh"
using namespace stuff;
namespace {
std::unique_ptr<Config> g_cfg;
std::unique_ptr<SenderClient> g_sender;
class Page;
Page* g_page;
class Page {
public:
Page(const std::string& channel)
: channel_(channel) {
assert(!g_page);
g_page = this;
header();
}
~Page() {
footer();
assert(g_page == this);
g_page = nullptr;
std::map<std::string, std::string> headers;
headers.insert(
std::make_pair("Content-Type", "text/html; charset=utf-8"));
Http::response(200, headers, content_);
}
void write(const std::string& text) {
content_.append(text);
}
void write_safe(const std::string& text) {
auto last = text.begin();
std::string tmp;
for (auto it = last; it != text.end(); ++it) {
if (!is_safe(*it, &tmp)) {
content_.append(last, it);
content_.push_back('&');
content_.append(tmp);
content_.push_back(';');
last = it + 1;
}
}
content_.append(last, text.end());
}
private:
static bool is_safe(char c, std::string* out) {
switch (c) {
case '<':
out->assign("lt");
return false;
case '>':
out->assign("gt");
return false;
case '&':
out->assign("amp");
return false;
case '"':
out->assign("quot");
return false;
default:
return true;
}
}
void header() {
write("<!doctype html>");
write("<html>");
write("<head>");
write("<title>Event for ");
write_safe(channel_);
write("</title>");
std::string stylesheet;
if (g_cfg) stylesheet = g_cfg->get("stylesheet", "");
if (!stylesheet.empty()) {
write("<link rel=\"stylesheet\" href=\"");
write_safe(stylesheet);
write("\">");
}
write("</head>");
write("<body>");
write("<div id=\"content\">");
}
void footer() {
write("</div>");
write("</body>");
write("</html>");
}
std::string channel_;
std::string content_;
};
void error_response(const std::string& message) {
g_page->write("<h2>Error</h2>");
g_page->write("<p>");
g_page->write_safe(message);
g_page->write("</p>");
}
std::string get_channel(CGI* cgi) {
auto path = cgi->request_path();
if (path.empty()) return path;
size_t end = path.size();
if (path.back() == '/') end--;
size_t start = 0;
if (path.front() == '/') start++;
return path.substr(start, end - start);
}
bool show(CGI* cgi, EventUtils* utils, const std::string& user) {
Page page(utils->channel());
auto event = utils->next();
if (!utils->good()) return true;
if (!event) {
page.write("<h2>No event scheduled</h2>");
return true;
}
page.write("<h1>");
page.write_safe(event->name());
page.write(" @ ");
page.write_safe(EventUtils::format_date(event->start()));
page.write("</h1>");
page.write("<p>");
page.write_safe(event->text());
page.write("</p>");
std::vector<Event::Going> going;
event->going(&going);
int8_t state = 0;
std::string note;
if (going.empty()) {
page.write("<p>Expect no-one</p>");
} else {
page.write("<p id=\"going\">");
auto it = going.begin();
for (; it != going.end(); ++it) {
if (!it->is_going) break;
if (it->name == user) {
state = 1;
note = it->note;
}
page.write("<span class=\"name\">");
page.write_safe(it->name);
page.write("</span>");
if (!it->note.empty()) {
page.write(" <span class=\"note\">");
page.write_safe(it->note);
page.write("</span>");
}
page.write("<br>");
}
if (it != going.end()) {
page.write("</p><h3>Not going</h3><p id=\"not_going\">");
for (; it != going.end(); ++it) {
if (it->name == user) {
state = -1;
note = it->note;
}
page.write("<span class=\"name\">");
page.write_safe(it->name);
page.write("</span>");
if (!it->note.empty()) {
page.write(" <span class=\"note\">");
page.write_safe(it->note);
page.write("</span>");
}
page.write("<br>");
}
}
}
page.write("</p>");
page.write("<form action=\"");
page.write_safe(cgi->request_uri());
page.write("\" method=\"post\">");
page.write("<input type=\"hidden\" name=\"id\" value=\"");
char tmp[100];
snprintf(tmp, sizeof(tmp), "%" PRId64, event->id());
page.write_safe(tmp);
page.write("\">");
page.write("<p>");
if (state == 0) {
page.write("<input type=\"submit\" name=\"going\" value=\"Going\">");
page.write("<input type=\"submit\" name=\"not_going\" value=\"Not going\">");
page.write("<br>");
page.write("<input type=\"text\" name=\"note\" value=\"\">");
} else if (state < 0) {
page.write("<input type=\"submit\" name=\"going\" value=\"Going\">");
page.write("<br>");
page.write("<input type=\"text\" name=\"note\" value=\"");
page.write_safe(note);
page.write("\">");
} else /* if (state > 0) */ {
page.write("<input type=\"submit\" name=\"not_going\" value=\"Not going\">");
page.write("<br>");
page.write("<input type=\"text\" name=\"note\" value=\"");
page.write_safe(note);
page.write("\">");
}
page.write("</p>");
page.write("</form>");
return true;
}
bool going(CGI* cgi, EventUtils* utils, const std::string& user,
const std::map<std::string, std::string>& data) {
bool const is_going = !data.at("going").empty();
std::string note;
auto it = data.find("note");
if (it != data.end()) note = it->second;
char* end = nullptr;
long long tmp;
it = data.find("id");
if (it != data.end()) {
errno = 0;
tmp = strtoll(it->second.c_str(), &end, 10);
}
if (errno == 0 && end && !*end) {
auto events = utils->all();
if (!utils->good()) return true;
for (auto& event : events) {
if (event->id() == tmp) {
event->update_going(user, is_going, note);
if (event->store()) {
utils->going(event.get(), is_going, user,
cgi->remote_addr());
}
}
}
}
// Redirect the POST response to a GET request
auto link = cgi->request_uri();
std::map<std::string, std::string> headers;
headers.insert(std::make_pair("Content-Type", "text/plain"));
headers.insert(std::make_pair("Location", link));
Http::response(303, headers, link);
return true;
}
bool handle_request(CGI* cgi) {
switch (cgi->request_type()) {
case CGI::GET:
case CGI::POST:
break;
default:
Http::response(500, "Unsupported request");
return true;
}
auto channel = get_channel(cgi);
if (channel.empty()) {
Http::response(500, "Bad channel");
return true;
}
std::string passwd;
bool ok_passwd = false;
if (g_cfg) {
passwd = g_cfg->get(channel, "bad");
if (passwd != "bad") {
ok_passwd = true;
} else {
passwd = g_cfg->get(channel, "bad2");
if (passwd != "bad2") {
ok_passwd = true;
}
}
}
if (!ok_passwd) {
Http::response(500, "Bad channel");
return true;
}
std::string user;
if (!Auth::auth(cgi, "Event for " + channel, passwd, &user)) {
return true;
}
auto utils = EventUtils::create(channel, error_response, g_cfg.get(),
g_sender.get());
std::map<std::string, std::string> data;
cgi->get_data(&data);
if (!data["going"].empty() || !data["not_going"].empty()) {
return going(cgi, utils.get(), user, data);
}
return show(cgi, utils.get(), user);
}
} // namespace
int main() {
g_cfg = Config::create();
if (!g_cfg->load("./page.config")) {
g_cfg->load(SYSCONFDIR "/page.config");
}
g_sender = SenderClient::create(g_cfg.get());
int ret = CGI::run(handle_request);
g_sender.reset();
g_cfg.reset();
return ret;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <util/MslUtils.h>
#include <crypto/IRandom.h>
#include <util/Base64.h>
#include <util/MslContext.h>
#include <assert.h>
#include <MslError.h>
#include <MslException.h>
#include <MslCryptoException.h>
#include <MslEncodingException.h>
#include <MslEntityAuthException.h>
#include <MslKeyExchangeException.h>
#include <MslMasterTokenException.h>
#include <MslMessageException.h>
#include <MslUserAuthException.h>
#include <MslUserIdTokenException.h>
#include <string.h>
#include <zlib.h>
#include <algorithm>
#include <sstream>
#include <streambuf>
#include <memory>
using namespace std;
using namespace netflix::msl::crypto;
namespace {
// --- GZIP compress / decompress ---
// Original: http://panthema.net/2007/0328-ZLibString.html, Timo Bingmann
// Edited to support gzip: http://blog.cppse.nl/deflate-and-gzip-compress-and-decompress-functions, Ray Burgemeestre
// License: http://www.boost.org/LICENSE_1_0.txt
// Edited to support vector instead of string.
// Found these here http://mail-archives.apache.org/mod_mbox/trafficserver-dev/201110.mbox/%3CCACJPjhYf=+br1W39vyazP=ix
//eQZ-4Gh9-U6TtiEdReG3S4ZZng@mail.gmail.com%3E
#define MOD_GZIP_ZLIB_WINDOWSIZE 15
#define MOD_GZIP_ZLIB_CFACTOR 9
#define MOD_GZIP_ZLIB_BSIZE 8096
const size_t BUFSIZE = 16 * 1024;
uint8_t tmpBuf[BUFSIZE];
void compress_gzip(const vector<uint8_t>& in, vector<uint8_t>& out,
int compressionlevel = Z_BEST_COMPRESSION)
{
z_stream zs; // z_stream is zlib's control structure
memset(&zs, 0, sizeof(zs));
if (deflateInit2(&zs,
compressionlevel,
Z_DEFLATED,
MOD_GZIP_ZLIB_WINDOWSIZE + 16,
MOD_GZIP_ZLIB_CFACTOR,
Z_DEFAULT_STRATEGY) != Z_OK
) {
throw(runtime_error("deflateInit2 failed while compressing."));
}
zs.next_in = (Bytef*)in.data();
zs.avail_in = (uInt)in.size(); // set the z_stream's input
int ret;
vector<uint8_t> tmpOut;
// retrieve the compressed bytes blockwise
do {
zs.next_out = reinterpret_cast<Bytef*>(tmpBuf);
zs.avail_out = sizeof(tmpBuf);
ret = deflate(&zs, Z_FINISH);
if (tmpOut.size() < zs.total_out) {
// append the block to the output
tmpOut.insert(tmpOut.end(), tmpBuf, tmpBuf + zs.total_out - tmpOut.size());
}
} while (ret == Z_OK);
deflateEnd(&zs);
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
ostringstream oss;
oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
throw(runtime_error(oss.str()));
}
out.swap(tmpOut);;
}
void decompress_gzip(const vector<uint8_t>& in, vector<uint8_t>& out)
{
z_stream zs; // z_stream is zlib's control structure
memset(&zs, 0, sizeof(zs));
if (inflateInit2(&zs, MOD_GZIP_ZLIB_WINDOWSIZE + 16) != Z_OK)
throw(runtime_error("inflateInit failed while decompressing."));
zs.next_in = (Bytef*)in.data();
zs.avail_in = (uInt)in.size();
int ret;
vector<uint8_t> tmpOut;
// get the decompressed bytes blockwise using repeated calls to inflate
do {
zs.next_out = reinterpret_cast<Bytef*>(tmpBuf);
zs.avail_out = sizeof(tmpBuf);
ret = inflate(&zs, 0);
if (tmpOut.size() < zs.total_out) {
tmpOut.insert(tmpOut.end(), tmpBuf, tmpBuf + zs.total_out - tmpOut.size());
}
} while (ret == Z_OK);
inflateEnd(&zs);
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
ostringstream oss;
oss << "Exception during zlib decompression: (" << ret << ") "
<< zs.msg;
throw(runtime_error(oss.str()));
}
out.swap(tmpOut);
}
bool insStringCompare_pred(unsigned char a, unsigned char b) {
return tolower(a) == tolower(b);
}
/**
* Return true if the number is a non-negative power of two. Zero is
* considered a power of two and will return true.
*
* @param n the number to test.
* @return true if the number is a non-negative power of two.
*/
bool is_power_of_2(uint64_t n) {
// If the number is a power of two, a binary AND operation between
// the number and itself minus one will equal zero.
if (n == 0) return true;
return (n & (n - 1)) == 0;
}
} // namespace anonymous
namespace netflix {
namespace msl {
namespace util {
namespace MslUtils {
shared_ptr<ByteArray> compress(const MslConstants::CompressionAlgorithm& compressionAlgo,
const ByteArray& data)
{
try {
shared_ptr<ByteArray> compressed = make_shared<ByteArray>();
if (compressionAlgo == MslConstants::CompressionAlgorithm::GZIP) {
compress_gzip(data, *compressed);
} else {
throw MslException(MslError::UNSUPPORTED_COMPRESSION, compressionAlgo.toString());
}
return compressed;
} catch (const Exception& e) {
shared_ptr<string> dataB64 = Base64::encode(data);
throw MslException(MslError::COMPRESSION_ERROR, string("algo ") + compressionAlgo.toString() + " data " + *dataB64, e);
}
}
shared_ptr<ByteArray> uncompress(const MslConstants::CompressionAlgorithm& compressionAlgo,
const ByteArray& data)
{
try {
shared_ptr<ByteArray> decompressed = make_shared<ByteArray>();
if (compressionAlgo == MslConstants::CompressionAlgorithm::GZIP) {
decompress_gzip(data, *decompressed);
} else {
throw MslException(MslError::UNSUPPORTED_COMPRESSION, compressionAlgo.toString());
}
return decompressed;
} catch (const Exception& e) {
shared_ptr<string> dataB64 = Base64::encode(data);
throw MslException(MslError::UNCOMPRESSION_ERROR, string("algo ") + compressionAlgo.toString() + " data " + *dataB64, e);
}
}
void rethrow(const MslException& e)
{
if (instanceof<MslCryptoException>(&e))
throw *dynamic_cast<const MslCryptoException*>(&e);
if (instanceof<MslEncodingException>(&e))
throw *dynamic_cast<const MslEncodingException*>(&e);
if (instanceof<MslEntityAuthException>(&e))
throw *dynamic_cast<const MslEntityAuthException*>(&e);
if (instanceof<MslKeyExchangeException>(&e))
throw *dynamic_cast<const MslKeyExchangeException*>(&e);
if (instanceof<MslMasterTokenException>(&e))
throw *dynamic_cast<const MslMasterTokenException*>(&e);
if (instanceof<MslMessageException>(&e))
throw *dynamic_cast<const MslMessageException*>(&e);
if (instanceof<MslUserAuthException>(&e))
throw *dynamic_cast<const MslUserAuthException*>(&e);
if (instanceof<MslUserIdTokenException>(&e))
throw *dynamic_cast<const MslUserIdTokenException*>(&e);
throw e;
}
void rethrow(shared_ptr<IException> e)
{
if (dynamic_pointer_cast<MslCryptoException>(e))
throw *dynamic_pointer_cast<MslCryptoException>(e);
if (dynamic_pointer_cast<MslEncodingException>(e))
throw *dynamic_pointer_cast<MslEncodingException>(e);
if (dynamic_pointer_cast<MslEntityAuthException>(e))
throw *dynamic_pointer_cast<MslEntityAuthException>(e);
if (dynamic_pointer_cast<MslKeyExchangeException>(e))
throw *dynamic_pointer_cast<MslKeyExchangeException>(e);
if (dynamic_pointer_cast<MslMasterTokenException>(e))
throw *dynamic_pointer_cast<MslMasterTokenException>(e);
if (dynamic_pointer_cast<MslMessageException>(e))
throw *dynamic_pointer_cast<MslMessageException>(e);
if (dynamic_pointer_cast<MslUserAuthException>(e))
throw *dynamic_pointer_cast<MslUserAuthException>(e);
if (dynamic_pointer_cast<MslUserIdTokenException>(e))
throw *dynamic_pointer_cast<MslUserIdTokenException>(e);
if (dynamic_pointer_cast<MslException>(e))
throw *dynamic_pointer_cast<MslException>(e);
}
// Case-insensitive string compare.
bool insStringCompare(std::string const& a, std::string const& b)
{
if (a.size() != b.size()) return false;
return equal(b.begin(), b.end(), a.begin(), insStringCompare_pred);
}
int64_t getRandomLong(shared_ptr<MslContext> ctx) {
// If the maximum long value is a power of 2, then we can perform a
// bitmask on the randomly generated long value to restrict to our
// target number space.
bool isPowerOf2 = is_power_of_2(MslConstants::MAX_LONG_VALUE);
// Generate the random value.
shared_ptr<IRandom> r = ctx->getRandom();
int64_t n = -1;
do {
n = r->nextLong();
// Perform a bitmask if permitted, which will force this loop
// to exit immediately.
if (isPowerOf2)
n &= (MslConstants::MAX_LONG_VALUE - 1);
} while (n < 0 || n > MslConstants::MAX_LONG_VALUE);
// Return the random value.
return n;
}
} // namespace MslUtils
}}} // namespace netflix::msl::util
<commit_msg>Change is_power_of_2 input parameter to int64_t to match signed type, and check for negative values.<commit_after>/**
* Copyright (c) 2016-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <util/MslUtils.h>
#include <crypto/IRandom.h>
#include <util/Base64.h>
#include <util/MslContext.h>
#include <assert.h>
#include <MslError.h>
#include <MslException.h>
#include <MslCryptoException.h>
#include <MslEncodingException.h>
#include <MslEntityAuthException.h>
#include <MslKeyExchangeException.h>
#include <MslMasterTokenException.h>
#include <MslMessageException.h>
#include <MslUserAuthException.h>
#include <MslUserIdTokenException.h>
#include <string.h>
#include <zlib.h>
#include <algorithm>
#include <sstream>
#include <streambuf>
#include <memory>
using namespace std;
using namespace netflix::msl::crypto;
namespace {
// --- GZIP compress / decompress ---
// Original: http://panthema.net/2007/0328-ZLibString.html, Timo Bingmann
// Edited to support gzip: http://blog.cppse.nl/deflate-and-gzip-compress-and-decompress-functions, Ray Burgemeestre
// License: http://www.boost.org/LICENSE_1_0.txt
// Edited to support vector instead of string.
// Found these here http://mail-archives.apache.org/mod_mbox/trafficserver-dev/201110.mbox/%3CCACJPjhYf=+br1W39vyazP=ix
//eQZ-4Gh9-U6TtiEdReG3S4ZZng@mail.gmail.com%3E
#define MOD_GZIP_ZLIB_WINDOWSIZE 15
#define MOD_GZIP_ZLIB_CFACTOR 9
#define MOD_GZIP_ZLIB_BSIZE 8096
const size_t BUFSIZE = 16 * 1024;
uint8_t tmpBuf[BUFSIZE];
void compress_gzip(const vector<uint8_t>& in, vector<uint8_t>& out,
int compressionlevel = Z_BEST_COMPRESSION)
{
z_stream zs; // z_stream is zlib's control structure
memset(&zs, 0, sizeof(zs));
if (deflateInit2(&zs,
compressionlevel,
Z_DEFLATED,
MOD_GZIP_ZLIB_WINDOWSIZE + 16,
MOD_GZIP_ZLIB_CFACTOR,
Z_DEFAULT_STRATEGY) != Z_OK
) {
throw(runtime_error("deflateInit2 failed while compressing."));
}
zs.next_in = (Bytef*)in.data();
zs.avail_in = (uInt)in.size(); // set the z_stream's input
int ret;
vector<uint8_t> tmpOut;
// retrieve the compressed bytes blockwise
do {
zs.next_out = reinterpret_cast<Bytef*>(tmpBuf);
zs.avail_out = sizeof(tmpBuf);
ret = deflate(&zs, Z_FINISH);
if (tmpOut.size() < zs.total_out) {
// append the block to the output
tmpOut.insert(tmpOut.end(), tmpBuf, tmpBuf + zs.total_out - tmpOut.size());
}
} while (ret == Z_OK);
deflateEnd(&zs);
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
ostringstream oss;
oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
throw(runtime_error(oss.str()));
}
out.swap(tmpOut);;
}
void decompress_gzip(const vector<uint8_t>& in, vector<uint8_t>& out)
{
z_stream zs; // z_stream is zlib's control structure
memset(&zs, 0, sizeof(zs));
if (inflateInit2(&zs, MOD_GZIP_ZLIB_WINDOWSIZE + 16) != Z_OK)
throw(runtime_error("inflateInit failed while decompressing."));
zs.next_in = (Bytef*)in.data();
zs.avail_in = (uInt)in.size();
int ret;
vector<uint8_t> tmpOut;
// get the decompressed bytes blockwise using repeated calls to inflate
do {
zs.next_out = reinterpret_cast<Bytef*>(tmpBuf);
zs.avail_out = sizeof(tmpBuf);
ret = inflate(&zs, 0);
if (tmpOut.size() < zs.total_out) {
tmpOut.insert(tmpOut.end(), tmpBuf, tmpBuf + zs.total_out - tmpOut.size());
}
} while (ret == Z_OK);
inflateEnd(&zs);
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
ostringstream oss;
oss << "Exception during zlib decompression: (" << ret << ") "
<< zs.msg;
throw(runtime_error(oss.str()));
}
out.swap(tmpOut);
}
bool insStringCompare_pred(unsigned char a, unsigned char b) {
return tolower(a) == tolower(b);
}
/**
* Return true if the number is a non-negative power of two. Zero is
* considered a power of two and will return true.
*
* @param n the number to test.
* @return true if the number is a non-negative power of two.
*/
bool is_power_of_2(int64_t n) {
// If the number is a power of two, a binary AND operation between
// the number and itself minus one will equal zero.
if (n < 0) return false;
if (n == 0) return true;
return (n & (n - 1)) == 0;
}
} // namespace anonymous
namespace netflix {
namespace msl {
namespace util {
namespace MslUtils {
shared_ptr<ByteArray> compress(const MslConstants::CompressionAlgorithm& compressionAlgo,
const ByteArray& data)
{
try {
shared_ptr<ByteArray> compressed = make_shared<ByteArray>();
if (compressionAlgo == MslConstants::CompressionAlgorithm::GZIP) {
compress_gzip(data, *compressed);
} else {
throw MslException(MslError::UNSUPPORTED_COMPRESSION, compressionAlgo.toString());
}
return compressed;
} catch (const Exception& e) {
shared_ptr<string> dataB64 = Base64::encode(data);
throw MslException(MslError::COMPRESSION_ERROR, string("algo ") + compressionAlgo.toString() + " data " + *dataB64, e);
}
}
shared_ptr<ByteArray> uncompress(const MslConstants::CompressionAlgorithm& compressionAlgo,
const ByteArray& data)
{
try {
shared_ptr<ByteArray> decompressed = make_shared<ByteArray>();
if (compressionAlgo == MslConstants::CompressionAlgorithm::GZIP) {
decompress_gzip(data, *decompressed);
} else {
throw MslException(MslError::UNSUPPORTED_COMPRESSION, compressionAlgo.toString());
}
return decompressed;
} catch (const Exception& e) {
shared_ptr<string> dataB64 = Base64::encode(data);
throw MslException(MslError::UNCOMPRESSION_ERROR, string("algo ") + compressionAlgo.toString() + " data " + *dataB64, e);
}
}
void rethrow(const MslException& e)
{
if (instanceof<MslCryptoException>(&e))
throw *dynamic_cast<const MslCryptoException*>(&e);
if (instanceof<MslEncodingException>(&e))
throw *dynamic_cast<const MslEncodingException*>(&e);
if (instanceof<MslEntityAuthException>(&e))
throw *dynamic_cast<const MslEntityAuthException*>(&e);
if (instanceof<MslKeyExchangeException>(&e))
throw *dynamic_cast<const MslKeyExchangeException*>(&e);
if (instanceof<MslMasterTokenException>(&e))
throw *dynamic_cast<const MslMasterTokenException*>(&e);
if (instanceof<MslMessageException>(&e))
throw *dynamic_cast<const MslMessageException*>(&e);
if (instanceof<MslUserAuthException>(&e))
throw *dynamic_cast<const MslUserAuthException*>(&e);
if (instanceof<MslUserIdTokenException>(&e))
throw *dynamic_cast<const MslUserIdTokenException*>(&e);
throw e;
}
void rethrow(shared_ptr<IException> e)
{
if (dynamic_pointer_cast<MslCryptoException>(e))
throw *dynamic_pointer_cast<MslCryptoException>(e);
if (dynamic_pointer_cast<MslEncodingException>(e))
throw *dynamic_pointer_cast<MslEncodingException>(e);
if (dynamic_pointer_cast<MslEntityAuthException>(e))
throw *dynamic_pointer_cast<MslEntityAuthException>(e);
if (dynamic_pointer_cast<MslKeyExchangeException>(e))
throw *dynamic_pointer_cast<MslKeyExchangeException>(e);
if (dynamic_pointer_cast<MslMasterTokenException>(e))
throw *dynamic_pointer_cast<MslMasterTokenException>(e);
if (dynamic_pointer_cast<MslMessageException>(e))
throw *dynamic_pointer_cast<MslMessageException>(e);
if (dynamic_pointer_cast<MslUserAuthException>(e))
throw *dynamic_pointer_cast<MslUserAuthException>(e);
if (dynamic_pointer_cast<MslUserIdTokenException>(e))
throw *dynamic_pointer_cast<MslUserIdTokenException>(e);
if (dynamic_pointer_cast<MslException>(e))
throw *dynamic_pointer_cast<MslException>(e);
}
// Case-insensitive string compare.
bool insStringCompare(std::string const& a, std::string const& b)
{
if (a.size() != b.size()) return false;
return equal(b.begin(), b.end(), a.begin(), insStringCompare_pred);
}
int64_t getRandomLong(shared_ptr<MslContext> ctx) {
// If the maximum long value is a power of 2, then we can perform a
// bitmask on the randomly generated long value to restrict to our
// target number space.
bool isPowerOf2 = is_power_of_2(MslConstants::MAX_LONG_VALUE);
// Generate the random value.
shared_ptr<IRandom> r = ctx->getRandom();
int64_t n = -1;
do {
n = r->nextLong();
// Perform a bitmask if permitted, which will force this loop
// to exit immediately.
if (isPowerOf2)
n &= (MslConstants::MAX_LONG_VALUE - 1);
} while (n < 0 || n > MslConstants::MAX_LONG_VALUE);
// Return the random value.
return n;
}
} // namespace MslUtils
}}} // namespace netflix::msl::util
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtpanelapplication.h"
#include "lxqtpanelapplication_p.h"
#include "lxqtpanel.h"
#include "config/configpaneldialog.h"
#include <LXQt/Settings>
#include <QtDebug>
#include <QUuid>
#include <QScreen>
#include <QWindow>
#include <QCommandLineParser>
LXQtPanelApplicationPrivate::LXQtPanelApplicationPrivate(LXQtPanelApplication *q)
: mSettings(0),
q_ptr(q)
{
}
ILXQtPanel::Position LXQtPanelApplicationPrivate::computeNewPanelPosition(const LXQtPanel *p, const int screenNum)
{
Q_Q(LXQtPanelApplication);
QVector<bool> screenPositions(4, false); // false means not occupied
for (int i = 0; i < q->mPanels.size(); ++i) {
if (p != q->mPanels.at(i)) {
// We are not the newly added one
if (screenNum == q->mPanels.at(i)->screenNum()) { // Panels on the same screen
int p = static_cast<int> (q->mPanels.at(i)->position());
screenPositions[p] = true; // occupied
}
}
}
int availablePosition = 0;
for (int i = 0; i < 4; ++i) { // Bottom, Top, Left, Right
if (!screenPositions[i]) {
availablePosition = i;
break;
}
}
return static_cast<ILXQtPanel::Position> (availablePosition);
}
LXQtPanelApplication::LXQtPanelApplication(int& argc, char** argv)
: LXQt::Application(argc, argv, true),
d_ptr(new LXQtPanelApplicationPrivate(this))
{
Q_D(LXQtPanelApplication);
QCoreApplication::setApplicationName(QLatin1String("lxqt-panel"));
const QString VERINFO = QStringLiteral(LXQT_PANEL_VERSION
"\nliblxqt " LXQT_VERSION
"\nQt " QT_VERSION_STR);
QCoreApplication::setApplicationVersion(VERINFO);
QCommandLineParser parser;
parser.setApplicationDescription(QLatin1String("LXQt Panel"));
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption configFileOption(QStringList()
<< QLatin1String("c") << QLatin1String("config") << QLatin1String("configfile"),
QCoreApplication::translate("main", "Use alternate configuration file."),
QCoreApplication::translate("main", "Configuration file"));
parser.addOption(configFileOption);
parser.process(*this);
const QString configFile = parser.value(configFileOption);
if (configFile.isEmpty())
d->mSettings = new LXQt::Settings(QLatin1String("panel"), this);
else
d->mSettings = new LXQt::Settings(configFile, QSettings::IniFormat, this);
// This is a workaround for Qt 5 bug #40681.
const auto allScreens = screens();
for(QScreen* screen : allScreens)
{
connect(screen, &QScreen::destroyed, this, &LXQtPanelApplication::screenDestroyed);
}
connect(this, &QGuiApplication::screenAdded, this, &LXQtPanelApplication::handleScreenAdded);
connect(this, &QCoreApplication::aboutToQuit, this, &LXQtPanelApplication::cleanup);
QStringList panels = d->mSettings->value(QStringLiteral("panels")).toStringList();
// WARNING: Giving a separate icon theme to the panel is wrong and has side effects.
// However, it is optional and can be used as the last resort for avoiding a low
// contrast in the case of symbolic SVG icons. (The correct way of doing that is
// using a Qt widget style that can assign a separate theme/QPalette to the panel.)
mGlobalIconTheme = QIcon::themeName();
const QString iconTheme = d->mSettings->value(QStringLiteral("iconTheme")).toString();
if (!iconTheme.isEmpty())
QIcon::setThemeName(iconTheme);
if (panels.isEmpty())
{
panels << QStringLiteral("panel1");
}
for(const QString& i : qAsConst(panels))
{
addPanel(i);
}
}
LXQtPanelApplication::~LXQtPanelApplication()
{
delete d_ptr;
}
void LXQtPanelApplication::cleanup()
{
qDeleteAll(mPanels);
}
void LXQtPanelApplication::addNewPanel()
{
Q_D(LXQtPanelApplication);
QString name(QStringLiteral("panel_") + QUuid::createUuid().toString());
LXQtPanel *p = addPanel(name);
int screenNum = p->screenNum();
ILXQtPanel::Position newPanelPosition = d->computeNewPanelPosition(p, screenNum);
p->setPosition(screenNum, newPanelPosition, true);
QStringList panels = d->mSettings->value(QStringLiteral("panels")).toStringList();
panels << name;
d->mSettings->setValue(QStringLiteral("panels"), panels);
// Poupup the configuration dialog to allow user configuration right away
p->showConfigDialog();
}
LXQtPanel* LXQtPanelApplication::addPanel(const QString& name)
{
Q_D(LXQtPanelApplication);
LXQtPanel *panel = new LXQtPanel(name, d->mSettings);
mPanels << panel;
// reemit signals
connect(panel, &LXQtPanel::deletedByUser, this, &LXQtPanelApplication::removePanel);
connect(panel, &LXQtPanel::pluginAdded, this, &LXQtPanelApplication::pluginAdded);
connect(panel, &LXQtPanel::pluginRemoved, this, &LXQtPanelApplication::pluginRemoved);
return panel;
}
void LXQtPanelApplication::handleScreenAdded(QScreen* newScreen)
{
// qDebug() << "LXQtPanelApplication::handleScreenAdded" << newScreen;
connect(newScreen, &QScreen::destroyed, this, &LXQtPanelApplication::screenDestroyed);
}
void LXQtPanelApplication::reloadPanelsAsNeeded()
{
Q_D(LXQtPanelApplication);
// NOTE by PCMan: This is a workaround for Qt 5 bug #40681.
// Here we try to re-create the missing panels which are deleted in
// LXQtPanelApplication::screenDestroyed().
// qDebug() << "LXQtPanelApplication::reloadPanelsAsNeeded()";
const QStringList names = d->mSettings->value(QStringLiteral("panels")).toStringList();
for(const QString& name : names)
{
bool found = false;
for(LXQtPanel* panel : qAsConst(mPanels))
{
if(panel->name() == name)
{
found = true;
break;
}
}
if(!found)
{
// the panel is found in the config file but does not exist, create it.
qDebug() << "Workaround Qt 5 bug #40681: re-create panel:" << name;
addPanel(name);
}
}
qApp->setQuitOnLastWindowClosed(true);
}
void LXQtPanelApplication::screenDestroyed(QObject* screenObj)
{
// NOTE by PCMan: This is a workaround for Qt 5 bug #40681.
// With this very dirty workaround, we can fix lxqt/lxqt bug #204, #205, and #206.
// Qt 5 has two new regression bugs which breaks lxqt-panel in a multihead environment.
// #40681: Regression bug: QWidget::winId() returns old value and QEvent::WinIdChange event is not emitted sometimes. (multihead setup)
// #40791: Regression: QPlatformWindow, QWindow, and QWidget::winId() are out of sync.
// Explanations for the workaround:
// Internally, Qt mantains a list of QScreens and update it when XRandR configuration changes.
// When the user turn off an monitor with xrandr --output <xxx> --off, this will destroy the QScreen
// object which represent the output. If the QScreen being destroyed contains our panel widget,
// Qt will call QWindow::setScreen(0) on the internal windowHandle() of our panel widget to move it
// to the primary screen. However, moving a window to a different screen is more than just changing
// its position. With XRandR, all screens are actually part of the same virtual desktop. However,
// this is not the case in other setups, such as Xinerama and moving a window to another screen is
// not possible unless you destroy the widget and create it again for a new screen.
// Therefore, Qt destroy the widget and re-create it when moving our panel to a new screen.
// Unfortunately, destroying the window also destroy the child windows embedded into it,
// using XEMBED such as the tray icons. (#206)
// Second, when the window is re-created, the winId of the QWidget is changed, but Qt failed to
// generate QEvent::WinIdChange event so we have no way to know that. We have to set
// some X11 window properties using the native winId() to make it a dock, but this stop working
// because we cannot get the correct winId(), so this causes #204 and #205.
//
// The workaround is very simple. Just completely destroy the panel before Qt has a chance to do
// QWindow::setScreen() for it. Later, we reload the panel ourselves. So this can bypassing the Qt bugs.
QScreen* screen = static_cast<QScreen*>(screenObj);
bool reloadNeeded = false;
qApp->setQuitOnLastWindowClosed(false);
for(LXQtPanel* panel : qAsConst(mPanels))
{
QWindow* panelWindow = panel->windowHandle();
if(panelWindow && panelWindow->screen() == screen)
{
// the screen containing the panel is destroyed
// delete and then re-create the panel ourselves
QString name = panel->name();
panel->saveSettings(false);
delete panel; // delete the panel, so Qt does not have a chance to set a new screen to it.
mPanels.removeAll(panel);
reloadNeeded = true;
qDebug() << "Workaround Qt 5 bug #40681: delete panel:" << name;
}
}
if(reloadNeeded)
QTimer::singleShot(1000, this, SLOT(reloadPanelsAsNeeded()));
else
qApp->setQuitOnLastWindowClosed(true);
}
void LXQtPanelApplication::removePanel(LXQtPanel* panel)
{
Q_D(LXQtPanelApplication);
Q_ASSERT(mPanels.contains(panel));
mPanels.removeAll(panel);
QStringList panels = d->mSettings->value(QStringLiteral("panels")).toStringList();
panels.removeAll(panel->name());
d->mSettings->setValue(QStringLiteral("panels"), panels);
panel->deleteLater();
}
bool LXQtPanelApplication::isPluginSingletonAndRunnig(QString const & pluginId) const
{
for (auto const & panel : mPanels)
if (panel->isPluginSingletonAndRunnig(pluginId))
return true;
return false;
}
// See LXQtPanelApplication::LXQtPanelApplication for why this isn't good.
void LXQtPanelApplication::setIconTheme(const QString &iconTheme)
{
Q_D(LXQtPanelApplication);
d->mSettings->setValue(QStringLiteral("iconTheme"), iconTheme == mGlobalIconTheme ? QString() : iconTheme);
QString newTheme = iconTheme.isEmpty() ? mGlobalIconTheme : iconTheme;
if (newTheme != QIcon::themeName())
{
QIcon::setThemeName(newTheme);
for(LXQtPanel* panel : qAsConst(mPanels))
{
panel->update();
panel->updateConfigDialog();
}
}
}
<commit_msg> lxqtpanelapplication: do not use deleted variable (#1157)<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtpanelapplication.h"
#include "lxqtpanelapplication_p.h"
#include "lxqtpanel.h"
#include "config/configpaneldialog.h"
#include <LXQt/Settings>
#include <QtDebug>
#include <QUuid>
#include <QScreen>
#include <QWindow>
#include <QCommandLineParser>
LXQtPanelApplicationPrivate::LXQtPanelApplicationPrivate(LXQtPanelApplication *q)
: mSettings(0),
q_ptr(q)
{
}
ILXQtPanel::Position LXQtPanelApplicationPrivate::computeNewPanelPosition(const LXQtPanel *p, const int screenNum)
{
Q_Q(LXQtPanelApplication);
QVector<bool> screenPositions(4, false); // false means not occupied
for (int i = 0; i < q->mPanels.size(); ++i) {
if (p != q->mPanels.at(i)) {
// We are not the newly added one
if (screenNum == q->mPanels.at(i)->screenNum()) { // Panels on the same screen
int p = static_cast<int> (q->mPanels.at(i)->position());
screenPositions[p] = true; // occupied
}
}
}
int availablePosition = 0;
for (int i = 0; i < 4; ++i) { // Bottom, Top, Left, Right
if (!screenPositions[i]) {
availablePosition = i;
break;
}
}
return static_cast<ILXQtPanel::Position> (availablePosition);
}
LXQtPanelApplication::LXQtPanelApplication(int& argc, char** argv)
: LXQt::Application(argc, argv, true),
d_ptr(new LXQtPanelApplicationPrivate(this))
{
Q_D(LXQtPanelApplication);
QCoreApplication::setApplicationName(QLatin1String("lxqt-panel"));
const QString VERINFO = QStringLiteral(LXQT_PANEL_VERSION
"\nliblxqt " LXQT_VERSION
"\nQt " QT_VERSION_STR);
QCoreApplication::setApplicationVersion(VERINFO);
QCommandLineParser parser;
parser.setApplicationDescription(QLatin1String("LXQt Panel"));
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption configFileOption(QStringList()
<< QLatin1String("c") << QLatin1String("config") << QLatin1String("configfile"),
QCoreApplication::translate("main", "Use alternate configuration file."),
QCoreApplication::translate("main", "Configuration file"));
parser.addOption(configFileOption);
parser.process(*this);
const QString configFile = parser.value(configFileOption);
if (configFile.isEmpty())
d->mSettings = new LXQt::Settings(QLatin1String("panel"), this);
else
d->mSettings = new LXQt::Settings(configFile, QSettings::IniFormat, this);
// This is a workaround for Qt 5 bug #40681.
const auto allScreens = screens();
for(QScreen* screen : allScreens)
{
connect(screen, &QScreen::destroyed, this, &LXQtPanelApplication::screenDestroyed);
}
connect(this, &QGuiApplication::screenAdded, this, &LXQtPanelApplication::handleScreenAdded);
connect(this, &QCoreApplication::aboutToQuit, this, &LXQtPanelApplication::cleanup);
QStringList panels = d->mSettings->value(QStringLiteral("panels")).toStringList();
// WARNING: Giving a separate icon theme to the panel is wrong and has side effects.
// However, it is optional and can be used as the last resort for avoiding a low
// contrast in the case of symbolic SVG icons. (The correct way of doing that is
// using a Qt widget style that can assign a separate theme/QPalette to the panel.)
mGlobalIconTheme = QIcon::themeName();
const QString iconTheme = d->mSettings->value(QStringLiteral("iconTheme")).toString();
if (!iconTheme.isEmpty())
QIcon::setThemeName(iconTheme);
if (panels.isEmpty())
{
panels << QStringLiteral("panel1");
}
for(const QString& i : qAsConst(panels))
{
addPanel(i);
}
}
LXQtPanelApplication::~LXQtPanelApplication()
{
delete d_ptr;
}
void LXQtPanelApplication::cleanup()
{
qDeleteAll(mPanels);
}
void LXQtPanelApplication::addNewPanel()
{
Q_D(LXQtPanelApplication);
QString name(QStringLiteral("panel_") + QUuid::createUuid().toString());
LXQtPanel *p = addPanel(name);
int screenNum = p->screenNum();
ILXQtPanel::Position newPanelPosition = d->computeNewPanelPosition(p, screenNum);
p->setPosition(screenNum, newPanelPosition, true);
QStringList panels = d->mSettings->value(QStringLiteral("panels")).toStringList();
panels << name;
d->mSettings->setValue(QStringLiteral("panels"), panels);
// Poupup the configuration dialog to allow user configuration right away
p->showConfigDialog();
}
LXQtPanel* LXQtPanelApplication::addPanel(const QString& name)
{
Q_D(LXQtPanelApplication);
LXQtPanel *panel = new LXQtPanel(name, d->mSettings);
mPanels << panel;
// reemit signals
connect(panel, &LXQtPanel::deletedByUser, this, &LXQtPanelApplication::removePanel);
connect(panel, &LXQtPanel::pluginAdded, this, &LXQtPanelApplication::pluginAdded);
connect(panel, &LXQtPanel::pluginRemoved, this, &LXQtPanelApplication::pluginRemoved);
return panel;
}
void LXQtPanelApplication::handleScreenAdded(QScreen* newScreen)
{
// qDebug() << "LXQtPanelApplication::handleScreenAdded" << newScreen;
connect(newScreen, &QScreen::destroyed, this, &LXQtPanelApplication::screenDestroyed);
}
void LXQtPanelApplication::reloadPanelsAsNeeded()
{
Q_D(LXQtPanelApplication);
// NOTE by PCMan: This is a workaround for Qt 5 bug #40681.
// Here we try to re-create the missing panels which are deleted in
// LXQtPanelApplication::screenDestroyed().
// qDebug() << "LXQtPanelApplication::reloadPanelsAsNeeded()";
const QStringList names = d->mSettings->value(QStringLiteral("panels")).toStringList();
for(const QString& name : names)
{
bool found = false;
for(LXQtPanel* panel : qAsConst(mPanels))
{
if(panel->name() == name)
{
found = true;
break;
}
}
if(!found)
{
// the panel is found in the config file but does not exist, create it.
qDebug() << "Workaround Qt 5 bug #40681: re-create panel:" << name;
addPanel(name);
}
}
qApp->setQuitOnLastWindowClosed(true);
}
void LXQtPanelApplication::screenDestroyed(QObject* screenObj)
{
// NOTE by PCMan: This is a workaround for Qt 5 bug #40681.
// With this very dirty workaround, we can fix lxqt/lxqt bug #204, #205, and #206.
// Qt 5 has two new regression bugs which breaks lxqt-panel in a multihead environment.
// #40681: Regression bug: QWidget::winId() returns old value and QEvent::WinIdChange event is not emitted sometimes. (multihead setup)
// #40791: Regression: QPlatformWindow, QWindow, and QWidget::winId() are out of sync.
// Explanations for the workaround:
// Internally, Qt mantains a list of QScreens and update it when XRandR configuration changes.
// When the user turn off an monitor with xrandr --output <xxx> --off, this will destroy the QScreen
// object which represent the output. If the QScreen being destroyed contains our panel widget,
// Qt will call QWindow::setScreen(0) on the internal windowHandle() of our panel widget to move it
// to the primary screen. However, moving a window to a different screen is more than just changing
// its position. With XRandR, all screens are actually part of the same virtual desktop. However,
// this is not the case in other setups, such as Xinerama and moving a window to another screen is
// not possible unless you destroy the widget and create it again for a new screen.
// Therefore, Qt destroy the widget and re-create it when moving our panel to a new screen.
// Unfortunately, destroying the window also destroy the child windows embedded into it,
// using XEMBED such as the tray icons. (#206)
// Second, when the window is re-created, the winId of the QWidget is changed, but Qt failed to
// generate QEvent::WinIdChange event so we have no way to know that. We have to set
// some X11 window properties using the native winId() to make it a dock, but this stop working
// because we cannot get the correct winId(), so this causes #204 and #205.
//
// The workaround is very simple. Just completely destroy the panel before Qt has a chance to do
// QWindow::setScreen() for it. Later, we reload the panel ourselves. So this can bypassing the Qt bugs.
QScreen* screen = static_cast<QScreen*>(screenObj);
bool reloadNeeded = false;
qApp->setQuitOnLastWindowClosed(false);
for(LXQtPanel* panel : qAsConst(mPanels))
{
QWindow* panelWindow = panel->windowHandle();
if(panelWindow && panelWindow->screen() == screen)
{
// the screen containing the panel is destroyed
// delete and then re-create the panel ourselves
QString name = panel->name();
panel->saveSettings(false);
mPanels.removeAll(panel);
delete panel; // delete the panel, so Qt does not have a chance to set a new screen to it.
reloadNeeded = true;
qDebug() << "Workaround Qt 5 bug #40681: delete panel:" << name;
}
}
if(reloadNeeded)
QTimer::singleShot(1000, this, SLOT(reloadPanelsAsNeeded()));
else
qApp->setQuitOnLastWindowClosed(true);
}
void LXQtPanelApplication::removePanel(LXQtPanel* panel)
{
Q_D(LXQtPanelApplication);
Q_ASSERT(mPanels.contains(panel));
mPanels.removeAll(panel);
QStringList panels = d->mSettings->value(QStringLiteral("panels")).toStringList();
panels.removeAll(panel->name());
d->mSettings->setValue(QStringLiteral("panels"), panels);
panel->deleteLater();
}
bool LXQtPanelApplication::isPluginSingletonAndRunnig(QString const & pluginId) const
{
for (auto const & panel : mPanels)
if (panel->isPluginSingletonAndRunnig(pluginId))
return true;
return false;
}
// See LXQtPanelApplication::LXQtPanelApplication for why this isn't good.
void LXQtPanelApplication::setIconTheme(const QString &iconTheme)
{
Q_D(LXQtPanelApplication);
d->mSettings->setValue(QStringLiteral("iconTheme"), iconTheme == mGlobalIconTheme ? QString() : iconTheme);
QString newTheme = iconTheme.isEmpty() ? mGlobalIconTheme : iconTheme;
if (newTheme != QIcon::themeName())
{
QIcon::setThemeName(newTheme);
for(LXQtPanel* panel : qAsConst(mPanels))
{
panel->update();
panel->updateConfigDialog();
}
}
}
<|endoftext|>
|
<commit_before>#include "narf/console.h"
#include "narf/path.h"
#if defined(__unix__) || defined(__APPLE__)
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#endif
#ifdef _MSC_VER
#include <direct.h>
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#include <shlobj.h>
#include "narf/utf.h"
const std::string narf::util::DirSeparator("\\");
#else
const std::string narf::util::DirSeparator("/");
#endif
#ifdef linux
static std::string readLink(const std::string &path) {
size_t len = 1024;
size_t lenStep = 1024;
size_t maxLen = 1024 * 4096;
do {
char *buf = new char[len + 1];
if (!buf) {
return std::string("");
}
auto bytes = readlink(path.c_str(), buf, len + 1);
if (bytes < 0) {
return std::string("");
}
if (static_cast<size_t>(bytes) > len) {
// try again with larger buffer
len += lenStep;
delete [] buf;
} else {
buf[bytes] = '\0';
auto s = std::string(buf);
delete [] buf;
return s;
}
} while (len <= maxLen);
return std::string("");
}
std::string narf::util::exeName() {
return readLink("/proc/self/exe");
}
#endif // linux
#if defined(__unix__) && !defined(linux)
std::string narf::util::exeName() {
return "";
}
#endif // unix && !linux
#if defined(__unix__) || defined(__APPLE__)
bool narf::util::dirExists(const std::string& path) {
struct stat st;
if (stat(path.c_str(), &st) == -1) {
return false;
}
return (st.st_mode & S_IFMT) == S_IFDIR;
}
#endif // unix
#ifdef _WIN32
std::string narf::util::exeName() {
const DWORD len = 32768; // max NT-style name length + terminator
wchar_t buffer[len];
DWORD ret = GetModuleFileNameW(NULL, buffer, len);
if (ret == 0 || ret >= len) {
return ""; // error
}
std::string result;
narf::toUTF8(buffer, result);
return result;
}
bool narf::util::dirExists(const std::string& path) {
std::wstring pathW;
narf::toUTF16(path, pathW);
DWORD attrs = GetFileAttributesW(pathW.c_str());
return (attrs != INVALID_FILE_ATTRIBUTES) && (attrs & FILE_ATTRIBUTE_DIRECTORY);
}
std::string narf::util::dirName(const std::string& path) {
char* s = new char[path.size() + 1];
std::strcpy(s, path.c_str());
PathRemoveFileSpec(s);
return std::string(s);
}
#endif // _WIN32
#ifdef __APPLE__
std::string narf::util::exeName() {
char buffer[32768];
uint32_t len = sizeof(buffer);
if (_NSGetExecutablePath(buffer, &len) == 0) {
return std::string(buffer);
}
return ""; // error
}
#endif // __APPLE__
std::string narf::util::exeDir() {
return dirName(exeName());
}
std::string narf::util::appendPath(const std::string& path, const std::string& append) {
if (path.back() == DirSeparator[0]) {
return path + append;
} else {
return path + DirSeparator + append;
}
}
bool narf::util::createDir(const std::string& path) {
#ifdef _MSC_VER
std::wstring pathW;
narf::toUTF16(path, pathW);
return _wmkdir(pathW.c_str()) == 0;
#else
return mkdir(path.c_str(), 0755) == 0;
#endif
}
bool narf::util::createDirs(const std::string& path) {
if (isDir(path)) {
return true; // We're already a directory
}
if (!createDirs(dirName(path))) {
return false; // Failed to create one of the parent directories
}
return createDir(path);
}
bool narf::util::exists(const std::string& path) {
struct stat st;
return (stat(path.c_str(), &st) == 0);
}
void narf::util::rename(const std::string& path, const std::string& newPath) {
::rename(path.c_str(), newPath.c_str());
}
bool narf::util::isDir(const std::string& path) {
struct stat st;
if (stat(path.c_str(), &st) != 0) {
return false;
}
return S_ISDIR(st.st_mode);
}
// TODO: These will be broken on Windows when given the root directory
std::string narf::util::dirName(const std::string& path) {
size_t len = path.length();
while (len > 0 && path[len - 1] == DirSeparator[0]) {
len--;
}
auto lastSlash = path.rfind(narf::util::DirSeparator, len - 1);
if (lastSlash != std::string::npos) {
return path.substr(0, lastSlash == 0 ? 1 : lastSlash);
}
return path;
}
std::string narf::util::baseName(const std::string& path) {
size_t len = path.length();
while (len > 0 && path[len - 1] == DirSeparator[0]) {
len--;
}
size_t lastSlash = path.rfind(DirSeparator, len - 1);
if (len > 1 && lastSlash != std::string::npos) {
return path.substr(lastSlash + 1, len - lastSlash - 1);
}
return path;
}
<commit_msg>Hopefully this should fix the Windows build finally.<commit_after>#include "narf/console.h"
#include "narf/path.h"
#include <sys/types.h>
#include <sys/stat.h>
#if defined(__unix__) || defined(__APPLE__)
#include <unistd.h>
#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#include <shlobj.h>
#include "narf/utf.h"
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
const std::string narf::util::DirSeparator("\\");
#else
const std::string narf::util::DirSeparator("/");
#endif
#ifdef linux
static std::string readLink(const std::string &path) {
size_t len = 1024;
size_t lenStep = 1024;
size_t maxLen = 1024 * 4096;
do {
char *buf = new char[len + 1];
if (!buf) {
return std::string("");
}
auto bytes = readlink(path.c_str(), buf, len + 1);
if (bytes < 0) {
return std::string("");
}
if (static_cast<size_t>(bytes) > len) {
// try again with larger buffer
len += lenStep;
delete [] buf;
} else {
buf[bytes] = '\0';
auto s = std::string(buf);
delete [] buf;
return s;
}
} while (len <= maxLen);
return std::string("");
}
std::string narf::util::exeName() {
return readLink("/proc/self/exe");
}
#endif // linux
#if defined(__unix__) && !defined(linux)
std::string narf::util::exeName() {
return "";
}
#endif // unix && !linux
#if defined(__unix__) || defined(__APPLE__)
bool narf::util::dirExists(const std::string& path) {
struct stat st;
if (stat(path.c_str(), &st) == -1) {
return false;
}
return (st.st_mode & S_IFMT) == S_IFDIR;
}
#endif // unix
#ifdef _WIN32
std::string narf::util::exeName() {
const DWORD len = 32768; // max NT-style name length + terminator
wchar_t buffer[len];
DWORD ret = GetModuleFileNameW(NULL, buffer, len);
if (ret == 0 || ret >= len) {
return ""; // error
}
std::string result;
narf::toUTF8(buffer, result);
return result;
}
bool narf::util::dirExists(const std::string& path) {
std::wstring pathW;
narf::toUTF16(path, pathW);
DWORD attrs = GetFileAttributesW(pathW.c_str());
return (attrs != INVALID_FILE_ATTRIBUTES) && (attrs & FILE_ATTRIBUTE_DIRECTORY);
}
#endif // _WIN32
#ifdef __APPLE__
std::string narf::util::exeName() {
char buffer[32768];
uint32_t len = sizeof(buffer);
if (_NSGetExecutablePath(buffer, &len) == 0) {
return std::string(buffer);
}
return ""; // error
}
#endif // __APPLE__
std::string narf::util::exeDir() {
return dirName(exeName());
}
std::string narf::util::appendPath(const std::string& path, const std::string& append) {
if (path.back() == DirSeparator[0]) {
return path + append;
} else {
return path + DirSeparator + append;
}
}
bool narf::util::createDir(const std::string& path) {
#ifdef _WIN32
std::wstring pathW;
narf::toUTF16(path, pathW);
return _wmkdir(pathW.c_str()) == 0;
#else
return mkdir(path.c_str(), 0755) == 0;
#endif
}
bool narf::util::createDirs(const std::string& path) {
if (isDir(path)) {
return true; // We're already a directory
}
if (!createDirs(dirName(path))) {
return false; // Failed to create one of the parent directories
}
return createDir(path);
}
bool narf::util::exists(const std::string& path) {
struct stat st;
return (stat(path.c_str(), &st) == 0);
}
void narf::util::rename(const std::string& path, const std::string& newPath) {
::rename(path.c_str(), newPath.c_str());
}
bool narf::util::isDir(const std::string& path) {
#ifdef _WIN32
std::wstring pathW;
narf::toUTF16(path, pathW);
struct _stat st;
if (_wstat(path.c_str(), &st) != 0) {
return false;
}
#else
struct stat st;
if (stat(path.c_str(), &st) != 0) {
return false;
}
#endif
return S_ISDIR(st.st_mode);
}
// TODO: These will be broken on Windows when given the root directory
std::string narf::util::dirName(const std::string& path) {
size_t len = path.length();
while (len > 0 && path[len - 1] == DirSeparator[0]) {
len--;
}
auto lastSlash = path.rfind(narf::util::DirSeparator, len - 1);
if (lastSlash != std::string::npos) {
return path.substr(0, lastSlash == 0 ? 1 : lastSlash);
}
return path;
}
std::string narf::util::baseName(const std::string& path) {
size_t len = path.length();
while (len > 0 && path[len - 1] == DirSeparator[0]) {
len--;
}
size_t lastSlash = path.rfind(DirSeparator, len - 1);
if (len > 1 && lastSlash != std::string::npos) {
return path.substr(lastSlash + 1, len - lastSlash - 1);
}
return path;
}
<|endoftext|>
|
<commit_before><commit_msg>Bugfix: `class Material`: always initialize `openGL_textureID`.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Bugfix: added missing `#include` line.<commit_after><|endoftext|>
|
<commit_before>/*
* A node that produces creates string messages based on various
* factors (events, velocity, etc.)
*
* Created by Christian Onuogu
*/
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Twist.h"
#include "nav_msgs/Odometry.h"
#include "move_base_msgs/MoveBaseActionGoal.h"
#include <math.h>
ros::Publisher T2S_pub;
std_msgs::String msg;
geometry_msgs::Twist velocity;
bool moving = false;
bool heardGoal = false;
double xPos;
double yPos;
double goalX;
double goalY;
/*
* The cb function that turns received velocity into strings
*/
void cmd_vel_cb(const geometry_msgs::Twist::ConstPtr& vel)
{
velocity = *vel;
if(moving == false && velocity.linear.x > 0) {
moving = true;
ROS_INFO("Hello?");
msg.data = "Started movement";
T2S_pub.publish(msg);
}
else if(moving == true && velocity.linear.x == 0) {
moving = false;
ROS_INFO("Bye?");
msg.data = "Stopped movement";
T2S_pub.publish(msg);
}
}
/*
* The cb function that gets the position of the robot's goal
*/
void goal_cb(const move_base_msgs::MoveBaseActionGoal::ConstPtr& gl)
{
move_base_msgs::MoveBaseActionGoal goal = *gl;
goalX = goal.goal.target_pose.pose.position.x;
goalY = goal.goal.target_pose.pose.position.y;
heardGoal = true;
}
/*
* The cb function that gets the position of the robot and
* checks if it has reached its goal
*/
void pos_cb(const nav_msgs::Odometry::ConstPtr& odom)
{
nav_msgs::Odometry odometer = *odom;
xPos = odometer.pose.pose.position.x;
yPos = odometer.pose.pose.position.y;
if(heardGoal){
if(fabs(xPos-goalX) < .5 && fabs(yPos-goalY) < .5) {
ROS_INFO("Please");
heardGoal = false;
msg.data = "Destination reached";
T2S_pub.publish(msg);
}
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "listener");
ros::NodeHandle n;
T2S_pub = n.advertise<std_msgs::String>("T2S", 1000);
ros::Subscriber sub = n.subscribe("/cmd_vel", 1, cmd_vel_cb );
ros::Subscriber sub2 = n.subscribe("/move_base/goal", 1, goal_cb );
ros::Subscriber sub3 = n.subscribe("/odom", 1, pos_cb );
while(ros::ok()) {
ros::spinOnce();
}
return 0;
}
<commit_msg>Removed debugging code<commit_after>/*
* A node that produces creates string messages based on various
* factors (events, velocity, etc.)
*
* Created by Christian Onuogu
*/
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Twist.h"
#include "nav_msgs/Odometry.h"
#include "move_base_msgs/MoveBaseActionGoal.h"
#include <math.h>
ros::Publisher T2S_pub;
std_msgs::String msg;
geometry_msgs::Twist velocity;
bool moving = false;
bool heardGoal = false;
double xPos;
double yPos;
double goalX;
double goalY;
/*
* The cb function that turns received velocity into strings
*/
void cmd_vel_cb(const geometry_msgs::Twist::ConstPtr& vel)
{
velocity = *vel;
if(moving == false && velocity.linear.x > 0) {
moving = true;
msg.data = "Started movement";
T2S_pub.publish(msg);
}
else if(moving == true && velocity.linear.x == 0) {
moving = false;
msg.data = "Stopped movement";
T2S_pub.publish(msg);
}
}
/*
* The cb function that gets the position of the robot's goal
*/
void goal_cb(const move_base_msgs::MoveBaseActionGoal::ConstPtr& gl)
{
move_base_msgs::MoveBaseActionGoal goal = *gl;
goalX = goal.goal.target_pose.pose.position.x;
goalY = goal.goal.target_pose.pose.position.y;
heardGoal = true;
}
/*
* The cb function that gets the position of the robot and
* checks if it has reached its goal
*/
void pos_cb(const nav_msgs::Odometry::ConstPtr& odom)
{
nav_msgs::Odometry odometer = *odom;
xPos = odometer.pose.pose.position.x;
yPos = odometer.pose.pose.position.y;
if(heardGoal){
if(fabs(xPos-goalX) < .5 && fabs(yPos-goalY) < .5) {
heardGoal = false;
msg.data = "Destination reached";
T2S_pub.publish(msg);
}
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "listener");
ros::NodeHandle n;
T2S_pub = n.advertise<std_msgs::String>("T2S", 1000);
ros::Subscriber sub = n.subscribe("/cmd_vel", 1, cmd_vel_cb );
ros::Subscriber sub2 = n.subscribe("/move_base/goal", 1, goal_cb );
ros::Subscriber sub3 = n.subscribe("/odom", 1, pos_cb );
while(ros::ok()) {
ros::spinOnce();
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* cclive is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hosthandler.h"
#include "curl.h"
LiveleakHandler::LiveleakHandler()
: HostHandler()
{
props.setHost ("lleak");
props.setDomain ("liveleak.com");
props.setFormats("flv");
}
void
LiveleakHandler::parseId() {
std::string id;
partialMatch("(?i)token=(.*?)'", &id);
props.setId(id);
}
void
LiveleakHandler::parseTitle() {
std::string title;
partialMatch("(?i)<title>(.*?)</", &title);
Util::subStrReplace(title, "LiveLeak.com - ", "");
props.setTitle(title);
}
void
LiveleakHandler::parseLink() {
std::string confPath;
partialMatch("(?i)'config','(.*?)'", &confPath);
curlmgr.unescape(confPath);
const std::string config =
curlmgr.fetchToMem(confPath, "config");
std::string plPath;
partialMatch("(?i)<file>(.*?)</", &plPath, config);
curlmgr.unescape(plPath);
const std::string playlist =
curlmgr.fetchToMem(plPath, "playlist");
std::string lnk;
partialMatch("(?i)<location>(.*?)</", &lnk, playlist);
props.setLink(lnk);
}
<commit_msg>hostid lleak -> liveleak.<commit_after>/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* cclive is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hosthandler.h"
#include "curl.h"
LiveleakHandler::LiveleakHandler()
: HostHandler()
{
props.setHost ("liveleak");
props.setDomain ("liveleak.com");
props.setFormats("flv");
}
void
LiveleakHandler::parseId() {
std::string id;
partialMatch("(?i)token=(.*?)'", &id);
props.setId(id);
}
void
LiveleakHandler::parseTitle() {
std::string title;
partialMatch("(?i)<title>(.*?)</", &title);
Util::subStrReplace(title, "LiveLeak.com - ", "");
props.setTitle(title);
}
void
LiveleakHandler::parseLink() {
std::string confPath;
partialMatch("(?i)'config','(.*?)'", &confPath);
curlmgr.unescape(confPath);
const std::string config =
curlmgr.fetchToMem(confPath, "config");
std::string plPath;
partialMatch("(?i)<file>(.*?)</", &plPath, config);
curlmgr.unescape(plPath);
const std::string playlist =
curlmgr.fetchToMem(plPath, "playlist");
std::string lnk;
partialMatch("(?i)<location>(.*?)</", &lnk, playlist);
props.setLink(lnk);
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/planning_scene/planning_scene.h>
#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <boost/program_options.hpp>
int main(int argc, char** argv)
{
ros::init(argc, argv, "playback");
ros::NodeHandle node_handle;
ros::AsyncSpinner spinner(1);
spinner.start();
sleep(20); // to let RVIZ come up
boost::program_options::options_description desc;
desc.add_options()
("help", "Show help message")
("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");
boost::program_options::variables_map vm;
boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);
boost::program_options::store(po, vm);
boost::program_options::notify(vm);
if (vm.count("help") || argc == 1) // show help if no parameters passed
{
std::cout << desc << std::endl;
return 1;
}
try
{
//connect to the DB
std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
moveit_warehouse::PlanningSceneStorage pss(host, port);
ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port);
ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
moveit_msgs::DisplayTrajectory display_trajectory;
//ask the warehouse for the scene
std::vector<std::string> ps_names;
pss.getPlanningSceneNames( ps_names );
ros::Publisher ps_pub = node_handle.advertise<moveit_msgs::PlanningScene>("planning_scene", 1);
while(ps_pub.getNumSubscribers() < 1)
{
ros::WallDuration sleep_t(0.5);
ROS_INFO("Not enough subscribers to \"%s\" topic... ", "planning_scene");
sleep_t.sleep();
}
ROS_INFO("%d available scenes to display", (int)ps_names.size());
std::vector<std::string>::iterator scene_it = ps_names.begin();
for(; scene_it!=ps_names.end(); ++scene_it)
{
ROS_INFO("Retrieving scene %s", scene_it->c_str());
moveit_warehouse::PlanningSceneWithMetadata pswm;
pss.getPlanningScene(pswm, *scene_it);
// visualize the scene_it
ROS_INFO("Publishing scene...");
ps_pub.publish(static_cast<const moveit_msgs::PlanningScene&>(*pswm));
moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm);
// get query list
std::vector<std::string> pq_names;
pss.getPlanningQueriesNames( pq_names, *scene_it);
ROS_INFO("%d available queries to display", (int)pq_names.size());
std::string first_query = pq_names.at(0);
//get trajectory list
std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results;
pss.getPlanningResults(planning_results, *scene_it, first_query);
ROS_INFO("Loaded %d trajectories for query %s", (int)planning_results.size(), first_query.c_str());
// animate the first trajectory
size_t ind = planning_results.size()-1;
moveit_msgs::RobotTrajectory rt_msg;
rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(*(planning_results[ind]));
// trajectory_processing::IterativeParabolicTimeParameterization traj_retimer;
// //make Robot Trajetory object
// robot_trajectory::RobotTrajectory rt(planning_scene_->getRobotModel(), motion_plan_req.group_name);
// moveit::core::RobotState rs(planning_scene_->getRobotModel());
// //retime the trajectory
// rs.setVariableValues(motion_plan_req.start_state.joint_state);
// rt.setRobotTrajectoryMsg(rs, *traj_it);
// bool success_retime = traj_retimer.computeTimeStamps(rt);
// ROS_INFO("Retimed trajectory successfully: %s", success_retime ? "yes" : "no" );
// rt.getRobotTrajectoryMsg(*traj_it);
// get the start point
moveit_warehouse::MotionPlanRequestWithMetadata planning_query;
pss.getPlanningQuery(planning_query, *scene_it, first_query);
moveit_msgs::MotionPlanRequest mpr = static_cast<const moveit_msgs::MotionPlanRequest&>(*planning_query);
// publish
if(1)
{
display_trajectory.trajectory_start = mpr.start_state;
display_trajectory.trajectory.push_back(rt_msg);
display_publisher.publish(display_trajectory);
sleep(5.0);
}
}
}
catch(mongo_ros::DbConnectException &ex)
{
ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again."
<< std::endl << ex.what());
}
ros::spin();
ROS_INFO("Successfully performed trajectory playback");
ros::shutdown();
return 0;
}
<commit_msg>added trajectory retiming support for visualizing trajectories<commit_after>#include <ros/ros.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/planning_scene/planning_scene.h>
#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <moveit/trajectory_processing/iterative_time_parameterization.h>
#include <boost/program_options.hpp>
int main(int argc, char** argv)
{
ros::init(argc, argv, "playback");
ros::NodeHandle node_handle;
ros::AsyncSpinner spinner(1);
spinner.start();
sleep(20); // to let RVIZ come up
boost::program_options::options_description desc;
desc.add_options()
("help", "Show help message")
("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");
boost::program_options::variables_map vm;
boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);
boost::program_options::store(po, vm);
boost::program_options::notify(vm);
if (vm.count("help") || argc == 1) // show help if no parameters passed
{
std::cout << desc << std::endl;
return 1;
}
try
{
//connect to the DB
std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
moveit_warehouse::PlanningSceneStorage pss(host, port);
ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port);
ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
moveit_msgs::DisplayTrajectory display_trajectory;
//ask the warehouse for the scene
std::vector<std::string> ps_names;
pss.getPlanningSceneNames( ps_names );
ros::Publisher ps_pub = node_handle.advertise<moveit_msgs::PlanningScene>("planning_scene", 1);
while(ps_pub.getNumSubscribers() < 1)
{
ros::WallDuration sleep_t(0.5);
ROS_INFO("Not enough subscribers to \"%s\" topic... ", "planning_scene");
sleep_t.sleep();
}
ROS_INFO("%d available scenes to display", (int)ps_names.size());
std::vector<std::string>::iterator scene_it = ps_names.begin();
for(; scene_it!=ps_names.end(); ++scene_it)
{
ROS_INFO("Retrieving scene %s", scene_it->c_str());
moveit_warehouse::PlanningSceneWithMetadata pswm;
pss.getPlanningScene(pswm, *scene_it);
// visualize the scene
ROS_INFO("Publishing scene...");
moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm);
ps_pub.publish(ps_msg);
// get query
std::vector<std::string> pq_names;
pss.getPlanningQueriesNames( pq_names, *scene_it);
ROS_INFO("%d available queries to display", (int)pq_names.size());
std::string first_query = pq_names.at(0);
moveit_warehouse::MotionPlanRequestWithMetadata mprwm;
pss.getPlanningQuery(mprwm, *scene_it, first_query);
moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm);
//get trajectory list
std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results;
pss.getPlanningResults(planning_results, *scene_it, first_query);
ROS_INFO("Loaded %d trajectories for query %s", (int)planning_results.size(), first_query.c_str());
// animate the first trajectory
size_t ind = 0;
moveit_msgs::RobotTrajectory rt_msg;
rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(*(planning_results[ind]));
// retime the trajectory
trajectory_processing::IterativeParabolicTimeParameterization traj_retimer;
planning_scene_monitor::PlanningSceneMonitor psm("robot_description");
planning_scene::PlanningScenePtr ps = psm.getPlanningScene();
ps->setPlanningSceneMsg( ps_msg );
robot_trajectory::RobotTrajectory rt(ps->getRobotModel(), mpr_msg.group_name);
moveit::core::RobotState rs(ps->getRobotModel());
rs.setVariableValues(mpr_msg.start_state.joint_state); //ref state
rt.setRobotTrajectoryMsg(rs, rt_msg);
bool success_retime = traj_retimer.computeTimeStamps(rt);
ROS_INFO("Retimed trajectory successfully: %s", success_retime ? "yes" : "no" );
rt.getRobotTrajectoryMsg(rt_msg);
// publish
if(1)
{
display_trajectory.trajectory_start = mpr_msg.start_state;
display_trajectory.trajectory.push_back(rt_msg);
display_publisher.publish(display_trajectory);
sleep(5.0);
}
}
}
catch(mongo_ros::DbConnectException &ex)
{
ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again."
<< std::endl << ex.what());
}
ros::spin();
ROS_INFO("Successfully performed trajectory playback");
ros::shutdown();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <sstream>
#include <float.h>
#include "reductions.h"
#include "gd.h"
struct oaa{
size_t k;
vw* all; // for raw
float*ret;
};
template <bool is_learn, bool print_all>
void predict_or_learn(oaa& o, LEARNER::base_learner& base, example& ec) {
MULTICLASS::label_t mc_label_data = ec.l.multi;
if (mc_label_data.label == 0 || (mc_label_data.label > o.k && mc_label_data.label != (uint32_t)-1))
cout << "label " << mc_label_data.label << " is not in {1,"<< o.k << "} This won't work right." << endl;
stringstream outputStringStream;
uint32_t prediction = 1;
ec.l.simple = {0.f, mc_label_data.weight, 0.f};
float score = INT_MIN;
for (uint32_t i = 1; i <= o.k; i++) {
if (is_learn) {
ec.l.simple.label = (mc_label_data.label == i) ? 1 : -1;
base.learn(ec, i-1);
} else
base.predict(ec, i-1);
if (ec.partial_prediction > score) {
score = ec.partial_prediction;
prediction = i;
}
if (print_all) {
if (i > 1) outputStringStream << ' ';
outputStringStream << i << ':' << ec.partial_prediction;
}
}
ec.pred.multiclass = prediction;
ec.l.multi = mc_label_data;
if (print_all)
o.all->print_text(o.all->raw_prediction, outputStringStream.str(), ec.tag);
}
LEARNER::base_learner* oaa_setup(vw& all)
{
if (missing_option<size_t, true>(all, "oaa", "One-against-all multiclass with <k> labels"))
return NULL;
oaa& data = calloc_or_die<oaa>();
data.k = all.vm["oaa"].as<size_t>();
data.all = &all;
data.ret = (float*)malloc(sizeof(float)*data.k);
LEARNER::learner<oaa>* l;
if (all.raw_prediction > 0)
l = &LEARNER::init_multiclass_learner(&data, setup_base(all), predict_or_learn<true, true>,
predict_or_learn<false, true>, all.p, data.k);
else
l = &LEARNER::init_multiclass_learner(&data, setup_base(all),predict_or_learn<true, false>,
predict_or_learn<false, false>, all.p, data.k);
return make_base(*l);
}
<commit_msg>cleaned up oaa.cc<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <sstream>
#include <float.h>
#include "reductions.h"
#include "gd.h"
struct oaa{
size_t k;
vw* all; // for raw
};
template <bool is_learn, bool print_all>
void predict_or_learn(oaa& o, LEARNER::base_learner& base, example& ec) {
MULTICLASS::label_t mc_label_data = ec.l.multi;
if (mc_label_data.label == 0 || (mc_label_data.label > o.k && mc_label_data.label != (uint32_t)-1))
cout << "label " << mc_label_data.label << " is not in {1,"<< o.k << "} This won't work right." << endl;
stringstream outputStringStream;
uint32_t prediction = 1;
ec.l.simple = {0.f, mc_label_data.weight, 0.f};
float score = INT_MIN;
for (uint32_t i = 1; i <= o.k; i++) {
if (is_learn) {
ec.l.simple.label = (mc_label_data.label == i) ? 1 : -1;
base.learn(ec, i-1);
} else
base.predict(ec, i-1);
if (ec.partial_prediction > score) {
score = ec.partial_prediction;
prediction = i;
}
if (print_all) {
if (i > 1) outputStringStream << ' ';
outputStringStream << i << ':' << ec.partial_prediction;
}
}
ec.pred.multiclass = prediction;
ec.l.multi = mc_label_data;
if (print_all)
o.all->print_text(o.all->raw_prediction, outputStringStream.str(), ec.tag);
}
LEARNER::base_learner* oaa_setup(vw& all)
{
if (missing_option<size_t, true>(all, "oaa", "One-against-all multiclass with <k> labels"))
return NULL;
oaa& data = calloc_or_die<oaa>();
data.k = all.vm["oaa"].as<size_t>();
data.all = &all;
LEARNER::learner<oaa>* l;
if (all.raw_prediction > 0)
l = &LEARNER::init_multiclass_learner(&data, setup_base(all), predict_or_learn<true, true>,
predict_or_learn<false, true>, all.p, data.k);
else
l = &LEARNER::init_multiclass_learner(&data, setup_base(all),predict_or_learn<true, false>,
predict_or_learn<false, false>, all.p, data.k);
return make_base(*l);
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <memory>
#include <utility>
// Linux headers
#include <libgen.h>
#include <signal.h>
#include "handler/feed_document_handler.h"
#include "handler/query_handler.h"
#include "handler/test_handler.h"
#include "index/document_index_manager.h"
#include "parser/document_parser.h"
#include "parser/feature_cache_parser.h"
#include "parser/query_request_parser.h"
#include "pipeline/feed_document_pipeline.h"
#include "query/simple_query_executor.h"
#include "ranking/default_model.h"
#include "ranking/feature_mapping_model.h"
#include "ranking/model_manager.h"
#include "ranking/ranking_model.h"
#include "service/server.h"
#include "third_party/rapidjson/document.h"
#include "third_party/rapidjson/filereadstream.h"
#include "utils/logger.h"
#include "utils/logger-inl.h"
#include "utils/scope_guard.h"
using std::string;
namespace redgiant {
DECLARE_LOGGER(logger, __FILE__);
static const unsigned int kParseFlags = rapidjson::kParseCommentsFlag | rapidjson::kParseTrailingCommasFlag;
static const char CONF_LOGGER_CONFIG [] = "logger_config";
static const char CONF_FEATURES [] = "feature_spaces";
static const char CONF_INDEX [] = "index";
static const char CONF_RANKING [] = "ranking";
static const char CONF_PIPELINE [] = "pipeline";
static const char CONF_SERVER [] = "server";
static volatile int g_exit_signal = 0;
static void new_handler_abort() {
std::abort();
}
void ignore_signal(int signal) {
(void) signal;
}
void exit_on_signal(int signal) {
(void) signal;
g_exit_signal = signal;
}
static int read_config_file(const char* file_name, rapidjson::Document& config) {
std::FILE* fp = std::fopen(file_name, "r");
if (!fp) {
fprintf(stderr, "Cannot open config file %s.\n", file_name);
return -1;
}
char readBuffer[8192];
rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
if (config.ParseStream<kParseFlags>(is).HasParseError()) {
fprintf(stderr, "Config file parse error %d at offset %zu.\n",
(int)config.GetParseError(), config.GetErrorOffset());
return -1;
}
std::fclose(fp);
return 0;
}
static int init_log_config(const char* file_name, const rapidjson::Value& config) {
if (!config.HasMember(CONF_LOGGER_CONFIG) || !config[CONF_LOGGER_CONFIG].IsString()) {
fprintf(stderr, "No log file configured!");
return init_logger(NULL);
}
// Copy the file name to a temporary buffer to call "dirname"
size_t file_name_len = strlen(file_name);
std::unique_ptr<char[]> file_name_buf(new char[file_name_len + 1]);
strncpy(file_name_buf.get(), file_name, file_name_len);
file_name_buf[file_name_len] = 0;
std::string dir = dirname(file_name_buf.get());
if (dir.back() != '/') {
dir += "/";
}
// get the file name relative to the configuration file.
std::string logger_file_name = dir + config[CONF_LOGGER_CONFIG].GetString();
return init_logger(logger_file_name.c_str());
}
static int server_main(rapidjson::Value& config) {
/*
* Initialize signal handler
*/
signal(SIGPIPE, ignore_signal);
signal(SIGHUP, ignore_signal);
signal(SIGTERM, exit_on_signal);
signal(SIGINT, exit_on_signal);
/*
* Initialization:
* Features initialization
*/
if (!config.HasMember(CONF_FEATURES)) {
LOG_ERROR(logger, "features configuration does not exist!");
return -1;
}
std::shared_ptr<FeatureCache> feature_cache = std::make_shared<FeatureCache>();
FeatureCacheParser feature_cache_parser;
if (feature_cache_parser.parse_json(config[CONF_FEATURES], *feature_cache) < 0) {
LOG_ERROR(logger, "feature cache parsing failed!");
return -1;
}
/*
* Initialization:
* Index initialization
*/
int document_index_initial_buckets = 100000;
int document_index_max_size = 5000000;
int document_index_maintain_interval = 300;
if (config.HasMember(CONF_INDEX)) {
auto& index_config = config[CONF_INDEX];
if (index_config.HasMember("initial_buckets") && index_config["initial_buckets"].IsInt()) {
document_index_initial_buckets = index_config["initial_buckets"].GetInt();
}
if (index_config.HasMember("max_size") && index_config["max_size"].IsInt()) {
document_index_max_size = index_config["max_size"].GetInt();
}
if (index_config.HasMember("maintain_interval") && index_config["maintain_interval"].IsInt()) {
document_index_maintain_interval = index_config["max_size"].GetInt();
}
}
DocumentIndexManager document_index(document_index_initial_buckets, document_index_max_size);
document_index.start_maintain(document_index_maintain_interval, document_index_maintain_interval);
ScopeGuard feed_document_index_guard([&document_index] {
LOG_INFO(logger, "document index maintain thread stopping...");
document_index.stop_maintain();
});
size_t feed_document_thread_num = 4;
size_t feed_document_queue_size = 2048;
if (config.HasMember(CONF_PIPELINE)) {
auto& pipeline_config = config[CONF_PIPELINE];
if (pipeline_config.HasMember("thread_num") && pipeline_config["thread_num"].IsInt()) {
feed_document_thread_num = pipeline_config["thread_num"].GetInt();
}
if (pipeline_config.HasMember("queue_size") && pipeline_config["queue_size"].IsInt()) {
feed_document_queue_size = pipeline_config["queue_size"].GetInt();
}
}
FeedDocumentPipeline feed_document(feed_document_thread_num, feed_document_queue_size, &document_index);
feed_document.start();
ScopeGuard feed_document_pipeline_guard([&feed_document] {
LOG_INFO(logger, "feed document pipeline stopping...");
feed_document.stop();
});
/*
* Initialization
* Query and ranking models
*/
ModelManagerFactory model_manager_factory;
model_manager_factory.register_model_factory(std::make_shared<DefaultModelFactory>());
model_manager_factory.register_model_factory(std::make_shared<FeatureMappingModelFactory>(feature_cache));
if (!config.HasMember(CONF_RANKING)) {
LOG_ERROR(logger, "ranking model config does not exist!");
return -1;
}
std::unique_ptr<RankingModel> model = model_manager_factory.create_model(config[CONF_RANKING]);
if (!model) {
LOG_ERROR(logger, "ranking model initialization failed!");
return -1;
}
/*
* Initialization:
* Server initialization
*/
LOG_INFO(logger, "server initializing ...");
int server_port = 19980;
size_t server_thread_num = 4;
size_t max_req_per_thread = 0;
if (config.HasMember(CONF_SERVER)) {
auto& server_config = config[CONF_SERVER];
if (server_config.HasMember("port") && server_config["port"].IsInt()) {
server_port = server_config["port"].GetInt();
}
if (server_config.HasMember("thread_num") && server_config["thread_num"].IsInt()) {
server_thread_num = server_config["thread_num"].GetInt();
}
if (server_config.HasMember("max_request_per_thread") && server_config["max_request_per_thread"].IsInt()) {
max_req_per_thread = server_config["max_request_per_thread"].GetInt();
}
}
Server test_server(server_port, server_thread_num, max_req_per_thread);
test_server.bind("/test", std::make_shared<TestHandlerFactory>());
test_server.bind("/document", std::make_shared<FeedDocumentHandlerFactory>(
std::make_shared<DocumentParserFactory>(feature_cache),
&feed_document, 0));
test_server.bind("/query", std::make_shared<QueryHandlerFactory>(
std::make_shared<QueryRequestParserFactory>(feature_cache),
std::make_shared<SimpleQueryExecutorFactory>(&document_index, model.get())));
if (test_server.initialize() < 0) {
LOG_ERROR(logger, "test server initialization failed!");
return -1;
}
ScopeGuard test_server_guard([&test_server] {
LOG_INFO(logger, "test server exiting...");
test_server.stop();
});
if (test_server.start() < 0) {
LOG_ERROR(logger, "failed to start test server!");
return -1;
}
LOG_INFO(logger, "test server stared.");
/*
* Main loop: wait for exit signal.
*/
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGTERM);
sigaddset(&mask, SIGINT);
sigset_t orig_mask;
sigprocmask(SIG_BLOCK, &mask, &orig_mask);
g_exit_signal = 0;
while (!g_exit_signal) {
sigsuspend(&orig_mask);
}
/*
* Exit: everything exits elegantly
*/
LOG_INFO(logger, "received signal %d. exiting.", g_exit_signal);
return 0;
}
int main(int argc, char** argv) {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
std::set_new_handler(new_handler_abort);
if (argc != 2) {
fprintf(stderr, "Usage: %s config_file\n", argv[0]);
return -1;
}
rapidjson::Document config;
if (read_config_file(argv[1], config) < 0) {
fprintf(stderr, "Failed to open config file %s.\n", argv[1]);
return -1;
}
if (init_log_config(argv[1], config) < 0) {
fprintf(stderr, "Failed to initialize log config.\n");
return -1;
}
int ret = -1;
try {
ret = server_main(config);
} catch (...) {
// don't make this happen
ret = -1;
LOG_ERROR(logger, "unkown error happened");
}
if (ret >= 0) {
LOG_INFO(logger, "server exit ALL OK.");
} else {
LOG_INFO(logger, "server exit OK with failure.");
}
return ret;
}
} /* namespace redgiant */
int main(int argc, char** argv) {
return redgiant::main(argc, argv);
}
<commit_msg>rename configuration constants<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <memory>
#include <utility>
// Linux headers
#include <libgen.h>
#include <signal.h>
#include "handler/feed_document_handler.h"
#include "handler/query_handler.h"
#include "handler/test_handler.h"
#include "index/document_index_manager.h"
#include "parser/document_parser.h"
#include "parser/feature_cache_parser.h"
#include "parser/query_request_parser.h"
#include "pipeline/feed_document_pipeline.h"
#include "query/simple_query_executor.h"
#include "ranking/default_model.h"
#include "ranking/feature_mapping_model.h"
#include "ranking/model_manager.h"
#include "ranking/ranking_model.h"
#include "service/server.h"
#include "third_party/rapidjson/document.h"
#include "third_party/rapidjson/filereadstream.h"
#include "utils/logger.h"
#include "utils/logger-inl.h"
#include "utils/scope_guard.h"
using std::string;
namespace redgiant {
DECLARE_LOGGER(logger, __FILE__);
// constants used by configuration files
static const unsigned int kConfigParseFlags =
rapidjson::kParseCommentsFlag | rapidjson::kParseTrailingCommasFlag;
static const char kConfigKeyLoggerConfig [] = "logger_config";
static const char kConfigKeyFeatureSpaces [] = "feature_spaces";
static const char kConfigKeyIndex [] = "index";
static const char kConfigKeyRanking [] = "ranking";
static const char kConfigKeyPipeline [] = "pipeline";
static const char kConfigKeyServer [] = "server";
static volatile int g_exit_signal = 0;
static void new_handler_abort() {
std::abort();
}
void ignore_signal(int signal) {
(void) signal;
}
void exit_on_signal(int signal) {
(void) signal;
g_exit_signal = signal;
}
static int read_config_file(const char* file_name, rapidjson::Document& config) {
std::FILE* fp = std::fopen(file_name, "r");
if (!fp) {
fprintf(stderr, "Cannot open config file %s.\n", file_name);
return -1;
}
char readBuffer[8192];
rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
if (config.ParseStream<kConfigParseFlags>(is).HasParseError()) {
fprintf(stderr, "Config file parse error %d at offset %zu.\n",
(int)config.GetParseError(), config.GetErrorOffset());
return -1;
}
std::fclose(fp);
return 0;
}
static int init_log_config(const char* file_name, const rapidjson::Value& config) {
if (!config.HasMember(kConfigKeyLoggerConfig) || !config[kConfigKeyLoggerConfig].IsString()) {
fprintf(stderr, "No log file configured!");
return init_logger(NULL);
}
// Copy the file name to a temporary buffer to call "dirname"
size_t file_name_len = strlen(file_name);
std::unique_ptr<char[]> file_name_buf(new char[file_name_len + 1]);
strncpy(file_name_buf.get(), file_name, file_name_len);
file_name_buf[file_name_len] = 0;
std::string dir = dirname(file_name_buf.get());
if (dir.back() != '/') {
dir += "/";
}
// get the file name relative to the configuration file.
std::string logger_file_name = dir + config[kConfigKeyLoggerConfig].GetString();
return init_logger(logger_file_name.c_str());
}
static int server_main(rapidjson::Value& config) {
/*
* Initialize signal handler
*/
signal(SIGPIPE, ignore_signal);
signal(SIGHUP, ignore_signal);
signal(SIGTERM, exit_on_signal);
signal(SIGINT, exit_on_signal);
/*
* Initialization:
* Features initialization
*/
if (!config.HasMember(kConfigKeyFeatureSpaces)) {
LOG_ERROR(logger, "features configuration does not exist!");
return -1;
}
std::shared_ptr<FeatureCache> feature_cache = std::make_shared<FeatureCache>();
FeatureCacheParser feature_cache_parser;
if (feature_cache_parser.parse_json(config[kConfigKeyFeatureSpaces], *feature_cache) < 0) {
LOG_ERROR(logger, "feature cache parsing failed!");
return -1;
}
/*
* Initialization:
* Index initialization
*/
int document_index_initial_buckets = 100000;
int document_index_max_size = 5000000;
int document_index_maintain_interval = 300;
if (config.HasMember(kConfigKeyIndex)) {
auto& index_config = config[kConfigKeyIndex];
if (index_config.HasMember("initial_buckets") && index_config["initial_buckets"].IsInt()) {
document_index_initial_buckets = index_config["initial_buckets"].GetInt();
}
if (index_config.HasMember("max_size") && index_config["max_size"].IsInt()) {
document_index_max_size = index_config["max_size"].GetInt();
}
if (index_config.HasMember("maintain_interval") && index_config["maintain_interval"].IsInt()) {
document_index_maintain_interval = index_config["max_size"].GetInt();
}
}
DocumentIndexManager document_index(document_index_initial_buckets, document_index_max_size);
document_index.start_maintain(document_index_maintain_interval, document_index_maintain_interval);
ScopeGuard feed_document_index_guard([&document_index] {
LOG_INFO(logger, "document index maintain thread stopping...");
document_index.stop_maintain();
});
size_t feed_document_thread_num = 4;
size_t feed_document_queue_size = 2048;
if (config.HasMember(kConfigKeyPipeline)) {
auto& pipeline_config = config[kConfigKeyPipeline];
if (pipeline_config.HasMember("thread_num") && pipeline_config["thread_num"].IsInt()) {
feed_document_thread_num = pipeline_config["thread_num"].GetInt();
}
if (pipeline_config.HasMember("queue_size") && pipeline_config["queue_size"].IsInt()) {
feed_document_queue_size = pipeline_config["queue_size"].GetInt();
}
}
FeedDocumentPipeline feed_document(feed_document_thread_num, feed_document_queue_size, &document_index);
feed_document.start();
ScopeGuard feed_document_pipeline_guard([&feed_document] {
LOG_INFO(logger, "feed document pipeline stopping...");
feed_document.stop();
});
/*
* Initialization
* Query and ranking models
*/
ModelManagerFactory model_manager_factory;
model_manager_factory.register_model_factory(std::make_shared<DefaultModelFactory>());
model_manager_factory.register_model_factory(std::make_shared<FeatureMappingModelFactory>(feature_cache));
if (!config.HasMember(kConfigKeyRanking)) {
LOG_ERROR(logger, "ranking model config does not exist!");
return -1;
}
std::unique_ptr<RankingModel> model = model_manager_factory.create_model(config[kConfigKeyRanking]);
if (!model) {
LOG_ERROR(logger, "ranking model initialization failed!");
return -1;
}
/*
* Initialization:
* Server initialization
*/
LOG_INFO(logger, "server initializing ...");
int server_port = 19980;
size_t server_thread_num = 4;
size_t max_req_per_thread = 0;
if (config.HasMember(kConfigKeyServer)) {
auto& server_config = config[kConfigKeyServer];
if (server_config.HasMember("port") && server_config["port"].IsInt()) {
server_port = server_config["port"].GetInt();
}
if (server_config.HasMember("thread_num") && server_config["thread_num"].IsInt()) {
server_thread_num = server_config["thread_num"].GetInt();
}
if (server_config.HasMember("max_request_per_thread") && server_config["max_request_per_thread"].IsInt()) {
max_req_per_thread = server_config["max_request_per_thread"].GetInt();
}
}
Server test_server(server_port, server_thread_num, max_req_per_thread);
test_server.bind("/test", std::make_shared<TestHandlerFactory>());
test_server.bind("/document", std::make_shared<FeedDocumentHandlerFactory>(
std::make_shared<DocumentParserFactory>(feature_cache),
&feed_document, 0));
test_server.bind("/query", std::make_shared<QueryHandlerFactory>(
std::make_shared<QueryRequestParserFactory>(feature_cache),
std::make_shared<SimpleQueryExecutorFactory>(&document_index, model.get())));
if (test_server.initialize() < 0) {
LOG_ERROR(logger, "test server initialization failed!");
return -1;
}
ScopeGuard test_server_guard([&test_server] {
LOG_INFO(logger, "test server exiting...");
test_server.stop();
});
if (test_server.start() < 0) {
LOG_ERROR(logger, "failed to start test server!");
return -1;
}
LOG_INFO(logger, "test server stared.");
/*
* Main loop: wait for exit signal.
*/
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGTERM);
sigaddset(&mask, SIGINT);
sigset_t orig_mask;
sigprocmask(SIG_BLOCK, &mask, &orig_mask);
g_exit_signal = 0;
while (!g_exit_signal) {
sigsuspend(&orig_mask);
}
/*
* Exit: everything exits elegantly
*/
LOG_INFO(logger, "received signal %d. exiting.", g_exit_signal);
return 0;
}
int main(int argc, char** argv) {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
std::set_new_handler(new_handler_abort);
if (argc != 2) {
fprintf(stderr, "Usage: %s config_file\n", argv[0]);
return -1;
}
rapidjson::Document config;
if (read_config_file(argv[1], config) < 0) {
fprintf(stderr, "Failed to open config file %s.\n", argv[1]);
return -1;
}
if (init_log_config(argv[1], config) < 0) {
fprintf(stderr, "Failed to initialize log config.\n");
return -1;
}
int ret = -1;
try {
ret = server_main(config);
} catch (...) {
// don't make this happen
ret = -1;
LOG_ERROR(logger, "unkown error happened");
}
if (ret >= 0) {
LOG_INFO(logger, "server exit ALL OK.");
} else {
LOG_INFO(logger, "server exit OK with failure.");
}
return ret;
}
} /* namespace redgiant */
int main(int argc, char** argv) {
return redgiant::main(argc, argv);
}
<|endoftext|>
|
<commit_before>#include <test/unit/math/test_ad.hpp>
#include <vector>
TEST(mathMixMatFun, acosh) {
auto f = [](const auto& x1) {
using stan::math::acosh;
return acosh(x1);
};
for (double x : stan::test::internal::common_args())
stan::test::expect_unary_vectorized(x);
stan::test::expect_unary_vectorized(f, 1.5, 3.2, 5, 10, 12.9);
// avoid pole at complex zero that can't be autodiffed
for (double re : std::vector<double>{-0.2, 0, 0.3}) {
for (double im : std::vector<double>{-0.3, 0.2}) {
stan::test::expect_ad(f, std::complex<double>{re, im});
}
}
}
TEST(mathMixMatFun, acosh_varmat) {
using stan::math::vec_concat;
using stan::test::expect_ad_vector_matvar;
using stan::test::internal::common_args;
auto f = [](const auto& x1) {
using stan::math::acosh;
return acosh(x1);
};
std::vector<double> com_args = common_args();
std::vector<double> args{1.5, 3.2, 5, 10, 12.9};
auto all_args = vec_concat(com_args, args);
Eigen::VectorXd A(all_args.size());
for (int i = 0; i < all_args.size(); ++i) {
A(i) = all_args[i];
}
expect_ad_vector_matvar(f, A);
}
<commit_msg>fix acosh<commit_after>#include <test/unit/math/test_ad.hpp>
#include <vector>
TEST(mathMixMatFun, acosh) {
auto f = [](const auto& x1) {
using stan::math::acosh;
return acosh(x1);
};
for (double x : stan::test::internal::common_args())
stan::test::expect_unary_vectorized(f, x);
stan::test::expect_unary_vectorized(f, 1.5, 3.2, 5, 10, 12.9);
// avoid pole at complex zero that can't be autodiffed
for (double re : std::vector<double>{-0.2, 0, 0.3}) {
for (double im : std::vector<double>{-0.3, 0.2}) {
stan::test::expect_ad(f, std::complex<double>{re, im});
}
}
}
TEST(mathMixMatFun, acosh_varmat) {
using stan::math::vec_concat;
using stan::test::expect_ad_vector_matvar;
using stan::test::internal::common_args;
auto f = [](const auto& x1) {
using stan::math::acosh;
return acosh(x1);
};
std::vector<double> com_args = common_args();
std::vector<double> args{1.5, 3.2, 5, 10, 12.9};
auto all_args = vec_concat(com_args, args);
Eigen::VectorXd A(all_args.size());
for (int i = 0; i < all_args.size(); ++i) {
A(i) = all_args[i];
}
expect_ad_vector_matvar(f, A);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "protocol.h"
#include "chainparams.h"
#include "util.h"
#ifndef WIN32
# include <arpa/inet.h>
#endif
static const char* ppszTypeName[] =
{
"ERROR",
"tx",
"block",
"filtered block"
};
CMessageHeader::CMessageHeader()
{
memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);
memset(pchCommand, 0, sizeof(pchCommand));
pchCommand[1] = 1;
nMessageSize = -1;
nChecksum = 0;
}
CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
{
memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);
strncpy(pchCommand, pszCommand, COMMAND_SIZE);
nMessageSize = nMessageSizeIn;
nChecksum = 0;
}
std::string CMessageHeader::GetCommand() const
{
if (pchCommand[COMMAND_SIZE-1] == 0)
return std::string(pchCommand, pchCommand + strlen(pchCommand));
else
return std::string(pchCommand, pchCommand + COMMAND_SIZE);
}
bool CMessageHeader::IsValid() const
{
// Check start string
if (memcmp(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0)
return false;
// Check the command string for errors
for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
{
if (*p1 == 0)
{
// Must be all zeros after the first zero
for (; p1 < pchCommand + COMMAND_SIZE; p1++)
if (*p1 != 0)
return false;
}
else if (*p1 < ' ' || *p1 > 0x7E)
return false;
}
// Message size
if (nMessageSize > MAX_SIZE)
{
LogPrintf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
return false;
}
return true;
}
CAddress::CAddress() : CService()
{
Init();
}
CAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)
{
Init();
nServices = nServicesIn;
}
void CAddress::Init()
{
nServices = NODE_NETWORK;
nTime = 100000000;
nLastTry = 0;
}
CInv::CInv()
{
type = 0;
hash = 0;
}
CInv::CInv(int typeIn, const uint256& hashIn)
{
type = typeIn;
hash = hashIn;
}
CInv::CInv(const std::string& strType, const uint256& hashIn)
{
unsigned int i;
for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
{
if (strType == ppszTypeName[i])
{
type = i;
break;
}
}
if (i == ARRAYLEN(ppszTypeName))
throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType));
hash = hashIn;
}
bool operator<(const CInv& a, const CInv& b)
{
return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}
bool CInv::IsKnownType() const
{
return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));
}
const char* CInv::GetCommand() const
{
if (!IsKnownType())
throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
return ppszTypeName[type];
}
std::string CInv::ToString() const
{
return strprintf("%s %s", GetCommand(), hash.ToString());
}
<commit_msg>CMessageHeader sanity changes<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "protocol.h"
#include "chainparams.h"
#include "util.h"
#ifndef WIN32
# include <arpa/inet.h>
#endif
static const char* ppszTypeName[] =
{
"ERROR",
"tx",
"block",
"filtered block"
};
CMessageHeader::CMessageHeader()
{
memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);
memset(pchCommand, 0, sizeof(pchCommand));
nMessageSize = -1;
nChecksum = 0;
}
CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
{
memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);
memset(pchCommand, 0, sizeof(pchCommand));
strncpy(pchCommand, pszCommand, COMMAND_SIZE);
nMessageSize = nMessageSizeIn;
nChecksum = 0;
}
std::string CMessageHeader::GetCommand() const
{
return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
}
bool CMessageHeader::IsValid() const
{
// Check start string
if (memcmp(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0)
return false;
// Check the command string for errors
for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
{
if (*p1 == 0)
{
// Must be all zeros after the first zero
for (; p1 < pchCommand + COMMAND_SIZE; p1++)
if (*p1 != 0)
return false;
}
else if (*p1 < ' ' || *p1 > 0x7E)
return false;
}
// Message size
if (nMessageSize > MAX_SIZE)
{
LogPrintf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
return false;
}
return true;
}
CAddress::CAddress() : CService()
{
Init();
}
CAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)
{
Init();
nServices = nServicesIn;
}
void CAddress::Init()
{
nServices = NODE_NETWORK;
nTime = 100000000;
nLastTry = 0;
}
CInv::CInv()
{
type = 0;
hash = 0;
}
CInv::CInv(int typeIn, const uint256& hashIn)
{
type = typeIn;
hash = hashIn;
}
CInv::CInv(const std::string& strType, const uint256& hashIn)
{
unsigned int i;
for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
{
if (strType == ppszTypeName[i])
{
type = i;
break;
}
}
if (i == ARRAYLEN(ppszTypeName))
throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType));
hash = hashIn;
}
bool operator<(const CInv& a, const CInv& b)
{
return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}
bool CInv::IsKnownType() const
{
return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));
}
const char* CInv::GetCommand() const
{
if (!IsKnownType())
throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
return ppszTypeName[type];
}
std::string CInv::ToString() const
{
return strprintf("%s %s", GetCommand(), hash.ToString());
}
<|endoftext|>
|
<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
#include <pybind11/operators.h>
#include <pybind11/functional.h>
#include <core.h>
#include <space.h>
#include <move.h>
#include <analysis.h>
#include <potentials.h>
#include <regions.h>
#include <montecarlo.h>
#include <energy.h>
namespace py = pybind11;
using namespace Faunus;
typedef typename Space::GroupType Tgroup;
typedef Energy::Hamiltonian Thamiltonian;
typedef MetropolisMonteCarlo Tmcsimulation;
inline json dict2json(py::dict dict) {
py::object dumps = py::module::import("json").attr("dumps");
return json::parse( dumps(dict).cast<std::string>() );
} // python dict --> c++ json
inline json list2json(py::list list) {
py::object dumps = py::module::import("json").attr("dumps");
return json::parse(dumps(list).cast<std::string>());
} // python list --> c++ json
inline py::dict json2dict(const json &j) {
py::object loads = py::module::import("json").attr("loads");
return loads( j.dump() ) ;
}
template<class T>
std::unique_ptr<T> from_dict(py::dict dict) {
auto ptr = new T();
*ptr = dict2json(dict);
return std::unique_ptr<T>(ptr);
} // convert py::dict to T through Faunus::json
PYBIND11_MODULE(pyfaunus, m)
{
using namespace pybind11::literals;
// json
py::class_<json>(m, "json")
.def(py::init( [](std::string arg) {
return std::unique_ptr<json>(new json(json::parse(arg)));
} ) )
.def(py::init([](py::dict dict) {
py::object dumps = py::module::import("json").attr("dumps");
std::string s = dumps(dict).cast<std::string>();
return std::unique_ptr<json>(new json(json::parse(s)));
} ) );
// Random
py::class_<Random>(m, "Random")
.def(py::init<>())
.def("__call__", [](Random &self){ return self(); } ); // function operator
m.attr("random") = &Faunus::random; // global instance
// Geometries
py::enum_<Geometry::VolumeMethod>(m, "VolumeMethod")
.value("ISOTROPIC", Geometry::VolumeMethod::ISOTROPIC)
.value("ISOCHORIC", Geometry::VolumeMethod::ISOCHORIC)
.value("XY", Geometry::VolumeMethod::XY)
.value("Z", Geometry::VolumeMethod::Z)
.export_values();
py::class_<Geometry::GeometryBase>(m, "Geometrybase")
.def("getVolume", &Geometry::GeometryBase::getVolume, "Get container volume", "dim"_a = 3)
.def("setVolume", &Geometry::GeometryBase::setVolume, "Set container volume", "volume"_a,
"method"_a = Geometry::VolumeMethod::ISOTROPIC)
.def("collision", &Geometry::GeometryBase::collision, "pos"_a, "Checks if point is inside container")
.def("getLength", &Geometry::GeometryBase::getLength, "Get cuboid sidelengths")
.def("vdist", &Geometry::GeometryBase::vdist, "Minimum vector distance, a-b", "a"_a, "b"_a)
.def("randompos",
[](Geometry::GeometryBase& g, Random& rnd) {
Point pos;
g.randompos(pos, rnd);
return pos;
})
.def(
"boundary",
[](Geometry::GeometryBase& g, const Point& pos) {
Point a = pos; // we cannot modify `pos` directly
g.boundary(a); // as in c++
return a;
},
R"(
Apply periodic boundaries
If applicable for the geometry type, this will apply
periodic boundaries to a coordinate.
Args:
pos (array): coordinate
Returns:
array: position with wrapped coordinate
)");
py::class_<Geometry::Chameleon, Geometry::GeometryBase>(m, "Chameleon")
.def(py::init<>())
.def(py::init([](py::dict dict) {
auto ptr = std::make_unique<Geometry::Chameleon>();
Faunus::Geometry::from_json(dict2json(dict), *ptr);
return ptr;
}))
.def("sqdist", &Geometry::Chameleon::sqdist, "Squared minimum distance, |a-b|^2", "a"_a, "b"_a);
// Particle properties
py::class_<Charge>(m, "Charge")
.def(py::init<>())
.def_readwrite("charge", &Charge::charge, "Particle charge (monopole)");
py::class_<Particle>(m, "Particle")
.def(py::init<>())
.def("traits", &Particle::traits)
.def_readwrite("id", &Particle::id, "Particle ID")
.def_readwrite("pos", &Particle::pos, "Particle position")
.def_readwrite("charge", &Particle::charge, "Particle charge (monopole)");
// Particle vector and it's iterator
py::class_<ParticleVector::iterator>(m, "ParticleVectorIterator")
.def("__add__", [](ParticleVector::iterator it, int i) { return it + i; })
.def("__sub__", [](ParticleVector::iterator it, int i) { return it - i; });
auto _pvec = py::bind_vector<ParticleVector>(m, "ParticleVector");
_pvec.def("positions", [](ParticleVector& p) { return asEigenMatrix(p.begin(), p.end(), &Particle::pos); })
.def("charges", [](ParticleVector& p) { return asEigenVector(p.begin(), p.end(), &Particle::charge); })
.def("begin", [](ParticleVector& p) { return p.begin(); })
.def("end", [](ParticleVector& p) { return p.end(); });
// Group
py::class_<Tgroup>(m, "Group")
.def(py::init<MoleculeData::index_type, ParticleVector::iterator, ParticleVector::iterator>())
.def_readwrite("groups", &Tgroup::id, "Molecule id")
.def_readwrite("id", &Tgroup::id, "Molecule id")
.def_readwrite("cm", &Tgroup::mass_center, "Center of mass")
.def("__len__", [](Tgroup& self) { return self.size(); })
.def(
"__iter__", [](Tgroup& v) { return py::make_iterator(v.begin(), v.end()); }, py::keep_alive<0, 1>())
.def("isAtomic", &Tgroup::isAtomic)
.def("isMolecular", &Tgroup::isMolecular)
.def("traits", &Tgroup::traits)
.def("contains", &Tgroup::contains)
.def("capacity", &Tgroup::capacity)
.def("deactivate", &Tgroup::deactivate)
.def("activate", &Tgroup::activate)
.def("begin", (ParticleVector::iterator & (Tgroup::*)()) & Tgroup::begin)
.def("end", (ParticleVector::iterator & (Tgroup::*)()) & Tgroup::end);
py::bind_vector<std::vector<Tgroup>>(m, "GroupVector");
// Region
py::enum_<Region::RegionBase::RegionType>(m, "RegionType")
.value("SPHERE", Region::RegionBase::RegionType::SPHERE)
.value("CUBOID", Region::RegionBase::RegionType::CUBOID)
.value("WITHIN", Region::RegionBase::RegionType::WITHIN)
.value("NONE", Region::RegionBase::RegionType::NONE)
.export_values();
py::class_<Region::RegionBase>(m, "RegionBase")
.def_readwrite("name", &Region::RegionBase::name)
.def_readwrite("type", &Region::RegionBase::type)
.def("volume", &Region::RegionBase::isInside)
.def("isInside", &Region::RegionBase::isInside);
// AtomData
py::class_<AtomData>(m, "AtomData")
.def(py::init<>())
.def_property(
"eps", [](const AtomData& a) { return a.interaction.at("eps"); },
[](AtomData& a, double val) { a.interaction.at("eps") = val; })
.def_property(
"sigma", [](const AtomData& a) { return a.interaction.at("sigma"); },
[](AtomData& a, double val) { a.interaction.at("sigma") = val; })
.def_readwrite("name", &AtomData::name)
.def_readwrite("activity", &AtomData::activity, "Activity = chemical potential in log scale (mol/l)")
.def("id", (const AtomData::index_type& (AtomData::*)() const) &
AtomData::id); // explicit signature due to overload in c++
auto _atomdatavec = py::bind_vector<std::vector<AtomData>>(m, "AtomDataVector");
_atomdatavec
.def("from_list", [](std::vector<AtomData> &a, py::list list) {
Faunus::from_json(list2json(list), a); } );
m.attr("atoms") = &Faunus::atoms; // global instance
// Temperature and other globals etc.
m.def("getTemperature", []() { return pc::temperature; } );
m.def("setTemperature", [](double T) { pc::temperature = T; } );
// --------- Pair Potentials ---------
// Base
py::class_<Potential::PairPotentialBase>(m, "PairPotentialBase")
.def_readwrite("name", &Potential::PairPotentialBase::name)
.def_readwrite("cite", &Potential::PairPotentialBase::cite)
.def_readwrite("isotropic", &Potential::PairPotentialBase::isotropic)
.def_readwrite("selfEnergy", &Potential::PairPotentialBase::selfEnergy)
.def("force", &Potential::PairPotentialBase::force)
.def("energy", [](Potential::PairPotentialBase &pot, const Particle &a, const Particle &b, double r2,
const Point &r) { return pot(a, b, r2, r); });
// Potentials::FunctorPotential
py::class_<Potential::FunctorPotential, Potential::PairPotentialBase>(m, "FunctorPotential")
.def(py::init([](py::dict dict) { return from_dict<Potential::FunctorPotential>(dict); }));
// Change::Data
py::class_<Change::GroupChange>(m, "ChangeData")
.def(py::init<>())
.def_readwrite("dNatomic", &Change::GroupChange::dNatomic)
.def_readwrite("dNswap", &Change::GroupChange::dNswap)
.def_readwrite("index", &Change::GroupChange::group_index)
.def_readwrite("internal", &Change::GroupChange::internal)
.def_readwrite("all", &Change::GroupChange::all)
.def_readwrite("atoms", &Change::GroupChange::relative_atom_indices);
py::bind_vector<std::vector<Change::GroupChange>>(m, "ChangeDataVec");
// Change
py::class_<Change>(m, "Change")
.def(py::init<>())
.def_readwrite("everything", &Change::everything)
.def_readwrite("volume_change", &Change::volume_change)
.def_readwrite("matter_change", &Change::matter_change)
.def_readwrite("groups", &Change::groups);
// Space
py::class_<Space>(m, "Space")
.def(py::init<>())
.def_readwrite("geo", &Space::geometry)
.def_readwrite("particles", &Space::particles)
.def_readwrite("groups", &Space::groups)
// https://stackoverflow.com/questions/65812046/disambiguate-non-const-and-const-access-methods-pybind11
// .def("findMolecules", &Space::findMolecules)
.def("from_dict", [](Space& spc, py::dict dict) { from_json(dict2json(dict), spc); });
// Hamiltonian
py::class_<Thamiltonian>(m, "Hamiltonian")
.def(py::init<Space &, const json &>())
.def(py::init([](Space &spc, py::list list) {
json j = list2json(list);
return std::unique_ptr<Thamiltonian>(new Thamiltonian(spc, j));
}))
.def("init", &Thamiltonian::init)
.def("energy", &Thamiltonian::energy);
// TranslationalEntropy
py::class_<TranslationalEntropy>(m, "TranslationalEntropy")
.def(py::init<Space &, Space &>())
.def("energy", &TranslationalEntropy::energy);
// MCSimulation
py::class_<Tmcsimulation>(m, "MetropolisMonteCarlo")
.def(py::init([](py::dict dict) {
json j = dict2json(dict);
return std::unique_ptr<Tmcsimulation>(new Tmcsimulation(j));
}))
.def(py::init([](py::dict dict) {
json j = dict2json(dict);
return std::unique_ptr<Tmcsimulation>(new Tmcsimulation(j));
}));
// Analysisbase
py::class_<Analysis::Analysisbase>(m, "Analysisbase")
.def_readonly("name", &Analysis::Analysisbase::name)
.def_readwrite("cite", &Analysis::Analysisbase::cite)
.def("to_disk", &Analysis::Analysisbase::to_disk)
.def("sample", &Analysis::Analysisbase::sample)
.def("to_dict", [](Analysis::Analysisbase &self) {
json j;
Analysis::to_json(j, self);
return json2dict(j);
});
py::bind_vector<std::vector<std::shared_ptr<Analysis::Analysisbase>>>(m, "AnalysisVector");
// CombinedAnalysis
py::class_<Analysis::CombinedAnalysis>(m, "Analysis")
.def(py::init([](Space &spc, Thamiltonian &pot, py::list list) {
json j = list2json(list);
return std::unique_ptr<Analysis::CombinedAnalysis>(new Analysis::CombinedAnalysis(j, spc, pot));
}))
.def_readwrite("vector", &Analysis::CombinedAnalysis::vec)
.def("to_dict",
[](Analysis::CombinedAnalysis &self) {
json j;
Faunus::to_json(j, self);
return json2dict(j);
})
.def("sample", &Analysis::CombinedAnalysis::sample);
}
<commit_msg>Fix regions in pyfaunus<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
#include <pybind11/operators.h>
#include <pybind11/functional.h>
#include <core.h>
#include <space.h>
#include <move.h>
#include <analysis.h>
#include <potentials.h>
#include <regions.h>
#include <montecarlo.h>
#include <energy.h>
namespace py = pybind11;
using namespace Faunus;
typedef typename Space::GroupType Tgroup;
typedef Energy::Hamiltonian Thamiltonian;
typedef MetropolisMonteCarlo Tmcsimulation;
inline json dict2json(py::dict dict) {
py::object dumps = py::module::import("json").attr("dumps");
return json::parse( dumps(dict).cast<std::string>() );
} // python dict --> c++ json
inline json list2json(py::list list) {
py::object dumps = py::module::import("json").attr("dumps");
return json::parse(dumps(list).cast<std::string>());
} // python list --> c++ json
inline py::dict json2dict(const json &j) {
py::object loads = py::module::import("json").attr("loads");
return loads( j.dump() ) ;
}
template<class T>
std::unique_ptr<T> from_dict(py::dict dict) {
auto ptr = new T();
*ptr = dict2json(dict);
return std::unique_ptr<T>(ptr);
} // convert py::dict to T through Faunus::json
PYBIND11_MODULE(pyfaunus, m)
{
using namespace pybind11::literals;
// json
py::class_<json>(m, "json")
.def(py::init( [](std::string arg) {
return std::unique_ptr<json>(new json(json::parse(arg)));
} ) )
.def(py::init([](py::dict dict) {
py::object dumps = py::module::import("json").attr("dumps");
std::string s = dumps(dict).cast<std::string>();
return std::unique_ptr<json>(new json(json::parse(s)));
} ) );
// Random
py::class_<Random>(m, "Random")
.def(py::init<>())
.def("__call__", [](Random &self){ return self(); } ); // function operator
m.attr("random") = &Faunus::random; // global instance
// Geometries
py::enum_<Geometry::VolumeMethod>(m, "VolumeMethod")
.value("ISOTROPIC", Geometry::VolumeMethod::ISOTROPIC)
.value("ISOCHORIC", Geometry::VolumeMethod::ISOCHORIC)
.value("XY", Geometry::VolumeMethod::XY)
.value("Z", Geometry::VolumeMethod::Z)
.export_values();
py::class_<Geometry::GeometryBase>(m, "Geometrybase")
.def("getVolume", &Geometry::GeometryBase::getVolume, "Get container volume", "dim"_a = 3)
.def("setVolume", &Geometry::GeometryBase::setVolume, "Set container volume", "volume"_a,
"method"_a = Geometry::VolumeMethod::ISOTROPIC)
.def("collision", &Geometry::GeometryBase::collision, "pos"_a, "Checks if point is inside container")
.def("getLength", &Geometry::GeometryBase::getLength, "Get cuboid sidelengths")
.def("vdist", &Geometry::GeometryBase::vdist, "Minimum vector distance, a-b", "a"_a, "b"_a)
.def("randompos",
[](Geometry::GeometryBase& g, Random& rnd) {
Point pos;
g.randompos(pos, rnd);
return pos;
})
.def(
"boundary",
[](Geometry::GeometryBase& g, const Point& pos) {
Point a = pos; // we cannot modify `pos` directly
g.boundary(a); // as in c++
return a;
},
R"(
Apply periodic boundaries
If applicable for the geometry type, this will apply
periodic boundaries to a coordinate.
Args:
pos (array): coordinate
Returns:
array: position with wrapped coordinate
)");
py::class_<Geometry::Chameleon, Geometry::GeometryBase>(m, "Chameleon")
.def(py::init<>())
.def(py::init([](py::dict dict) {
auto ptr = std::make_unique<Geometry::Chameleon>();
Faunus::Geometry::from_json(dict2json(dict), *ptr);
return ptr;
}))
.def("sqdist", &Geometry::Chameleon::sqdist, "Squared minimum distance, |a-b|^2", "a"_a, "b"_a);
// Particle properties
py::class_<Charge>(m, "Charge")
.def(py::init<>())
.def_readwrite("charge", &Charge::charge, "Particle charge (monopole)");
py::class_<Particle>(m, "Particle")
.def(py::init<>())
.def("traits", &Particle::traits)
.def_readwrite("id", &Particle::id, "Particle ID")
.def_readwrite("pos", &Particle::pos, "Particle position")
.def_readwrite("charge", &Particle::charge, "Particle charge (monopole)");
// Particle vector and it's iterator
py::class_<ParticleVector::iterator>(m, "ParticleVectorIterator")
.def("__add__", [](ParticleVector::iterator it, int i) { return it + i; })
.def("__sub__", [](ParticleVector::iterator it, int i) { return it - i; });
auto _pvec = py::bind_vector<ParticleVector>(m, "ParticleVector");
_pvec.def("positions", [](ParticleVector& p) { return asEigenMatrix(p.begin(), p.end(), &Particle::pos); })
.def("charges", [](ParticleVector& p) { return asEigenVector(p.begin(), p.end(), &Particle::charge); })
.def("begin", [](ParticleVector& p) { return p.begin(); })
.def("end", [](ParticleVector& p) { return p.end(); });
// Group
py::class_<Tgroup>(m, "Group")
.def(py::init<MoleculeData::index_type, ParticleVector::iterator, ParticleVector::iterator>())
.def_readwrite("groups", &Tgroup::id, "Molecule id")
.def_readwrite("id", &Tgroup::id, "Molecule id")
.def_readwrite("cm", &Tgroup::mass_center, "Center of mass")
.def("__len__", [](Tgroup& self) { return self.size(); })
.def(
"__iter__", [](Tgroup& v) { return py::make_iterator(v.begin(), v.end()); }, py::keep_alive<0, 1>())
.def("isAtomic", &Tgroup::isAtomic)
.def("isMolecular", &Tgroup::isMolecular)
.def("traits", &Tgroup::traits)
.def("contains", &Tgroup::contains)
.def("capacity", &Tgroup::capacity)
.def("deactivate", &Tgroup::deactivate)
.def("activate", &Tgroup::activate)
.def("begin", (ParticleVector::iterator & (Tgroup::*)()) & Tgroup::begin)
.def("end", (ParticleVector::iterator & (Tgroup::*)()) & Tgroup::end);
py::bind_vector<std::vector<Tgroup>>(m, "GroupVector");
// Region
py::enum_<Region::RegionType>(m, "RegionType")
.value("WITHIN_PARTICLE", Region::RegionType::WITHIN_PARTICLE)
.value("WITHIN_MOLID", Region::RegionType::WITHIN_MOLID)
.value("NONE", Region::RegionType::INVALID)
.export_values();
py::class_<Region::RegionBase>(m, "RegionBase")
.def_readonly("type", &Region::RegionBase::type)
.def("volume", &Region::RegionBase::isInside)
.def("isInside", &Region::RegionBase::isInside);
// AtomData
py::class_<AtomData>(m, "AtomData")
.def(py::init<>())
.def_property(
"eps", [](const AtomData& a) { return a.interaction.at("eps"); },
[](AtomData& a, double val) { a.interaction.at("eps") = val; })
.def_property(
"sigma", [](const AtomData& a) { return a.interaction.at("sigma"); },
[](AtomData& a, double val) { a.interaction.at("sigma") = val; })
.def_readwrite("name", &AtomData::name)
.def_readwrite("activity", &AtomData::activity, "Activity = chemical potential in log scale (mol/l)")
.def("id", (const AtomData::index_type& (AtomData::*)() const) &
AtomData::id); // explicit signature due to overload in c++
auto _atomdatavec = py::bind_vector<std::vector<AtomData>>(m, "AtomDataVector");
_atomdatavec
.def("from_list", [](std::vector<AtomData> &a, py::list list) {
Faunus::from_json(list2json(list), a); } );
m.attr("atoms") = &Faunus::atoms; // global instance
// Temperature and other globals etc.
m.def("getTemperature", []() { return pc::temperature; } );
m.def("setTemperature", [](double T) { pc::temperature = T; } );
// --------- Pair Potentials ---------
// Base
py::class_<Potential::PairPotentialBase>(m, "PairPotentialBase")
.def_readwrite("name", &Potential::PairPotentialBase::name)
.def_readwrite("cite", &Potential::PairPotentialBase::cite)
.def_readwrite("isotropic", &Potential::PairPotentialBase::isotropic)
.def_readwrite("selfEnergy", &Potential::PairPotentialBase::selfEnergy)
.def("force", &Potential::PairPotentialBase::force)
.def("energy", [](Potential::PairPotentialBase &pot, const Particle &a, const Particle &b, double r2,
const Point &r) { return pot(a, b, r2, r); });
// Potentials::FunctorPotential
py::class_<Potential::FunctorPotential, Potential::PairPotentialBase>(m, "FunctorPotential")
.def(py::init([](py::dict dict) { return from_dict<Potential::FunctorPotential>(dict); }));
// Change::Data
py::class_<Change::GroupChange>(m, "ChangeData")
.def(py::init<>())
.def_readwrite("dNatomic", &Change::GroupChange::dNatomic)
.def_readwrite("dNswap", &Change::GroupChange::dNswap)
.def_readwrite("index", &Change::GroupChange::group_index)
.def_readwrite("internal", &Change::GroupChange::internal)
.def_readwrite("all", &Change::GroupChange::all)
.def_readwrite("atoms", &Change::GroupChange::relative_atom_indices);
py::bind_vector<std::vector<Change::GroupChange>>(m, "ChangeDataVec");
// Change
py::class_<Change>(m, "Change")
.def(py::init<>())
.def_readwrite("everything", &Change::everything)
.def_readwrite("volume_change", &Change::volume_change)
.def_readwrite("matter_change", &Change::matter_change)
.def_readwrite("groups", &Change::groups);
// Space
py::class_<Space>(m, "Space")
.def(py::init<>())
.def_readwrite("geo", &Space::geometry)
.def_readwrite("particles", &Space::particles)
.def_readwrite("groups", &Space::groups)
// https://stackoverflow.com/questions/65812046/disambiguate-non-const-and-const-access-methods-pybind11
// .def("findMolecules", &Space::findMolecules)
.def("from_dict", [](Space& spc, py::dict dict) { from_json(dict2json(dict), spc); });
// Hamiltonian
py::class_<Thamiltonian>(m, "Hamiltonian")
.def(py::init<Space &, const json &>())
.def(py::init([](Space &spc, py::list list) {
json j = list2json(list);
return std::unique_ptr<Thamiltonian>(new Thamiltonian(spc, j));
}))
.def("init", &Thamiltonian::init)
.def("energy", &Thamiltonian::energy);
// TranslationalEntropy
py::class_<TranslationalEntropy>(m, "TranslationalEntropy")
.def(py::init<Space &, Space &>())
.def("energy", &TranslationalEntropy::energy);
// MCSimulation
py::class_<Tmcsimulation>(m, "MetropolisMonteCarlo")
.def(py::init([](py::dict dict) {
json j = dict2json(dict);
return std::unique_ptr<Tmcsimulation>(new Tmcsimulation(j));
}))
.def(py::init([](py::dict dict) {
json j = dict2json(dict);
return std::unique_ptr<Tmcsimulation>(new Tmcsimulation(j));
}));
// Analysisbase
py::class_<Analysis::Analysisbase>(m, "Analysisbase")
.def_readonly("name", &Analysis::Analysisbase::name)
.def_readwrite("cite", &Analysis::Analysisbase::cite)
.def("to_disk", &Analysis::Analysisbase::to_disk)
.def("sample", &Analysis::Analysisbase::sample)
.def("to_dict", [](Analysis::Analysisbase &self) {
json j;
Analysis::to_json(j, self);
return json2dict(j);
});
py::bind_vector<std::vector<std::shared_ptr<Analysis::Analysisbase>>>(m, "AnalysisVector");
// CombinedAnalysis
py::class_<Analysis::CombinedAnalysis>(m, "Analysis")
.def(py::init([](Space &spc, Thamiltonian &pot, py::list list) {
json j = list2json(list);
return std::unique_ptr<Analysis::CombinedAnalysis>(new Analysis::CombinedAnalysis(j, spc, pot));
}))
.def_readwrite("vector", &Analysis::CombinedAnalysis::vec)
.def("to_dict",
[](Analysis::CombinedAnalysis &self) {
json j;
Faunus::to_json(j, self);
return json2dict(j);
})
.def("sample", &Analysis::CombinedAnalysis::sample);
}
<|endoftext|>
|
<commit_before>/*
Resembla
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RESEMBLA_RERANKER_HPP
#define RESEMBLA_RERANKER_HPP
#include <vector>
#include <algorithm>
#include <string>
#ifdef DEBUG
#include "string_util.hpp"
#include <iostream>
#endif
namespace resembla {
template<typename Original>
class Reranker
{
public:
using output_type = std::pair<Original, double>;
template<
typename Iterator,
typename ScoreFunction
>
std::vector<output_type> rerank(
const typename std::iterator_traits<Iterator>::value_type& target,
const Iterator begin,
const Iterator end,
const ScoreFunction& score_func,
double threshold = 0.0,
size_t max_output = 0
) const
{
#ifdef DEBUG
std::cerr << "DEBUG: " << "target=" << cast_string<std::string>(target.first) << std::endl;
std::cerr << "DEBUG: " << "===========before reranking=============" << std::endl;
for(auto i = begin; i != end; ++i){
std::cerr << "DEBUG: " << cast_string<std::string>(i->first) << std::endl;
}
std::cerr << "DEBUG: " << "start reranking: threshold==" << threshold << ", max_output=" << max_output << std::endl;
#endif
std::vector<output_type> result;
for(auto i = begin; i != end; ++i){
auto score = score_func(target.second, i->second);
if(threshold == 0.0 || score >= threshold){
result.push_back(std::make_pair(i->first, score));
}
}
std::sort(std::begin(result), std::end(result), Sorter());
if(max_output != 0 && result.size() > max_output){
result.erase(std::begin(result) + max_output, std::end(result));
}
#ifdef DEBUG
std::cerr << "DEBUG: " << "===========after reranking=============" << std::endl;
for(auto i = std::begin(result); i != std::end(result); ++i){
std::cerr << "DEBUG: " << "text=" << cast_string<std::string>(i->first) << ", score=" << i->second << std::endl;
}
#endif
return result;
}
protected:
struct Sorter
{
bool operator()(const output_type& a, const output_type& b) const
{
return a.second > b.second;
}
};
};
}
#endif
<commit_msg>use partial_sort<commit_after>/*
Resembla
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RESEMBLA_RERANKER_HPP
#define RESEMBLA_RERANKER_HPP
#include <vector>
#include <algorithm>
#ifdef DEBUG
#include <string>
#include <iostream>
#include "string_util.hpp"
#endif
namespace resembla {
template<typename Original>
class Reranker
{
public:
using output_type = std::pair<Original, double>;
template<typename Iterator, typename ScoreFunction>
std::vector<output_type> rerank(
const typename std::iterator_traits<Iterator>::value_type& target,
const Iterator begin, const Iterator end,
const ScoreFunction& score_func,
double threshold = 0.0, size_t max_output = 0
) const
{
#ifdef DEBUG
std::cerr << "DEBUG: " << "target=" << cast_string<std::string>(target.first) << std::endl;
std::cerr << "DEBUG: " << "===========before reranking=============" << std::endl;
for(auto i = begin; i != end; ++i){
std::cerr << "DEBUG: " << cast_string<std::string>(i->first) << std::endl;
}
std::cerr << "DEBUG: " << "start reranking: threshold==" << threshold << ", max_output=" << max_output << std::endl;
#endif
std::vector<output_type> result;
for(auto i = begin; i != end; ++i){
auto score = score_func(target.second, i->second);
if(threshold == 0.0 || score >= threshold){
result.push_back(std::make_pair(i->first, score));
}
}
if(max_output != 0 && result.size() > max_output){
std::partial_sort(result.begin(), result.begin() + max_output, result.end(), Sorter());
result.erase(std::begin(result) + max_output, std::end(result));
}
else{
std::sort(result.begin(), result.end(), Sorter());
}
#ifdef DEBUG
std::cerr << "DEBUG: " << "===========after reranking=============" << std::endl;
for(const auto& r: result){
std::cerr << "DEBUG: " << "text=" << cast_string<std::string>(r.first) << ", score=" << r.second << std::endl;
}
#endif
return result;
}
protected:
struct Sorter
{
bool operator()(const output_type& a, const output_type& b) const
{
return a.second > b.second;
}
};
};
}
#endif
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <chrono>
#include <cstdlib>
#include <string>
#include <thread>
#include "ur_modern_driver/log.h"
#include "ur_modern_driver/pipeline.h"
#include "ur_modern_driver/ros/action_server.h"
#include "ur_modern_driver/ros/controller.h"
#include "ur_modern_driver/ros/io_service.h"
#include "ur_modern_driver/ros/mb_publisher.h"
#include "ur_modern_driver/ros/rt_publisher.h"
#include "ur_modern_driver/ros/service_stopper.h"
#include "ur_modern_driver/ros/trajectory_follower.h"
#include "ur_modern_driver/ur/commander.h"
#include "ur_modern_driver/ur/factory.h"
#include "ur_modern_driver/ur/messages.h"
#include "ur_modern_driver/ur/parser.h"
#include "ur_modern_driver/ur/producer.h"
#include "ur_modern_driver/ur/rt_state.h"
#include "ur_modern_driver/ur/state.h"
static const std::string IP_ADDR_ARG("~robot_ip_address");
static const std::string REVERSE_PORT_ARG("~reverse_port");
static const std::string ROS_CONTROL_ARG("~use_ros_control");
static const std::string MAX_VEL_CHANGE_ARG("~max_vel_change");
static const std::string PREFIX_ARG("~prefix");
static const std::string BASE_FRAME_ARG("~base_frame");
static const std::string TOOL_FRAME_ARG("~tool_frame");
static const std::string TCP_LINK_ARG("~tcp_link");
static const std::string JOINT_NAMES_PARAM("hardware_interface/joints");
static const std::vector<std::string> DEFAULT_JOINTS = { "shoulder_pan_joint", "shoulder_lift_joint", "elbow_joint",
"wrist_1_joint", "wrist_2_joint", "wrist_3_joint" };
static const int UR_SECONDARY_PORT = 30002;
static const int UR_RT_PORT = 30003;
struct ProgArgs
{
public:
std::string host;
std::string prefix;
std::string base_frame;
std::string tool_frame;
std::string tcp_link;
std::vector<std::string> joint_names;
double max_acceleration;
double max_velocity;
double max_vel_change;
int32_t reverse_port;
bool use_ros_control;
};
bool parse_args(ProgArgs &args)
{
if (!ros::param::get(IP_ADDR_ARG, args.host))
{
LOG_ERROR("robot_ip_address parameter must be set!");
return false;
}
ros::param::param(REVERSE_PORT_ARG, args.reverse_port, int32_t(50001));
ros::param::param(MAX_VEL_CHANGE_ARG, args.max_vel_change, 15.0); // rad/s
ros::param::param(MAX_VEL_CHANGE_ARG, args.max_velocity, 10.0);
ros::param::param(ROS_CONTROL_ARG, args.use_ros_control, false);
ros::param::param(PREFIX_ARG, args.prefix, std::string());
ros::param::param(BASE_FRAME_ARG, args.base_frame, args.prefix + "base_link");
ros::param::param(TOOL_FRAME_ARG, args.tool_frame, args.prefix + "tool0_controller");
ros::param::param(TCP_LINK_ARG, args.tcp_link, args.prefix + "ee_link");
ros::param::param(JOINT_NAMES_PARAM, args.joint_names, DEFAULT_JOINTS);
return true;
}
std::string getLocalIPAccessibleFromHost(std::string &host)
{
URStream stream(host, UR_RT_PORT);
return stream.connect() ? stream.getIP() : std::string();
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "ur_driver");
ProgArgs args;
if (!parse_args(args))
{
return EXIT_FAILURE;
}
//Add prefix to joint names
std::transform (args.joint_names.begin(), args.joint_names.end(), args.joint_names.begin(),
[&args](std::string name){return args.prefix + name;});
std::string local_ip(getLocalIPAccessibleFromHost(args.host));
URFactory factory(args.host);
vector<Service *> services;
// RT packets
auto rt_parser = factory.getRTParser();
URStream rt_stream(args.host, UR_RT_PORT);
URProducer<RTPacket> rt_prod(rt_stream, *rt_parser);
RTPublisher rt_pub(args.prefix, args.base_frame, args.tool_frame, args.use_ros_control);
auto rt_commander = factory.getCommander(rt_stream);
vector<IConsumer<RTPacket> *> rt_vec{ &rt_pub };
TrajectoryFollower traj_follower(*rt_commander, local_ip, args.reverse_port, factory.isVersion3());
ROSController *controller(nullptr);
ActionServer *action_server(nullptr);
if (args.use_ros_control)
{
LOG_INFO("ROS control enabled");
controller = new ROSController(*rt_commander, traj_follower, args.joint_names, args.max_vel_change, args.tcp_link);
rt_vec.push_back(controller);
services.push_back(controller);
}
else
{
LOG_INFO("ActionServer enabled");
action_server = new ActionServer(traj_follower, args.joint_names, args.max_velocity);
rt_vec.push_back(action_server);
services.push_back(action_server);
}
MultiConsumer<RTPacket> rt_cons(rt_vec);
Pipeline<RTPacket> rt_pl(rt_prod, rt_cons);
// Message packets
auto state_parser = factory.getStateParser();
URStream state_stream(args.host, UR_SECONDARY_PORT);
URProducer<StatePacket> state_prod(state_stream, *state_parser);
MBPublisher state_pub;
ServiceStopper service_stopper(services);
vector<IConsumer<StatePacket> *> state_vec{ &state_pub, &service_stopper };
MultiConsumer<StatePacket> state_cons(state_vec);
Pipeline<StatePacket> state_pl(state_prod, state_cons);
LOG_INFO("Starting main loop");
rt_pl.run();
state_pl.run();
auto state_commander = factory.getCommander(state_stream);
IOService io_service(*state_commander);
if (action_server)
action_server->start();
ros::spin();
LOG_INFO("ROS stopping, shutting down pipelines");
rt_pl.stop();
state_pl.stop();
if (controller)
delete controller;
LOG_INFO("Pipelines shutdown complete");
return EXIT_SUCCESS;
}
<commit_msg>Fixed default tcp_link value<commit_after>#include <ros/ros.h>
#include <chrono>
#include <cstdlib>
#include <string>
#include <thread>
#include "ur_modern_driver/log.h"
#include "ur_modern_driver/pipeline.h"
#include "ur_modern_driver/ros/action_server.h"
#include "ur_modern_driver/ros/controller.h"
#include "ur_modern_driver/ros/io_service.h"
#include "ur_modern_driver/ros/mb_publisher.h"
#include "ur_modern_driver/ros/rt_publisher.h"
#include "ur_modern_driver/ros/service_stopper.h"
#include "ur_modern_driver/ros/trajectory_follower.h"
#include "ur_modern_driver/ur/commander.h"
#include "ur_modern_driver/ur/factory.h"
#include "ur_modern_driver/ur/messages.h"
#include "ur_modern_driver/ur/parser.h"
#include "ur_modern_driver/ur/producer.h"
#include "ur_modern_driver/ur/rt_state.h"
#include "ur_modern_driver/ur/state.h"
static const std::string IP_ADDR_ARG("~robot_ip_address");
static const std::string REVERSE_PORT_ARG("~reverse_port");
static const std::string ROS_CONTROL_ARG("~use_ros_control");
static const std::string MAX_VEL_CHANGE_ARG("~max_vel_change");
static const std::string PREFIX_ARG("~prefix");
static const std::string BASE_FRAME_ARG("~base_frame");
static const std::string TOOL_FRAME_ARG("~tool_frame");
static const std::string TCP_LINK_ARG("~tcp_link");
static const std::string JOINT_NAMES_PARAM("hardware_interface/joints");
static const std::vector<std::string> DEFAULT_JOINTS = { "shoulder_pan_joint", "shoulder_lift_joint", "elbow_joint",
"wrist_1_joint", "wrist_2_joint", "wrist_3_joint" };
static const int UR_SECONDARY_PORT = 30002;
static const int UR_RT_PORT = 30003;
struct ProgArgs
{
public:
std::string host;
std::string prefix;
std::string base_frame;
std::string tool_frame;
std::string tcp_link;
std::vector<std::string> joint_names;
double max_acceleration;
double max_velocity;
double max_vel_change;
int32_t reverse_port;
bool use_ros_control;
};
bool parse_args(ProgArgs &args)
{
if (!ros::param::get(IP_ADDR_ARG, args.host))
{
LOG_ERROR("robot_ip_address parameter must be set!");
return false;
}
ros::param::param(REVERSE_PORT_ARG, args.reverse_port, int32_t(50001));
ros::param::param(MAX_VEL_CHANGE_ARG, args.max_vel_change, 15.0); // rad/s
ros::param::param(MAX_VEL_CHANGE_ARG, args.max_velocity, 10.0);
ros::param::param(ROS_CONTROL_ARG, args.use_ros_control, false);
ros::param::param(PREFIX_ARG, args.prefix, std::string());
ros::param::param(BASE_FRAME_ARG, args.base_frame, args.prefix + "base_link");
ros::param::param(TOOL_FRAME_ARG, args.tool_frame, args.prefix + "tool0_controller");
ros::param::param(TCP_LINK_ARG, args.tcp_link, args.prefix + "tool0");
ros::param::param(JOINT_NAMES_PARAM, args.joint_names, DEFAULT_JOINTS);
return true;
}
std::string getLocalIPAccessibleFromHost(std::string &host)
{
URStream stream(host, UR_RT_PORT);
return stream.connect() ? stream.getIP() : std::string();
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "ur_driver");
ProgArgs args;
if (!parse_args(args))
{
return EXIT_FAILURE;
}
//Add prefix to joint names
std::transform (args.joint_names.begin(), args.joint_names.end(), args.joint_names.begin(),
[&args](std::string name){return args.prefix + name;});
std::string local_ip(getLocalIPAccessibleFromHost(args.host));
URFactory factory(args.host);
vector<Service *> services;
// RT packets
auto rt_parser = factory.getRTParser();
URStream rt_stream(args.host, UR_RT_PORT);
URProducer<RTPacket> rt_prod(rt_stream, *rt_parser);
RTPublisher rt_pub(args.prefix, args.base_frame, args.tool_frame, args.use_ros_control);
auto rt_commander = factory.getCommander(rt_stream);
vector<IConsumer<RTPacket> *> rt_vec{ &rt_pub };
TrajectoryFollower traj_follower(*rt_commander, local_ip, args.reverse_port, factory.isVersion3());
ROSController *controller(nullptr);
ActionServer *action_server(nullptr);
if (args.use_ros_control)
{
LOG_INFO("ROS control enabled");
controller = new ROSController(*rt_commander, traj_follower, args.joint_names, args.max_vel_change, args.tcp_link);
rt_vec.push_back(controller);
services.push_back(controller);
}
else
{
LOG_INFO("ActionServer enabled");
action_server = new ActionServer(traj_follower, args.joint_names, args.max_velocity);
rt_vec.push_back(action_server);
services.push_back(action_server);
}
MultiConsumer<RTPacket> rt_cons(rt_vec);
Pipeline<RTPacket> rt_pl(rt_prod, rt_cons);
// Message packets
auto state_parser = factory.getStateParser();
URStream state_stream(args.host, UR_SECONDARY_PORT);
URProducer<StatePacket> state_prod(state_stream, *state_parser);
MBPublisher state_pub;
ServiceStopper service_stopper(services);
vector<IConsumer<StatePacket> *> state_vec{ &state_pub, &service_stopper };
MultiConsumer<StatePacket> state_cons(state_vec);
Pipeline<StatePacket> state_pl(state_prod, state_cons);
LOG_INFO("Starting main loop");
rt_pl.run();
state_pl.run();
auto state_commander = factory.getCommander(state_stream);
IOService io_service(*state_commander);
if (action_server)
action_server->start();
ros::spin();
LOG_INFO("ROS stopping, shutting down pipelines");
rt_pl.stop();
state_pl.stop();
if (controller)
delete controller;
LOG_INFO("Pipelines shutdown complete");
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "cons_util.hh"
#include "env.hh"
#include "s_closure.hh"
#include "zs_error.hh"
SyntacticClosure::SyntacticClosure(Env* e, Lisp_ptr f, Lisp_ptr ex)
: env_(e), free_names_(f), expr_(ex){
for(auto i : f){
if(!identifierp(i)){
throw_zs_error(i, "syntactic closure: free-list has a non-identifier value");
}
}
}
SyntacticClosure::~SyntacticClosure() = default;
// checks recursively
bool identifierp(Lisp_ptr p){
if(p.tag() == Ptr_tag::symbol){
return true;
}else if(p.tag() == Ptr_tag::syntactic_closure){
return identifierp(p.get<SyntacticClosure*>()->expr());
}else{
return false;
}
}
bool identifier_eq(Env* ident1_env, Lisp_ptr ident1,
Env* ident2_env, Lisp_ptr ident2){
return eq_internal(ident1_env->find(ident1).first,
ident2_env->find(ident2).first);
}
<commit_msg>cleanup s_closure<commit_after>#include "cons_util.hh"
#include "env.hh"
#include "s_closure.hh"
#include "zs_error.hh"
SyntacticClosure::SyntacticClosure(Env* e, Lisp_ptr f, Lisp_ptr ex)
: env_(e), free_names_(f), expr_(ex){
for(auto i : f){
check_identifier_type(i);
}
}
SyntacticClosure::~SyntacticClosure() = default;
// checks recursively
bool identifierp(Lisp_ptr p){
if(p.tag() == Ptr_tag::symbol){
return true;
}else if(p.tag() == Ptr_tag::syntactic_closure){
return identifierp(p.get<SyntacticClosure*>()->expr());
}else{
return false;
}
}
bool identifier_eq(Env* ident1_env, Lisp_ptr ident1,
Env* ident2_env, Lisp_ptr ident2){
return eq_internal(ident1_env->find(ident1).first,
ident2_env->find(ident2).first);
}
<|endoftext|>
|
<commit_before>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _SRC_SIGNAL_P_HPP_
#define _SRC_SIGNAL_P_HPP_
#include <qitype/signal.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/recursive_mutex.hpp>
namespace qi {
typedef std::map<SignalBase::Link, SignalSubscriberPtr> SignalSubscriberMap;
class SignalBasePrivate
{
public:
bool disconnect(const SignalBase::Link& l);
bool reset();
public:
SignalBase::OnSubscribers onSubscribers;
SignalSubscriberMap subscriberMap;
std::string signature;
boost::recursive_mutex mutex;
MetaCallType defaultCallType;
};
}
#endif // _SRC_SIGNAL_P_HPP_
<commit_msg>Signal: Fix uninitialized variable.<commit_after>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _SRC_SIGNAL_P_HPP_
#define _SRC_SIGNAL_P_HPP_
#include <qitype/signal.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/recursive_mutex.hpp>
namespace qi {
typedef std::map<SignalBase::Link, SignalSubscriberPtr> SignalSubscriberMap;
class SignalBasePrivate
{
public:
SignalBasePrivate(): defaultCallType(MetaCallType_Auto) {}
bool disconnect(const SignalBase::Link& l);
bool reset();
public:
SignalBase::OnSubscribers onSubscribers;
SignalSubscriberMap subscriberMap;
std::string signature;
boost::recursive_mutex mutex;
MetaCallType defaultCallType;
};
}
#endif // _SRC_SIGNAL_P_HPP_
<|endoftext|>
|
<commit_before>#include <mapbox/geojsonvt/simplify.hpp>
#include <deque>
namespace mapbox {
namespace geojsonvt {
// calculate simplification data using optimized Douglas-Peucker algorithm
void Simplify::simplify(ProjectedPoints& points, double tolerance) {
const double sqTolerance = tolerance * tolerance;
const size_t len = points.size();
size_t first = 0;
size_t last = len - 1;
std::deque<std::pair<size_t,size_t>> stack;
double maxSqDist = 0;
double sqDist = 0;
size_t index = 0;
// always retain the endpoints (1 is the max value)
points[first].z = 1;
points[last].z = 1;
// avoid recursion by using a stack
while (last != 0u) {
maxSqDist = 0;
for (size_t i = (first + 1); i < last; ++i) {
sqDist = getSqSegDist(points[i], points[first], points[last]);
if (sqDist > maxSqDist) {
index = i;
maxSqDist = sqDist;
}
}
if (maxSqDist > sqTolerance) {
// save the point importance in squared pixels as a z coordinate
points[index].z = maxSqDist;
stack.emplace_back(first, index);
first = index;
} else {
if (!stack.empty()) {
auto const& p = stack.back();
first = p.first;
last = p.second;
stack.pop_back();
} else {
last = 0;
first = 0;
}
}
}
}
// square distance from a point to a segment
double
Simplify::getSqSegDist(const ProjectedPoint& p, const ProjectedPoint& a, const ProjectedPoint& b) {
double x = a.x;
double y = a.y;
double dx = b.x - a.x;
double dy = b.y - a.y;
if ((dx != 0.0) || (dy != 0.0)) {
const double t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = b.x;
y = b.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p.x - x;
dy = p.y - y;
return dx * dx + dy * dy;
}
} // namespace geojsonvt
} // namespace mapbox
<commit_msg>sprinkle syntactic sugar<commit_after>#include <mapbox/geojsonvt/simplify.hpp>
#include <deque>
namespace mapbox {
namespace geojsonvt {
// calculate simplification data using optimized Douglas-Peucker algorithm
void Simplify::simplify(ProjectedPoints& points, double tolerance) {
const double sqTolerance = tolerance * tolerance;
const size_t len = points.size();
size_t first = 0;
size_t last = len - 1;
std::deque<std::pair<size_t,size_t>> stack;
double maxSqDist = 0;
double sqDist = 0;
size_t index = 0;
// always retain the endpoints (1 is the max value)
points[first].z = 1;
points[last].z = 1;
// avoid recursion by using a stack
while (last != 0u) {
maxSqDist = 0;
for (size_t i = (first + 1); i < last; ++i) {
sqDist = getSqSegDist(points[i], points[first], points[last]);
if (sqDist > maxSqDist) {
index = i;
maxSqDist = sqDist;
}
}
if (maxSqDist > sqTolerance) {
// save the point importance in squared pixels as a z coordinate
points[index].z = maxSqDist;
stack.emplace_back(first, index);
first = index;
} else {
if (!stack.empty()) {
std::tie(first, last) = stack.back();
stack.pop_back();
} else {
last = 0;
first = 0;
}
}
}
}
// square distance from a point to a segment
double
Simplify::getSqSegDist(const ProjectedPoint& p, const ProjectedPoint& a, const ProjectedPoint& b) {
double x = a.x;
double y = a.y;
double dx = b.x - a.x;
double dy = b.y - a.y;
if ((dx != 0.0) || (dy != 0.0)) {
const double t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = b.x;
y = b.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p.x - x;
dy = p.y - y;
return dx * dx + dy * dy;
}
} // namespace geojsonvt
} // namespace mapbox
<|endoftext|>
|
<commit_before>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
*/
#ifndef LUWRA_COMMON_H_
#define LUWRA_COMMON_H_
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
// Check for proper Lua version
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 || LUA_VERSION_NUM >= 600
#error Luwra has not been tested against your installed version of Lua
#endif
// Namespaces
#define LUWRA_NS_BEGIN namespace luwra {
#define LUWRA_NS_END }
// Version MAJOR.MINOR.PATCH
#define LUWRA_VERSION_MAJOR 0
#define LUWRA_VERSION_MINOR 2
#define LUWRA_VERSION_PATCH 0
#endif
<commit_msg>Bump version<commit_after>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
*/
#ifndef LUWRA_COMMON_H_
#define LUWRA_COMMON_H_
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
// Check for proper Lua version
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 || LUA_VERSION_NUM >= 600
#error Luwra has not been tested against your installed version of Lua
#endif
// Namespaces
#define LUWRA_NS_BEGIN namespace luwra {
#define LUWRA_NS_END }
// Version MAJOR.MINOR.PATCH
#define LUWRA_VERSION_MAJOR 0
#define LUWRA_VERSION_MINOR 3
#define LUWRA_VERSION_PATCH 0
#endif
<|endoftext|>
|
<commit_before>#include "momentum.h"
#include <boost/unordered_map.hpp>
#include <iostream>
#include <semiOrderedMap.cpp>
namespace bts
{
#define MAX_MOMENTUM_NONCE (1<<26)
#define SEARCH_SPACE_BITS 50
#define BIRTHDAYS_PER_HASH 8
std::vector< std::pair<uint32_t,uint32_t> > momentum_search( uint256 midHash )
{
semiOrderedMap somap;
somap.allocate(4);
std::vector< std::pair<uint32_t,uint32_t> > results;
char hash_tmp[sizeof(midHash)+4];
memcpy((char*)&hash_tmp[4], (char*)&midHash, sizeof(midHash) );
uint32_t* index = (uint32_t*)hash_tmp;
for( uint32_t i = 0; i < MAX_MOMENTUM_NONCE; )
{
if(i%1048576==0){
boost::this_thread::interruption_point();
}
*index = i;
uint64_t result_hash[8];
SHA512((unsigned char*)hash_tmp, sizeof(hash_tmp), (unsigned char*)result_hash);
for( uint32_t x = 0; x < 8; ++x )
{
uint64_t birthday = result_hash[x] >> (64-SEARCH_SPACE_BITS);
uint32_t nonce = i+x;
//boost::unordered_map<uint64_t,uint32_t>::const_iterator itr = found.find( birthday );
uint64_t foundMatch=somap.checkAdd( birthday, nonce );
if( foundMatch != 0 ){
results.push_back( std::make_pair( foundMatch, nonce ) );
}
}
i += BIRTHDAYS_PER_HASH;
}
//for( auto itr = results.begin(); itr != results.end(); ++itr )
//{
// assert( momentum_verify( midHash, itr->first, itr->second ) );
// }
//somap.destroy();
return results;
}
uint64_t getBirthdayHash(const uint256& midHash, uint32_t a)
{
uint32_t index = a - (a%8);
char hash_tmp[sizeof(midHash)+4];
// std::cerr<<"midHash size:" <<sizeof(midHash)<<"\n";
memcpy(&hash_tmp[4], (char*)&midHash, sizeof(midHash) );
memcpy(&hash_tmp[0], (char*)&index, sizeof(index) );
uint64_t result_hash[8];
// for( uint32_t i = 0; i < sizeof(hash_tmp); ++i )
// {
// std::cerr<<" "<<uint16_t((((unsigned char*)hash_tmp)[i]));
// }
// std::cerr<<"\n";
SHA512((unsigned char*)hash_tmp, sizeof(hash_tmp), (unsigned char*)&result_hash);
// std::cerr<<"result_hash "<<a<<" "<<a%8<<" --- ";
// for( uint32_t i = 0; i < 8; ++i ) std::cerr<<result_hash[i]<<" ";
// std::cerr<<"\n";
uint64_t r = result_hash[a%BIRTHDAYS_PER_HASH]>>(64-SEARCH_SPACE_BITS);
// std::cerr<<"bdayresult: "<<r<<"\n";
return r;
}
bool momentum_verify( uint256 head, uint32_t a, uint32_t b ){
// std::cerr<<"verify "<<a<<" and "<<b<<" mid: "<<head.ToString()<<"\n";
// std::cerr<<" "<<getBirthdayHash(head,a)<<" "<<getBirthdayHash(head,b)<<"\n";
if( a == b ) return false;
if( a > MAX_MOMENTUM_NONCE ) return false;
if( b > MAX_MOMENTUM_NONCE ) return false;
bool r = (getBirthdayHash(head,a) == getBirthdayHash(head,b));
// std::cerr<< "####### Verified "<<int(r)<<"\n";
return r;
}
}
<commit_msg>Initial Commit<commit_after>#include "momentum.h"
#include <boost/unordered_map.hpp>
#include <iostream>
namespace bts
{
#define MAX_MOMENTUM_NONCE (1<<26)
#define SEARCH_SPACE_BITS 50
#define BIRTHDAYS_PER_HASH 8
std::vector< std::pair<uint32_t, uint32_t> > momentum_search(uint256 midHash)
{
std::vector< std::pair<uint32_t, uint32_t> > results;
char hash_tmp[sizeof(midHash) + 4];
memcpy((char *)&hash_tmp[4], (char *)&midHash, sizeof(midHash));
uint32_t *index = (uint32_t *)hash_tmp;
bool found_hit = false;
// X
uint32_t turtle_nonce = 0;
uint32_t turtle_offset = 0;
uint64_t turtle[8];
// X'
uint32_t hare_nonce = 0;
uint32_t hare_offset = 0;
uint64_t hare[8];
// Defining X_0
*index = 0;
uint64_t result_hash[8];
SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)result_hash);
turtle = result_hash;
hare = result_hash;
// Dig for a hit.
// We can optimize out the backtrack step
// because we're keeping track of our nonces.
for(uint32_t i = 0; i < (1<<(SEARCH_SPACE_BITS/2) + 1); ++i) {
// TURTLE
// X = H(X)
++turtle_offset;
if (turtle_offset >= BIRTHDAYS_PER_HASH) {
turtle_offset = turtle_offset % BIRTHDAYS_PER_HASH;
turtle_nonce = (turtle_nonce + BIRTHDAYS_PER_HASH) % MAX_MOMENTUM_NONCE;
*index = turtle_nonce;
SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)result_hash);
turtle = result_hash;
}
// HARE
// X' = H( H(X) )
hare_offset += 2;
if (hare_offset >= BIRTHDAYS_PER_HASH) {
hare_offset = hare_offset % BIRTHDAYS_PER_HASH;
hare_nonce = (hare_nonce + BIRTHDAYS_PER_HASH) % MAX_MOMENTUM_NONCE;
*index = hare_nonce;
SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)result_hash);
hare = result_hash;
}
// Found a collision!
if (turtle[turtle_offset] >> (64 - SEARCH_SPACE_BITS) == hare[hare_offset] >> (64 - SEARCH_SPACE_BITS) {
fount_hit = true;
break;
}
}
// If we stopped due to running out of entries, return the empty list
if (!found_hit) {
std::cerr << "No collision found.\n";
return results;
}
std::cerr << "Collision found!\n";
results.push_back( std::make_pair(turtle_nonce + turtle_offset, hare_nonce + hare_offset) );
return results;
}
uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a)
{
uint32_t index = a - (a % 8);
char hash_tmp[sizeof(midHash) + 4];
memcpy(&hash_tmp[4], (char *)&midHash, sizeof(midHash));
memcpy(&hash_tmp[0], (char *)&index, sizeof(index));
uint64_t result_hash[8];
SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)&result_hash);
uint64_t r = result_hash[a % BIRTHDAYS_PER_HASH] >> (64 - SEARCH_SPACE_BITS);
return r;
}
bool momentum_verify(uint256 head, uint32_t a, uint32_t b)
{
if(a == b) {
return false;
}
if(a > MAX_MOMENTUM_NONCE) {
return false;
}
if(b > MAX_MOMENTUM_NONCE) {
return false;
}
bool r = (getBirthdayHash(head, a) == getBirthdayHash(head, b));
return r;
}
}
<|endoftext|>
|
<commit_before>#include <os>
#include <net/inet.hpp>
#include <net/util.hpp>
#include <stdlib.h>
/*
uint16_t net::checksum(uint16_t* buf, uint32_t len)
{
union sum
{
uint32_t whole;
uint16_t part[2];
} sum32{0};
// Iterate in short int steps.
for (uint16_t* i = buf; i < buf + len / 2; i++){
sum32.whole += *i;
}
// odd-length case
if (len & 1)
{
//printf("odd case\n");
sum32.whole += ((uint8_t*) buf)[len-1];
}
return ~(sum32.part[0]+sum32.part[1]);
}
*/
/**
* http://www.microhowto.info/howto/calculate_an_internet_protocol_checksum_in_c.html
* by Graham Shaw, some rights reserved.
**/
uint16_t net::checksum(void* vdata, size_t length)
{
// Cast the data pointer to one that can be indexed.
char* data=(char*)vdata;
// Initialise the accumulator.
uint64_t acc=0xffff;
// Handle any partial block at the start of the data.
unsigned int offset=((uintptr_t)data)&3;
if (offset) {
size_t count=4-offset;
if (count>length) count=length;
uint32_t word=0;
memcpy(offset+(char*)&word,data,count);
acc+=ntohl(word);
data+=count;
length-=count;
}
// Handle any complete 32-bit blocks.
char* data_end=data+(length&~3);
while (data!=data_end) {
uint32_t word;
memcpy(&word,data,4);
acc+=ntohl(word);
data+=4;
}
length&=3;
// Handle any partial block at the end of the data.
if (length) {
uint32_t word=0;
memcpy(&word,data,length);
acc+=ntohl(word);
}
// Handle deferred carries.
acc=(acc&0xffffffff)+(acc>>32);
while (acc>>16) {
acc=(acc&0xffff)+(acc>>16);
}
// If the data began at an odd byte address
// then reverse the byte order to compensate.
if (offset&1) {
acc=((acc&0xff00)>>8)|((acc&0x00ff)<<8);
}
// Return the checksum in network byte order.
return htons(~acc);
}
<commit_msg>Reverted to old checksum. It's faster, see #189<commit_after>#include <os>
#include <net/inet.hpp>
#include <net/util.hpp>
#include <stdlib.h>
// Should be pretty much like the example in RFC 1071, but using a uinon for readability
uint16_t net::checksum(void* data, size_t len)
{
uint16_t* buf = (uint16_t*)data;
union sum
{
uint32_t whole;
uint16_t part[2];
} sum32{0};
// Iterate in short int steps.
for (uint16_t* i = buf; i < buf + len / 2; i++)
sum32.whole += *i;
// odd-length case
if (len & 1)
sum32.whole += ((uint8_t*) buf)[len-1];
return ~(sum32.part[0]+sum32.part[1]);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: dsselect.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2004-11-09 12:32:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBAUI_ODBC_CONFIG_HXX_
#include "odbcconfig.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HRC_
#include "dsselect.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif
#if defined( WIN ) || defined( WNT )
#define HWND void*
#define HMENU void*
// was unable to include windows.h, that's why this direct define
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_
#include <com/sun/star/sdbcx/XCreateCatalog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::comphelper;
//==================================================================
ODatasourceSelectDialog::ODatasourceSelectDialog(Window* _pParent, const StringBag& _rDatasources, DATASOURCE_TYPE _eType,SfxItemSet* _pOutputSet)
:ModalDialog(_pParent, ModuleRes(DLG_DATASOURCE_SELECTION))
,m_aDescription (this, ResId(FT_DESCRIPTION))
,m_aDatasource (this, ResId(LB_DATASOURCE))
,m_aOk (this, ResId(PB_OK))
,m_aCancel (this, ResId(PB_CANCEL))
,m_aHelp (this, ResId(PB_HELP))
,m_aManageDatasources (this, ResId(PB_MANAGE))
,m_aCreateAdabasDB (this, ResId(PB_CREATE))
,m_pOutputSet(_pOutputSet)
{
if (DST_ADABAS == _eType)
{ // set a new title (indicating that we're browsing local data sources only)
SetText(ResId(STR_LOCAL_DATASOURCES));
m_aDescription.SetText(ResId(STR_DESCRIPTION2));
m_aCreateAdabasDB.Show();
m_aCreateAdabasDB.SetClickHdl(LINK(this,ODatasourceSelectDialog,CreateDBClickHdl));
// resize the dialog a little bit, 'cause Adabas data source names are usually somewhat shorter
// than ODBC ones are
// shrink the listbox
Size aOldSize = m_aDatasource.GetSizePixel();
Size aNewSize(3 * aOldSize.Width() / 4, aOldSize.Height());
m_aDatasource.SetSizePixel(aNewSize);
sal_Int32 nLostPixels = aOldSize.Width() - aNewSize.Width();
// shrink the fixed text
aOldSize = m_aDescription.GetSizePixel();
m_aDescription.SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
// move the buttons
PushButton* pButtons[] = { &m_aOk, &m_aCancel, &m_aHelp ,&m_aCreateAdabasDB};
for (sal_Int32 i=0; i<sizeof(pButtons)/sizeof(pButtons[0]); ++i)
{
Point aOldPos = pButtons[i]->GetPosPixel();
pButtons[i]->SetPosPixel(Point(aOldPos.X() - nLostPixels, aOldPos.Y()));
}
// resize the dialog itself
aOldSize = GetSizePixel();
SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
}
fillListBox(_rDatasources);
// allow ODBC datasource managenment
if ( DST_ODBC == _eType || DST_MYSQL_ODBC == _eType )
{
m_aManageDatasources.Show();
m_aManageDatasources.Enable();
m_aManageDatasources.SetClickHdl(LINK(this,ODatasourceSelectDialog,ManageClickHdl));
}
m_aDatasource.SetDoubleClickHdl(LINK(this,ODatasourceSelectDialog,ListDblClickHdl));
FreeResource();
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ListDblClickHdl, ListBox *, pListBox )
{
if (pListBox->GetSelectEntryCount())
EndDialog(RET_OK);
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, CreateDBClickHdl, PushButton*, pButton )
{
try
{
OSL_ENSURE(m_pOutputSet,"No itemset given!");
Reference< ::com::sun::star::lang::XMultiServiceFactory > xORB = ::comphelper::getProcessServiceFactory();
Reference<XCreateCatalog> xCatalog(xORB->createInstance(SERVICE_EXTENDED_ADABAS_DRIVER),UNO_QUERY);
if ( xCatalog.is() && m_pOutputSet )
{
Sequence< Any > aArgs(2);
aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("CreateCatalog"), 0,makeAny(xCatalog) , PropertyState_DIRECT_VALUE);
aArgs[1] <<= PropertyValue(PROPERTY_PARENTWINDOW, 0, makeAny(VCLUnoHelper::GetInterface(this)), PropertyState_DIRECT_VALUE);
Reference< XExecutableDialog > xDialog(
xORB->createInstanceWithArguments(SERVICE_SDB_ADABASCREATIONDIALOG, aArgs), UNO_QUERY);
if (!xDialog.is())
{
// ShowServiceNotAvailableError(this, String(SERVICE_SDB_ADABASCREATIONDIALOG), sal_True);
return 0L;
}
if ( xDialog->execute() == RET_OK )
{
Reference<XPropertySet> xProp(xDialog,UNO_QUERY);
if(xProp.is())
{
Reference<XPropertySetInfo> xPropInfo(xProp->getPropertySetInfo());
if(xPropInfo->hasPropertyByName(PROPERTY_DATABASENAME))
{
String sDatabaseName;
sDatabaseName = String(::comphelper::getString(xProp->getPropertyValue(PROPERTY_DATABASENAME)));
m_aDatasource.SelectEntry(m_aDatasource.InsertEntry( sDatabaseName ));
}
if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLUSER) )
m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLUSER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLUSER))));
if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLPASSWORD) )
m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLPWD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLPASSWORD))));
if ( xPropInfo->hasPropertyByName(PROPERTY_USER) )
m_pOutputSet->Put(SfxStringItem(DSID_USER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_USER))));
if ( xPropInfo->hasPropertyByName(PROPERTY_PASSWORD) )
m_pOutputSet->Put(SfxStringItem(DSID_PASSWORD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_PASSWORD))));
if ( xPropInfo->hasPropertyByName(PROPERTY_CACHESIZE) )
m_pOutputSet->Put(SfxInt32Item(DSID_CONN_CACHESIZE, ::comphelper::getINT32(xProp->getPropertyValue(PROPERTY_CACHESIZE))));
}
}
}
}
catch(Exception&)
{
}
return 0L;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ManageClickHdl, PushButton*, pButton )
{
OOdbcManagement aOdbcConfig;
#ifdef HAVE_ODBC_ADMINISTRATION
if (!aOdbcConfig.isLoaded())
{
#endif
// show an error message
OLocalResourceAccess aLocRes(DLG_DATASOURCE_SELECTION, RSC_MODALDIALOG);
String sError(ModuleRes(STR_COULDNOTLOAD_CONFIGLIB));
sError.SearchAndReplaceAscii("#lib#", aOdbcConfig.getLibraryName());
ErrorBox aDialog(this, WB_OK, sError);
aDialog.Execute();
m_aDatasource.GrabFocus();
m_aManageDatasources.Disable();
return 1L;
#ifdef HAVE_ODBC_ADMINISTRATION
}
aOdbcConfig.manageDataSources(GetSystemData()->hWnd);
// now we have to look if there are any new datasources added
StringBag aOdbcDatasources;
OOdbcEnumeration aEnumeration;
aEnumeration.getDatasourceNames(aOdbcDatasources);
fillListBox(aOdbcDatasources);
return 0L;
#endif
}
// -----------------------------------------------------------------------------
void ODatasourceSelectDialog::fillListBox(const StringBag& _rDatasources)
{
m_aDatasource.Clear();
// fill the list
for ( ConstStringBagIterator aDS = _rDatasources.begin();
aDS != _rDatasources.end();
++aDS
)
{
m_aDatasource.InsertEntry( *aDS );
}
// select the first entry
if (m_aDatasource.GetEntryCount())
m_aDatasource.SelectEntryPos(0);
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS presentationengine01 (1.8.28); FILE MERGED 2004/11/17 14:57:21 thb 1.8.28.2: RESYNC: (1.8-1.9); FILE MERGED 2004/09/22 21:30:03 cl 1.8.28.1: fixed header problem with vcl/sysdata.hxx<commit_after>/*************************************************************************
*
* $RCSfile: dsselect.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2004-11-26 18:19:18 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBAUI_ODBC_CONFIG_HXX_
#include "odbcconfig.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HRC_
#include "dsselect.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif
#if defined( WIN ) || defined( WNT )
#define HWND void*
#define HMENU void*
typedef void* HDC;
// was unable to include windows.h, that's why this direct define
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_
#include <com/sun/star/sdbcx/XCreateCatalog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::comphelper;
//==================================================================
ODatasourceSelectDialog::ODatasourceSelectDialog(Window* _pParent, const StringBag& _rDatasources, DATASOURCE_TYPE _eType,SfxItemSet* _pOutputSet)
:ModalDialog(_pParent, ModuleRes(DLG_DATASOURCE_SELECTION))
,m_aDescription (this, ResId(FT_DESCRIPTION))
,m_aDatasource (this, ResId(LB_DATASOURCE))
,m_aOk (this, ResId(PB_OK))
,m_aCancel (this, ResId(PB_CANCEL))
,m_aHelp (this, ResId(PB_HELP))
,m_aManageDatasources (this, ResId(PB_MANAGE))
,m_aCreateAdabasDB (this, ResId(PB_CREATE))
,m_pOutputSet(_pOutputSet)
{
if (DST_ADABAS == _eType)
{ // set a new title (indicating that we're browsing local data sources only)
SetText(ResId(STR_LOCAL_DATASOURCES));
m_aDescription.SetText(ResId(STR_DESCRIPTION2));
m_aCreateAdabasDB.Show();
m_aCreateAdabasDB.SetClickHdl(LINK(this,ODatasourceSelectDialog,CreateDBClickHdl));
// resize the dialog a little bit, 'cause Adabas data source names are usually somewhat shorter
// than ODBC ones are
// shrink the listbox
Size aOldSize = m_aDatasource.GetSizePixel();
Size aNewSize(3 * aOldSize.Width() / 4, aOldSize.Height());
m_aDatasource.SetSizePixel(aNewSize);
sal_Int32 nLostPixels = aOldSize.Width() - aNewSize.Width();
// shrink the fixed text
aOldSize = m_aDescription.GetSizePixel();
m_aDescription.SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
// move the buttons
PushButton* pButtons[] = { &m_aOk, &m_aCancel, &m_aHelp ,&m_aCreateAdabasDB};
for (sal_Int32 i=0; i<sizeof(pButtons)/sizeof(pButtons[0]); ++i)
{
Point aOldPos = pButtons[i]->GetPosPixel();
pButtons[i]->SetPosPixel(Point(aOldPos.X() - nLostPixels, aOldPos.Y()));
}
// resize the dialog itself
aOldSize = GetSizePixel();
SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
}
fillListBox(_rDatasources);
// allow ODBC datasource managenment
if ( DST_ODBC == _eType || DST_MYSQL_ODBC == _eType )
{
m_aManageDatasources.Show();
m_aManageDatasources.Enable();
m_aManageDatasources.SetClickHdl(LINK(this,ODatasourceSelectDialog,ManageClickHdl));
}
m_aDatasource.SetDoubleClickHdl(LINK(this,ODatasourceSelectDialog,ListDblClickHdl));
FreeResource();
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ListDblClickHdl, ListBox *, pListBox )
{
if (pListBox->GetSelectEntryCount())
EndDialog(RET_OK);
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, CreateDBClickHdl, PushButton*, pButton )
{
try
{
OSL_ENSURE(m_pOutputSet,"No itemset given!");
Reference< ::com::sun::star::lang::XMultiServiceFactory > xORB = ::comphelper::getProcessServiceFactory();
Reference<XCreateCatalog> xCatalog(xORB->createInstance(SERVICE_EXTENDED_ADABAS_DRIVER),UNO_QUERY);
if ( xCatalog.is() && m_pOutputSet )
{
Sequence< Any > aArgs(2);
aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("CreateCatalog"), 0,makeAny(xCatalog) , PropertyState_DIRECT_VALUE);
aArgs[1] <<= PropertyValue(PROPERTY_PARENTWINDOW, 0, makeAny(VCLUnoHelper::GetInterface(this)), PropertyState_DIRECT_VALUE);
Reference< XExecutableDialog > xDialog(
xORB->createInstanceWithArguments(SERVICE_SDB_ADABASCREATIONDIALOG, aArgs), UNO_QUERY);
if (!xDialog.is())
{
// ShowServiceNotAvailableError(this, String(SERVICE_SDB_ADABASCREATIONDIALOG), sal_True);
return 0L;
}
if ( xDialog->execute() == RET_OK )
{
Reference<XPropertySet> xProp(xDialog,UNO_QUERY);
if(xProp.is())
{
Reference<XPropertySetInfo> xPropInfo(xProp->getPropertySetInfo());
if(xPropInfo->hasPropertyByName(PROPERTY_DATABASENAME))
{
String sDatabaseName;
sDatabaseName = String(::comphelper::getString(xProp->getPropertyValue(PROPERTY_DATABASENAME)));
m_aDatasource.SelectEntry(m_aDatasource.InsertEntry( sDatabaseName ));
}
if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLUSER) )
m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLUSER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLUSER))));
if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLPASSWORD) )
m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLPWD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLPASSWORD))));
if ( xPropInfo->hasPropertyByName(PROPERTY_USER) )
m_pOutputSet->Put(SfxStringItem(DSID_USER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_USER))));
if ( xPropInfo->hasPropertyByName(PROPERTY_PASSWORD) )
m_pOutputSet->Put(SfxStringItem(DSID_PASSWORD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_PASSWORD))));
if ( xPropInfo->hasPropertyByName(PROPERTY_CACHESIZE) )
m_pOutputSet->Put(SfxInt32Item(DSID_CONN_CACHESIZE, ::comphelper::getINT32(xProp->getPropertyValue(PROPERTY_CACHESIZE))));
}
}
}
}
catch(Exception&)
{
}
return 0L;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ManageClickHdl, PushButton*, pButton )
{
OOdbcManagement aOdbcConfig;
#ifdef HAVE_ODBC_ADMINISTRATION
if (!aOdbcConfig.isLoaded())
{
#endif
// show an error message
OLocalResourceAccess aLocRes(DLG_DATASOURCE_SELECTION, RSC_MODALDIALOG);
String sError(ModuleRes(STR_COULDNOTLOAD_CONFIGLIB));
sError.SearchAndReplaceAscii("#lib#", aOdbcConfig.getLibraryName());
ErrorBox aDialog(this, WB_OK, sError);
aDialog.Execute();
m_aDatasource.GrabFocus();
m_aManageDatasources.Disable();
return 1L;
#ifdef HAVE_ODBC_ADMINISTRATION
}
aOdbcConfig.manageDataSources(GetSystemData()->hWnd);
// now we have to look if there are any new datasources added
StringBag aOdbcDatasources;
OOdbcEnumeration aEnumeration;
aEnumeration.getDatasourceNames(aOdbcDatasources);
fillListBox(aOdbcDatasources);
return 0L;
#endif
}
// -----------------------------------------------------------------------------
void ODatasourceSelectDialog::fillListBox(const StringBag& _rDatasources)
{
m_aDatasource.Clear();
// fill the list
for ( ConstStringBagIterator aDS = _rDatasources.begin();
aDS != _rDatasources.end();
++aDS
)
{
m_aDatasource.InsertEntry( *aDS );
}
// select the first entry
if (m_aDatasource.GetEntryCount())
m_aDatasource.SelectEntryPos(0);
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
int p[50]={0};
void Init(){
p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[23]=p[29]=p[31]=1;
return ;
}
int a[30]={0};
int count1;
int add(int cur,int i){
if(p[a[cur-3]+a[cur-2]+a[cur-1]+a[cur]]==1){
return 1;
}
else{
return 0;
}
}
int n;
int dfs(int cur){
REP(i,0,9){
if(add(cur,i)){
if(cur==n+5){
count++;
}else{
a[cur++]=i
dfs(cur);
}
}
}
}
void Solve(){
dfs(5);
cout<<count<<endl;
return ;
}
int main(){
#ifdef LOCAL
freopen("uoj18025.in","r",stdin);
#endif
Init(),Solve();
return 0;
}<commit_msg>update uoj18025<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
int p[50]={0};
void Init(){
p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[23]=p[29]=p[31]=1;
return ;
}
int a[30]={0};
int count1;
int add(int cur,int i){
if(p[a[cur-3]+a[cur-2]+a[cur-1]+a[cur]]==1){
return 1;
}
else{
return 0;
}
}
int n;
int dfs(int cur){
REP(i,0,9){
if(add(cur,i)){
if(cur==n+5){
count1++;
}else{
a[cur++]=i;
dfs(cur);
}
}
}
}
void Solve(){
dfs(5);
cout<<count1<<endl;
return ;
}
int main(){
#ifdef LOCAL
freopen("uoj18025.in","r",stdin);
#endif
Init(),Solve();
return 0;
}<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" Target size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" Standard Star size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" Sky Fiber size %d \n",M.size());
F.Ngal = M.size();
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
// Make a plan ----------------------------------------------------
print_time(t,"# Start assignment at : ");
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
for(int i=0;i<F.NUsedplate;i++)printf(" jused %d j %d\n",i,A.suborder[i]);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
// Results -------------------------------------------------------*/
std::vector <int> total_used_by_class(M.priority_list.size(),0);
int total_used_SS=0;
int total_used_SF=0;
for (int jused=0;jused<F.NUsedplate;++jused){
std::vector <int> used_by_class(M.priority_list.size(),0);
int used_SS=0;
int used_SF=0;
int j=A.suborder[jused];
for(int k=0;k<F.Nfiber;++k){
int g=A.TF[j][k];
if(g!=-1){
if(M[g].SS){
total_used_SS++;
used_SS++;
}
else if(M[g].SF){
used_SF++;
total_used_SF++;
}
else{
used_by_class[M[g].priority_class]++;
total_used_by_class[M[g].priority_class]++;
}
}
}
printf(" plate jused %5d j %5d SS %4d SF %4d",jused,j,used_SS,used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,used_by_class[pr]);
}
printf("\n");
}
printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,total_used_by_class[pr]);
}
printf("\n");
if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
int j=A.suborder[jused];
write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int jused=0; jused<F.Nusedplate; jused++){
int j=A.suborder[jused];
fa_write(j,F.outDir,M,P,pp,F,A); // Write output
}
/*
display_results("doc/figs/",G,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
*/
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>jused only in ascii write<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" Target size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" Standard Star size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" Sky Fiber size %d \n",M.size());
F.Ngal = M.size();
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
// Make a plan ----------------------------------------------------
print_time(t,"# Start assignment at : ");
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
for(int i=0;i<F.NUsedplate;i++)printf(" jused %d j %d\n",i,A.suborder[i]);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
// Results -------------------------------------------------------*/
std::vector <int> total_used_by_class(M.priority_list.size(),0);
int total_used_SS=0;
int total_used_SF=0;
for (int jused=0;jused<F.NUsedplate;++jused){
std::vector <int> used_by_class(M.priority_list.size(),0);
int used_SS=0;
int used_SF=0;
int j=A.suborder[jused];
for(int k=0;k<F.Nfiber;++k){
int g=A.TF[j][k];
if(g!=-1){
if(M[g].SS){
total_used_SS++;
used_SS++;
}
else if(M[g].SF){
used_SF++;
total_used_SF++;
}
else{
used_by_class[M[g].priority_class]++;
total_used_by_class[M[g].priority_class]++;
}
}
}
printf(" plate jused %5d j %5d SS %4d SF %4d",jused,j,used_SS,used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,used_by_class[pr]);
}
printf("\n");
}
printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,total_used_by_class[pr]);
}
printf("\n");
if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
int j=A.suborder[jused];
write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
int j=A.suborder[jused];
fa_write(j,F.outDir,M,P,pp,F,A); // Write output
}
/*
display_results("doc/figs/",G,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
*/
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <OGRE/OgreCamera.h>
#include <OGRE/OgreQuaternion.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreVector3.h>
#include <OGRE/OgreViewport.h>
#include <rviz/display_context.h>
#include <rviz/geometry.h>
#include <rviz/ogre_helpers/shape.h>
#include <rviz/properties/bool_property.h>
#include <rviz/properties/float_property.h>
#include <rviz/properties/vector_property.h>
#include <rviz/uniform_string_stream.h>
#include <rviz/viewport_mouse_event.h>
#include <rviz/load_resource.h>
#include <rviz/render_panel.h>
#include <rviz/default_plugin/view_controllers/orbit_view_controller.h>
static const float PITCH_START = Ogre::Math::HALF_PI / 2.0;
static const float YAW_START = Ogre::Math::HALF_PI * 0.5;
static const float DISTANCE_START = 10;
static const float FOV_START = Ogre::Math::HALF_PI / 2.0;
static const float FOCAL_SHAPE_SIZE_START = 0.05;
static const bool FOCAL_SHAPE_FIXED_SIZE = true;
namespace rviz
{
OrbitViewController::OrbitViewController() : dragging_(false)
{
distance_property_ =
new FloatProperty("Distance", DISTANCE_START, "Distance from the focal point.", this);
distance_property_->setMin(0.001);
focal_shape_size_property_ =
new FloatProperty("Focal Shape Size", FOCAL_SHAPE_SIZE_START, "Focal shape size.", this);
focal_shape_size_property_->setMin(0.001);
focal_shape_fixed_size_property_ =
new BoolProperty("Focal Shape Fixed Size", FOCAL_SHAPE_FIXED_SIZE, "Focal shape size.", this);
yaw_property_ =
new FloatProperty("Yaw", YAW_START, "Rotation of the camera around the Z (up) axis.", this);
pitch_property_ =
new FloatProperty("Pitch", PITCH_START, "How much the camera is tipped downward.", this);
pitch_property_->setMax(Ogre::Math::HALF_PI - 0.001);
pitch_property_->setMin(-pitch_property_->getMax());
fov_property_ =
new FloatProperty("Field of View", FOV_START, "The field of view of the camera.", this);
fov_property_->setMin(0.001);
fov_property_->setMax(Ogre::Math::HALF_PI);
focal_point_property_ = new VectorProperty("Focal Point", Ogre::Vector3::ZERO,
"The center point which the camera orbits.", this);
}
void OrbitViewController::onInitialize()
{
FramePositionTrackingViewController::onInitialize();
camera_->setProjectionType(Ogre::PT_PERSPECTIVE);
focal_shape_ = new Shape(Shape::Sphere, context_->getSceneManager(), target_scene_node_);
updateFocalShapeSize();
focal_shape_->setColor(1.0f, 1.0f, 0.0f, 0.5f);
focal_shape_->getRootNode()->setVisible(false);
}
OrbitViewController::~OrbitViewController()
{
delete focal_shape_;
}
void OrbitViewController::reset()
{
dragging_ = false;
yaw_property_->setFloat(YAW_START);
pitch_property_->setFloat(PITCH_START);
distance_property_->setFloat(DISTANCE_START);
fov_property_->setFloat(FOV_START);
focal_shape_size_property_->setFloat(FOCAL_SHAPE_SIZE_START);
focal_shape_fixed_size_property_->setBool(false);
updateFocalShapeSize();
focal_point_property_->setVector(Ogre::Vector3::ZERO);
}
void OrbitViewController::handleMouseEvent(ViewportMouseEvent& event)
{
if (event.shift())
{
setStatus(
"<b>Left-Click:</b> Move X/Y. <b>Right-Click:</b>: Move Z. <b>Mouse Wheel:</b>: Zoom. ");
}
else
{
setStatus("<b>Left-Click:</b> Rotate. <b>Middle-Click:</b> Move X/Y. <b>Right-Click/Mouse "
"Wheel:</b>: Zoom. <b>Shift</b>: More options.");
}
float distance = distance_property_->getFloat();
updateFocalShapeSize();
int32_t diff_x = 0;
int32_t diff_y = 0;
bool moved = false;
if (event.type == QEvent::MouseButtonPress)
{
focal_shape_->getRootNode()->setVisible(true);
moved = true;
dragging_ = true;
}
else if (event.type == QEvent::MouseButtonRelease)
{
focal_shape_->getRootNode()->setVisible(false);
moved = true;
dragging_ = false;
}
else if (dragging_ && event.type == QEvent::MouseMove)
{
diff_x = event.x - event.last_x;
diff_y = event.y - event.last_y;
moved = true;
}
// regular left-button drag
if (event.left() && !event.shift())
{
setCursor(Rotate3D);
yaw(diff_x * 0.005);
pitch(-diff_y * 0.005);
}
// middle or shift-left drag
else if (event.middle() || (event.shift() && event.left()))
{
setCursor(MoveXY);
float fovY = camera_->getFOVy().valueRadians();
float fovX = 2.0f * std::atan(std::tan(fovY / 2.0f) * camera_->getAspectRatio());
int width = camera_->getViewport()->getActualWidth();
int height = camera_->getViewport()->getActualHeight();
move(-((float)diff_x / (float)width) * distance * std::tan(fovX / 2.0f) * 2.0f,
((float)diff_y / (float)height) * distance * std::tan(fovY / 2.0f) * 2.0f, 0.0f);
}
else if (event.right())
{
if (event.shift())
{
// move in z direction
setCursor(MoveZ);
move(0.0f, 0.0f, diff_y * 0.1 * (distance / 10.0f));
}
else
{
// zoom
setCursor(Zoom);
zoom(-diff_y * 0.1 * (distance / 10.0f));
}
}
else
{
setCursor(event.shift() ? MoveXY : Rotate3D);
}
moved = true;
if (event.wheel_delta != 0)
{
int diff = event.wheel_delta;
if (event.shift())
{
move(0, 0, -diff * 0.001 * distance);
}
else
{
zoom(diff * 0.001 * distance);
}
moved = true;
}
if (moved)
{
context_->queueRender();
}
}
void OrbitViewController::mimic(ViewController* source_view)
{
FramePositionTrackingViewController::mimic(source_view);
Ogre::Camera* source_camera = source_view->getCamera();
Ogre::Vector3 position = source_camera->getPosition();
Ogre::Quaternion orientation = source_camera->getOrientation();
if (source_view->getClassId() == "rviz/Orbit")
{
// If I'm initializing from another instance of this same class, get the distance exactly.
distance_property_->setFloat(source_view->subProp("Distance")->getValue().toFloat());
updateFocalShapeSize();
}
else
{
// Determine the distance from here to the reference frame, and use
// that as the distance our focal point should be at.
distance_property_->setFloat(position.length());
updateFocalShapeSize();
}
Ogre::Vector3 direction =
orientation * (Ogre::Vector3::NEGATIVE_UNIT_Z * distance_property_->getFloat());
focal_point_property_->setVector(position + direction);
calculatePitchYawFromPosition(position);
}
void OrbitViewController::update(float dt, float ros_dt)
{
FramePositionTrackingViewController::update(dt, ros_dt);
updateCamera();
}
void OrbitViewController::lookAt(const Ogre::Vector3& point)
{
Ogre::Vector3 camera_position = camera_->getPosition();
focal_point_property_->setVector(target_scene_node_->getOrientation().Inverse() *
(point - target_scene_node_->getPosition()));
distance_property_->setFloat(focal_point_property_->getVector().distance(camera_position));
updateFocalShapeSize();
calculatePitchYawFromPosition(camera_position);
}
void OrbitViewController::onTargetFrameChanged(const Ogre::Vector3& old_reference_position,
const Ogre::Quaternion& /*old_reference_orientation*/)
{
focal_point_property_->add(old_reference_position - reference_position_);
}
void OrbitViewController::updateCamera()
{
float distance = distance_property_->getFloat();
float yaw = yaw_property_->getFloat();
float pitch = pitch_property_->getFloat();
float fov = fov_property_->getFloat();
Ogre::Vector3 camera_z = Ogre::Vector3::UNIT_Z;
// If requested, turn the world upside down.
if (this->invert_z_->getBool())
{
yaw = -yaw;
pitch = -pitch;
camera_z = -camera_z;
}
Ogre::Vector3 focal_point = focal_point_property_->getVector();
float x = distance * std::cos(yaw) * std::cos(pitch) + focal_point.x;
float y = distance * std::sin(yaw) * std::cos(pitch) + focal_point.y;
float z = distance * std::sin(pitch) + focal_point.z;
Ogre::Vector3 pos(x, y, z);
camera_->setPosition(pos);
camera_->setFixedYawAxis(true, target_scene_node_->getOrientation() * camera_z);
camera_->setDirection(target_scene_node_->getOrientation() * (focal_point - pos));
camera_->setFOVy(Ogre::Radian(fov));
focal_shape_->setPosition(focal_point);
}
void OrbitViewController::yaw(float angle)
{
yaw_property_->setFloat(mapAngleTo0_2Pi(yaw_property_->getFloat() - angle));
}
void OrbitViewController::pitch(float angle)
{
pitch_property_->add(-angle);
}
void OrbitViewController::calculatePitchYawFromPosition(const Ogre::Vector3& position)
{
Ogre::Vector3 diff = position - focal_point_property_->getVector();
pitch_property_->setFloat(std::asin(diff.z / distance_property_->getFloat()));
yaw_property_->setFloat(atan2(diff.y, diff.x));
}
void OrbitViewController::updateFocalShapeSize()
{
const double fshape_size(focal_shape_size_property_->getFloat());
double distance_property(distance_property_->getFloat());
if (focal_shape_fixed_size_property_->getBool())
distance_property = 1;
focal_shape_->setScale(Ogre::Vector3(fshape_size * distance_property, fshape_size * distance_property,
fshape_size * distance_property / 5.0));
}
void OrbitViewController::zoom(float amount)
{
distance_property_->add(-amount);
updateFocalShapeSize();
}
void OrbitViewController::move(float x, float y, float z)
{
focal_point_property_->add(camera_->getOrientation() * Ogre::Vector3(x, y, z));
}
} // end namespace rviz
#include <cmath>
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(rviz::OrbitViewController, rviz::ViewController)
<commit_msg>fix clang-tidy: unused value<commit_after>/*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <OGRE/OgreCamera.h>
#include <OGRE/OgreQuaternion.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreVector3.h>
#include <OGRE/OgreViewport.h>
#include <rviz/display_context.h>
#include <rviz/geometry.h>
#include <rviz/ogre_helpers/shape.h>
#include <rviz/properties/bool_property.h>
#include <rviz/properties/float_property.h>
#include <rviz/properties/vector_property.h>
#include <rviz/uniform_string_stream.h>
#include <rviz/viewport_mouse_event.h>
#include <rviz/load_resource.h>
#include <rviz/render_panel.h>
#include <rviz/default_plugin/view_controllers/orbit_view_controller.h>
static const float PITCH_START = Ogre::Math::HALF_PI / 2.0;
static const float YAW_START = Ogre::Math::HALF_PI * 0.5;
static const float DISTANCE_START = 10;
static const float FOV_START = Ogre::Math::HALF_PI / 2.0;
static const float FOCAL_SHAPE_SIZE_START = 0.05;
static const bool FOCAL_SHAPE_FIXED_SIZE = true;
namespace rviz
{
OrbitViewController::OrbitViewController() : dragging_(false)
{
distance_property_ =
new FloatProperty("Distance", DISTANCE_START, "Distance from the focal point.", this);
distance_property_->setMin(0.001);
focal_shape_size_property_ =
new FloatProperty("Focal Shape Size", FOCAL_SHAPE_SIZE_START, "Focal shape size.", this);
focal_shape_size_property_->setMin(0.001);
focal_shape_fixed_size_property_ =
new BoolProperty("Focal Shape Fixed Size", FOCAL_SHAPE_FIXED_SIZE, "Focal shape size.", this);
yaw_property_ =
new FloatProperty("Yaw", YAW_START, "Rotation of the camera around the Z (up) axis.", this);
pitch_property_ =
new FloatProperty("Pitch", PITCH_START, "How much the camera is tipped downward.", this);
pitch_property_->setMax(Ogre::Math::HALF_PI - 0.001);
pitch_property_->setMin(-pitch_property_->getMax());
fov_property_ =
new FloatProperty("Field of View", FOV_START, "The field of view of the camera.", this);
fov_property_->setMin(0.001);
fov_property_->setMax(Ogre::Math::HALF_PI);
focal_point_property_ = new VectorProperty("Focal Point", Ogre::Vector3::ZERO,
"The center point which the camera orbits.", this);
}
void OrbitViewController::onInitialize()
{
FramePositionTrackingViewController::onInitialize();
camera_->setProjectionType(Ogre::PT_PERSPECTIVE);
focal_shape_ = new Shape(Shape::Sphere, context_->getSceneManager(), target_scene_node_);
updateFocalShapeSize();
focal_shape_->setColor(1.0f, 1.0f, 0.0f, 0.5f);
focal_shape_->getRootNode()->setVisible(false);
}
OrbitViewController::~OrbitViewController()
{
delete focal_shape_;
}
void OrbitViewController::reset()
{
dragging_ = false;
yaw_property_->setFloat(YAW_START);
pitch_property_->setFloat(PITCH_START);
distance_property_->setFloat(DISTANCE_START);
fov_property_->setFloat(FOV_START);
focal_shape_size_property_->setFloat(FOCAL_SHAPE_SIZE_START);
focal_shape_fixed_size_property_->setBool(false);
updateFocalShapeSize();
focal_point_property_->setVector(Ogre::Vector3::ZERO);
}
void OrbitViewController::handleMouseEvent(ViewportMouseEvent& event)
{
if (event.shift())
{
setStatus(
"<b>Left-Click:</b> Move X/Y. <b>Right-Click:</b>: Move Z. <b>Mouse Wheel:</b>: Zoom. ");
}
else
{
setStatus("<b>Left-Click:</b> Rotate. <b>Middle-Click:</b> Move X/Y. <b>Right-Click/Mouse "
"Wheel:</b>: Zoom. <b>Shift</b>: More options.");
}
float distance = distance_property_->getFloat();
updateFocalShapeSize();
int32_t diff_x = 0;
int32_t diff_y = 0;
if (event.type == QEvent::MouseButtonPress)
{
focal_shape_->getRootNode()->setVisible(true);
dragging_ = true;
}
else if (event.type == QEvent::MouseButtonRelease)
{
focal_shape_->getRootNode()->setVisible(false);
dragging_ = false;
}
else if (dragging_ && event.type == QEvent::MouseMove)
{
diff_x = event.x - event.last_x;
diff_y = event.y - event.last_y;
}
// regular left-button drag
if (event.left() && !event.shift())
{
setCursor(Rotate3D);
yaw(diff_x * 0.005);
pitch(-diff_y * 0.005);
}
// middle or shift-left drag
else if (event.middle() || (event.shift() && event.left()))
{
setCursor(MoveXY);
float fovY = camera_->getFOVy().valueRadians();
float fovX = 2.0f * std::atan(std::tan(fovY / 2.0f) * camera_->getAspectRatio());
int width = camera_->getViewport()->getActualWidth();
int height = camera_->getViewport()->getActualHeight();
move(-((float)diff_x / (float)width) * distance * std::tan(fovX / 2.0f) * 2.0f,
((float)diff_y / (float)height) * distance * std::tan(fovY / 2.0f) * 2.0f, 0.0f);
}
else if (event.right())
{
if (event.shift())
{
// move in z direction
setCursor(MoveZ);
move(0.0f, 0.0f, diff_y * 0.1 * (distance / 10.0f));
}
else
{
// zoom
setCursor(Zoom);
zoom(-diff_y * 0.1 * (distance / 10.0f));
}
}
else
{
setCursor(event.shift() ? MoveXY : Rotate3D);
}
if (event.wheel_delta != 0)
{
int diff = event.wheel_delta;
if (event.shift())
{
move(0, 0, -diff * 0.001 * distance);
}
else
{
zoom(diff * 0.001 * distance);
}
}
context_->queueRender();
}
void OrbitViewController::mimic(ViewController* source_view)
{
FramePositionTrackingViewController::mimic(source_view);
Ogre::Camera* source_camera = source_view->getCamera();
Ogre::Vector3 position = source_camera->getPosition();
Ogre::Quaternion orientation = source_camera->getOrientation();
if (source_view->getClassId() == "rviz/Orbit")
{
// If I'm initializing from another instance of this same class, get the distance exactly.
distance_property_->setFloat(source_view->subProp("Distance")->getValue().toFloat());
updateFocalShapeSize();
}
else
{
// Determine the distance from here to the reference frame, and use
// that as the distance our focal point should be at.
distance_property_->setFloat(position.length());
updateFocalShapeSize();
}
Ogre::Vector3 direction =
orientation * (Ogre::Vector3::NEGATIVE_UNIT_Z * distance_property_->getFloat());
focal_point_property_->setVector(position + direction);
calculatePitchYawFromPosition(position);
}
void OrbitViewController::update(float dt, float ros_dt)
{
FramePositionTrackingViewController::update(dt, ros_dt);
updateCamera();
}
void OrbitViewController::lookAt(const Ogre::Vector3& point)
{
Ogre::Vector3 camera_position = camera_->getPosition();
focal_point_property_->setVector(target_scene_node_->getOrientation().Inverse() *
(point - target_scene_node_->getPosition()));
distance_property_->setFloat(focal_point_property_->getVector().distance(camera_position));
updateFocalShapeSize();
calculatePitchYawFromPosition(camera_position);
}
void OrbitViewController::onTargetFrameChanged(const Ogre::Vector3& old_reference_position,
const Ogre::Quaternion& /*old_reference_orientation*/)
{
focal_point_property_->add(old_reference_position - reference_position_);
}
void OrbitViewController::updateCamera()
{
float distance = distance_property_->getFloat();
float yaw = yaw_property_->getFloat();
float pitch = pitch_property_->getFloat();
float fov = fov_property_->getFloat();
Ogre::Vector3 camera_z = Ogre::Vector3::UNIT_Z;
// If requested, turn the world upside down.
if (this->invert_z_->getBool())
{
yaw = -yaw;
pitch = -pitch;
camera_z = -camera_z;
}
Ogre::Vector3 focal_point = focal_point_property_->getVector();
float x = distance * std::cos(yaw) * std::cos(pitch) + focal_point.x;
float y = distance * std::sin(yaw) * std::cos(pitch) + focal_point.y;
float z = distance * std::sin(pitch) + focal_point.z;
Ogre::Vector3 pos(x, y, z);
camera_->setPosition(pos);
camera_->setFixedYawAxis(true, target_scene_node_->getOrientation() * camera_z);
camera_->setDirection(target_scene_node_->getOrientation() * (focal_point - pos));
camera_->setFOVy(Ogre::Radian(fov));
focal_shape_->setPosition(focal_point);
}
void OrbitViewController::yaw(float angle)
{
yaw_property_->setFloat(mapAngleTo0_2Pi(yaw_property_->getFloat() - angle));
}
void OrbitViewController::pitch(float angle)
{
pitch_property_->add(-angle);
}
void OrbitViewController::calculatePitchYawFromPosition(const Ogre::Vector3& position)
{
Ogre::Vector3 diff = position - focal_point_property_->getVector();
pitch_property_->setFloat(std::asin(diff.z / distance_property_->getFloat()));
yaw_property_->setFloat(atan2(diff.y, diff.x));
}
void OrbitViewController::updateFocalShapeSize()
{
const double fshape_size(focal_shape_size_property_->getFloat());
double distance_property(distance_property_->getFloat());
if (focal_shape_fixed_size_property_->getBool())
distance_property = 1;
focal_shape_->setScale(Ogre::Vector3(fshape_size * distance_property, fshape_size * distance_property,
fshape_size * distance_property / 5.0));
}
void OrbitViewController::zoom(float amount)
{
distance_property_->add(-amount);
updateFocalShapeSize();
}
void OrbitViewController::move(float x, float y, float z)
{
focal_point_property_->add(camera_->getOrientation() * Ogre::Vector3(x, y, z));
}
} // end namespace rviz
#include <cmath>
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(rviz::OrbitViewController, rviz::ViewController)
<|endoftext|>
|
<commit_before>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Player.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "TaskScheduler.h"
#include "temple_of_ahnqiraj.h"
enum Spells
{
// Both
SPELL_TWIN_EMPATHY = 1177,
SPELL_TWIN_TELEPORT_1 = 800,
SPELL_TWIN_TELEPORT_VISUAL = 26638,
SPELL_HEAL_BROTHER = 7393,
// Vek'lor
SPELL_SHADOW_BOLT = 26006,
SPELL_BLIZZARD = 26607,
SPELL_FRENZY = 27897,
SPELL_ARCANE_BURST = 568,
SPELL_EXPLODE_BUG = 804,
SPELL_TWIN_TELEPORT_0 = 799,
// Vek'nilash
SPELL_UPPERCUT = 26007,
SPELL_UNBALANCING_STRIKE = 26613,
SPELL_BERSERK = 27680,
SPELL_MUTATE_BUG = 802,
// Bugs
SPELL_VIRULENT_POISON_PROC = 22413
};
enum Actions
{
ACTION_START_INTRO = 0,
ACTION_CANCEL_INTRO = 1,
ACTION_AFTER_TELEPORT = 2
};
enum Say
{
SAY_INTRO_0 = 0,
SAY_INTRO_1 = 1,
SAY_INTRO_2 = 2,
SAY_KILL = 3,
SAY_DEATH = 4,
EMOTE_ENRAGE = 5,
EMOTE_MASTERS_EYE_AT = 0,
};
enum Sounds
{
SOUND_VK_AGGRO = 8657,
SOUND_VN_AGGRO = 8661
};
enum Misc
{
GROUP_INTRO = 0,
NPC_QIRAJI_SCARAB = 15316,
NPC_QIRAJI_SCORPION = 15317,
FACTION_HOSTILE = 16
};
constexpr float veklorOrientationIntro = 2.241519f;
constexpr float veknilashOrientationIntro = 1.144451f;
struct boss_twinemperorsAI : public BossAI
{
boss_twinemperorsAI(Creature* creature): BossAI(creature, DATA_TWIN_EMPERORS), _introDone(false)
{
me->SetStandState(UNIT_STAND_STATE_KNEEL);
_scheduler.SetValidator([this]
{
return !me->HasUnitState(UNIT_STATE_CASTING);
});
}
Creature* GetTwin()
{
return instance->GetCreature(IAmVeklor() ? DATA_VEKNILASH : DATA_VEKLOR);
}
void DamageTaken(Unit* attacker, uint32& damage, DamageEffectType, SpellSchoolMask) override
{
if (attacker)
{
if (attacker->GetEntry() == NPC_VEKLOR || attacker->GetEntry() == NPC_VEKNILASH)
{
me->LowerPlayerDamageReq(damage);
return;
}
if (Creature* twin = GetTwin())
{
float dmgPct = damage / (float)me->GetMaxHealth();
int32 actualDmg = dmgPct * twin->GetMaxHealth();
twin->CastCustomSpell(twin, SPELL_TWIN_EMPATHY, &actualDmg, nullptr, nullptr, true);
}
}
}
void KilledUnit(Unit* victim) override
{
if (victim && victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_KILL);
}
void EnterEvadeMode(EvadeReason why) override
{
BossAI::EnterEvadeMode(why);
if (Creature* twin = GetTwin())
if (!twin->IsInEvadeMode())
twin->AI()->EnterEvadeMode(why);
_scheduler.CancelAll();
}
void JustDied(Unit* killer) override
{
if (Creature* twin = GetTwin())
if (twin->IsAlive())
Unit::Kill(me, twin);
Talk(SAY_DEATH);
BossAI::JustDied(killer);
}
void DoAction(int32 action) override
{
if (action == ACTION_CANCEL_INTRO)
{
_introDone = true;
_scheduler.CancelGroup(GROUP_INTRO);
return;
}
if (action == ACTION_AFTER_TELEPORT)
{
DoResetThreat();
me->SetReactState(REACT_PASSIVE);
DoCastSelf(SPELL_TWIN_TELEPORT_VISUAL, true);
_scheduler.DelayAll(2300ms);
_scheduler.Schedule(2s, [this](TaskContext /*context*/)
{
me->SetReactState(REACT_AGGRESSIVE);
me->SetControlled(false, UNIT_STATE_ROOT);
if (Unit* victim = me->SelectNearestTarget())
{
me->AddThreat(victim, 2000.f);
AttackStart(victim);
}
});
}
if (action != ACTION_START_INTRO)
return;
_scheduler.Schedule(5s, [this](TaskContext /*context*/)
{
me->SetStandState(UNIT_STAND_STATE_STAND);
me->LoadEquipment(1, true);
});
if (IAmVeklor())
{
_scheduler
.Schedule(12s, GROUP_INTRO, [this](TaskContext /*context*/)
{
Talk(SAY_INTRO_0);
})
.Schedule(20s, GROUP_INTRO, [this](TaskContext /*context*/)
{
Talk(SAY_INTRO_1);
})
.Schedule(28s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_ROAR);
})
.Schedule(30s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->SetFacingTo(veklorOrientationIntro);
Talk(SAY_INTRO_2);
})
.Schedule(33s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_POINT);
_introDone = true;
});
}
else
{
_scheduler
.Schedule(17s, GROUP_INTRO, [this](TaskContext /*context*/)
{
Talk(SAY_INTRO_0);
})
.Schedule(23s, GROUP_INTRO, [this](TaskContext /*context*/)
{
Talk(SAY_INTRO_1);
})
.Schedule(28s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_ROAR);
})
.Schedule(32s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->SetFacingTo(veknilashOrientationIntro);
Talk(SAY_INTRO_2);
})
.Schedule(33s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_POINT);
_introDone = true;
});
}
}
void EnterCombat(Unit* who) override
{
BossAI::EnterCombat(who);
if (!_introDone)
{
DoAction(ACTION_CANCEL_INTRO);
if (Creature* twin = GetTwin())
twin->AI()->DoAction(ACTION_CANCEL_INTRO);
}
if (Creature* twin = GetTwin())
if (!twin->IsInCombat())
twin->AI()->AttackStart(who);
_scheduler
.Schedule(15min, [this](TaskContext /*context*/)
{
if (IAmVeklor())
{
DoCastSelf(SPELL_FRENZY, true);
Talk(EMOTE_ENRAGE);
}
else
DoCastSelf(SPELL_BERSERK, true);
})
.Schedule(3600ms, [this](TaskContext context) // according to sniffs it should be casted by both emperors.
{
if (Creature* twin = GetTwin())
{
if (me->IsWithinDist(twin, 60.f))
DoCast(twin, SPELL_HEAL_BROTHER, true);
}
context.Repeat();
});
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() && _introDone)
return;
_scheduler.Update(diff, [this]
{
if (!IAmVeklor())
DoMeleeAttackIfReady();
});
}
virtual bool IAmVeklor() = 0;
protected:
TaskScheduler _scheduler;
bool _introDone;
};
struct boss_veknilash : public boss_twinemperorsAI
{
boss_veknilash(Creature* creature) : boss_twinemperorsAI(creature) { }
bool IAmVeklor() override { return false; }
void EnterCombat(Unit* who) override
{
boss_twinemperorsAI::EnterCombat(who);
DoPlaySoundToSet(me, SOUND_VN_AGGRO);
_scheduler
.Schedule(14s, [this](TaskContext context)
{
DoCastRandomTarget(SPELL_UPPERCUT, 0, me->GetMeleeReach(), true);
context.Repeat(4s, 15s);
})
.Schedule(12s, [this](TaskContext context)
{
DoCastVictim(SPELL_UNBALANCING_STRIKE);
context.Repeat(8s, 20s);
})
.Schedule(16s, [this](TaskContext context)
{
DoCastAOE(SPELL_MUTATE_BUG);
context.Repeat(10s, 20s);
});
}
};
struct boss_veklor : public boss_twinemperorsAI
{
boss_veklor(Creature* creature) : boss_twinemperorsAI(creature)
{
me->SetFloatValue(UNIT_FIELD_COMBATREACH, 45.f);
}
bool IAmVeklor() override { return true; }
void EnterCombat(Unit* who) override
{
boss_twinemperorsAI::EnterCombat(who);
DoPlaySoundToSet(me, SOUND_VK_AGGRO);
_scheduler
.Schedule(4s, [this](TaskContext context)
{
DoCastVictim(SPELL_SHADOW_BOLT);
context.Repeat(2500ms);
})
.Schedule(10s, 15s, [this](TaskContext context)
{
DoCastRandomTarget(SPELL_BLIZZARD, 0, 45.f);
context.Repeat(5s, 12s);
})
.Schedule(1s, [this](TaskContext context)
{
if (me->SelectNearestPlayer(NOMINAL_MELEE_RANGE))
DoCastAOE(SPELL_ARCANE_BURST);
context.Repeat(7s, 12s);
})
.Schedule(30s, 40s, [this](TaskContext context)
{
DoCastSelf(SPELL_TWIN_TELEPORT_0);
context.Repeat();
})
.Schedule(5s, [this](TaskContext context)
{
DoCastAOE(SPELL_EXPLODE_BUG);
context.Repeat(4500ms, 10s);
});
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spellInfo) override
{
if (spellInfo->Id == SPELL_TWIN_TELEPORT_0)
{
if (Creature* veknilash = GetTwin())
{
DoCastSelf(SPELL_TWIN_TELEPORT_1, true);
me->SetControlled(true, UNIT_STATE_ROOT);
Position veklorPos = me->GetPosition();
Position veknilashPos = veknilash->GetPosition();
me->NearTeleportTo(veknilashPos);
veknilash->CastSpell(veknilash, SPELL_TWIN_TELEPORT_1, true);
veknilash->SetControlled(true, UNIT_STATE_ROOT);
veknilash->NearTeleportTo(veklorPos);
veknilash->AI()->DoAction(ACTION_AFTER_TELEPORT);
DoAction(ACTION_AFTER_TELEPORT);
}
}
}
};
class at_twin_emperors : public OnlyOnceAreaTriggerScript
{
public:
at_twin_emperors() : OnlyOnceAreaTriggerScript("at_twin_emperors") { }
bool _OnTrigger(Player* player, const AreaTrigger* /*at*/) override
{
if (InstanceScript* instance = player->GetInstanceScript())
{
if (instance->GetBossState(DATA_TWIN_EMPERORS) != DONE)
{
if (Creature* mastersEye = instance->GetCreature(DATA_MASTERS_EYE))
{
mastersEye->AI()->Talk(EMOTE_MASTERS_EYE_AT, player);
mastersEye->DespawnOrUnsummon(11000);
mastersEye->m_Events.AddEventAtOffset([mastersEye, player]()
{
mastersEye->SetFacingToObject(player);
}, 3s);
}
if (Creature* veklor = instance->GetCreature(DATA_VEKLOR))
veklor->AI()->DoAction(ACTION_START_INTRO);
if (Creature* veknilash = instance->GetCreature(DATA_VEKNILASH))
veknilash->AI()->DoAction(ACTION_START_INTRO);
}
}
return false;
}
};
class spell_mutate_explode_bug : public SpellScript
{
PrepareSpellScript(spell_mutate_explode_bug);
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.remove_if([&](WorldObject const* target) -> bool
{
if (target->GetEntry() != NPC_QIRAJI_SCARAB && target->GetEntry() != NPC_QIRAJI_SCORPION)
return true;
if (Creature const* creature = target->ToCreature())
if (creature->HasAura(SPELL_EXPLODE_BUG) || creature->HasAura(SPELL_MUTATE_BUG))
return true;
return false;
});
Acore::Containers::RandomResize(targets, 1);
}
void HandleOnHit()
{
if (!GetHitUnit())
return;
Creature* target = GetHitUnit()->ToCreature();
if (!target)
return;
if (m_scriptSpellId == SPELL_MUTATE_BUG)
target->CastSpell(target, SPELL_VIRULENT_POISON_PROC, true);
target->SetFaction(FACTION_HOSTILE);
target->SetReactState(REACT_AGGRESSIVE);
target->SetInCombatWithZone();
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_mutate_explode_bug::FilterTargets, EFFECT_ALL, TARGET_UNIT_SRC_AREA_ENTRY);
OnHit += SpellHitFn(spell_mutate_explode_bug::HandleOnHit);
}
};
void AddSC_boss_twinemperors()
{
RegisterTempleOfAhnQirajCreatureAI(boss_veknilash);
RegisterTempleOfAhnQirajCreatureAI(boss_veklor);
new at_twin_emperors();
RegisterSpellScript(spell_mutate_explode_bug);
}
<commit_msg>fix(Scripts/TempleOfAhnQiraj): Prevent Uppercut from triggering Double Attack (#13482)<commit_after>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Player.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "TaskScheduler.h"
#include "temple_of_ahnqiraj.h"
enum Spells
{
// Both
SPELL_TWIN_EMPATHY = 1177,
SPELL_TWIN_TELEPORT_1 = 800,
SPELL_TWIN_TELEPORT_VISUAL = 26638,
SPELL_HEAL_BROTHER = 7393,
// Vek'lor
SPELL_SHADOW_BOLT = 26006,
SPELL_BLIZZARD = 26607,
SPELL_FRENZY = 27897,
SPELL_ARCANE_BURST = 568,
SPELL_EXPLODE_BUG = 804,
SPELL_TWIN_TELEPORT_0 = 799,
// Vek'nilash
SPELL_UPPERCUT = 26007,
SPELL_UNBALANCING_STRIKE = 26613,
SPELL_BERSERK = 27680,
SPELL_MUTATE_BUG = 802,
// Bugs
SPELL_VIRULENT_POISON_PROC = 22413
};
enum Actions
{
ACTION_START_INTRO = 0,
ACTION_CANCEL_INTRO = 1,
ACTION_AFTER_TELEPORT = 2
};
enum Say
{
SAY_INTRO_0 = 0,
SAY_INTRO_1 = 1,
SAY_INTRO_2 = 2,
SAY_KILL = 3,
SAY_DEATH = 4,
EMOTE_ENRAGE = 5,
EMOTE_MASTERS_EYE_AT = 0,
};
enum Sounds
{
SOUND_VK_AGGRO = 8657,
SOUND_VN_AGGRO = 8661
};
enum Misc
{
GROUP_INTRO = 0,
NPC_QIRAJI_SCARAB = 15316,
NPC_QIRAJI_SCORPION = 15317,
FACTION_HOSTILE = 16
};
constexpr float veklorOrientationIntro = 2.241519f;
constexpr float veknilashOrientationIntro = 1.144451f;
struct boss_twinemperorsAI : public BossAI
{
boss_twinemperorsAI(Creature* creature): BossAI(creature, DATA_TWIN_EMPERORS), _introDone(false)
{
me->SetStandState(UNIT_STAND_STATE_KNEEL);
_scheduler.SetValidator([this]
{
return !me->HasUnitState(UNIT_STATE_CASTING);
});
}
Creature* GetTwin()
{
return instance->GetCreature(IAmVeklor() ? DATA_VEKNILASH : DATA_VEKLOR);
}
void DamageTaken(Unit* attacker, uint32& damage, DamageEffectType, SpellSchoolMask) override
{
if (attacker)
{
if (attacker->GetEntry() == NPC_VEKLOR || attacker->GetEntry() == NPC_VEKNILASH)
{
me->LowerPlayerDamageReq(damage);
return;
}
if (Creature* twin = GetTwin())
{
float dmgPct = damage / (float)me->GetMaxHealth();
int32 actualDmg = dmgPct * twin->GetMaxHealth();
twin->CastCustomSpell(twin, SPELL_TWIN_EMPATHY, &actualDmg, nullptr, nullptr, true);
}
}
}
void KilledUnit(Unit* victim) override
{
if (victim && victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_KILL);
}
void EnterEvadeMode(EvadeReason why) override
{
BossAI::EnterEvadeMode(why);
if (Creature* twin = GetTwin())
if (!twin->IsInEvadeMode())
twin->AI()->EnterEvadeMode(why);
_scheduler.CancelAll();
}
void JustDied(Unit* killer) override
{
if (Creature* twin = GetTwin())
if (twin->IsAlive())
Unit::Kill(me, twin);
Talk(SAY_DEATH);
BossAI::JustDied(killer);
}
void DoAction(int32 action) override
{
if (action == ACTION_CANCEL_INTRO)
{
_introDone = true;
_scheduler.CancelGroup(GROUP_INTRO);
return;
}
if (action == ACTION_AFTER_TELEPORT)
{
DoResetThreat();
me->SetReactState(REACT_PASSIVE);
DoCastSelf(SPELL_TWIN_TELEPORT_VISUAL, true);
_scheduler.DelayAll(2300ms);
_scheduler.Schedule(2s, [this](TaskContext /*context*/)
{
me->SetReactState(REACT_AGGRESSIVE);
me->SetControlled(false, UNIT_STATE_ROOT);
if (Unit* victim = me->SelectNearestTarget())
{
me->AddThreat(victim, 2000.f);
AttackStart(victim);
}
});
}
if (action != ACTION_START_INTRO)
return;
_scheduler.Schedule(5s, [this](TaskContext /*context*/)
{
me->SetStandState(UNIT_STAND_STATE_STAND);
me->LoadEquipment(1, true);
});
if (IAmVeklor())
{
_scheduler
.Schedule(12s, GROUP_INTRO, [this](TaskContext /*context*/)
{
Talk(SAY_INTRO_0);
})
.Schedule(20s, GROUP_INTRO, [this](TaskContext /*context*/)
{
Talk(SAY_INTRO_1);
})
.Schedule(28s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_ROAR);
})
.Schedule(30s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->SetFacingTo(veklorOrientationIntro);
Talk(SAY_INTRO_2);
})
.Schedule(33s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_POINT);
_introDone = true;
});
}
else
{
_scheduler
.Schedule(17s, GROUP_INTRO, [this](TaskContext /*context*/)
{
Talk(SAY_INTRO_0);
})
.Schedule(23s, GROUP_INTRO, [this](TaskContext /*context*/)
{
Talk(SAY_INTRO_1);
})
.Schedule(28s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_ROAR);
})
.Schedule(32s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->SetFacingTo(veknilashOrientationIntro);
Talk(SAY_INTRO_2);
})
.Schedule(33s, GROUP_INTRO, [this](TaskContext /*context*/)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_POINT);
_introDone = true;
});
}
}
void EnterCombat(Unit* who) override
{
BossAI::EnterCombat(who);
if (!_introDone)
{
DoAction(ACTION_CANCEL_INTRO);
if (Creature* twin = GetTwin())
twin->AI()->DoAction(ACTION_CANCEL_INTRO);
}
if (Creature* twin = GetTwin())
if (!twin->IsInCombat())
twin->AI()->AttackStart(who);
_scheduler
.Schedule(15min, [this](TaskContext /*context*/)
{
if (IAmVeklor())
{
DoCastSelf(SPELL_FRENZY, true);
Talk(EMOTE_ENRAGE);
}
else
DoCastSelf(SPELL_BERSERK, true);
})
.Schedule(3600ms, [this](TaskContext context) // according to sniffs it should be casted by both emperors.
{
if (Creature* twin = GetTwin())
{
if (me->IsWithinDist(twin, 60.f))
DoCast(twin, SPELL_HEAL_BROTHER, true);
}
context.Repeat();
});
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() && _introDone)
return;
_scheduler.Update(diff, [this]
{
if (!IAmVeklor())
DoMeleeAttackIfReady();
});
}
virtual bool IAmVeklor() = 0;
protected:
TaskScheduler _scheduler;
bool _introDone;
};
struct boss_veknilash : public boss_twinemperorsAI
{
boss_veknilash(Creature* creature) : boss_twinemperorsAI(creature) { }
bool IAmVeklor() override { return false; }
void EnterCombat(Unit* who) override
{
boss_twinemperorsAI::EnterCombat(who);
DoPlaySoundToSet(me, SOUND_VN_AGGRO);
_scheduler
.Schedule(14s, [this](TaskContext context)
{
DoCastRandomTarget(SPELL_UPPERCUT, 0, me->GetMeleeReach(), true, true);
context.Repeat(4s, 15s);
})
.Schedule(12s, [this](TaskContext context)
{
DoCastVictim(SPELL_UNBALANCING_STRIKE);
context.Repeat(8s, 20s);
})
.Schedule(16s, [this](TaskContext context)
{
DoCastAOE(SPELL_MUTATE_BUG);
context.Repeat(10s, 20s);
});
}
};
struct boss_veklor : public boss_twinemperorsAI
{
boss_veklor(Creature* creature) : boss_twinemperorsAI(creature)
{
me->SetFloatValue(UNIT_FIELD_COMBATREACH, 45.f);
}
bool IAmVeklor() override { return true; }
void EnterCombat(Unit* who) override
{
boss_twinemperorsAI::EnterCombat(who);
DoPlaySoundToSet(me, SOUND_VK_AGGRO);
_scheduler
.Schedule(4s, [this](TaskContext context)
{
DoCastVictim(SPELL_SHADOW_BOLT);
context.Repeat(2500ms);
})
.Schedule(10s, 15s, [this](TaskContext context)
{
DoCastRandomTarget(SPELL_BLIZZARD, 0, 45.f);
context.Repeat(5s, 12s);
})
.Schedule(1s, [this](TaskContext context)
{
if (me->SelectNearestPlayer(NOMINAL_MELEE_RANGE))
DoCastAOE(SPELL_ARCANE_BURST);
context.Repeat(7s, 12s);
})
.Schedule(30s, 40s, [this](TaskContext context)
{
DoCastSelf(SPELL_TWIN_TELEPORT_0);
context.Repeat();
})
.Schedule(5s, [this](TaskContext context)
{
DoCastAOE(SPELL_EXPLODE_BUG);
context.Repeat(4500ms, 10s);
});
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spellInfo) override
{
if (spellInfo->Id == SPELL_TWIN_TELEPORT_0)
{
if (Creature* veknilash = GetTwin())
{
DoCastSelf(SPELL_TWIN_TELEPORT_1, true);
me->SetControlled(true, UNIT_STATE_ROOT);
Position veklorPos = me->GetPosition();
Position veknilashPos = veknilash->GetPosition();
me->NearTeleportTo(veknilashPos);
veknilash->CastSpell(veknilash, SPELL_TWIN_TELEPORT_1, true);
veknilash->SetControlled(true, UNIT_STATE_ROOT);
veknilash->NearTeleportTo(veklorPos);
veknilash->AI()->DoAction(ACTION_AFTER_TELEPORT);
DoAction(ACTION_AFTER_TELEPORT);
}
}
}
};
class at_twin_emperors : public OnlyOnceAreaTriggerScript
{
public:
at_twin_emperors() : OnlyOnceAreaTriggerScript("at_twin_emperors") { }
bool _OnTrigger(Player* player, const AreaTrigger* /*at*/) override
{
if (InstanceScript* instance = player->GetInstanceScript())
{
if (instance->GetBossState(DATA_TWIN_EMPERORS) != DONE)
{
if (Creature* mastersEye = instance->GetCreature(DATA_MASTERS_EYE))
{
mastersEye->AI()->Talk(EMOTE_MASTERS_EYE_AT, player);
mastersEye->DespawnOrUnsummon(11000);
mastersEye->m_Events.AddEventAtOffset([mastersEye, player]()
{
mastersEye->SetFacingToObject(player);
}, 3s);
}
if (Creature* veklor = instance->GetCreature(DATA_VEKLOR))
veklor->AI()->DoAction(ACTION_START_INTRO);
if (Creature* veknilash = instance->GetCreature(DATA_VEKNILASH))
veknilash->AI()->DoAction(ACTION_START_INTRO);
}
}
return false;
}
};
class spell_mutate_explode_bug : public SpellScript
{
PrepareSpellScript(spell_mutate_explode_bug);
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.remove_if([&](WorldObject const* target) -> bool
{
if (target->GetEntry() != NPC_QIRAJI_SCARAB && target->GetEntry() != NPC_QIRAJI_SCORPION)
return true;
if (Creature const* creature = target->ToCreature())
if (creature->HasAura(SPELL_EXPLODE_BUG) || creature->HasAura(SPELL_MUTATE_BUG))
return true;
return false;
});
Acore::Containers::RandomResize(targets, 1);
}
void HandleOnHit()
{
if (!GetHitUnit())
return;
Creature* target = GetHitUnit()->ToCreature();
if (!target)
return;
if (m_scriptSpellId == SPELL_MUTATE_BUG)
target->CastSpell(target, SPELL_VIRULENT_POISON_PROC, true);
target->SetFaction(FACTION_HOSTILE);
target->SetReactState(REACT_AGGRESSIVE);
target->SetInCombatWithZone();
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_mutate_explode_bug::FilterTargets, EFFECT_ALL, TARGET_UNIT_SRC_AREA_ENTRY);
OnHit += SpellHitFn(spell_mutate_explode_bug::HandleOnHit);
}
};
void AddSC_boss_twinemperors()
{
RegisterTempleOfAhnQirajCreatureAI(boss_veknilash);
RegisterTempleOfAhnQirajCreatureAI(boss_veklor);
new at_twin_emperors();
RegisterSpellScript(spell_mutate_explode_bug);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {ROI_QB_MUL_1.png}
// OUTPUTS: {MSLabeledOutput.tif}, {MSClusteredOutput.tif} {MSLabeledOutput-pretty.png}, {MSClusteredOutput-pretty.png}
// 16 16 100 100 0.1
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example demonstrates the use of the
// \doxygen{otb}{MeanShiftSegmentationFilter} class which implements
// filtering and clustering using the mean shift algorithm
// \cite{Comaniciu2002}. For a given pixel, the mean shift will
// build a set of neighboring pixels within a given spatial radius
// and a color range. The spatial and color center of this set is
// then computed and the algorithm iterates with this new spatial and
// color center. The Mean Shift can be used for edge-preserving
// smoothing, or for clustering.
//
// Software Guide : EndLatex
#include "itkMacro.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImageFileWriter.h"
#include "otbPrintableImageFilter.h"
#include "itkRGBPixel.h"
#include "itkScalarToRGBPixelFunctor.h"
#include "itkUnaryFunctorImageFilter.h"
// Software Guide : BeginLatex
//
// We start by including the needed header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbMeanShiftSegmentationFilter.h"
// Software Guide : EndCodeSnippet
int main(int argc, char * argv[])
{
if (argc != 11)
{
std::cerr << "Usage: " << argv[0] << " infname labeledfname clusteredfname labeledpretty clusteredpretty "
<< "spatialRadius rangeRadius minRegionSize maxiter thres" << std::endl;
return EXIT_FAILURE;
}
const char * infname = argv[1];
const char * labeledfname = argv[2];
const char * clusteredfname = argv[3];
const char * labeledpretty = argv[4];
const char * clusteredpretty = argv[5];
const unsigned int spatialRadius = atoi(argv[6]);
const double rangeRadius = atof(argv[7]);
const unsigned int minRegionSize = atoi(argv[8]);
const unsigned int maxiter = atoi(argv[9]);
const double thres = atof(argv[10]);
// Software Guide : BeginLatex
//
// We start by the classical \code{typedef}s needed for reading and
// writing the images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef float PixelType;
typedef unsigned int LabelPixelType;
typedef itk::RGBPixel<unsigned char> ColorPixelType;
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::Image<LabelPixelType, Dimension> LabelImageType;
typedef otb::Image<ColorPixelType, Dimension> RGBImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
typedef otb::StreamingImageFileWriter<LabelImageType> LabelWriterType;
typedef otb::MeanShiftSegmentationFilter<ImageType, LabelImageType, ImageType> FilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We instantiate the filter, the reader, and 2 writers (for the
// labeled and clustered images ):
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
FilterType::Pointer filter = FilterType::New();
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer1 = WriterType::New();
LabelWriterType::Pointer writer2 = LabelWriterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We set the file names for the reader and the writers:
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
reader->SetFileName(infname);
writer1->SetFileName(clusteredfname);
writer2->SetFileName(labeledfname);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now set the parameters for the filter. There are 3 main
// parameters: the spatial radius used for defining the neighborhood,
// the range radius used for defining the interval in the color space
// and the minimum size for the regions to be kept after clustering.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetSpatialBandwidth(spatialRadius);
filter->SetRangeBandwidth(rangeRadius);
filter->SetMinRegionSize(minRegionSize);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Two another parameters can be set the maximum iteration number, which define maximum number of iteration until convergence.
// Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.
// Threshold parameter defines mean-shift vector convergence value. Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetMaxIterationNumber(maxiter);
filter->SetThreshold(thres);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now plug the pipeline and run it.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetInput(reader->GetOutput());
writer1->SetInput(filter->GetClusteredOutput());
writer2->SetInput(filter->GetLabelOutput());
writer1->Update();
writer2->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Figure~\ref{fig:MeanShiftSegmentationFilter} shows the result of applying the mean shift
// to a Quickbird image.
// \begin{figure}
// \center
// \includegraphics[width=0.40\textwidth]{ROI_QB_MUL_1.eps}
// \includegraphics[width=0.40\textwidth]{MSClusteredOutput-pretty.eps}
// \includegraphics[width=0.40\textwidth]{MSLabeledOutput-pretty.eps}
// \itkcaption[Mean Shift]{From top to bottom and left to right:
// Original image, image filtered by
// mean shift after clustering clustering, and labeled image..}
// \label{fig:MeanShiftSegmentationFilter}
// \end{figure}
// Software Guide : EndLatex
typedef otb::PrintableImageFilter<ImageType> PrintableFilterType;
PrintableFilterType::Pointer printableImageFilter = PrintableFilterType::New();
printableImageFilter->SetChannel(1);
printableImageFilter->SetChannel(2);
printableImageFilter->SetChannel(3);
typedef PrintableFilterType::OutputImageType OutputImageType;
typedef otb::ImageFileWriter<OutputImageType> PrettyWriterType;
PrettyWriterType::Pointer prettyWriter = PrettyWriterType::New();
printableImageFilter->SetInput(filter->GetClusteredOutput());
prettyWriter->SetFileName(clusteredpretty);
prettyWriter->SetInput(printableImageFilter->GetOutput());
prettyWriter->Update();
typedef otb::ImageFileWriter<RGBImageType> LabelRGBWriterType;
LabelRGBWriterType::Pointer labelRGBWriter = LabelRGBWriterType::New();
// Label to RGB image
typedef itk::Functor::ScalarToRGBPixelFunctor<LabelPixelType> FunctorType;
typedef itk::UnaryFunctorImageFilter<LabelImageType, RGBImageType, FunctorType> ColorLabelFilterType;
ColorLabelFilterType::Pointer labelToRGB = ColorLabelFilterType::New();
labelToRGB->SetInput(filter->GetLabelOutput());
labelRGBWriter->SetFileName(labeledpretty);
labelRGBWriter->SetInput(labelToRGB->GetOutput());
labelRGBWriter->Update();
return EXIT_SUCCESS;
}
<commit_msg>DOC: doc update.<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {ROI_QB_MUL_1.png}
// OUTPUTS: {MSLabeledOutput.tif}, {MSClusteredOutput.tif} {MSLabeledOutput-pretty.png}, {MSClusteredOutput-pretty.png}
// 16 16 100 100 0.1
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example demonstrates the use of the
// \doxygen{otb}{MeanShiftSegmentationFilter} class which implements
// filtering and clustering using the mean shift algorithm
// \cite{Comaniciu2002}. For a given pixel, the mean shift will
// build a set of neighboring pixels within a given spatial radius
// and a color range. The spatial and color center of this set is
// then computed and the algorithm iterates with this new spatial and
// color center. The Mean Shift can be used for edge-preserving
// smoothing, or for clustering.
//
// Software Guide : EndLatex
#include "itkMacro.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImageFileWriter.h"
#include "otbPrintableImageFilter.h"
#include "itkRGBPixel.h"
#include "itkScalarToRGBPixelFunctor.h"
#include "itkUnaryFunctorImageFilter.h"
// Software Guide : BeginLatex
//
// We start by including the needed header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbMeanShiftSegmentationFilter.h"
// Software Guide : EndCodeSnippet
int main(int argc, char * argv[])
{
if (argc != 11)
{
std::cerr << "Usage: " << argv[0] << " infname labeledfname clusteredfname labeledpretty clusteredpretty "
<< "spatialRadius rangeRadius minRegionSize maxiter thres" << std::endl;
return EXIT_FAILURE;
}
const char * infname = argv[1];
const char * labeledfname = argv[2];
const char * clusteredfname = argv[3];
const char * labeledpretty = argv[4];
const char * clusteredpretty = argv[5];
const unsigned int spatialRadius = atoi(argv[6]);
const double rangeRadius = atof(argv[7]);
const unsigned int minRegionSize = atoi(argv[8]);
const unsigned int maxiter = atoi(argv[9]);
const double thres = atof(argv[10]);
// Software Guide : BeginLatex
//
// We start by the classical \code{typedef}s needed for reading and
// writing the images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef float PixelType;
typedef unsigned int LabelPixelType;
typedef itk::RGBPixel<unsigned char> ColorPixelType;
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::Image<LabelPixelType, Dimension> LabelImageType;
typedef otb::Image<ColorPixelType, Dimension> RGBImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
typedef otb::StreamingImageFileWriter<LabelImageType> LabelWriterType;
typedef otb::MeanShiftSegmentationFilter<ImageType, LabelImageType, ImageType> FilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We instantiate the filter, the reader, and 2 writers (for the
// labeled and clustered images).
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
FilterType::Pointer filter = FilterType::New();
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer1 = WriterType::New();
LabelWriterType::Pointer writer2 = LabelWriterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We set the file names for the reader and the writers:
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
reader->SetFileName(infname);
writer1->SetFileName(clusteredfname);
writer2->SetFileName(labeledfname);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now set the parameters for the filter. There are 3 main
// parameters: the spatial radius used for defining the neighborhood,
// the range radius used for defining the interval in the color space
// and the minimum size for the regions to be kept after clustering.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetSpatialBandwidth(spatialRadius);
filter->SetRangeBandwidth(rangeRadius);
filter->SetMinRegionSize(minRegionSize);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Two another parameters can be set : the maximum iteration number, which defines maximum number of iteration until convergence.
// Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.
// Threshold parameter defines mean-shift vector convergence value. Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetMaxIterationNumber(maxiter);
filter->SetThreshold(thres);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now plug the pipeline and run it.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetInput(reader->GetOutput());
writer1->SetInput(filter->GetClusteredOutput());
writer2->SetInput(filter->GetLabelOutput());
writer1->Update();
writer2->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Figure~\ref{fig:MeanShiftSegmentationFilter} shows the result of applying the mean shift
// to a Quickbird image.
// \begin{figure}
// \center
// \includegraphics[width=0.40\textwidth]{ROI_QB_MUL_1.eps}
// \includegraphics[width=0.40\textwidth]{MSClusteredOutput-pretty.eps}
// \includegraphics[width=0.40\textwidth]{MSLabeledOutput-pretty.eps}
// \itkcaption[Mean Shift]{From top to bottom and left to right:
// Original image, image filtered by
// mean shift after clustering , and labeled image.}
// \label{fig:MeanShiftSegmentationFilter}
// \end{figure}
// Software Guide : EndLatex
typedef otb::PrintableImageFilter<ImageType> PrintableFilterType;
PrintableFilterType::Pointer printableImageFilter = PrintableFilterType::New();
printableImageFilter->SetChannel(1);
printableImageFilter->SetChannel(2);
printableImageFilter->SetChannel(3);
typedef PrintableFilterType::OutputImageType OutputImageType;
typedef otb::ImageFileWriter<OutputImageType> PrettyWriterType;
PrettyWriterType::Pointer prettyWriter = PrettyWriterType::New();
printableImageFilter->SetInput(filter->GetClusteredOutput());
prettyWriter->SetFileName(clusteredpretty);
prettyWriter->SetInput(printableImageFilter->GetOutput());
prettyWriter->Update();
typedef otb::ImageFileWriter<RGBImageType> LabelRGBWriterType;
LabelRGBWriterType::Pointer labelRGBWriter = LabelRGBWriterType::New();
// Label to RGB image
typedef itk::Functor::ScalarToRGBPixelFunctor<LabelPixelType> FunctorType;
typedef itk::UnaryFunctorImageFilter<LabelImageType, RGBImageType, FunctorType> ColorLabelFilterType;
ColorLabelFilterType::Pointer labelToRGB = ColorLabelFilterType::New();
labelToRGB->SetInput(filter->GetLabelOutput());
labelRGBWriter->SetFileName(labeledpretty);
labelRGBWriter->SetInput(labelToRGB->GetOutput());
labelRGBWriter->Update();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
MIT License
Copyright (c) 2017 Alan Tonks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "serial.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int checkPort(std::string port)
{
struct stat stat_buf;
if (stat(port.c_str(), &stat_buf) == 0) return 0;
else return -1;
}
Serial::Serial():Serial(4800, "/dev/ttyUSB0") { } // Delegating constructor
Serial::Serial(speed_t baud, std::string port):Serial(baud,port,true){ } // Delegating constructor
Serial::Serial(speed_t baud, std::string port, bool canon) // Target constructor
{
if (setBaud(baud) != 0) setBaud(4800);
if (checkPort(port) == 0) PORT = port;
else PORT = "/dev/ttyUSB0";
isCanonical = canon;
init();
}
// Open and configure the port
void Serial::init()
{
dev_fd = open(PORT.c_str(), O_RDWR | O_NOCTTY);
if (dev_fd < 0) {
perror("Failed to open device: ");
exit(-1);
}
else isOpen = true;
tcgetattr(dev_fd, &oldConfig);
memset(&terminalConfiguration, 0, sizeof(terminalConfiguration)); // Clear junk from location of terminalConfiguration to start with clean slate
tcgetattr(dev_fd, &terminalConfiguration);
// TERMIOS CONFIGURATION
// BAUDRATE: Integer multiple of 2400
// CRTSCTS: Hardware flow control
// CS8: 8N1
// CLOCAL: No modem control. (local device)
// HUPCL: Generates modem disconnect when port is closed
// CREAD: Receive chars
terminalConfiguration.c_cflag |= (BAUDRATE | CS8 | CLOCAL | HUPCL | CREAD);
// IGNPAR: Ignore parity errors
terminalConfiguration.c_iflag |= IGNPAR;
// 0 for raw output
terminalConfiguration.c_oflag = 0;
// Setting input mode
if (isCanonical == true) {
terminalConfiguration.c_lflag |= (ICANON | ECHO | ECHOE); // Canonical input
}
else {
//Configure non-canonical mode
terminalConfiguration.c_lflag &= ~(ICANON | ECHO | ECHOE); // Disable canonical mode and echo
terminalConfiguration.c_cc[VMIN] = 1; // Minimum number of chars to read before returning
terminalConfiguration.c_cc[VTIME] = 0; // Timeout in deciseconds. 0 to disregard timing between bytes
}
tcflush(dev_fd, TCIFLUSH);
applyNewConfig();
}
int Serial::setBaud(speed_t baud)
{
int status = -1;
switch (baud) {
case 2400:
status = cfsetspeed(&terminalConfiguration, B2400);
BAUDRATE = B2400;
break;
case 4800:
status = cfsetspeed(&terminalConfiguration, B4800);
BAUDRATE = B4800;
break;
case 9600:
status = cfsetspeed(&terminalConfiguration, B9600);
BAUDRATE = B9600;
break;
case 19200:
status = cfsetspeed(&terminalConfiguration, B19200);
BAUDRATE = B19200;
break;
case 38400:
status = cfsetspeed(&terminalConfiguration, B38400);
BAUDRATE = B38400;
break;
case 57600:
status = cfsetspeed(&terminalConfiguration, B57600);
BAUDRATE = B57600;
break;
case 115200:
status = cfsetspeed(&terminalConfiguration, B115200);
BAUDRATE = B115200;
break;
case 230400:
status = cfsetspeed(&terminalConfiguration, B230400);
BAUDRATE = B230400;
break;
default:
std::cout << "Invalid baudrate requested.\n";
return -1;
}
if (status < 0) {
perror("In function setBaud() failed to set requested baudrate: ");
return -1;
}
else {
return status;
}
}
int Serial::applyNewConfig()
{
if (tcsetattr(dev_fd, TCSANOW, &terminalConfiguration) < 0) perror("Could not apply configuration: ");
else return 0;
}
speed_t Serial::getBaud()
{
return cfgetispeed(&terminalConfiguration);
}
termios Serial::getConfig()
{
return terminalConfiguration;
}
// Helper function checks if port is open,
// then flushes the serial line.
int Serial::setupRead()
{
if (!isOpen) return -1;
if (tcflush(dev_fd, TCIOFLUSH < 0)) {
perror("Could not flush line: ");
return -1;
}
else return 0;
}
int Serial::serialRead()
{
return serialRead(255); // Request 255 bytes. Will return when \n is received.
}
int Serial::serialRead(int bytes)
{
if (setupRead() < 0) return -1;
int buf_size = bytes;
char buf[buf_size];
bytesReceived = read(dev_fd, buf, bytes);
if (bytesReceived < 0) perror("Read failed: ");
else buf[bytesReceived] = '\0'; // Null terminated
serialData.assign(buf); // Store as std::string
return bytesReceived;
}
int Serial::flush()
{
return tcflush(dev_fd, TCIOFLUSH);
}
int Serial::serialWrite(std::string str)
{
if (!isOpen) return -1;
int write_status = write(dev_fd, str.c_str(), str.length());
if (write_status < 0) {
perror("Failed to write to port: ");
return -1;
}
else return write_status;
}
std::string Serial::getData()
{
return serialData;
}
Serial::~Serial()
{
tcsetattr(dev_fd, TCSANOW, &oldConfig); // Leave port how we found it
close(dev_fd);
}
<commit_msg>Slight changes to setBaud(), initialize isOpen<commit_after>/*
MIT License
Copyright (c) 2017 Alan Tonks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "serial.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int checkPort(std::string port)
{
struct stat stat_buf;
if (stat(port.c_str(), &stat_buf) == 0) return 0;
else return -1;
}
Serial::Serial():Serial(4800, "/dev/ttyUSB0") { } // Delegating constructor
Serial::Serial(speed_t baud, std::string port):Serial(baud,port,true){ } // Delegating constructor
Serial::Serial(speed_t baud, std::string port, bool canon) // Target constructor
{
if (setBaud(baud) != 0) setBaud(4800);
if (checkPort(port) == 0) PORT = port;
else PORT = "/dev/ttyUSB0";
isCanonical = canon;
isOpen = false;
init();
}
// Open and configure the port
void Serial::init()
{
dev_fd = open(PORT.c_str(), O_RDWR | O_NOCTTY);
if (dev_fd < 0) {
perror("Failed to open device: ");
exit(-1);
}
else isOpen = true;
tcgetattr(dev_fd, &oldConfig);
memset(&terminalConfiguration, 0, sizeof(terminalConfiguration)); // Clear junk from location of terminalConfiguration to start with clean slate
tcgetattr(dev_fd, &terminalConfiguration);
// TERMIOS CONFIGURATION
// BAUDRATE: Integer multiple of 2400
// CRTSCTS: Hardware flow control
// CS8: 8N1
// CLOCAL: No modem control. (local device)
// HUPCL: Generates modem disconnect when port is closed
// CREAD: Receive chars
terminalConfiguration.c_cflag |= (BAUDRATE | CS8 | CLOCAL | HUPCL | CREAD);
// IGNPAR: Ignore parity errors
terminalConfiguration.c_iflag |= IGNPAR;
// 0 for raw output
terminalConfiguration.c_oflag = 0;
// Setting input mode
if (isCanonical == true) {
terminalConfiguration.c_lflag |= (ICANON | ECHO | ECHOE); // Canonical input
}
else {
//Configure non-canonical mode
terminalConfiguration.c_lflag &= ~(ICANON | ECHO | ECHOE); // Disable canonical mode and echo
terminalConfiguration.c_cc[VMIN] = 1; // Minimum number of chars to read before returning
terminalConfiguration.c_cc[VTIME] = 0; // Timeout in deciseconds. 0 to disregard timing between bytes
}
tcflush(dev_fd, TCIFLUSH);
applyNewConfig();
}
int Serial::setBaud(speed_t baud)
{
int status = -1;
switch (baud) {
case 2400:
status = cfsetspeed(&terminalConfiguration, B2400);
BAUDRATE = B2400;
break;
case 4800:
status = cfsetspeed(&terminalConfiguration, B4800);
BAUDRATE = B4800;
break;
case 9600:
status = cfsetspeed(&terminalConfiguration, B9600);
BAUDRATE = B9600;
break;
case 19200:
status = cfsetspeed(&terminalConfiguration, B19200);
BAUDRATE = B19200;
break;
case 38400:
status = cfsetspeed(&terminalConfiguration, B38400);
BAUDRATE = B38400;
break;
case 57600:
status = cfsetspeed(&terminalConfiguration, B57600);
BAUDRATE = B57600;
break;
case 115200:
status = cfsetspeed(&terminalConfiguration, B115200);
BAUDRATE = B115200;
break;
case 230400:
status = cfsetspeed(&terminalConfiguration, B230400);
BAUDRATE = B230400;
break;
default:
std::cout << "Invalid baudrate requested.\n";
return -1;
}
if (status < 0) {
perror("In function setBaud() failed to set requested baudrate: ");
return -1;
}
else {
return status;
}
}
int Serial::applyNewConfig()
{
if (tcsetattr(dev_fd, TCSANOW, &terminalConfiguration) < 0) {
perror("Could not apply configuration");
return -1;
}
else return 0;
}
speed_t Serial::getBaud()
{
return cfgetispeed(&terminalConfiguration);
}
termios Serial::getConfig()
{
return terminalConfiguration;
}
// Helper function checks if port is open,
// then flushes the serial line.
int Serial::setupRead()
{
if (!isOpen) return -1;
if (tcflush(dev_fd, TCIOFLUSH < 0)) {
perror("Could not flush line: ");
return -1;
}
else return 0;
}
int Serial::serialRead()
{
return serialRead(255); // Request 255 bytes. Will return when \n is received.
}
int Serial::serialRead(int bytes)
{
if (setupRead() < 0) return -1;
int buf_size = bytes;
char buf[buf_size];
bytesReceived = read(dev_fd, buf, bytes);
if (bytesReceived < 0) perror("Read failed: ");
else buf[bytesReceived] = '\0'; // Null terminated
serialData.assign(buf); // Store as std::string
return bytesReceived;
}
int Serial::flush()
{
return tcflush(dev_fd, TCIOFLUSH);
}
int Serial::serialWrite(std::string str)
{
if (!isOpen) return -1;
int write_status = write(dev_fd, str.c_str(), str.length());
if (write_status < 0) {
perror("Failed to write to port: ");
return -1;
}
else return write_status;
}
std::string Serial::getData()
{
return serialData;
}
Serial::~Serial()
{
tcsetattr(dev_fd, TCSANOW, &oldConfig); // Leave port how we found it
close(dev_fd);
}
<|endoftext|>
|
<commit_before>#ifndef DISSENT_CONNECTIONS_CSNETWORK_H_GUARD
#define DISSENT_CONNECTIONS_CSNETWORK_H_GUARD
#include <QByteArray>
#include <QSharedPointer>
#include <QVariant>
#include "Connections/Connection.hpp"
#include "Connections/ConnectionManager.hpp"
#include "Connections/ConnectionTable.hpp"
#include "Connections/DefaultNetwork.hpp"
#include "Connections/Id.hpp"
#include "Identity/Group.hpp"
#include "Identity/GroupHolder.hpp"
#include "Identity/PublicIdentity.hpp"
#include "Messaging/RpcHandler.hpp"
#include "CSForwarder.hpp"
namespace Dissent {
namespace ClientServer {
class CSNetwork : public Connections::DefaultNetwork {
public:
typedef Connections::ConnectionManager ConnectionManager;
typedef Connections::Id Id;
typedef Identity::GroupHolder GroupHolder;
typedef Identity::PublicIdentity PublicIdentity;
typedef Messaging::RpcHandler RpcHandler;
typedef Messaging::ISender ISender;
/**
* Constructor
* @param cm connection manager providing id to sender
* @param rpc messaging substrate
* @param group_holder
*/
CSNetwork(const QSharedPointer<ConnectionManager> &cm,
const QSharedPointer<RpcHandler> &rpc,
const QSharedPointer<GroupHolder> &group_holder) :
DefaultNetwork(cm, rpc),
_group_holder(group_holder),
_forwarder(CSForwarder::Get(cm->GetId(), cm->GetConnectionTable(),
rpc, group_holder))
{
}
/**
* Virtual destructor
*/
virtual ~CSNetwork() {}
/**
* Send a notification
* @param id the destination for the request
* @param method the remote method
* @param data the input data for that method
*/
inline virtual void SendNotification(const Id &to, const QString &method,
const QVariant &data)
{
GetRpcHandler()->SendNotification(GetSender(to), method, data);
}
/**
* Send a request
* @param id the destination for the request
* @param method the remote method
* @param data the input data for that method
* @param callback called when the request is complete
*/
virtual void SendRequest(const Id &to, const QString &method,
const QVariant &data, QSharedPointer<ResponseHandler> &callback)
{
GetRpcHandler()->SendRequest(GetSender(to), method, data, callback);
}
/**
* Send a notification -- a request without expecting a response
* @param to id to destination
* @param data message to send to the remote side
*/
inline virtual void Send(const Id &to, const QByteArray &data)
{
DefaultNetwork::Send(GetSender(to), data);
}
/**
* Send a message to all group members
* @param data Data to be sent to all peers
*/
inline virtual void Broadcast(const QByteArray &data)
{
foreach(const PublicIdentity &gc, _group_holder->GetGroup().GetRoster()) {
DefaultNetwork::Send(GetSender(gc.GetId()), data);
}
}
/**
* Returns a copy
*/
virtual Network *Clone() const
{
Network *net = new CSNetwork(GetConnectionManager(),
GetRpcHandler(), _group_holder);
net->SetHeaders(GetHeaders());
net->SetMethod(GetMethod());
return net;
}
protected:
inline QSharedPointer<ISender> GetSender(const Id &to)
{
QSharedPointer<ISender> sender = GetConnection(to);
if(!sender) {
sender = _forwarder->GetSender(to);
}
return sender;
}
private:
QSharedPointer<GroupHolder> _group_holder;
QSharedPointer<CSForwarder> _forwarder;
};
}
}
#endif
<commit_msg>[ClientServer] CSNetwork should be an exact clone so as to not create duplicate Forwarders that when deleted muck with the registered Rpc Method<commit_after>#ifndef DISSENT_CONNECTIONS_CSNETWORK_H_GUARD
#define DISSENT_CONNECTIONS_CSNETWORK_H_GUARD
#include <QByteArray>
#include <QSharedPointer>
#include <QVariant>
#include "Connections/Connection.hpp"
#include "Connections/ConnectionManager.hpp"
#include "Connections/ConnectionTable.hpp"
#include "Connections/DefaultNetwork.hpp"
#include "Connections/Id.hpp"
#include "Identity/Group.hpp"
#include "Identity/GroupHolder.hpp"
#include "Identity/PublicIdentity.hpp"
#include "Messaging/RpcHandler.hpp"
#include "CSForwarder.hpp"
namespace Dissent {
namespace ClientServer {
class CSNetwork : public Connections::DefaultNetwork {
public:
typedef Connections::ConnectionManager ConnectionManager;
typedef Connections::Id Id;
typedef Identity::GroupHolder GroupHolder;
typedef Identity::PublicIdentity PublicIdentity;
typedef Messaging::RpcHandler RpcHandler;
typedef Messaging::ISender ISender;
/**
* Constructor
* @param cm connection manager providing id to sender
* @param rpc messaging substrate
* @param group_holder
*/
CSNetwork(const QSharedPointer<ConnectionManager> &cm,
const QSharedPointer<RpcHandler> &rpc,
const QSharedPointer<GroupHolder> &group_holder) :
DefaultNetwork(cm, rpc),
_group_holder(group_holder),
_forwarder(CSForwarder::Get(cm->GetId(), cm->GetConnectionTable(),
rpc, group_holder))
{
}
/**
* Virtual destructor
*/
virtual ~CSNetwork() {}
/**
* Send a notification
* @param id the destination for the request
* @param method the remote method
* @param data the input data for that method
*/
inline virtual void SendNotification(const Id &to, const QString &method,
const QVariant &data)
{
GetRpcHandler()->SendNotification(GetSender(to), method, data);
}
/**
* Send a request
* @param id the destination for the request
* @param method the remote method
* @param data the input data for that method
* @param callback called when the request is complete
*/
virtual void SendRequest(const Id &to, const QString &method,
const QVariant &data, QSharedPointer<ResponseHandler> &callback)
{
GetRpcHandler()->SendRequest(GetSender(to), method, data, callback);
}
/**
* Send a notification -- a request without expecting a response
* @param to id to destination
* @param data message to send to the remote side
*/
inline virtual void Send(const Id &to, const QByteArray &data)
{
DefaultNetwork::Send(GetSender(to), data);
}
/**
* Send a message to all group members
* @param data Data to be sent to all peers
*/
inline virtual void Broadcast(const QByteArray &data)
{
foreach(const PublicIdentity &gc, _group_holder->GetGroup().GetRoster()) {
DefaultNetwork::Send(GetSender(gc.GetId()), data);
}
}
/**
* Returns a copy
*/
virtual Network *Clone() const
{
return new CSNetwork(*this);
}
protected:
inline QSharedPointer<ISender> GetSender(const Id &to)
{
QSharedPointer<ISender> sender = GetConnection(to);
if(!sender) {
sender = _forwarder->GetSender(to);
}
return sender;
}
private:
QSharedPointer<GroupHolder> _group_holder;
QSharedPointer<CSForwarder> _forwarder;
};
}
}
#endif
<|endoftext|>
|
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#define EIGEN_USE_THREADS
#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <utility>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/util/overflow.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
namespace tensorflow {
template <typename T>
class SparseConcatOp : public OpKernel {
public:
explicit SparseConcatOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("concat_dim", &concat_dim_attr_));
}
void Compute(OpKernelContext* context) override {
OpInputList inds;
OP_REQUIRES_OK(context, context->input_list("indices", &inds));
const int N = inds.size();
for (int i = 0; i < N; i++) {
OP_REQUIRES(context, TensorShapeUtils::IsMatrix(inds[i].shape()),
errors::InvalidArgument(
"Input indices should be a matrix but received shape ",
inds[i].shape().DebugString(), " at position ", i));
}
OpInputList vals;
OP_REQUIRES_OK(context, context->input_list("values", &vals));
OP_REQUIRES(context, vals.size() == N,
errors::InvalidArgument("Expected ", N, " input values, got ",
vals.size()));
for (int i = 0; i < N; i++) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(vals[i].shape()),
errors::InvalidArgument(
"Input values should be a vector but received shape ",
vals[i].shape().DebugString(), " at position ", i));
}
OpInputList shapes;
OP_REQUIRES_OK(context, context->input_list("shapes", &shapes));
OP_REQUIRES(context, shapes.size() == N,
errors::InvalidArgument("Expected ", N, " input shapes, got ",
shapes.size()));
for (int i = 0; i < N; i++) {
int new_num_elements = 1;
bool overflow_ocurred = false;
OP_REQUIRES(context, TensorShapeUtils::IsVector(shapes[i].shape()),
errors::InvalidArgument(
"Input shapes should be a vector but received shape ",
shapes[i].shape().DebugString(), " at position ", i));
auto input_shape_vector = shapes[i].vec<int64>();
for (int j = 0; j < input_shape_vector.size(); j++) {
new_num_elements =
MultiplyWithoutOverflow(new_num_elements, input_shape_vector(j));
if (new_num_elements < 0) {
overflow_ocurred = true;
break;
}
}
OP_REQUIRES(
context, !overflow_ocurred,
errors::Internal("Encountered overflow from large input shape."));
}
const TensorShape input_shape(shapes[0].vec<int64>());
const int input_rank = input_shape.dims();
const int concat_dim = (concat_dim_attr_ < 0)
? input_rank + concat_dim_attr_
: concat_dim_attr_;
OP_REQUIRES(context, concat_dim >= 0 && concat_dim < input_rank,
errors::InvalidArgument("Concat dimension must be in range [",
-input_rank, ", ", input_rank,
"), got ", concat_dim_attr_));
for (int i = 1; i < N; ++i) {
const TensorShape current_shape(shapes[i].vec<int64>());
OP_REQUIRES(
context, current_shape.dims() == input_rank,
errors::InvalidArgument(
"Ranks of all input tensors must match: expected ", input_rank,
" but got ", current_shape.dims(), " at position ", i));
for (int j = 0; j < input_rank; ++j) {
if (j != concat_dim) {
OP_REQUIRES(
context, input_shape.dim_size(j) == current_shape.dim_size(j),
errors::InvalidArgument(
"Input shapes must match: expected ", input_shape.dim_size(j),
" for dimension ", j, " but got ", current_shape.dim_size(j),
" at position ", i));
}
}
}
// The input and output sparse tensors are assumed to be ordered along
// increasing dimension number. But in order for concat to work properly,
// order[0] must be concat_dim. So we will reorder the inputs to the
// concat ordering, concatenate, then reorder back to the standard order.
// We make a deep copy of the input tensors to ensure that the in-place
// reorder doesn't create race conditions for other ops that may be
// concurrently reading the indices and values tensors.
gtl::InlinedVector<int64, 8> std_order(input_rank);
std::iota(std_order.begin(), std_order.end(), 0);
std::vector<int64> concat_order;
concat_order.reserve(input_rank);
concat_order.push_back(concat_dim);
for (int j = 0; j < input_rank; ++j) {
if (j != concat_dim) {
concat_order.push_back(j);
}
}
std::vector<sparse::SparseTensor> sp_inputs;
for (int i = 0; i < N; ++i) {
const TensorShape current_shape(shapes[i].vec<int64>());
sparse::SparseTensor tensor;
OP_REQUIRES_OK(context,
sparse::SparseTensor::Create(
tensor::DeepCopy(inds[i]), tensor::DeepCopy(vals[i]),
current_shape, std_order, &tensor));
sp_inputs.push_back(std::move(tensor));
sp_inputs[i].Reorder<T>(concat_order);
}
sparse::SparseTensor concat = sparse::SparseTensor::Concat<T>(sp_inputs);
concat.Reorder<T>(std_order);
context->set_output(0, concat.indices());
context->set_output(1, concat.values());
Tensor* output_shape_out = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(2, TensorShape({concat.dims()}),
&output_shape_out));
auto output_shape = output_shape_out->vec<int64>();
auto concat_shape = concat.shape();
for (int j = 0; j < concat.dims(); ++j) {
output_shape(j) = concat_shape[j];
}
}
private:
int concat_dim_attr_;
};
#define REGISTER_KERNELS(type) \
REGISTER_KERNEL_BUILDER( \
Name("SparseConcat").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
SparseConcatOp<type>)
TF_CALL_ALL_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS
} // namespace tensorflow
<commit_msg>Fix overflow CHECK issue with `tf.raw_ops.AddManySparseToTensorsMap`.<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#define EIGEN_USE_THREADS
#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <utility>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
namespace tensorflow {
template <typename T>
class SparseConcatOp : public OpKernel {
public:
explicit SparseConcatOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("concat_dim", &concat_dim_attr_));
}
void Compute(OpKernelContext* context) override {
OpInputList inds;
OP_REQUIRES_OK(context, context->input_list("indices", &inds));
const int N = inds.size();
for (int i = 0; i < N; i++) {
OP_REQUIRES(context, TensorShapeUtils::IsMatrix(inds[i].shape()),
errors::InvalidArgument(
"Input indices should be a matrix but received shape ",
inds[i].shape().DebugString(), " at position ", i));
}
OpInputList vals;
OP_REQUIRES_OK(context, context->input_list("values", &vals));
OP_REQUIRES(context, vals.size() == N,
errors::InvalidArgument("Expected ", N, " input values, got ",
vals.size()));
for (int i = 0; i < N; i++) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(vals[i].shape()),
errors::InvalidArgument(
"Input values should be a vector but received shape ",
vals[i].shape().DebugString(), " at position ", i));
}
OpInputList shapes;
OP_REQUIRES_OK(context, context->input_list("shapes", &shapes));
OP_REQUIRES(context, shapes.size() == N,
errors::InvalidArgument("Expected ", N, " input shapes, got ",
shapes.size()));
for (int i = 0; i < N; i++) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(shapes[i].shape()),
errors::InvalidArgument(
"Input shapes should be a vector but received shape ",
shapes[i].shape().DebugString(), " at position ", i));
}
const TensorShape input_shape(shapes[0].vec<int64>());
const int input_rank = input_shape.dims();
const int concat_dim = (concat_dim_attr_ < 0)
? input_rank + concat_dim_attr_
: concat_dim_attr_;
OP_REQUIRES(context, concat_dim >= 0 && concat_dim < input_rank,
errors::InvalidArgument("Concat dimension must be in range [",
-input_rank, ", ", input_rank,
"), got ", concat_dim_attr_));
for (int i = 1; i < N; ++i) {
const TensorShape current_shape(shapes[i].vec<int64>());
OP_REQUIRES(
context, current_shape.dims() == input_rank,
errors::InvalidArgument(
"Ranks of all input tensors must match: expected ", input_rank,
" but got ", current_shape.dims(), " at position ", i));
for (int j = 0; j < input_rank; ++j) {
if (j != concat_dim) {
OP_REQUIRES(
context, input_shape.dim_size(j) == current_shape.dim_size(j),
errors::InvalidArgument(
"Input shapes must match: expected ", input_shape.dim_size(j),
" for dimension ", j, " but got ", current_shape.dim_size(j),
" at position ", i));
}
}
}
// The input and output sparse tensors are assumed to be ordered along
// increasing dimension number. But in order for concat to work properly,
// order[0] must be concat_dim. So we will reorder the inputs to the
// concat ordering, concatenate, then reorder back to the standard order.
// We make a deep copy of the input tensors to ensure that the in-place
// reorder doesn't create race conditions for other ops that may be
// concurrently reading the indices and values tensors.
gtl::InlinedVector<int64, 8> std_order(input_rank);
std::iota(std_order.begin(), std_order.end(), 0);
std::vector<int64> concat_order;
concat_order.reserve(input_rank);
concat_order.push_back(concat_dim);
for (int j = 0; j < input_rank; ++j) {
if (j != concat_dim) {
concat_order.push_back(j);
}
}
std::vector<sparse::SparseTensor> sp_inputs;
for (int i = 0; i < N; ++i) {
const TensorShape current_shape(shapes[i].vec<int64>());
sparse::SparseTensor tensor;
OP_REQUIRES_OK(context,
sparse::SparseTensor::Create(
tensor::DeepCopy(inds[i]), tensor::DeepCopy(vals[i]),
current_shape, std_order, &tensor));
sp_inputs.push_back(std::move(tensor));
sp_inputs[i].Reorder<T>(concat_order);
}
sparse::SparseTensor concat = sparse::SparseTensor::Concat<T>(sp_inputs);
concat.Reorder<T>(std_order);
context->set_output(0, concat.indices());
context->set_output(1, concat.values());
Tensor* output_shape_out = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(2, TensorShape({concat.dims()}),
&output_shape_out));
auto output_shape = output_shape_out->vec<int64>();
auto concat_shape = concat.shape();
for (int j = 0; j < concat.dims(); ++j) {
output_shape(j) = concat_shape[j];
}
}
private:
int concat_dim_attr_;
};
#define REGISTER_KERNELS(type) \
REGISTER_KERNEL_BUILDER( \
Name("SparseConcat").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
SparseConcatOp<type>)
TF_CALL_ALL_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/*-
* Copyright (c) 2012, Achilleas Margaritis
* Copyright (c) 2014, David T. Chisnall
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PEGMATITE_AST_HPP
#define PEGMATITE_AST_HPP
#include <cassert>
#include <list>
#include <unordered_map>
#include <memory>
#include "parser.hpp"
namespace pegmatite {
class ASTNode;
template <class T, bool OPT> class ASTPtr;
template <class T> class ASTList;
template <class T> class BindAST;
/** type of AST node stack.
*/
typedef std::vector<std::unique_ptr<ASTNode>> ASTStack;
#ifdef USE_RTTI
#define PARSELIB_RTTI(thisclass, superclass)
#else
/**
* Define the methods required for pegmatite's lightweight RTTI replacement to
* work. This should be used at the end of the class definition and will
* provide support for safe downcasting.
*/
#define PARSELIB_RTTI(thisclass, superclass) \
friend ASTNode; \
protected: \
virtual char *kind() \
{ \
return thisclass::classKind(); \
} \
static char *classKind() \
{ \
static char thisclass ## id; \
return &thisclass ## id; \
} \
public: \
virtual bool isa(char *x) \
{ \
return (x == kind()) || \
(superclass::isa(x)); \
}
#endif
/**
* Base class for AST nodes.
*/
class ASTNode
{
public:
/**
* Constructs the AST node, with a null parent.
*/
ASTNode() : parent_node(0) {}
/**
* Copying AST nodes is not supported.
*/
ASTNode(const ASTNode&) = delete;
/**
* Destructor does nothing, virtual for subclasses to use.
*/
virtual ~ASTNode() {}
/**
* Returns the parent of this AST node, or `nullptr` if there isn't one
* (either if this is the root, or if it is still in the stack waiting to
* be added to the tree).
*/
ASTNode *parent() const { return parent_node; }
/**
* Interface for constructing the AST node. The input range `r` is the
* range within the source.
*/
virtual void construct(const InputRange &r, ASTStack &st) {}
private:
/**
* The parent AST node.
*/
ASTNode *parent_node;
template <class T, bool OPT> friend class ASTPtr;
template <class T> friend class ASTList;
template <class T> friend class BindAST;
#ifndef USE_RTTI
protected:
/**
* Returns the kind of object class. This is a unique pointer that can be
* tested against pointers returned by classKind() to determine whether
* they can be safely compared.
*/
virtual char *kind() { return classKind(); }
/**
* Returns the unique identifier for this class.
*/
static char *classKind()
{
static char ASTNodeid;
return &ASTNodeid;
}
public:
/**
* Root implementation of the RTTI-replacement for builds not wishing to
* use RTTI. This returns true if `x` is the value returned from
* `classKind()`, or false otherwise.
*/
virtual bool isa(char *x)
{
return x == classKind();
}
/**
* Returns true if this object is an instance of `T`. Note that this
* *only* works with single-inheritance hierarchies. If you wish to use
* multiple inheritance in your AST classes, then you must define
* `USE_RTTI` and use the C++ RTTI mechanism.
*/
template <class T> bool isa()
{
return isa(T::classKind());
}
/**
* Returns a pointer to this object as a pointer to a child class, or
* `nullptr` if the cast would be unsafe.
*
* Note that AST nodes are intended to be always used as unique pointers
* and so the returned object is *only* valid as long as the unique pointer
* is valid.
*/
template <class T> T* get_as()
{
return isa<T>() ? static_cast<T*>(this) : nullptr;
}
#else
public:
template <class T> T* get_as()
{
return dynamic_cast<T*>(this);
}
#endif
};
class ASTMember;
/** type of ast member vector.
*/
/**
* The base class for non-leaf AST nodes. Subclasses can have instances of
* `ASTMember` subclasses as fields and will automatically construct them.
*/
class ASTContainer : public ASTNode
{
public:
/**
* Constructs the container, setting a thread-local value to point to it
* allowing constructors in fields of the subclass to register themselves
* in the members vector.
*/
ASTContainer();
/**
* Asks all members to construct themselves from the stack. The members are
* asked to construct themselves in reverse order from a node stack (`st`).
*
* The input range (`r`) is unused, because the leaf nodes have already
* constructed themselves at this point.
*/
virtual void construct(const InputRange &r, ASTStack &st);
private:
/**
* The type used for tracking the fields of subclasses.
*/
typedef std::vector<ASTMember *> ASTMember_vector;
/**
* References to all of the fields of the subclass that will be
* automatically constructed.
*/
ASTMember_vector members;
friend class ASTMember;
PARSELIB_RTTI(ASTContainer, ASTNode)
};
/** Base class for children of ASTContainer.
*/
class ASTMember
{
public:
/**
* On construction, `ASTMember` sets its `container_node` field to the
* `ASTContainer` currently under construction and registers itself with
* the container, to be notified during the construction phase.
*/
ASTMember();
/**
* Returns the container of which this object is a field.
*/
ASTContainer *container() const { return container_node; }
/**
* Interface for constructing references to AST objects from the stack.
*/
virtual void construct(ASTStack &st) = 0;
private:
/**
* The container that owns this object.
*/
ASTContainer *container_node;
};
/**
* An `ASTPtr` is a wrapper around a pointer to an AST object. It is intended
* to be a member of an `ASTContainer` and will automatically pop the top item
* from the stack and claim it when building the AST..
*/
template <class T, bool OPT = false> class ASTPtr : public ASTMember
{
public:
/**
* Constructs the object in the
*/
ASTPtr() : ptr(nullptr) {}
/** gets the underlying ptr value.
@return the underlying ptr value.
*/
T *get() const
{
return ptr.get();
}
/** auto conversion to the underlying object ptr.
@return the underlying ptr value.
*/
operator T *() const
{
return ptr;
}
/** member access.
@return the underlying ptr value.
*/
T *operator ->() const
{
assert(ptr);
return ptr;
}
/**
* Pops the next matching object from the AST stack `st` and claims it.
*/
virtual void construct(ASTStack &st)
{
//check the stack node
//if (st.empty()) throw std::logic_error("empty AST stack");
//get the node
ASTNode *node = st.back().get();
//get the object
T *obj = node->get_as<T>();
//if the object is optional, simply return
if (OPT)
{
if (!obj) return;
}
//else if the object is mandatory, throw an exception
else
{
//if (!obj) throw std::logic_error("invalid AST node");
}
//set the new object
ptr.reset(obj);
//pop the node from the stack
st.back().release();
st.pop_back();
_set_parent();
}
private:
//ptr
std::unique_ptr<T> ptr;
//set parent of object
void _set_parent()
{
}
};
/** A list of objects.
It pops objects of the given type from the ast stack, until no more objects can be popped.
It assumes ownership of objects.
@param T type of object to control.
*/
template <class T> class ASTList : public ASTMember
{
public:
///list type.
typedef std::list<std::unique_ptr<T>> container;
///the default constructor.
ASTList() {}
/** duplicates the objects of the given list.
@param src source object.
*/
ASTList(const ASTList<T> &src)
{
_dup(src);
}
/** returns the container of objects.
@return the container of objects.
*/
const container &objects() const
{
return child_objects;
}
/**
* Pops objects of type T from the stack (`st`) until no more objects can
* be popped.
*/
virtual void construct(ASTStack &st)
{
for(;;)
{
//if the stack is empty
if (st.empty()) break;
//get the node
ASTNode *node = st.back().get();
//get the object
T *obj = node->get_as<T>();
//if the object was not not of the appropriate type,
//end the list parsing
if (!obj) return;
//remove the node from the stack
st.back().release();
st.pop_back();
//insert the object in the list, in reverse order
child_objects.push_front(std::unique_ptr<T>(obj));
//set the object's parent
obj->parent_node = ASTMember::container();
}
}
private:
//objects
container child_objects;
//duplicate the given list.
void _dup(const ASTList<T> &src)
{
for (auto child : src.child_objects)
{
T *obj = new T(child.get());
child_objects.push_back(obj);
obj->parent_node = ASTMember::container();
}
}
};
/** parses the given input.
@param i input.
@param g root rule of grammar.
@param ws whitespace rule.
@param el list of errors.
@param d user data, passed to the parse procedures.
@return pointer to ast node created, or null if there was an error.
The return object must be deleted by the caller.
*/
std::unique_ptr<ASTNode> parse(Input &i, Rule &g, Rule &ws, ErrorList &el,
const ParserDelegate &d);
/**
* A parser delegate that is responsible for creating AST nodes from the input.
*
* This class manages a mapping from rules in some grammar to AST nodes.
* Instances of the `BindAST` class that are fields of a subclass of this will
* automatically register rules on creation.
*
* The recommended use for this class is to only register rules on construction
* (either explicitly in the constructor or implicitly via `BindAST` members).
* This will give a completely reentrant delegate, which can be used by
* multiple threads to parse multiple inputs safely.
*/
class ASTParserDelegate : ParserDelegate
{
/**
* BindAST is a friend so that it can call the `set_parse_proc()` function,
* which should never be called from anything else.
*/
template <class T> friend class BindAST;
private:
/**
* The map from rules to parsing handlers.
*/
std::unordered_map<Rule*, parse_proc> handlers;
/**
* Registers a callback in this delegate. This should only be called from
* the `static` version of this function.
*/
void set_parse_proc(Rule &r, parse_proc p);
/**
* Registers a callback for a specific rule in the instance of this class
* currently under construction in this thread. This should only ever be
* called by `BindAST` instances.
*/
static void bind_parse_proc(Rule &r, parse_proc p);
public:
/**
* Default constructor, registers this class in thread-local storage so
* that it can be referenced by BindAST fields in subclasses when their
* constructors are run.
*/
ASTParserDelegate();
virtual parse_proc get_parse_proc(Rule &) const;
/**
* Parse an input `i`, starting from rule `g` in the grammar for which
* this is a delegate. The rule `ws` is used as whitespace. Errors are
* returned via the `el` parameter and the root of the AST via the `ast`
* parameter.
*
* This function returns true on a successful parse, or false otherwise.
*/
template <class T> bool parse(Input &i, Rule &g, Rule &ws, ErrorList &el,
std::unique_ptr<T> &ast) const
{
std::unique_ptr<ASTNode> node = pegmatite::parse(i, g, ws, el, *this);
T *n = node->get_as<T>();
if (n)
{
node.release();
ast.reset(n);
return true;
}
return false;
}
};
/**
* The `BindAST` class is responsible for
*/
template <class T> class BindAST
{
public:
/**
* Bind the AST class described in the
*/
BindAST(Rule &r)
{
ASTParserDelegate::bind_parse_proc(r, [](const ParserPosition &b,
const ParserPosition &e, void *d)
{
ASTStack *st = reinterpret_cast<ASTStack *>(d);
T *obj = new T();
obj->construct(InputRange(b, e), *st);
st->push_back(std::unique_ptr<ASTNode>(obj));
});
}
};
} //namespace pegmatite
#endif //PEGMATITE_AST_HPP
<commit_msg>Correctly set the parent from AST pointers.<commit_after>/*-
* Copyright (c) 2012, Achilleas Margaritis
* Copyright (c) 2014, David T. Chisnall
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PEGMATITE_AST_HPP
#define PEGMATITE_AST_HPP
#include <cassert>
#include <list>
#include <unordered_map>
#include <memory>
#include "parser.hpp"
namespace pegmatite {
class ASTNode;
template <class T, bool OPT> class ASTPtr;
template <class T> class ASTList;
template <class T> class BindAST;
/** type of AST node stack.
*/
typedef std::vector<std::unique_ptr<ASTNode>> ASTStack;
#ifdef USE_RTTI
#define PARSELIB_RTTI(thisclass, superclass)
#else
/**
* Define the methods required for pegmatite's lightweight RTTI replacement to
* work. This should be used at the end of the class definition and will
* provide support for safe downcasting.
*/
#define PARSELIB_RTTI(thisclass, superclass) \
friend ASTNode; \
protected: \
virtual char *kind() \
{ \
return thisclass::classKind(); \
} \
static char *classKind() \
{ \
static char thisclass ## id; \
return &thisclass ## id; \
} \
public: \
virtual bool isa(char *x) \
{ \
return (x == kind()) || \
(superclass::isa(x)); \
}
#endif
/**
* Base class for AST nodes.
*/
class ASTNode
{
public:
/**
* Constructs the AST node, with a null parent.
*/
ASTNode() : parent_node(0) {}
/**
* Copying AST nodes is not supported.
*/
ASTNode(const ASTNode&) = delete;
/**
* Destructor does nothing, virtual for subclasses to use.
*/
virtual ~ASTNode() {}
/**
* Returns the parent of this AST node, or `nullptr` if there isn't one
* (either if this is the root, or if it is still in the stack waiting to
* be added to the tree).
*/
ASTNode *parent() const { return parent_node; }
/**
* Interface for constructing the AST node. The input range `r` is the
* range within the source.
*/
virtual void construct(const InputRange &r, ASTStack &st) {}
private:
/**
* The parent AST node.
*/
ASTNode *parent_node;
template <class T, bool OPT> friend class ASTPtr;
template <class T> friend class ASTList;
template <class T> friend class BindAST;
#ifndef USE_RTTI
protected:
/**
* Returns the kind of object class. This is a unique pointer that can be
* tested against pointers returned by classKind() to determine whether
* they can be safely compared.
*/
virtual char *kind() { return classKind(); }
/**
* Returns the unique identifier for this class.
*/
static char *classKind()
{
static char ASTNodeid;
return &ASTNodeid;
}
public:
/**
* Root implementation of the RTTI-replacement for builds not wishing to
* use RTTI. This returns true if `x` is the value returned from
* `classKind()`, or false otherwise.
*/
virtual bool isa(char *x)
{
return x == classKind();
}
/**
* Returns true if this object is an instance of `T`. Note that this
* *only* works with single-inheritance hierarchies. If you wish to use
* multiple inheritance in your AST classes, then you must define
* `USE_RTTI` and use the C++ RTTI mechanism.
*/
template <class T> bool isa()
{
return isa(T::classKind());
}
/**
* Returns a pointer to this object as a pointer to a child class, or
* `nullptr` if the cast would be unsafe.
*
* Note that AST nodes are intended to be always used as unique pointers
* and so the returned object is *only* valid as long as the unique pointer
* is valid.
*/
template <class T> T* get_as()
{
return isa<T>() ? static_cast<T*>(this) : nullptr;
}
#else
public:
template <class T> T* get_as()
{
return dynamic_cast<T*>(this);
}
#endif
};
class ASTMember;
/** type of ast member vector.
*/
/**
* The base class for non-leaf AST nodes. Subclasses can have instances of
* `ASTMember` subclasses as fields and will automatically construct them.
*/
class ASTContainer : public ASTNode
{
public:
/**
* Constructs the container, setting a thread-local value to point to it
* allowing constructors in fields of the subclass to register themselves
* in the members vector.
*/
ASTContainer();
/**
* Asks all members to construct themselves from the stack. The members are
* asked to construct themselves in reverse order from a node stack (`st`).
*
* The input range (`r`) is unused, because the leaf nodes have already
* constructed themselves at this point.
*/
virtual void construct(const InputRange &r, ASTStack &st);
private:
/**
* The type used for tracking the fields of subclasses.
*/
typedef std::vector<ASTMember *> ASTMember_vector;
/**
* References to all of the fields of the subclass that will be
* automatically constructed.
*/
ASTMember_vector members;
friend class ASTMember;
PARSELIB_RTTI(ASTContainer, ASTNode)
};
/** Base class for children of ASTContainer.
*/
class ASTMember
{
public:
/**
* On construction, `ASTMember` sets its `container_node` field to the
* `ASTContainer` currently under construction and registers itself with
* the container, to be notified during the construction phase.
*/
ASTMember();
/**
* Returns the container of which this object is a field.
*/
ASTContainer *container() const { return container_node; }
/**
* Interface for constructing references to AST objects from the stack.
*/
virtual void construct(ASTStack &st) = 0;
protected:
/**
* The container that owns this object.
*/
ASTContainer *container_node;
};
/**
* An `ASTPtr` is a wrapper around a pointer to an AST object. It is intended
* to be a member of an `ASTContainer` and will automatically pop the top item
* from the stack and claim it when building the AST..
*/
template <class T, bool OPT = false> class ASTPtr : public ASTMember
{
public:
/**
* Constructs the object in the
*/
ASTPtr() : ptr(nullptr) {}
/** gets the underlying ptr value.
@return the underlying ptr value.
*/
T *get() const
{
return ptr.get();
}
/** auto conversion to the underlying object ptr.
@return the underlying ptr value.
*/
operator T *() const
{
return ptr;
}
/** member access.
@return the underlying ptr value.
*/
T *operator ->() const
{
assert(ptr);
return ptr;
}
/**
* Pops the next matching object from the AST stack `st` and claims it.
*/
virtual void construct(ASTStack &st)
{
//check the stack node
//if (st.empty()) throw std::logic_error("empty AST stack");
//get the node
ASTNode *node = st.back().get();
//get the object
T *obj = node->get_as<T>();
//if the object is optional, simply return
if (OPT)
{
if (!obj) return;
}
//else if the object is mandatory, throw an exception
else
{
//if (!obj) throw std::logic_error("invalid AST node");
}
//set the new object
ptr.reset(obj);
//pop the node from the stack
st.back().release();
st.pop_back();
ptr->parent_node = container_node;
}
private:
/**
* The node that we are pointing to.
*/
std::unique_ptr<T> ptr;
};
/** A list of objects.
It pops objects of the given type from the ast stack, until no more objects can be popped.
It assumes ownership of objects.
@param T type of object to control.
*/
template <class T> class ASTList : public ASTMember
{
public:
///list type.
typedef std::list<std::unique_ptr<T>> container;
///the default constructor.
ASTList() {}
/** duplicates the objects of the given list.
@param src source object.
*/
ASTList(const ASTList<T> &src)
{
_dup(src);
}
/** returns the container of objects.
@return the container of objects.
*/
const container &objects() const
{
return child_objects;
}
/**
* Pops objects of type T from the stack (`st`) until no more objects can
* be popped.
*/
virtual void construct(ASTStack &st)
{
for(;;)
{
//if the stack is empty
if (st.empty()) break;
//get the node
ASTNode *node = st.back().get();
//get the object
T *obj = node->get_as<T>();
//if the object was not not of the appropriate type,
//end the list parsing
if (!obj) return;
//remove the node from the stack
st.back().release();
st.pop_back();
//insert the object in the list, in reverse order
child_objects.push_front(std::unique_ptr<T>(obj));
//set the object's parent
obj->parent_node = ASTMember::container();
}
}
private:
//objects
container child_objects;
//duplicate the given list.
void _dup(const ASTList<T> &src)
{
for (auto child : src.child_objects)
{
T *obj = new T(child.get());
child_objects.push_back(obj);
obj->parent_node = ASTMember::container();
}
}
};
/** parses the given input.
@param i input.
@param g root rule of grammar.
@param ws whitespace rule.
@param el list of errors.
@param d user data, passed to the parse procedures.
@return pointer to ast node created, or null if there was an error.
The return object must be deleted by the caller.
*/
std::unique_ptr<ASTNode> parse(Input &i, Rule &g, Rule &ws, ErrorList &el,
const ParserDelegate &d);
/**
* A parser delegate that is responsible for creating AST nodes from the input.
*
* This class manages a mapping from rules in some grammar to AST nodes.
* Instances of the `BindAST` class that are fields of a subclass of this will
* automatically register rules on creation.
*
* The recommended use for this class is to only register rules on construction
* (either explicitly in the constructor or implicitly via `BindAST` members).
* This will give a completely reentrant delegate, which can be used by
* multiple threads to parse multiple inputs safely.
*/
class ASTParserDelegate : ParserDelegate
{
/**
* BindAST is a friend so that it can call the `set_parse_proc()` function,
* which should never be called from anything else.
*/
template <class T> friend class BindAST;
private:
/**
* The map from rules to parsing handlers.
*/
std::unordered_map<Rule*, parse_proc> handlers;
/**
* Registers a callback in this delegate. This should only be called from
* the `static` version of this function.
*/
void set_parse_proc(Rule &r, parse_proc p);
/**
* Registers a callback for a specific rule in the instance of this class
* currently under construction in this thread. This should only ever be
* called by `BindAST` instances.
*/
static void bind_parse_proc(Rule &r, parse_proc p);
public:
/**
* Default constructor, registers this class in thread-local storage so
* that it can be referenced by BindAST fields in subclasses when their
* constructors are run.
*/
ASTParserDelegate();
virtual parse_proc get_parse_proc(Rule &) const;
/**
* Parse an input `i`, starting from rule `g` in the grammar for which
* this is a delegate. The rule `ws` is used as whitespace. Errors are
* returned via the `el` parameter and the root of the AST via the `ast`
* parameter.
*
* This function returns true on a successful parse, or false otherwise.
*/
template <class T> bool parse(Input &i, Rule &g, Rule &ws, ErrorList &el,
std::unique_ptr<T> &ast) const
{
std::unique_ptr<ASTNode> node = pegmatite::parse(i, g, ws, el, *this);
T *n = node->get_as<T>();
if (n)
{
node.release();
ast.reset(n);
return true;
}
return false;
}
};
/**
* The `BindAST` class is responsible for
*/
template <class T> class BindAST
{
public:
/**
* Bind the AST class described in the
*/
BindAST(Rule &r)
{
ASTParserDelegate::bind_parse_proc(r, [](const ParserPosition &b,
const ParserPosition &e, void *d)
{
ASTStack *st = reinterpret_cast<ASTStack *>(d);
T *obj = new T();
obj->construct(InputRange(b, e), *st);
st->push_back(std::unique_ptr<ASTNode>(obj));
});
}
};
} //namespace pegmatite
#endif //PEGMATITE_AST_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_aura.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "content/browser/tab_contents/interstitial_page.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "ui/aura/window.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/focus/widget_focus_manager.h"
#include "views/views_delegate.h"
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerAura, public:
NativeTabContentsContainerAura::NativeTabContentsContainerAura(
TabContentsContainer* container)
: container_(container) {
set_id(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW);
}
NativeTabContentsContainerAura::~NativeTabContentsContainerAura() {
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerAura, NativeTabContentsContainer overrides:
void NativeTabContentsContainerAura::AttachContents(TabContents* contents) {
// We need to register the tab contents window with the BrowserContainer so
// that the BrowserContainer is the focused view when the focus is on the
// TabContents window (for the TabContents case).
set_focus_view(this);
Attach(contents->GetNativeView());
}
void NativeTabContentsContainerAura::DetachContents(TabContents* contents) {
// Detach the TabContents. Do this before we unparent the
// TabContentsViewViews so that the window hierarchy is intact for any
// cleanup during Detach().
Detach();
}
void NativeTabContentsContainerAura::SetFastResize(bool fast_resize) {
set_fast_resize(fast_resize);
}
bool NativeTabContentsContainerAura::GetFastResize() const {
return fast_resize();
}
bool NativeTabContentsContainerAura::FastResizeAtLastLayout() const {
return fast_resize_at_last_layout();
}
void NativeTabContentsContainerAura::RenderViewHostChanged(
RenderViewHost* old_host,
RenderViewHost* new_host) {
// If we are focused, we need to pass the focus to the new RenderViewHost.
if (GetFocusManager()->GetFocusedView() == this)
OnFocus();
}
views::View* NativeTabContentsContainerAura::GetView() {
return this;
}
void NativeTabContentsContainerAura::TabContentsFocused(
TabContents* tab_contents) {
views::FocusManager* focus_manager = GetFocusManager();
if (!focus_manager) {
NOTREACHED();
return;
}
focus_manager->SetFocusedView(this);
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerAura, views::View overrides:
bool NativeTabContentsContainerAura::SkipDefaultKeyEventProcessing(
const views::KeyEvent& e) {
// Don't look-up accelerators or tab-traversal if we are showing a non-crashed
// TabContents.
// We'll first give the page a chance to process the key events. If it does
// not process them, they'll be returned to us and we'll treat them as
// accelerators then.
return container_->tab_contents() &&
!container_->tab_contents()->is_crashed();
}
bool NativeTabContentsContainerAura::IsFocusable() const {
// We need to be focusable when our contents is not a view hierarchy, as
// clicking on the contents needs to focus us.
return container_->tab_contents() != NULL;
}
void NativeTabContentsContainerAura::OnFocus() {
if (container_->tab_contents())
container_->tab_contents()->Focus();
}
void NativeTabContentsContainerAura::RequestFocus() {
// This is a hack to circumvent the fact that a the OnFocus() method is not
// invoked when RequestFocus() is called on an already focused view.
// The TabContentsContainer is the view focused when the TabContents has
// focus. When switching between from one tab that has focus to another tab
// that should also have focus, RequestFocus() is invoked one the
// TabContentsContainer. In order to make sure OnFocus() is invoked we need
// to clear the focus before hands.
{
// Disable notifications. Clear focus will assign the focus to the main
// browser window. Because this change of focus was not user requested,
// don't send it to listeners.
views::AutoNativeNotificationDisabler local_notification_disabler;
GetFocusManager()->ClearFocus();
}
View::RequestFocus();
}
void NativeTabContentsContainerAura::AboutToRequestFocusFromTabTraversal(
bool reverse) {
container_->tab_contents()->FocusThroughTabTraversal(reverse);
}
void NativeTabContentsContainerAura::GetAccessibleState(
ui::AccessibleViewState* state) {
state->role = ui::AccessibilityTypes::ROLE_GROUPING;
}
gfx::NativeViewAccessible
NativeTabContentsContainerAura::GetNativeViewAccessible() {
// TODO(beng):
NOTIMPLEMENTED();
return View::GetNativeViewAccessible();
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainer, public:
// static
NativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer(
TabContentsContainer* container) {
return new NativeTabContentsContainerAura(container);
}
<commit_msg>Revert 110950 - views: Fix the include path for views_delegate.h<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_aura.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "content/browser/tab_contents/interstitial_page.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "ui/aura/window.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/focus/widget_focus_manager.h"
#include "ui/views/views_delegate.h"
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerAura, public:
NativeTabContentsContainerAura::NativeTabContentsContainerAura(
TabContentsContainer* container)
: container_(container) {
set_id(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW);
}
NativeTabContentsContainerAura::~NativeTabContentsContainerAura() {
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerAura, NativeTabContentsContainer overrides:
void NativeTabContentsContainerAura::AttachContents(TabContents* contents) {
// We need to register the tab contents window with the BrowserContainer so
// that the BrowserContainer is the focused view when the focus is on the
// TabContents window (for the TabContents case).
set_focus_view(this);
Attach(contents->GetNativeView());
}
void NativeTabContentsContainerAura::DetachContents(TabContents* contents) {
// Detach the TabContents. Do this before we unparent the
// TabContentsViewViews so that the window hierarchy is intact for any
// cleanup during Detach().
Detach();
}
void NativeTabContentsContainerAura::SetFastResize(bool fast_resize) {
set_fast_resize(fast_resize);
}
bool NativeTabContentsContainerAura::GetFastResize() const {
return fast_resize();
}
bool NativeTabContentsContainerAura::FastResizeAtLastLayout() const {
return fast_resize_at_last_layout();
}
void NativeTabContentsContainerAura::RenderViewHostChanged(
RenderViewHost* old_host,
RenderViewHost* new_host) {
// If we are focused, we need to pass the focus to the new RenderViewHost.
if (GetFocusManager()->GetFocusedView() == this)
OnFocus();
}
views::View* NativeTabContentsContainerAura::GetView() {
return this;
}
void NativeTabContentsContainerAura::TabContentsFocused(
TabContents* tab_contents) {
views::FocusManager* focus_manager = GetFocusManager();
if (!focus_manager) {
NOTREACHED();
return;
}
focus_manager->SetFocusedView(this);
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerAura, views::View overrides:
bool NativeTabContentsContainerAura::SkipDefaultKeyEventProcessing(
const views::KeyEvent& e) {
// Don't look-up accelerators or tab-traversal if we are showing a non-crashed
// TabContents.
// We'll first give the page a chance to process the key events. If it does
// not process them, they'll be returned to us and we'll treat them as
// accelerators then.
return container_->tab_contents() &&
!container_->tab_contents()->is_crashed();
}
bool NativeTabContentsContainerAura::IsFocusable() const {
// We need to be focusable when our contents is not a view hierarchy, as
// clicking on the contents needs to focus us.
return container_->tab_contents() != NULL;
}
void NativeTabContentsContainerAura::OnFocus() {
if (container_->tab_contents())
container_->tab_contents()->Focus();
}
void NativeTabContentsContainerAura::RequestFocus() {
// This is a hack to circumvent the fact that a the OnFocus() method is not
// invoked when RequestFocus() is called on an already focused view.
// The TabContentsContainer is the view focused when the TabContents has
// focus. When switching between from one tab that has focus to another tab
// that should also have focus, RequestFocus() is invoked one the
// TabContentsContainer. In order to make sure OnFocus() is invoked we need
// to clear the focus before hands.
{
// Disable notifications. Clear focus will assign the focus to the main
// browser window. Because this change of focus was not user requested,
// don't send it to listeners.
views::AutoNativeNotificationDisabler local_notification_disabler;
GetFocusManager()->ClearFocus();
}
View::RequestFocus();
}
void NativeTabContentsContainerAura::AboutToRequestFocusFromTabTraversal(
bool reverse) {
container_->tab_contents()->FocusThroughTabTraversal(reverse);
}
void NativeTabContentsContainerAura::GetAccessibleState(
ui::AccessibleViewState* state) {
state->role = ui::AccessibilityTypes::ROLE_GROUPING;
}
gfx::NativeViewAccessible
NativeTabContentsContainerAura::GetNativeViewAccessible() {
// TODO(beng):
NOTIMPLEMENTED();
return View::GetNativeViewAccessible();
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainer, public:
// static
NativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer(
TabContentsContainer* container) {
return new NativeTabContentsContainerAura(container);
}
<|endoftext|>
|
<commit_before>/*
* Takes an arbitrary number of tuples as input and calculates the fewest
* possible groups of sets whose combined Cartesian product contains exactly
* those tuples.
*
* Copyright (c) 2012, Dennis Hedback
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <iostream>
#include <iterator>
#include "common.hpp"
void read_tuples(Product &prod)
{
Tuple current_tuple;
std::string current_elem;
for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++)
{
char c = *it;
if (c == ',' || c == '\n')
{
current_tuple.push_back(current_elem);
current_elem.clear();
if (c == '\n')
{
prod.insert(current_tuple);
current_tuple.clear();
}
}
else
{
current_elem += c;
}
}
}
void init_generator(Generator &gen, size_t size)
{
for (unsigned int i = 0; i < size; i++)
gen.push_back(Set());
}
bool product_contains(Product &prod, Tuple const &tuple)
{
return prod.find(tuple) != prod.end();
}
void print_generator(Generator &gen)
{
for (Generator::const_iterator gi = gen.begin(); gi != gen.end(); gi++)
{
for (Set::const_iterator si = gi->begin(); si != gi->end(); si++)
{
std::cout << *si;
if (++si != gi->end())
std::cout << ',';
si--;
}
std::cout << '\n';
}
std::cout << "%%\n";
}
void insert_tuple(Generator &gen, Tuple const &tup)
{
// FIXME: Handle cases where tup.size() != gen.size()
Generator::iterator set = gen.begin();
Tuple::const_iterator elem = tup.begin();
for (; set != gen.end() && elem != tup.end(); set++, elem++)
{
set->insert(*elem);
}
}
bool is_subset(Product &subset, Product &superset)
{
#ifdef USE_HTAB
for (Product::const_iterator subit = subset.begin(); subit != subset.end(); subit++)
{
if (!product_contains(superset, *subit))
{
return false;
}
}
return true;
#else
return std::includes(superset.begin(), superset.end(), subset.begin(), subset.end());
#endif // USE_HTAB
}
void generating_sets(Product &prod)
{
Product ref_prod = prod;
while (prod.size() > 0)
{
Generator gen;
init_generator(gen, prod.begin()->size());
for (Product::iterator prod_it = prod.begin(); prod_it != prod.end();)
{
Generator tmp_gen = gen;
Product tmp_prod;
insert_tuple(tmp_gen, *prod_it);
cartesian_product(tmp_gen, tmp_prod, false);
if (is_subset(tmp_prod, ref_prod))
{
gen = tmp_gen;
prod.erase(prod_it++);
}
else
{
++prod_it;
}
}
print_generator(gen);
}
}
int main(int argc, char *argv[])
{
Product prod;
read_tuples(prod);
generating_sets(prod);
return 0;
}
<commit_msg>Added comments<commit_after>/*
* Takes an arbitrary number of tuples as input and calculates the fewest
* possible groups of sets whose combined Cartesian product contains exactly
* those tuples.
*
* Copyright (c) 2012, Dennis Hedback
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <iostream>
#include <iterator>
#include "common.hpp"
// Reads tuples from input stream and puts them in prod.
void read_tuples(Product &prod)
{
Tuple tup;
std::string elem;
// Read the input stream character by character
for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++)
{
char c = *it;
// Tuple elements are delimited by ',' and tuples are delimited by '\n'
if (c == ',' || c == '\n')
{
// This is the end of the current element, push it into the tuple
// and finalize
tup.push_back(elem);
elem.clear();
if (c == '\n')
{
// This is the end of the current tuple, insert it into the
// product and finalize
prod.insert(tup);
tup.clear();
}
}
else
{
elem += c; // Append character to the current element
}
}
}
// Populates a generator FIXME: This could easily be done in the call to the
// generator's constructor instead
void init_generator(Generator &gen, size_t size)
{
for (unsigned int i = 0; i < size; i++)
gen.push_back(Set());
}
// Does product contains Tuple 'tup'?
bool product_contains(Product &prod, Tuple const &tup)
{
return prod.find(tup) != prod.end();
}
// Prints a generator
void print_generator(Generator &gen)
{
for (Generator::const_iterator gi = gen.begin(); gi != gen.end(); gi++)
{
for (Set::const_iterator si = gi->begin(); si != gi->end(); si++)
{
std::cout << *si;
if (++si != gi->end()) // This is not the last element
std::cout << ','; // Delimit elements with ','
si--;
}
std::cout << '\n'; // Sets are delimited with newline
}
std::cout << "%%\n"; // Generators are delimited with "%%"
}
// Inserts a tuple into a generator
void insert_tuple(Generator &gen, Tuple const &tup)
{
// FIXME: Handle cases where tup.size() != gen.size()
Generator::iterator set = gen.begin();
Tuple::const_iterator elem = tup.begin();
// Insert tup[n] into gen[n]
for (; set != gen.end() && elem != tup.end(); set++, elem++)
{
set->insert(*elem);
}
}
// Is one product a subset of another?
bool is_subset(Product &subset, Product &superset)
{
#ifdef USE_HTAB
// We're using boost::unordered_set so the std::includes algo won't work
for (Product::const_iterator it = subset.begin(); it != subset.end(); it++)
{
if (!product_contains(superset, *it))
{
// If superset does not contain any given tuple of subset, then
// subset is not a subset of superset
return false;
}
}
return true;
#else
// We're using std::set so let's use the std::includes algo
return std::includes(superset.begin(), superset.end(), subset.begin(), subset.end());
#endif // USE_HTAB
}
// Calculate, and print, the groups of generating sets whose combined Cartesian
// products contain exactly the tuples in 'prod'
void generating_sets(Product &prod)
{
Product ref_prod = prod; // Our reference
// Remove a tuple from prod once it's been inserted into a generator, so
// we'll continue until all tuples' been inserted
while (prod.size() > 0)
{
Generator gen; // Current generator
init_generator(gen, prod.begin()->size());
// Iterate over all tuples in prod and try to insert them into gen
for (Product::iterator prod_it = prod.begin(); prod_it != prod.end();)
{
Generator tmp_gen = gen; // Temporary copy of current generator
Product tmp_prod; // Cartesian product of temporary generator
// Insert the tuple into the temporary generator instead of the
// current generator so we can discard the generator if its product
// is not a subset of the input product
insert_tuple(tmp_gen, *prod_it);
// Calculate the Cartesian product of the current generator and put
// it in tmp_prod
cartesian_product(tmp_gen, tmp_prod, false);
// If the temporary product is a subset of the input product, the
// generator is kept and the tuple is deleted from the input
// input product. The goal is that all generators' combined
// Cartesian products contain exactly the tuples in the input
// product. If the Cartesian product of one generator is _not_ a
// subset of the input product, then this is not the case.
if (is_subset(tmp_prod, ref_prod))
{
gen = tmp_gen;
prod.erase(prod_it++);
}
else
{
++prod_it;
}
}
print_generator(gen); // Generator is complete, print it
}
}
int main(int argc, char *argv[])
{
Product prod;
read_tuples(prod);
generating_sets(prod);
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options2/chromeos/cros_language_options_handler.h"
#include <map>
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/user_metrics.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
CrosLanguageOptionsHandler::CrosLanguageOptionsHandler() {
}
CrosLanguageOptionsHandler::~CrosLanguageOptionsHandler() {
}
void CrosLanguageOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
LanguageOptionsHandlerCommon::GetLocalizedValues(localized_strings);
RegisterTitle(localized_strings, "languagePage",
IDS_OPTIONS_SETTINGS_LANGUAGES_AND_INPUT_DIALOG_TITLE);
localized_strings->SetString("ok_button", l10n_util::GetStringUTF16(IDS_OK));
localized_strings->SetString("configure",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_CONFIGURE));
localized_strings->SetString("input_method",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD));
localized_strings->SetString("please_add_another_input_method",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_PLEASE_ADD_ANOTHER_INPUT_METHOD));
localized_strings->SetString("input_method_instructions",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD_INSTRUCTIONS));
localized_strings->SetString("switch_input_methods_hint",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SWITCH_INPUT_METHODS_HINT));
localized_strings->SetString("select_previous_input_method_hint",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SELECT_PREVIOUS_INPUT_METHOD_HINT));
localized_strings->SetString("restart_button",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SIGN_OUT_BUTTON));
localized_strings->SetString("virtual_keyboard_button",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_VIRTUAL_KEYBOARD_BUTTON));
input_method::InputMethodManager* manager =
input_method::InputMethodManager::GetInstance();
// GetSupportedInputMethods() never return NULL.
scoped_ptr<input_method::InputMethodDescriptors> descriptors(
manager->GetSupportedInputMethods());
localized_strings->Set("languageList", GetLanguageList(*descriptors));
localized_strings->Set("inputMethodList", GetInputMethodList(*descriptors));
}
void CrosLanguageOptionsHandler::RegisterMessages() {
LanguageOptionsHandlerCommon::RegisterMessages();
web_ui_->RegisterMessageCallback("inputMethodDisable",
base::Bind(&CrosLanguageOptionsHandler::InputMethodDisableCallback,
base::Unretained(this)));
web_ui_->RegisterMessageCallback("inputMethodEnable",
base::Bind(&CrosLanguageOptionsHandler::InputMethodEnableCallback,
base::Unretained(this)));
web_ui_->RegisterMessageCallback("inputMethodOptionsOpen",
base::Bind(&CrosLanguageOptionsHandler::InputMethodOptionsOpenCallback,
base::Unretained(this)));
web_ui_->RegisterMessageCallback("uiLanguageRestart",
base::Bind(&CrosLanguageOptionsHandler::RestartCallback,
base::Unretained(this)));
}
ListValue* CrosLanguageOptionsHandler::GetInputMethodList(
const input_method::InputMethodDescriptors& descriptors) {
input_method::InputMethodManager* manager =
input_method::InputMethodManager::GetInstance();
ListValue* input_method_list = new ListValue();
for (size_t i = 0; i < descriptors.size(); ++i) {
const input_method::InputMethodDescriptor& descriptor =
descriptors[i];
const std::string language_code =
manager->GetInputMethodUtil()->GetLanguageCodeFromDescriptor(
descriptor);
const std::string display_name =
manager->GetInputMethodUtil()->GetInputMethodDisplayNameFromId(
descriptor.id());
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString("id", descriptor.id());
dictionary->SetString("displayName", display_name);
// One input method can be associated with multiple languages, hence
// we use a dictionary here.
DictionaryValue* language_codes = new DictionaryValue();
language_codes->SetBoolean(language_code, true);
// Check kExtraLanguages to see if there are languages associated with
// this input method. If these are present, add these.
for (size_t j = 0; j < input_method::kExtraLanguagesLength; ++j) {
const std::string extra_input_method_id =
input_method::kExtraLanguages[j].input_method_id;
const std::string extra_language_code =
input_method::kExtraLanguages[j].language_code;
if (extra_input_method_id == descriptor.id()) {
language_codes->SetBoolean(extra_language_code, true);
}
}
dictionary->Set("languageCodeSet", language_codes);
input_method_list->Append(dictionary);
}
return input_method_list;
}
ListValue* CrosLanguageOptionsHandler::GetLanguageList(
const input_method::InputMethodDescriptors& descriptors) {
input_method::InputMethodManager* manager =
input_method::InputMethodManager::GetInstance();
std::set<std::string> language_codes;
// Collect the language codes from the supported input methods.
for (size_t i = 0; i < descriptors.size(); ++i) {
const input_method::InputMethodDescriptor& descriptor = descriptors[i];
const std::string language_code =
manager->GetInputMethodUtil()->GetLanguageCodeFromDescriptor(
descriptor);
language_codes.insert(language_code);
}
// Collect the language codes from kExtraLanguages.
for (size_t i = 0; i < input_method::kExtraLanguagesLength; ++i) {
const char* language_code =
input_method::kExtraLanguages[i].language_code;
language_codes.insert(language_code);
}
// Map of display name -> {language code, native_display_name}.
// In theory, we should be able to create a map that is sorted by
// display names using ICU comparator, but doing it is hard, thus we'll
// use an auxiliary vector to achieve the same result.
typedef std::pair<std::string, string16> LanguagePair;
typedef std::map<string16, LanguagePair> LanguageMap;
LanguageMap language_map;
// The auxiliary vector mentioned above.
std::vector<string16> display_names;
// Build the list of display names, and build the language map.
for (std::set<std::string>::const_iterator iter = language_codes.begin();
iter != language_codes.end(); ++iter) {
const string16 display_name =
input_method::InputMethodUtil::GetLanguageDisplayNameFromCode(*iter);
const string16 native_display_name =
input_method::InputMethodUtil::GetLanguageNativeDisplayNameFromCode(
*iter);
display_names.push_back(display_name);
language_map[display_name] =
std::make_pair(*iter, native_display_name);
}
DCHECK_EQ(display_names.size(), language_map.size());
// Sort display names using locale specific sorter.
l10n_util::SortStrings16(g_browser_process->GetApplicationLocale(),
&display_names);
// Build the language list from the language map.
ListValue* language_list = new ListValue();
for (size_t i = 0; i < display_names.size(); ++i) {
const LanguagePair& pair = language_map[display_names[i]];
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString("code", pair.first);
dictionary->SetString("displayName", display_names[i]);
dictionary->SetString("nativeDisplayName", pair.second);
language_list->Append(dictionary);
}
return language_list;
}
string16 CrosLanguageOptionsHandler::GetProductName() {
return l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME);
}
void CrosLanguageOptionsHandler::SetApplicationLocale(
const std::string& language_code) {
Profile::FromWebUI(web_ui_)->ChangeAppLocale(
language_code, Profile::APP_LOCALE_CHANGED_VIA_SETTINGS);
}
void CrosLanguageOptionsHandler::RestartCallback(const ListValue* args) {
UserMetrics::RecordAction(UserMetricsAction("LanguageOptions_SignOut"));
Browser* browser = Browser::GetBrowserForController(
&web_ui_->tab_contents()->controller(), NULL);
if (browser)
browser->ExecuteCommand(IDC_EXIT);
}
void CrosLanguageOptionsHandler::InputMethodDisableCallback(
const ListValue* args) {
const std::string input_method_id = UTF16ToASCII(ExtractStringValue(args));
const std::string action = base::StringPrintf(
"LanguageOptions_DisableInputMethod_%s", input_method_id.c_str());
UserMetrics::RecordComputedAction(action);
}
void CrosLanguageOptionsHandler::InputMethodEnableCallback(
const ListValue* args) {
const std::string input_method_id = UTF16ToASCII(ExtractStringValue(args));
const std::string action = base::StringPrintf(
"LanguageOptions_EnableInputMethod_%s", input_method_id.c_str());
UserMetrics::RecordComputedAction(action);
}
void CrosLanguageOptionsHandler::InputMethodOptionsOpenCallback(
const ListValue* args) {
const std::string input_method_id = UTF16ToASCII(ExtractStringValue(args));
const std::string action = base::StringPrintf(
"InputMethodOptions_Open_%s", input_method_id.c_str());
UserMetrics::RecordComputedAction(action);
}
} // namespace chromeos
<commit_msg>Options: Fix CrOS that slipped underneath.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options2/chromeos/cros_language_options_handler.h"
#include <map>
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/user_metrics.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
using content::UserMetricsAction;
namespace chromeos {
CrosLanguageOptionsHandler::CrosLanguageOptionsHandler() {
}
CrosLanguageOptionsHandler::~CrosLanguageOptionsHandler() {
}
void CrosLanguageOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
LanguageOptionsHandlerCommon::GetLocalizedValues(localized_strings);
RegisterTitle(localized_strings, "languagePage",
IDS_OPTIONS_SETTINGS_LANGUAGES_AND_INPUT_DIALOG_TITLE);
localized_strings->SetString("ok_button", l10n_util::GetStringUTF16(IDS_OK));
localized_strings->SetString("configure",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_CONFIGURE));
localized_strings->SetString("input_method",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD));
localized_strings->SetString("please_add_another_input_method",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_PLEASE_ADD_ANOTHER_INPUT_METHOD));
localized_strings->SetString("input_method_instructions",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD_INSTRUCTIONS));
localized_strings->SetString("switch_input_methods_hint",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SWITCH_INPUT_METHODS_HINT));
localized_strings->SetString("select_previous_input_method_hint",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SELECT_PREVIOUS_INPUT_METHOD_HINT));
localized_strings->SetString("restart_button",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SIGN_OUT_BUTTON));
localized_strings->SetString("virtual_keyboard_button",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_VIRTUAL_KEYBOARD_BUTTON));
input_method::InputMethodManager* manager =
input_method::InputMethodManager::GetInstance();
// GetSupportedInputMethods() never return NULL.
scoped_ptr<input_method::InputMethodDescriptors> descriptors(
manager->GetSupportedInputMethods());
localized_strings->Set("languageList", GetLanguageList(*descriptors));
localized_strings->Set("inputMethodList", GetInputMethodList(*descriptors));
}
void CrosLanguageOptionsHandler::RegisterMessages() {
LanguageOptionsHandlerCommon::RegisterMessages();
web_ui_->RegisterMessageCallback("inputMethodDisable",
base::Bind(&CrosLanguageOptionsHandler::InputMethodDisableCallback,
base::Unretained(this)));
web_ui_->RegisterMessageCallback("inputMethodEnable",
base::Bind(&CrosLanguageOptionsHandler::InputMethodEnableCallback,
base::Unretained(this)));
web_ui_->RegisterMessageCallback("inputMethodOptionsOpen",
base::Bind(&CrosLanguageOptionsHandler::InputMethodOptionsOpenCallback,
base::Unretained(this)));
web_ui_->RegisterMessageCallback("uiLanguageRestart",
base::Bind(&CrosLanguageOptionsHandler::RestartCallback,
base::Unretained(this)));
}
ListValue* CrosLanguageOptionsHandler::GetInputMethodList(
const input_method::InputMethodDescriptors& descriptors) {
input_method::InputMethodManager* manager =
input_method::InputMethodManager::GetInstance();
ListValue* input_method_list = new ListValue();
for (size_t i = 0; i < descriptors.size(); ++i) {
const input_method::InputMethodDescriptor& descriptor =
descriptors[i];
const std::string language_code =
manager->GetInputMethodUtil()->GetLanguageCodeFromDescriptor(
descriptor);
const std::string display_name =
manager->GetInputMethodUtil()->GetInputMethodDisplayNameFromId(
descriptor.id());
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString("id", descriptor.id());
dictionary->SetString("displayName", display_name);
// One input method can be associated with multiple languages, hence
// we use a dictionary here.
DictionaryValue* language_codes = new DictionaryValue();
language_codes->SetBoolean(language_code, true);
// Check kExtraLanguages to see if there are languages associated with
// this input method. If these are present, add these.
for (size_t j = 0; j < input_method::kExtraLanguagesLength; ++j) {
const std::string extra_input_method_id =
input_method::kExtraLanguages[j].input_method_id;
const std::string extra_language_code =
input_method::kExtraLanguages[j].language_code;
if (extra_input_method_id == descriptor.id()) {
language_codes->SetBoolean(extra_language_code, true);
}
}
dictionary->Set("languageCodeSet", language_codes);
input_method_list->Append(dictionary);
}
return input_method_list;
}
ListValue* CrosLanguageOptionsHandler::GetLanguageList(
const input_method::InputMethodDescriptors& descriptors) {
input_method::InputMethodManager* manager =
input_method::InputMethodManager::GetInstance();
std::set<std::string> language_codes;
// Collect the language codes from the supported input methods.
for (size_t i = 0; i < descriptors.size(); ++i) {
const input_method::InputMethodDescriptor& descriptor = descriptors[i];
const std::string language_code =
manager->GetInputMethodUtil()->GetLanguageCodeFromDescriptor(
descriptor);
language_codes.insert(language_code);
}
// Collect the language codes from kExtraLanguages.
for (size_t i = 0; i < input_method::kExtraLanguagesLength; ++i) {
const char* language_code =
input_method::kExtraLanguages[i].language_code;
language_codes.insert(language_code);
}
// Map of display name -> {language code, native_display_name}.
// In theory, we should be able to create a map that is sorted by
// display names using ICU comparator, but doing it is hard, thus we'll
// use an auxiliary vector to achieve the same result.
typedef std::pair<std::string, string16> LanguagePair;
typedef std::map<string16, LanguagePair> LanguageMap;
LanguageMap language_map;
// The auxiliary vector mentioned above.
std::vector<string16> display_names;
// Build the list of display names, and build the language map.
for (std::set<std::string>::const_iterator iter = language_codes.begin();
iter != language_codes.end(); ++iter) {
const string16 display_name =
input_method::InputMethodUtil::GetLanguageDisplayNameFromCode(*iter);
const string16 native_display_name =
input_method::InputMethodUtil::GetLanguageNativeDisplayNameFromCode(
*iter);
display_names.push_back(display_name);
language_map[display_name] =
std::make_pair(*iter, native_display_name);
}
DCHECK_EQ(display_names.size(), language_map.size());
// Sort display names using locale specific sorter.
l10n_util::SortStrings16(g_browser_process->GetApplicationLocale(),
&display_names);
// Build the language list from the language map.
ListValue* language_list = new ListValue();
for (size_t i = 0; i < display_names.size(); ++i) {
const LanguagePair& pair = language_map[display_names[i]];
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString("code", pair.first);
dictionary->SetString("displayName", display_names[i]);
dictionary->SetString("nativeDisplayName", pair.second);
language_list->Append(dictionary);
}
return language_list;
}
string16 CrosLanguageOptionsHandler::GetProductName() {
return l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME);
}
void CrosLanguageOptionsHandler::SetApplicationLocale(
const std::string& language_code) {
Profile::FromWebUI(web_ui_)->ChangeAppLocale(
language_code, Profile::APP_LOCALE_CHANGED_VIA_SETTINGS);
}
void CrosLanguageOptionsHandler::RestartCallback(const ListValue* args) {
content::RecordAction(UserMetricsAction("LanguageOptions_SignOut"));
Browser* browser = Browser::GetBrowserForController(
&web_ui_->tab_contents()->controller(), NULL);
if (browser)
browser->ExecuteCommand(IDC_EXIT);
}
void CrosLanguageOptionsHandler::InputMethodDisableCallback(
const ListValue* args) {
const std::string input_method_id = UTF16ToASCII(ExtractStringValue(args));
const std::string action = base::StringPrintf(
"LanguageOptions_DisableInputMethod_%s", input_method_id.c_str());
content::RecordComputedAction(action);
}
void CrosLanguageOptionsHandler::InputMethodEnableCallback(
const ListValue* args) {
const std::string input_method_id = UTF16ToASCII(ExtractStringValue(args));
const std::string action = base::StringPrintf(
"LanguageOptions_EnableInputMethod_%s", input_method_id.c_str());
content::RecordComputedAction(action);
}
void CrosLanguageOptionsHandler::InputMethodOptionsOpenCallback(
const ListValue* args) {
const std::string input_method_id = UTF16ToASCII(ExtractStringValue(args));
const std::string action = base::StringPrintf(
"InputMethodOptions_Open_%s", input_method_id.c_str());
content::RecordComputedAction(action);
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Hugh Bailey <obs.jim@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include "dshow-base.hpp"
#include "log.hpp"
#include "../dshowcapture.hpp"
namespace DShow {
void *logParam = NULL;
static LogCallback logCallback = NULL;
void SetLogCallback(LogCallback callback, void *param)
{
logCallback = callback;
logParam = param;
}
static void Log(LogType type, const wchar_t *format, va_list args)
{
wchar_t str[4096];
vswprintf_s(str, 4096, format, args);
if (logCallback)
logCallback(type, str, logParam);
}
void Error(const wchar_t *format, ...)
{
va_list args;
va_start(args, format);
Log(LogType::Error, format, args);
va_end(args);
}
void Warning(const wchar_t *format, ...)
{
va_list args;
va_start(args, format);
Log(LogType::Warning, format, args);
va_end(args);
}
void Info(const wchar_t *format, ...)
{
va_list args;
va_start(args, format);
Log(LogType::Info, format, args);
va_end(args);
}
void Debug(const wchar_t *format, ...)
{
va_list args;
va_start(args, format);
Log(LogType::Debug, format, args);
va_end(args);
}
void ErrorHR(const wchar_t *str, HRESULT hr)
{
Error(L"%s (0x%08lX): %s", str, hr, ConvertHRToEnglish(hr).c_str());
}
void WarningHR(const wchar_t *str, HRESULT hr)
{
Warning(L"%s (0x%08lX): %s", str, hr, ConvertHRToEnglish(hr).c_str());
}
void InfoHR(const wchar_t *str, HRESULT hr)
{
Info(L"%s (0x%08lX): %s", str, hr, ConvertHRToEnglish(hr).c_str());
}
void DebugHR(const wchar_t *str, HRESULT hr)
{
Info(L"%s (0x%08lX): %s", str, hr, ConvertHRToEnglish(hr).c_str());
}
}; /* namespace DShow */
<commit_msg>Fix log level of DebugHR<commit_after>/*
* Copyright (C) 2014 Hugh Bailey <obs.jim@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include "dshow-base.hpp"
#include "log.hpp"
#include "../dshowcapture.hpp"
namespace DShow {
void *logParam = NULL;
static LogCallback logCallback = NULL;
void SetLogCallback(LogCallback callback, void *param)
{
logCallback = callback;
logParam = param;
}
static void Log(LogType type, const wchar_t *format, va_list args)
{
wchar_t str[4096];
vswprintf_s(str, 4096, format, args);
if (logCallback)
logCallback(type, str, logParam);
}
void Error(const wchar_t *format, ...)
{
va_list args;
va_start(args, format);
Log(LogType::Error, format, args);
va_end(args);
}
void Warning(const wchar_t *format, ...)
{
va_list args;
va_start(args, format);
Log(LogType::Warning, format, args);
va_end(args);
}
void Info(const wchar_t *format, ...)
{
va_list args;
va_start(args, format);
Log(LogType::Info, format, args);
va_end(args);
}
void Debug(const wchar_t *format, ...)
{
va_list args;
va_start(args, format);
Log(LogType::Debug, format, args);
va_end(args);
}
void ErrorHR(const wchar_t *str, HRESULT hr)
{
Error(L"%s (0x%08lX): %s", str, hr, ConvertHRToEnglish(hr).c_str());
}
void WarningHR(const wchar_t *str, HRESULT hr)
{
Warning(L"%s (0x%08lX): %s", str, hr, ConvertHRToEnglish(hr).c_str());
}
void InfoHR(const wchar_t *str, HRESULT hr)
{
Info(L"%s (0x%08lX): %s", str, hr, ConvertHRToEnglish(hr).c_str());
}
void DebugHR(const wchar_t *str, HRESULT hr)
{
Debug(L"%s (0x%08lX): %s", str, hr, ConvertHRToEnglish(hr).c_str());
}
}; /* namespace DShow */
<|endoftext|>
|
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/platform/file_system.h"
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/imgutils.h"
#include "libswscale/swscale.h"
#include <dlfcn.h>
}
#include "kernels/ffmpeg_reader.h"
namespace tensorflow {
namespace data {
static mutex mu(LINKER_INITIALIZED);
static unsigned count(0);
void FFmpegReaderInit() {
mutex_lock lock(mu);
count++;
if (count == 1) {
// Register all formats and codecs
av_register_all();
}
}
static int io_read_packet(void *opaque, uint8_t *buf, int buf_size) {
FFmpegReader *r = (FFmpegReader *)opaque;
StringPiece result;
Status status = r->stream_->Read(r->offset_, buf_size, &result, (char *)buf);
if (!(status.ok() || errors::IsOutOfRange(status))) {
return -1;
}
r->offset_ += result.size();
return result.size();
}
static int64_t io_seek(void *opaque, int64_t offset, int whence) {
FFmpegReader *r = (FFmpegReader *)opaque;
uint64 file_size = 0;
Status status = r->stream_->GetFileSize(&file_size);
if (!status.ok()) {
return -1;
}
switch (whence)
{
case SEEK_SET:
if (offset > file_size) {
return -1;
}
r->offset_ = offset;
return r->offset_;
case SEEK_CUR:
if (r->offset_ + offset > file_size) {
return -1;
}
r->offset_ += offset;
return r->offset_;
case SEEK_END:
if (offset > file_size) {
return -1;
}
r->offset_ = file_size - offset;
return r->offset_;
case AVSEEK_SIZE:
return file_size;
default:
break;
}
return -1;
}
Status FFmpegReader::InitializeReader()
{
// Allocate format
if ((format_context_ = avformat_alloc_context()) == NULL) {
return errors::InvalidArgument("could not allocate format context");
}
// Allocate context
if ((io_context_ = avio_alloc_context(NULL, 0, 0, this, io_read_packet, NULL, io_seek)) == NULL) {
return errors::InvalidArgument("could not allocate io context");
}
format_context_->pb = io_context_;
// Open input file, and allocate format context
if (avformat_open_input(&format_context_, filename_.c_str(), NULL, NULL) < 0) {
return errors::InvalidArgument("could not open media file: ", filename_);
}
// Retrieve stream information
if (avformat_find_stream_info(format_context_, NULL) < 0) {
return errors::InvalidArgument("could not find stream information: ", filename_);
}
// Find media stream
if ((stream_index_ = av_find_best_stream(format_context_, MediaType(), -1, -1, NULL, 0)) < 0) {
return errors::InvalidArgument("could not find media stream: ", filename_);
}
AVStream *media_stream = format_context_->streams[stream_index_];
#if LIBAVCODEC_VERSION_MAJOR > 56
// Find decoder for the stream
AVCodec *codec = avcodec_find_decoder(media_stream->codecpar->codec_id);
if (!codec) {
return errors::Internal("could not find media codec: ", media_stream->codecpar->codec_id);
}
// Allocate a codec context for the decoder
codec_context_ = avcodec_alloc_context3(codec);
if (!codec_context_) {
return errors::Internal("could not allocate codec context");
}
// Copy codec parameters from input stream to output codec context
if (avcodec_parameters_to_context(codec_context_, media_stream->codecpar) < 0) {
return errors::Internal("could not copy codec parameters from input stream to output codec context");
}
#else
codec_context_ = media_stream->codec;
// Find decoder for the stream
AVCodec *codec = avcodec_find_decoder(codec_context_->codec_id);
if (!codec) {
return errors::Internal("could not find media codec: ", codec_context_->codec_id);
}
#endif
// Initialize the decoders
// TODO (yongtang): avcodec_open2 is not thread-safe
AVDictionary *opts = NULL;
if (avcodec_open2(codec_context_, codec, &opts) < 0) {
return errors::Internal("could not open codec");
}
// Allocate frame
#if LIBAVCODEC_VERSION_MAJOR > 54
frame_ = av_frame_alloc();
#else
frame_ = avcodec_alloc_frame();
#endif
if (!frame_) {
return errors::Internal("could not allocate frame");
}
// Initialize packet
av_init_packet(&packet_);
packet_.data = NULL;
packet_.size = 0;
return Status::OK();
}
bool FFmpegReader::ReadAhead(bool first)
{
while (packet_more_ || frame_more_) {
while (packet_more_) {
packet_more_ = false;
if (packet_.stream_index == stream_index_) {
int got_frame = 0;
int decoded = DecodeFrame(&got_frame);
if (!frame_more_ && got_frame) {
// This is the cached packet.
ProcessFrame();
packet_more_ = true;
return true;
}
if (decoded >= 0 && got_frame) {
ProcessFrame();
if (packet_.data) {
packet_.data += decoded;
packet_.size -= decoded;
packet_more_ = (packet_.size > 0);
}
return true;
}
}
}
if (frame_more_) {
// If this is not the first time, unref the packet
#if LIBAVCODEC_VERSION_MAJOR > 54
av_packet_unref(&packet_);
#else
// NOTE: libav 9.20 does not need unref or free here.
// av_packet_unref(&packet_);
#endif
frame_more_ = (av_read_frame(format_context_, &packet_) == 0);
if (!frame_more_) {
// Flush out the cached packet
packet_more_ = true;
packet_.data = NULL;
packet_.size = 0;
} else {
// More packet to process
packet_more_ = true;
}
}
}
return false;
}
FFmpegReader::~FFmpegReader() {
#if LIBAVCODEC_VERSION_MAJOR > 54
av_frame_free(&frame_);
#else
avcodec_free_frame(&frame_);
#endif
#if LIBAVCODEC_VERSION_MAJOR > 56
avcodec_free_context(&codec_context_);
#endif
avformat_close_input(&format_context_);
av_free(format_context_);
if (io_context_ != NULL) {
av_free(io_context_);
}
}
} // namespace data
} // namespace tensorflow
<commit_msg>Add option to set FFmpeg log level through environmental variable (#530)<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/platform/file_system.h"
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/imgutils.h"
#include "libavutil/log.h"
#include "libswscale/swscale.h"
#include <dlfcn.h>
}
#include "kernels/ffmpeg_reader.h"
namespace tensorflow {
namespace data {
static mutex mu(LINKER_INITIALIZED);
static unsigned count(0);
void FFmpegReaderInit() {
mutex_lock lock(mu);
count++;
if (count == 1) {
// Set log level if needed
static const struct { const char *name; int level; } log_levels[] = {
{ "quiet" , AV_LOG_QUIET },
{ "panic" , AV_LOG_PANIC },
{ "fatal" , AV_LOG_FATAL },
{ "error" , AV_LOG_ERROR },
{ "warning", AV_LOG_WARNING },
{ "info" , AV_LOG_INFO },
{ "verbose", AV_LOG_VERBOSE },
{ "debug" , AV_LOG_DEBUG },
// { "trace" , AV_LOG_TRACE },
};
const char* log_level_name = getenv("FFMPEG_LOG_LEVEL");
if (log_level_name != nullptr) {
string log_level = log_level_name;
for (size_t i = 0; i < sizeof(log_levels)/sizeof(log_levels[0]); i++) {
if (log_level == log_levels[i].name) {
LOG(INFO) << "FFmpeg log level: " << log_level;
av_log_set_level(log_levels[i].level);
break;
}
}
}
// Register all formats and codecs
av_register_all();
}
}
static int io_read_packet(void *opaque, uint8_t *buf, int buf_size) {
FFmpegReader *r = (FFmpegReader *)opaque;
StringPiece result;
Status status = r->stream_->Read(r->offset_, buf_size, &result, (char *)buf);
if (!(status.ok() || errors::IsOutOfRange(status))) {
return -1;
}
r->offset_ += result.size();
return result.size();
}
static int64_t io_seek(void *opaque, int64_t offset, int whence) {
FFmpegReader *r = (FFmpegReader *)opaque;
uint64 file_size = 0;
Status status = r->stream_->GetFileSize(&file_size);
if (!status.ok()) {
return -1;
}
switch (whence)
{
case SEEK_SET:
if (offset > file_size) {
return -1;
}
r->offset_ = offset;
return r->offset_;
case SEEK_CUR:
if (r->offset_ + offset > file_size) {
return -1;
}
r->offset_ += offset;
return r->offset_;
case SEEK_END:
if (offset > file_size) {
return -1;
}
r->offset_ = file_size - offset;
return r->offset_;
case AVSEEK_SIZE:
return file_size;
default:
break;
}
return -1;
}
Status FFmpegReader::InitializeReader()
{
// Allocate format
if ((format_context_ = avformat_alloc_context()) == NULL) {
return errors::InvalidArgument("could not allocate format context");
}
// Allocate context
if ((io_context_ = avio_alloc_context(NULL, 0, 0, this, io_read_packet, NULL, io_seek)) == NULL) {
return errors::InvalidArgument("could not allocate io context");
}
format_context_->pb = io_context_;
// Open input file, and allocate format context
if (avformat_open_input(&format_context_, filename_.c_str(), NULL, NULL) < 0) {
return errors::InvalidArgument("could not open media file: ", filename_);
}
// Retrieve stream information
if (avformat_find_stream_info(format_context_, NULL) < 0) {
return errors::InvalidArgument("could not find stream information: ", filename_);
}
// Find media stream
if ((stream_index_ = av_find_best_stream(format_context_, MediaType(), -1, -1, NULL, 0)) < 0) {
return errors::InvalidArgument("could not find media stream: ", filename_);
}
AVStream *media_stream = format_context_->streams[stream_index_];
#if LIBAVCODEC_VERSION_MAJOR > 56
// Find decoder for the stream
AVCodec *codec = avcodec_find_decoder(media_stream->codecpar->codec_id);
if (!codec) {
return errors::Internal("could not find media codec: ", media_stream->codecpar->codec_id);
}
// Allocate a codec context for the decoder
codec_context_ = avcodec_alloc_context3(codec);
if (!codec_context_) {
return errors::Internal("could not allocate codec context");
}
// Copy codec parameters from input stream to output codec context
if (avcodec_parameters_to_context(codec_context_, media_stream->codecpar) < 0) {
return errors::Internal("could not copy codec parameters from input stream to output codec context");
}
#else
codec_context_ = media_stream->codec;
// Find decoder for the stream
AVCodec *codec = avcodec_find_decoder(codec_context_->codec_id);
if (!codec) {
return errors::Internal("could not find media codec: ", codec_context_->codec_id);
}
#endif
// Initialize the decoders
// TODO (yongtang): avcodec_open2 is not thread-safe
AVDictionary *opts = NULL;
if (avcodec_open2(codec_context_, codec, &opts) < 0) {
return errors::Internal("could not open codec");
}
// Allocate frame
#if LIBAVCODEC_VERSION_MAJOR > 54
frame_ = av_frame_alloc();
#else
frame_ = avcodec_alloc_frame();
#endif
if (!frame_) {
return errors::Internal("could not allocate frame");
}
// Initialize packet
av_init_packet(&packet_);
packet_.data = NULL;
packet_.size = 0;
return Status::OK();
}
bool FFmpegReader::ReadAhead(bool first)
{
while (packet_more_ || frame_more_) {
while (packet_more_) {
packet_more_ = false;
if (packet_.stream_index == stream_index_) {
int got_frame = 0;
int decoded = DecodeFrame(&got_frame);
if (!frame_more_ && got_frame) {
// This is the cached packet.
ProcessFrame();
packet_more_ = true;
return true;
}
if (decoded >= 0 && got_frame) {
ProcessFrame();
if (packet_.data) {
packet_.data += decoded;
packet_.size -= decoded;
packet_more_ = (packet_.size > 0);
}
return true;
}
}
}
if (frame_more_) {
// If this is not the first time, unref the packet
#if LIBAVCODEC_VERSION_MAJOR > 54
av_packet_unref(&packet_);
#else
// NOTE: libav 9.20 does not need unref or free here.
// av_packet_unref(&packet_);
#endif
frame_more_ = (av_read_frame(format_context_, &packet_) == 0);
if (!frame_more_) {
// Flush out the cached packet
packet_more_ = true;
packet_.data = NULL;
packet_.size = 0;
} else {
// More packet to process
packet_more_ = true;
}
}
}
return false;
}
FFmpegReader::~FFmpegReader() {
#if LIBAVCODEC_VERSION_MAJOR > 54
av_frame_free(&frame_);
#else
avcodec_free_frame(&frame_);
#endif
#if LIBAVCODEC_VERSION_MAJOR > 56
avcodec_free_context(&codec_context_);
#endif
avformat_close_input(&format_context_);
av_free(format_context_);
if (io_context_ != NULL) {
av_free(io_context_);
}
}
} // namespace data
} // namespace tensorflow
<|endoftext|>
|
<commit_before>// Copyright 2016 AUV-IITK
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>
#include <sstream> // for converting the command line parameter to integer
#include <string>
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <stdio.h>
#include <dynamic_reconfigure/server.h>
#include <hardware_camera/cameraConfig.h>
/*! \file
* \brief super short description
*
* Long decription
*/
double rotation_error;
bool flag;
std::string exec(const char *cmd)
{
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
while (!feof(pipe))
{
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
return result;
}
bool checkIfFrontisZero()
{
std::string serialNumber = "243FA8C0";
const char *command = "udevadm info -a -p $(udevadm info -q path -n /dev/video0)";
std::string video0 = exec(command);
if (video0.find(serialNumber))
return true;
return false;
}
cv::Mat rotate(cv::Mat src, double angle)
{
// get rotation matrix for rotating the image around its center
cv::Point2f center(src.cols/2.0, src.rows/2.0);
cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0);
// determine bounding rectangle
cv::Rect bbox = cv::RotatedRect(center,src.size(), angle).boundingRect();
// adjust transformation matrix
rot.at<double>(0,2) += bbox.width/2.0 - center.x;
rot.at<double>(1,2) += bbox.height/2.0 - center.y;
cv::Mat dst;
cv::warpAffine(src, dst, rot, bbox.size());
return dst;
}
// dynamic reconfig
void callback(hardware_camera::cameraConfig &config, double level)
{
ROS_INFO("%s Vide_pub: Reconfigure Request: angle= %f flag= %d", ros::this_node::getName().c_str(),
config.angle, config.flag);
rotation_error = config.angle;
flag = config.flag;
}
/*! member description */
int main(int argc, char **argv)
{
ros::init(argc, argv, "image_publisher");
ros::NodeHandle nh;
// register dynamic reconfig server.
dynamic_reconfigure::Server<hardware_camera::cameraConfig> server;
dynamic_reconfigure::Server<hardware_camera::cameraConfig>::CallbackType f;
f = boost::bind(&callback, _1, _2);
server.setCallback(f);
// get launch file constants
double error_angle; int flag_integer;
nh.getParam("cameras/error_angle", error_angle);
nh.getParam("cameras/flag", flag_integer);
// set launch file constants
hardware_camera::cameraConfig config;
config.angle = error_angle;
config.flag = (flag_integer==1) ? true : false;
callback(config, 0);
std::string bottom_topic_name, front_topic_name, node_name;
int front_camera_number, bottom_camera_number;
front_topic_name = "/varun/sensors/front_camera/image_raw";
bottom_topic_name = "/varun/sensors/bottom_camera/image_raw";
image_transport::ImageTransport it(nh);
image_transport::Publisher front_pub = it.advertise(front_topic_name, 1);
image_transport::Publisher bottom_pub = it.advertise(bottom_topic_name, 1);
if (checkIfFrontisZero())
{
front_camera_number = 0;
bottom_camera_number = 1;
}
else
{
front_camera_number = 1;
bottom_camera_number = 0;
}
cv::VideoCapture front_cap(front_camera_number);
cv::VideoCapture bottom_cap(bottom_camera_number);
cv::Mat front_frame, bottom_frame;
sensor_msgs::ImagePtr front_msg, bottom_msg;
int loopRate = 10;
ros::Rate loop_rate(loopRate);
while (nh.ok())
{
if (flag) {
front_cap >> bottom_frame;
bottom_cap >> front_frame;
} else {
front_cap >> front_frame;
bottom_cap >> bottom_frame;
}
// Check if grabbed frame is actually full with some content
if (!front_frame.empty())
{
cv::Mat final_front_frame = rotate(front_frame, rotation_error);
front_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", final_front_frame).toImageMsg();
front_pub.publish(front_msg);
}
// Check if grabbed frame is actually full with some content
if (!bottom_frame.empty())
{
bottom_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", bottom_frame).toImageMsg();
bottom_pub.publish(bottom_msg);
}
ros::spinOnce();
}
}
<commit_msg>remove lint errors<commit_after>// Copyright 2016 AUV-IITK
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>
#include <sstream> // for converting the command line parameter to integer
#include <string>
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <stdio.h>
#include <dynamic_reconfigure/server.h>
#include <hardware_camera/cameraConfig.h>
/*! \file
* \brief super short description
*
* Long decription
*/
double rotation_error;
bool flag;
std::string exec(const char *cmd)
{
char buffer[128];
std::string result = "";
FILE *pipe = popen(cmd, "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
while (!feof(pipe))
{
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
return result;
}
bool checkIfFrontisZero()
{
std::string serialNumber = "243FA8C0";
const char *command = "udevadm info -a -p $(udevadm info -q path -n /dev/video0)";
std::string video0 = exec(command);
if (video0.find(serialNumber))
return true;
return false;
}
cv::Mat rotate(cv::Mat src, double angle)
{
// get rotation matrix for rotating the image around its center
cv::Point2f center(src.cols / 2.0, src.rows / 2.0);
cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0);
// determine bounding rectangle
cv::Rect bbox = cv::RotatedRect(center, src.size(), angle).boundingRect();
// adjust transformation matrix
rot.at<double>(0, 2) += bbox.width / 2.0 - center.x;
rot.at<double>(1, 2) += bbox.height / 2.0 - center.y;
cv::Mat dst;
cv::warpAffine(src, dst, rot, bbox.size());
return dst;
}
// dynamic reconfig
void callback(hardware_camera::cameraConfig &config, double level)
{
ROS_INFO("%s Vide_pub: Reconfigure Request: angle= %f flag= %d", ros::this_node::getName().c_str(), config.angle,
config.flag);
rotation_error = config.angle;
flag = config.flag;
}
/*! member description */
int main(int argc, char **argv)
{
ros::init(argc, argv, "image_publisher");
ros::NodeHandle nh;
// register dynamic reconfig server.
dynamic_reconfigure::Server<hardware_camera::cameraConfig> server;
dynamic_reconfigure::Server<hardware_camera::cameraConfig>::CallbackType f;
f = boost::bind(&callback, _1, _2);
server.setCallback(f);
// get launch file constants
double error_angle;
int flag_integer;
nh.getParam("cameras/error_angle", error_angle);
nh.getParam("cameras/flag", flag_integer);
// set launch file constants
hardware_camera::cameraConfig config;
config.angle = error_angle;
config.flag = (flag_integer == 1) ? true : false;
callback(config, 0);
std::string bottom_topic_name, front_topic_name, node_name;
int front_camera_number, bottom_camera_number;
front_topic_name = "/varun/sensors/front_camera/image_raw";
bottom_topic_name = "/varun/sensors/bottom_camera/image_raw";
image_transport::ImageTransport it(nh);
image_transport::Publisher front_pub = it.advertise(front_topic_name, 1);
image_transport::Publisher bottom_pub = it.advertise(bottom_topic_name, 1);
if (checkIfFrontisZero())
{
front_camera_number = 0;
bottom_camera_number = 1;
}
else
{
front_camera_number = 1;
bottom_camera_number = 0;
}
cv::VideoCapture front_cap(front_camera_number);
cv::VideoCapture bottom_cap(bottom_camera_number);
cv::Mat front_frame, bottom_frame;
sensor_msgs::ImagePtr front_msg, bottom_msg;
int loopRate = 10;
ros::Rate loop_rate(loopRate);
while (nh.ok())
{
if (flag)
{
front_cap >> bottom_frame;
bottom_cap >> front_frame;
}
else
{
front_cap >> front_frame;
bottom_cap >> bottom_frame;
}
// Check if grabbed frame is actually full with some content
if (!front_frame.empty())
{
cv::Mat final_front_frame = rotate(front_frame, rotation_error);
front_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", final_front_frame).toImageMsg();
front_pub.publish(front_msg);
}
// Check if grabbed frame is actually full with some content
if (!bottom_frame.empty())
{
bottom_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", bottom_frame).toImageMsg();
bottom_pub.publish(bottom_msg);
}
ros::spinOnce();
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/FailableMemoryAllocator.h"
#include "CppUTest/TestTestingFixture.h"
// Allocator must be global. Otherwise, it does not exist when memory leak detector
// reports memory leaks.
static FailableMemoryAllocator failableMallocAllocator("Failable malloc");
TEST_GROUP(FailableMemoryAllocator)
{
TestTestingFixture *fixture;
void setup()
{
fixture = new TestTestingFixture;
failableMallocAllocator.clearFailedAllocations();
setCurrentMallocAllocator(&failableMallocAllocator);
}
void teardown()
{
setCurrentMallocAllocatorToDefault();
delete fixture;
}
};
TEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail)
{
int *memory = (int*)malloc(sizeof(int));
*memory = 1;
CHECK(memory != NULL);
free(memory);
}
TEST(FailableMemoryAllocator, FailFirstMalloc)
{
failableMallocAllocator.failAllocNumber(1);
LONGS_EQUAL(NULL, (int*)malloc(sizeof(int)));
}
TEST(FailableMemoryAllocator, FailSecondAndFourthMalloc)
{
failableMallocAllocator.failAllocNumber(2);
failableMallocAllocator.failAllocNumber(4);
int *memory1 = (int*)malloc(sizeof(int));
int *memory2 = (int*)malloc(sizeof(int));
int *memory3 = (int*)malloc(sizeof(int));
int *memory4 = (int*)malloc(sizeof(int));
CHECK(NULL != memory1);
LONGS_EQUAL(NULL, memory2);
CHECK(NULL != memory3);
LONGS_EQUAL(NULL, memory4);
free(memory1);
free(memory3);
}
static void setUpTooManyFailedMallocs()
{
FailableMemoryAllocator allocator;
for (int i = 0; i <= allocator.MAX_NUMBER_OF_FAILED_ALLOCS; i++)
allocator.failAllocNumber(i + 1);
}
TEST(FailableMemoryAllocator, SettingUpTooManyFailedAllocsWillFail)
{
fixture->setTestFunction(setUpTooManyFailedMallocs);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
fixture->assertPrintContains("Maximum number of failed memory allocations exceeded");
}
<commit_msg>Tests for new<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/FailableMemoryAllocator.h"
#include "CppUTest/TestTestingFixture.h"
// Allocator must be global. Otherwise, it does not exist when memory leak detector
// reports memory leaks.
static FailableMemoryAllocator failableMallocAllocator("failable malloc", "malloc", "free");
static FailableMemoryAllocator failableNewAllocator("failable new", "new", "delete");
TEST_GROUP(FailableMemoryAllocator)
{
TestTestingFixture *fixture;
void setup()
{
fixture = new TestTestingFixture;
failableMallocAllocator.clearFailedAllocations();
failableNewAllocator.clearFailedAllocations();
setCurrentMallocAllocator(&failableMallocAllocator);
setCurrentNewAllocator(&failableNewAllocator);
}
void teardown()
{
setCurrentMallocAllocatorToDefault();
setCurrentNewAllocatorToDefault();
delete fixture;
}
};
TEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail)
{
int *memory = (int*)malloc(sizeof(int));
*memory = 1;
CHECK(memory != NULL);
free(memory);
}
TEST(FailableMemoryAllocator, FailFirstMalloc)
{
failableMallocAllocator.failAllocNumber(1);
LONGS_EQUAL(NULL, (int*)malloc(sizeof(int)));
}
TEST(FailableMemoryAllocator, FailSecondAndFourthMalloc)
{
failableMallocAllocator.failAllocNumber(2);
failableMallocAllocator.failAllocNumber(4);
int *memory1 = (int*)malloc(sizeof(int));
int *memory2 = (int*)malloc(sizeof(int));
int *memory3 = (int*)malloc(sizeof(int));
int *memory4 = (int*)malloc(sizeof(int));
CHECK(NULL != memory1);
LONGS_EQUAL(NULL, memory2);
CHECK(NULL != memory3);
LONGS_EQUAL(NULL, memory4);
free(memory1);
free(memory3);
}
static void _setUpTooManyFailedMallocs()
{
FailableMemoryAllocator allocator;
for (int i = 0; i <= allocator.MAX_NUMBER_OF_FAILED_ALLOCS; i++)
allocator.failAllocNumber(i + 1);
}
TEST(FailableMemoryAllocator, SettingUpTooManyFailedAllocsWillFail)
{
fixture->setTestFunction(_setUpTooManyFailedMallocs);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
fixture->assertPrintContains("Maximum number of failed memory allocations exceeded");
}
TEST(FailableMemoryAllocator, NewWorksNormallyIfNotAskedToFail)
{
int *memory = new int;
*memory = 1;
CHECK(memory != NULL);
delete memory;
}
#if CPPUTEST_USE_STD_CPP_LIB
TEST(FailableMemoryAllocator, FailSecondRaisesException)
{
failableNewAllocator.failAllocNumber(2);
int *memory1 = new int;
CHECK_THROWS(std::bad_alloc, new int);
delete memory1;
}
#endif
TEST(FailableMemoryAllocator, FailSecondAndFourthNewNoThrow)
{
#undef new
failableNewAllocator.failAllocNumber(2);
failableNewAllocator.failAllocNumber(4);
int *memory1 = new (std::nothrow) int;
int *memory2 = new (std::nothrow) int;
int *memory3 = new (std::nothrow) int;
int *memory4 = new (std::nothrow) int;
CHECK(NULL != memory1);
LONGS_EQUAL(NULL, memory2);
CHECK(NULL != memory3);
LONGS_EQUAL(NULL, memory4);
delete memory1;
delete memory3;
}
<|endoftext|>
|
<commit_before>#include "himan_unit.h"
#include "metutil.h"
#define BOOST_TEST_MODULE metutil
using namespace std;
using namespace himan;
const double kEpsilon = 1e-3;
BOOST_AUTO_TEST_CASE(LCL_SLOW)
{
// "slow" calculation of LCL
lcl_t LCL = himan::metutil::LCL_(85000,273.15 + 16.5828, 273.15 + -1.45402);
BOOST_CHECK_CLOSE(LCL.P, 64829.6, kEpsilon);
BOOST_CHECK_CLOSE(LCL.T, 273.15 + -5.01719, kEpsilon);
}
BOOST_AUTO_TEST_CASE(LCL_FAST)
{
// fast calculation of LCL
lcl_t LCL = himan::metutil::LCL_(85000,273.15 + 16.6453, 273.15 + -1.29777);
BOOST_CHECK_CLOSE(LCL.P, 64878.5986, kEpsilon);
BOOST_CHECK_CLOSE(LCL.T, 273.15 + -4.90058, kEpsilon);
}
BOOST_AUTO_TEST_CASE(LCL_SMARTTOOL_COMPATIBILITY)
{
// testing if himan LCL is compatible with smarttool LCL
double T = 16.5828;
double Td = -1.45402;
double P = 850;
lcl_t LCL = himan::metutil::LCL_(P*100, 273.15 + T, 273.15 + Td);
BOOST_CHECK_CLOSE(LCL.P, 100*647.3825, 1);
}
BOOST_AUTO_TEST_CASE(MIXING_RATIO)
{
double TD = 4.2;
double P = 850;
double ratio = metutil::MixingRatio_(273.15 + TD, 100 * P);
BOOST_CHECK_CLOSE(ratio, 6.0955, kEpsilon);
}
BOOST_AUTO_TEST_CASE(SATURATED_MIXING_RATIO)
{
// saturated mixing ratio
double ratio = metutil::MixingRatio_(290, 98000);
BOOST_CHECK_CLOSE(ratio, 12.4395, kEpsilon);
}
BOOST_AUTO_TEST_CASE(ES)
{
// water vapour pressure
double E = metutil::Es_(285);
BOOST_CHECK_CLOSE(E, 1389.859, kEpsilon);
// negative temperatures
E = metutil::Es_(266);
BOOST_CHECK_CLOSE(E, 333.356, kEpsilon);
}
<commit_msg>Unit tests for dewpoint<commit_after>#include "himan_unit.h"
#include "metutil.h"
#define BOOST_TEST_MODULE metutil
using namespace std;
using namespace himan;
const double kEpsilon = 1e-3;
BOOST_AUTO_TEST_CASE(LCL_SLOW)
{
// "slow" calculation of LCL
lcl_t LCL = himan::metutil::LCL_(85000,273.15 + 16.5828, 273.15 + -1.45402);
BOOST_CHECK_CLOSE(LCL.P, 64829.6, kEpsilon);
BOOST_CHECK_CLOSE(LCL.T, 273.15 + -5.01719, kEpsilon);
}
BOOST_AUTO_TEST_CASE(LCL_FAST)
{
// fast calculation of LCL
lcl_t LCL = himan::metutil::LCL_(85000,273.15 + 16.6453, 273.15 + -1.29777);
BOOST_CHECK_CLOSE(LCL.P, 64878.5986, kEpsilon);
BOOST_CHECK_CLOSE(LCL.T, 273.15 + -4.90058, kEpsilon);
}
BOOST_AUTO_TEST_CASE(LCL_SMARTTOOL_COMPATIBILITY)
{
// testing if himan LCL is compatible with smarttool LCL
double T = 16.5828;
double Td = -1.45402;
double P = 850;
lcl_t LCL = himan::metutil::LCL_(P*100, 273.15 + T, 273.15 + Td);
BOOST_CHECK_CLOSE(LCL.P, 100*647.3825, 1);
}
BOOST_AUTO_TEST_CASE(MIXING_RATIO)
{
double TD = 4.2;
double P = 850;
double ratio = metutil::MixingRatio_(273.15 + TD, 100 * P);
BOOST_CHECK_CLOSE(ratio, 6.0955, kEpsilon);
}
BOOST_AUTO_TEST_CASE(SATURATED_MIXING_RATIO)
{
// saturated mixing ratio
double ratio = metutil::MixingRatio_(290, 98000);
BOOST_CHECK_CLOSE(ratio, 12.4395, kEpsilon);
}
BOOST_AUTO_TEST_CASE(ES)
{
// water vapour pressure
double E = metutil::Es_(285);
BOOST_CHECK_CLOSE(E, 1389.859, kEpsilon);
// negative temperatures
E = metutil::Es_(266);
BOOST_CHECK_CLOSE(E, 333.356, kEpsilon);
}
BOOST_AUTO_TEST_CASE(DEWPOINT_HIGH_RH)
{
double TD = metutil::DewPointFromHighRH_(292.5, 92.1);
BOOST_CHECK_CLOSE(TD, 290.9200, kEpsilon);
// negative temperatures
TD = metutil::DewPointFromHighRH_(264, 57.44);
BOOST_CHECK_CLOSE(TD, 255.488, kEpsilon);
}
BOOST_AUTO_TEST_CASE(DEWPOINT_LOW_RH)
{
double TD = metutil::DewPointFromLowRH_(292.5, 22);
BOOST_CHECK_CLOSE(TD, 292.3959, kEpsilon);
// negative temperatures
TD = metutil::DewPointFromLowRH_(264, 42.0);
BOOST_CHECK_CLOSE(TD, 263.9865, kEpsilon);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
const ll infty = 10000000000000007;
struct edge {
int to;
ll cap;
int rev;
};
vector<edge> G[100010];
bool used[100010];
void add_edge(int from, int to, ll cap) {
G[from].push_back((edge){to, cap, (int)G[to].size()});
G[to].push_back((edge){to, 0, (int)G[to].size()-1});
}
ll dfs(int v, int t, ll f) {
if (v == t) return f;
used[v] = true;
for (auto& e : G[v]) {
if (!used[e.to] && e.cap > 0) {
ll d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
ll max_flow(int s, int t) {
ll flow = 0;
while (true) {
fill(used, used+100010, false);
ll f = dfs(s, t, infty);
if (f == 0) return flow;
flow += f;
}
}
int R, C;
string S[100];
int src, dst;
int vertex = 0;
bool valid(int i, int j) {
return (0 <= i && i < R && 0 <= j && j < C && S[i][j] == '.');
}
int num(int i, int j) {
return i * C + j;
}
void add_edge_grid(int i, int j) {
if (!valid(i, j)) return;
int now = num(i, j);
vertex++;
if ((i+j) % 2 == 0) {
for (auto k = 0; k < 4; ++k) {
int x = i + dx[k];
int y = j + dy[k];
if (valid(x, y)) {
add_edge(now, num(x, y), 1);
#if DEBUG == 1
cerr << "add_edge(" << now << ", " << num(x, y) << ", 1)" << endl;
#endif
}
}
add_edge(src, now, 1);
} else {
add_edge(now, dst, 1);
}
}
int main () {
cin >> R >> C;
for (auto i = 0; i < R; ++i) {
cin >> S[i];
}
src = R * C;
dst = R * C + 1;
for (auto i = 0; i < R; ++i) {
for (auto j = 0; j < C; ++j) {
add_edge_grid(i, j);
}
}
ll maxi = max_flow(src, dst);
#if DEBUG == 1
cerr << "vertex = " << vertex << endl;
cerr << "maxi = " << maxi << endl;
#endif
cout << vertex - maxi << endl;
}
<commit_msg>tried C2.cpp to 'C'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 1 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
const ll infty = 10000000000000007;
struct edge {
int to;
ll cap;
int rev;
};
vector<edge> G[100010];
bool used[100010];
void add_edge(int from, int to, ll cap) {
G[from].push_back((edge){to, cap, (int)G[to].size()});
G[to].push_back((edge){to, 0, (int)G[to].size()-1});
}
ll dfs(int v, int t, ll f) {
if (v == t) return f;
used[v] = true;
for (auto& e : G[v]) {
if (!used[e.to] && e.cap > 0) {
ll d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
ll max_flow(int s, int t) {
ll flow = 0;
while (true) {
fill(used, used+100010, false);
ll f = dfs(s, t, infty);
if (f == 0) return flow;
flow += f;
}
}
int R, C;
string S[100];
int src, dst;
int vertex = 0;
bool valid(int i, int j) {
return (0 <= i && i < R && 0 <= j && j < C && S[i][j] == '.');
}
int num(int i, int j) {
return i * C + j;
}
void add_edge_grid(int i, int j) {
if (!valid(i, j)) return;
int now = num(i, j);
vertex++;
if ((i+j) % 2 == 0) {
for (auto k = 0; k < 4; ++k) {
int x = i + dx[k];
int y = j + dy[k];
if (valid(x, y)) {
add_edge(now, num(x, y), 1);
#if DEBUG == 1
cerr << "add_edge(" << now << ", " << num(x, y) << ", 1)" << endl;
#endif
}
}
add_edge(src, now, 1);
} else {
add_edge(now, dst, 1);
}
}
int main () {
cin >> R >> C;
for (auto i = 0; i < R; ++i) {
cin >> S[i];
}
src = R * C;
dst = R * C + 1;
for (auto i = 0; i < R; ++i) {
for (auto j = 0; j < C; ++j) {
add_edge_grid(i, j);
}
}
ll maxi = max_flow(src, dst);
#if DEBUG == 1
cerr << "vertex = " << vertex << endl;
cerr << "maxi = " << maxi << endl;
#endif
cout << vertex - maxi << endl;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/node_bindings.h"
#include <string>
#include <vector>
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/api/locker.h"
#include "atom/common/atom_command_line.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "base/command_line.h"
#include "base/base_paths.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_paths.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
using content::BrowserThread;
// Force all builtin modules to be referenced so they can actually run their
// DSO constructors, see http://git.io/DRIqCg.
#define REFERENCE_MODULE(name) \
extern "C" void _register_ ## name(void); \
void (*fp_register_ ## name)(void) = _register_ ## name
// Electron's builtin modules.
REFERENCE_MODULE(atom_browser_app);
REFERENCE_MODULE(atom_browser_auto_updater);
REFERENCE_MODULE(atom_browser_content_tracing);
REFERENCE_MODULE(atom_browser_dialog);
REFERENCE_MODULE(atom_browser_debugger);
REFERENCE_MODULE(atom_browser_desktop_capturer);
REFERENCE_MODULE(atom_browser_download_item);
REFERENCE_MODULE(atom_browser_menu);
REFERENCE_MODULE(atom_browser_power_monitor);
REFERENCE_MODULE(atom_browser_power_save_blocker);
REFERENCE_MODULE(atom_browser_protocol);
REFERENCE_MODULE(atom_browser_global_shortcut);
REFERENCE_MODULE(atom_browser_render_process_preferences);
REFERENCE_MODULE(atom_browser_session);
REFERENCE_MODULE(atom_browser_system_preferences);
REFERENCE_MODULE(atom_browser_tray);
REFERENCE_MODULE(atom_browser_web_contents);
REFERENCE_MODULE(atom_browser_web_view_manager);
REFERENCE_MODULE(atom_browser_window);
REFERENCE_MODULE(atom_common_asar);
REFERENCE_MODULE(atom_common_clipboard);
REFERENCE_MODULE(atom_common_crash_reporter);
REFERENCE_MODULE(atom_common_native_image);
REFERENCE_MODULE(atom_common_screen);
REFERENCE_MODULE(atom_common_shell);
REFERENCE_MODULE(atom_common_v8_util);
REFERENCE_MODULE(atom_renderer_ipc);
REFERENCE_MODULE(atom_renderer_web_frame);
#undef REFERENCE_MODULE
// The "v8::Function::kLineOffsetNotFound" is exported in node.dll, but the
// linker can not find it, could be a bug of VS.
#if defined(OS_WIN) && !defined(DEBUG)
namespace v8 {
const int Function::kLineOffsetNotFound = -1;
}
#endif
namespace atom {
namespace {
// Empty callback for async handle.
void UvNoOp(uv_async_t* handle) {
}
// Convert the given vector to an array of C-strings. The strings in the
// returned vector are only guaranteed valid so long as the vector of strings
// is not modified.
std::unique_ptr<const char*[]> StringVectorToArgArray(
const std::vector<std::string>& vector) {
std::unique_ptr<const char*[]> array(new const char*[vector.size()]);
for (size_t i = 0; i < vector.size(); ++i) {
array[i] = vector[i].c_str();
}
return array;
}
base::FilePath GetResourcesPath(bool is_browser) {
auto command_line = base::CommandLine::ForCurrentProcess();
base::FilePath exec_path(command_line->GetProgram());
PathService::Get(base::FILE_EXE, &exec_path);
base::FilePath resources_path =
#if defined(OS_MACOSX)
is_browser ? exec_path.DirName().DirName().Append("Resources") :
exec_path.DirName().DirName().DirName().DirName().DirName()
.Append("Resources");
#else
exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
#endif
return resources_path;
}
} // namespace
NodeBindings::NodeBindings(bool is_browser)
: is_browser_(is_browser),
message_loop_(nullptr),
uv_loop_(uv_default_loop()),
embed_closed_(false),
uv_env_(nullptr),
weak_factory_(this) {
}
NodeBindings::~NodeBindings() {
// Quit the embed thread.
embed_closed_ = true;
uv_sem_post(&embed_sem_);
WakeupEmbedThread();
// Wait for everything to be done.
uv_thread_join(&embed_thread_);
// Clear uv.
uv_sem_destroy(&embed_sem_);
}
void NodeBindings::Initialize() {
// Open node's error reporting system for browser process.
node::g_standalone_mode = is_browser_;
node::g_upstream_node_mode = false;
#if defined(OS_LINUX)
// Get real command line in renderer process forked by zygote.
if (!is_browser_)
AtomCommandLine::InitializeFromCommandLine();
#endif
// Init node.
// (we assume node::Init would not modify the parameters under embedded mode).
node::Init(nullptr, nullptr, nullptr, nullptr);
#if defined(OS_WIN)
// uv_init overrides error mode to suppress the default crash dialog, bring
// it back if user wants to show it.
std::unique_ptr<base::Environment> env(base::Environment::Create());
if (env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
SetErrorMode(0);
#endif
}
node::Environment* NodeBindings::CreateEnvironment(
v8::Handle<v8::Context> context) {
auto args = AtomCommandLine::argv();
// Feed node the path to initialization script.
base::FilePath::StringType process_type = is_browser_ ?
FILE_PATH_LITERAL("browser") : FILE_PATH_LITERAL("renderer");
base::FilePath resources_path = GetResourcesPath(is_browser_);
base::FilePath script_path =
resources_path.Append(FILE_PATH_LITERAL("electron.asar"))
.Append(process_type)
.Append(FILE_PATH_LITERAL("init.js"));
std::string script_path_str = script_path.AsUTF8Unsafe();
args.insert(args.begin() + 1, script_path_str.c_str());
std::unique_ptr<const char*[]> c_argv = StringVectorToArgArray(args);
node::Environment* env = node::CreateEnvironment(
context->GetIsolate(), uv_default_loop(), context,
args.size(), c_argv.get(), 0, nullptr);
// Node turns off AutorunMicrotasks, but we need it in web pages to match the
// behavior of Chrome.
if (!is_browser_)
context->GetIsolate()->SetAutorunMicrotasks(true);
mate::Dictionary process(context->GetIsolate(), env->process_object());
process.Set("type", process_type);
process.Set("resourcesPath", resources_path);
// Do not set DOM globals for renderer process.
if (!is_browser_)
process.Set("_noBrowserGlobals", resources_path);
// The path to helper app.
base::FilePath helper_exec_path;
PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
process.Set("helperExecPath", helper_exec_path);
return env;
}
void NodeBindings::LoadEnvironment(node::Environment* env) {
node::LoadEnvironment(env);
mate::EmitEvent(env->isolate(), env->process_object(), "loaded");
}
void NodeBindings::PrepareMessageLoop() {
DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
// Add dummy handle for libuv, otherwise libuv would quit when there is
// nothing to do.
uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp);
// Start worker that will interrupt main loop when having uv events.
uv_sem_init(&embed_sem_, 0);
uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
}
void NodeBindings::RunMessageLoop() {
DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
// The MessageLoop should have been created, remember the one in main thread.
message_loop_ = base::MessageLoop::current();
// Run uv loop for once to give the uv__io_poll a chance to add all events.
UvRunOnce();
}
void NodeBindings::UvRunOnce() {
DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
node::Environment* env = uv_env();
// Use Locker in browser process.
mate::Locker locker(env->isolate());
v8::HandleScope handle_scope(env->isolate());
// Enter node context while dealing with uv events.
v8::Context::Scope context_scope(env->context());
// Perform microtask checkpoint after running JavaScript.
v8::MicrotasksScope script_scope(env->isolate(),
v8::MicrotasksScope::kRunMicrotasks);
// Deal with uv events.
int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
if (r == 0 || uv_loop_->stop_flag != 0)
message_loop_->QuitWhenIdle(); // Quit from uv.
// Tell the worker thread to continue polling.
uv_sem_post(&embed_sem_);
}
void NodeBindings::WakeupMainThread() {
DCHECK(message_loop_);
message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,
weak_factory_.GetWeakPtr()));
}
void NodeBindings::WakeupEmbedThread() {
uv_async_send(&dummy_uv_handle_);
}
// static
void NodeBindings::EmbedThreadRunner(void *arg) {
NodeBindings* self = static_cast<NodeBindings*>(arg);
while (true) {
// Wait for the main loop to deal with events.
uv_sem_wait(&self->embed_sem_);
if (self->embed_closed_)
break;
// Wait for something to happen in uv loop.
// Note that the PollEvents() is implemented by derived classes, so when
// this class is being destructed the PollEvents() would not be available
// anymore. Because of it we must make sure we only invoke PollEvents()
// when this class is alive.
self->PollEvents();
if (self->embed_closed_)
break;
// Deal with event in main thread.
self->WakeupMainThread();
}
}
} // namespace atom
<commit_msg>Remove unneeded libuv callback<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/node_bindings.h"
#include <string>
#include <vector>
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/api/locker.h"
#include "atom/common/atom_command_line.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "base/command_line.h"
#include "base/base_paths.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_paths.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
using content::BrowserThread;
// Force all builtin modules to be referenced so they can actually run their
// DSO constructors, see http://git.io/DRIqCg.
#define REFERENCE_MODULE(name) \
extern "C" void _register_ ## name(void); \
void (*fp_register_ ## name)(void) = _register_ ## name
// Electron's builtin modules.
REFERENCE_MODULE(atom_browser_app);
REFERENCE_MODULE(atom_browser_auto_updater);
REFERENCE_MODULE(atom_browser_content_tracing);
REFERENCE_MODULE(atom_browser_dialog);
REFERENCE_MODULE(atom_browser_debugger);
REFERENCE_MODULE(atom_browser_desktop_capturer);
REFERENCE_MODULE(atom_browser_download_item);
REFERENCE_MODULE(atom_browser_menu);
REFERENCE_MODULE(atom_browser_power_monitor);
REFERENCE_MODULE(atom_browser_power_save_blocker);
REFERENCE_MODULE(atom_browser_protocol);
REFERENCE_MODULE(atom_browser_global_shortcut);
REFERENCE_MODULE(atom_browser_render_process_preferences);
REFERENCE_MODULE(atom_browser_session);
REFERENCE_MODULE(atom_browser_system_preferences);
REFERENCE_MODULE(atom_browser_tray);
REFERENCE_MODULE(atom_browser_web_contents);
REFERENCE_MODULE(atom_browser_web_view_manager);
REFERENCE_MODULE(atom_browser_window);
REFERENCE_MODULE(atom_common_asar);
REFERENCE_MODULE(atom_common_clipboard);
REFERENCE_MODULE(atom_common_crash_reporter);
REFERENCE_MODULE(atom_common_native_image);
REFERENCE_MODULE(atom_common_screen);
REFERENCE_MODULE(atom_common_shell);
REFERENCE_MODULE(atom_common_v8_util);
REFERENCE_MODULE(atom_renderer_ipc);
REFERENCE_MODULE(atom_renderer_web_frame);
#undef REFERENCE_MODULE
// The "v8::Function::kLineOffsetNotFound" is exported in node.dll, but the
// linker can not find it, could be a bug of VS.
#if defined(OS_WIN) && !defined(DEBUG)
namespace v8 {
const int Function::kLineOffsetNotFound = -1;
}
#endif
namespace atom {
namespace {
// Convert the given vector to an array of C-strings. The strings in the
// returned vector are only guaranteed valid so long as the vector of strings
// is not modified.
std::unique_ptr<const char*[]> StringVectorToArgArray(
const std::vector<std::string>& vector) {
std::unique_ptr<const char*[]> array(new const char*[vector.size()]);
for (size_t i = 0; i < vector.size(); ++i) {
array[i] = vector[i].c_str();
}
return array;
}
base::FilePath GetResourcesPath(bool is_browser) {
auto command_line = base::CommandLine::ForCurrentProcess();
base::FilePath exec_path(command_line->GetProgram());
PathService::Get(base::FILE_EXE, &exec_path);
base::FilePath resources_path =
#if defined(OS_MACOSX)
is_browser ? exec_path.DirName().DirName().Append("Resources") :
exec_path.DirName().DirName().DirName().DirName().DirName()
.Append("Resources");
#else
exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
#endif
return resources_path;
}
} // namespace
NodeBindings::NodeBindings(bool is_browser)
: is_browser_(is_browser),
message_loop_(nullptr),
uv_loop_(uv_default_loop()),
embed_closed_(false),
uv_env_(nullptr),
weak_factory_(this) {
}
NodeBindings::~NodeBindings() {
// Quit the embed thread.
embed_closed_ = true;
uv_sem_post(&embed_sem_);
WakeupEmbedThread();
// Wait for everything to be done.
uv_thread_join(&embed_thread_);
// Clear uv.
uv_sem_destroy(&embed_sem_);
}
void NodeBindings::Initialize() {
// Open node's error reporting system for browser process.
node::g_standalone_mode = is_browser_;
node::g_upstream_node_mode = false;
#if defined(OS_LINUX)
// Get real command line in renderer process forked by zygote.
if (!is_browser_)
AtomCommandLine::InitializeFromCommandLine();
#endif
// Init node.
// (we assume node::Init would not modify the parameters under embedded mode).
node::Init(nullptr, nullptr, nullptr, nullptr);
#if defined(OS_WIN)
// uv_init overrides error mode to suppress the default crash dialog, bring
// it back if user wants to show it.
std::unique_ptr<base::Environment> env(base::Environment::Create());
if (env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
SetErrorMode(0);
#endif
}
node::Environment* NodeBindings::CreateEnvironment(
v8::Handle<v8::Context> context) {
auto args = AtomCommandLine::argv();
// Feed node the path to initialization script.
base::FilePath::StringType process_type = is_browser_ ?
FILE_PATH_LITERAL("browser") : FILE_PATH_LITERAL("renderer");
base::FilePath resources_path = GetResourcesPath(is_browser_);
base::FilePath script_path =
resources_path.Append(FILE_PATH_LITERAL("electron.asar"))
.Append(process_type)
.Append(FILE_PATH_LITERAL("init.js"));
std::string script_path_str = script_path.AsUTF8Unsafe();
args.insert(args.begin() + 1, script_path_str.c_str());
std::unique_ptr<const char*[]> c_argv = StringVectorToArgArray(args);
node::Environment* env = node::CreateEnvironment(
context->GetIsolate(), uv_default_loop(), context,
args.size(), c_argv.get(), 0, nullptr);
// Node turns off AutorunMicrotasks, but we need it in web pages to match the
// behavior of Chrome.
if (!is_browser_)
context->GetIsolate()->SetAutorunMicrotasks(true);
mate::Dictionary process(context->GetIsolate(), env->process_object());
process.Set("type", process_type);
process.Set("resourcesPath", resources_path);
// Do not set DOM globals for renderer process.
if (!is_browser_)
process.Set("_noBrowserGlobals", resources_path);
// The path to helper app.
base::FilePath helper_exec_path;
PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
process.Set("helperExecPath", helper_exec_path);
return env;
}
void NodeBindings::LoadEnvironment(node::Environment* env) {
node::LoadEnvironment(env);
mate::EmitEvent(env->isolate(), env->process_object(), "loaded");
}
void NodeBindings::PrepareMessageLoop() {
DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
// Add dummy handle for libuv, otherwise libuv would quit when there is
// nothing to do.
uv_async_init(uv_loop_, &dummy_uv_handle_, nullptr);
// Start worker that will interrupt main loop when having uv events.
uv_sem_init(&embed_sem_, 0);
uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
}
void NodeBindings::RunMessageLoop() {
DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
// The MessageLoop should have been created, remember the one in main thread.
message_loop_ = base::MessageLoop::current();
// Run uv loop for once to give the uv__io_poll a chance to add all events.
UvRunOnce();
}
void NodeBindings::UvRunOnce() {
DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
node::Environment* env = uv_env();
// Use Locker in browser process.
mate::Locker locker(env->isolate());
v8::HandleScope handle_scope(env->isolate());
// Enter node context while dealing with uv events.
v8::Context::Scope context_scope(env->context());
// Perform microtask checkpoint after running JavaScript.
v8::MicrotasksScope script_scope(env->isolate(),
v8::MicrotasksScope::kRunMicrotasks);
// Deal with uv events.
int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
if (r == 0 || uv_loop_->stop_flag != 0)
message_loop_->QuitWhenIdle(); // Quit from uv.
// Tell the worker thread to continue polling.
uv_sem_post(&embed_sem_);
}
void NodeBindings::WakeupMainThread() {
DCHECK(message_loop_);
message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,
weak_factory_.GetWeakPtr()));
}
void NodeBindings::WakeupEmbedThread() {
uv_async_send(&dummy_uv_handle_);
}
// static
void NodeBindings::EmbedThreadRunner(void *arg) {
NodeBindings* self = static_cast<NodeBindings*>(arg);
while (true) {
// Wait for the main loop to deal with events.
uv_sem_wait(&self->embed_sem_);
if (self->embed_closed_)
break;
// Wait for something to happen in uv loop.
// Note that the PollEvents() is implemented by derived classes, so when
// this class is being destructed the PollEvents() would not be available
// anymore. Because of it we must make sure we only invoke PollEvents()
// when this class is alive.
self->PollEvents();
if (self->embed_closed_)
break;
// Deal with event in main thread.
self->WakeupMainThread();
}
}
} // namespace atom
<|endoftext|>
|
<commit_before>#include "Memory.h"
#include <vector>
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <cassert>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>
#include "Type.h"
#include "Runtime.h"
#include "GasMeter.h"
#include "Endianness.h"
#include "RuntimeManager.h"
namespace dev
{
namespace eth
{
namespace jit
{
Memory::Memory(RuntimeManager& _runtimeManager, GasMeter& _gasMeter):
RuntimeHelper(_runtimeManager), // TODO: RuntimeHelper not needed
m_gasMeter(_gasMeter)
{
llvm::Type* resizeArgs[] = {Type::RuntimePtr, Type::WordPtr};
m_resize = llvm::Function::Create(llvm::FunctionType::get(Type::BytePtr, resizeArgs, false), llvm::Function::ExternalLinkage, "mem_resize", getModule());
llvm::AttrBuilder attrBuilder;
attrBuilder.addAttribute(llvm::Attribute::NoAlias).addAttribute(llvm::Attribute::NoCapture).addAttribute(llvm::Attribute::NonNull).addAttribute(llvm::Attribute::ReadOnly);
m_resize->setAttributes(llvm::AttributeSet::get(m_resize->getContext(), 1, attrBuilder));
m_require = createRequireFunc(_gasMeter);
m_loadWord = createFunc(false, Type::Word, _gasMeter);
m_storeWord = createFunc(true, Type::Word, _gasMeter);
m_storeByte = createFunc(true, Type::Byte, _gasMeter);
}
llvm::Function* Memory::createRequireFunc(GasMeter& _gasMeter)
{
llvm::Type* argTypes[] = {Type::RuntimePtr, Type::Word, Type::Word};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "mem.require", getModule());
auto rt = func->arg_begin();
rt->setName("rt");
auto offset = rt->getNextNode();
offset->setName("offset");
auto size = offset->getNextNode();
size->setName("size");
auto preBB = llvm::BasicBlock::Create(func->getContext(), "Pre", func);
auto checkBB = llvm::BasicBlock::Create(func->getContext(), "Check", func);
auto resizeBB = llvm::BasicBlock::Create(func->getContext(), "Resize", func);
auto returnBB = llvm::BasicBlock::Create(func->getContext(), "Return", func);
InsertPointGuard guard(m_builder); // Restores insert point at function exit
// BB "Pre": Ignore checks with size 0
m_builder.SetInsertPoint(preBB);
auto sizeIsZero = m_builder.CreateICmpEQ(size, Constant::get(0));
m_builder.CreateCondBr(sizeIsZero, returnBB, checkBB);
// BB "Check"
m_builder.SetInsertPoint(checkBB);
auto uaddWO = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::uadd_with_overflow, Type::Word);
auto uaddRes = m_builder.CreateCall2(uaddWO, offset, size, "res");
auto sizeRequired = m_builder.CreateExtractValue(uaddRes, 0, "sizeReq");
auto overflow1 = m_builder.CreateExtractValue(uaddRes, 1, "overflow1");
auto rtPtr = getRuntimeManager().getRuntimePtr();
auto sizePtr = m_builder.CreateStructGEP(rtPtr, 4);
auto currSize = m_builder.CreateLoad(sizePtr, "currSize");
auto tooSmall = m_builder.CreateICmpULE(currSize, sizeRequired, "tooSmall");
auto resizeNeeded = m_builder.CreateOr(tooSmall, overflow1, "resizeNeeded");
m_builder.CreateCondBr(resizeNeeded, resizeBB, returnBB); // OPT branch weights?
// BB "Resize"
m_builder.SetInsertPoint(resizeBB);
// Check gas first
uaddRes = m_builder.CreateCall2(uaddWO, sizeRequired, Constant::get(31), "res");
auto wordsRequired = m_builder.CreateExtractValue(uaddRes, 0);
auto overflow2 = m_builder.CreateExtractValue(uaddRes, 1, "overflow2");
auto overflow = m_builder.CreateOr(overflow1, overflow2, "overflow");
wordsRequired = m_builder.CreateSelect(overflow, Constant::get(-1), wordsRequired);
wordsRequired = m_builder.CreateUDiv(wordsRequired, Constant::get(32), "wordsReq");
sizeRequired = m_builder.CreateMul(wordsRequired, Constant::get(32), "roundedSizeReq");
auto words = m_builder.CreateUDiv(currSize, Constant::get(32), "words"); // size is always 32*k
auto newWords = m_builder.CreateSub(wordsRequired, words, "addtionalWords");
_gasMeter.countMemory(newWords);
// Resize
m_builder.CreateStore(sizeRequired, sizePtr);
auto newData = m_builder.CreateCall2(m_resize, rt, sizePtr, "newData");
auto dataPtr = m_builder.CreateStructGEP(rtPtr, 3);
m_builder.CreateStore(newData, dataPtr);
m_builder.CreateBr(returnBB);
// BB "Return"
m_builder.SetInsertPoint(returnBB);
m_builder.CreateRetVoid();
return func;
}
llvm::Function* Memory::createFunc(bool _isStore, llvm::Type* _valueType, GasMeter&)
{
auto isWord = _valueType == Type::Word;
llvm::Type* storeArgs[] = {Type::RuntimePtr, Type::Word, _valueType};
llvm::Type* loadArgs[] = {Type::RuntimePtr, Type::Word};
auto name = _isStore ? isWord ? "mstore" : "mstore8" : "mload";
auto funcType = _isStore ? llvm::FunctionType::get(Type::Void, storeArgs, false) : llvm::FunctionType::get(Type::Word, loadArgs, false);
auto func = llvm::Function::Create(funcType, llvm::Function::PrivateLinkage, name, getModule());
InsertPointGuard guard(m_builder); // Restores insert point at function exit
m_builder.SetInsertPoint(llvm::BasicBlock::Create(func->getContext(), {}, func));
auto rt = func->arg_begin();
rt->setName("rt");
auto index = rt->getNextNode();
index->setName("index");
auto valueSize = _valueType->getPrimitiveSizeInBits() / 8;
this->require(index, Constant::get(valueSize));
auto ptr = getBytePtr(index);
if (isWord)
ptr = m_builder.CreateBitCast(ptr, Type::WordPtr, "wordPtr");
if (_isStore)
{
llvm::Value* value = index->getNextNode();
value->setName("value");
if (isWord)
value = Endianness::toBE(m_builder, value);
m_builder.CreateStore(value, ptr);
m_builder.CreateRetVoid();
}
else
{
llvm::Value* ret = m_builder.CreateLoad(ptr);
ret = Endianness::toNative(m_builder, ret);
m_builder.CreateRet(ret);
}
return func;
}
llvm::Value* Memory::loadWord(llvm::Value* _addr)
{
return createCall(m_loadWord, {getRuntimeManager().getRuntimePtr(), _addr});
}
void Memory::storeWord(llvm::Value* _addr, llvm::Value* _word)
{
createCall(m_storeWord, {getRuntimeManager().getRuntimePtr(), _addr, _word});
}
void Memory::storeByte(llvm::Value* _addr, llvm::Value* _word)
{
auto byte = m_builder.CreateTrunc(_word, Type::Byte, "byte");
createCall(m_storeByte, {getRuntimeManager().getRuntimePtr(), _addr, byte});
}
llvm::Value* Memory::getData()
{
auto rtPtr = getRuntimeManager().getRuntimePtr();
auto dataPtr = m_builder.CreateStructGEP(rtPtr, 3);
return m_builder.CreateLoad(dataPtr, "data");
}
llvm::Value* Memory::getSize()
{
auto rtPtr = getRuntimeManager().getRuntimePtr();
auto sizePtr = m_builder.CreateStructGEP(rtPtr, 4);
return m_builder.CreateLoad(sizePtr, "size");
}
llvm::Value* Memory::getBytePtr(llvm::Value* _index)
{
auto idx = m_builder.CreateTrunc(_index, Type::Size, "idx"); // Never allow memory index be a type bigger than i64
return m_builder.CreateGEP(getData(), idx, "ptr");
}
void Memory::require(llvm::Value* _offset, llvm::Value* _size)
{
createCall(m_require, {getRuntimeManager().getRuntimePtr(), _offset, _size});
}
void Memory::copyBytes(llvm::Value* _srcPtr, llvm::Value* _srcSize, llvm::Value* _srcIdx,
llvm::Value* _destMemIdx, llvm::Value* _reqBytes)
{
require(_destMemIdx, _reqBytes);
// Additional copy cost
// TODO: This round ups to 32 happens in many places
auto copyWords = m_builder.CreateUDiv(m_builder.CreateAdd(_reqBytes, Constant::get(31)), Constant::get(32));
m_gasMeter.countCopy(copyWords);
// Algorithm:
// isOutsideData = idx256 >= size256
// idx64 = trunc idx256
// size64 = trunc size256
// dataLeftSize = size64 - idx64 // safe if not isOutsideData
// reqBytes64 = trunc _reqBytes // require() handles large values
// bytesToCopy0 = select(reqBytes64 > dataLeftSize, dataSizeLeft, reqBytes64) // min
// bytesToCopy = select(isOutsideData, 0, bytesToCopy0)
auto isOutsideData = m_builder.CreateICmpUGE(_srcIdx, _srcSize);
auto idx64 = m_builder.CreateTrunc(_srcIdx, Type::lowPrecision);
auto size64 = m_builder.CreateTrunc(_srcSize, Type::lowPrecision);
auto dataLeftSize = m_builder.CreateNUWSub(size64, idx64);
auto reqBytes64 = m_builder.CreateTrunc(_reqBytes, Type::lowPrecision);
auto outOfBound = m_builder.CreateICmpUGT(reqBytes64, dataLeftSize);
auto bytesToCopyInner = m_builder.CreateSelect(outOfBound, dataLeftSize, reqBytes64);
auto zero64 = llvm::ConstantInt::get(Type::lowPrecision, 0); // TODO: Cache common constants
auto bytesToCopy = m_builder.CreateSelect(isOutsideData, zero64, bytesToCopyInner);
auto src = m_builder.CreateGEP(_srcPtr, idx64, "src");
auto dstIdx = m_builder.CreateTrunc(_destMemIdx, Type::Size, "dstIdx"); // Never allow memory index be a type bigger than i64
auto dst = m_builder.CreateGEP(getData(), dstIdx, "dst");
m_builder.CreateMemCpy(dst, src, bytesToCopy, 0);
}
}
}
}
extern "C"
{
using namespace dev::eth::jit;
EXPORT byte* mem_resize(Runtime* _rt, i256* _size) // TODO: Use uint64 as size OR use realloc in LLVM IR
{
auto size = _size->a; // Trunc to 64-bit
auto& memory = _rt->getMemory();
memory.resize(size);
return memory.data();
}
}
<commit_msg>Do not check memory requirements when size is 0<commit_after>#include "Memory.h"
#include <vector>
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <cassert>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>
#include "Type.h"
#include "Runtime.h"
#include "GasMeter.h"
#include "Endianness.h"
#include "RuntimeManager.h"
namespace dev
{
namespace eth
{
namespace jit
{
Memory::Memory(RuntimeManager& _runtimeManager, GasMeter& _gasMeter):
RuntimeHelper(_runtimeManager), // TODO: RuntimeHelper not needed
m_gasMeter(_gasMeter)
{
llvm::Type* resizeArgs[] = {Type::RuntimePtr, Type::WordPtr};
m_resize = llvm::Function::Create(llvm::FunctionType::get(Type::BytePtr, resizeArgs, false), llvm::Function::ExternalLinkage, "mem_resize", getModule());
llvm::AttrBuilder attrBuilder;
attrBuilder.addAttribute(llvm::Attribute::NoAlias).addAttribute(llvm::Attribute::NoCapture).addAttribute(llvm::Attribute::NonNull).addAttribute(llvm::Attribute::ReadOnly);
m_resize->setAttributes(llvm::AttributeSet::get(m_resize->getContext(), 1, attrBuilder));
m_require = createRequireFunc(_gasMeter);
m_loadWord = createFunc(false, Type::Word, _gasMeter);
m_storeWord = createFunc(true, Type::Word, _gasMeter);
m_storeByte = createFunc(true, Type::Byte, _gasMeter);
}
llvm::Function* Memory::createRequireFunc(GasMeter& _gasMeter)
{
llvm::Type* argTypes[] = {Type::RuntimePtr, Type::Word, Type::Word};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "mem.require", getModule());
auto rt = func->arg_begin();
rt->setName("rt");
auto offset = rt->getNextNode();
offset->setName("offset");
auto size = offset->getNextNode();
size->setName("size");
auto preBB = llvm::BasicBlock::Create(func->getContext(), "Pre", func);
auto checkBB = llvm::BasicBlock::Create(func->getContext(), "Check", func);
auto resizeBB = llvm::BasicBlock::Create(func->getContext(), "Resize", func);
auto returnBB = llvm::BasicBlock::Create(func->getContext(), "Return", func);
InsertPointGuard guard(m_builder); // Restores insert point at function exit
// BB "Pre": Ignore checks with size 0
m_builder.SetInsertPoint(preBB);
auto sizeIsZero = m_builder.CreateICmpEQ(size, Constant::get(0));
m_builder.CreateCondBr(sizeIsZero, returnBB, checkBB);
// BB "Check"
m_builder.SetInsertPoint(checkBB);
auto uaddWO = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::uadd_with_overflow, Type::Word);
auto uaddRes = m_builder.CreateCall2(uaddWO, offset, size, "res");
auto sizeRequired = m_builder.CreateExtractValue(uaddRes, 0, "sizeReq");
auto overflow1 = m_builder.CreateExtractValue(uaddRes, 1, "overflow1");
auto rtPtr = getRuntimeManager().getRuntimePtr();
auto sizePtr = m_builder.CreateStructGEP(rtPtr, 4);
auto currSize = m_builder.CreateLoad(sizePtr, "currSize");
auto tooSmall = m_builder.CreateICmpULE(currSize, sizeRequired, "tooSmall");
auto resizeNeeded = m_builder.CreateOr(tooSmall, overflow1, "resizeNeeded");
m_builder.CreateCondBr(resizeNeeded, resizeBB, returnBB); // OPT branch weights?
// BB "Resize"
m_builder.SetInsertPoint(resizeBB);
// Check gas first
uaddRes = m_builder.CreateCall2(uaddWO, sizeRequired, Constant::get(31), "res");
auto wordsRequired = m_builder.CreateExtractValue(uaddRes, 0);
auto overflow2 = m_builder.CreateExtractValue(uaddRes, 1, "overflow2");
auto overflow = m_builder.CreateOr(overflow1, overflow2, "overflow");
wordsRequired = m_builder.CreateSelect(overflow, Constant::get(-1), wordsRequired);
wordsRequired = m_builder.CreateUDiv(wordsRequired, Constant::get(32), "wordsReq");
sizeRequired = m_builder.CreateMul(wordsRequired, Constant::get(32), "roundedSizeReq");
auto words = m_builder.CreateUDiv(currSize, Constant::get(32), "words"); // size is always 32*k
auto newWords = m_builder.CreateSub(wordsRequired, words, "addtionalWords");
_gasMeter.countMemory(newWords);
// Resize
m_builder.CreateStore(sizeRequired, sizePtr);
auto newData = m_builder.CreateCall2(m_resize, rt, sizePtr, "newData");
auto dataPtr = m_builder.CreateStructGEP(rtPtr, 3);
m_builder.CreateStore(newData, dataPtr);
m_builder.CreateBr(returnBB);
// BB "Return"
m_builder.SetInsertPoint(returnBB);
m_builder.CreateRetVoid();
return func;
}
llvm::Function* Memory::createFunc(bool _isStore, llvm::Type* _valueType, GasMeter&)
{
auto isWord = _valueType == Type::Word;
llvm::Type* storeArgs[] = {Type::RuntimePtr, Type::Word, _valueType};
llvm::Type* loadArgs[] = {Type::RuntimePtr, Type::Word};
auto name = _isStore ? isWord ? "mstore" : "mstore8" : "mload";
auto funcType = _isStore ? llvm::FunctionType::get(Type::Void, storeArgs, false) : llvm::FunctionType::get(Type::Word, loadArgs, false);
auto func = llvm::Function::Create(funcType, llvm::Function::PrivateLinkage, name, getModule());
InsertPointGuard guard(m_builder); // Restores insert point at function exit
m_builder.SetInsertPoint(llvm::BasicBlock::Create(func->getContext(), {}, func));
auto rt = func->arg_begin();
rt->setName("rt");
auto index = rt->getNextNode();
index->setName("index");
auto valueSize = _valueType->getPrimitiveSizeInBits() / 8;
this->require(index, Constant::get(valueSize));
auto ptr = getBytePtr(index);
if (isWord)
ptr = m_builder.CreateBitCast(ptr, Type::WordPtr, "wordPtr");
if (_isStore)
{
llvm::Value* value = index->getNextNode();
value->setName("value");
if (isWord)
value = Endianness::toBE(m_builder, value);
m_builder.CreateStore(value, ptr);
m_builder.CreateRetVoid();
}
else
{
llvm::Value* ret = m_builder.CreateLoad(ptr);
ret = Endianness::toNative(m_builder, ret);
m_builder.CreateRet(ret);
}
return func;
}
llvm::Value* Memory::loadWord(llvm::Value* _addr)
{
return createCall(m_loadWord, {getRuntimeManager().getRuntimePtr(), _addr});
}
void Memory::storeWord(llvm::Value* _addr, llvm::Value* _word)
{
createCall(m_storeWord, {getRuntimeManager().getRuntimePtr(), _addr, _word});
}
void Memory::storeByte(llvm::Value* _addr, llvm::Value* _word)
{
auto byte = m_builder.CreateTrunc(_word, Type::Byte, "byte");
createCall(m_storeByte, {getRuntimeManager().getRuntimePtr(), _addr, byte});
}
llvm::Value* Memory::getData()
{
auto rtPtr = getRuntimeManager().getRuntimePtr();
auto dataPtr = m_builder.CreateStructGEP(rtPtr, 3);
return m_builder.CreateLoad(dataPtr, "data");
}
llvm::Value* Memory::getSize()
{
auto rtPtr = getRuntimeManager().getRuntimePtr();
auto sizePtr = m_builder.CreateStructGEP(rtPtr, 4);
return m_builder.CreateLoad(sizePtr, "size");
}
llvm::Value* Memory::getBytePtr(llvm::Value* _index)
{
auto idx = m_builder.CreateTrunc(_index, Type::Size, "idx"); // Never allow memory index be a type bigger than i64
return m_builder.CreateGEP(getData(), idx, "ptr");
}
void Memory::require(llvm::Value* _offset, llvm::Value* _size)
{
if (auto constant = llvm::dyn_cast<llvm::ConstantInt>(_size))
{
if (!constant->getValue())
return;
}
createCall(m_require, {getRuntimeManager().getRuntimePtr(), _offset, _size});
}
void Memory::copyBytes(llvm::Value* _srcPtr, llvm::Value* _srcSize, llvm::Value* _srcIdx,
llvm::Value* _destMemIdx, llvm::Value* _reqBytes)
{
require(_destMemIdx, _reqBytes);
// Additional copy cost
// TODO: This round ups to 32 happens in many places
auto copyWords = m_builder.CreateUDiv(m_builder.CreateAdd(_reqBytes, Constant::get(31)), Constant::get(32));
m_gasMeter.countCopy(copyWords);
// Algorithm:
// isOutsideData = idx256 >= size256
// idx64 = trunc idx256
// size64 = trunc size256
// dataLeftSize = size64 - idx64 // safe if not isOutsideData
// reqBytes64 = trunc _reqBytes // require() handles large values
// bytesToCopy0 = select(reqBytes64 > dataLeftSize, dataSizeLeft, reqBytes64) // min
// bytesToCopy = select(isOutsideData, 0, bytesToCopy0)
auto isOutsideData = m_builder.CreateICmpUGE(_srcIdx, _srcSize);
auto idx64 = m_builder.CreateTrunc(_srcIdx, Type::lowPrecision);
auto size64 = m_builder.CreateTrunc(_srcSize, Type::lowPrecision);
auto dataLeftSize = m_builder.CreateNUWSub(size64, idx64);
auto reqBytes64 = m_builder.CreateTrunc(_reqBytes, Type::lowPrecision);
auto outOfBound = m_builder.CreateICmpUGT(reqBytes64, dataLeftSize);
auto bytesToCopyInner = m_builder.CreateSelect(outOfBound, dataLeftSize, reqBytes64);
auto zero64 = llvm::ConstantInt::get(Type::lowPrecision, 0); // TODO: Cache common constants
auto bytesToCopy = m_builder.CreateSelect(isOutsideData, zero64, bytesToCopyInner);
auto src = m_builder.CreateGEP(_srcPtr, idx64, "src");
auto dstIdx = m_builder.CreateTrunc(_destMemIdx, Type::Size, "dstIdx"); // Never allow memory index be a type bigger than i64
auto dst = m_builder.CreateGEP(getData(), dstIdx, "dst");
m_builder.CreateMemCpy(dst, src, bytesToCopy, 0);
}
}
}
}
extern "C"
{
using namespace dev::eth::jit;
EXPORT byte* mem_resize(Runtime* _rt, i256* _size) // TODO: Use uint64 as size OR use realloc in LLVM IR
{
auto size = _size->a; // Trunc to 64-bit
auto& memory = _rt->getMemory();
memory.resize(size);
return memory.data();
}
}
<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2019-6-1 22:04:14
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
/*
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
*/
/*
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
*/
// const ll MOD = 1000000007;
class UnionFind
{
public:
vector<long long> par;
UnionFind() {}
UnionFind(int n) : par(n, -1) {}
void init(int n)
{
par.assign(n, -1);
}
int root(int x)
{
if (par[x] < 0)
{
return x;
}
return par[x] = root(par[x]);
}
bool is_same(int x, int y)
{
return root(x) == root(y);
}
bool merge(int x, int y)
{
x = root(x);
y = root(y);
if (x == y)
{
return false;
}
if (par[x] > par[y])
{
swap(x, y);
}
par[x] += par[y];
par[y] = x;
return true;
}
long long size(int x)
{
return -par[root(x)];
}
};
int N;
bool A[2010][2010];
vector<int> V[2010];
vector<int> W[2010];
vector<int> X;
set<int> Y;
bool visited[2010];
UnionFind uf;
void dfs(int v)
{
if (!visited[v])
{
visited[v] = true;
for (auto x : V[v])
{
if (!visited[x])
{
dfs(x);
}
}
X.push_back(v);
}
}
void dfs2(int v)
{
if (!visited[v])
{
visited[v] = true;
for (auto x : W[v])
{
if (!visited[x])
{
dfs2(x);
uf.merge(v, x);
}
}
}
}
void dfs3(int v)
{
if (!visited[v] && Y.find(v) != Y.end())
{
visited[v] = true;
for (auto x : V[v])
{
if (!visited[x] && Y.find(v) != Y.end())
{
dfs3(x);
}
}
}
}
int main()
{
cin >> N;
for (auto i = 0; i < N; i++)
{
string S;
cin >> S;
for (auto j = 0; j < i; j++)
{
A[i][j] = (S[j] == '1');
if (A[i][j])
{
V[j].push_back(i);
W[i].push_back(j);
}
else
{
V[i].push_back(j);
W[j].push_back(i);
}
}
}
fill(visited, visited + N, false);
#if DEBUG == 1
cerr << "dfs" << endl;
#endif
for (auto i = 0; i < N; i++)
{
dfs(i);
}
#if DEBUG == 1
cerr << "dfs" << endl;
#endif
uf = UnionFind(N);
reverse(X.begin(), X.end());
fill(visited, visited + N, false);
for (auto x : X)
{
dfs2(x);
}
for (auto i = 0; i < N; i++)
{
bool ok = true;
for (auto j = 0; j < N; j++)
{
if (uf.is_same(i, j))
{
ok = false;
break;
}
}
if (ok)
{
Y.insert(i);
}
}
for (auto x : Y)
{
fill(visited, visited + N, false);
dfs3(x);
bool ok = true;
for (auto y : Y)
{
if (!visited[y])
{
ok = false;
break;
}
}
if (ok)
{
cout << uf.size(x) << endl;
return 0;
}
}
}<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2019-6-1 22:04:14
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
/*
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
*/
/*
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
*/
// const ll MOD = 1000000007;
class UnionFind
{
public:
vector<long long> par;
UnionFind() {}
UnionFind(int n) : par(n, -1) {}
void init(int n)
{
par.assign(n, -1);
}
int root(int x)
{
if (par[x] < 0)
{
return x;
}
return par[x] = root(par[x]);
}
bool is_same(int x, int y)
{
return root(x) == root(y);
}
bool merge(int x, int y)
{
x = root(x);
y = root(y);
if (x == y)
{
return false;
}
if (par[x] > par[y])
{
swap(x, y);
}
par[x] += par[y];
par[y] = x;
return true;
}
long long size(int x)
{
return -par[root(x)];
}
};
int N;
bool A[2010][2010];
vector<int> V[2010];
vector<int> W[2010];
vector<int> X;
set<int> Y;
bool visited[2010];
UnionFind uf;
void dfs(int v)
{
if (!visited[v])
{
visited[v] = true;
for (auto x : V[v])
{
if (!visited[x])
{
dfs(x);
}
}
X.push_back(v);
}
}
void dfs2(int v)
{
if (!visited[v])
{
visited[v] = true;
for (auto x : W[v])
{
if (!visited[x])
{
dfs2(x);
uf.merge(v, x);
}
}
}
}
void dfs3(int v)
{
if (!visited[v] && Y.find(v) != Y.end())
{
visited[v] = true;
for (auto x : V[v])
{
if (!visited[x] && Y.find(v) != Y.end())
{
dfs3(x);
}
}
}
}
int main()
{
cin >> N;
for (auto i = 1; i < N; i++)
{
string S;
cin >> S;
for (auto j = 0; j < i; j++)
{
A[i][j] = (S[j] == '1');
if (A[i][j])
{
V[j].push_back(i);
W[i].push_back(j);
}
else
{
V[i].push_back(j);
W[j].push_back(i);
}
}
}
fill(visited, visited + N, false);
#if DEBUG == 1
cerr << "dfs" << endl;
#endif
for (auto i = 0; i < N; i++)
{
dfs(i);
}
#if DEBUG == 1
cerr << "dfs" << endl;
#endif
uf = UnionFind(N);
reverse(X.begin(), X.end());
fill(visited, visited + N, false);
for (auto x : X)
{
dfs2(x);
}
for (auto i = 0; i < N; i++)
{
bool ok = true;
for (auto j = 0; j < N; j++)
{
if (uf.is_same(i, j))
{
ok = false;
break;
}
}
if (ok)
{
Y.insert(i);
}
}
for (auto x : Y)
{
fill(visited, visited + N, false);
dfs3(x);
bool ok = true;
for (auto y : Y)
{
if (!visited[y])
{
ok = false;
break;
}
}
if (ok)
{
cout << uf.size(x) << endl;
return 0;
}
}
}<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingStatisticsVectorImageFilter.h"
#include "otbEigenvalueLikelihoodMaximisation.h"
#include "otbVirtualDimensionality.h"
namespace otb
{
namespace Wrapper
{
class EndmemberNumberEstimation : public Application
{
public:
/** Standard class typedefs. */
typedef EndmemberNumberEstimation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(EndmemberNumberEstimation, otb::Application);
typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType, float> StreamingStatisticsVectorImageFilterType;
typedef otb::VirtualDimensionality<float> VirtualDimensionalityType;
typedef otb::EigenvalueLikelihoodMaximisation<float> EigenvalueLikelihoodMaximisationType;
private:
void DoInit() override
{
SetName("EndmemberNumberEstimation");
SetDescription("Estimate the number of endmembers in a hyperspectral image");
// Documentation
SetDocName("Endmember Number Estimation");
SetDocLongDescription("Estimate the number of endmembers "
"in a hyperspectral image. First, compute statistics on the image and then "
"apply an endmember number estimation algorithm using these statistics. Two "
"algorithms are available:\n\n"
"1. Virtual Dimensionality (VD) [1][2]\n"
"2. Eigenvalue Likelihood Maximization (ELM) [3][4]\n\n"
"The application then returns the estimated number of endmembers.\n\n"
"[1] C.-I. Chang and Q. Du, Estimation of number of spectrally distinct signal "
"sources in hyperspectral imagery, IEEE Transactions on Geoscience and Remote "
"Sensing, vol. 43, no. 3, mar 2004.\n\n"
"[2] J. Wang and C.-I. Chang, Applications of independent component analysis "
"in endmember extraction and abundance quantification for hyperspectral imagery"
", IEEE Transactions on Geoscience and Remote Sensing, vol. 44, no. 9, pp. "
"2601-1616, sep 2006.\n\n"
"[3] Unsupervised Endmember Extraction of Martian Hyperspectral Images, B.Luo, "
"J. Chanussot, S. Dout\'e and X. Ceamanos, IEEE Whispers 2009, Grenoble France, 2009\n\n"
"[4] Unsupervised classification of hyperspectral images by using "
"linear unmixing algorithm Luo, B. and Chanussot, J., IEEE Int. Conf. On Image"
"Processing(ICIP) 2009, Cairo, Egypte, 2009"
);
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("VertexComponentAnalysis, HyperspectralUnmixing");
AddDocTag(Tags::Hyperspectral);
AddParameter(ParameterType_InputImage, "in", "Input Image Filename");
SetParameterDescription("in","The hyperspectral data cube input");
AddParameter(ParameterType_Choice, "algo", "Unmixing algorithm");
SetParameterDescription("algo", "The algorithm to use for the estimation");
AddChoice("algo.elm", "Eigenvalue Likelihood Maximization");
SetParameterDescription("algo.elm", "");
AddChoice("algo.vd", "Virtual Dimensionality");
SetParameterDescription("algo.vd", "");
AddParameter( ParameterType_Float , "algo.vd.far" , "False alarm rate");
SetMinimumParameterFloatValue("algo.vd.far", 0);
SetMaximumParameterFloatValue("algo.vd.far", 1);
SetDefaultParameterFloat( "algo.vd.far" , 1.0E-3 );
SetParameterDescription( "algo.vd.far" ,
"False alarm rate for the virtual dimensionality algorithm");
AddParameter(ParameterType_Int,"number","Number of endmembers");
SetParameterDescription("number", "Estimated number of endmembers");
SetParameterRole("number", Role_Output);
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
SetDocExampleParameterValue("algo", "vd");
SetDocExampleParameterValue("algo.vd.far", "1.0E-3");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
// Nothing to do here : all parameters are independent
}
void DoExecute() override
{
// Load input image
auto inputImage = GetParameterImage("in");
otbAppLogINFO("Computing statistics on input image...");
auto statisticsFilter = StreamingStatisticsVectorImageFilterType::New();
statisticsFilter->SetInput(inputImage);
statisticsFilter->Update();
auto correlationMatrix = statisticsFilter->GetCorrelation().GetVnlMatrix();
auto covarianceMatrix = statisticsFilter->GetCovariance().GetVnlMatrix();
auto numberOfPixels = inputImage->GetLargestPossibleRegion().GetNumberOfPixels();
int numberOfEndmembers = 0;
const std::string algorithm = GetParameterString("algo");
if (algorithm=="elm")
{
otbAppLogINFO("Estimation algorithm: Eigenvalue Likelihood Maximization.");
auto elm = EigenvalueLikelihoodMaximisationType::New();
elm->SetCovariance(covarianceMatrix);
elm->SetCorrelation(correlationMatrix);
elm->SetNumberOfPixels(numberOfPixels);
elm->Compute();
numberOfEndmembers = elm->GetNumberOfEndmembers();
}
else if (algorithm=="vd")
{
otbAppLogINFO("Estimation algorithm: Virtual Dimensionality.");
auto vd = VirtualDimensionalityType::New();
vd->SetCovariance(covarianceMatrix);
vd->SetCorrelation(correlationMatrix);
vd->SetNumberOfPixels(numberOfPixels);
vd->SetFAR(GetParameterFloat("algo.vd.far"));
vd->Compute();
numberOfEndmembers = vd->GetNumberOfEndmembers();
}
SetParameterInt("number", numberOfEndmembers);
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::EndmemberNumberEstimation)
<commit_msg>ENH: added progress reporting to the statistic estimation step<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingStatisticsVectorImageFilter.h"
#include "otbEigenvalueLikelihoodMaximisation.h"
#include "otbVirtualDimensionality.h"
namespace otb
{
namespace Wrapper
{
class EndmemberNumberEstimation : public Application
{
public:
/** Standard class typedefs. */
typedef EndmemberNumberEstimation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(EndmemberNumberEstimation, otb::Application);
typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType, float> StreamingStatisticsVectorImageFilterType;
typedef otb::VirtualDimensionality<float> VirtualDimensionalityType;
typedef otb::EigenvalueLikelihoodMaximisation<float> EigenvalueLikelihoodMaximisationType;
private:
void DoInit() override
{
SetName("EndmemberNumberEstimation");
SetDescription("Estimate the number of endmembers in a hyperspectral image");
// Documentation
SetDocName("Endmember Number Estimation");
SetDocLongDescription("Estimate the number of endmembers "
"in a hyperspectral image. First, compute statistics on the image and then "
"apply an endmember number estimation algorithm using these statistics. Two "
"algorithms are available:\n\n"
"1. Virtual Dimensionality (VD) [1][2]\n"
"2. Eigenvalue Likelihood Maximization (ELM) [3][4]\n\n"
"The application then returns the estimated number of endmembers.\n\n"
"[1] C.-I. Chang and Q. Du, Estimation of number of spectrally distinct signal "
"sources in hyperspectral imagery, IEEE Transactions on Geoscience and Remote "
"Sensing, vol. 43, no. 3, mar 2004.\n\n"
"[2] J. Wang and C.-I. Chang, Applications of independent component analysis "
"in endmember extraction and abundance quantification for hyperspectral imagery"
", IEEE Transactions on Geoscience and Remote Sensing, vol. 44, no. 9, pp. "
"2601-1616, sep 2006.\n\n"
"[3] Unsupervised Endmember Extraction of Martian Hyperspectral Images, B.Luo, "
"J. Chanussot, S. Dout\'e and X. Ceamanos, IEEE Whispers 2009, Grenoble France, 2009\n\n"
"[4] Unsupervised classification of hyperspectral images by using "
"linear unmixing algorithm Luo, B. and Chanussot, J., IEEE Int. Conf. On Image"
"Processing(ICIP) 2009, Cairo, Egypte, 2009"
);
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("VertexComponentAnalysis, HyperspectralUnmixing");
AddDocTag(Tags::Hyperspectral);
AddParameter(ParameterType_InputImage, "in", "Input Image Filename");
SetParameterDescription("in","The hyperspectral data cube input");
AddParameter(ParameterType_Choice, "algo", "Unmixing algorithm");
SetParameterDescription("algo", "The algorithm to use for the estimation");
AddChoice("algo.elm", "Eigenvalue Likelihood Maximization");
SetParameterDescription("algo.elm", "");
AddChoice("algo.vd", "Virtual Dimensionality");
SetParameterDescription("algo.vd", "");
AddParameter( ParameterType_Float , "algo.vd.far" , "False alarm rate");
SetMinimumParameterFloatValue("algo.vd.far", 0);
SetMaximumParameterFloatValue("algo.vd.far", 1);
SetDefaultParameterFloat( "algo.vd.far" , 1.0E-3 );
SetParameterDescription( "algo.vd.far" ,
"False alarm rate for the virtual dimensionality algorithm");
AddParameter(ParameterType_Int,"number","Number of endmembers");
SetParameterDescription("number", "Estimated number of endmembers");
SetParameterRole("number", Role_Output);
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
SetDocExampleParameterValue("algo", "vd");
SetDocExampleParameterValue("algo.vd.far", "1.0E-3");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
// Nothing to do here : all parameters are independent
}
void DoExecute() override
{
// Load input image
auto inputImage = GetParameterImage("in");
otbAppLogINFO("Computing statistics on input image...");
auto statisticsFilter = StreamingStatisticsVectorImageFilterType::New();
statisticsFilter->SetInput(inputImage);
AddProcess(statisticsFilter->GetStreamer(), "Statistic estimation step");
statisticsFilter->Update();
auto correlationMatrix = statisticsFilter->GetCorrelation().GetVnlMatrix();
auto covarianceMatrix = statisticsFilter->GetCovariance().GetVnlMatrix();
auto numberOfPixels = inputImage->GetLargestPossibleRegion().GetNumberOfPixels();
int numberOfEndmembers = 0;
const std::string algorithm = GetParameterString("algo");
if (algorithm=="elm")
{
otbAppLogINFO("Estimation algorithm: Eigenvalue Likelihood Maximization.");
auto elm = EigenvalueLikelihoodMaximisationType::New();
elm->SetCovariance(covarianceMatrix);
elm->SetCorrelation(correlationMatrix);
elm->SetNumberOfPixels(numberOfPixels);
elm->Compute();
numberOfEndmembers = elm->GetNumberOfEndmembers();
}
else if (algorithm=="vd")
{
otbAppLogINFO("Estimation algorithm: Virtual Dimensionality.");
auto vd = VirtualDimensionalityType::New();
vd->SetCovariance(covarianceMatrix);
vd->SetCorrelation(correlationMatrix);
vd->SetNumberOfPixels(numberOfPixels);
vd->SetFAR(GetParameterFloat("algo.vd.far"));
vd->Compute();
numberOfEndmembers = vd->GetNumberOfEndmembers();
}
SetParameterInt("number", numberOfEndmembers);
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::EndmemberNumberEstimation)
<|endoftext|>
|
<commit_before><commit_msg>Simplify expression to fix bool/sal_Bool ambiguity<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/importers/proto/heap_graph_tracker.h"
#include "perfetto/base/logging.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace trace_processor {
namespace {
using ::testing::UnorderedElementsAre;
TEST(HeapGraphTrackerTest, PackageFromLocationApp) {
TraceProcessorContext context;
HeapGraphTracker tracker(&context);
EXPECT_EQ(tracker.PackageFromLocation(
"/data/app/~~ASDFGH1234QWerT==/"
"com.twitter.android-MNBVCX7890SDTst6==/test.apk"),
"com.twitter.android");
EXPECT_EQ(tracker.PackageFromLocation(
"/data/app/com.google.android.webview-6XfQhnaSkFwGK0sYL9is0G==/"
"base.apk"),
"com.google.android.webview");
}
TEST(HeapGraphTrackerTest, BuildFlamegraph) {
// 4@A 5@B
// \ /
// 2@Y 3@Y
// \ /
// 1@X
constexpr uint64_t kSeqId = 1;
constexpr UniquePid kPid = 1;
constexpr int64_t kTimestamp = 1;
TraceProcessorContext context;
context.storage.reset(new TraceStorage());
HeapGraphTracker tracker(&context);
constexpr uint64_t kField = 1;
constexpr uint64_t kX = 1;
constexpr uint64_t kY = 2;
constexpr uint64_t kA = 3;
constexpr uint64_t kB = 4;
base::StringView field = base::StringView("foo");
StringPool::Id x = context.storage->InternString("X");
StringPool::Id y = context.storage->InternString("Y");
StringPool::Id a = context.storage->InternString("A");
StringPool::Id b = context.storage->InternString("B");
tracker.AddInternedFieldName(kSeqId, kField, field);
tracker.AddInternedTypeName(kSeqId, kX, x);
tracker.AddInternedTypeName(kSeqId, kY, y);
tracker.AddInternedTypeName(kSeqId, kA, a);
tracker.AddInternedTypeName(kSeqId, kB, b);
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 1;
obj.self_size = 1;
obj.type_id = kX;
HeapGraphTracker::SourceObject::Reference ref;
ref.field_name_id = kField;
ref.owned_object_id = 2;
obj.references.emplace_back(std::move(ref));
ref.field_name_id = kField;
ref.owned_object_id = 3;
obj.references.emplace_back(std::move(ref));
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 2;
obj.self_size = 2;
obj.type_id = kY;
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 3;
obj.self_size = 3;
obj.type_id = kY;
HeapGraphTracker::SourceObject::Reference ref;
ref.field_name_id = kField;
ref.owned_object_id = 4;
obj.references.emplace_back(std::move(ref));
ref.field_name_id = kField;
ref.owned_object_id = 5;
obj.references.emplace_back(std::move(ref));
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 4;
obj.self_size = 4;
obj.type_id = kA;
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 5;
obj.self_size = 5;
obj.type_id = kB;
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
HeapGraphTracker::SourceRoot root;
root.root_type = context.storage->InternString("ROOT");
root.object_ids.emplace_back(1);
tracker.AddRoot(kSeqId, kPid, kTimestamp, root);
tracker.FinalizeProfile(kSeqId);
std::unique_ptr<tables::ExperimentalFlamegraphNodesTable> flame =
tracker.BuildFlamegraph(kPid, kTimestamp);
ASSERT_NE(flame, nullptr);
auto cumulative_sizes = flame->cumulative_size().ToVectorForTesting();
EXPECT_THAT(cumulative_sizes, UnorderedElementsAre(15, 4, 14, 5));
auto cumulative_counts = flame->cumulative_count().ToVectorForTesting();
EXPECT_THAT(cumulative_counts, UnorderedElementsAre(5, 4, 1, 1));
auto sizes = flame->size().ToVectorForTesting();
EXPECT_THAT(sizes, UnorderedElementsAre(1, 5, 4, 5));
auto counts = flame->count().ToVectorForTesting();
EXPECT_THAT(counts, UnorderedElementsAre(1, 2, 1, 1));
}
static const char kArray[] = "X[]";
static const char kDoubleArray[] = "X[][]";
static const char kNoArray[] = "X";
static const char kLongNoArray[] = "ABCDE";
static const char kStaticClassNoArray[] = "java.lang.Class<abc>";
static const char kStaticClassArray[] = "java.lang.Class<abc[]>";
TEST(HeapGraphTrackerTest, NormalizeTypeName) {
// sizeof(...) - 1 below to get rid of the null-byte.
EXPECT_EQ(NormalizeTypeName(base::StringView(kArray, sizeof(kArray) - 1))
.ToStdString(),
"X");
EXPECT_EQ(NormalizeTypeName(
base::StringView(kDoubleArray, sizeof(kDoubleArray) - 1))
.ToStdString(),
"X");
EXPECT_EQ(NormalizeTypeName(base::StringView(kNoArray, sizeof(kNoArray) - 1))
.ToStdString(),
"X");
EXPECT_EQ(NormalizeTypeName(
base::StringView(kLongNoArray, sizeof(kLongNoArray) - 1))
.ToStdString(),
"ABCDE");
EXPECT_EQ(NormalizeTypeName(base::StringView(kStaticClassNoArray,
sizeof(kStaticClassNoArray) - 1))
.ToStdString(),
"abc");
EXPECT_EQ(NormalizeTypeName(base::StringView(kStaticClassArray,
sizeof(kStaticClassArray) - 1))
.ToStdString(),
"abc");
}
TEST(HeapGraphTrackerTest, NumberOfArray) {
// sizeof(...) - 1 below to get rid of the null-byte.
EXPECT_EQ(NumberOfArrays(base::StringView(kArray, sizeof(kArray) - 1)), 1u);
EXPECT_EQ(
NumberOfArrays(base::StringView(kDoubleArray, sizeof(kDoubleArray) - 1)),
2u);
EXPECT_EQ(NumberOfArrays(base::StringView(kNoArray, sizeof(kNoArray) - 1)),
0u);
EXPECT_EQ(
NumberOfArrays(base::StringView(kLongNoArray, sizeof(kLongNoArray) - 1)),
0u);
}
} // namespace
} // namespace trace_processor
} // namespace perfetto
<commit_msg>Set TraceStorage for TraceProcessorContext.<commit_after>/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/importers/proto/heap_graph_tracker.h"
#include "perfetto/base/logging.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace trace_processor {
namespace {
using ::testing::UnorderedElementsAre;
TEST(HeapGraphTrackerTest, PackageFromLocationApp) {
TraceProcessorContext context;
context.storage.reset(new TraceStorage);
HeapGraphTracker tracker(&context);
EXPECT_EQ(tracker.PackageFromLocation(
"/data/app/~~ASDFGH1234QWerT==/"
"com.twitter.android-MNBVCX7890SDTst6==/test.apk"),
"com.twitter.android");
EXPECT_EQ(tracker.PackageFromLocation(
"/data/app/com.google.android.webview-6XfQhnaSkFwGK0sYL9is0G==/"
"base.apk"),
"com.google.android.webview");
}
TEST(HeapGraphTrackerTest, BuildFlamegraph) {
// 4@A 5@B
// \ /
// 2@Y 3@Y
// \ /
// 1@X
constexpr uint64_t kSeqId = 1;
constexpr UniquePid kPid = 1;
constexpr int64_t kTimestamp = 1;
TraceProcessorContext context;
context.storage.reset(new TraceStorage());
HeapGraphTracker tracker(&context);
constexpr uint64_t kField = 1;
constexpr uint64_t kX = 1;
constexpr uint64_t kY = 2;
constexpr uint64_t kA = 3;
constexpr uint64_t kB = 4;
base::StringView field = base::StringView("foo");
StringPool::Id x = context.storage->InternString("X");
StringPool::Id y = context.storage->InternString("Y");
StringPool::Id a = context.storage->InternString("A");
StringPool::Id b = context.storage->InternString("B");
tracker.AddInternedFieldName(kSeqId, kField, field);
tracker.AddInternedTypeName(kSeqId, kX, x);
tracker.AddInternedTypeName(kSeqId, kY, y);
tracker.AddInternedTypeName(kSeqId, kA, a);
tracker.AddInternedTypeName(kSeqId, kB, b);
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 1;
obj.self_size = 1;
obj.type_id = kX;
HeapGraphTracker::SourceObject::Reference ref;
ref.field_name_id = kField;
ref.owned_object_id = 2;
obj.references.emplace_back(std::move(ref));
ref.field_name_id = kField;
ref.owned_object_id = 3;
obj.references.emplace_back(std::move(ref));
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 2;
obj.self_size = 2;
obj.type_id = kY;
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 3;
obj.self_size = 3;
obj.type_id = kY;
HeapGraphTracker::SourceObject::Reference ref;
ref.field_name_id = kField;
ref.owned_object_id = 4;
obj.references.emplace_back(std::move(ref));
ref.field_name_id = kField;
ref.owned_object_id = 5;
obj.references.emplace_back(std::move(ref));
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 4;
obj.self_size = 4;
obj.type_id = kA;
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
{
HeapGraphTracker::SourceObject obj;
obj.object_id = 5;
obj.self_size = 5;
obj.type_id = kB;
tracker.AddObject(kSeqId, kPid, kTimestamp, std::move(obj));
}
HeapGraphTracker::SourceRoot root;
root.root_type = context.storage->InternString("ROOT");
root.object_ids.emplace_back(1);
tracker.AddRoot(kSeqId, kPid, kTimestamp, root);
tracker.FinalizeProfile(kSeqId);
std::unique_ptr<tables::ExperimentalFlamegraphNodesTable> flame =
tracker.BuildFlamegraph(kPid, kTimestamp);
ASSERT_NE(flame, nullptr);
auto cumulative_sizes = flame->cumulative_size().ToVectorForTesting();
EXPECT_THAT(cumulative_sizes, UnorderedElementsAre(15, 4, 14, 5));
auto cumulative_counts = flame->cumulative_count().ToVectorForTesting();
EXPECT_THAT(cumulative_counts, UnorderedElementsAre(5, 4, 1, 1));
auto sizes = flame->size().ToVectorForTesting();
EXPECT_THAT(sizes, UnorderedElementsAre(1, 5, 4, 5));
auto counts = flame->count().ToVectorForTesting();
EXPECT_THAT(counts, UnorderedElementsAre(1, 2, 1, 1));
}
static const char kArray[] = "X[]";
static const char kDoubleArray[] = "X[][]";
static const char kNoArray[] = "X";
static const char kLongNoArray[] = "ABCDE";
static const char kStaticClassNoArray[] = "java.lang.Class<abc>";
static const char kStaticClassArray[] = "java.lang.Class<abc[]>";
TEST(HeapGraphTrackerTest, NormalizeTypeName) {
// sizeof(...) - 1 below to get rid of the null-byte.
EXPECT_EQ(NormalizeTypeName(base::StringView(kArray, sizeof(kArray) - 1))
.ToStdString(),
"X");
EXPECT_EQ(NormalizeTypeName(
base::StringView(kDoubleArray, sizeof(kDoubleArray) - 1))
.ToStdString(),
"X");
EXPECT_EQ(NormalizeTypeName(base::StringView(kNoArray, sizeof(kNoArray) - 1))
.ToStdString(),
"X");
EXPECT_EQ(NormalizeTypeName(
base::StringView(kLongNoArray, sizeof(kLongNoArray) - 1))
.ToStdString(),
"ABCDE");
EXPECT_EQ(NormalizeTypeName(base::StringView(kStaticClassNoArray,
sizeof(kStaticClassNoArray) - 1))
.ToStdString(),
"abc");
EXPECT_EQ(NormalizeTypeName(base::StringView(kStaticClassArray,
sizeof(kStaticClassArray) - 1))
.ToStdString(),
"abc");
}
TEST(HeapGraphTrackerTest, NumberOfArray) {
// sizeof(...) - 1 below to get rid of the null-byte.
EXPECT_EQ(NumberOfArrays(base::StringView(kArray, sizeof(kArray) - 1)), 1u);
EXPECT_EQ(
NumberOfArrays(base::StringView(kDoubleArray, sizeof(kDoubleArray) - 1)),
2u);
EXPECT_EQ(NumberOfArrays(base::StringView(kNoArray, sizeof(kNoArray) - 1)),
0u);
EXPECT_EQ(
NumberOfArrays(base::StringView(kLongNoArray, sizeof(kLongNoArray) - 1)),
0u);
}
} // namespace
} // namespace trace_processor
} // namespace perfetto
<|endoftext|>
|
<commit_before>/*
Title: Bitmap. Generally used by the garbage collector to indicate allocated words
Copyright (c) 2006 David C.J. Matthews
Based on original code in garbage_collect.c.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
Bitmaps are used particularly in the garbage collector to indicate allocated
words. The efficiency of this code is crucial for the speed of the garbage
collector.
*/
#ifdef _WIN32_WCE
#include "winceconfig.h"
#include "wincelib.h"
#else
#ifdef WIN32
#include "winconfig.h"
#else
#include "config.h"
#endif
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(h) assert(h)
#else
#define ASSERT(h)
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include "bitmap.h"
#include "globals.h"
Bitmap::Bitmap(POLYUNSIGNED bits)
{
POLYUNSIGNED words = (bits+BITS_PER_WORD-1) / BITS_PER_WORD;
m_bits = (POLYUNSIGNED *)calloc(words, sizeof(POLYUNSIGNED));
}
bool Bitmap::Create(POLYUNSIGNED bits)
{
free(m_bits);
POLYUNSIGNED words = (bits+BITS_PER_WORD-1) / BITS_PER_WORD;
m_bits = (POLYUNSIGNED *)calloc(words, sizeof(POLYUNSIGNED));
return m_bits != 0;
}
Bitmap::~Bitmap()
{
free(m_bits);
}
// Set a range of bits in a bitmap. This checks that the bits are not already set.
void Bitmap::SetBits(POLYUNSIGNED bitno, POLYUNSIGNED length)
{
POLYUNSIGNED word_index = bitno / BITS_PER_WORD;
ASSERT (0 < length);
/* Set the first part word */
POLYUNSIGNED start_bit_index = bitno % BITS_PER_WORD;
POLYUNSIGNED stop_bit_index = start_bit_index + length;
/* Do we need to change more than one word? */
if (stop_bit_index < BITS_PER_WORD)
{
/* N.B. On some machines shifts of the number of bits per word can mean
no shift at all. */
const POLYUNSIGNED mask1 = ((~ (POLYUNSIGNED)0)) << start_bit_index;
const POLYUNSIGNED mask2 = ((~ (POLYUNSIGNED)0)) << stop_bit_index;
const POLYUNSIGNED mask = mask1 & ~mask2;
ASSERT((m_bits[word_index] & mask) == 0);
m_bits[word_index] |= mask;
return;
}
else /* Set all the bits we can in the first word */
{
const POLYUNSIGNED mask = ((POLYUNSIGNED)(~ 0)) << start_bit_index;
ASSERT((m_bits[word_index] & mask) == 0);
m_bits[word_index] |= mask;
/* length = length - (BITS_PER_WORD - start_bit_index); */
length = stop_bit_index - BITS_PER_WORD;
}
/* Invariant: 0 <= length */
/* Set as many full words as possible */
while (BITS_PER_WORD <= length)
{
/* Invariant: BITS_PER_WORD <= length */
word_index ++;
ASSERT(m_bits[word_index] == 0);
m_bits[word_index] = ~ (POLYUNSIGNED)0;
length -= BITS_PER_WORD;
/* Invariant: 0 <= length */
}
/* Invariant: 0 <= length < BITS_PER_WORD */
if (length == 0) return;
/* Invariant: 0 < length < BITS_PER_WORD */
/* Set the final part word */
word_index ++;
const POLYUNSIGNED mask1 = (~ (POLYUNSIGNED)0) << 0;
const POLYUNSIGNED mask2 = (~ (POLYUNSIGNED)0) << length;
const POLYUNSIGNED mask = mask1 & ~mask2;
ASSERT((m_bits[word_index] & mask) == 0);
m_bits[word_index] |= mask;
}
void Bitmap::ClearBits(POLYUNSIGNED bitno, POLYUNSIGNED length)
{
POLYUNSIGNED word_index = bitno / BITS_PER_WORD;
ASSERT (0 < length);
// Clear the first part word
POLYUNSIGNED start_bit_index = bitno % BITS_PER_WORD;
POLYUNSIGNED stop_bit_index = start_bit_index + length;
/* Do we need to change more than one word? */
if (stop_bit_index < BITS_PER_WORD)
{
const POLYUNSIGNED mask1 = ((~ (POLYUNSIGNED)0)) << start_bit_index;
const POLYUNSIGNED mask2 = ((~ (POLYUNSIGNED)0)) << stop_bit_index;
const POLYUNSIGNED mask = mask1 & ~mask2;
m_bits[word_index] &= ~mask;
return;
}
else /* Clear all the bits we can in the first word */
{
const POLYUNSIGNED mask = ((POLYUNSIGNED)(~ 0)) << start_bit_index;
m_bits[word_index] &= ~mask;
length = stop_bit_index - BITS_PER_WORD;
}
/* Invariant: 0 <= length */
// Clear as many full words as possible.
while (BITS_PER_WORD <= length)
{
/* Invariant: BITS_PER_WORD <= length */
word_index ++;
m_bits[word_index] = 0;
length -= BITS_PER_WORD;
/* Invariant: 0 <= length */
}
/* Invariant: 0 <= length < BITS_PER_WORD */
if (length == 0)
return;
/* Invariant: 0 < length < BITS_PER_WORD */
// Clear the final part word
word_index ++;
const POLYUNSIGNED mask1 = (~ (POLYUNSIGNED)0) << 0;
const POLYUNSIGNED mask2 = (~ (POLYUNSIGNED)0) << length;
const POLYUNSIGNED mask = mask1 & ~mask2;
m_bits[word_index] &= ~mask;
}
// How many zero bits (maximum n) are there in the bitmap, starting at location start? */
POLYUNSIGNED Bitmap::CountZeroBits(POLYUNSIGNED bitno, POLYUNSIGNED n)
{
POLYUNSIGNED *bitmap = m_bits;
/* Less naive version */
POLYUNSIGNED word_index = bitno / BITS_PER_WORD;
POLYUNSIGNED bit_index = bitno % BITS_PER_WORD;
POLYUNSIGNED bits = bitmap[word_index];
POLYUNSIGNED mask = (POLYUNSIGNED)1 << bit_index;
POLYUNSIGNED zero_bits = 0;
ASSERT (0 < n);
/* Check the first part word */
while (mask != 0)
{
/* zero_bits < n */
if ((bits & mask) != 0) return zero_bits;
zero_bits ++;
if (zero_bits == n) return zero_bits;
mask <<= 1;
/* zero_bits < n */
}
/* zero_bits < n */
/* Check as many full words as possible */
word_index ++;
bits = bitmap[word_index];
while (zero_bits < n && bits == 0)
{
zero_bits += BITS_PER_WORD;
word_index ++;
if (zero_bits < n) // Be careful not to go over the end
bits = bitmap[word_index];
}
/* Check the final part word */
mask = 1;
while (zero_bits < n && ((bits & mask) == 0))
{
zero_bits ++;
mask <<= 1;
}
return zero_bits;
}
/* search the bitmap from the high end down looking for n contiguous zeros */
POLYUNSIGNED Bitmap::FindFree
(
POLYUNSIGNED limit, /* The highest numbered bit that's too small to use */
POLYUNSIGNED bitno, /* The lowest numbered bit that's too large to use */
POLYUNSIGNED n /* The number of consecutive zero bits required */
)
{
if (limit + n >= bitno)
return 0;
POLYUNSIGNED candidate = bitno - n;
ASSERT (bitno > limit);
while (1)
{
POLYUNSIGNED bits_free = CountZeroBits(candidate, n);
if (n <= bits_free)
return candidate;
if (candidate < n - bits_free + limit)
return 0;
candidate -= (n - bits_free);
}
}
<commit_msg>A heap segment may possibly be completely full in which case the length for ClearBits could be zero.<commit_after>/*
Title: Bitmap. Generally used by the garbage collector to indicate allocated words
Copyright (c) 2006 David C.J. Matthews
Based on original code in garbage_collect.c.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
Bitmaps are used particularly in the garbage collector to indicate allocated
words. The efficiency of this code is crucial for the speed of the garbage
collector.
*/
#ifdef _WIN32_WCE
#include "winceconfig.h"
#include "wincelib.h"
#else
#ifdef WIN32
#include "winconfig.h"
#else
#include "config.h"
#endif
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(h) assert(h)
#else
#define ASSERT(h)
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include "bitmap.h"
#include "globals.h"
Bitmap::Bitmap(POLYUNSIGNED bits)
{
POLYUNSIGNED words = (bits+BITS_PER_WORD-1) / BITS_PER_WORD;
m_bits = (POLYUNSIGNED *)calloc(words, sizeof(POLYUNSIGNED));
}
bool Bitmap::Create(POLYUNSIGNED bits)
{
free(m_bits);
POLYUNSIGNED words = (bits+BITS_PER_WORD-1) / BITS_PER_WORD;
m_bits = (POLYUNSIGNED *)calloc(words, sizeof(POLYUNSIGNED));
return m_bits != 0;
}
Bitmap::~Bitmap()
{
free(m_bits);
}
// Set a range of bits in a bitmap. This checks that the bits are not already set.
void Bitmap::SetBits(POLYUNSIGNED bitno, POLYUNSIGNED length)
{
POLYUNSIGNED word_index = bitno / BITS_PER_WORD;
ASSERT (0 < length);
/* Set the first part word */
POLYUNSIGNED start_bit_index = bitno % BITS_PER_WORD;
POLYUNSIGNED stop_bit_index = start_bit_index + length;
/* Do we need to change more than one word? */
if (stop_bit_index < BITS_PER_WORD)
{
/* N.B. On some machines shifts of the number of bits per word can mean
no shift at all. */
const POLYUNSIGNED mask1 = ((~ (POLYUNSIGNED)0)) << start_bit_index;
const POLYUNSIGNED mask2 = ((~ (POLYUNSIGNED)0)) << stop_bit_index;
const POLYUNSIGNED mask = mask1 & ~mask2;
ASSERT((m_bits[word_index] & mask) == 0);
m_bits[word_index] |= mask;
return;
}
else /* Set all the bits we can in the first word */
{
const POLYUNSIGNED mask = ((POLYUNSIGNED)(~ 0)) << start_bit_index;
ASSERT((m_bits[word_index] & mask) == 0);
m_bits[word_index] |= mask;
/* length = length - (BITS_PER_WORD - start_bit_index); */
length = stop_bit_index - BITS_PER_WORD;
}
/* Invariant: 0 <= length */
/* Set as many full words as possible */
while (BITS_PER_WORD <= length)
{
/* Invariant: BITS_PER_WORD <= length */
word_index ++;
ASSERT(m_bits[word_index] == 0);
m_bits[word_index] = ~ (POLYUNSIGNED)0;
length -= BITS_PER_WORD;
/* Invariant: 0 <= length */
}
/* Invariant: 0 <= length < BITS_PER_WORD */
if (length == 0) return;
/* Invariant: 0 < length < BITS_PER_WORD */
/* Set the final part word */
word_index ++;
const POLYUNSIGNED mask1 = (~ (POLYUNSIGNED)0) << 0;
const POLYUNSIGNED mask2 = (~ (POLYUNSIGNED)0) << length;
const POLYUNSIGNED mask = mask1 & ~mask2;
ASSERT((m_bits[word_index] & mask) == 0);
m_bits[word_index] |= mask;
}
void Bitmap::ClearBits(POLYUNSIGNED bitno, POLYUNSIGNED length)
{
POLYUNSIGNED word_index = bitno / BITS_PER_WORD;
if (length == 0)
return;
// Clear the first part word
POLYUNSIGNED start_bit_index = bitno % BITS_PER_WORD;
POLYUNSIGNED stop_bit_index = start_bit_index + length;
/* Do we need to change more than one word? */
if (stop_bit_index < BITS_PER_WORD)
{
const POLYUNSIGNED mask1 = ((~ (POLYUNSIGNED)0)) << start_bit_index;
const POLYUNSIGNED mask2 = ((~ (POLYUNSIGNED)0)) << stop_bit_index;
const POLYUNSIGNED mask = mask1 & ~mask2;
m_bits[word_index] &= ~mask;
return;
}
else /* Clear all the bits we can in the first word */
{
const POLYUNSIGNED mask = ((POLYUNSIGNED)(~ 0)) << start_bit_index;
m_bits[word_index] &= ~mask;
length = stop_bit_index - BITS_PER_WORD;
}
/* Invariant: 0 <= length */
// Clear as many full words as possible.
while (BITS_PER_WORD <= length)
{
/* Invariant: BITS_PER_WORD <= length */
word_index ++;
m_bits[word_index] = 0;
length -= BITS_PER_WORD;
/* Invariant: 0 <= length */
}
/* Invariant: 0 <= length < BITS_PER_WORD */
if (length == 0)
return;
/* Invariant: 0 < length < BITS_PER_WORD */
// Clear the final part word
word_index ++;
const POLYUNSIGNED mask1 = (~ (POLYUNSIGNED)0) << 0;
const POLYUNSIGNED mask2 = (~ (POLYUNSIGNED)0) << length;
const POLYUNSIGNED mask = mask1 & ~mask2;
m_bits[word_index] &= ~mask;
}
// How many zero bits (maximum n) are there in the bitmap, starting at location start? */
POLYUNSIGNED Bitmap::CountZeroBits(POLYUNSIGNED bitno, POLYUNSIGNED n)
{
POLYUNSIGNED *bitmap = m_bits;
/* Less naive version */
POLYUNSIGNED word_index = bitno / BITS_PER_WORD;
POLYUNSIGNED bit_index = bitno % BITS_PER_WORD;
POLYUNSIGNED bits = bitmap[word_index];
POLYUNSIGNED mask = (POLYUNSIGNED)1 << bit_index;
POLYUNSIGNED zero_bits = 0;
ASSERT (0 < n);
/* Check the first part word */
while (mask != 0)
{
/* zero_bits < n */
if ((bits & mask) != 0) return zero_bits;
zero_bits ++;
if (zero_bits == n) return zero_bits;
mask <<= 1;
/* zero_bits < n */
}
/* zero_bits < n */
/* Check as many full words as possible */
word_index ++;
bits = bitmap[word_index];
while (zero_bits < n && bits == 0)
{
zero_bits += BITS_PER_WORD;
word_index ++;
if (zero_bits < n) // Be careful not to go over the end
bits = bitmap[word_index];
}
/* Check the final part word */
mask = 1;
while (zero_bits < n && ((bits & mask) == 0))
{
zero_bits ++;
mask <<= 1;
}
return zero_bits;
}
/* search the bitmap from the high end down looking for n contiguous zeros */
POLYUNSIGNED Bitmap::FindFree
(
POLYUNSIGNED limit, /* The highest numbered bit that's too small to use */
POLYUNSIGNED bitno, /* The lowest numbered bit that's too large to use */
POLYUNSIGNED n /* The number of consecutive zero bits required */
)
{
if (limit + n >= bitno)
return 0;
POLYUNSIGNED candidate = bitno - n;
ASSERT (bitno > limit);
while (1)
{
POLYUNSIGNED bits_free = CountZeroBits(candidate, n);
if (n <= bits_free)
return candidate;
if (candidate < n - bits_free + limit)
return 0;
candidate -= (n - bits_free);
}
}
<|endoftext|>
|
<commit_before>//! \file **************************************************************
//! \brief Source ressource.
//!
//! - Compilateur : GCC,MinGW
//!
//! \author Antoine Maleyrie
//! \version 0.19
//! \date 30.03.2013
//!
//! ********************************************************************
/*
* Copyright © 2013 - Antoine Maleyrie.
*/
#include "resource.hpp"
#include <wx/jsonval.h>
#include <wx/jsonreader.h>
#include <wx/clipbrd.h>
#include <wx/sstream.h>
#include <wx/intl.h>
#include <wx/url.h>
#include <wx/log.h>
#if defined(__WXMSW__)
#include <windows.h>
#endif
//TEST
#include <iostream>
// *********************************************************************
// Class Resource
// *********************************************************************
Resource::Resource()
{
#if defined(__UNIX__)
#elif defined(__WXMSW__)
#endif
//Le menu doit être afficher (par défaut)
_showMenu = true;
//Volume 100%
_ttsVolume = 1.0;
//Par défaut on ne démarre pas l'application au démarrage.
_powerOn = false;
//Liste des langues
_languages["af"] = _("Afrikaans");
_languages["sq"] = _("Albanian");
_languages["ar"] = _("Arabic");
_languages["hy"] = _("Armenian");
_languages["az"] = _("Azerbaijani");
_languages["eu"] = _("Basque");
_languages["be"] = _("Belarusian");
_languages["bn"] = _("Bengali");
_languages["bg"] = _("Bulgarian");
_languages["ca"] = _("Catalan");
_languages["zh-CN"] = _("Chinese");
_languages["hr"] = _("Croatian");
_languages["sr"] = _("Czech");
_languages["da"] = _("Danish");
_languages["nl"] = _("Dutch");
_languages["en"] = _("English");
_languages["eo"] = _("Esperanto");
_languages["et"] = _("Estonian");
_languages["tl"] = _("Filipino");
_languages["fi"] = _("Finnish");
_languages["fr"] = _("French");
_languages["gl"] = _("Galician");
_languages["ka"] = _("Georgian");
_languages["de"] = _("German");
_languages["el"] = _("Greek");
_languages["gu"] = _("Gujarati");
_languages["ht"] = _("Haitian Creole");
_languages["iw"] = _("Hebrew");
_languages["hi"] = _("Hindi");
_languages["hu"] = _("Hungarian");
_languages["is"] = _("Icelandic");
_languages["id"] = _("Indonesian");
_languages["ga"] = _("Irish");
_languages["it"] = _("Italian");
_languages["ja"] = _("Japanese");
_languages["kn"] = _("Kannada");
_languages["ko"] = _("Korean");
_languages["lo"] = _("Lao");
_languages["la"] = _("Latin");
_languages["lv"] = _("Latvian");
_languages["it"] = _("Lithuanian");
_languages["mk"] = _("Macedonian");
_languages["ms"] = _("Malay");
_languages["mt"] = _("Maltese");
_languages["no"] = _("Norwegian");
_languages["fa"] = _("Persian");
_languages["pl"] = _("Polish");
_languages["pt"] = _("Portuguese");
_languages["ro"] = _("Romanian");
_languages["ru"] = _("Russian");
_languages["sr"] = _("Serbian");
_languages["sk"] = _("Slovak");
_languages["sl"] = _("Slovenian");
_languages["es"] = _("Spanish");
_languages["sw"] = _("Swahili");
_languages["sv"] = _("Swedish");
_languages["ta"] = _("Tamil");
_languages["te"] = _("Telugu");
_languages["th"] = _("Thai");
_languages["tr"] = _("Turkish");
_languages["uk"] = _("Ukrainian");
_languages["ur"] = _("Urdu");
_languages["vi"] = _("Vietnamese");
_languages["cy"] = _("Welsh");
_languages["yi"] = _("Yiddish");
//Liste des actions
_actions[_("Translation")] = "ActTranslation";
_actions[_("Translation to list")] = "ActTranslationToList";
_actions[_("Learn a list")] = "ActLearn";
}
Resource::~Resource()
{
#if defined(__UNIX__)
#elif defined(__WXMSW__)
#endif
}
std::map<wxString, wxString> const& Resource::getLanguages()const
{
return _languages;
}
wxString Resource::abbreviationToLanguage(wxString const& abbreviation)const
{
return _languages.at(abbreviation);
}
wxString Resource::languageToAbbreviation(wxString const& language)const
{
for(auto &it: _languages)
{
if(it.second == language)
return it.first;
}
return wxEmptyString;
}
std::map<wxString, wxString> const& Resource::getActions()const
{
return _actions;
}
wxString Resource::typeToAction(wxString const& actTypeName)const
{
for(auto &it: _actions)
{
if(it.second == actTypeName)
return it.first;
}
return wxEmptyString;
}
wxString Resource::actionsToType(wxString const& actionName)const
{
return _actions.at(actionName);
}
wxString Resource::getClipboard()
{
wxString text;
#if defined(__WXMSW__)
//buffer ...
INPUT input[32];
int iinput = 0;
//Relacher tout les tocuhes.
for(int i = 0; i != 0xff; i++)
{
if(GetAsyncKeyState(i))
{
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = i;
input[iinput].ki.wScan = 0;
input[iinput].ki.dwFlags = KEYEVENTF_KEYUP;//released
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
}
}
//Presser ctrl
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = VK_CONTROL;
input[iinput].ki.wScan = MapVirtualKey( VK_CONTROL, MAPVK_VK_TO_VSC );
input[iinput].ki.dwFlags = 0;//pressed
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
//Presser 'c'
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = 0x43;//C key
input[iinput].ki.wScan = 0;
input[iinput].ki.dwFlags = 0;//pressed
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
//Relacher 'c'
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = 0x43;//C key
input[iinput].ki.wScan = 0;
input[iinput].ki.dwFlags = KEYEVENTF_KEYUP;//released
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
//Relacher ctrl
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = VK_CONTROL;
input[iinput].ki.wScan = 0;
input[iinput].ki.dwFlags = KEYEVENTF_KEYUP;//released
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
//Simule l'appuie sur ctrl+c
SendInput(iinput, input, sizeof(INPUT));
Sleep(40);
#endif
//Lire le text de la presse papier
if (wxTheClipboard->Open())
{
#if defined(__UNIX__)
//Lire le text qui ce trouvent dans la presse papier primére.
wxTheClipboard->UsePrimarySelection(true);
#endif
if (wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxTextDataObject data;
wxTheClipboard->GetData( data );
text = data.GetText();
}
wxTheClipboard->Close();
}
//On enlève les éventuelle retour à la ligne en début et fin du texte.
text.StartsWith('\n', &text);
text.EndsWith('\n', &text);
//On enlève les éventuelle espace en début et fin du texte.
text.StartsWith(' ', &text);
text.EndsWith(' ', &text);
//On enlève les éventuelle (2eme fois) retour à la ligne en début et fin du texte.
text.StartsWith('\n', &text);
text.EndsWith('\n', &text);
return text;
}
wxString Resource::getTranslations(
std::map<wxString, wxArrayString>* translations,
wxString const& text,
wxString const& lgsrc,
wxString const& lgto)
{
//Représentent la traduction au forma json
wxString jsonText;
//Si il y a un texte à traduire.
if(!text.IsEmpty())
{
//Télécharger la raiponce de google
wxMemoryBuffer buffer;
if(!Resource::getInstance()->downloadFromUrl(&buffer,"http://translate.google.com/translate_a/t?ie=UTF-8&oe=UTF-8&client=x&text="+text+"&hl="+lgto+"&sl="+lgsrc+"&tl="+lgto))
return wxEmptyString;
//ajouter au jsonText
jsonText.Append(wxString::FromUTF8((const char *)buffer.GetData(), buffer.GetDataLen()));
}
else
return wxEmptyString;
//std::cout << jsonText << std::endl << std::endl;
//Variable qui va contenir la traduction.
wxString trans;
//Variable pour la lecture du JSON
wxJSONValue root;
wxJSONReader reader;
//Lecture du JSON
if(reader.Parse(jsonText, &root))
{
wxLogError(_("The reading the JSON document was failed."));
return wxEmptyString;
}
//std::cout << root.GetInfo() << std::endl;
//wxJSONValue& sentences = root["sentences"];
//std::cout << sentences.GetInfo() << std::endl;
//for(int i = 0; i < sentences.Size(); i++)
//std::cout << sentences[0]["trans"].AsString() << std::endl;
//std::cout << root["wxWidgets"]["Version"].GetInfo() << std::endl;
//Récupère la phrase.
wxJSONValue& sentences = root["sentences"];
//Récupère la traduction (principale)
for(int i = 0; i < sentences.Size(); i++)
trans << sentences[i]["trans"].AsString();
////Analyser du forma jSON provenant de google (Code fonctionnelle ...)
//wxString mainTranslate;
//bool inSentences = false;
//bool inSentencesTrans = false;
//bool inDict = false;
//bool inDictPos = false;
//bool inDictTerms = false;
//wxString parseText;
//wxString proposal;
//unsigned int accolade = 0;
//unsigned int quote = 0;
//for(size_t i = 0; i<jsonText.Len(); i++)
//{
//if(jsonText[i] == '{')
//accolade++;
//else if(jsonText[i] == '}')
//accolade--;
//else if(jsonText[i] == ':')
//{
//if(!parseText.IsEmpty())
//{
//if((accolade-1) == 0)
//{
//inSentences = false;
//inDict = false;
//if(parseText == "sentences")
//inSentences = true;
//else if(parseText == "dict")
//inDict = true;
//}
//else if((accolade-1) == 1)
//{
//if(inSentences)
//{
//inSentencesTrans = false;
//if(parseText == "trans")
//inSentencesTrans = true;
//}
//else if(inDict)
//{
//inDictPos = false;
//inDictTerms = false;
//if(parseText == "pos")
//inDictPos = true;
//else if(parseText == "terms")
//inDictTerms = true;
//}
//}
//}
//}
//else if(jsonText[i] == ',')
//{
//if(!parseText.IsEmpty())
//{
//if(inSentencesTrans)
//{
////ici parseText est la traduction du text
//mainTranslate = parseText;
//}
//else if(inDictPos)
//{
////ici parseText est la proposition
//proposal = parseText;
//(*translations)[proposal] = wxArrayString();
//}
//else if(inDictTerms)
//{
////ici parseText est un terme de la proposition
//(*translations)[proposal].Add(parseText);
//}
//}
//}
//else if(jsonText[i] == '"')
//{
//if(quote == 0)
//{
//parseText.Empty();
//quote = 1;
//}
//else
//quote = 0;
//}
//else if(quote == 1)
//{
//parseText << jsonText[i];
//}
//}
//return mainTranslate;
//On retour la traduction du texte.
return trans;
}
//! \todo ajouter une timeout
bool Resource::downloadFromUrl(wxMemoryBuffer* buffer, wxString const& sUrl)
{
wxURL url(sUrl);
//Erreur ?
if (url.GetError() == wxURL_NOERR)
{
//Récupération des données.
wxInputStream *urlStream = url.GetInputStream();
if(!urlStream)
return false;
//Erreur ?
if(urlStream->IsOk())
{
//data temporaire.
uint8_t tmpData[1024];
//Lie des données temps qu'il y en a.
while(urlStream->CanRead() && !urlStream->Eof())
{
urlStream->Read(tmpData, 1024);
buffer->AppendData(tmpData, urlStream->LastRead());
}
}
delete urlStream;
}
return true;
}
void Resource::setShowMenu(bool showMenu)
{
_showMenu = showMenu;
}
bool Resource::getShowMenu()
{
return _showMenu;
}
//! \todo a compléter pour réellement le prendre en compte coter os.
void Resource::setPowerOn(bool powerOn)
{
_powerOn = powerOn;
}
bool Resource::getPowerOn()
{
return _powerOn;
}
void Resource::load(wxFileConfig& fileConfig)
{
fileConfig.Read("show_menu", &_showMenu);
fileConfig.Read("power_on", &_powerOn);
}
void Resource::save(wxFileConfig& fileConfig)const
{
fileConfig.Write("show_menu", _showMenu);
fileConfig.Write("power_on", _powerOn);
}
<commit_msg>reimplement getTranslations with wxJSON<commit_after>//! \file **************************************************************
//! \brief Source ressource.
//!
//! - Compilateur : GCC,MinGW
//!
//! \author Antoine Maleyrie
//! \version 0.19
//! \date 30.03.2013
//!
//! ********************************************************************
/*
* Copyright © 2013 - Antoine Maleyrie.
*/
#include "resource.hpp"
#include <wx/jsonval.h>
#include <wx/jsonreader.h>
#include <wx/clipbrd.h>
#include <wx/sstream.h>
#include <wx/intl.h>
#include <wx/url.h>
#include <wx/log.h>
#if defined(__WXMSW__)
#include <windows.h>
#endif
//TEST
#include <iostream>
// *********************************************************************
// Class Resource
// *********************************************************************
Resource::Resource()
{
#if defined(__UNIX__)
#elif defined(__WXMSW__)
#endif
//Le menu doit être afficher (par défaut)
_showMenu = true;
//Volume 100%
_ttsVolume = 1.0;
//Par défaut on ne démarre pas l'application au démarrage.
_powerOn = false;
//Liste des langues
_languages["af"] = _("Afrikaans");
_languages["sq"] = _("Albanian");
_languages["ar"] = _("Arabic");
_languages["hy"] = _("Armenian");
_languages["az"] = _("Azerbaijani");
_languages["eu"] = _("Basque");
_languages["be"] = _("Belarusian");
_languages["bn"] = _("Bengali");
_languages["bg"] = _("Bulgarian");
_languages["ca"] = _("Catalan");
_languages["zh-CN"] = _("Chinese");
_languages["hr"] = _("Croatian");
_languages["sr"] = _("Czech");
_languages["da"] = _("Danish");
_languages["nl"] = _("Dutch");
_languages["en"] = _("English");
_languages["eo"] = _("Esperanto");
_languages["et"] = _("Estonian");
_languages["tl"] = _("Filipino");
_languages["fi"] = _("Finnish");
_languages["fr"] = _("French");
_languages["gl"] = _("Galician");
_languages["ka"] = _("Georgian");
_languages["de"] = _("German");
_languages["el"] = _("Greek");
_languages["gu"] = _("Gujarati");
_languages["ht"] = _("Haitian Creole");
_languages["iw"] = _("Hebrew");
_languages["hi"] = _("Hindi");
_languages["hu"] = _("Hungarian");
_languages["is"] = _("Icelandic");
_languages["id"] = _("Indonesian");
_languages["ga"] = _("Irish");
_languages["it"] = _("Italian");
_languages["ja"] = _("Japanese");
_languages["kn"] = _("Kannada");
_languages["ko"] = _("Korean");
_languages["lo"] = _("Lao");
_languages["la"] = _("Latin");
_languages["lv"] = _("Latvian");
_languages["it"] = _("Lithuanian");
_languages["mk"] = _("Macedonian");
_languages["ms"] = _("Malay");
_languages["mt"] = _("Maltese");
_languages["no"] = _("Norwegian");
_languages["fa"] = _("Persian");
_languages["pl"] = _("Polish");
_languages["pt"] = _("Portuguese");
_languages["ro"] = _("Romanian");
_languages["ru"] = _("Russian");
_languages["sr"] = _("Serbian");
_languages["sk"] = _("Slovak");
_languages["sl"] = _("Slovenian");
_languages["es"] = _("Spanish");
_languages["sw"] = _("Swahili");
_languages["sv"] = _("Swedish");
_languages["ta"] = _("Tamil");
_languages["te"] = _("Telugu");
_languages["th"] = _("Thai");
_languages["tr"] = _("Turkish");
_languages["uk"] = _("Ukrainian");
_languages["ur"] = _("Urdu");
_languages["vi"] = _("Vietnamese");
_languages["cy"] = _("Welsh");
_languages["yi"] = _("Yiddish");
//Liste des actions
_actions[_("Translation")] = "ActTranslation";
_actions[_("Translation to list")] = "ActTranslationToList";
_actions[_("Learn a list")] = "ActLearn";
}
Resource::~Resource()
{
#if defined(__UNIX__)
#elif defined(__WXMSW__)
#endif
}
std::map<wxString, wxString> const& Resource::getLanguages()const
{
return _languages;
}
wxString Resource::abbreviationToLanguage(wxString const& abbreviation)const
{
return _languages.at(abbreviation);
}
wxString Resource::languageToAbbreviation(wxString const& language)const
{
for(auto &it: _languages)
{
if(it.second == language)
return it.first;
}
return wxEmptyString;
}
std::map<wxString, wxString> const& Resource::getActions()const
{
return _actions;
}
wxString Resource::typeToAction(wxString const& actTypeName)const
{
for(auto &it: _actions)
{
if(it.second == actTypeName)
return it.first;
}
return wxEmptyString;
}
wxString Resource::actionsToType(wxString const& actionName)const
{
return _actions.at(actionName);
}
wxString Resource::getClipboard()
{
wxString text;
#if defined(__WXMSW__)
//buffer ...
INPUT input[32];
int iinput = 0;
//Relacher tout les tocuhes.
for(int i = 0; i != 0xff; i++)
{
if(GetAsyncKeyState(i))
{
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = i;
input[iinput].ki.wScan = 0;
input[iinput].ki.dwFlags = KEYEVENTF_KEYUP;//released
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
}
}
//Presser ctrl
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = VK_CONTROL;
input[iinput].ki.wScan = MapVirtualKey( VK_CONTROL, MAPVK_VK_TO_VSC );
input[iinput].ki.dwFlags = 0;//pressed
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
//Presser 'c'
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = 0x43;//C key
input[iinput].ki.wScan = 0;
input[iinput].ki.dwFlags = 0;//pressed
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
//Relacher 'c'
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = 0x43;//C key
input[iinput].ki.wScan = 0;
input[iinput].ki.dwFlags = KEYEVENTF_KEYUP;//released
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
//Relacher ctrl
input[iinput].type = INPUT_KEYBOARD;
input[iinput].ki.wVk = VK_CONTROL;
input[iinput].ki.wScan = 0;
input[iinput].ki.dwFlags = KEYEVENTF_KEYUP;//released
input[iinput].ki.time = 0;
input[iinput].ki.dwExtraInfo = 0;
iinput++;
//Simule l'appuie sur ctrl+c
SendInput(iinput, input, sizeof(INPUT));
Sleep(40);
#endif
//Lire le text de la presse papier
if (wxTheClipboard->Open())
{
#if defined(__UNIX__)
//Lire le text qui ce trouvent dans la presse papier primére.
wxTheClipboard->UsePrimarySelection(true);
#endif
if (wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxTextDataObject data;
wxTheClipboard->GetData( data );
text = data.GetText();
}
wxTheClipboard->Close();
}
//On enlève les éventuelle retour à la ligne en début et fin du texte.
text.StartsWith('\n', &text);
text.EndsWith('\n', &text);
//On enlève les éventuelle espace en début et fin du texte.
text.StartsWith(' ', &text);
text.EndsWith(' ', &text);
//On enlève les éventuelle (2eme fois) retour à la ligne en début et fin du texte.
text.StartsWith('\n', &text);
text.EndsWith('\n', &text);
return text;
}
wxString Resource::getTranslations(
std::map<wxString, wxArrayString>* translations,
wxString const& text,
wxString const& lgsrc,
wxString const& lgto)
{
//Représentent la traduction au forma json
wxString jsonText;
//Si il y a un texte à traduire.
if(!text.IsEmpty())
{
//Télécharger la raiponce de google
wxMemoryBuffer buffer;
if(!Resource::getInstance()->downloadFromUrl(&buffer,"http://translate.google.com/translate_a/t?ie=UTF-8&oe=UTF-8&client=x&text="+text+"&hl="+lgto+"&sl="+lgsrc+"&tl="+lgto))
return wxEmptyString;
//ajouter au jsonText
jsonText.Append(wxString::FromUTF8((const char *)buffer.GetData(), buffer.GetDataLen()));
}
else
return wxEmptyString;
//Variable qui va contenir la traduction.
wxString trans;
//Variable pour la lecture du JSON
wxJSONValue root;
wxJSONReader reader;
//Lecture du JSON
if(reader.Parse(jsonText, &root))
{
wxLogError(_("The reading the JSON document was failed."));
return wxEmptyString;
}
//Récupère la phrase.
wxJSONValue& sentences = root["sentences"];
//Récupère la traduction (principale).
for(int i = 0; i < sentences.Size(); i++)
trans << sentences[i]["trans"].AsString();
//Récupère le dictionnaire (Les autres traductions).
wxJSONValue& dict = root["dict"];
for(int i = 0; i < dict.Size(); i++)
{
wxString pos = dict[i]["pos"].AsString();
wxJSONValue& terms = dict[i]["terms"];
for(int i = 0; i < terms.Size(); i++)
{
(*translations)[pos].Add(terms[i].AsString());
}
}
return trans;
}
//! \todo ajouter une timeout
bool Resource::downloadFromUrl(wxMemoryBuffer* buffer, wxString const& sUrl)
{
wxURL url(sUrl);
//Erreur ?
if (url.GetError() == wxURL_NOERR)
{
//Récupération des données.
wxInputStream *urlStream = url.GetInputStream();
if(!urlStream)
return false;
//Erreur ?
if(urlStream->IsOk())
{
//data temporaire.
uint8_t tmpData[1024];
//Lie des données temps qu'il y en a.
while(urlStream->CanRead() && !urlStream->Eof())
{
urlStream->Read(tmpData, 1024);
buffer->AppendData(tmpData, urlStream->LastRead());
}
}
delete urlStream;
}
return true;
}
void Resource::setShowMenu(bool showMenu)
{
_showMenu = showMenu;
}
bool Resource::getShowMenu()
{
return _showMenu;
}
//! \todo a compléter pour réellement le prendre en compte coter os.
void Resource::setPowerOn(bool powerOn)
{
_powerOn = powerOn;
}
bool Resource::getPowerOn()
{
return _powerOn;
}
void Resource::load(wxFileConfig& fileConfig)
{
fileConfig.Read("show_menu", &_showMenu);
fileConfig.Read("power_on", &_powerOn);
}
void Resource::save(wxFileConfig& fileConfig)const
{
fileConfig.Write("show_menu", _showMenu);
fileConfig.Write("power_on", _powerOn);
}
<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/lite/python/graphdef_to_tfl_flatbuffer.h"
#include <ostream>
#include <utility>
#include "llvm/Support/ToolOutputFile.h"
#include "mlir/IR/MLIRContext.h" // TF:local_config_mlir
#include "mlir/IR/Module.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Support/FileUtilities.h" // TF:local_config_mlir
#include "mlir/Transforms/ViewOpGraph.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/lite/common/tfl_pass_config.h"
#include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h"
#include "tensorflow/compiler/mlir/lite/tf_to_tfl_flatbuffer.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/protobuf/graph_debug_info.pb.h"
#include "tensorflow/lite/toco/model_flags.pb.h"
#include "tensorflow/lite/toco/toco_flags.pb.h"
#include "tensorflow/lite/toco/types.pb.h"
#include "tensorflow/stream_executor/lib/statusor.h"
using stream_executor::port::StatusOr;
namespace tensorflow {
namespace {
// Op def string for TFLite_Detection_PostProcess Op.
const char kDetectionPostProcessOp[] =
"name: 'TFLite_Detection_PostProcess' input_arg: { name: "
"'raw_outputs/box_encodings' type: DT_FLOAT } input_arg: { name: "
"'raw_outputs/class_predictions' type: DT_FLOAT } input_arg: { name: "
"'anchors' type: DT_FLOAT } output_arg: { name: "
"'TFLite_Detection_PostProcess' type: DT_FLOAT } output_arg: { name: "
"'TFLite_Detection_PostProcess:1' type: DT_FLOAT } output_arg: { name: "
"'TFLite_Detection_PostProcess:2' type: DT_FLOAT } output_arg: { name: "
"'TFLite_Detection_PostProcess:3' type: DT_FLOAT } attr : { name: "
"'h_scale' type: 'float'} attr : { name: 'max_classes_per_detection' "
"type: 'int'} attr : { name: 'max_detections' type: 'int'} attr : { "
"name: 'nms_iou_threshold' type: 'float'} attr : { name: "
"'nms_score_threshold' type: 'float'} attr : { name: 'num_classes' type: "
"'int'} attr : { name: 'w_scale' type: 'float'} attr : { name: 'x_scale' "
"type: 'float'} attr : { name: 'y_scale' type: 'float'} attr { name: "
"'detections_per_class' type: 'int' default_value { i : 100 }} attr { "
"name: 'use_regular_nms' type: 'bool' default_value { b : false }}";
// Converts the toco::IODataType to tensorflow::DataType. Only contains the
// conversion mapping for constants defined in TFLite Python API.
DataType ConvertIODataTypeToDataType(toco::IODataType dtype) {
switch (dtype) {
case toco::IODataType::FLOAT:
return DT_FLOAT;
case toco::IODataType::QUANTIZED_UINT8:
return DT_QUINT8;
case toco::IODataType::INT8:
return DT_QINT8;
case toco::IODataType::INT32:
return DT_INT32;
case toco::IODataType::INT64:
return DT_INT64;
case toco::IODataType::STRING:
return DT_STRING;
case toco::IODataType::BOOL:
return DT_BOOL;
default:
return DT_INVALID;
}
}
StatusOr<std::pair<double, double>> InputStatsToMinMax(double mean, double std,
DataType type) {
// Only qint8 and quint8 are considered here.
double qmin, qmax;
if (type == DT_QUINT8) {
qmin = 0.0;
qmax = 255.0;
} else if (type == DT_QINT8) {
qmin = -128.0;
qmax = 127.0;
} else {
return errors::InvalidArgument("Only int8 and uint8 are considered.");
}
return std::make_pair((qmin - mean) / std, (qmax - mean) / std);
}
// Give a warning for any unused flags that have been specified.
void WarningUnusedFlags(const toco::ModelFlags& model_flags,
const toco::TocoFlags& toco_flags) {
if (toco_flags.output_format()) {
LOG(WARNING) << "Ignored output_format.";
}
if (toco_flags.default_ranges_min() || toco_flags.default_ranges_max()) {
LOG(WARNING) << "Ignored default_ranges_stats.";
}
if (toco_flags.drop_control_dependency()) {
LOG(WARNING) << "Ignored drop_control_dependency.";
}
if (toco_flags.reorder_across_fake_quant()) {
LOG(WARNING) << "Ignored reorder_across_fake_quant.";
}
if (model_flags.change_concat_input_ranges()) {
LOG(WARNING) << "Ignored change_concat_input_ranges.";
}
if (toco_flags.dump_graphviz_include_video()) {
LOG(WARNING) << "Ignored dump_graphviz_video.";
}
if (model_flags.allow_nonexistent_arrays()) {
LOG(WARNING) << "Allow allow_nonexistent_arrays.";
}
}
// Dumps the op graph of the `module` to `filename` in DOT format.
Status DumpOpGraphToFile(mlir::ModuleOp module, const std::string& filename) {
std::string error_message;
auto output = mlir::openOutputFile(filename, &error_message);
if (!error_message.empty()) {
return errors::InvalidArgument("Failed to open file in %s.", filename);
}
mlir::PassManager pm(module.getContext());
pm.addPass(mlir::createPrintOpGraphPass(output->os()));
if (failed(pm.run(module))) {
return errors::Unknown("Failed to dump Op Graph from MLIR module.");
}
output->keep();
return Status::OK();
}
Status RegisterCustomBuiltinOps(const std::vector<string> extra_tf_opdefs) {
for (const auto& tf_opdefs_string : extra_tf_opdefs) {
tensorflow::OpDef opdef;
if (!tensorflow::protobuf::TextFormat::ParseFromString(tf_opdefs_string,
&opdef)) {
return errors::InvalidArgument("fail to parse extra OpDef");
}
// Make sure the op is not already registered. If registered continue.
const OpRegistrationData* op_reg =
tensorflow::OpRegistry::Global()->LookUp(opdef.name());
if (op_reg) continue;
tensorflow::OpRegistry::Global()->Register(
[opdef](tensorflow::OpRegistrationData* op_reg_data) -> Status {
*op_reg_data = tensorflow::OpRegistrationData(opdef);
return Status::OK();
});
}
return Status::OK();
}
} // namespace
Status ConvertGraphDefToTFLiteFlatBuffer(const toco::ModelFlags& model_flags,
const toco::TocoFlags& toco_flags,
const GraphDebugInfo& debug_info,
const GraphDef& input,
string* result) {
mlir::MLIRContext context;
GraphImportConfig specs;
mlir::TFL::QuantizationSpecs quant_specs;
// Parse input arrays.
std::vector<string> node_names;
std::vector<string> node_dtypes;
std::vector<std::vector<int>> node_shapes;
std::vector<double> node_mins;
std::vector<double> node_maxs;
quant_specs.inference_input_type =
ConvertIODataTypeToDataType(toco_flags.inference_input_type());
tensorflow::DataType inference_type =
ConvertIODataTypeToDataType(toco_flags.inference_type());
// Use non-float flag `inference_input_type` to override the `inference_type`
// because we have to apply quantization to satisfy that.
if (quant_specs.inference_input_type != tensorflow::DT_FLOAT) {
inference_type = quant_specs.inference_input_type;
}
for (auto& flag : model_flags.input_arrays()) {
node_names.push_back(flag.name());
// TOCO doesn't required `data_type` to be filled for every input.
// If it's not filled, make it an empty string so the importer will use
// the data type in the NodeDef.
auto toco_data_type = flag.data_type();
if (toco_data_type == ::toco::IODataType::IO_DATA_TYPE_UNKNOWN) {
node_dtypes.push_back("");
} else {
node_dtypes.push_back(
DataType_Name(ConvertIODataTypeToDataType(toco_data_type)));
}
node_shapes.push_back(std::vector<int>(flag.shape().dims().begin(),
flag.shape().dims().end()));
// Currently, only UINT8 and INT8 require inputs stats
if (inference_type == DT_QINT8 || inference_type == DT_QUINT8) {
TF_ASSIGN_OR_RETURN(
auto min_max, InputStatsToMinMax(flag.mean_value(), flag.std_value(),
inference_type));
node_mins.push_back(min_max.first);
node_maxs.push_back(min_max.second);
}
}
TF_RETURN_IF_ERROR(tensorflow::ParseInputArrayInfo(
node_names, node_dtypes, node_shapes, &specs.inputs));
if (mlir::TFL::GetInputNodeQuantSpecs(node_names, node_mins, node_maxs,
inference_type, &quant_specs)) {
return errors::InvalidArgument("Failed to get input quant spec.");
}
// Some extra flag related to post training quantization. If post-training
// quantization is enabled, `inference_type` and `inference_input_type` are
// not used by MLIR passes.
if (toco_flags.post_training_quantize()) {
quant_specs.weight_quantization = true;
if (toco_flags.quantize_to_float16()) {
quant_specs.inference_type = tensorflow::DT_HALF;
quant_specs.inference_input_type = tensorflow::DT_HALF;
} else {
quant_specs.inference_type = tensorflow::DT_QINT8;
quant_specs.inference_input_type = tensorflow::DT_QINT8;
}
}
// Parse output arrays.
std::vector<string> output_arrays(model_flags.output_arrays().begin(),
model_flags.output_arrays().end());
TF_RETURN_IF_ERROR(
tensorflow::ParseOutputArrayInfo(output_arrays, &specs.outputs));
// Other flags.
bool emit_builtin_tflite_ops = !toco_flags.force_select_tf_ops();
bool emit_select_tf_ops = toco_flags.enable_select_tf_ops();
bool emit_custom_ops = toco_flags.allow_custom_ops();
specs.prune_unused_nodes = true;
specs.convert_legacy_fed_inputs = true;
specs.graph_as_function = false;
specs.upgrade_legacy = true;
WarningUnusedFlags(model_flags, toco_flags);
// Register any custom OpDefs.
std::vector<string> extra_tf_opdefs(toco_flags.custom_opdefs().begin(),
toco_flags.custom_opdefs().end());
extra_tf_opdefs.push_back(kDetectionPostProcessOp);
TF_RETURN_IF_ERROR(RegisterCustomBuiltinOps(extra_tf_opdefs));
TF_ASSIGN_OR_RETURN(
auto module, ConvertGraphdefToMlir(input, debug_info, specs, &context));
if (toco_flags.has_dump_graphviz_dir()) {
TF_RETURN_IF_ERROR(DumpOpGraphToFile(
module.get(),
// rename once we enable the new converter feature flag.
absl::StrCat(toco_flags.dump_graphviz_dir(), "/toco_AT_IMPORT.dot")));
}
mlir::PassManager pm(module->getContext());
mlir::TFL::PassConfig pass_config(quant_specs);
pass_config.emit_builtin_tflite_ops = emit_builtin_tflite_ops;
pass_config.lower_tensor_list_ops = true;
tensorflow::AddTFToTFLConversionPasses(pass_config, &pm);
auto status = ConvertTFExecutorToTFLOrFlatbuffer(
module.get(), /*export_to_mlir=*/false, emit_builtin_tflite_ops,
emit_select_tf_ops, emit_custom_ops, quant_specs, result, &pm);
if (toco_flags.has_dump_graphviz_dir()) {
TF_RETURN_IF_ERROR(DumpOpGraphToFile(
// rename once we enable the new converter feature flag.
module.get(), absl::StrCat(toco_flags.dump_graphviz_dir(),
"/toco_AFTER_TRANSFORMATIONS.dot")));
}
return status;
}
} // namespace tensorflow
<commit_msg>Fix the mnist test for keras quantization api<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/lite/python/graphdef_to_tfl_flatbuffer.h"
#include <ostream>
#include <utility>
#include "llvm/Support/ToolOutputFile.h"
#include "mlir/IR/MLIRContext.h" // TF:local_config_mlir
#include "mlir/IR/Module.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Support/FileUtilities.h" // TF:local_config_mlir
#include "mlir/Transforms/ViewOpGraph.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/lite/common/tfl_pass_config.h"
#include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h"
#include "tensorflow/compiler/mlir/lite/tf_to_tfl_flatbuffer.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/protobuf/graph_debug_info.pb.h"
#include "tensorflow/lite/toco/model_flags.pb.h"
#include "tensorflow/lite/toco/toco_flags.pb.h"
#include "tensorflow/lite/toco/types.pb.h"
#include "tensorflow/stream_executor/lib/statusor.h"
using stream_executor::port::StatusOr;
namespace tensorflow {
namespace {
// Op def string for TFLite_Detection_PostProcess Op.
const char kDetectionPostProcessOp[] =
"name: 'TFLite_Detection_PostProcess' input_arg: { name: "
"'raw_outputs/box_encodings' type: DT_FLOAT } input_arg: { name: "
"'raw_outputs/class_predictions' type: DT_FLOAT } input_arg: { name: "
"'anchors' type: DT_FLOAT } output_arg: { name: "
"'TFLite_Detection_PostProcess' type: DT_FLOAT } output_arg: { name: "
"'TFLite_Detection_PostProcess:1' type: DT_FLOAT } output_arg: { name: "
"'TFLite_Detection_PostProcess:2' type: DT_FLOAT } output_arg: { name: "
"'TFLite_Detection_PostProcess:3' type: DT_FLOAT } attr : { name: "
"'h_scale' type: 'float'} attr : { name: 'max_classes_per_detection' "
"type: 'int'} attr : { name: 'max_detections' type: 'int'} attr : { "
"name: 'nms_iou_threshold' type: 'float'} attr : { name: "
"'nms_score_threshold' type: 'float'} attr : { name: 'num_classes' type: "
"'int'} attr : { name: 'w_scale' type: 'float'} attr : { name: 'x_scale' "
"type: 'float'} attr : { name: 'y_scale' type: 'float'} attr { name: "
"'detections_per_class' type: 'int' default_value { i : 100 }} attr { "
"name: 'use_regular_nms' type: 'bool' default_value { b : false }}";
// Converts the toco::IODataType to tensorflow::DataType. Only contains the
// conversion mapping for constants defined in TFLite Python API.
DataType ConvertIODataTypeToDataType(toco::IODataType dtype) {
switch (dtype) {
case toco::IODataType::FLOAT:
return DT_FLOAT;
case toco::IODataType::QUANTIZED_UINT8:
return DT_QUINT8;
case toco::IODataType::INT8:
return DT_QINT8;
case toco::IODataType::INT32:
return DT_INT32;
case toco::IODataType::INT64:
return DT_INT64;
case toco::IODataType::STRING:
return DT_STRING;
case toco::IODataType::BOOL:
return DT_BOOL;
default:
return DT_INVALID;
}
}
StatusOr<std::pair<double, double>> InputStatsToMinMax(double mean, double std,
DataType type) {
// Only qint8 and quint8 are considered here.
double qmin, qmax;
if (type == DT_QUINT8) {
qmin = 0.0;
qmax = 255.0;
} else if (type == DT_QINT8) {
qmin = -128.0;
qmax = 127.0;
} else {
return errors::InvalidArgument("Only int8 and uint8 are considered.");
}
return std::make_pair((qmin - mean) / std, (qmax - mean) / std);
}
// Give a warning for any unused flags that have been specified.
void WarningUnusedFlags(const toco::ModelFlags& model_flags,
const toco::TocoFlags& toco_flags) {
if (toco_flags.output_format()) {
LOG(WARNING) << "Ignored output_format.";
}
if (toco_flags.default_ranges_min() || toco_flags.default_ranges_max()) {
LOG(WARNING) << "Ignored default_ranges_stats.";
}
if (toco_flags.drop_control_dependency()) {
LOG(WARNING) << "Ignored drop_control_dependency.";
}
if (toco_flags.reorder_across_fake_quant()) {
LOG(WARNING) << "Ignored reorder_across_fake_quant.";
}
if (model_flags.change_concat_input_ranges()) {
LOG(WARNING) << "Ignored change_concat_input_ranges.";
}
if (toco_flags.dump_graphviz_include_video()) {
LOG(WARNING) << "Ignored dump_graphviz_video.";
}
if (model_flags.allow_nonexistent_arrays()) {
LOG(WARNING) << "Allow allow_nonexistent_arrays.";
}
}
// Dumps the op graph of the `module` to `filename` in DOT format.
Status DumpOpGraphToFile(mlir::ModuleOp module, const std::string& filename) {
std::string error_message;
auto output = mlir::openOutputFile(filename, &error_message);
if (!error_message.empty()) {
return errors::InvalidArgument("Failed to open file in %s.", filename);
}
mlir::PassManager pm(module.getContext());
pm.addPass(mlir::createPrintOpGraphPass(output->os()));
if (failed(pm.run(module))) {
return errors::Unknown("Failed to dump Op Graph from MLIR module.");
}
output->keep();
return Status::OK();
}
Status RegisterCustomBuiltinOps(const std::vector<string> extra_tf_opdefs) {
for (const auto& tf_opdefs_string : extra_tf_opdefs) {
tensorflow::OpDef opdef;
if (!tensorflow::protobuf::TextFormat::ParseFromString(tf_opdefs_string,
&opdef)) {
return errors::InvalidArgument("fail to parse extra OpDef");
}
// Make sure the op is not already registered. If registered continue.
const OpRegistrationData* op_reg =
tensorflow::OpRegistry::Global()->LookUp(opdef.name());
if (op_reg) continue;
tensorflow::OpRegistry::Global()->Register(
[opdef](tensorflow::OpRegistrationData* op_reg_data) -> Status {
*op_reg_data = tensorflow::OpRegistrationData(opdef);
return Status::OK();
});
}
return Status::OK();
}
} // namespace
Status ConvertGraphDefToTFLiteFlatBuffer(const toco::ModelFlags& model_flags,
const toco::TocoFlags& toco_flags,
const GraphDebugInfo& debug_info,
const GraphDef& input,
string* result) {
mlir::MLIRContext context;
GraphImportConfig specs;
mlir::TFL::QuantizationSpecs quant_specs;
// Parse input arrays.
std::vector<string> node_names;
std::vector<string> node_dtypes;
std::vector<std::vector<int>> node_shapes;
std::vector<double> node_mins;
std::vector<double> node_maxs;
quant_specs.inference_input_type =
ConvertIODataTypeToDataType(toco_flags.inference_input_type());
tensorflow::DataType inference_type =
ConvertIODataTypeToDataType(toco_flags.inference_type());
// Use non-float flag `inference_input_type` to override the `inference_type`
// because we have to apply quantization to satisfy that.
if (quant_specs.inference_input_type != tensorflow::DT_FLOAT) {
inference_type = quant_specs.inference_input_type;
}
for (auto& flag : model_flags.input_arrays()) {
node_names.push_back(flag.name());
// TOCO doesn't required `data_type` to be filled for every input.
// If it's not filled, make it an empty string so the importer will use
// the data type in the NodeDef.
auto toco_data_type = flag.data_type();
if (toco_data_type == ::toco::IODataType::IO_DATA_TYPE_UNKNOWN) {
node_dtypes.push_back("");
} else {
node_dtypes.push_back(
DataType_Name(ConvertIODataTypeToDataType(toco_data_type)));
}
node_shapes.push_back(std::vector<int>(flag.shape().dims().begin(),
flag.shape().dims().end()));
// Currently, only UINT8 and INT8 require inputs stats
if (inference_type == DT_QINT8 || inference_type == DT_QUINT8) {
TF_ASSIGN_OR_RETURN(
auto min_max, InputStatsToMinMax(flag.mean_value(), flag.std_value(),
inference_type));
node_mins.push_back(min_max.first);
node_maxs.push_back(min_max.second);
}
}
TF_RETURN_IF_ERROR(tensorflow::ParseInputArrayInfo(
node_names, node_dtypes, node_shapes, &specs.inputs));
if (mlir::TFL::GetInputNodeQuantSpecs(node_names, node_mins, node_maxs,
inference_type, &quant_specs)) {
return errors::InvalidArgument("Failed to get input quant spec.");
}
// Some extra flag related to post training quantization. If post-training
// quantization is enabled, `inference_type` and `inference_input_type` are
// not used by MLIR passes.
if (toco_flags.post_training_quantize()) {
quant_specs.weight_quantization = true;
if (toco_flags.quantize_to_float16()) {
quant_specs.inference_type = tensorflow::DT_HALF;
quant_specs.inference_input_type = tensorflow::DT_HALF;
} else {
quant_specs.inference_type = tensorflow::DT_QINT8;
quant_specs.inference_input_type = tensorflow::DT_QINT8;
}
}
// Parse output arrays.
std::vector<string> output_arrays(model_flags.output_arrays().begin(),
model_flags.output_arrays().end());
TF_RETURN_IF_ERROR(
tensorflow::ParseOutputArrayInfo(output_arrays, &specs.outputs));
// Other flags.
bool emit_builtin_tflite_ops = !toco_flags.force_select_tf_ops();
bool emit_select_tf_ops = toco_flags.enable_select_tf_ops();
bool emit_custom_ops = toco_flags.allow_custom_ops();
specs.prune_unused_nodes = true;
specs.convert_legacy_fed_inputs = true;
specs.graph_as_function = false;
specs.upgrade_legacy = true;
WarningUnusedFlags(model_flags, toco_flags);
// Register any custom OpDefs.
std::vector<string> extra_tf_opdefs(toco_flags.custom_opdefs().begin(),
toco_flags.custom_opdefs().end());
extra_tf_opdefs.push_back(kDetectionPostProcessOp);
TF_RETURN_IF_ERROR(RegisterCustomBuiltinOps(extra_tf_opdefs));
TF_ASSIGN_OR_RETURN(
auto module, ConvertGraphdefToMlir(input, debug_info, specs, &context));
if (toco_flags.has_dump_graphviz_dir()) {
TF_RETURN_IF_ERROR(DumpOpGraphToFile(
module.get(),
// rename once we enable the new converter feature flag.
absl::StrCat(toco_flags.dump_graphviz_dir(), "/toco_AT_IMPORT.dot")));
}
mlir::PassManager pm(module->getContext());
mlir::TFL::PassConfig pass_config(quant_specs);
pass_config.emit_builtin_tflite_ops = emit_builtin_tflite_ops;
pass_config.lower_tensor_list_ops = true;
tensorflow::AddTFToTFLConversionPasses(pass_config, &pm);
auto status = ConvertTFExecutorToTFLOrFlatbuffer(
module.get(), /*export_to_mlir=*/false, emit_builtin_tflite_ops,
emit_select_tf_ops, emit_custom_ops, quant_specs, result, &pm);
if (toco_flags.has_dump_graphviz_dir()) {
TF_RETURN_IF_ERROR(DumpOpGraphToFile(
// rename once we enable the new converter feature flag.
module.get(), absl::StrCat(toco_flags.dump_graphviz_dir(),
"/toco_AFTER_TRANSFORMATIONS.dot")));
}
return status;
}
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <array>
#include <string>
#include "llvm/Support/FormatVariadic.h"
#include "tensorflow/compiler/mlir/tfrt/benchmarks/benchmark_mlir_function.h"
namespace tensorflow {
static const char* mlir_2d_input = R"(
func @compute(%arg0: tensor<?x?xf32>) -> tensor<?x?xf32> {{
%0 = "tf.Const"()
{{value = dense<[1, 0]> : tensor<2xi64>,
device = "/job:localhost/replica:0/task:0/device:CPU:0"}
: () -> tensor<2xi64>
%1 = "tf.Transpose"(%arg0, %0)
{{device = "/job:localhost/replica:0/task:0/device:CPU:0"}
: (tensor<?x?xf32>, tensor<2xi64>) -> tensor<?x?xf32>
return %1 : tensor<?x?xf32>
}
)";
static const char* mlir_3d_input = R"(
func @compute(%arg0: tensor<?x?x?xf32>) -> tensor<?x?x?xf32> {{
%0 = "tf.Const"()
{{value = dense<[{0}, {1}, {2}]> : tensor<3xi64>,
device = "/job:localhost/replica:0/task:0/device:CPU:0"}
: () -> tensor<3xi64>
%1 = "tf.Transpose"(%arg0, %0)
{{device = "/job:localhost/replica:0/task:0/device:CPU:0"}
: (tensor<?x?x?xf32>, tensor<3xi64>) -> tensor<?x?x?xf32>
return %1 : tensor<?x?x?xf32>
}
)";
static std::string Transpose2D() { return llvm::formatv(mlir_2d_input); }
static std::string Transpose3D(std::array<int32_t, 3> perm) {
return llvm::formatv(mlir_3d_input, perm[0], perm[1], perm[2]);
}
template <int32_t size>
static auto Shuffle(std::array<int32_t, size> perm) {
return [perm](llvm::ArrayRef<Tensor> inputs,
llvm::Optional<Eigen::ThreadPoolDevice> device) {
std::array<int64_t, size> shuffled;
for (unsigned d = 0; d < size; d++)
shuffled[d] = inputs[0].dim_size(perm[d]);
Tensor output(DT_FLOAT, TensorShape(shuffled));
auto in0 = inputs[0].tensor<float, size>();
auto out0 = output.tensor<float, size>();
if (device.hasValue()) {
out0.device(*device) = in0.shuffle(perm);
} else {
out0 = in0.shuffle(perm);
}
};
}
static llvm::SmallVector<InputTensorSpec> Inputs(llvm::ArrayRef<ssize_t> dims) {
return {InputTensorSpec(DT_FLOAT, dims)};
}
#define BM(FN) BM_##FN->Arg(0)->Arg(4)->Arg(8);
// Small 2D Transpose: [1, 0]
BM(Jitrt(Transpose_small_1x0, Transpose2D(), "compute", Inputs({128, 128})));
BM(JitrtV(Transpose_small_1x0, Transpose2D(), "compute", Inputs({128, 128})));
BM(Tfrt(Transpose_small_1x0, Transpose2D(), "compute", Inputs({128, 128})));
BM(Eigen(Transpose_small_1x0, Shuffle<2>({1, 0}), Inputs({128, 128})));
// Small 3D Transpose: [0, 2, 1]
BM(Jitrt(Transpose_small_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_0x2x1, Shuffle<3>({0, 2, 1}), Inputs({32, 32, 16})));
// Small 3D Transpose: [2, 0, 1]
BM(Jitrt(Transpose_small_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_2x0x1, Shuffle<3>({2, 0, 1}), Inputs({32, 32, 16})));
// Small 3D Transpose: [2, 1, 0]
BM(Jitrt(Transpose_small_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_2x1x0, Shuffle<3>({2, 1, 0}), Inputs({32, 32, 16})));
// Small 3D Transpose: [1, 2, 0]
BM(Jitrt(Transpose_small_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_1x2x0, Shuffle<3>({1, 2, 0}), Inputs({32, 32, 16})));
// 2D Transpose: [1, 0]
BM(Jitrt(Transpose_1x0, Transpose2D(), "compute", Inputs({4096, 4096})));
BM(JitrtV(Transpose_1x0, Transpose2D(), "compute", Inputs({4096, 4096})));
BM(Tfrt(Transpose_1x0, Transpose2D(), "compute", Inputs({4096, 4096})));
BM(Eigen(Transpose_1x0, Shuffle<2>({1, 0}), Inputs({4096, 4096})));
// 3D Transpose: [0, 2, 1]
BM(Jitrt(Transpose_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_0x2x1, Shuffle<3>({0, 2, 1}), Inputs({256, 256, 256})));
// 3D Transpose: [2, 0, 1]
BM(Jitrt(Transpose_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_2x0x1, Shuffle<3>({2, 0, 1}), Inputs({256, 256, 256})));
// 3D Transpose: [2, 1, 0]
BM(Jitrt(Transpose_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_2x1x0, Shuffle<3>({2, 1, 0}), Inputs({256, 256, 256})));
// 3D Transpose: [1, 2, 0]
BM(Jitrt(Transpose_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_1x2x0, Shuffle<3>({1, 2, 0}), Inputs({256, 256, 256})));
} // namespace tensorflow
<commit_msg>[tf:tfrt] Add [1, 0, 2] case to transpose benchmarks<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <array>
#include <string>
#include "llvm/Support/FormatVariadic.h"
#include "tensorflow/compiler/mlir/tfrt/benchmarks/benchmark_mlir_function.h"
namespace tensorflow {
static const char* mlir_2d_input = R"(
func @compute(%arg0: tensor<?x?xf32>) -> tensor<?x?xf32> {{
%0 = "tf.Const"()
{{value = dense<[1, 0]> : tensor<2xi64>,
device = "/job:localhost/replica:0/task:0/device:CPU:0"}
: () -> tensor<2xi64>
%1 = "tf.Transpose"(%arg0, %0)
{{device = "/job:localhost/replica:0/task:0/device:CPU:0"}
: (tensor<?x?xf32>, tensor<2xi64>) -> tensor<?x?xf32>
return %1 : tensor<?x?xf32>
}
)";
static const char* mlir_3d_input = R"(
func @compute(%arg0: tensor<?x?x?xf32>) -> tensor<?x?x?xf32> {{
%0 = "tf.Const"()
{{value = dense<[{0}, {1}, {2}]> : tensor<3xi64>,
device = "/job:localhost/replica:0/task:0/device:CPU:0"}
: () -> tensor<3xi64>
%1 = "tf.Transpose"(%arg0, %0)
{{device = "/job:localhost/replica:0/task:0/device:CPU:0"}
: (tensor<?x?x?xf32>, tensor<3xi64>) -> tensor<?x?x?xf32>
return %1 : tensor<?x?x?xf32>
}
)";
static std::string Transpose2D() { return llvm::formatv(mlir_2d_input); }
static std::string Transpose3D(std::array<int32_t, 3> perm) {
return llvm::formatv(mlir_3d_input, perm[0], perm[1], perm[2]);
}
template <int32_t size>
static auto Shuffle(std::array<int32_t, size> perm) {
return [perm](llvm::ArrayRef<Tensor> inputs,
llvm::Optional<Eigen::ThreadPoolDevice> device) {
std::array<int64_t, size> shuffled;
for (unsigned d = 0; d < size; d++)
shuffled[d] = inputs[0].dim_size(perm[d]);
Tensor output(DT_FLOAT, TensorShape(shuffled));
auto in0 = inputs[0].tensor<float, size>();
auto out0 = output.tensor<float, size>();
if (device.hasValue()) {
out0.device(*device) = in0.shuffle(perm);
} else {
out0 = in0.shuffle(perm);
}
};
}
static llvm::SmallVector<InputTensorSpec> Inputs(llvm::ArrayRef<ssize_t> dims) {
return {InputTensorSpec(DT_FLOAT, dims)};
}
#define BM(FN) BM_##FN->Arg(0)->Arg(4)->Arg(8);
// Small 2D Transpose: [1, 0]
BM(Jitrt(Transpose_small_1x0, Transpose2D(), "compute", Inputs({128, 128})));
BM(JitrtV(Transpose_small_1x0, Transpose2D(), "compute", Inputs({128, 128})));
BM(Tfrt(Transpose_small_1x0, Transpose2D(), "compute", Inputs({128, 128})));
BM(Eigen(Transpose_small_1x0, Shuffle<2>({1, 0}), Inputs({128, 128})));
// Small 3D Transpose: [0, 2, 1]
BM(Jitrt(Transpose_small_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_0x2x1, Shuffle<3>({0, 2, 1}), Inputs({32, 32, 16})));
// Small 3D Transpose: [2, 0, 1]
BM(Jitrt(Transpose_small_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_2x0x1, Shuffle<3>({2, 0, 1}), Inputs({32, 32, 16})));
// Small 3D Transpose: [2, 1, 0]
BM(Jitrt(Transpose_small_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_2x1x0, Shuffle<3>({2, 1, 0}), Inputs({32, 32, 16})));
// Small 3D Transpose: [1, 2, 0]
BM(Jitrt(Transpose_small_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_1x2x0, Shuffle<3>({1, 2, 0}), Inputs({32, 32, 16})));
// Small 3D Transpose: [1, 0, 2]
BM(Jitrt(Transpose_small_1x0x2, Transpose3D({1, 0, 2}), "compute",
Inputs({32, 32, 16})));
BM(JitrtV(Transpose_small_1x0x2, Transpose3D({1, 0, 2}), "compute",
Inputs({32, 32, 16})));
BM(Tfrt(Transpose_small_1x0x2, Transpose3D({1, 0, 2}), "compute",
Inputs({32, 32, 16})));
BM(Eigen(Transpose_small_1x0x2, Shuffle<3>({1, 0, 2}), Inputs({32, 32, 16})));
// 2D Transpose: [1, 0]
BM(Jitrt(Transpose_1x0, Transpose2D(), "compute", Inputs({4096, 4096})));
BM(JitrtV(Transpose_1x0, Transpose2D(), "compute", Inputs({4096, 4096})));
BM(Tfrt(Transpose_1x0, Transpose2D(), "compute", Inputs({4096, 4096})));
BM(Eigen(Transpose_1x0, Shuffle<2>({1, 0}), Inputs({4096, 4096})));
// 3D Transpose: [0, 2, 1]
BM(Jitrt(Transpose_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_0x2x1, Transpose3D({0, 2, 1}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_0x2x1, Shuffle<3>({0, 2, 1}), Inputs({256, 256, 256})));
// 3D Transpose: [2, 0, 1]
BM(Jitrt(Transpose_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_2x0x1, Transpose3D({2, 0, 1}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_2x0x1, Shuffle<3>({2, 0, 1}), Inputs({256, 256, 256})));
// 3D Transpose: [2, 1, 0]
BM(Jitrt(Transpose_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_2x1x0, Transpose3D({2, 1, 0}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_2x1x0, Shuffle<3>({2, 1, 0}), Inputs({256, 256, 256})));
// 3D Transpose: [1, 2, 0]
BM(Jitrt(Transpose_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_1x2x0, Transpose3D({1, 2, 0}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_1x2x0, Shuffle<3>({1, 2, 0}), Inputs({256, 256, 256})));
// 3D Transpose: [1, 0, 2]
BM(Jitrt(Transpose_1x0x2, Transpose3D({1, 0, 2}), "compute",
Inputs({256, 256, 256})));
BM(JitrtV(Transpose_1x0x2, Transpose3D({1, 0, 2}), "compute",
Inputs({256, 256, 256})));
BM(Tfrt(Transpose_1x0x2, Transpose3D({1, 0, 2}), "compute",
Inputs({256, 256, 256})));
BM(Eigen(Transpose_1x0x2, Shuffle<3>({1, 0, 2}), Inputs({256, 256, 256})));
} // namespace tensorflow
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <map>
#include <node.h>
#include "PSATResult.h"
#include "calculator/EstimateFLA.h"
using namespace v8;
using namespace std;
Isolate* iso;
Local<Object> inp;
double Get(const char *nm) {
auto rObj = inp->ToObject()->Get(String::NewFromUtf8(iso,nm));
if (rObj->IsUndefined()) {
cout << nm << endl;;
assert(!"defined");
}
return rObj->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
inp = args[0]->ToObject();
auto r = Object::New(iso);
auto drive = (Pump::Drive)(int)Get("drive");
auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");
Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_specified"),Get("pump_rated_speed"),drive,
Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed")));
Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"),
effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin"));
Financial fin(Get("fraction"),Get("cost"));
FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1),
Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage"));
PSATResult psat(pump,motor,fin,fd);
psat.calculateExisting();
psat.calculateOptimal();
auto ex = psat.getExisting(), opt = psat.getOptimal();
map<const char *,vector<double>> out = {
{"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}},
{"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}},
{"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}},
{"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}},
{"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}},
{"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}},
{"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}},
{"Motor Power", {ex.motorPower_,opt.motorPower_}},
{"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}},
{"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}},
{"Savings Potential", {psat.getAnnualSavingsPotential(),-1}},
{"Optimization Rating", {psat.getOptimizationRating(),-1}}
};
for(auto p: out) {
auto a = Array::New(iso);
a->Set(0,Number::New(iso,p.second[0]));
a->Set(1,Number::New(iso,p.second[1]));
r->Set(String::NewFromUtf8(iso,p.first),a);
}
args.GetReturnValue().Set(r);
}
void EstFLA(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
inp = args[0]->ToObject();
EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::LineFrequency)(int)(!Get("line")),(Motor::EfficiencyClass)(int)Get("efficiency_class"),
Get("efficiency"),Get("motor_rated_voltage"));
fla.calculate();
args.GetReturnValue().Set(fla.getEstimatedFLA());
}
//TODO round vs js round; loosen up to make next test case
void Check(double exp, double act, const char* nm="") {
//cout << "e " << exp << "; a " << act << endl;
// if (isnan(act) || (abs(exp-act)>.01*exp)) {
auto p = 10;
if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) {
printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
assert(!"equal");
}
}
void Check100(double exp, double act, const char* nm="") {
Check(exp,act*100,nm);
}
void Test(const FunctionCallbackInfo<Value>& args) {
MotorEfficiency mef(Motor::LineFrequency::FREQ60,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,.75);
Check100(95.69,mef.calculate());
EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460);
fla.calculate();
Check(225.8,fla.getEstimatedFLA());
#define BASE \
Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\
1,1,1,Pump::Speed::NOT_FIXED_SPEED);\
Motor motor(Motor::LineFrequency::FREQ60,200,1780,\
Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\
Financial fin(1,.05);\
FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\
150,0,460);
#define CALC \
PSATResult psat(pump,motor,fin,fd);\
psat.calculateExisting();\
auto ex = psat.getExisting();
for (int i=1; i<=10000; i=i+2) {
BASE
CALC
Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME");
}
{
BASE
motor.setMotorRpm(1786);
fd.setMotorPower(80);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(79.1,ex.motorPowerFactor_);
Check(127,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
motor.setMotorRatedPower(100);
motor.setFullLoadAmps(113.8);
CALC
Check(101.8,ex.motorShaftPower_);
Check100(94.9,ex.motorEfficiency_);
Check100(86.7,ex.motorPowerFactor_);
Check(115.8,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
fd.setVoltage(260);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(138.8,ex.motorPowerFactor_);
Check(128,ex.motorCurrent_);
}
{
BASE
motor.setMotorRpm(1200);
fd.setMotorPower(80);
motor.setFullLoadAmps(235.3);
CALC
Check(101.4,ex.motorShaftPower_);
Check100(94.5,ex.motorEfficiency_);
Check100(74.3,ex.motorPowerFactor_);
Check(135.1,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(111.855);
CALC
Check(143.4,ex.motorShaftPower_);
Check100(95.6,ex.motorEfficiency_);
Check100(84.3,ex.motorPowerFactor_);
Check(166.5,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
motor.setMotorRatedVoltage(200);
motor.setFullLoadAmps(519.3);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(35.2,ex.motorPowerFactor_);
Check(284.9,ex.motorCurrent_);
}
{
BASE
CALC
Check(217.5,ex.motorCurrent_);
}
{
BASE
fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT);
fd.setMotorAmps(218);
fd.setMotorPower(0);
CALC
Check(150.4,ex.motorPower_);
Check100(72.5,ex.pumpEfficiency_);
}
{
BASE
fd.setMotorPower(80);
CALC
Check(700.8,ex.annualEnergy_);
}
{
BASE
fin.setOperatingFraction(.25);
CALC
Check(328.5,ex.annualEnergy_);
Check(16.4,ex.annualCost_);
}
{
BASE
motor.setFullLoadAmps(300);
CALC
Check(288.9,ex.motorCurrent_);
}
{
BASE
motor.setEfficiencyClass(Motor::EfficiencyClass(0));
CALC
Check(213.7,ex.motorCurrent_);
}
{
BASE
motor.setEfficiencyClass(Motor::EfficiencyClass(2));
motor.setSpecifiedEfficiency(75);
CALC
Check(173.7,ex.motorCurrent_);
}
cout << "done";
}
void Wtf(const FunctionCallbackInfo<Value>& args) {
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "results", Results);
NODE_SET_METHOD(exports, "estFLA", EstFLA);
NODE_SET_METHOD(exports, "test", Test);
NODE_SET_METHOD(exports, "wtf", Wtf);
}
NODE_MODULE(bridge, Init)
<commit_msg>no message<commit_after>#include <iostream>
#include <vector>
#include <map>
#include <node.h>
#include "PSATResult.h"
#include "calculator/EstimateFLA.h"
#include "calculator/MotorCurrent.h"
using namespace v8;
using namespace std;
Isolate* iso;
Local<Object> inp;
double Get(const char *nm) {
auto rObj = inp->ToObject()->Get(String::NewFromUtf8(iso,nm));
if (rObj->IsUndefined()) {
cout << nm << endl;;
assert(!"defined");
}
return rObj->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
inp = args[0]->ToObject();
auto r = Object::New(iso);
auto drive = (Pump::Drive)(int)Get("drive");
auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");
Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_specified"),Get("pump_rated_speed"),drive,
Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed")));
Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"),
effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin"));
Financial fin(Get("fraction"),Get("cost"));
FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1),
Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage"));
PSATResult psat(pump,motor,fin,fd);
psat.calculateExisting();
psat.calculateOptimal();
auto ex = psat.getExisting(), opt = psat.getOptimal();
map<const char *,vector<double>> out = {
{"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}},
{"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}},
{"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}},
{"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}},
{"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}},
{"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}},
{"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}},
{"Motor Power", {ex.motorPower_,opt.motorPower_}},
{"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}},
{"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}},
{"Savings Potential", {psat.getAnnualSavingsPotential(),-1}},
{"Optimization Rating", {psat.getOptimizationRating(),-1}}
};
for(auto p: out) {
auto a = Array::New(iso);
a->Set(0,Number::New(iso,p.second[0]));
a->Set(1,Number::New(iso,p.second[1]));
r->Set(String::NewFromUtf8(iso,p.first),a);
}
args.GetReturnValue().Set(r);
}
void EstFLA(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
inp = args[0]->ToObject();
EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::LineFrequency)(int)(!Get("line")),(Motor::EfficiencyClass)(int)Get("efficiency_class"),
Get("efficiency"),Get("motor_rated_voltage"));
fla.calculate();
args.GetReturnValue().Set(fla.getEstimatedFLA());
}
//TODO round vs js round; loosen up to make next test case
void Check(double exp, double act, const char* nm="") {
cout << "e " << exp << "; a " << act << endl;
// if (isnan(act) || (abs(exp-act)>.01*exp)) {
auto p = 10;
if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) {
printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
assert(!"equal");
}
}
void Check100(double exp, double act, const char* nm="") {
Check(exp,act*100,nm);
}
void Test(const FunctionCallbackInfo<Value>& args) {
MotorEfficiency mef(Motor::LineFrequency::FREQ60,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,.75);
Check100(95.69,mef.calculate());
MotorCurrent mc(200,1780,Motor::LineFrequency::FREQ60,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,.75,460,225.8);
Check100(76.63,mc.calculate()/225.8);
return;
EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460);
fla.calculate();
Check(225.8,fla.getEstimatedFLA());
#define BASE \
Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\
1,1,1,Pump::Speed::NOT_FIXED_SPEED);\
Motor motor(Motor::LineFrequency::FREQ60,200,1780,\
Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\
Financial fin(1,.05);\
FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\
150,0,460);
#define CALC \
PSATResult psat(pump,motor,fin,fd);\
psat.calculateExisting();\
auto ex = psat.getExisting();
for (int i=1; i<=10000; i=i+2) {
BASE
CALC
Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME");
}
{
BASE
motor.setMotorRpm(1786);
fd.setMotorPower(80);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(79.1,ex.motorPowerFactor_);
Check(127,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
motor.setMotorRatedPower(100);
motor.setFullLoadAmps(113.8);
CALC
Check(101.8,ex.motorShaftPower_);
Check100(94.9,ex.motorEfficiency_);
Check100(86.7,ex.motorPowerFactor_);
Check(115.8,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
fd.setVoltage(260);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(138.8,ex.motorPowerFactor_);
Check(128,ex.motorCurrent_);
}
{
BASE
motor.setMotorRpm(1200);
fd.setMotorPower(80);
motor.setFullLoadAmps(235.3);
CALC
Check(101.4,ex.motorShaftPower_);
Check100(94.5,ex.motorEfficiency_);
Check100(74.3,ex.motorPowerFactor_);
Check(135.1,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(111.855);
CALC
Check(143.4,ex.motorShaftPower_);
Check100(95.6,ex.motorEfficiency_);
Check100(84.3,ex.motorPowerFactor_);
Check(166.5,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
motor.setMotorRatedVoltage(200);
motor.setFullLoadAmps(519.3);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(35.2,ex.motorPowerFactor_);
Check(284.9,ex.motorCurrent_);
}
{
BASE
CALC
Check(217.5,ex.motorCurrent_);
}
{
BASE
fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT);
fd.setMotorAmps(218);
fd.setMotorPower(0);
CALC
Check(150.4,ex.motorPower_);
Check100(72.5,ex.pumpEfficiency_);
}
{
BASE
fd.setMotorPower(80);
CALC
Check(700.8,ex.annualEnergy_);
}
{
BASE
fin.setOperatingFraction(.25);
CALC
Check(328.5,ex.annualEnergy_);
Check(16.4,ex.annualCost_);
}
{
BASE
motor.setFullLoadAmps(300);
CALC
Check(288.9,ex.motorCurrent_);
}
{
BASE
motor.setEfficiencyClass(Motor::EfficiencyClass(0));
CALC
Check(213.7,ex.motorCurrent_);
}
{
BASE
motor.setEfficiencyClass(Motor::EfficiencyClass(2));
motor.setSpecifiedEfficiency(75);
CALC
Check(173.7,ex.motorCurrent_);
}
cout << "done";
}
void Wtf(const FunctionCallbackInfo<Value>& args) {
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "results", Results);
NODE_SET_METHOD(exports, "estFLA", EstFLA);
NODE_SET_METHOD(exports, "test", Test);
NODE_SET_METHOD(exports, "wtf", Wtf);
}
NODE_MODULE(bridge, Init)
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/common/resource_type.h"
#include "base/logging.h"
using blink::WebURLRequest;
// static
ResourceType::Type ResourceType::FromTargetType(
WebURLRequest::TargetType type) {
switch (type) {
case WebURLRequest::TargetIsMainFrame:
return ResourceType::MAIN_FRAME;
case WebURLRequest::TargetIsSubframe:
return ResourceType::SUB_FRAME;
case WebURLRequest::TargetIsSubresource:
return ResourceType::SUB_RESOURCE;
case WebURLRequest::TargetIsStyleSheet:
return ResourceType::STYLESHEET;
case WebURLRequest::TargetIsScript:
return ResourceType::SCRIPT;
case WebURLRequest::TargetIsFontResource:
return ResourceType::FONT_RESOURCE;
case WebURLRequest::TargetIsImage:
return ResourceType::IMAGE;
case WebURLRequest::TargetIsObject:
return ResourceType::OBJECT;
case WebURLRequest::TargetIsMedia:
return ResourceType::MEDIA;
case WebURLRequest::TargetIsWorker:
return ResourceType::WORKER;
case WebURLRequest::TargetIsSharedWorker:
return ResourceType::SHARED_WORKER;
case WebURLRequest::TargetIsPrefetch:
return ResourceType::PREFETCH;
case WebURLRequest::TargetIsFavicon:
return ResourceType::FAVICON;
case WebURLRequest::TargetIsXHR:
return ResourceType::XHR;
#if defined(WEBKIT_HAS_TARGET_IS_PING)
case WebURLRequest::TargetIsPing:
return ResourceType::PING;
#endif
default:
NOTREACHED();
return ResourceType::SUB_RESOURCE;
}
}
<commit_msg>Remove WEBKIT_HAS_TARGET_IS_PING #ifdef.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/common/resource_type.h"
#include "base/logging.h"
using blink::WebURLRequest;
// static
ResourceType::Type ResourceType::FromTargetType(
WebURLRequest::TargetType type) {
switch (type) {
case WebURLRequest::TargetIsMainFrame:
return ResourceType::MAIN_FRAME;
case WebURLRequest::TargetIsSubframe:
return ResourceType::SUB_FRAME;
case WebURLRequest::TargetIsSubresource:
return ResourceType::SUB_RESOURCE;
case WebURLRequest::TargetIsStyleSheet:
return ResourceType::STYLESHEET;
case WebURLRequest::TargetIsScript:
return ResourceType::SCRIPT;
case WebURLRequest::TargetIsFontResource:
return ResourceType::FONT_RESOURCE;
case WebURLRequest::TargetIsImage:
return ResourceType::IMAGE;
case WebURLRequest::TargetIsObject:
return ResourceType::OBJECT;
case WebURLRequest::TargetIsMedia:
return ResourceType::MEDIA;
case WebURLRequest::TargetIsWorker:
return ResourceType::WORKER;
case WebURLRequest::TargetIsSharedWorker:
return ResourceType::SHARED_WORKER;
case WebURLRequest::TargetIsPrefetch:
return ResourceType::PREFETCH;
case WebURLRequest::TargetIsFavicon:
return ResourceType::FAVICON;
case WebURLRequest::TargetIsXHR:
return ResourceType::XHR;
case WebURLRequest::TargetIsPing:
return ResourceType::PING;
default:
NOTREACHED();
return ResourceType::SUB_RESOURCE;
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <vector>
#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/proto/pauli_sum.pb.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"
namespace tfq {
using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::proto::PauliSum;
using ::tfq::qsim_old::GetStateSpace;
using ::tfq::qsim_old::StateSpace;
class TfqSimulateSampledExpectationOp : public tensorflow::OpKernel {
public:
explicit TfqSimulateSampledExpectationOp(
tensorflow::OpKernelConstruction *context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext *context) override {
// TODO (mbbrough): add more dimension checks for other inputs here.
const int num_inputs = context->num_inputs();
OP_REQUIRES(context, num_inputs == 5,
tensorflow::errors::InvalidArgument(absl::StrCat(
"Expected 5 inputs, got ", num_inputs, " inputs.")));
// Create the output Tensor.
const int output_dim_batch_size = context->input(0).dim_size(0);
const int output_dim_op_size = context->input(3).dim_size(1);
tensorflow::TensorShape output_shape;
output_shape.AddDim(output_dim_batch_size);
output_shape.AddDim(output_dim_op_size);
tensorflow::Tensor *output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_tensor = output->matrix<float>();
std::vector<Program> programs;
std::vector<int> num_qubits;
std::vector<std::vector<PauliSum>> pauli_sums;
OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs,
&num_qubits, &pauli_sums));
std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
OP_REQUIRES(context, pauli_sums.size() == programs.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Number of circuits and PauliSums do not match. Got ",
programs.size(), " circuits and ", pauli_sums.size(),
" paulisums.")));
std::vector<std::vector<int>> num_samples;
OP_REQUIRES_OK(context, GetNumSamples(context, &num_samples));
OP_REQUIRES(context, num_samples.size() == pauli_sums.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Dimension 0 of num_samples and pauli_sums do not match.",
"Got ", num_samples.size(), " lists of sample sizes and ",
pauli_sums.size(), " lists of pauli sums.")));
OP_REQUIRES(
context, num_samples[0].size() == pauli_sums[0].size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Dimension 1 of num_samples and pauli_sums do not match.", "Got ",
num_samples[0].size(), " lists of sample sizes and ",
pauli_sums[0].size(), " lists of pauli sums.")));
auto DoWork = [&](int start, int end) {
int old_batch_index = -2;
int cur_batch_index = -1;
int old_num_qubits = -2;
int cur_op_index;
std::unique_ptr<StateSpace> test_state = GetStateSpace(1, 1);
std::unique_ptr<StateSpace> scratch_state = GetStateSpace(1, 1);
for (int i = start; i < end; i++) {
cur_batch_index = i / output_dim_op_size;
cur_op_index = i % output_dim_op_size;
// (#679) Just ignore empty program
if (programs[cur_batch_index].circuit().moments().empty()) {
output_tensor(cur_batch_index, cur_op_index) = -2.0;
continue;
}
if (cur_batch_index != old_batch_index) {
// We've run into a new wavefunction we must compute.
// Only compute a new wavefunction when we have to.
Program program = programs[cur_batch_index];
const int num = num_qubits[cur_batch_index];
OP_REQUIRES_OK(context,
ResolveSymbols(maps[cur_batch_index], &program));
Circuit circuit;
OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));
// TODO(mbbrough): Update this allocation hack so that a StateSpace
// object can grow it's memory dynamically to larger and larger size
// without ever having to call free (until very end). This is tricky
// to implement because right now certain statespaces can't simulate
// all states and we use StateSpaceSlow for smaller circuits.
if (num != old_num_qubits) {
test_state = GetStateSpace(num, 1);
test_state->CreateState();
// Also re-allocate scratch state for expectation calculations.
scratch_state = GetStateSpace(num, 1);
scratch_state->CreateState();
}
// no need to update scratch_state since ComputeExpectation
// will take care of things for us.
test_state->SetStateZero();
OP_REQUIRES_OK(context, test_state->Update(circuit));
old_num_qubits = num;
}
float expectation = 0.0;
OP_REQUIRES_OK(
context,
test_state->ComputeSampledExpectation(
pauli_sums[cur_batch_index][cur_op_index], scratch_state.get(),
&expectation, num_samples[cur_batch_index][cur_op_index]));
output_tensor(cur_batch_index, cur_op_index) = expectation;
old_batch_index = cur_batch_index;
}
};
const int block_size =
GetBlockSize(context, output_dim_batch_size * output_dim_op_size);
context->device()
->tensorflow_cpu_worker_threads()
->workers->TransformRangeConcurrently(
block_size, output_dim_batch_size * output_dim_op_size, DoWork);
}
};
REGISTER_KERNEL_BUILDER(
Name("TfqSimulateSampledExpectation").Device(tensorflow::DEVICE_CPU),
TfqSimulateSampledExpectationOp);
REGISTER_OP("TfqSimulateSampledExpectation")
.Input("programs: string")
.Input("symbol_names: string")
.Input("symbol_values: float")
.Input("pauli_sums: string")
.Input("num_samples: int32")
.Output("expectations: float")
.SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
tensorflow::shape_inference::ShapeHandle programs_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));
tensorflow::shape_inference::ShapeHandle symbol_names_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));
tensorflow::shape_inference::ShapeHandle symbol_values_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));
tensorflow::shape_inference::ShapeHandle pauli_sums_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &pauli_sums_shape));
tensorflow::shape_inference::ShapeHandle num_samples_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &num_samples_shape));
tensorflow::shape_inference::DimensionHandle output_rows =
c->Dim(programs_shape, 0);
tensorflow::shape_inference::DimensionHandle output_cols =
c->Dim(pauli_sums_shape, 1);
c->set_output(0, c->Matrix(output_rows, output_cols));
return tensorflow::Status::OK();
});
} // namespace tfq
<commit_msg>Moved Sampled Expectation op to OSS qsim. (#303)<commit_after>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <vector>
#include "../qsim/lib/circuit.h"
#include "../qsim/lib/gate_appl.h"
#include "../qsim/lib/gates_cirq.h"
#include "../qsim/lib/simmux.h"
#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/proto/pauli_sum.pb.h"
#include "tensorflow_quantum/core/src/util_qsim.h"
namespace tfq {
using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::proto::PauliSum;
typedef qsim::Cirq::GateCirq<float> QsimGate;
typedef qsim::Circuit<QsimGate> QsimCircuit;
class TfqSimulateSampledExpectationOp : public tensorflow::OpKernel {
public:
explicit TfqSimulateSampledExpectationOp(
tensorflow::OpKernelConstruction *context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext *context) override {
// TODO (mbbrough): add more dimension checks for other inputs here.
const int num_inputs = context->num_inputs();
OP_REQUIRES(context, num_inputs == 5,
tensorflow::errors::InvalidArgument(absl::StrCat(
"Expected 5 inputs, got ", num_inputs, " inputs.")));
// Create the output Tensor.
const int output_dim_batch_size = context->input(0).dim_size(0);
const int output_dim_op_size = context->input(3).dim_size(1);
tensorflow::TensorShape output_shape;
output_shape.AddDim(output_dim_batch_size);
output_shape.AddDim(output_dim_op_size);
tensorflow::Tensor *output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_tensor = output->matrix<float>();
std::vector<Program> programs;
std::vector<int> num_qubits;
std::vector<std::vector<PauliSum>> pauli_sums;
OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs,
&num_qubits, &pauli_sums));
std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
OP_REQUIRES(context, pauli_sums.size() == programs.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Number of circuits and PauliSums do not match. Got ",
programs.size(), " circuits and ", pauli_sums.size(),
" paulisums.")));
std::vector<std::vector<int>> num_samples;
OP_REQUIRES_OK(context, GetNumSamples(context, &num_samples));
OP_REQUIRES(context, num_samples.size() == pauli_sums.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Dimension 0 of num_samples and pauli_sums do not match.",
"Got ", num_samples.size(), " lists of sample sizes and ",
pauli_sums.size(), " lists of pauli sums.")));
OP_REQUIRES(
context, num_samples[0].size() == pauli_sums[0].size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Dimension 1 of num_samples and pauli_sums do not match.", "Got ",
num_samples[0].size(), " lists of sample sizes and ",
pauli_sums[0].size(), " lists of pauli sums.")));
// Construct qsim circuits.
std::vector<QsimCircuit> qsim_circuits(programs.size(), QsimCircuit());
std::vector<std::vector<qsim::GateFused<QsimGate>>> fused_circuits(
programs.size(), std::vector<qsim::GateFused<QsimGate>>({}));
auto construct_f = [&](int start, int end) {
for (int i = start; i < end; i++) {
OP_REQUIRES_OK(context, QsimCircuitFromProgram(
programs[i], maps[i], num_qubits[i],
&qsim_circuits[i], &fused_circuits[i]));
}
};
const int num_cycles = 1000;
context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor(
programs.size(), num_cycles, construct_f);
// Instantiate qsim objects.
const auto tfq_for = tfq::QsimFor(context);
using Simulator = qsim::Simulator<const tfq::QsimFor &>;
using StateSpace = Simulator::StateSpace;
using State = StateSpace::State;
// Begin simulation.
int largest_nq = 1;
State sv = StateSpace(largest_nq, tfq_for).CreateState();
State scratch = StateSpace(largest_nq, tfq_for).CreateState();
// Simulate programs one by one. Parallelizing over wavefunctions
// we no longer parallelize over circuits. Each time we encounter a
// a larger circuit we will grow the Statevector as necessary.
for (int i = 0; i < programs.size(); i++) {
int nq = num_qubits[i];
Simulator sim = Simulator(nq, tfq_for);
StateSpace ss = StateSpace(nq, tfq_for);
if (nq > largest_nq) {
// need to switch to larger statespace.
largest_nq = nq;
sv = ss.CreateState();
scratch = ss.CreateState();
}
// TODO: add heuristic here so that we do not always recompute
// the state if there is a possibility that circuit[i] and
// circuit[i + 1] produce the same state.
ss.SetStateZero(sv);
for (int j = 0; j < fused_circuits[i].size(); j++) {
qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv);
}
for (int j = 0; j < pauli_sums[i].size(); j++) {
// (#679) Just ignore empty program
if (programs[i].circuit().moments().empty()) {
output_tensor(i, j) = -2.0;
continue;
}
float exp_v = 0.0;
OP_REQUIRES_OK(context, ComputeSampledExpectationQsim(
pauli_sums[i][j], sim, ss, sv, scratch,
num_samples[i][j], &exp_v));
output_tensor(i, j) = exp_v;
}
}
// just to be on the safe side.
sv.release();
scratch.release();
qsim_circuits.clear();
fused_circuits.clear();
num_qubits.clear();
maps.clear();
pauli_sums.clear();
num_samples.clear();
programs.clear();
}
};
REGISTER_KERNEL_BUILDER(
Name("TfqSimulateSampledExpectation").Device(tensorflow::DEVICE_CPU),
TfqSimulateSampledExpectationOp);
REGISTER_OP("TfqSimulateSampledExpectation")
.Input("programs: string")
.Input("symbol_names: string")
.Input("symbol_values: float")
.Input("pauli_sums: string")
.Input("num_samples: int32")
.Output("expectations: float")
.SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
tensorflow::shape_inference::ShapeHandle programs_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));
tensorflow::shape_inference::ShapeHandle symbol_names_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));
tensorflow::shape_inference::ShapeHandle symbol_values_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));
tensorflow::shape_inference::ShapeHandle pauli_sums_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &pauli_sums_shape));
tensorflow::shape_inference::ShapeHandle num_samples_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &num_samples_shape));
tensorflow::shape_inference::DimensionHandle output_rows =
c->Dim(programs_shape, 0);
tensorflow::shape_inference::DimensionHandle output_cols =
c->Dim(pauli_sums_shape, 1);
c->set_output(0, c->Matrix(output_rows, output_cols));
return tensorflow::Status::OK();
});
} // namespace tfq
<|endoftext|>
|
<commit_before>/*******************************************************************************
* thrill/data/channel.hpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
* Copyright (C) 2015 Tobias Sturm <mail@tobiassturm.de>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_DATA_CHANNEL_HEADER
#define THRILL_DATA_CHANNEL_HEADER
#include <thrill/common/stats_counter.hpp>
#include <thrill/common/stats_timer.hpp>
#include <thrill/data/block_queue.hpp>
#include <thrill/data/channel_sink.hpp>
#include <thrill/data/concat_block_source.hpp>
#include <thrill/data/file.hpp>
#include <thrill/data/multiplexer.hpp>
#include <thrill/data/multiplexer_header.hpp>
#include <thrill/net/connection.hpp>
#include <thrill/net/group.hpp>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
namespace thrill {
namespace data {
//! \addtogroup data Data Subsystem
//! \{
using ChannelId = size_t;
/*!
* A Channel is a virtual set of connections to all other worker instances,
* hence a "Channel" bundles them to a logical communication context. We call an
* individual connection from a worker to another worker a "Host".
*
* To use a Channel, one can get a vector of BlockWriter via OpenWriters() of
* outbound Channel. The vector is of size of workers in the system.
* One can then write items destined to the
* corresponding worker. The written items are buffered into a Block and only
* sent when the Block is full. To force a send, use BlockWriter::Flush(). When
* all items are sent, the BlockWriters **must** be closed using
* BlockWriter::Close().
*
* To read the inbound Connection items, one can get a vector of BlockReader via
* OpenReaders(), which can then be used to read items sent by individual
* workers.
*
* Alternatively, one can use OpenReader() to get a BlockReader which delivers
* all items from *all* worker in worker order (concatenating all inbound
* Connections).
*
* As soon as all attached streams of the Channel have been Close() the number of
* expected streams is reached, the channel is marked as finished and no more
* data will arrive.
*/
class Channel
{
public:
using BlockQueueSource = ConsumeBlockQueueSource;
using BlockQueueReader = BlockReader<BlockQueueSource>;
using ConcatBlockSource = data::ConcatBlockSource<DynBlockSource>;
using ConcatBlockReader = BlockReader<ConcatBlockSource>;
using Writer = DynBlockWriter;
using Reader = BlockQueueReader;
using ConcatReader = ConcatBlockReader;
using StatsCounter = common::StatsCounter<size_t, common::g_enable_stats>;
using StatsTimer = common::StatsTimer<common::g_enable_stats>;
using ClosedCallback = std::function<void()>;
//! Creates a new channel instance
Channel(data::Multiplexer& multiplexer, const ChannelId& id,
size_t my_local_worker_id)
: tx_lifetime_(true), rx_lifetime_(true),
tx_timespan_(), rx_timespan_(),
id_(id),
my_local_worker_id_(my_local_worker_id),
multiplexer_(multiplexer),
expected_closing_blocks_(
(multiplexer_.num_hosts() - 1) * multiplexer_.num_workers_per_host_),
received_closing_blocks_(0) {
sinks_.reserve(multiplexer_.num_workers());
queues_.reserve(multiplexer_.num_workers());
// construct ChannelSink array
for (size_t host = 0; host < multiplexer_.num_hosts(); ++host) {
for (size_t worker = 0; worker < multiplexer_.num_workers_per_host_; worker++) {
if (host == multiplexer_.my_host_rank()) {
sinks_.emplace_back(multiplexer_.block_pool_);
}
else {
sinks_.emplace_back(
multiplexer_.block_pool_,
&multiplexer_.dispatcher_,
&multiplexer_.group_.connection(host),
id,
multiplexer_.my_host_rank(), my_local_worker_id, worker,
&outgoing_bytes_, &outgoing_blocks_, &tx_timespan_);
}
// construct inbound queues
queues_.emplace_back(multiplexer_.block_pool_);
}
}
}
//! non-copyable: delete copy-constructor
Channel(const Channel&) = delete;
//! non-copyable: delete assignment operator
Channel& operator = (const Channel&) = delete;
//! move-constructor: default
Channel(Channel&&) = default;
const ChannelId & id() const {
return id_;
}
//! Creates BlockWriters for each worker. BlockWriter can only be opened
//! once, otherwise the block sequence is incorrectly interleaved!
std::vector<Writer> OpenWriters(size_t block_size = default_block_size) {
tx_timespan_.StartEventually();
std::vector<Writer> result;
for (size_t host = 0; host < multiplexer_.num_hosts(); ++host) {
for (size_t local_worker_id = 0; local_worker_id < multiplexer_.num_workers_per_host_; ++local_worker_id) {
if (host == multiplexer_.my_host_rank()) {
auto target_queue_ptr = multiplexer_.loopback(id_, my_local_worker_id_, local_worker_id);
result.emplace_back(target_queue_ptr, block_size);
}
else {
size_t worker_id = host * multiplexer_.num_workers_per_host_ + local_worker_id;
result.emplace_back(&sinks_[worker_id], block_size);
}
}
}
assert(result.size() == multiplexer_.num_workers());
return result;
}
//! Creates a BlockReader for each worker. The BlockReaders are attached to
//! the BlockQueues in the Channel and wait for further Blocks to arrive or
//! the Channel's remote close.
std::vector<BlockQueueReader> OpenReaders() {
rx_timespan_.StartEventually();
std::vector<BlockQueueReader> result;
for (size_t host = 0; host < multiplexer_.num_hosts(); ++host) {
for (size_t local_worker_id = 0; local_worker_id < multiplexer_.num_workers_per_host_; ++local_worker_id) {
size_t worker_id = host * multiplexer_.num_workers_per_host_ + local_worker_id;
result.emplace_back(BlockQueueSource(queues_[worker_id]));
}
}
assert(result.size() == multiplexer_.num_workers());
return result;
}
//! Creates a BlockReader which concatenates items from all workers in
//! worker rank order. The BlockReader is attached to one \ref
//! ConcatBlockSource which includes all incoming queues of this channel.
ConcatBlockReader OpenConcatReader(bool consume) {
rx_timespan_.StartEventually();
// construct vector of CachingBlockQueueSources to read from queues_.
std::vector<DynBlockSource> result;
for (size_t worker = 0; worker < multiplexer_.num_workers(); ++worker) {
result.emplace_back(queues_[worker].GetBlockSource(consume));
}
// move BlockQueueSources into concatenation BlockSource, and to Reader.
return ConcatBlockReader(ConcatBlockSource(std::move(result)));
}
/*!
* Scatters a File to many worker
*
* elements from 0..offset[0] are sent to the first worker,
* elements from (offset[0] + 1)..offset[1] are sent to the second worker.
* elements from (offset[my_rank - 1] + 1)..(offset[my_rank]) are copied
* The offset values range from 0..Manager::GetNumElements().
* The number of given offsets must be equal to the net::Group::num_workers() * workers_per_host_.
*
* /param source File containing the data to be scattered.
*
* /param offsets - as described above. offsets.size must be equal to group.size
*/
template <typename ItemType>
void Scatter(const File& source, const std::vector<size_t>& offsets) {
tx_timespan_.StartEventually();
// current item offset in Reader
size_t current = 0;
File::KeepReader reader = source.GetKeepReader();
std::vector<Writer> writers = OpenWriters();
for (size_t worker = 0; worker < multiplexer_.num_workers(); ++worker) {
// write [current,limit) to this worker
size_t limit = offsets[worker];
assert(current <= limit);
#if 0
for ( ; current < limit; ++current) {
assert(reader.HasNext());
// move over one item (with deserialization and serialization)
writers[worker](reader.template Next<ItemType>());
}
#else
if (current != limit) {
writers[worker].AppendBlocks(
reader.template GetItemBatch<ItemType>(limit - current));
current = limit;
}
#endif
writers[worker].Close();
}
tx_timespan_.Stop();
}
//! shuts the channel down.
void Close() {
// close all sinks, this should emit sentinel to all other worker.
for (size_t i = 0; i != sinks_.size(); ++i) {
if (sinks_[i].closed()) continue;
sinks_[i].Close();
}
// close loop-back queue from this worker to itself
auto my_global_worker_id = multiplexer_.my_host_rank() * multiplexer_.num_workers_per_host() + my_local_worker_id_;
if (!queues_[my_global_worker_id].write_closed())
queues_[my_global_worker_id].Close();
// wait for close packets to arrive (this is a busy waiting loop, try to
// do it better -tb)
for (size_t i = 0; i != queues_.size(); ++i) {
while (!queues_[i].write_closed()) {
LOG << "wait for close from worker" << i;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
tx_lifetime_.StopEventually();
tx_timespan_.StopEventually();
CallClosedCallbacksEventually();
}
void CallClosedCallbacksEventually() {
std::lock_guard<std::mutex> lock(mutex_);
if (closed()) {
for (const auto& cb : closed_callbacks_)
cb();
closed_callbacks_.clear();
}
}
//! Indicates if the channel is closed - meaning all remite streams have
//! been closed. This does *not* include the loopback stream
bool closed() const {
bool closed = true;
for (auto& q : queues_) {
closed = closed && q.write_closed();
}
return closed;
}
//! Adds a Callback that is called when the channel is closed (r+w)
void OnClose(ClosedCallback cb) {
closed_callbacks_.push_back(cb);
}
///////// expse these members - getters would be too java-ish /////////////
//! StatsCounter for incoming data transfer
//! Do not include loopback data transfer
StatsCounter incoming_bytes_, incoming_blocks_;
//! StatsCounters for outgoing data transfer - shared by all sinks
//! Do not include loopback data transfer
StatsCounter outgoing_bytes_, outgoing_blocks_;
//! Timers from creation of channel until rx / tx direction is closed.
StatsTimer tx_lifetime_, rx_lifetime_;
//! Timers from first rx / tx package until rx / tx direction is closed.
StatsTimer tx_timespan_, rx_timespan_;
///////////////////////////////////////////////////////////////////////////
protected:
static const bool debug = false;
ChannelId id_;
size_t my_local_worker_id_;
//! reference to multiplexer
data::Multiplexer& multiplexer_;
//! ChannelSink objects are receivers of Blocks outbound for other worker.
std::vector<ChannelSink> sinks_;
//! BlockQueues to store incoming Blocks with no attached destination.
std::vector<BlockQueue> queues_;
//! number of expected / received stream closing operations. Required to know when to
//! stop rx_lifetime
size_t expected_closing_blocks_, received_closing_blocks_;
//! Callbacks that are called once when the channel is closed (r+w)
std::vector<ClosedCallback> closed_callbacks_;
// protects against race conditions in closed_callbacks_ loop
std::mutex mutex_;
//! for calling methods to deliver blocks
friend class Multiplexer;
//! called from Multiplexer when there is a new Block on a
//! Channel.
//! \param from the worker rank (host rank * num_workers/host + worker id)
void OnChannelBlock(size_t from, Block&& b) {
assert(from < queues_.size());
rx_timespan_.StartEventually();
incoming_bytes_ += b.size();
incoming_blocks_++;
sLOG << "OnChannelBlock" << b;
if (debug) {
sLOG << "channel" << id_ << "receive from" << from << ":"
<< common::hexdump(b.ToString());
}
queues_[from].AppendBlock(b);
}
//! called from Multiplexer when a Channel closed notification was
//! received.
//! \param from the worker rank (host rank * num_workers/host + worker id)
void OnCloseChannel(size_t from) {
assert(from < queues_.size());
assert(!queues_[from].write_closed());
queues_[from].Close();
if (expected_closing_blocks_ == ++received_closing_blocks_) {
rx_lifetime_.StopEventually();
rx_timespan_.StopEventually();
CallClosedCallbacksEventually();
}
}
//! Returns the loopback queue for the worker of this channel.
BlockQueue * loopback_queue(size_t from_worker_id) {
assert(from_worker_id < multiplexer_.num_workers_per_host_);
size_t global_worker_rank = multiplexer_.num_workers_per_host_ * multiplexer_.my_host_rank() + from_worker_id;
sLOG << "expose loopback queue for" << from_worker_id << "->" << my_local_worker_id_;
return &(queues_[global_worker_rank]);
}
};
using ChannelPtr = std::shared_ptr<Channel>;
/*! Simple structure that holds a all channel instances for the workers on the
*! local host for a given channel id.
*/
class ChannelSet
{
public:
//! Creates a ChannelSet with the given number of channels (num workers per host).
ChannelSet(data::Multiplexer& multiplexer, ChannelId id, size_t num_workers_per_host) {
for (size_t i = 0; i < num_workers_per_host; i++)
channels_.push_back(std::make_shared<Channel>(multiplexer, id, i));
}
//! Returns the channel that will be consumed by the worker with the given
//! local id
ChannelPtr peer(size_t local_worker_id) {
assert(local_worker_id < channels_.size());
return channels_[local_worker_id];
}
void Close() {
for (auto& c : channels_)
c->Close();
}
private:
//! 'owns' all channels belonging to one channel id for all local workers.
std::vector<ChannelPtr> channels_;
};
//! \}
} // namespace data
} // namespace thrill
#endif // !THRILL_DATA_CHANNEL_HEADER
/******************************************************************************/
<commit_msg>use StatLogger in data::Channel<commit_after>/*******************************************************************************
* thrill/data/channel.hpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
* Copyright (C) 2015 Tobias Sturm <mail@tobiassturm.de>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_DATA_CHANNEL_HEADER
#define THRILL_DATA_CHANNEL_HEADER
#include <thrill/common/stats_counter.hpp>
#include <thrill/common/stats_timer.hpp>
#include <thrill/common/stat_logger.hpp>
#include <thrill/data/block_queue.hpp>
#include <thrill/data/channel_sink.hpp>
#include <thrill/data/concat_block_source.hpp>
#include <thrill/data/file.hpp>
#include <thrill/data/multiplexer.hpp>
#include <thrill/data/multiplexer_header.hpp>
#include <thrill/net/connection.hpp>
#include <thrill/net/group.hpp>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
namespace thrill {
namespace data {
//! \addtogroup data Data Subsystem
//! \{
using ChannelId = size_t;
/*!
* A Channel is a virtual set of connections to all other worker instances,
* hence a "Channel" bundles them to a logical communication context. We call an
* individual connection from a worker to another worker a "Host".
*
* To use a Channel, one can get a vector of BlockWriter via OpenWriters() of
* outbound Channel. The vector is of size of workers in the system.
* One can then write items destined to the
* corresponding worker. The written items are buffered into a Block and only
* sent when the Block is full. To force a send, use BlockWriter::Flush(). When
* all items are sent, the BlockWriters **must** be closed using
* BlockWriter::Close().
*
* To read the inbound Connection items, one can get a vector of BlockReader via
* OpenReaders(), which can then be used to read items sent by individual
* workers.
*
* Alternatively, one can use OpenReader() to get a BlockReader which delivers
* all items from *all* worker in worker order (concatenating all inbound
* Connections).
*
* As soon as all attached streams of the Channel have been Close() the number of
* expected streams is reached, the channel is marked as finished and no more
* data will arrive.
*/
class Channel
{
public:
using BlockQueueSource = ConsumeBlockQueueSource;
using BlockQueueReader = BlockReader<BlockQueueSource>;
using ConcatBlockSource = data::ConcatBlockSource<DynBlockSource>;
using ConcatBlockReader = BlockReader<ConcatBlockSource>;
using Writer = DynBlockWriter;
using Reader = BlockQueueReader;
using ConcatReader = ConcatBlockReader;
using StatsCounter = common::StatsCounter<size_t, common::g_enable_stats>;
using StatsTimer = common::StatsTimer<common::g_enable_stats>;
using ClosedCallback = std::function<void()>;
//! Creates a new channel instance
Channel(data::Multiplexer& multiplexer, const ChannelId& id,
size_t my_local_worker_id)
: tx_lifetime_(true), rx_lifetime_(true),
tx_timespan_(), rx_timespan_(),
id_(id),
my_local_worker_id_(my_local_worker_id),
multiplexer_(multiplexer),
expected_closing_blocks_(
(multiplexer_.num_hosts() - 1) * multiplexer_.num_workers_per_host_),
received_closing_blocks_(0) {
sinks_.reserve(multiplexer_.num_workers());
queues_.reserve(multiplexer_.num_workers());
// construct ChannelSink array
for (size_t host = 0; host < multiplexer_.num_hosts(); ++host) {
for (size_t worker = 0; worker < multiplexer_.num_workers_per_host_; worker++) {
if (host == multiplexer_.my_host_rank()) {
sinks_.emplace_back(multiplexer_.block_pool_);
}
else {
sinks_.emplace_back(
multiplexer_.block_pool_,
&multiplexer_.dispatcher_,
&multiplexer_.group_.connection(host),
id,
multiplexer_.my_host_rank(), my_local_worker_id, worker,
&outgoing_bytes_, &outgoing_blocks_, &tx_timespan_);
}
// construct inbound queues
queues_.emplace_back(multiplexer_.block_pool_);
}
}
}
//! non-copyable: delete copy-constructor
Channel(const Channel&) = delete;
//! non-copyable: delete assignment operator
Channel& operator = (const Channel&) = delete;
//! move-constructor: default
Channel(Channel&&) = default;
const ChannelId & id() const {
return id_;
}
//! Creates BlockWriters for each worker. BlockWriter can only be opened
//! once, otherwise the block sequence is incorrectly interleaved!
std::vector<Writer> OpenWriters(size_t block_size = default_block_size) {
tx_timespan_.StartEventually();
std::vector<Writer> result;
for (size_t host = 0; host < multiplexer_.num_hosts(); ++host) {
for (size_t local_worker_id = 0; local_worker_id < multiplexer_.num_workers_per_host_; ++local_worker_id) {
if (host == multiplexer_.my_host_rank()) {
auto target_queue_ptr = multiplexer_.loopback(id_, my_local_worker_id_, local_worker_id);
result.emplace_back(target_queue_ptr, block_size);
}
else {
size_t worker_id = host * multiplexer_.num_workers_per_host_ + local_worker_id;
result.emplace_back(&sinks_[worker_id], block_size);
}
}
}
assert(result.size() == multiplexer_.num_workers());
return result;
}
//! Creates a BlockReader for each worker. The BlockReaders are attached to
//! the BlockQueues in the Channel and wait for further Blocks to arrive or
//! the Channel's remote close.
std::vector<BlockQueueReader> OpenReaders() {
rx_timespan_.StartEventually();
std::vector<BlockQueueReader> result;
for (size_t host = 0; host < multiplexer_.num_hosts(); ++host) {
for (size_t local_worker_id = 0; local_worker_id < multiplexer_.num_workers_per_host_; ++local_worker_id) {
size_t worker_id = host * multiplexer_.num_workers_per_host_ + local_worker_id;
result.emplace_back(BlockQueueSource(queues_[worker_id]));
}
}
assert(result.size() == multiplexer_.num_workers());
return result;
}
//! Creates a BlockReader which concatenates items from all workers in
//! worker rank order. The BlockReader is attached to one \ref
//! ConcatBlockSource which includes all incoming queues of this channel.
ConcatBlockReader OpenConcatReader(bool consume) {
rx_timespan_.StartEventually();
// construct vector of CachingBlockQueueSources to read from queues_.
std::vector<DynBlockSource> result;
for (size_t worker = 0; worker < multiplexer_.num_workers(); ++worker) {
result.emplace_back(queues_[worker].GetBlockSource(consume));
}
// move BlockQueueSources into concatenation BlockSource, and to Reader.
return ConcatBlockReader(ConcatBlockSource(std::move(result)));
}
/*!
* Scatters a File to many worker
*
* elements from 0..offset[0] are sent to the first worker,
* elements from (offset[0] + 1)..offset[1] are sent to the second worker.
* elements from (offset[my_rank - 1] + 1)..(offset[my_rank]) are copied
* The offset values range from 0..Manager::GetNumElements().
* The number of given offsets must be equal to the net::Group::num_workers() * workers_per_host_.
*
* /param source File containing the data to be scattered.
*
* /param offsets - as described above. offsets.size must be equal to group.size
*/
template <typename ItemType>
void Scatter(const File& source, const std::vector<size_t>& offsets) {
tx_timespan_.StartEventually();
// current item offset in Reader
size_t current = 0;
File::KeepReader reader = source.GetKeepReader();
std::vector<Writer> writers = OpenWriters();
for (size_t worker = 0; worker < multiplexer_.num_workers(); ++worker) {
// write [current,limit) to this worker
size_t limit = offsets[worker];
assert(current <= limit);
#if 0
for ( ; current < limit; ++current) {
assert(reader.HasNext());
// move over one item (with deserialization and serialization)
writers[worker](reader.template Next<ItemType>());
}
#else
if (current != limit) {
writers[worker].AppendBlocks(
reader.template GetItemBatch<ItemType>(limit - current));
current = limit;
}
#endif
writers[worker].Close();
}
tx_timespan_.Stop();
STAT_NO_RANK << "worker_id" << my_global_worker_id()
<< "event" << "scatter_send_done"
<< "channel_id" << id_
<< "tx_time_μs" << tx_timespan_.Microseconds()
<< "tx_lifetime_μs" << tx_lifetime_.Microseconds()
<< "bytes_sent" << outgoing_bytes_
<< "blocks_sent" << outgoing_blocks_;
}
//! shuts the channel down.
void Close() {
// close all sinks, this should emit sentinel to all other worker.
for (size_t i = 0; i != sinks_.size(); ++i) {
if (sinks_[i].closed()) continue;
sinks_[i].Close();
}
// close loop-back queue from this worker to itself
if (!queues_[my_global_worker_id()].write_closed())
queues_[my_global_worker_id()].Close();
// wait for close packets to arrive (this is a busy waiting loop, try to
// do it better -tb)
for (size_t i = 0; i != queues_.size(); ++i) {
while (!queues_[i].write_closed()) {
LOG << "wait for close from worker" << i;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
tx_lifetime_.StopEventually();
tx_timespan_.StopEventually();
CallClosedCallbacksEventually();
}
void CallClosedCallbacksEventually() {
std::lock_guard<std::mutex> lock(mutex_);
if (closed()) {
for (const auto& cb : closed_callbacks_)
cb();
closed_callbacks_.clear();
}
}
//! Indicates if the channel is closed - meaning all remite streams have
//! been closed. This does *not* include the loopback stream
bool closed() const {
bool closed = true;
for (auto& q : queues_) {
closed = closed && q.write_closed();
}
return closed;
}
//! Adds a Callback that is called when the channel is closed (r+w)
void OnClose(ClosedCallback cb) {
closed_callbacks_.push_back(cb);
}
///////// expse these members - getters would be too java-ish /////////////
//! StatsCounter for incoming data transfer
//! Do not include loopback data transfer
StatsCounter incoming_bytes_, incoming_blocks_;
//! StatsCounters for outgoing data transfer - shared by all sinks
//! Do not include loopback data transfer
StatsCounter outgoing_bytes_, outgoing_blocks_;
//! Timers from creation of channel until rx / tx direction is closed.
StatsTimer tx_lifetime_, rx_lifetime_;
//! Timers from first rx / tx package until rx / tx direction is closed.
StatsTimer tx_timespan_, rx_timespan_;
///////////////////////////////////////////////////////////////////////////
protected:
static const bool debug = false;
ChannelId id_;
size_t my_local_worker_id_;
//! reference to multiplexer
data::Multiplexer& multiplexer_;
//! ChannelSink objects are receivers of Blocks outbound for other worker.
std::vector<ChannelSink> sinks_;
//! BlockQueues to store incoming Blocks with no attached destination.
std::vector<BlockQueue> queues_;
//! number of expected / received stream closing operations. Required to know when to
//! stop rx_lifetime
size_t expected_closing_blocks_, received_closing_blocks_;
//! Callbacks that are called once when the channel is closed (r+w)
std::vector<ClosedCallback> closed_callbacks_;
// protects against race conditions in closed_callbacks_ loop
std::mutex mutex_;
//! for calling methods to deliver blocks
friend class Multiplexer;
//! called from Multiplexer when there is a new Block on a
//! Channel.
//! \param from the worker rank (host rank * num_workers/host + worker id)
void OnChannelBlock(size_t from, Block&& b) {
assert(from < queues_.size());
rx_timespan_.StartEventually();
incoming_bytes_ += b.size();
incoming_blocks_++;
sLOG << "OnChannelBlock" << b;
if (debug) {
sLOG << "channel" << id_ << "receive from" << from << ":"
<< common::hexdump(b.ToString());
}
queues_[from].AppendBlock(b);
}
//! called from Multiplexer when a Channel closed notification was
//! received.
//! \param from the worker rank (host rank * num_workers/host + worker id)
void OnCloseChannel(size_t from) {
assert(from < queues_.size());
assert(!queues_[from].write_closed());
queues_[from].Close();
if (expected_closing_blocks_ == ++received_closing_blocks_) {
rx_lifetime_.StopEventually();
rx_timespan_.StopEventually();
STAT_NO_RANK << "worker_id" << my_global_worker_id()
<< "event" << "channel_closed"
<< "channel_id" << id_
<< "tx_time_μs" << tx_timespan_.Microseconds()
<< "rx_time_μs" << rx_timespan_.Microseconds()
<< "tx_lifetime_μs" << tx_lifetime_.Microseconds()
<< "rx_lifetime_μs" << rx_lifetime_.Microseconds()
<< "bytes_sent" << outgoing_bytes_
<< "blocks_sent" << outgoing_blocks_
<< "bytes_incoming" << incoming_bytes_
<< "blocks_sent" << incoming_blocks_;
CallClosedCallbacksEventually();
}
}
//! Returns the loopback queue for the worker of this channel.
BlockQueue * loopback_queue(size_t from_worker_id) {
assert(from_worker_id < multiplexer_.num_workers_per_host_);
size_t global_worker_rank = multiplexer_.num_workers_per_host_ * multiplexer_.my_host_rank() + from_worker_id;
sLOG << "expose loopback queue for" << from_worker_id << "->" << my_local_worker_id_;
return &(queues_[global_worker_rank]);
}
private:
//TODO maybe use context as memer reference instead ?
size_t my_global_worker_id() const {
return multiplexer_.my_host_rank() * multiplexer_.num_workers_per_host() + my_local_worker_id_;
}
};
using ChannelPtr = std::shared_ptr<Channel>;
/*! Simple structure that holds a all channel instances for the workers on the
*! local host for a given channel id.
*/
class ChannelSet
{
public:
//! Creates a ChannelSet with the given number of channels (num workers per host).
ChannelSet(data::Multiplexer& multiplexer, ChannelId id, size_t num_workers_per_host) {
for (size_t i = 0; i < num_workers_per_host; i++)
channels_.push_back(std::make_shared<Channel>(multiplexer, id, i));
}
//! Returns the channel that will be consumed by the worker with the given
//! local id
ChannelPtr peer(size_t local_worker_id) {
assert(local_worker_id < channels_.size());
return channels_[local_worker_id];
}
void Close() {
for (auto& c : channels_)
c->Close();
}
private:
//! 'owns' all channels belonging to one channel id for all local workers.
std::vector<ChannelPtr> channels_;
};
//! \}
} // namespace data
} // namespace thrill
#endif // !THRILL_DATA_CHANNEL_HEADER
/******************************************************************************/
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Test of FieldTrial class
#include "base/field_trial.h"
#include "base/stringprintf.h"
#include "testing/gtest/include/gtest/gtest.h"
class FieldTrialTest : public testing::Test {
public:
FieldTrialTest() : trial_list_() { }
private:
FieldTrialList trial_list_;
};
// Test registration, and also check that destructors are called for trials
// (and that Purify doesn't catch us leaking).
TEST_F(FieldTrialTest, Registration) {
const char* name1 = "name 1 test";
const char* name2 = "name 2 test";
EXPECT_FALSE(FieldTrialList::Find(name1));
EXPECT_FALSE(FieldTrialList::Find(name2));
FieldTrial* trial1 = new FieldTrial(name1, 10);
EXPECT_EQ(FieldTrial::kNotParticipating, trial1->group());
EXPECT_EQ(name1, trial1->name());
EXPECT_EQ("", trial1->group_name());
trial1->AppendGroup("", 7);
EXPECT_EQ(trial1, FieldTrialList::Find(name1));
EXPECT_FALSE(FieldTrialList::Find(name2));
FieldTrial* trial2 = new FieldTrial(name2, 10);
EXPECT_EQ(FieldTrial::kNotParticipating, trial2->group());
EXPECT_EQ(name2, trial2->name());
EXPECT_EQ("", trial2->group_name());
trial2->AppendGroup("a first group", 7);
EXPECT_EQ(trial1, FieldTrialList::Find(name1));
EXPECT_EQ(trial2, FieldTrialList::Find(name2));
// Note: FieldTrialList should delete the objects at shutdown.
}
TEST_F(FieldTrialTest, AbsoluteProbabilities) {
char always_true[] = " always true";
char always_false[] = " always false";
for (int i = 1; i < 250; ++i) {
// Try lots of names, by changing the first character of the name.
always_true[0] = i;
always_false[0] = i;
FieldTrial* trial_true = new FieldTrial(always_true, 10);
const std::string winner = "TheWinner";
int winner_group = trial_true->AppendGroup(winner, 10);
EXPECT_EQ(winner_group, trial_true->group());
EXPECT_EQ(winner, trial_true->group_name());
FieldTrial* trial_false = new FieldTrial(always_false, 10);
int loser_group = trial_false->AppendGroup("ALoser", 0);
EXPECT_NE(loser_group, trial_false->group());
}
}
TEST_F(FieldTrialTest, RemainingProbability) {
// First create a test that hasn't had a winner yet.
const std::string winner = "Winner";
const std::string loser = "Loser";
scoped_refptr<FieldTrial> trial;
int counter = 0;
do {
std::string name = base::StringPrintf("trial%d", ++counter);
trial = new FieldTrial(name, 10);
trial->AppendGroup(loser, 5); // 50% chance of not being chosen.
} while (trial->group() != FieldTrial::kNotParticipating);
// Now add a winner with all remaining probability.
trial->AppendGroup(winner, FieldTrial::kAllRemainingProbability);
// And that winner should ALWAYS win.
EXPECT_EQ(winner, trial->group_name());
}
TEST_F(FieldTrialTest, MiddleProbabilities) {
char name[] = " same name";
bool false_event_seen = false;
bool true_event_seen = false;
for (int i = 1; i < 250; ++i) {
name[0] = i;
FieldTrial* trial = new FieldTrial(name, 10);
int might_win = trial->AppendGroup("MightWin", 5);
if (trial->group() == might_win) {
true_event_seen = true;
} else {
false_event_seen = true;
}
if (false_event_seen && true_event_seen)
return; // Successful test!!!
}
// Very surprising to get here. Probability should be around 1 in 2 ** 250.
// One of the following will fail.
EXPECT_TRUE(false_event_seen);
EXPECT_TRUE(true_event_seen);
}
TEST_F(FieldTrialTest, OneWinner) {
char name[] = "Some name";
int group_count(10);
FieldTrial* trial = new FieldTrial(name, group_count);
int winner_index(-2);
std::string winner_name;
for (int i = 1; i <= group_count; ++i) {
int might_win = trial->AppendGroup("", 1);
if (trial->group() == might_win) {
EXPECT_EQ(-2, winner_index);
winner_index = might_win;
StringAppendF(&winner_name, "%d", might_win);
EXPECT_EQ(winner_name, trial->group_name());
}
}
EXPECT_GE(winner_index, 0);
EXPECT_EQ(trial->group(), winner_index);
EXPECT_EQ(trial->group_name(), winner_name);
}
TEST_F(FieldTrialTest, Save) {
std::string save_string;
FieldTrial* trial = new FieldTrial("Some name", 10);
// There is no winner yet, so no textual group name is associated with trial.
EXPECT_EQ("", trial->group_name());
FieldTrialList::StatesToString(&save_string);
EXPECT_EQ("", save_string);
save_string.clear();
// Create a winning group.
trial->AppendGroup("Winner", 10);
FieldTrialList::StatesToString(&save_string);
EXPECT_EQ("Some name/Winner/", save_string);
save_string.clear();
// Create a second trial and winning group.
FieldTrial* trial2 = new FieldTrial("xxx", 10);
trial2->AppendGroup("yyyy", 10);
FieldTrialList::StatesToString(&save_string);
// We assume names are alphabetized... though this is not critical.
EXPECT_EQ("Some name/Winner/xxx/yyyy/", save_string);
}
TEST_F(FieldTrialTest, Restore) {
EXPECT_TRUE(FieldTrialList::Find("Some_name") == NULL);
EXPECT_TRUE(FieldTrialList::Find("xxx") == NULL);
FieldTrialList::StringAugmentsState("Some_name/Winner/xxx/yyyy/");
FieldTrial* trial = FieldTrialList::Find("Some_name");
ASSERT_NE(static_cast<FieldTrial*>(NULL), trial);
EXPECT_EQ("Winner", trial->group_name());
EXPECT_EQ("Some_name", trial->name());
trial = FieldTrialList::Find("xxx");
ASSERT_NE(static_cast<FieldTrial*>(NULL), trial);
EXPECT_EQ("yyyy", trial->group_name());
EXPECT_EQ("xxx", trial->name());
}
TEST_F(FieldTrialTest, BogusRestore) {
EXPECT_FALSE(FieldTrialList::StringAugmentsState("MissingSlash"));
EXPECT_FALSE(FieldTrialList::StringAugmentsState("MissingGroupName/"));
EXPECT_FALSE(FieldTrialList::StringAugmentsState("MissingFinalSlash/gname"));
EXPECT_FALSE(FieldTrialList::StringAugmentsState("/noname, only group/"));
}
TEST_F(FieldTrialTest, DuplicateRestore) {
FieldTrial* trial = new FieldTrial("Some name", 10);
trial->AppendGroup("Winner", 10);
std::string save_string;
FieldTrialList::StatesToString(&save_string);
EXPECT_EQ("Some name/Winner/", save_string);
// It is OK if we redundantly specify a winner.
EXPECT_TRUE(FieldTrialList::StringAugmentsState(save_string));
// But it is an error to try to change to a different winner.
EXPECT_FALSE(FieldTrialList::StringAugmentsState("Some name/Loser/"));
}
TEST_F(FieldTrialTest, MakeName) {
FieldTrial* trial = new FieldTrial("Field Trial", 10);
trial->AppendGroup("Winner", 10);
EXPECT_EQ("Histogram_Winner",
FieldTrial::MakeName("Histogram", "Field Trial"));
}
<commit_msg>Add extra unit test to avoid off-by-one errors<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Test of FieldTrial class
#include "base/field_trial.h"
#include "base/stringprintf.h"
#include "testing/gtest/include/gtest/gtest.h"
class FieldTrialTest : public testing::Test {
public:
FieldTrialTest() : trial_list_() { }
private:
FieldTrialList trial_list_;
};
// Test registration, and also check that destructors are called for trials
// (and that Purify doesn't catch us leaking).
TEST_F(FieldTrialTest, Registration) {
const char* name1 = "name 1 test";
const char* name2 = "name 2 test";
EXPECT_FALSE(FieldTrialList::Find(name1));
EXPECT_FALSE(FieldTrialList::Find(name2));
FieldTrial* trial1 = new FieldTrial(name1, 10);
EXPECT_EQ(FieldTrial::kNotParticipating, trial1->group());
EXPECT_EQ(name1, trial1->name());
EXPECT_EQ("", trial1->group_name());
trial1->AppendGroup("", 7);
EXPECT_EQ(trial1, FieldTrialList::Find(name1));
EXPECT_FALSE(FieldTrialList::Find(name2));
FieldTrial* trial2 = new FieldTrial(name2, 10);
EXPECT_EQ(FieldTrial::kNotParticipating, trial2->group());
EXPECT_EQ(name2, trial2->name());
EXPECT_EQ("", trial2->group_name());
trial2->AppendGroup("a first group", 7);
EXPECT_EQ(trial1, FieldTrialList::Find(name1));
EXPECT_EQ(trial2, FieldTrialList::Find(name2));
// Note: FieldTrialList should delete the objects at shutdown.
}
TEST_F(FieldTrialTest, AbsoluteProbabilities) {
char always_true[] = " always true";
char always_false[] = " always false";
for (int i = 1; i < 250; ++i) {
// Try lots of names, by changing the first character of the name.
always_true[0] = i;
always_false[0] = i;
FieldTrial* trial_true = new FieldTrial(always_true, 10);
const std::string winner = "TheWinner";
int winner_group = trial_true->AppendGroup(winner, 10);
EXPECT_EQ(winner_group, trial_true->group());
EXPECT_EQ(winner, trial_true->group_name());
FieldTrial* trial_false = new FieldTrial(always_false, 10);
int loser_group = trial_false->AppendGroup("ALoser", 0);
EXPECT_NE(loser_group, trial_false->group());
}
}
TEST_F(FieldTrialTest, RemainingProbability) {
// First create a test that hasn't had a winner yet.
const std::string winner = "Winner";
const std::string loser = "Loser";
scoped_refptr<FieldTrial> trial;
int counter = 0;
do {
std::string name = base::StringPrintf("trial%d", ++counter);
trial = new FieldTrial(name, 10);
trial->AppendGroup(loser, 5); // 50% chance of not being chosen.
} while (trial->group() != FieldTrial::kNotParticipating);
// Now add a winner with all remaining probability.
trial->AppendGroup(winner, FieldTrial::kAllRemainingProbability);
// And that winner should ALWAYS win.
EXPECT_EQ(winner, trial->group_name());
}
TEST_F(FieldTrialTest, FiftyFiftyProbability) {
// Check that even with small divisors, we have the proper probabilities, and
// all outcomes are possible. Since this is a 50-50 test, it should get both
// outcomes in a few tries, but we'll try no more than 100 times (and be flaky
// with probability around 1 in 2^99).
bool first_winner = false;
bool second_winner = false;
int counter = 0;
do {
std::string name = base::StringPrintf("FiftyFifty%d", ++counter);
scoped_refptr<FieldTrial> trial = new FieldTrial(name, 2);
trial->AppendGroup("first", 1); // 50% chance of being chosen.
if (trial->group() != FieldTrial::kNotParticipating) {
first_winner = true;
continue;
}
trial->AppendGroup("second", 1); // Always chosen at this point.
EXPECT_NE(FieldTrial::kNotParticipating, trial->group());
second_winner = true;
} while ((!second_winner || !first_winner) && counter < 100);
EXPECT_TRUE(second_winner);
EXPECT_TRUE(first_winner);
}
TEST_F(FieldTrialTest, MiddleProbabilities) {
char name[] = " same name";
bool false_event_seen = false;
bool true_event_seen = false;
for (int i = 1; i < 250; ++i) {
name[0] = i;
FieldTrial* trial = new FieldTrial(name, 10);
int might_win = trial->AppendGroup("MightWin", 5);
if (trial->group() == might_win) {
true_event_seen = true;
} else {
false_event_seen = true;
}
if (false_event_seen && true_event_seen)
return; // Successful test!!!
}
// Very surprising to get here. Probability should be around 1 in 2 ** 250.
// One of the following will fail.
EXPECT_TRUE(false_event_seen);
EXPECT_TRUE(true_event_seen);
}
TEST_F(FieldTrialTest, OneWinner) {
char name[] = "Some name";
int group_count(10);
FieldTrial* trial = new FieldTrial(name, group_count);
int winner_index(-2);
std::string winner_name;
for (int i = 1; i <= group_count; ++i) {
int might_win = trial->AppendGroup("", 1);
if (trial->group() == might_win) {
EXPECT_EQ(-2, winner_index);
winner_index = might_win;
StringAppendF(&winner_name, "%d", might_win);
EXPECT_EQ(winner_name, trial->group_name());
}
}
EXPECT_GE(winner_index, 0);
EXPECT_EQ(trial->group(), winner_index);
EXPECT_EQ(trial->group_name(), winner_name);
}
TEST_F(FieldTrialTest, Save) {
std::string save_string;
FieldTrial* trial = new FieldTrial("Some name", 10);
// There is no winner yet, so no textual group name is associated with trial.
EXPECT_EQ("", trial->group_name());
FieldTrialList::StatesToString(&save_string);
EXPECT_EQ("", save_string);
save_string.clear();
// Create a winning group.
trial->AppendGroup("Winner", 10);
FieldTrialList::StatesToString(&save_string);
EXPECT_EQ("Some name/Winner/", save_string);
save_string.clear();
// Create a second trial and winning group.
FieldTrial* trial2 = new FieldTrial("xxx", 10);
trial2->AppendGroup("yyyy", 10);
FieldTrialList::StatesToString(&save_string);
// We assume names are alphabetized... though this is not critical.
EXPECT_EQ("Some name/Winner/xxx/yyyy/", save_string);
}
TEST_F(FieldTrialTest, Restore) {
EXPECT_TRUE(FieldTrialList::Find("Some_name") == NULL);
EXPECT_TRUE(FieldTrialList::Find("xxx") == NULL);
FieldTrialList::StringAugmentsState("Some_name/Winner/xxx/yyyy/");
FieldTrial* trial = FieldTrialList::Find("Some_name");
ASSERT_NE(static_cast<FieldTrial*>(NULL), trial);
EXPECT_EQ("Winner", trial->group_name());
EXPECT_EQ("Some_name", trial->name());
trial = FieldTrialList::Find("xxx");
ASSERT_NE(static_cast<FieldTrial*>(NULL), trial);
EXPECT_EQ("yyyy", trial->group_name());
EXPECT_EQ("xxx", trial->name());
}
TEST_F(FieldTrialTest, BogusRestore) {
EXPECT_FALSE(FieldTrialList::StringAugmentsState("MissingSlash"));
EXPECT_FALSE(FieldTrialList::StringAugmentsState("MissingGroupName/"));
EXPECT_FALSE(FieldTrialList::StringAugmentsState("MissingFinalSlash/gname"));
EXPECT_FALSE(FieldTrialList::StringAugmentsState("/noname, only group/"));
}
TEST_F(FieldTrialTest, DuplicateRestore) {
FieldTrial* trial = new FieldTrial("Some name", 10);
trial->AppendGroup("Winner", 10);
std::string save_string;
FieldTrialList::StatesToString(&save_string);
EXPECT_EQ("Some name/Winner/", save_string);
// It is OK if we redundantly specify a winner.
EXPECT_TRUE(FieldTrialList::StringAugmentsState(save_string));
// But it is an error to try to change to a different winner.
EXPECT_FALSE(FieldTrialList::StringAugmentsState("Some name/Loser/"));
}
TEST_F(FieldTrialTest, MakeName) {
FieldTrial* trial = new FieldTrial("Field Trial", 10);
trial->AppendGroup("Winner", 10);
EXPECT_EQ("Histogram_Winner",
FieldTrial::MakeName("Histogram", "Field Trial"));
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _SBSTDOBJ1_HXX
#define _SBSTDOBJ1_HXX
#include <basic/sbxobj.hxx>
#include <vcl/graph.hxx>
#include <basic/sbxfac.hxx>
#include "basicdllapi.h"
class StarBASIC;
class SbStdFactory;
//--------------------
// class SbStdFactory
//--------------------
class BASIC_DLLPUBLIC SbStdFactory : public SbxFactory
{
public:
SbStdFactory();
virtual SbxObject* CreateObject( const rtl::OUString& rClassName );
};
//--------------------
// class SbStdPicture
//--------------------
class BASIC_DLLPUBLIC SbStdPicture : public SbxObject
{
protected:
Graphic aGraphic;
~SbStdPicture();
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
void PropType( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropWidth( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropHeight( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
public:
TYPEINFO();
SbStdPicture();
virtual SbxVariable* Find( const rtl::OUString&, SbxClassType );
Graphic GetGraphic() const { return aGraphic; }
void SetGraphic( const Graphic& rGrf ) { aGraphic = rGrf; }
};
//-----------------
// class SbStdFont
//-----------------
class BASIC_DLLPUBLIC SbStdFont : public SbxObject
{
protected:
sal_Bool bBold;
sal_Bool bItalic;
sal_Bool bStrikeThrough;
sal_Bool bUnderline;
sal_uInt16 nSize;
String aName;
~SbStdFont();
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
void PropBold( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropItalic( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropStrikeThrough( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropUnderline( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropSize( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropName( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
public:
TYPEINFO();
SbStdFont();
virtual SbxVariable* Find( const rtl::OUString&, SbxClassType );
void SetBold( sal_Bool bB ) { bBold = bB; }
sal_Bool IsBold() const { return bBold; }
void SetItalic( sal_Bool bI ) { bItalic = bI; }
sal_Bool IsItalic() const { return bItalic; }
void SetStrikeThrough( sal_Bool bS ) { bStrikeThrough = bS; }
sal_Bool IsStrikeThrough() const { return bStrikeThrough; }
void SetUnderline( sal_Bool bU ) { bUnderline = bU; }
sal_Bool IsUnderline() const { return bUnderline; }
void SetSize( sal_uInt16 nS ) { nSize = nS; }
sal_uInt16 GetSize() const { return nSize; }
void SetFontName( const String& rName ) { aName = rName; }
String GetFontName() const { return aName; }
};
//----------------------
// class SbStdClipboard
//----------------------
class BASIC_DLLPUBLIC SbStdClipboard : public SbxObject
{
protected:
~SbStdClipboard();
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
void MethClear( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethGetData( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethGetFormat( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethGetText( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethSetData( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethSetText( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
public:
TYPEINFO();
SbStdClipboard();
virtual SbxVariable* Find( const rtl::OUString&, SbxClassType );
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Bin useless includes<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _SBSTDOBJ1_HXX
#define _SBSTDOBJ1_HXX
#include <basic/sbxobj.hxx>
#include <vcl/graph.hxx>
#include <basic/sbxfac.hxx>
#include "basicdllapi.h"
//--------------------
// class SbStdFactory
//--------------------
class BASIC_DLLPUBLIC SbStdFactory : public SbxFactory
{
public:
SbStdFactory();
virtual SbxObject* CreateObject( const rtl::OUString& rClassName );
};
//--------------------
// class SbStdPicture
//--------------------
class BASIC_DLLPUBLIC SbStdPicture : public SbxObject
{
protected:
Graphic aGraphic;
~SbStdPicture();
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
void PropType( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropWidth( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropHeight( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
public:
TYPEINFO();
SbStdPicture();
virtual SbxVariable* Find( const rtl::OUString&, SbxClassType );
Graphic GetGraphic() const { return aGraphic; }
void SetGraphic( const Graphic& rGrf ) { aGraphic = rGrf; }
};
//-----------------
// class SbStdFont
//-----------------
class BASIC_DLLPUBLIC SbStdFont : public SbxObject
{
protected:
sal_Bool bBold;
sal_Bool bItalic;
sal_Bool bStrikeThrough;
sal_Bool bUnderline;
sal_uInt16 nSize;
String aName;
~SbStdFont();
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
void PropBold( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropItalic( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropStrikeThrough( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropUnderline( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropSize( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
void PropName( SbxVariable* pVar, SbxArray* pPar, sal_Bool bWrite );
public:
TYPEINFO();
SbStdFont();
virtual SbxVariable* Find( const rtl::OUString&, SbxClassType );
void SetBold( sal_Bool bB ) { bBold = bB; }
sal_Bool IsBold() const { return bBold; }
void SetItalic( sal_Bool bI ) { bItalic = bI; }
sal_Bool IsItalic() const { return bItalic; }
void SetStrikeThrough( sal_Bool bS ) { bStrikeThrough = bS; }
sal_Bool IsStrikeThrough() const { return bStrikeThrough; }
void SetUnderline( sal_Bool bU ) { bUnderline = bU; }
sal_Bool IsUnderline() const { return bUnderline; }
void SetSize( sal_uInt16 nS ) { nSize = nS; }
sal_uInt16 GetSize() const { return nSize; }
void SetFontName( const String& rName ) { aName = rName; }
String GetFontName() const { return aName; }
};
//----------------------
// class SbStdClipboard
//----------------------
class BASIC_DLLPUBLIC SbStdClipboard : public SbxObject
{
protected:
~SbStdClipboard();
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
void MethClear( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethGetData( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethGetFormat( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethGetText( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethSetData( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
void MethSetText( SbxVariable* pVar, SbxArray* pPar_, sal_Bool bWrite );
public:
TYPEINFO();
SbStdClipboard();
virtual SbxVariable* Find( const rtl::OUString&, SbxClassType );
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BASIC_TTSTRHLP_HXX
#define _BASIC_TTSTRHLP_HXX
#include <tools/string.hxx>
#define CByteString( constAsciiStr ) ByteString( RTL_CONSTASCII_STRINGPARAM ( constAsciiStr ) )
#define CUniString( constAsciiStr ) UniString( RTL_CONSTASCII_USTRINGPARAM ( constAsciiStr ) )
#define StartKenn CUniString("%")
#define EndKenn CUniString("%")
#define UIdKenn ( StartKenn.AppendAscii("UId") )
#define MethodKenn ( StartKenn.AppendAscii("Method") )
#define TypeKenn ( StartKenn.AppendAscii("RType") )
#define SlotKenn ( StartKenn.AppendAscii("SlotId") )
#define RcKenn ( StartKenn.AppendAscii("RCommand") )
#define TabKenn ( StartKenn.AppendAscii("Tab") )
#define MakeStringParam(Type,aText) ( Type.AppendAscii("=").Append( aText ).Append( EndKenn ) )
#define MakeStringNumber(Type,nNumber) MakeStringParam (Type, UniString::CreateFromInt32(nNumber))
#define UIdString(aID) MakeStringParam(UIdKenn,aID.GetText())
#define MethodString(nNumber) MakeStringNumber(MethodKenn,nNumber)
#define TypeString(nNumber) MakeStringNumber(TypeKenn,nNumber)
#define SlotString(nNumber) MakeStringNumber(SlotKenn,nNumber)
#define RcString(nNumber) MakeStringNumber(RcKenn,nNumber)
#define TabString(nNumber) MakeStringNumber(TabKenn,nNumber)
#define ResKenn ( StartKenn.AppendAscii("ResId") )
#define BaseArgKenn ( StartKenn.AppendAscii("Arg") )
#define ArgKenn(nNumber) ( BaseArgKenn.Append( UniString::CreateFromInt32(nNumber) ) )
#define ResString(nNumber) MakeStringNumber(ResKenn,nNumber)
#define ArgString(nNumber, aText) MakeStringParam(ArgKenn(nNumber),aText)
UniString GEN_RES_STR0( ULONG nResId );
UniString GEN_RES_STR1( ULONG nResId, const String &Text1 );
UniString GEN_RES_STR2( ULONG nResId, const String &Text1, const String &Text2 );
UniString GEN_RES_STR3( ULONG nResId, const String &Text1, const String &Text2, const String &Text3 );
#define GEN_RES_STR1c( nResId, Text1 ) GEN_RES_STR1( nResId, CUniString(Text1) )
#define GEN_RES_STR2c2( nResId, Text1, Text2 ) GEN_RES_STR2( nResId, Text1, CUniString(Text2) )
#define GEN_RES_STR3c3( nResId, Text1, Text2, Text3 ) GEN_RES_STR3( nResId, Text1, Text2, CUniString(Text3) )
#define IMPL_GEN_RES_STR \
UniString GEN_RES_STR0( ULONG nResId ) { return ResString( nResId ); } \
UniString GEN_RES_STR1( ULONG nResId, const UniString &Text1 ) { return GEN_RES_STR0( nResId ).Append( ArgString( 1, Text1 ) ); } \
UniString GEN_RES_STR2( ULONG nResId, const UniString &Text1, const UniString &Text2 ) { return GEN_RES_STR1( nResId, Text1 ).Append( ArgString( 2, Text2 ) ); } \
UniString GEN_RES_STR3( ULONG nResId, const UniString &Text1, const UniString &Text2, const UniString &Text3 ) { return GEN_RES_STR2( nResId, Text1, Text2 ).Append( ArgString( 3, Text3 ) );}
#endif
<commit_msg>testtool: fix libsts to work with old testtool<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BASIC_TTSTRHLP_HXX
#define _BASIC_TTSTRHLP_HXX
#include <tools/string.hxx>
#define CByteString( constAsciiStr ) ByteString( RTL_CONSTASCII_STRINGPARAM ( constAsciiStr ) )
#define CUniString( constAsciiStr ) UniString( RTL_CONSTASCII_USTRINGPARAM ( constAsciiStr ) )
#define Str2Id( Str ) rtl::OUStringToOString( Str, RTL_TEXTENCODING_ASCII_US )
#define Id2Str( Id ) String( rtl::OStringToOUString( Id, RTL_TEXTENCODING_ASCII_US ) )
#define StartKenn CUniString("%")
#define EndKenn CUniString("%")
#define UIdKenn ( StartKenn.AppendAscii("UId") )
#define MethodKenn ( StartKenn.AppendAscii("Method") )
#define TypeKenn ( StartKenn.AppendAscii("RType") )
#define SlotKenn ( StartKenn.AppendAscii("SlotId") )
#define RcKenn ( StartKenn.AppendAscii("RCommand") )
#define TabKenn ( StartKenn.AppendAscii("Tab") )
#define MakeStringParam(Type,aText) ( Type.AppendAscii("=").Append( aText ).Append( EndKenn ) )
#define MakeStringNumber(Type,nNumber) MakeStringParam (Type, UniString::CreateFromInt32(nNumber))
#define UIdString(aID) MakeStringParam(UIdKenn,String(rtl::OStringToOUString( aID, RTL_TEXTENCODING_ASCII_US )))
#define MethodString(nNumber) MakeStringNumber(MethodKenn,nNumber)
#define TypeString(nNumber) MakeStringNumber(TypeKenn,nNumber)
#define SlotString(nNumber) MakeStringNumber(SlotKenn,nNumber)
#define RcString(nNumber) MakeStringNumber(RcKenn,nNumber)
#define TabString(nNumber) MakeStringNumber(TabKenn,nNumber)
#define ResKenn ( StartKenn.AppendAscii("ResId") )
#define BaseArgKenn ( StartKenn.AppendAscii("Arg") )
#define ArgKenn(nNumber) ( BaseArgKenn.Append( UniString::CreateFromInt32(nNumber) ) )
#define ResString(nNumber) MakeStringNumber(ResKenn,nNumber)
#define ArgString(nNumber, aText) MakeStringParam(ArgKenn(nNumber),aText)
UniString GEN_RES_STR0( ULONG nResId );
UniString GEN_RES_STR1( ULONG nResId, const String &Text1 );
UniString GEN_RES_STR2( ULONG nResId, const String &Text1, const String &Text2 );
UniString GEN_RES_STR3( ULONG nResId, const String &Text1, const String &Text2, const String &Text3 );
#define GEN_RES_STR1c( nResId, Text1 ) GEN_RES_STR1( nResId, CUniString(Text1) )
#define GEN_RES_STR2c2( nResId, Text1, Text2 ) GEN_RES_STR2( nResId, Text1, CUniString(Text2) )
#define GEN_RES_STR3c3( nResId, Text1, Text2, Text3 ) GEN_RES_STR3( nResId, Text1, Text2, CUniString(Text3) )
#define IMPL_GEN_RES_STR \
UniString GEN_RES_STR0( ULONG nResId ) { return ResString( nResId ); } \
UniString GEN_RES_STR1( ULONG nResId, const UniString &Text1 ) { return GEN_RES_STR0( nResId ).Append( ArgString( 1, Text1 ) ); } \
UniString GEN_RES_STR2( ULONG nResId, const UniString &Text1, const UniString &Text2 ) { return GEN_RES_STR1( nResId, Text1 ).Append( ArgString( 2, Text2 ) ); } \
UniString GEN_RES_STR3( ULONG nResId, const UniString &Text1, const UniString &Text2, const UniString &Text3 ) { return GEN_RES_STR2( nResId, Text1, Text2 ).Append( ArgString( 3, Text3 ) );}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: process.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hro $ $Date: 2001-05-10 15:59:46 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef WNT
#include <tools/prewin.h>
#include "winbase.h"
#include <tools/postwin.h>
#endif
#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _SBXCORE_HXX
#include <svtools/sbxcore.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _BASIC_TTRESHLP_HXX
#include "ttstrhlp.hxx"
#endif
//#ifndef _BYTE_STRING_LIST
//DECLARE_LIST( ByteStringList, ByteString * );
//#define _BYTE_STRING_LIST
//#endif
#include "process.hxx"
// Konstruktor fr den Process
Process::Process()
: bWasGPF( FALSE )
, pArgumentList( NULL )
, pProcess( NULL )
, bHasBeenStarted( FALSE )
{
}
// Destruktor
Process::~Process()
{
delete pArgumentList;
delete pProcess;
}
BOOL Process::ImplIsRunning()
{
if ( pProcess && bHasBeenStarted )
{
NAMESPACE_VOS(OProcess::TProcessInfo) aProcessInfo;
pProcess->getInfo( NAMESPACE_VOS(OProcess::TData_ExitCode), &aProcessInfo );
if ( !(aProcessInfo.Fields & NAMESPACE_VOS(OProcess::TData_ExitCode)) )
return TRUE;
else
return FALSE;
}
else
return FALSE;
}
long Process::ImplGetExitCode()
{
if ( pProcess )
{
NAMESPACE_VOS(OProcess::TProcessInfo) aProcessInfo;
pProcess->getInfo( NAMESPACE_VOS(OProcess::TData_ExitCode), &aProcessInfo );
if ( !(aProcessInfo.Fields & NAMESPACE_VOS(OProcess::TData_ExitCode)) )
SbxBase::SetError( SbxERR_NO_ACTIVE_OBJECT );
return aProcessInfo.Code;
}
else
SbxBase::SetError( SbxERR_NO_ACTIVE_OBJECT );
return 0;
}
////////////////////////////////////////////////////////////////////////////
// Die Methoden:
void Process::SetImage( const String &aAppPath, const String &aAppParams )
{ // Imagedatei des Executables
if ( pProcess && ImplIsRunning() )
SbxBase::SetError( SbxERR_NO_ACTIVE_OBJECT );
else
{
delete pArgumentList;
delete pProcess;
xub_StrLen i, nCount = aAppParams.GetQuotedTokenCount( CUniString("\"\"" ), ' ' );
::rtl::OUString *pParamList = new ::rtl::OUString[nCount];
for ( i = 0 ; i < nCount ; i++ )
{
::rtl::OUString aTemp = ::rtl::OUString(aAppParams.GetQuotedToken( i, CUniString("\"\"" ), ' ' ));
if ( aTemp.getLength() )
pParamList[i] = aTemp;
}
pArgumentList = new NAMESPACE_VOS(OArgumentList)( pParamList, nCount );
::rtl::OUString aNormalizedAppPath;
#ifdef TF_FILEURL
osl::FileBase::getFileURLFromSystemPath( ::rtl::OUString(aAppPath), aNormalizedAppPath );
#else
osl::FileBase::normalizePath( ::rtl::OUString(aAppPath), aNormalizedAppPath );
#endif
pProcess = new NAMESPACE_VOS(OProcess)( aNormalizedAppPath );
bHasBeenStarted = FALSE;
}
}
BOOL Process::Start()
{ // Programm wird gestartet
BOOL bSuccess=FALSE;
if ( pProcess && !ImplIsRunning() )
{
bWasGPF = FALSE;
#ifdef WNT
// sal_uInt32 nErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_NOALIGNMENTFAULTEXCEPT | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
sal_uInt32 nErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX);
try
{
#endif
bSuccess = pProcess->execute( (NAMESPACE_VOS(OProcess)::TProcessOption)
( NAMESPACE_VOS(OProcess)::TOption_SearchPath
/*| NAMESPACE_VOS(OProcess)::TOption_Detached*/
/*| NAMESPACE_VOS(OProcess)::TOption_Wait*/ ),
*pArgumentList ) == NAMESPACE_VOS(OProcess)::E_None;
#ifdef WNT
}
catch( ... )
{
bWasGPF = TRUE;
}
nErrorMode = SetErrorMode(nErrorMode);
#endif
bHasBeenStarted = bSuccess;
}
else
SbxBase::SetError( SbxERR_NO_ACTIVE_OBJECT );
return bSuccess;
}
ULONG Process::GetExitCode()
{ // ExitCode des Programms(nachdem es beendet ist)
return ImplGetExitCode();
}
BOOL Process::IsRunning()
{ // Programm luft noch
return ImplIsRunning();
}
BOOL Process::WasGPF()
{ // Programm mit GPF o.. abgebrochen
#ifdef WNT
return ImplGetExitCode() == 3221225477;
#else
return bWasGPF;
#endif
}
<commit_msg>#90267#<commit_after>/*************************************************************************
*
* $RCSfile: process.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: gh $ $Date: 2001-07-30 12:14:09 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef WNT
#include <tools/prewin.h>
#include "winbase.h"
#include <tools/postwin.h>
#endif
#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _SBXCORE_HXX
#include <svtools/sbxcore.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _BASIC_TTRESHLP_HXX
#include "ttstrhlp.hxx"
#endif
//#ifndef _BYTE_STRING_LIST
//DECLARE_LIST( ByteStringList, ByteString * );
//#define _BYTE_STRING_LIST
//#endif
#include "process.hxx"
// Konstruktor fr den Process
Process::Process()
: bWasGPF( FALSE )
, pArgumentList( NULL )
, pProcess( NULL )
, bHasBeenStarted( FALSE )
{
}
// Destruktor
Process::~Process()
{
delete pArgumentList;
delete pProcess;
}
BOOL Process::ImplIsRunning()
{
if ( pProcess && bHasBeenStarted )
{
NAMESPACE_VOS(OProcess::TProcessInfo) aProcessInfo;
pProcess->getInfo( NAMESPACE_VOS(OProcess::TData_ExitCode), &aProcessInfo );
if ( !(aProcessInfo.Fields & NAMESPACE_VOS(OProcess::TData_ExitCode)) )
return TRUE;
else
return FALSE;
}
else
return FALSE;
}
long Process::ImplGetExitCode()
{
if ( pProcess )
{
NAMESPACE_VOS(OProcess::TProcessInfo) aProcessInfo;
pProcess->getInfo( NAMESPACE_VOS(OProcess::TData_ExitCode), &aProcessInfo );
if ( !(aProcessInfo.Fields & NAMESPACE_VOS(OProcess::TData_ExitCode)) )
SbxBase::SetError( SbxERR_NO_ACTIVE_OBJECT );
return aProcessInfo.Code;
}
else
SbxBase::SetError( SbxERR_NO_ACTIVE_OBJECT );
return 0;
}
////////////////////////////////////////////////////////////////////////////
// Die Methoden:
void Process::SetImage( const String &aAppPath, const String &aAppParams )
{ // Imagedatei des Executables
if ( pProcess && ImplIsRunning() )
SbxBase::SetError( SbxERR_NO_ACTIVE_OBJECT );
else
{
delete pArgumentList;
delete pProcess;
xub_StrLen i, nCount = aAppParams.GetQuotedTokenCount( CUniString("\"\"" ), ' ' );
::rtl::OUString *pParamList = new ::rtl::OUString[nCount];
for ( i = 0 ; i < nCount ; i++ )
{
::rtl::OUString aTemp = ::rtl::OUString(aAppParams.GetQuotedToken( i, CUniString("\"\"" ), ' ' ));
if ( aTemp.getLength() )
pParamList[i] = aTemp;
}
pArgumentList = new NAMESPACE_VOS(OArgumentList)( pParamList, nCount );
::rtl::OUString aNormalizedAppPath;
osl::FileBase::getFileURLFromSystemPath( ::rtl::OUString(aAppPath), aNormalizedAppPath );
pProcess = new NAMESPACE_VOS(OProcess)( aNormalizedAppPath );
bHasBeenStarted = FALSE;
}
}
BOOL Process::Start()
{ // Programm wird gestartet
BOOL bSuccess=FALSE;
if ( pProcess && !ImplIsRunning() )
{
bWasGPF = FALSE;
#ifdef WNT
// sal_uInt32 nErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_NOALIGNMENTFAULTEXCEPT | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
sal_uInt32 nErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX);
try
{
#endif
bSuccess = pProcess->execute( (NAMESPACE_VOS(OProcess)::TProcessOption)
( NAMESPACE_VOS(OProcess)::TOption_SearchPath
/*| NAMESPACE_VOS(OProcess)::TOption_Detached*/
/*| NAMESPACE_VOS(OProcess)::TOption_Wait*/ ),
*pArgumentList ) == NAMESPACE_VOS(OProcess)::E_None;
#ifdef WNT
}
catch( ... )
{
bWasGPF = TRUE;
}
nErrorMode = SetErrorMode(nErrorMode);
#endif
bHasBeenStarted = bSuccess;
}
else
SbxBase::SetError( SbxERR_NO_ACTIVE_OBJECT );
return bSuccess;
}
ULONG Process::GetExitCode()
{ // ExitCode des Programms(nachdem es beendet ist)
return ImplGetExitCode();
}
BOOL Process::IsRunning()
{ // Programm luft noch
return ImplIsRunning();
}
BOOL Process::WasGPF()
{ // Programm mit GPF o.. abgebrochen
#ifdef WNT
return ImplGetExitCode() == 3221225477;
#else
return bWasGPF;
#endif
}
<|endoftext|>
|
<commit_before>#ifndef selection_hh_INCLUDED
#define selection_hh_INCLUDED
#include "buffer.hh"
namespace Kakoune
{
using CaptureList = Vector<String, MemoryDomain::Selections>;
// A selection is a Selection, associated with a CaptureList
struct Selection
{
static constexpr MemoryDomain Domain = MemoryDomain::Selections;
Selection() = default;
Selection(BufferCoord pos) : Selection(pos,pos) {}
Selection(BufferCoord anchor, BufferCoord cursor,
CaptureList captures = {})
: m_anchor{anchor}, m_cursor{cursor},
m_captures(std::move(captures)) {}
void merge_with(const Selection& range);
BufferCoord& anchor() { return m_anchor; }
BufferCoordAndTarget& cursor() { return m_cursor; }
const BufferCoord& anchor() const { return m_anchor; }
const BufferCoordAndTarget& cursor() const { return m_cursor; }
CaptureList& captures() { return m_captures; }
const CaptureList& captures() const { return m_captures; }
bool operator== (const Selection& other) const
{
return m_anchor == other.m_anchor and m_cursor == other.m_cursor;
}
const BufferCoord& min() const { return m_anchor < m_cursor ? m_anchor : m_cursor; }
const BufferCoord& max() const { return m_anchor < m_cursor ? m_cursor : m_anchor; }
BufferCoord& min() { return m_anchor < m_cursor ? m_anchor : m_cursor; }
BufferCoord& max() { return m_anchor < m_cursor ? m_cursor : m_anchor; }
private:
BufferCoord m_anchor;
BufferCoordAndTarget m_cursor;
CaptureList m_captures;
};
inline bool overlaps(const Selection& lhs, const Selection& rhs)
{
return lhs.min() <= rhs.min() ? lhs.max() >= rhs.min()
: lhs.min() <= rhs.max();
}
void update_selections(Vector<Selection>& selections, size_t& main,
Buffer& buffer, size_t timestamp);
enum class InsertMode : unsigned
{
Insert,
InsertCursor,
Append,
Replace,
InsertAtLineBegin,
InsertAtNextLineBegin,
AppendAtLineEnd,
OpenLineBelow,
OpenLineAbove
};
struct SelectionList
{
static constexpr MemoryDomain Domain = MemoryDomain::Selections;
SelectionList(Buffer& buffer, Selection s);
SelectionList(Buffer& buffer, Selection s, size_t timestamp);
SelectionList(Buffer& buffer, Vector<Selection> s);
SelectionList(Buffer& buffer, Vector<Selection> s, size_t timestamp);
void update();
void check_invariant() const;
const Selection& main() const { return (*this)[m_main]; }
Selection& main() { return (*this)[m_main]; }
size_t main_index() const { return m_main; }
void set_main_index(size_t main) { kak_assert(main < size()); m_main = main; }
void rotate_main(int count) { m_main = (m_main + count) % size(); }
void avoid_eol();
void push_back(const Selection& sel) { m_selections.push_back(sel); }
void push_back(Selection&& sel) { m_selections.push_back(std::move(sel)); }
Selection& operator[](size_t i) { return m_selections[i]; }
const Selection& operator[](size_t i) const { return m_selections[i]; }
SelectionList& operator=(Vector<Selection> list)
{
set(std::move(list), list.size()-1);
return *this;
}
void set(Vector<Selection> list, size_t main)
{
kak_assert(main < list.size());
m_selections = std::move(list);
m_main = main;
sort_and_merge_overlapping();
update_timestamp();
check_invariant();
}
using iterator = Vector<Selection>::iterator;
iterator begin() { return m_selections.begin(); }
iterator end() { return m_selections.end(); }
using const_iterator = Vector<Selection>::const_iterator;
const_iterator begin() const { return m_selections.begin(); }
const_iterator end() const { return m_selections.end(); }
void remove(size_t index) { m_selections.erase(begin() + index); }
size_t size() const { return m_selections.size(); }
bool operator==(const SelectionList& other) const { return m_buffer == other.m_buffer and m_selections == other.m_selections; }
bool operator!=(const SelectionList& other) const { return not ((*this) == other); }
void sort();
void merge_overlapping();
void merge_consecutive();
void sort_and_merge_overlapping();
Buffer& buffer() const { return *m_buffer; }
size_t timestamp() const { return m_timestamp; }
void update_timestamp() { m_timestamp = m_buffer->timestamp(); }
void insert(ConstArrayView<String> strings, InsertMode mode,
Vector<BufferCoord>* out_insert_pos = nullptr);
void erase();
private:
size_t m_main = 0;
Vector<Selection> m_selections;
SafePtr<Buffer> m_buffer;
size_t m_timestamp;
};
Vector<Selection> compute_modified_ranges(Buffer& buffer, size_t timestamp);
String selection_to_string(const Selection& selection);
String selection_list_to_string(const SelectionList& selection);
Selection selection_from_string(StringView desc);
SelectionList selection_list_from_string(Buffer& buffer, StringView desc);
}
#endif // selection_hh_INCLUDED
<commit_msg>Fix bug relying on undefined arg evaluation order.<commit_after>#ifndef selection_hh_INCLUDED
#define selection_hh_INCLUDED
#include "buffer.hh"
namespace Kakoune
{
using CaptureList = Vector<String, MemoryDomain::Selections>;
// A selection is a Selection, associated with a CaptureList
struct Selection
{
static constexpr MemoryDomain Domain = MemoryDomain::Selections;
Selection() = default;
Selection(BufferCoord pos) : Selection(pos,pos) {}
Selection(BufferCoord anchor, BufferCoord cursor,
CaptureList captures = {})
: m_anchor{anchor}, m_cursor{cursor},
m_captures(std::move(captures)) {}
void merge_with(const Selection& range);
BufferCoord& anchor() { return m_anchor; }
BufferCoordAndTarget& cursor() { return m_cursor; }
const BufferCoord& anchor() const { return m_anchor; }
const BufferCoordAndTarget& cursor() const { return m_cursor; }
CaptureList& captures() { return m_captures; }
const CaptureList& captures() const { return m_captures; }
bool operator== (const Selection& other) const
{
return m_anchor == other.m_anchor and m_cursor == other.m_cursor;
}
const BufferCoord& min() const { return m_anchor < m_cursor ? m_anchor : m_cursor; }
const BufferCoord& max() const { return m_anchor < m_cursor ? m_cursor : m_anchor; }
BufferCoord& min() { return m_anchor < m_cursor ? m_anchor : m_cursor; }
BufferCoord& max() { return m_anchor < m_cursor ? m_cursor : m_anchor; }
private:
BufferCoord m_anchor;
BufferCoordAndTarget m_cursor;
CaptureList m_captures;
};
inline bool overlaps(const Selection& lhs, const Selection& rhs)
{
return lhs.min() <= rhs.min() ? lhs.max() >= rhs.min()
: lhs.min() <= rhs.max();
}
void update_selections(Vector<Selection>& selections, size_t& main,
Buffer& buffer, size_t timestamp);
enum class InsertMode : unsigned
{
Insert,
InsertCursor,
Append,
Replace,
InsertAtLineBegin,
InsertAtNextLineBegin,
AppendAtLineEnd,
OpenLineBelow,
OpenLineAbove
};
struct SelectionList
{
static constexpr MemoryDomain Domain = MemoryDomain::Selections;
SelectionList(Buffer& buffer, Selection s);
SelectionList(Buffer& buffer, Selection s, size_t timestamp);
SelectionList(Buffer& buffer, Vector<Selection> s);
SelectionList(Buffer& buffer, Vector<Selection> s, size_t timestamp);
void update();
void check_invariant() const;
const Selection& main() const { return (*this)[m_main]; }
Selection& main() { return (*this)[m_main]; }
size_t main_index() const { return m_main; }
void set_main_index(size_t main) { kak_assert(main < size()); m_main = main; }
void rotate_main(int count) { m_main = (m_main + count) % size(); }
void avoid_eol();
void push_back(const Selection& sel) { m_selections.push_back(sel); }
void push_back(Selection&& sel) { m_selections.push_back(std::move(sel)); }
Selection& operator[](size_t i) { return m_selections[i]; }
const Selection& operator[](size_t i) const { return m_selections[i]; }
SelectionList& operator=(Vector<Selection> list)
{
const size_t main_index = list.size()-1;
set(std::move(list), main_index);
return *this;
}
void set(Vector<Selection> list, size_t main)
{
kak_assert(main < list.size());
m_selections = std::move(list);
m_main = main;
sort_and_merge_overlapping();
update_timestamp();
check_invariant();
}
using iterator = Vector<Selection>::iterator;
iterator begin() { return m_selections.begin(); }
iterator end() { return m_selections.end(); }
using const_iterator = Vector<Selection>::const_iterator;
const_iterator begin() const { return m_selections.begin(); }
const_iterator end() const { return m_selections.end(); }
void remove(size_t index) { m_selections.erase(begin() + index); }
size_t size() const { return m_selections.size(); }
bool operator==(const SelectionList& other) const { return m_buffer == other.m_buffer and m_selections == other.m_selections; }
bool operator!=(const SelectionList& other) const { return not ((*this) == other); }
void sort();
void merge_overlapping();
void merge_consecutive();
void sort_and_merge_overlapping();
Buffer& buffer() const { return *m_buffer; }
size_t timestamp() const { return m_timestamp; }
void update_timestamp() { m_timestamp = m_buffer->timestamp(); }
void insert(ConstArrayView<String> strings, InsertMode mode,
Vector<BufferCoord>* out_insert_pos = nullptr);
void erase();
private:
size_t m_main = 0;
Vector<Selection> m_selections;
SafePtr<Buffer> m_buffer;
size_t m_timestamp;
};
Vector<Selection> compute_modified_ranges(Buffer& buffer, size_t timestamp);
String selection_to_string(const Selection& selection);
String selection_list_to_string(const SelectionList& selection);
Selection selection_from_string(StringView desc);
SelectionList selection_list_from_string(Buffer& buffer, StringView desc);
}
#endif // selection_hh_INCLUDED
<|endoftext|>
|
<commit_before>#ifndef _SDD_DD_NARY_HH_
#define _SDD_DD_NARY_HH_
#include <algorithm> // copy, equal
#include <cassert>
#include <initializer_list>
#include <iosfwd>
#include <boost/container/flat_set.hpp>
#include "sdd/dd/context_fwd.hh"
#include "sdd/dd/definition.hh"
#include "sdd/dd/top.hh"
namespace sdd { namespace dd {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Check that all operands are compatible and determine the nodes' type (hierarchical
/// or flat).
template<typename C>
struct check_visitor
{
typedef node_tag result_type;
node_tag
operator()( const flat_node<C>& lhs, const flat_node<C>& rhs
, const SDD<C>& sdd_lhs, const SDD<C>& sdd_rhs)
const
{
if (not (lhs.variable() == rhs.variable()))
{
throw top<C>(sdd_lhs, sdd_rhs);
}
return node_tag::flat;
}
node_tag
operator()( const hierarchical_node<C>& lhs, const hierarchical_node<C>& rhs
, const SDD<C>& sdd_lhs, const SDD<C>& sdd_rhs)
const
{
if (not (lhs.variable() == rhs.variable()))
{
throw top<C>(sdd_lhs, sdd_rhs);
}
return node_tag::hierarchical;
}
node_tag
operator()(const one_terminal<C>&, const one_terminal<C>&, const SDD<C>&, const SDD<C>&)
const noexcept
{
assert(false && "More than one |1| in operands.");
__builtin_unreachable();
}
template <typename T, typename U>
__attribute__((noreturn))
node_tag
operator()(const T&, const U&, const SDD<C>& sdd_lhs, const SDD<C>& sdd_rhs)
const
{
throw top<C>(sdd_lhs, sdd_rhs);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Base class for sum and intersection operations, used by the cache.
///
/// It manages the allocation and deallocation of operands, as well as the dispatch on the
/// correct type (flat or hierarchical node). Use CRTP.
/// As it's an internally used structure, we don't bother with private and public sections.
template <typename C, typename Operation>
struct LIBSDD_ATTRIBUTE_PACKED nary_base
{
// Can't copy a nary_base.
nary_base(const nary_base&) = delete;
nary_base& operator=(const nary_base&) = delete;
/// Used by the cache to know the type of the result.
typedef SDD<C> result_type;
/// To iterate on operands.
typedef const SDD<C>* const_iterator;
/// The dynamically allocated array of operands.
char* operands;
/// The number of operands.
const typename C::operands_size_type size;
template <typename Builder>
nary_base(Builder& builder)
: operands(new char[builder.size_to_allocate()])
, size(static_cast<typename C::operands_size_type>(builder.size()))
{
builder.consolidate(operands);
}
nary_base(nary_base&& other)
noexcept
: operands(other.operands)
, size(other.size)
{
other.operands = nullptr;
}
~nary_base()
{
if (operands != nullptr)
{
for (auto& operand : *this)
{
operand.~SDD<C>();
}
delete[] operands;
}
}
const_iterator
begin()
const noexcept
{
return reinterpret_cast<const SDD<C>*>(operands);
}
const_iterator
end()
const noexcept
{
return reinterpret_cast<const SDD<C>*>(operands) + size;
}
SDD<C>
operator()(context<C>& cxt)
const
{
// Check compatibility of operands, size is necessarily at least 2.
auto cit = begin();
auto last = end() - 1;
node_tag tag = node_tag::flat;
for (; cit != last; ++cit)
{
tag = apply_binary_visitor( check_visitor<C>()
, (*cit)->data(), (*(cit + 1))->data()
, *cit, *(cit + 1));
}
// Dispatch on the function that does the real work with the deduced type.
const Operation* impl = static_cast<const Operation*>(this);
if (tag == node_tag::flat)
{
return impl->template work<node_tag::flat>(cxt);
}
else
{
return impl->template work<node_tag::hierarchical>(cxt);
}
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Equality of two operations based on nary_base.
/// @related nary_base
template <typename C, typename Operation>
inline
bool
operator==(const nary_base<C, Operation>& lhs, const nary_base<C, Operation>& rhs)
noexcept
{
return lhs.size == rhs.size and std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
/// @internal
/// @related nary_base
template <typename C, typename Operation>
std::ostream&
operator<<(std::ostream& os, const nary_base<C, Operation>& x)
{
os << Operation::symbol() << " (";
std::copy(x.begin(), std::prev(x.end()), std::ostream_iterator<SDD<C>>(os, ", "));
return os << *std::prev(x.end()) << ")";
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Base type for builders of sum and intersection operations.
///
/// The goal of a this builder is ensure that operands are always stored in the same order
/// (to improve cache hits); and to know the exact number of operands in order to allocate the
/// smallest possible memory to store all of them (this allocation is performed in the
/// construction of operations in nary_base).
template <typename Valuation, typename Builder>
struct LIBSDD_ATTRIBUTE_PACKED nary_builder
{
typedef boost::container::flat_set<Valuation> set_type;
typedef typename set_type::const_iterator const_iterator;
/// @brief The policy to add new operands.
Builder builder_;
/// @brief Sorted container of operands.
set_type set_;
/// @brief Default constructor.
nary_builder()
: builder_()
, set_()
{
}
/// @brief Construction with a reserve request.
nary_builder(std::size_t size)
: builder_()
, set_()
{
set_.reserve(size);
}
/// @brief Construction from a list of operands.
nary_builder(std::initializer_list<Valuation> operands)
: nary_builder(operands.size())
{
for (const auto& op : operands)
{
add(op);
}
}
/// @brief Add a new operand.
void
add(Valuation&& operand)
{
builder_.add(set_, std::move(operand));
}
/// @brief Add a new operand.
void
add(const Valuation& operand)
{
builder_.add(set_, operand);
}
/// @brief Request for allocation of additional memory.
void
reserve(std::size_t size)
noexcept
{
set_.reserve(size);
}
const_iterator
begin()
const noexcept
{
return set_.begin();
}
const_iterator
end()
const noexcept
{
return set_.end();
}
/// @brief Tell if this build doesn't contain any node.
bool
empty()
const noexcept
{
return set_.empty();
}
std::size_t
size()
const noexcept
{
return set_.size();
}
/// @brief Compute the size needed to store all the operands contained by this builder.
std::size_t
size_to_allocate()
const noexcept
{
return set_.size() * sizeof(Valuation);
}
/// @brief Move operands of this builder to a given memory location.
/// @param addr shall point to an allocated memory location of the size returned by
/// size_to_allocate().
///
/// Once performed, all subsequent calls to this instance are invalid.
void
consolidate(void* addr)
noexcept
{
Valuation* base = reinterpret_cast<Valuation*>(addr);
std::size_t i = 0;
for (auto it = set_.begin(); it != set_.end(); ++it, ++i)
{
new (base + i) Valuation(std::move(*it));
}
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::dd
#endif // _SDD_DD_NARY_HH_
<commit_msg>Documentation.<commit_after>#ifndef _SDD_DD_NARY_HH_
#define _SDD_DD_NARY_HH_
#include <algorithm> // copy, equal
#include <cassert>
#include <initializer_list>
#include <iosfwd>
#include <boost/container/flat_set.hpp>
#include "sdd/dd/context_fwd.hh"
#include "sdd/dd/definition.hh"
#include "sdd/dd/top.hh"
namespace sdd { namespace dd {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Check that all operands are compatible and determine the nodes' type (hierarchical
/// or flat).
template<typename C>
struct check_visitor
{
typedef node_tag result_type;
node_tag
operator()( const flat_node<C>& lhs, const flat_node<C>& rhs
, const SDD<C>& sdd_lhs, const SDD<C>& sdd_rhs)
const
{
if (not (lhs.variable() == rhs.variable()))
{
throw top<C>(sdd_lhs, sdd_rhs);
}
return node_tag::flat;
}
node_tag
operator()( const hierarchical_node<C>& lhs, const hierarchical_node<C>& rhs
, const SDD<C>& sdd_lhs, const SDD<C>& sdd_rhs)
const
{
if (not (lhs.variable() == rhs.variable()))
{
throw top<C>(sdd_lhs, sdd_rhs);
}
return node_tag::hierarchical;
}
node_tag
operator()(const one_terminal<C>&, const one_terminal<C>&, const SDD<C>&, const SDD<C>&)
const noexcept
{
assert(false && "More than one |1| in operands.");
__builtin_unreachable();
}
template <typename T, typename U>
__attribute__((noreturn))
node_tag
operator()(const T&, const U&, const SDD<C>& sdd_lhs, const SDD<C>& sdd_rhs)
const
{
throw top<C>(sdd_lhs, sdd_rhs);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Base class for sum and intersection operations, used by the cache.
///
/// It manages the allocation and deallocation of operands, as well as the dispatch on the
/// correct type (flat or hierarchical node). Use CRTP.
/// As it's an internally used structure, we don't bother with private and public sections.
template <typename C, typename Operation>
struct LIBSDD_ATTRIBUTE_PACKED nary_base
{
// Can't copy a nary_base.
nary_base(const nary_base&) = delete;
nary_base& operator=(const nary_base&) = delete;
/// Used by the cache to know the type of the result.
typedef SDD<C> result_type;
/// To iterate on operands.
typedef const SDD<C>* const_iterator;
/// The dynamically allocated array of operands.
char* operands;
/// The number of operands.
const typename C::operands_size_type size;
template <typename Builder>
nary_base(Builder& builder)
: operands(new char[builder.size_to_allocate()])
, size(static_cast<typename C::operands_size_type>(builder.size()))
{
builder.consolidate(operands);
}
nary_base(nary_base&& other)
noexcept
: operands(other.operands)
, size(other.size)
{
other.operands = nullptr;
}
~nary_base()
{
if (operands != nullptr)
{
for (auto& operand : *this)
{
operand.~SDD<C>();
}
delete[] operands;
}
}
const_iterator
begin()
const noexcept
{
return reinterpret_cast<const SDD<C>*>(operands);
}
const_iterator
end()
const noexcept
{
return reinterpret_cast<const SDD<C>*>(operands) + size;
}
SDD<C>
operator()(context<C>& cxt)
const
{
// Check compatibility of operands, size is necessarily at least 2.
auto cit = begin();
auto last = end() - 1;
node_tag tag = node_tag::flat;
for (; cit != last; ++cit)
{
tag = apply_binary_visitor( check_visitor<C>()
, (*cit)->data(), (*(cit + 1))->data()
, *cit, *(cit + 1));
}
// Dispatch on the function that does the real work with the deduced type.
const Operation* impl = static_cast<const Operation*>(this);
if (tag == node_tag::flat)
{
return impl->template work<node_tag::flat>(cxt);
}
else
{
return impl->template work<node_tag::hierarchical>(cxt);
}
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Equality of two operations based on nary_base.
/// @related nary_base
template <typename C, typename Operation>
inline
bool
operator==(const nary_base<C, Operation>& lhs, const nary_base<C, Operation>& rhs)
noexcept
{
return lhs.size == rhs.size and std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
/// @internal
/// @related nary_base
template <typename C, typename Operation>
std::ostream&
operator<<(std::ostream& os, const nary_base<C, Operation>& x)
{
os << Operation::symbol() << " (";
std::copy(x.begin(), std::prev(x.end()), std::ostream_iterator<SDD<C>>(os, ", "));
return os << *std::prev(x.end()) << ")";
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Base type for builders of sum and intersection operations.
///
/// The goal of a this builder is ensure that operands are always stored in the same order
/// (to improve cache hits); and to know the exact number of operands in order to allocate the
/// smallest possible memory to store all of them (this allocation is performed in the
/// construction of operations in nary_base).
template <typename Valuation, typename Builder>
struct LIBSDD_ATTRIBUTE_PACKED nary_builder
{
typedef boost::container::flat_set<Valuation> set_type;
typedef typename set_type::const_iterator const_iterator;
/// @brief The policy to add new operands.
///
/// An instance is needed for builders with a state (intersection).
Builder builder_;
/// @brief Sorted container of operands.
set_type set_;
/// @brief Default constructor.
nary_builder()
: builder_()
, set_()
{
}
/// @brief Construction with a reserve request.
nary_builder(std::size_t size)
: builder_()
, set_()
{
set_.reserve(size);
}
/// @brief Construction from a list of operands.
nary_builder(std::initializer_list<Valuation> operands)
: nary_builder(operands.size())
{
for (const auto& op : operands)
{
add(op);
}
}
/// @brief Add a new operand.
void
add(Valuation&& operand)
{
builder_.add(set_, std::move(operand));
}
/// @brief Add a new operand.
void
add(const Valuation& operand)
{
builder_.add(set_, operand);
}
/// @brief Request for allocation of additional memory.
void
reserve(std::size_t size)
noexcept
{
set_.reserve(size);
}
const_iterator
begin()
const noexcept
{
return set_.begin();
}
const_iterator
end()
const noexcept
{
return set_.end();
}
/// @brief Tell if this build doesn't contain any node.
bool
empty()
const noexcept
{
return set_.empty();
}
std::size_t
size()
const noexcept
{
return set_.size();
}
/// @brief Compute the size needed to store all the operands contained by this builder.
std::size_t
size_to_allocate()
const noexcept
{
return set_.size() * sizeof(Valuation);
}
/// @brief Move operands of this builder to a given memory location.
/// @param addr shall point to an allocated memory location of the size returned by
/// size_to_allocate().
///
/// Once performed, all subsequent calls to this instance are invalid.
void
consolidate(void* addr)
noexcept
{
Valuation* base = reinterpret_cast<Valuation*>(addr);
std::size_t i = 0;
for (auto it = set_.begin(); it != set_.end(); ++it, ++i)
{
new (base + i) Valuation(std::move(*it));
}
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::dd
#endif // _SDD_DD_NARY_HH_
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <queue>
#include <utility>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <errno.h>
#include <unistd.h>
#include <assert.h>
#include "../vowpalwabbit/vw.h"
using namespace std;
int pairs = 0;
int users = 0;
int items = 0;
int recs = 0;
int skipped = 0;
int banned = 0;
int show = 1;
void progress()
{
fprintf(stderr, "%12d %8d %8d %8d %8d\n", pairs, users, items, recs, skipped);
}
void usage(char *prog) {
fprintf(stderr, "usage: %s [-b <2|4|8|...|32>] [-v] <blacklist> <users> <items> <topN> <vwparams>\n", prog);
exit(EXIT_FAILURE);
}
int b=16;
int topn=10;
int verbose=0;
char * blacklistfilename = NULL;
char * itemfilename = NULL;
char * userfilename = NULL;
char * vwparams = NULL;
unsigned hash_ber(char *in, size_t len) {
unsigned hashv = 0;
while (len--) hashv = ((hashv) * 33) + *in++;
return hashv;
}
unsigned hash_fnv(char *in, size_t len) {
unsigned hashv = 2166136261UL;
while(len--) hashv = (hashv * 16777619) ^ *in++;
return hashv;
}
#define MASK(u,b) ( u & ((1UL << b) - 1))
#define NUM_HASHES 2
void get_hashv(char *in, size_t len, unsigned *out) {
assert(NUM_HASHES==2);
out[0] = MASK(hash_ber(in,len),b);
out[1] = MASK(hash_fnv(in,len),b);
}
#define BIT_TEST(c,i) (c[i/8] & (1 << (i % 8)))
#define BIT_SET(c,i) (c[i/8] |= (1 << (i % 8)))
#define byte_len(b) (((1UL << b) / 8) + (((1UL << b) % 8) ? 1 : 0))
#define num_bits(b) (1UL << b)
char *bf_new(unsigned b) {
char *bf = (char*)calloc(1,byte_len(b));
return bf;
}
void bf_add(char *bf, char *line) {
unsigned i, hashv[NUM_HASHES];
get_hashv(line,strlen(line),hashv);
for(i=0;i<NUM_HASHES;i++) BIT_SET(bf,hashv[i]);
}
void bf_info(char *bf, FILE *f) {
unsigned i, on=0;
for(i=0; i<num_bits(b); i++)
if (BIT_TEST(bf,i)) on++;
fprintf(f, "%.2f%% saturation\n%lu bf bit size\n", on*100.0/num_bits(b), num_bits(b));
}
int bf_hit(char *bf, char *line) {
unsigned i, hashv[NUM_HASHES];
get_hashv(line,strlen(line),hashv);
for(i=0;i<NUM_HASHES;i++) {
if (BIT_TEST(bf,hashv[i])==0) return 0;
}
return 1;
}
typedef pair<float, string> scored_example;
vector<scored_example> scored_examples;
struct compare_scored_examples
{
bool operator()(scored_example const& a, scored_example const& b) const
{
return a.first > b.first;
}
};
priority_queue<scored_example, vector<scored_example>, compare_scored_examples > pr_queue;
int main(int argc, char *argv[])
{
int opt;
while ( (opt = getopt(argc, argv, "b:v+N:")) != -1) {
switch (opt) {
case 'N':
topn = atoi(optarg);
break;
case 'b':
b = atoi(optarg);
break;
case 'v':
verbose++;
break;
default:
usage(argv[0]);
break;
}
}
if (optind < argc) blacklistfilename=argv[optind++];
if (optind < argc) userfilename=argv[optind++];
if (optind < argc) itemfilename=argv[optind++];
if (optind < argc) vwparams=argv[optind++];
if (!blacklistfilename || !userfilename || !itemfilename || !vwparams) usage(argv[0]);
FILE * fB;
FILE * fU;
FILE * fI;
if((fB = fopen(blacklistfilename, "r")) == NULL)
{
fprintf(stderr,"can't open %s: %s\n", blacklistfilename, strerror(errno));
usage(argv[0]);
}
if((fU = fopen(userfilename, "r")) == NULL )
{
fprintf(stderr,"can't open %s: %s\n", userfilename, strerror(errno));
usage(argv[0]);
}
if((fI = fopen(itemfilename, "r")) == NULL )
{
fprintf(stderr,"can't open %s: %s\n", itemfilename, strerror(errno));
usage(argv[0]);
}
char * buf = NULL;
char * u = NULL;
char * i = NULL;
size_t len = 0;
ssize_t read;
/* make the bloom filter */
if(verbose>0)
fprintf(stderr, "loading blacklist into bloom filter...\n");
char *bf= bf_new(b);
/* loop over the source file */
while ((read = getline(&buf,&len,fB)) != -1)
{
bf_add(bf,buf);
banned++;
}
/* print saturation etc */
if (verbose)
{
bf_info(bf,stderr);
fprintf(stderr, "%d banned pairs\n", banned);
}
// INITIALIZE WITH WHATEVER YOU WOULD PUT ON THE VW COMMAND LINE
if(verbose>0)
fprintf(stderr, "initializing vw...\n");
vw* model = VW::initialize(vwparams);
char * estr = NULL;
if(verbose>0)
{
fprintf(stderr, "predicting...\n");
fprintf(stderr, "%12s %8s %8s %8s %8s\n", "pair", "user", "item", "rec", "skipped");
}
while ((read = getline(&u, &len, fU)) != -1)
{
users++;
u[strlen(u)-1] = 0; // chop
rewind(fI);
items=0;
while ((read = getline(&i, &len, fI)) != -1)
{
items++;
pairs++;
if((verbose > 0) & (pairs % show == 0))
{
progress();
show *= 2;
}
free(estr);
estr = strdup((string(u)+string(i)).c_str());
if (!bf_hit(bf,estr))
{
example *ex = VW::read_example(*model, estr);
model->learn(ex);
const string str(estr);
if(pr_queue.size() < topn)
{
pr_queue.push(make_pair(ex->final_prediction, str));
}
else if(pr_queue.top().first < ex->final_prediction)
{
pr_queue.pop();
pr_queue.push(make_pair(ex->final_prediction, str));
}
VW::finish_example(*model, ex);
}
else
{
skipped++;
if(verbose>=2)
fprintf(stderr,"skipping:|%s|\n", estr);
}
}
while(!pr_queue.empty())
{
cout << pr_queue.top().first << "\t" << pr_queue.top().second;
pr_queue.pop();
recs++;
}
}
if(verbose>0)
{
progress();
}
VW::finish(*model);
fclose(fI);
fclose(fU);
exit(EXIT_SUCCESS);
}
<commit_msg>use boost::program_options instead of getopt<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <queue>
#include <utility>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <errno.h>
#include <unistd.h>
#include <assert.h>
#include <boost/program_options.hpp>
#include "../vowpalwabbit/vw.h"
using namespace std;
namespace po = boost::program_options;
int pairs = 0;
int users = 0;
int items = 0;
int recs = 0;
int skipped = 0;
int banned = 0;
int show = 1;
int b=16;
int topk=10;
int verbose=0;
string blacklistfilename;
string itemfilename;
string userfilename;
string vwparams;
void progress()
{
fprintf(stderr, "%12d %8d %8d %8d %12d %s %s\n", pairs, users, items, recs, skipped, userfilename.c_str(), itemfilename.c_str());
}
unsigned hash_ber(char *in, size_t len) {
unsigned hashv = 0;
while (len--) hashv = ((hashv) * 33) + *in++;
return hashv;
}
unsigned hash_fnv(char *in, size_t len) {
unsigned hashv = 2166136261UL;
while(len--) hashv = (hashv * 16777619) ^ *in++;
return hashv;
}
#define MASK(u,b) ( u & ((1UL << b) - 1))
#define NUM_HASHES 2
void get_hashv(char *in, size_t len, unsigned *out) {
assert(NUM_HASHES==2);
out[0] = MASK(hash_ber(in,len),b);
out[1] = MASK(hash_fnv(in,len),b);
}
#define BIT_TEST(c,i) (c[i/8] & (1 << (i % 8)))
#define BIT_SET(c,i) (c[i/8] |= (1 << (i % 8)))
#define byte_len(b) (((1UL << b) / 8) + (((1UL << b) % 8) ? 1 : 0))
#define num_bits(b) (1UL << b)
char *bf_new(unsigned b) {
char *bf = (char*)calloc(1,byte_len(b));
return bf;
}
void bf_add(char *bf, char *line) {
unsigned i, hashv[NUM_HASHES];
get_hashv(line,strlen(line),hashv);
for(i=0;i<NUM_HASHES;i++) BIT_SET(bf,hashv[i]);
}
void bf_info(char *bf, FILE *f) {
unsigned i, on=0;
for(i=0; i<num_bits(b); i++)
if (BIT_TEST(bf,i)) on++;
fprintf(f, "%.2f%% saturation\n%lu bf bit size\n", on*100.0/num_bits(b), num_bits(b));
}
int bf_hit(char *bf, char *line) {
unsigned i, hashv[NUM_HASHES];
get_hashv(line,strlen(line),hashv);
for(i=0;i<NUM_HASHES;i++) {
if (BIT_TEST(bf,hashv[i])==0) return 0;
}
return 1;
}
typedef pair<float, string> scored_example;
vector<scored_example> scored_examples;
struct compare_scored_examples
{
bool operator()(scored_example const& a, scored_example const& b) const
{
return a.first > b.first;
}
};
priority_queue<scored_example, vector<scored_example>, compare_scored_examples > pr_queue;
int main(int argc, char *argv[])
{
try {
po::variables_map vm;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("topk", po::value<int>(&topk), "number of items to recommend per user")
("verbose,v", po::value<int>(&verbose), "increase verbosity (can be repeated)")
("bf_bits,b", po::value<int>(&b), "number of items to recommend")
("blacklist,B", po::value<string>(&blacklistfilename), "user item pairs (in vw format) that we should not recommend (have been seen before)")
("users,U", po::value<string>(&userfilename), "users portion in vw format to make recs for")
("items,I", po::value<string>(&itemfilename), "items (in vw format) to recommend from")
("vwparams", po::value<string>(&vwparams), "vw parameters for model instantiation (-i model ...)")
;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
if (blacklistfilename.empty() || userfilename.empty() || itemfilename.empty() || vwparams.empty())
{
cout << desc << "\n";
exit(2);
}
FILE * fB;
FILE * fU;
FILE * fI;
if((fB = fopen(blacklistfilename.c_str(), "r")) == NULL)
{
fprintf(stderr,"can't open %s: %s\n", blacklistfilename.c_str(), strerror(errno));
cerr << desc << endl;
exit(2);
}
if((fU = fopen(userfilename.c_str(), "r")) == NULL )
{
fprintf(stderr,"can't open %s: %s\n", userfilename.c_str(), strerror(errno));
cerr << desc << endl;
exit(2);
}
if((fI = fopen(itemfilename.c_str(), "r")) == NULL )
{
fprintf(stderr,"can't open %s: %s\n", itemfilename.c_str(), strerror(errno));
cerr << desc << endl;
exit(2);
}
char * buf = NULL;
char * u = NULL;
char * i = NULL;
size_t len = 0;
ssize_t read;
/* make the bloom filter */
if(verbose>0)
fprintf(stderr, "loading blacklist into bloom filter...\n");
char *bf= bf_new(b);
/* loop over the source file */
while ((read = getline(&buf,&len,fB)) != -1)
{
bf_add(bf,buf);
banned++;
}
/* print saturation etc */
if (verbose)
{
bf_info(bf,stderr);
fprintf(stderr, "%d banned pairs\n", banned);
}
// INITIALIZE WITH WHATEVER YOU WOULD PUT ON THE VW COMMAND LINE
if(verbose>0)
fprintf(stderr, "initializing vw...\n");
vw* model = VW::initialize(vwparams);
char * estr = NULL;
if(verbose>0)
{
fprintf(stderr, "predicting...\n");
fprintf(stderr, "%12s %8s %8s %8s %12s %s %s\n", "pair", "user", "item", "rec", "skipped", "userfile", "itemfile");
}
while ((read = getline(&u, &len, fU)) != -1)
{
users++;
u[strlen(u)-1] = 0; // chop
rewind(fI);
items=0;
while ((read = getline(&i, &len, fI)) != -1)
{
items++;
pairs++;
if((verbose > 0) & (pairs % show == 0))
{
progress();
show *= 2;
}
free(estr);
estr = strdup((string(u)+string(i)).c_str());
if (!bf_hit(bf,estr))
{
example *ex = VW::read_example(*model, estr);
model->learn(ex);
const string str(estr);
if(pr_queue.size() < topk)
{
pr_queue.push(make_pair(ex->final_prediction, str));
}
else if(pr_queue.top().first < ex->final_prediction)
{
pr_queue.pop();
pr_queue.push(make_pair(ex->final_prediction, str));
}
VW::finish_example(*model, ex);
}
else
{
skipped++;
if(verbose>=2)
fprintf(stderr,"skipping:#%s#\n", estr);
}
}
while(!pr_queue.empty())
{
cout << pr_queue.top().first << "\t" << pr_queue.top().second;
pr_queue.pop();
recs++;
}
}
if(verbose>0)
{
progress();
}
VW::finish(*model);
fclose(fI);
fclose(fU);
exit(EXIT_SUCCESS);
}
catch(exception & e)
{
cout << e.what();
return 0;
}
}
<|endoftext|>
|
<commit_before>#include "button.h"
#include "const.h"
#include "logger.h"
#include "bluetooth.h"
namespace button {
namespace {
//Stores the value of the button pressed or depressed
const uint8_t BUTTON_NONE = 65;
volatile uint8_t buttonPressed = BUTTON_NONE;
//Method to call when the the interrupt pin is falling
void isr() {
buttonPressed = 0;
for (int i = 0; i < 8; i++) {
//Wait for clock to go high
while (digitalRead(constants::P_BUTTON_CLOCK) == LOW);
//If value is high add one
buttonPressed = buttonPressed + digitalRead(constants::P_BUTTON_DATA);
//If not last time in loop, shift bits
if (i != 7) {
buttonPressed = buttonPressed << 1;
}
//Wait for clock to go low
while (digitalRead(constants::P_BUTTON_CLOCK) == HIGH);
}
buttonPressed -= 1;
if (buttonPressed > 64) {
buttonPressed -= 128;
bluetooth::sendPacket(bluetooth::C_BUTTON_PRESS + String(buttonPressed));
logger::log(logger::TYPE_INFO, "button", "Button pressed : " + String(buttonPressed));
}
}
}
//Checks whether the button got pressed
bool isPressed(uint8_t buttonToCheck) {
//If not button shield wait two seconds and return true
if (not constants::IS_BUTTON_SHIELD_CONNECTED) {
delay(2000);
return true;
}
//If button pressed is the button to check return true
if (buttonPressed == buttonToCheck) {
return true;
}
return false;
}
void clearLast() {
buttonPressed = BUTTON_NONE;
}
void setup() {
attachInterrupt(digitalPinToInterrupt(constants::P_BUTTON_INTERRUPT), isr, FALLING); //Attach interrupt for 64 button shield
}
}
<commit_msg>Fix bug where button is called twice - untested<commit_after>#include "button.h"
#include "const.h"
#include "logger.h"
#include "bluetooth.h"
namespace button {
namespace {
//Stores the value of the button pressed or depressed
const int8_t BUTTON_NONE = -1;
volatile int8_t buttonPressed = BUTTON_NONE;
//Method to call when the the interrupt pin is falling
void isr() {
uint8_t button = 0;
for (int i = 0; i < 8; i++) {
while (digitalRead(constants::P_BUTTON_CLOCK) == LOW); //Wait for clock to go high
buttonPressed = buttonPressed + digitalRead(constants::P_BUTTON_DATA); //If value is high add one
//If not last time in loop, shift bits
if (i != 7) {
buttonPressed = buttonPressed << 1;
}
while (digitalRead(constants::P_BUTTON_CLOCK) == HIGH); //Wait for clock to go low
}
if (button > 64) { // If button pressed
buttonPressed = button - 129 ;
bluetooth::sendPacket(bluetooth::C_BUTTON_PRESS + String(buttonPressed));
}
}
}
//Checks whether the button got pressed
bool isPressed(uint8_t buttonToCheck) {
//If not button shield wait two seconds and return true
if (not constants::IS_BUTTON_SHIELD_CONNECTED) {
delay(2000);
return true;
}
//If button pressed is the button to check return true
if (buttonPressed == buttonToCheck) {
return true;
}
return false;
}
void clearLast() {
buttonPressed = BUTTON_NONE;
}
void setup() {
attachInterrupt(digitalPinToInterrupt(constants::P_BUTTON_INTERRUPT), isr, FALLING); //Attach interrupt for 64 button shield
}
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("before read secretfile \n");
init_time_at(time,"# read Secret file",t);
Secret=read_Secretfile(F.Secretfile,F);
printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
print_time(time,"# ... took :");
std::vector<int> count;
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);}
//read the three input files
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
assign_priority_class(M);
//establish priority classes
init_time_at(time,"# establish priority clasess",t);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
print_time(time,"# ... took :");
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F); pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
printf(" future plates %d\n",P.size());
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,0);
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);
not_done=false;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates after screening %d \n",F.NUsedplate);
//if(F.diagnose)diagnostic(M,G,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<1; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(js,M,P,pp,F,A);
}
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
for(int i=0;i<F.pass_intervals.size();i++)printf(" i=%d interval %d \n",i,F.pass_intervals[i]);
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);//to end intervals at last plate
for(int i=0;i<update_intervals.size()-2;++i){//go plate by used plate
int starter=update_intervals[i];
printf(" before pass = %d at %d tiles \n",i,starter);
//display_results("doc/figs/",G,P,pp,F,A,true);
//plan whole survey from this point out
/*
for (int jj=starter; jj<F.NUsedplate; jj++) {
int js = A.suborder[jj];
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF
assign_unused(js,M,P,pp,F,A);
}
*/
//update target information for interval i
for (int jj=starter; jj<update_intervals[i+1]; jj++) {
printf(" jj %d \n",jj);
}
}
/*
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A); else printf("\n no update\n");
redistribute_tf(M,P,pp,F,A,starter);
improve(M,P,pp,F,A,starter);
redistribute_tf(M,P,pp,F,A,starter);
//}
if(F.diagnose)diagnostic(M,Secret,F,A);
// check on SS and SF
/*
for(int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf("\n js = %d\n",js);
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[js][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
printf(" %d %d ",count_SS,count_SF);
}
printf("\n");
}
}
*/
// Results -------------------------------------------------------
if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){
write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){
fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>diagnostic<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("before read secretfile \n");
init_time_at(time,"# read Secret file",t);
Secret=read_Secretfile(F.Secretfile,F);
printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
print_time(time,"# ... took :");
std::vector<int> count;
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);}
//read the three input files
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
assign_priority_class(M);
//establish priority classes
init_time_at(time,"# establish priority clasess",t);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
print_time(time,"# ... took :");
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F); pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
printf(" future plates %d\n",P.size());
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,0);
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);
not_done=false;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates after screening %d \n",F.NUsedplate);
//if(F.diagnose)diagnostic(M,G,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<1; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(js,M,P,pp,F,A);
}
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
for(int i=0;i<F.pass_intervals.size();i++)printf(" i=%d interval %d \n",i,F.pass_intervals[i]);
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);//to end intervals at last plate
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
int starter=update_intervals[i];
printf(" before pass = %d at %d tiles \n",i,starter);
//display_results("doc/figs/",G,P,pp,F,A,true);
//plan whole survey from this point out
/*
for (int jj=starter; jj<F.NUsedplate; jj++) {
int js = A.suborder[jj];
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF
assign_unused(js,M,P,pp,F,A);
}
*/
//update target information for interval i
for (int jj=starter; jj<update_intervals[i+1]; jj++) {
printf(" jj %d \n",jj);
}
}
/*
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A); else printf("\n no update\n");
redistribute_tf(M,P,pp,F,A,starter);
improve(M,P,pp,F,A,starter);
redistribute_tf(M,P,pp,F,A,starter);
//}
if(F.diagnose)diagnostic(M,Secret,F,A);
// check on SS and SF
/*
for(int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf("\n js = %d\n",js);
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[js][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
printf(" %d %d ",count_SS,count_SF);
}
printf("\n");
}
}
*/
// Results -------------------------------------------------------
if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){
write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){
fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2017-2020 The Bitcoin Core developers
// Copyright (c) 2020 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "fs.h"
#ifndef WIN32
#include <fcntl.h>
#else
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <codecvt>
#include <windows.h>
#endif
namespace fsbridge {
FILE *fopen(const fs::path& p, const char *mode)
{
#ifndef WIN32
return ::fopen(p.string().c_str(), mode);
#else
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> utf8_cvt;
return ::_wfopen(p.wstring().c_str(), utf8_cvt.from_bytes(mode).c_str());
#endif
}
#ifndef WIN32
static std::string GetErrorReason() {
return std::strerror(errno);
}
FileLock::FileLock(const fs::path& file)
{
fd = open(file.string().c_str(), O_RDWR);
if (fd == -1) {
reason = GetErrorReason();
}
}
FileLock::~FileLock()
{
if (fd != -1) {
close(fd);
}
}
bool FileLock::TryLock()
{
if (fd == -1) {
return false;
}
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) == -1) {
reason = GetErrorReason();
return false;
}
return true;
}
#else
static std::string GetErrorReason() {
wchar_t* err;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<WCHAR*>(&err), 0, nullptr);
std::wstring err_str(err);
LocalFree(err);
return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(err_str);
}
FileLock::FileLock(const fs::path& file)
{
hFile = CreateFileW(file.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
reason = GetErrorReason();
}
}
FileLock::~FileLock()
{
if (hFile != INVALID_HANDLE_VALUE) {
CloseHandle(hFile);
}
}
bool FileLock::TryLock()
{
if (hFile == INVALID_HANDLE_VALUE) {
return false;
}
_OVERLAPPED overlapped = {0};
if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, std::numeric_limits<DWORD>::max(), std::numeric_limits<DWORD>::max(), &overlapped)) {
reason = GetErrorReason();
return false;
}
return true;
}
#endif
std::string get_filesystem_error_message(const fs::filesystem_error& e)
{
#ifndef WIN32
return e.what();
#else
// Convert from Multi Byte to utf-16
std::string mb_string(e.what());
int size = MultiByteToWideChar(CP_ACP, 0, mb_string.c_str(), mb_string.size(), nullptr, 0);
std::wstring utf16_string(size, L'\0');
MultiByteToWideChar(CP_ACP, 0, mb_string.c_str(), mb_string.size(), &*utf16_string.begin(), size);
// Convert from utf-16 to utf-8
return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>().to_bytes(utf16_string);
#endif
}
#ifdef WIN32
#ifdef __GLIBCXX__
// reference: https://github.com/gcc-mirror/gcc/blob/gcc-7_3_0-release/libstdc%2B%2B-v3/include/std/fstream#L270
static std::string openmodeToStr(std::ios_base::openmode mode)
{
switch (mode & ~std::ios_base::ate) {
case std::ios_base::out:
case std::ios_base::out | std::ios_base::trunc:
return "w";
case std::ios_base::out | std::ios_base::app:
case std::ios_base::app:
return "a";
case std::ios_base::in:
return "r";
case std::ios_base::in | std::ios_base::out:
return "r+";
case std::ios_base::in | std::ios_base::out | std::ios_base::trunc:
return "w+";
case std::ios_base::in | std::ios_base::out | std::ios_base::app:
case std::ios_base::in | std::ios_base::app:
return "a+";
case std::ios_base::out | std::ios_base::binary:
case std::ios_base::out | std::ios_base::trunc | std::ios_base::binary:
return "wb";
case std::ios_base::out | std::ios_base::app | std::ios_base::binary:
case std::ios_base::app | std::ios_base::binary:
return "ab";
case std::ios_base::in | std::ios_base::binary:
return "rb";
case std::ios_base::in | std::ios_base::out | std::ios_base::binary:
return "r+b";
case std::ios_base::in | std::ios_base::out | std::ios_base::trunc | std::ios_base::binary:
return "w+b";
case std::ios_base::in | std::ios_base::out | std::ios_base::app | std::ios_base::binary:
case std::ios_base::in | std::ios_base::app | std::ios_base::binary:
return "a+b";
default:
return std::string();
}
}
void ifstream::open(const fs::path& p, std::ios_base::openmode mode)
{
close();
m_file = fsbridge::fopen(p, openmodeToStr(mode).c_str());
if (m_file == nullptr) {
return;
}
m_filebuf = __gnu_cxx::stdio_filebuf<char>(m_file, mode);
rdbuf(&m_filebuf);
if (mode & std::ios_base::ate) {
seekg(0, std::ios_base::end);
}
}
void ifstream::close()
{
if (m_file != nullptr) {
m_filebuf.close();
fclose(m_file);
}
m_file = nullptr;
}
void ofstream::open(const fs::path& p, std::ios_base::openmode mode)
{
close();
m_file = fsbridge::fopen(p, openmodeToStr(mode).c_str());
if (m_file == nullptr) {
return;
}
m_filebuf = __gnu_cxx::stdio_filebuf<char>(m_file, mode);
rdbuf(&m_filebuf);
if (mode & std::ios_base::ate) {
seekp(0, std::ios_base::end);
}
}
void ofstream::close()
{
if (m_file != nullptr) {
m_filebuf.close();
fclose(m_file);
}
m_file = nullptr;
}
#else // __GLIBCXX__
static_assert(sizeof(*fs::path().BOOST_FILESYSTEM_C_STR) == sizeof(wchar_t),
"Warning: This build is using boost::filesystem ofstream and ifstream "
"implementations which will fail to open paths containing multibyte "
"characters. You should delete this static_assert to ignore this warning, "
"or switch to a different C++ standard library like the Microsoft C++ "
"Standard Library (where boost uses non-standard extensions to construct "
"stream objects with wide filenames), or the GNU libstdc++ library (where "
"a more complicated workaround has been implemented above).");
#endif // __GLIBCXX__
#endif // WIN32
} // fsbridge
<commit_msg>Fix WSL file locking by using flock instead of fcntl<commit_after>// Copyright (c) 2017-2020 The Bitcoin Core developers
// Copyright (c) 2020 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "fs.h"
#ifndef WIN32
#include <fcntl.h>
#include <string>
#include <sys/file.h>
#include <sys/utsname.h>
#else
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <codecvt>
#include <windows.h>
#endif
namespace fsbridge {
FILE *fopen(const fs::path& p, const char *mode)
{
#ifndef WIN32
return ::fopen(p.string().c_str(), mode);
#else
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> utf8_cvt;
return ::_wfopen(p.wstring().c_str(), utf8_cvt.from_bytes(mode).c_str());
#endif
}
#ifndef WIN32
static std::string GetErrorReason() {
return std::strerror(errno);
}
FileLock::FileLock(const fs::path& file)
{
fd = open(file.string().c_str(), O_RDWR);
if (fd == -1) {
reason = GetErrorReason();
}
}
FileLock::~FileLock()
{
if (fd != -1) {
close(fd);
}
}
static bool IsWSL()
{
struct utsname uname_data;
return uname(&uname_data) == 0 && std::string(uname_data.version).find("Microsoft") != std::string::npos;
}
bool FileLock::TryLock()
{
if (fd == -1) {
return false;
}
// Exclusive file locking is broken on WSL using fcntl (issue #18622)
// This workaround can be removed once the bug on WSL is fixed
static const bool is_wsl = IsWSL();
if (is_wsl) {
if (flock(fd, LOCK_EX | LOCK_NB) == -1) {
reason = GetErrorReason();
return false;
}
} else {
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) == -1) {
reason = GetErrorReason();
return false;
}
}
return true;
}
#else
static std::string GetErrorReason() {
wchar_t* err;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<WCHAR*>(&err), 0, nullptr);
std::wstring err_str(err);
LocalFree(err);
return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(err_str);
}
FileLock::FileLock(const fs::path& file)
{
hFile = CreateFileW(file.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
reason = GetErrorReason();
}
}
FileLock::~FileLock()
{
if (hFile != INVALID_HANDLE_VALUE) {
CloseHandle(hFile);
}
}
bool FileLock::TryLock()
{
if (hFile == INVALID_HANDLE_VALUE) {
return false;
}
_OVERLAPPED overlapped = {0};
if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, std::numeric_limits<DWORD>::max(), std::numeric_limits<DWORD>::max(), &overlapped)) {
reason = GetErrorReason();
return false;
}
return true;
}
#endif
std::string get_filesystem_error_message(const fs::filesystem_error& e)
{
#ifndef WIN32
return e.what();
#else
// Convert from Multi Byte to utf-16
std::string mb_string(e.what());
int size = MultiByteToWideChar(CP_ACP, 0, mb_string.c_str(), mb_string.size(), nullptr, 0);
std::wstring utf16_string(size, L'\0');
MultiByteToWideChar(CP_ACP, 0, mb_string.c_str(), mb_string.size(), &*utf16_string.begin(), size);
// Convert from utf-16 to utf-8
return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>().to_bytes(utf16_string);
#endif
}
#ifdef WIN32
#ifdef __GLIBCXX__
// reference: https://github.com/gcc-mirror/gcc/blob/gcc-7_3_0-release/libstdc%2B%2B-v3/include/std/fstream#L270
static std::string openmodeToStr(std::ios_base::openmode mode)
{
switch (mode & ~std::ios_base::ate) {
case std::ios_base::out:
case std::ios_base::out | std::ios_base::trunc:
return "w";
case std::ios_base::out | std::ios_base::app:
case std::ios_base::app:
return "a";
case std::ios_base::in:
return "r";
case std::ios_base::in | std::ios_base::out:
return "r+";
case std::ios_base::in | std::ios_base::out | std::ios_base::trunc:
return "w+";
case std::ios_base::in | std::ios_base::out | std::ios_base::app:
case std::ios_base::in | std::ios_base::app:
return "a+";
case std::ios_base::out | std::ios_base::binary:
case std::ios_base::out | std::ios_base::trunc | std::ios_base::binary:
return "wb";
case std::ios_base::out | std::ios_base::app | std::ios_base::binary:
case std::ios_base::app | std::ios_base::binary:
return "ab";
case std::ios_base::in | std::ios_base::binary:
return "rb";
case std::ios_base::in | std::ios_base::out | std::ios_base::binary:
return "r+b";
case std::ios_base::in | std::ios_base::out | std::ios_base::trunc | std::ios_base::binary:
return "w+b";
case std::ios_base::in | std::ios_base::out | std::ios_base::app | std::ios_base::binary:
case std::ios_base::in | std::ios_base::app | std::ios_base::binary:
return "a+b";
default:
return std::string();
}
}
void ifstream::open(const fs::path& p, std::ios_base::openmode mode)
{
close();
m_file = fsbridge::fopen(p, openmodeToStr(mode).c_str());
if (m_file == nullptr) {
return;
}
m_filebuf = __gnu_cxx::stdio_filebuf<char>(m_file, mode);
rdbuf(&m_filebuf);
if (mode & std::ios_base::ate) {
seekg(0, std::ios_base::end);
}
}
void ifstream::close()
{
if (m_file != nullptr) {
m_filebuf.close();
fclose(m_file);
}
m_file = nullptr;
}
void ofstream::open(const fs::path& p, std::ios_base::openmode mode)
{
close();
m_file = fsbridge::fopen(p, openmodeToStr(mode).c_str());
if (m_file == nullptr) {
return;
}
m_filebuf = __gnu_cxx::stdio_filebuf<char>(m_file, mode);
rdbuf(&m_filebuf);
if (mode & std::ios_base::ate) {
seekp(0, std::ios_base::end);
}
}
void ofstream::close()
{
if (m_file != nullptr) {
m_filebuf.close();
fclose(m_file);
}
m_file = nullptr;
}
#else // __GLIBCXX__
static_assert(sizeof(*fs::path().BOOST_FILESYSTEM_C_STR) == sizeof(wchar_t),
"Warning: This build is using boost::filesystem ofstream and ifstream "
"implementations which will fail to open paths containing multibyte "
"characters. You should delete this static_assert to ignore this warning, "
"or switch to a different C++ standard library like the Microsoft C++ "
"Standard Library (where boost uses non-standard extensions to construct "
"stream objects with wide filenames), or the GNU libstdc++ library (where "
"a more complicated workaround has been implemented above).");
#endif // __GLIBCXX__
#endif // WIN32
} // fsbridge
<|endoftext|>
|
<commit_before>//@ {"targets":[{"name":"serializer.hpp","type":"include"}]}
#ifndef TEMPLE_SERIALIZER_HPP
#define TEMPLE_SERIALIZER_HPP
#include "item.hpp"
#include "treenode.hpp"
#include <stack>
namespace Temple
{
namespace
{
template<class Callback>
class VisitorBase
{
public:
virtual bool atEnd() const noexcept=0;
virtual void advance() noexcept=0;
virtual void itemProcess(Callback& cb) const=0;
virtual ~VisitorBase()=default;
char terminator() const noexcept
{return m_terminator;}
size_t size() const noexcept
{return m_size;}
protected:
explicit VisitorBase(char term,size_t size) noexcept:
m_terminator(term),m_size(size)
{}
private:
char m_terminator;
size_t m_size;
};
template<class Callback,class Container>
class Visitor:public VisitorBase<Callback>
{
public:
explicit Visitor(Container&&)=delete;
explicit Visitor(const Container& container,char term):
VisitorBase<Callback>(term,container.size())
,m_begin(container.begin())
,m_current(container.begin())
,m_end(container.end())
{}
bool atEnd() const noexcept
{return m_current==m_end;}
bool atBegin() const noexcept
{return m_current==m_begin;}
void advance() noexcept
{++m_current;}
void itemProcess(Callback& cb) const
{cb(*m_current,*this);}
static auto create(const Container& cnt,char term)
{return std::unique_ptr<VisitorBase<Callback>>(new Visitor(cnt,term));}
private:
typename Container::const_iterator m_begin;
typename Container::const_iterator m_current;
typename Container::const_iterator m_end;
};
template<class Sink>
void indent(size_t level,Sink& sink)
{
assert(level!=0);
--level;
while(level!=0)
{
putc('\t',sink);
--level;
}
}
template<class CharType,class Sink>
void write(const CharType* src,Sink& sink)
{
while(true)
{
auto ch_in=*src;
if(ch_in=='\0')
{return;}
if(ch_in=='\\' || ch_in=='\"')
{putc('\\',sink);}
putc(ch_in,sink);
++src;
}
}
template<class StorageModel,class Sink>
void write(const typename StorageModel::StringType& string,Sink& sink)
{
putc('"',sink);
write(string.c_str(),sink);
putc('"',sink);
}
template<class StorageModel,class T,class Sink,std::enable_if_t<std::is_arithmetic<T>::value,int> a=0>
void write(T x,Sink& sink)
{write(convert<std::string>(x).c_str(),sink);}
template<class StorageModel,class T,class Sink>
void write(const typename StorageModel::template ArrayType<T>& array,Sink& sink)
{
putc('[',sink);
auto ptr=array.begin();
auto ptr_end=array.end();
if(ptr!=ptr_end)
{
write<StorageModel>(*ptr,sink);
++ptr;
}
while(ptr!=ptr_end)
{
putc(',',sink);
write<StorageModel>(*ptr,sink);
++ptr;
}
putc(']',sink);
}
template<class StorageModel,class Sink>
class Acceptor
{
public:
using MapType=typename StorageModel::template MapType< std::unique_ptr< ItemBase<StorageModel> > > ;
using CompoundArray=typename StorageModel::template ArrayType<MapType>;
using VisitorArray=Visitor<Acceptor,CompoundArray>;
using VisitorMap=Visitor<Acceptor,MapType>;
explicit Acceptor(ItemBase<StorageModel>&&)=delete;
explicit Acceptor(const ItemBase<StorageModel>& root,Sink& sink):r_sink(sink)
{
if(root.array())
{m_stack.push(VisitorArray::create(root.template value<CompoundArray>(),']') );}
else
{m_stack.push(VisitorMap::create(root.template value<MapType>(),'}'));}
}
void run()
{
while(!m_stack.empty())
{
auto& visitor=m_stack.top();
if(visitor->atEnd())
{
if(visitor->size()>1
|| (visitor->terminator()==']' && visitor->size()!=0))
{indent(m_stack.size(),r_sink);}
putc(visitor->terminator(),r_sink);
putc('\n',r_sink);
m_stack.pop();
}
else
{
visitor->itemProcess(*this);
visitor->advance();
}
}
}
void operator()(const MapType& node_current,const VisitorArray& visitor)
{
indent(m_stack.size(),r_sink);
putc(visitor.atBegin()?'[':',',r_sink);
putc('\n',r_sink);
m_stack.push(VisitorMap::create(node_current,'}'));
}
void operator()(const typename MapType::value_type& node_current,const VisitorMap& visitor)
{
indent(m_stack.size(),r_sink);
if(visitor.size()==1)
{putc('{',r_sink);}
else
{
fputs(visitor.atBegin()?"{\n":",",r_sink);
if(visitor.atBegin())
{
indent(m_stack.size(),r_sink);
putc(' ',r_sink);
}
}
putc('"',r_sink);
write(node_current.first.c_str(),r_sink);
auto type_current=node_current.second->type();
fprintf(r_sink,"\",%s:",type(type_current));
if(type_current==Type::COMPOUND)
{
auto node=VisitorMap::create(node_current.second->template value<MapType>(),'}');
putc('\n',r_sink);
if(node->atEnd())
{
indent(m_stack.size()+1,r_sink);
putc('{',r_sink);
}
m_stack.push(std::move(node));
}
else
if(type_current==Type::COMPOUND_ARRAY)
{
auto node=VisitorArray::create(node_current.second->template value<CompoundArray>(),']');
putc('\n',r_sink);
if(node->atEnd())
{
indent(m_stack.size()+1,r_sink);
putc('[',r_sink);
}
m_stack.push(std::move(node));
}
else
{
for_type<StorageModel,Type::I8,1,Type::STRING_ARRAY>(type_current,[&node_current,this,&visitor](auto tag)
{
using TypeCurrent=typename decltype(tag)::type;
auto& object=node_current.second->template value<TypeCurrent>();
write<StorageModel>(object,this->r_sink);
if(visitor.size()!=1)
{putc('\n',this->r_sink);}
});
}
}
private:
Sink& r_sink;
std::stack< std::unique_ptr< VisitorBase<Acceptor> > > m_stack;
};
}
template<class StorageModel,class Sink>
void temple_store(const ItemBase<StorageModel>& root,Sink& sink)
{
Locale loc;
Acceptor<StorageModel,Sink>(root,sink).run();
}
}
#endif
<commit_msg>whitespace after comma when writing arrays<commit_after>//@ {"targets":[{"name":"serializer.hpp","type":"include"}]}
#ifndef TEMPLE_SERIALIZER_HPP
#define TEMPLE_SERIALIZER_HPP
#include "item.hpp"
#include "treenode.hpp"
#include <stack>
namespace Temple
{
namespace
{
template<class Callback>
class VisitorBase
{
public:
virtual bool atEnd() const noexcept=0;
virtual void advance() noexcept=0;
virtual void itemProcess(Callback& cb) const=0;
virtual ~VisitorBase()=default;
char terminator() const noexcept
{return m_terminator;}
size_t size() const noexcept
{return m_size;}
protected:
explicit VisitorBase(char term,size_t size) noexcept:
m_terminator(term),m_size(size)
{}
private:
char m_terminator;
size_t m_size;
};
template<class Callback,class Container>
class Visitor:public VisitorBase<Callback>
{
public:
explicit Visitor(Container&&)=delete;
explicit Visitor(const Container& container,char term):
VisitorBase<Callback>(term,container.size())
,m_begin(container.begin())
,m_current(container.begin())
,m_end(container.end())
{}
bool atEnd() const noexcept
{return m_current==m_end;}
bool atBegin() const noexcept
{return m_current==m_begin;}
void advance() noexcept
{++m_current;}
void itemProcess(Callback& cb) const
{cb(*m_current,*this);}
static auto create(const Container& cnt,char term)
{return std::unique_ptr<VisitorBase<Callback>>(new Visitor(cnt,term));}
private:
typename Container::const_iterator m_begin;
typename Container::const_iterator m_current;
typename Container::const_iterator m_end;
};
template<class Sink>
void indent(size_t level,Sink& sink)
{
assert(level!=0);
--level;
while(level!=0)
{
putc('\t',sink);
--level;
}
}
template<class CharType,class Sink>
void write(const CharType* src,Sink& sink)
{
while(true)
{
auto ch_in=*src;
if(ch_in=='\0')
{return;}
if(ch_in=='\\' || ch_in=='\"')
{putc('\\',sink);}
putc(ch_in,sink);
++src;
}
}
template<class StorageModel,class Sink>
void write(const typename StorageModel::StringType& string,Sink& sink)
{
putc('"',sink);
write(string.c_str(),sink);
putc('"',sink);
}
template<class StorageModel,class T,class Sink,std::enable_if_t<std::is_arithmetic<T>::value,int> a=0>
void write(T x,Sink& sink)
{write(convert<std::string>(x).c_str(),sink);}
template<class StorageModel,class T,class Sink>
void write(const typename StorageModel::template ArrayType<T>& array,Sink& sink)
{
putc('[',sink);
auto ptr=array.begin();
auto ptr_end=array.end();
if(ptr!=ptr_end)
{
write<StorageModel>(*ptr,sink);
++ptr;
}
while(ptr!=ptr_end)
{
fputs(", ",sink);
write<StorageModel>(*ptr,sink);
++ptr;
}
putc(']',sink);
}
template<class StorageModel,class Sink>
class Acceptor
{
public:
using MapType=typename StorageModel::template MapType< std::unique_ptr< ItemBase<StorageModel> > > ;
using CompoundArray=typename StorageModel::template ArrayType<MapType>;
using VisitorArray=Visitor<Acceptor,CompoundArray>;
using VisitorMap=Visitor<Acceptor,MapType>;
explicit Acceptor(ItemBase<StorageModel>&&)=delete;
explicit Acceptor(const ItemBase<StorageModel>& root,Sink& sink):r_sink(sink)
{
if(root.array())
{m_stack.push(VisitorArray::create(root.template value<CompoundArray>(),']') );}
else
{m_stack.push(VisitorMap::create(root.template value<MapType>(),'}'));}
}
void run()
{
while(!m_stack.empty())
{
auto& visitor=m_stack.top();
if(visitor->atEnd())
{
if(visitor->size()>1
|| (visitor->terminator()==']' && visitor->size()!=0))
{indent(m_stack.size(),r_sink);}
putc(visitor->terminator(),r_sink);
putc('\n',r_sink);
m_stack.pop();
}
else
{
visitor->itemProcess(*this);
visitor->advance();
}
}
}
void operator()(const MapType& node_current,const VisitorArray& visitor)
{
indent(m_stack.size(),r_sink);
putc(visitor.atBegin()?'[':',',r_sink);
putc('\n',r_sink);
m_stack.push(VisitorMap::create(node_current,'}'));
}
void operator()(const typename MapType::value_type& node_current,const VisitorMap& visitor)
{
indent(m_stack.size(),r_sink);
if(visitor.size()==1)
{putc('{',r_sink);}
else
{
fputs(visitor.atBegin()?"{\n":",",r_sink);
if(visitor.atBegin())
{
indent(m_stack.size(),r_sink);
putc(' ',r_sink);
}
}
putc('"',r_sink);
write(node_current.first.c_str(),r_sink);
auto type_current=node_current.second->type();
fprintf(r_sink,"\",%s:",type(type_current));
if(type_current==Type::COMPOUND)
{
auto node=VisitorMap::create(node_current.second->template value<MapType>(),'}');
putc('\n',r_sink);
if(node->atEnd())
{
indent(m_stack.size()+1,r_sink);
putc('{',r_sink);
}
m_stack.push(std::move(node));
}
else
if(type_current==Type::COMPOUND_ARRAY)
{
auto node=VisitorArray::create(node_current.second->template value<CompoundArray>(),']');
putc('\n',r_sink);
if(node->atEnd())
{
indent(m_stack.size()+1,r_sink);
putc('[',r_sink);
}
m_stack.push(std::move(node));
}
else
{
for_type<StorageModel,Type::I8,1,Type::STRING_ARRAY>(type_current,[&node_current,this,&visitor](auto tag)
{
using TypeCurrent=typename decltype(tag)::type;
auto& object=node_current.second->template value<TypeCurrent>();
write<StorageModel>(object,this->r_sink);
if(visitor.size()!=1)
{putc('\n',this->r_sink);}
});
}
}
private:
Sink& r_sink;
std::stack< std::unique_ptr< VisitorBase<Acceptor> > > m_stack;
};
}
template<class StorageModel,class Sink>
void temple_store(const ItemBase<StorageModel>& root,Sink& sink)
{
Locale loc;
Acceptor<StorageModel,Sink>(root,sink).run();
}
}
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
vector<string> fileParam;
// Loops through arguments looking for flags/files/directories
for(int i = 1; i < argc; ++i)
{
// Is a flag if first char of c-string is '-'
if(argv[i][0] == '-')
{
// Accounts for flags like -laR, -lR, etc.
for(int j = 1; argv[i][j] != '\n'; ++j)
{
if(argv[i][j] == 'a')
{
aFlag = true;
}
else if(argv[i][j] == 'l')
{
lFlag = true;
}
else if(argv[i][j] == 'R')
{
RFlag = true;
}
else
{
// If flag is neither 'l', 'a', nor 'R'
cerr << "Error: Invalid flag" << endl;
exit(1);
}
}
}
else
{
// Adds directories/files to vector
fileParam.push_back(argv[i]);
}
}
if(fileParam.size() == 0)
{
fileParam.push_back("."); // Current directory, if no others specified
}
return 0;
}
<commit_msg>Updated ls<commit_after>#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
vector<string> fileParam;
// Loops through arguments looking for flags/files/directories
for(int i = 1; i < argc; ++i)
{
// Is a flag if first char of c-string is '-'
if(argv[i][0] == '-')
{
// Accounts for flags like -laR, -lR, etc.
for(int j = 1; argv[i][j] != '\n'; ++j)
{
if(argv[i][j] == 'a')
{
aFlag = true;
}
else if(argv[i][j] == 'l')
{
lFlag = true;
}
else if(argv[i][j] == 'R')
{
RFlag = true;
}
else
{
// If flag is neither 'l', 'a', nor 'R'
cerr << "Error: Invalid flag" << endl;
exit(1);
}
}
}
else
{
// Adds directories/files to vector
fileParam.push_back(argv[i]);
}
}
if(fileParam.size() == 0)
{
fileParam.push_back("."); // Current directory, if no others specified
}
for(auto str : fileParam)
{
DIR* dirp;
if(-1 == (dirp = opendir(str.c_str())))
{
perror("Error in opening directory");
exit(1);
}
}
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>WaE: overriding virtual function declaration not marked 'override'<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include <vector>
#include <memory>
#include "acmacs-base/throw.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/timeit.hh"
#include "acmacs-chart-2/chart.hh"
#include "acmacs-draw/viewport.hh"
#include "acmacs-map-draw/point-style-draw.hh"
#include "acmacs-map-draw/map-elements.hh"
#include "acmacs-map-draw/labels.hh"
class Surface;
// ----------------------------------------------------------------------
class DrawingOrder : public std::vector<size_t>
{
public:
DrawingOrder(acmacs::chart::Chart& aChart);
inline DrawingOrder& operator=(const std::vector<size_t>& aSource) { std::vector<size_t>::operator=(aSource); return *this; }
void raise(size_t aPointNo);
void lower(size_t aPointNo);
}; // class DrawingOrder
// ----------------------------------------------------------------------
class ChartDraw
{
public:
ChartDraw(acmacs::chart::Chart& aChart, size_t aProjectionNo);
void prepare();
void draw(Surface& aSurface) const;
void draw(std::string aFilename, double aSize, report_time aTimer = report_time::No) const;
const acmacs::Viewport& calculate_viewport(bool verbose = true);
inline const std::vector<PointStyleDraw>& point_styles() const { return mPointStyles; }
inline std::vector<acmacs::PointStyle> point_styles_base() const { std::vector<acmacs::PointStyle> ps{mPointStyles.begin(), mPointStyles.end()}; return ps; }
inline auto& chart() { return mChart; }
inline const auto& chart() const { return mChart; }
inline auto projection_no() const { return mProjectionNo; }
inline std::shared_ptr<acmacs::chart::Layout> layout() const { return chart().projection(projection_no())->layout(); }
// inline auto& layout() { return chart().projection(projection_no()).layout(); }
// for "found_in_previous" and "not_found_in_previous" select keys
inline void previous_chart(acmacs::chart::Chart& aPreviousChart) { mPreviousChart = &aPreviousChart; }
inline const auto& previous_chart() const { return mPreviousChart; }
template <typename index_type> inline void modify(index_type aIndex, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
const auto index = static_cast<size_t>(aIndex);
mPointStyles.at(index) = aStyle;
switch (aPointDrawingOrder) {
case PointDrawingOrder::Raise:
drawing_order().raise(index);
break;
case PointDrawingOrder::Lower:
drawing_order().lower(index);
break;
case PointDrawingOrder::NoChange:
break;
}
}
template <typename index_type> inline void modify_serum(index_type aSerumNo, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
modify(static_cast<size_t>(aSerumNo) + number_of_antigens(), aStyle, aPointDrawingOrder);
}
template <typename IndexIterator> inline void modify(IndexIterator first, IndexIterator last, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
for (; first != last; ++first)
modify(*first, aStyle, aPointDrawingOrder);
}
inline void modify(const acmacs::chart::Indexes& aIndexes, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
for (auto index: aIndexes)
modify(index, aStyle, aPointDrawingOrder);
}
template <typename IndexIterator> inline void modify_sera(IndexIterator first, IndexIterator last, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
for (; first != last; ++first)
modify_serum(*first, aStyle, aPointDrawingOrder);
}
inline void modify_sera(const acmacs::chart::Indexes& aIndexes, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
for (auto index: aIndexes)
modify_serum(index, aStyle, aPointDrawingOrder);
}
void hide_all_except(const std::vector<size_t>& aNotHide);
void mark_egg_antigens();
void mark_reassortant_antigens();
void mark_all_grey(Color aColor);
void scale_points(double aPointScale, double aOulineScale);
void modify_all_sera(const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange);
inline void rotate(double aAngle)
{
if (!float_zero(aAngle))
log("rotate radians:", aAngle, " degrees:", 180.0 * aAngle / M_PI, " ", aAngle > 0 ? "counter-" : "", "clockwise");
mTransformation.rotate(aAngle);
}
inline void flip(double aX, double aY)
{
// std::cout << "INFO: flip " << aX << " " << aY << std::endl;
log("flip ", aX, " ", aY);
mTransformation.flip(aX, aY); // reflect about a line specified with vector [aX, aY]
}
inline const acmacs::Transformation& transformation() const { return mTransformation; }
inline void viewport(double aX, double aY, double aSize) { mViewport.set(aX, aY, aSize); }
inline void viewport(const acmacs::Viewport& aViewport) { mViewport = aViewport; }
inline const acmacs::Viewport& viewport() const { return mViewport; }
DrawingOrder& drawing_order() { return mDrawingOrder; }
inline void background_color(Color aBackgroud) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).background_color(aBackgroud); }
inline void grid(Color aGridColor, double aGridLineWidth) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).grid(aGridColor, aGridLineWidth); }
inline void border(Color aBorderColor, double aBorderWidth) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).border(aBorderColor, aBorderWidth); }
inline void continent_map(const acmacs::Location& aOffset, Pixels aWidth) { DYNAMIC_CAST(map_elements::ContinentMap&, (mMapElements["continent-map"])).offset_width(aOffset, aWidth); }
inline map_elements::LegendPointLabel& legend(const acmacs::Location& aOffset) { auto& legend = DYNAMIC_CAST(map_elements::LegendPointLabel&, (mMapElements["legend-point-label"])); legend.offset(aOffset); return legend; }
inline map_elements::LegendPointLabel& legend() { return DYNAMIC_CAST(map_elements::LegendPointLabel&, (mMapElements["legend-point-label"])); }
inline void remove_legend() { mMapElements.remove("legend-point-label"); }
inline map_elements::Title& title(const acmacs::Location& aOffset) { auto& title = DYNAMIC_CAST(map_elements::Title&, (mMapElements["title"])); title.offset(aOffset); return title; }
inline map_elements::Title& title() { return DYNAMIC_CAST(map_elements::Title&, (mMapElements["title"])); }
inline map_elements::Labels& labels() { return mLabels; }
inline map_elements::Label& add_label(size_t aIndex) { return mLabels.add(aIndex, mChart); }
inline void remove_label(size_t aIndex) { return mLabels.remove(aIndex); }
map_elements::SerumCircle& serum_circle(size_t aSerumNo, Scaled aRadius);
map_elements::Line& line(const acmacs::Location& aBegin, const acmacs::Location& aEnd);
map_elements::Arrow& arrow(const acmacs::Location& aBegin, const acmacs::Location& aEnd);
map_elements::Point& point(const acmacs::Location& aCenter, Pixels aSize);
map_elements::Rectangle& rectangle(const acmacs::Location& aCorner1, const acmacs::Location& aCorner2);
map_elements::Circle& circle(const acmacs::Location& aCenter, Scaled aSize);
void remove_serum_circles();
inline const acmacs::chart::Layout& transformed_layout() const
{
if (!mTransformedLayout) {
mTransformedLayout = std::unique_ptr<acmacs::chart::Layout>(mChart.projection(mProjectionNo)->layout()->transform(mTransformation));
}
return *mTransformedLayout;
}
size_t number_of_antigens() const;
size_t number_of_sera() const;
inline size_t number_of_points() const { return number_of_antigens() + number_of_sera(); }
void save(std::string aFilename, std::string aProgramName);
private:
acmacs::chart::Chart& mChart;
acmacs::chart::Chart* mPreviousChart = nullptr;
size_t mProjectionNo;
acmacs::Viewport mViewport;
acmacs::Transformation mTransformation;
std::vector<PointStyleDraw> mPointStyles;
DrawingOrder mDrawingOrder;
map_elements::Elements mMapElements;
map_elements::Labels mLabels;
mutable std::unique_ptr<acmacs::chart::Layout> mTransformedLayout;
}; // class ChartDraw
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>reset transformed layout on rotation/flipping<commit_after>#pragma once
#include <string>
#include <vector>
#include <memory>
#include "acmacs-base/throw.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/timeit.hh"
#include "acmacs-chart-2/chart.hh"
#include "acmacs-draw/viewport.hh"
#include "acmacs-map-draw/point-style-draw.hh"
#include "acmacs-map-draw/map-elements.hh"
#include "acmacs-map-draw/labels.hh"
class Surface;
// ----------------------------------------------------------------------
class DrawingOrder : public std::vector<size_t>
{
public:
DrawingOrder(acmacs::chart::Chart& aChart);
inline DrawingOrder& operator=(const std::vector<size_t>& aSource) { std::vector<size_t>::operator=(aSource); return *this; }
void raise(size_t aPointNo);
void lower(size_t aPointNo);
}; // class DrawingOrder
// ----------------------------------------------------------------------
class ChartDraw
{
public:
ChartDraw(acmacs::chart::Chart& aChart, size_t aProjectionNo);
void prepare();
void draw(Surface& aSurface) const;
void draw(std::string aFilename, double aSize, report_time aTimer = report_time::No) const;
const acmacs::Viewport& calculate_viewport(bool verbose = true);
inline const std::vector<PointStyleDraw>& point_styles() const { return mPointStyles; }
inline std::vector<acmacs::PointStyle> point_styles_base() const { std::vector<acmacs::PointStyle> ps{mPointStyles.begin(), mPointStyles.end()}; return ps; }
inline auto& chart() { return mChart; }
inline const auto& chart() const { return mChart; }
inline auto projection_no() const { return mProjectionNo; }
inline std::shared_ptr<acmacs::chart::Layout> layout() const { return chart().projection(projection_no())->layout(); }
// inline auto& layout() { return chart().projection(projection_no()).layout(); }
// for "found_in_previous" and "not_found_in_previous" select keys
inline void previous_chart(acmacs::chart::Chart& aPreviousChart) { mPreviousChart = &aPreviousChart; }
inline const auto& previous_chart() const { return mPreviousChart; }
template <typename index_type> inline void modify(index_type aIndex, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
const auto index = static_cast<size_t>(aIndex);
mPointStyles.at(index) = aStyle;
switch (aPointDrawingOrder) {
case PointDrawingOrder::Raise:
drawing_order().raise(index);
break;
case PointDrawingOrder::Lower:
drawing_order().lower(index);
break;
case PointDrawingOrder::NoChange:
break;
}
}
template <typename index_type> inline void modify_serum(index_type aSerumNo, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
modify(static_cast<size_t>(aSerumNo) + number_of_antigens(), aStyle, aPointDrawingOrder);
}
template <typename IndexIterator> inline void modify(IndexIterator first, IndexIterator last, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
for (; first != last; ++first)
modify(*first, aStyle, aPointDrawingOrder);
}
inline void modify(const acmacs::chart::Indexes& aIndexes, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
for (auto index: aIndexes)
modify(index, aStyle, aPointDrawingOrder);
}
template <typename IndexIterator> inline void modify_sera(IndexIterator first, IndexIterator last, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
for (; first != last; ++first)
modify_serum(*first, aStyle, aPointDrawingOrder);
}
inline void modify_sera(const acmacs::chart::Indexes& aIndexes, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
{
for (auto index: aIndexes)
modify_serum(index, aStyle, aPointDrawingOrder);
}
void hide_all_except(const std::vector<size_t>& aNotHide);
void mark_egg_antigens();
void mark_reassortant_antigens();
void mark_all_grey(Color aColor);
void scale_points(double aPointScale, double aOulineScale);
void modify_all_sera(const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange);
inline void rotate(double aAngle)
{
if (!float_zero(aAngle))
log("rotate radians:", aAngle, " degrees:", 180.0 * aAngle / M_PI, " ", aAngle > 0 ? "counter-" : "", "clockwise");
mTransformation.rotate(aAngle);
mTransformedLayout.reset();
}
inline void flip(double aX, double aY)
{
// std::cout << "INFO: flip " << aX << " " << aY << std::endl;
log("flip ", aX, " ", aY);
mTransformation.flip(aX, aY); // reflect about a line specified with vector [aX, aY]
mTransformedLayout.reset();
}
inline const acmacs::Transformation& transformation() const { return mTransformation; }
inline void viewport(double aX, double aY, double aSize) { mViewport.set(aX, aY, aSize); }
inline void viewport(const acmacs::Viewport& aViewport) { mViewport = aViewport; }
inline const acmacs::Viewport& viewport() const { return mViewport; }
DrawingOrder& drawing_order() { return mDrawingOrder; }
inline void background_color(Color aBackgroud) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).background_color(aBackgroud); }
inline void grid(Color aGridColor, double aGridLineWidth) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).grid(aGridColor, aGridLineWidth); }
inline void border(Color aBorderColor, double aBorderWidth) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).border(aBorderColor, aBorderWidth); }
inline void continent_map(const acmacs::Location& aOffset, Pixels aWidth) { DYNAMIC_CAST(map_elements::ContinentMap&, (mMapElements["continent-map"])).offset_width(aOffset, aWidth); }
inline map_elements::LegendPointLabel& legend(const acmacs::Location& aOffset) { auto& legend = DYNAMIC_CAST(map_elements::LegendPointLabel&, (mMapElements["legend-point-label"])); legend.offset(aOffset); return legend; }
inline map_elements::LegendPointLabel& legend() { return DYNAMIC_CAST(map_elements::LegendPointLabel&, (mMapElements["legend-point-label"])); }
inline void remove_legend() { mMapElements.remove("legend-point-label"); }
inline map_elements::Title& title(const acmacs::Location& aOffset) { auto& title = DYNAMIC_CAST(map_elements::Title&, (mMapElements["title"])); title.offset(aOffset); return title; }
inline map_elements::Title& title() { return DYNAMIC_CAST(map_elements::Title&, (mMapElements["title"])); }
inline map_elements::Labels& labels() { return mLabels; }
inline map_elements::Label& add_label(size_t aIndex) { return mLabels.add(aIndex, mChart); }
inline void remove_label(size_t aIndex) { return mLabels.remove(aIndex); }
map_elements::SerumCircle& serum_circle(size_t aSerumNo, Scaled aRadius);
map_elements::Line& line(const acmacs::Location& aBegin, const acmacs::Location& aEnd);
map_elements::Arrow& arrow(const acmacs::Location& aBegin, const acmacs::Location& aEnd);
map_elements::Point& point(const acmacs::Location& aCenter, Pixels aSize);
map_elements::Rectangle& rectangle(const acmacs::Location& aCorner1, const acmacs::Location& aCorner2);
map_elements::Circle& circle(const acmacs::Location& aCenter, Scaled aSize);
void remove_serum_circles();
inline const acmacs::chart::Layout& transformed_layout() const
{
if (!mTransformedLayout) {
mTransformedLayout = std::unique_ptr<acmacs::chart::Layout>(mChart.projection(mProjectionNo)->layout()->transform(mTransformation));
}
return *mTransformedLayout;
}
size_t number_of_antigens() const;
size_t number_of_sera() const;
inline size_t number_of_points() const { return number_of_antigens() + number_of_sera(); }
void save(std::string aFilename, std::string aProgramName);
private:
acmacs::chart::Chart& mChart;
acmacs::chart::Chart* mPreviousChart = nullptr;
size_t mProjectionNo;
acmacs::Viewport mViewport;
acmacs::Transformation mTransformation;
std::vector<PointStyleDraw> mPointStyles;
DrawingOrder mDrawingOrder;
map_elements::Elements mMapElements;
map_elements::Labels mLabels;
mutable std::unique_ptr<acmacs::chart::Layout> mTransformedLayout;
}; // class ChartDraw
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iterator>
#include <sstream>
#include <string>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <gsl/gsl>
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/scalar.h"
namespace xchainer {
namespace {
namespace py = pybind11; // standard convention
void InitXchainerModule(pybind11::module& m) {
m.doc() = "xChainer";
m.attr("__name__") = "xchainer"; // Show each member as "xchainer.*" instead of "xchainer.core.*"
py::register_exception<XchainerError>(m, "XchainerError");
py::register_exception<DtypeError>(m, "DtypeError");
//
// Types
//
{
py::enum_<Dtype> dtype_type(m, "Dtype");
for (Dtype dtype : GetAllDtypes()) {
dtype_type.value(GetDtypeName(dtype), dtype);
}
dtype_type.export_values();
dtype_type.def(py::init(&GetDtype));
dtype_type.def_property_readonly("char", [](Dtype dtype) { return std::string(1, GetCharCode(dtype)); });
dtype_type.def_property_readonly("itemsize", &GetElementSize);
dtype_type.def_property_readonly("name", &GetDtypeName);
}
py::class_<Scalar>(m, "Scalar")
.def(py::init<bool>())
.def(py::init<int64_t>())
.def(py::init<double>())
.def(+py::self)
.def(-py::self)
.def("__bool__", &Scalar::UnwrapAndCast<bool>)
.def("__int__", &Scalar::UnwrapAndCast<int64_t>)
.def("__float__", &Scalar::UnwrapAndCast<double>)
.def("__repr__", &Scalar::ToString)
.def_property_readonly("dtype", &Scalar::dtype);
}
} // namespace
} // namespace xchainer
PYBIND11_MODULE(_core, m) { xchainer::InitXchainerModule(m); }
<commit_msg>Cleaner Scalar method bindings<commit_after>#include <algorithm>
#include <iterator>
#include <sstream>
#include <string>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <gsl/gsl>
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/scalar.h"
namespace xchainer {
namespace {
namespace py = pybind11; // standard convention
void InitXchainerModule(pybind11::module& m) {
m.doc() = "xChainer";
m.attr("__name__") = "xchainer"; // Show each member as "xchainer.*" instead of "xchainer.core.*"
py::register_exception<XchainerError>(m, "XchainerError");
py::register_exception<DtypeError>(m, "DtypeError");
//
// Types
//
{
py::enum_<Dtype> dtype_type(m, "Dtype");
for (Dtype dtype : GetAllDtypes()) {
dtype_type.value(GetDtypeName(dtype), dtype);
}
dtype_type.export_values();
dtype_type.def(py::init(&GetDtype));
dtype_type.def_property_readonly("char", [](Dtype dtype) { return std::string(1, GetCharCode(dtype)); });
dtype_type.def_property_readonly("itemsize", &GetElementSize);
dtype_type.def_property_readonly("name", &GetDtypeName);
}
py::class_<Scalar>(m, "Scalar")
.def(py::init<bool>())
.def(py::init<int64_t>())
.def(py::init<double>())
.def(+py::self)
.def(-py::self)
.def("__bool__", &Scalar::operator bool)
.def("__int__", &Scalar::operator int64_t)
.def("__float__", &Scalar::operator double)
.def("__repr__", &Scalar::ToString)
.def_property_readonly("dtype", &Scalar::dtype);
}
} // namespace
} // namespace xchainer
PYBIND11_MODULE(_core, m) { xchainer::InitXchainerModule(m); }
<|endoftext|>
|
<commit_before>#include <QLabel>
#include <QScrollArea>
#include <QPixmap>
#include <QImage>
#include <QMouseEvent>
#include <QApplication>
#include <math.h>
#ifndef QT_NO_WHEELEVENT
#include <QWheelEvent>
#endif
#include <stdio.h>
#include "widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
}
Widget::~Widget()
{
}
bool Widget::showPicture() {
imageLabel = new QLabel(this);
imageLabel->setBackgroundRole(QPalette::Base);
imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
imageLabel->setScaledContents(true);
setWindowTitle(mFilename);
//resize(500, 400);
QImage image(mFilename);
if(image.isNull()) {
fprintf(stderr, "Can't load %s\n", mFilename.toLocal8Bit().data());
return false;
}
imageLabel->setPixmap(QPixmap::fromImage(image));
resize(imageLabel->pixmap()->size());
imageLabel->resize(this->width(), this->height());
imageLabel->move(0,0);
return true;
}
void Widget::resizeEvent(QResizeEvent *e) {
this->QWidget::resizeEvent(e);
imageLabel->resize(this->width(), this->height());
imageLabel->move(0,0);
}
void Widget::mousePressEvent(QMouseEvent *e) {
if(e->modifiers() != 0) {
if(e->modifiers() == Qt::ControlModifier && e->button() == Qt::LeftButton) {
this->rememberedPointForPanning = e->pos();
}
return;
}
switch(e->button()) {
case Qt::RightButton:
QApplication::exit(0);
break;
case Qt::LeftButton:
this->printCoordinates(this->coordWindowToPicture( e->pos()));
break;
case Qt::MiddleButton:
this->rememberedPointForPanning = e->pos();
break;
}
}
void Widget::mouseMoveEvent(QMouseEvent *e) {
int buttonSet = e->buttons().operator int();
int modifierSet = e->modifiers().operator int();
if(buttonSet == Qt::MiddleButton ||
(modifierSet == Qt::ControlModifier && buttonSet == Qt::LeftButton)) {
imageLabel->move(imageLabel->pos() + e->pos() - this->rememberedPointForPanning);
this->rememberedPointForPanning = e->pos();
}
}
QPoint Widget::coordWindowToPicture(QPoint in) {
int pictureWidth = imageLabel->pixmap()->size().width();
int pictureHeight = imageLabel->pixmap()->size().height();
int windowWidth = imageLabel->width();
int windowHeight = imageLabel->height();
int xx = (in.x() - imageLabel->x()) * pictureWidth / windowWidth;
int yy = (in.y() - imageLabel->y()) * pictureHeight / windowHeight;
return QPoint(xx, yy);
}
QPoint Widget::coordPictureToWindow(QPoint in) {
int pictureWidth = imageLabel->pixmap()->size().width();
int pictureHeight = imageLabel->pixmap()->size().height();
int windowWidth = imageLabel->width();
int windowHeight = imageLabel->height();
int xx = in.x() * windowWidth / pictureWidth + imageLabel->x();
int yy = in.y() * windowHeight / pictureHeight + imageLabel->y();
return QPoint(xx, yy);
}
void Widget::printCoordinates(QPoint coords) {
fprintf(stdout, "%d,%d\n", coords.x(), coords.y());
fflush(stdout);
}
#ifndef QT_NO_WHEELEVENT
void Widget::wheelEvent(QWheelEvent * e) {
int d = e->delta();
double q = exp(0.001*d);
//fprintf(stderr, "D: %d %g\n", d, q);
QPoint pictCoords = this->coordWindowToPicture( e->pos());
imageLabel->resize(imageLabel->size()*q);
QPoint windowCoords = this->coordPictureToWindow(pictCoords) - imageLabel->pos();
imageLabel->move(e->pos() - windowCoords );
}
#endif
<commit_msg>Make it buildable again<commit_after>#include <QLabel>
#include <QScrollArea>
#include <QPixmap>
#include <QImage>
#include <QMouseEvent>
#include <QApplication>
#include <math.h>
#ifndef QT_NO_WHEELEVENT
#include <QWheelEvent>
#endif
#include <stdio.h>
#include "widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
}
Widget::~Widget()
{
}
bool Widget::showPicture() {
imageLabel = new QLabel(this);
imageLabel->setBackgroundRole(QPalette::Base);
imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
imageLabel->setScaledContents(true);
setWindowTitle(mFilename);
//resize(500, 400);
QImage image(mFilename);
if(image.isNull()) {
fprintf(stderr, "Can't load %s\n", mFilename.toLocal8Bit().data());
return false;
}
imageLabel->setPixmap(QPixmap::fromImage(image));
resize(imageLabel->pixmap()->size());
imageLabel->resize(this->width(), this->height());
imageLabel->move(0,0);
return true;
}
void Widget::resizeEvent(QResizeEvent *e) {
this->QWidget::resizeEvent(e);
imageLabel->resize(this->width(), this->height());
imageLabel->move(0,0);
}
void Widget::mousePressEvent(QMouseEvent *e) {
if(e->modifiers() != 0) {
if(e->modifiers() == Qt::ControlModifier && e->button() == Qt::LeftButton) {
this->rememberedPointForPanning = e->pos();
}
return;
}
switch(e->button()) {
case Qt::RightButton:
QApplication::exit(0);
break;
case Qt::LeftButton:
this->printCoordinates(this->coordWindowToPicture( e->pos()));
break;
case Qt::MiddleButton:
this->rememberedPointForPanning = e->pos();
break;
}
}
void Widget::mouseMoveEvent(QMouseEvent *e) {
Qt::MouseButtons buttonSet = e->buttons();
Qt::KeyboardModifiers modifierSet = e->modifiers();
if(buttonSet == Qt::MiddleButton ||
(modifierSet == Qt::ControlModifier && buttonSet == Qt::LeftButton)) {
imageLabel->move(imageLabel->pos() + e->pos() - this->rememberedPointForPanning);
this->rememberedPointForPanning = e->pos();
}
}
QPoint Widget::coordWindowToPicture(QPoint in) {
int pictureWidth = imageLabel->pixmap()->size().width();
int pictureHeight = imageLabel->pixmap()->size().height();
int windowWidth = imageLabel->width();
int windowHeight = imageLabel->height();
int xx = (in.x() - imageLabel->x()) * pictureWidth / windowWidth;
int yy = (in.y() - imageLabel->y()) * pictureHeight / windowHeight;
return QPoint(xx, yy);
}
QPoint Widget::coordPictureToWindow(QPoint in) {
int pictureWidth = imageLabel->pixmap()->size().width();
int pictureHeight = imageLabel->pixmap()->size().height();
int windowWidth = imageLabel->width();
int windowHeight = imageLabel->height();
int xx = in.x() * windowWidth / pictureWidth + imageLabel->x();
int yy = in.y() * windowHeight / pictureHeight + imageLabel->y();
return QPoint(xx, yy);
}
void Widget::printCoordinates(QPoint coords) {
fprintf(stdout, "%d,%d\n", coords.x(), coords.y());
fflush(stdout);
}
#ifndef QT_NO_WHEELEVENT
void Widget::wheelEvent(QWheelEvent * e) {
int d = e->delta();
double q = exp(0.001*d);
//fprintf(stderr, "D: %d %g\n", d, q);
QPoint pictCoords = this->coordWindowToPicture( e->pos());
imageLabel->resize(imageLabel->size()*q);
QPoint windowCoords = this->coordPictureToWindow(pictCoords) - imageLabel->pos();
imageLabel->move(e->pos() - windowCoords );
}
#endif
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* (C) 2019 Eddie Hung <eddie@fpgeh.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
// for peepopt_pm
bool did_something;
#include "passes/pmgen/xilinx_srl_pm.h"
#include "passes/pmgen/ice40_dsp_pm.h"
#include "passes/pmgen/peepopt_pm.h"
void run_fixed(xilinx_srl_pm &pm)
{
auto &st = pm.st_fixed;
auto &ud = pm.ud_fixed;
auto param_def = [&ud](Cell *cell, IdString param) {
auto def = ud.default_params.at(std::make_pair(cell->type,param));
return cell->parameters.at(param, def);
};
log("Found fixed chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type));
auto last_cell = ud.longest_chain.back();
SigSpec initval;
for (auto cell : ud.longest_chain) {
log_debug(" %s\n", log_id(cell));
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) {
SigBit Q = cell->getPort(ID(Q));
log_assert(Q.wire);
auto it = Q.wire->attributes.find(ID(init));
if (it != Q.wire->attributes.end()) {
initval.append(it->second[Q.offset]);
}
else
initval.append(State::Sx);
}
else if (cell->type.in(ID(FDRE), ID(FDRE_1)))
initval.append(param_def(cell, ID(INIT)));
else
log_abort();
if (cell != last_cell)
pm.autoremove(cell);
}
Cell *c = last_cell;
SigBit Q = st.first->getPort(ID(Q));
c->setPort(ID(Q), Q);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID(FDRE), ID(FDRE_1))) {
c->parameters.clear();
c->setParam(ID(DEPTH), GetSize(ud.longest_chain));
c->setParam(ID(INIT), initval.as_const());
if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
c->setParam(ID(CLKPOL), 1);
else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1)))
c->setParam(ID(CLKPOL), 0);
else if (c->type.in(ID(FDRE)))
c->setParam(ID(CLKPOL), param_def(c, ID(IS_C_INVERTED)).as_bool() ? 0 : 1);
else
log_abort();
if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
c->setParam(ID(ENPOL), 1);
else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
c->setParam(ID(ENPOL), 0);
else
c->setParam(ID(ENPOL), 2);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_)))
c->setPort(ID(E), State::S1);
c->setPort(ID(L), GetSize(ud.longest_chain)-1);
c->type = ID($__XILINX_SHREG_);
}
else
log_abort();
log(" -> %s (%s)\n", log_id(c), log_id(c->type));
}
void run_variable(xilinx_srl_pm &pm)
{
auto &st = pm.st_variable;
auto &ud = pm.ud_variable;
log("Found variable chain of length %d (%s):\n", GetSize(ud.chain), log_id(st.first->type));
auto last_cell = ud.chain.back().first;
auto last_slice = ud.chain.back().second;
SigSpec initval;
for (const auto &i : ud.chain) {
auto cell = i.first;
auto slice = i.second;
log_debug(" %s\n", log_id(cell));
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
SigBit Q = cell->getPort(ID(Q))[slice];
log_assert(Q.wire);
auto it = Q.wire->attributes.find(ID(init));
if (it != Q.wire->attributes.end()) {
initval.append(it->second[Q.offset]);
}
else
initval.append(State::Sx);
}
else
log_abort();
if (cell != last_cell)
cell->connections_.at(ID(Q))[slice] = pm.module->addWire(NEW_ID);
}
pm.autoremove(st.shiftx);
Cell *c = last_cell;
SigBit Q = st.first->getPort(ID(Q))[last_slice];
c->setPort(ID(Q), Q);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
Const clkpol, enpol;
if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
clkpol = 1;
else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_)))
clkpol = 0;
else if (c->type.in(ID($dff), ID($dffe))) {
clkpol = c->getParam(ID(CLK_POLARITY));
c->setPort(ID(C), c->getPort(ID(CLK)));
c->unsetPort(ID(CLK));
}
else
log_abort();
if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
enpol = 1;
else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
enpol = 0;
else if (c->type.in(ID($dffe))) {
enpol = c->getParam(ID(EN_POLARITY));
c->setPort(ID(E), c->getPort(ID(EN)));
c->unsetPort(ID(EN));
}
else
enpol = 2;
c->parameters.clear();
c->setParam(ID(DEPTH), GetSize(ud.chain));
c->setParam(ID(INIT), initval.as_const());
c->setParam(ID(CLKPOL), clkpol);
c->setParam(ID(ENPOL), enpol);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($dff)))
c->setPort(ID(E), State::S1);
c->setPort(ID(L), st.shiftx->getPort(ID(B)));
c->setPort(ID(Q), st.shiftx->getPort(ID(Y)));
c->type = ID($__XILINX_SHREG_);
}
else
log_abort();
log(" -> %s (%s)\n", log_id(c), log_id(c->type));
}
struct XilinxSrlPass : public Pass {
XilinxSrlPass() : Pass("xilinx_srl", "Xilinx shift register extraction") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" xilinx_srl [options] [selection]\n");
log("\n");
log("This pass converts chains of built-in flops ($_DFF_[NP]_, $_DFFE_*) as well as\n");
log("Xilinx flops (FDRE, FDRE_1) into a $__XILINX_SHREG cell. Chains must be of the\n");
log("same type, clock, clock polarity, enable, enable polarity (when relevant).\n");
log("Flops with resets cannot be mapped to Xilinx devices and will not be inferred.");
log("\n");
log(" -minlen N\n");
log(" min length of shift register (default = 3)\n");
log("\n");
log(" -fixed\n");
log(" infer fixed-length shift registers.\n");
log("\n");
log(" -variable\n");
log(" infer variable-length shift registers (i.e. fixed-length shifts where\n");
log(" each element also fans-out to a $shiftx cell.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing XILINX_SRL pass (Xilinx shift register extraction).\n");
bool fixed = false;
bool variable = false;
int minlen = 3;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
minlen = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-fixed") {
fixed = true;
continue;
}
if (args[argidx] == "-variable") {
variable = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!fixed && !variable)
log_cmd_error("'-fixed' and/or '-variable' must be specified.\n");
for (auto module : design->selected_modules()) {
auto pm = xilinx_srl_pm(module, module->selected_cells());
pm.ud_fixed.minlen = minlen;
pm.ud_variable.minlen = minlen;
if (fixed) {
// TODO: How to get these automatically?
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(INIT))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_C_INVERTED))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_D_INVERTED))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_R_INVERTED))] = State::S0;
pm.run_fixed(run_fixed);
}
if (variable)
pm.run_variable(run_variable);
}
}
} XilinxSrlPass;
PRIVATE_NAMESPACE_END
<commit_msg>Remove (* init *) entry when consumed into SRL<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* (C) 2019 Eddie Hung <eddie@fpgeh.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
// for peepopt_pm
bool did_something;
#include "passes/pmgen/xilinx_srl_pm.h"
#include "passes/pmgen/ice40_dsp_pm.h"
#include "passes/pmgen/peepopt_pm.h"
void run_fixed(xilinx_srl_pm &pm)
{
auto &st = pm.st_fixed;
auto &ud = pm.ud_fixed;
auto param_def = [&ud](Cell *cell, IdString param) {
auto def = ud.default_params.at(std::make_pair(cell->type,param));
return cell->parameters.at(param, def);
};
log("Found fixed chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type));
auto last_cell = ud.longest_chain.back();
SigSpec initval;
for (auto cell : ud.longest_chain) {
log_debug(" %s\n", log_id(cell));
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) {
SigBit Q = cell->getPort(ID(Q));
log_assert(Q.wire);
auto it = Q.wire->attributes.find(ID(init));
if (it != Q.wire->attributes.end()) {
auto &i = it->second[Q.offset];
initval.append(i);
i = State::Sx;
}
else
initval.append(State::Sx);
}
else if (cell->type.in(ID(FDRE), ID(FDRE_1)))
initval.append(param_def(cell, ID(INIT)));
else
log_abort();
if (cell != last_cell)
pm.autoremove(cell);
}
Cell *c = last_cell;
SigBit Q = st.first->getPort(ID(Q));
c->setPort(ID(Q), Q);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID(FDRE), ID(FDRE_1))) {
c->parameters.clear();
c->setParam(ID(DEPTH), GetSize(ud.longest_chain));
c->setParam(ID(INIT), initval.as_const());
if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
c->setParam(ID(CLKPOL), 1);
else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1)))
c->setParam(ID(CLKPOL), 0);
else if (c->type.in(ID(FDRE)))
c->setParam(ID(CLKPOL), param_def(c, ID(IS_C_INVERTED)).as_bool() ? 0 : 1);
else
log_abort();
if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
c->setParam(ID(ENPOL), 1);
else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
c->setParam(ID(ENPOL), 0);
else
c->setParam(ID(ENPOL), 2);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_)))
c->setPort(ID(E), State::S1);
c->setPort(ID(L), GetSize(ud.longest_chain)-1);
c->type = ID($__XILINX_SHREG_);
}
else
log_abort();
log(" -> %s (%s)\n", log_id(c), log_id(c->type));
}
void run_variable(xilinx_srl_pm &pm)
{
auto &st = pm.st_variable;
auto &ud = pm.ud_variable;
log("Found variable chain of length %d (%s):\n", GetSize(ud.chain), log_id(st.first->type));
auto last_cell = ud.chain.back().first;
auto last_slice = ud.chain.back().second;
SigSpec initval;
for (const auto &i : ud.chain) {
auto cell = i.first;
auto slice = i.second;
log_debug(" %s\n", log_id(cell));
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
SigBit Q = cell->getPort(ID(Q))[slice];
log_assert(Q.wire);
auto it = Q.wire->attributes.find(ID(init));
if (it != Q.wire->attributes.end()) {
auto &i = it->second[Q.offset];
initval.append(i);
i = State::Sx;
}
else
initval.append(State::Sx);
}
else
log_abort();
if (cell != last_cell)
cell->connections_.at(ID(Q))[slice] = pm.module->addWire(NEW_ID);
}
pm.autoremove(st.shiftx);
Cell *c = last_cell;
SigBit Q = st.first->getPort(ID(Q))[last_slice];
c->setPort(ID(Q), Q);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
Const clkpol, enpol;
if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
clkpol = 1;
else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_)))
clkpol = 0;
else if (c->type.in(ID($dff), ID($dffe))) {
clkpol = c->getParam(ID(CLK_POLARITY));
c->setPort(ID(C), c->getPort(ID(CLK)));
c->unsetPort(ID(CLK));
}
else
log_abort();
if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
enpol = 1;
else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
enpol = 0;
else if (c->type.in(ID($dffe))) {
enpol = c->getParam(ID(EN_POLARITY));
c->setPort(ID(E), c->getPort(ID(EN)));
c->unsetPort(ID(EN));
}
else
enpol = 2;
c->parameters.clear();
c->setParam(ID(DEPTH), GetSize(ud.chain));
c->setParam(ID(INIT), initval.as_const());
c->setParam(ID(CLKPOL), clkpol);
c->setParam(ID(ENPOL), enpol);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($dff)))
c->setPort(ID(E), State::S1);
c->setPort(ID(L), st.shiftx->getPort(ID(B)));
c->setPort(ID(Q), st.shiftx->getPort(ID(Y)));
c->type = ID($__XILINX_SHREG_);
}
else
log_abort();
log(" -> %s (%s)\n", log_id(c), log_id(c->type));
}
struct XilinxSrlPass : public Pass {
XilinxSrlPass() : Pass("xilinx_srl", "Xilinx shift register extraction") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" xilinx_srl [options] [selection]\n");
log("\n");
log("This pass converts chains of built-in flops ($_DFF_[NP]_, $_DFFE_*) as well as\n");
log("Xilinx flops (FDRE, FDRE_1) into a $__XILINX_SHREG cell. Chains must be of the\n");
log("same type, clock, clock polarity, enable, enable polarity (when relevant).\n");
log("Flops with resets cannot be mapped to Xilinx devices and will not be inferred.");
log("\n");
log(" -minlen N\n");
log(" min length of shift register (default = 3)\n");
log("\n");
log(" -fixed\n");
log(" infer fixed-length shift registers.\n");
log("\n");
log(" -variable\n");
log(" infer variable-length shift registers (i.e. fixed-length shifts where\n");
log(" each element also fans-out to a $shiftx cell.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing XILINX_SRL pass (Xilinx shift register extraction).\n");
bool fixed = false;
bool variable = false;
int minlen = 3;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
minlen = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-fixed") {
fixed = true;
continue;
}
if (args[argidx] == "-variable") {
variable = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!fixed && !variable)
log_cmd_error("'-fixed' and/or '-variable' must be specified.\n");
for (auto module : design->selected_modules()) {
auto pm = xilinx_srl_pm(module, module->selected_cells());
pm.ud_fixed.minlen = minlen;
pm.ud_variable.minlen = minlen;
if (fixed) {
// TODO: How to get these automatically?
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(INIT))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_C_INVERTED))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_D_INVERTED))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_R_INVERTED))] = State::S0;
pm.run_fixed(run_fixed);
}
if (variable)
pm.run_variable(run_variable);
}
}
} XilinxSrlPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
void split_portname_pair(std::string &port1, std::string &port2)
{
size_t pos = port1.find_first_of(':');
if (pos != std::string::npos) {
port2 = port1.substr(pos+1);
port1 = port1.substr(0, pos);
}
}
struct IopadmapPass : public Pass {
IopadmapPass() : Pass("iopadmap", "technology mapping of i/o pads (or buffers)") { }
virtual void help()
{
log("\n");
log(" iopadmap [options] [selection]\n");
log("\n");
log("Map module inputs/outputs to PAD cells from a library. This pass\n");
log("can only map to very simple PAD cells. Use 'techmap' to further map\n");
log("the resulting cells to more sophisticated PAD cells.\n");
log("\n");
log(" -inpad <celltype> <portname>[:<portname>]\n");
log(" Map module input ports to the given cell type with\n");
log(" the given port name. if a 2nd portname is given, the\n");
log(" signal is passed through the pad call, using the 2nd\n");
log(" portname as output.\n");
log("\n");
log(" -outpad <celltype> <portname>[:<portname>]\n");
log(" -inoutpad <celltype> <portname>[:<portname>]\n");
log(" Similar to -inpad, but for output and inout ports.\n");
log("\n");
log(" -widthparam <param_name>\n");
log(" Use the specified parameter name to set the port width.\n");
log("\n");
log(" -nameparam <param_name>\n");
log(" Use the specified parameter to set the port name.\n");
log("\n");
log(" -bits\n");
log(" create individual bit-wide buffers even for ports that\n");
log(" are wider. (the default behavior is to create word-wide\n");
log(" buffers using -widthparam to set the word size on the cell.)\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header("Executing IOPADMAP pass (mapping inputs/outputs to IO-PAD cells).\n");
std::string inpad_celltype, inpad_portname, inpad_portname2;
std::string outpad_celltype, outpad_portname, outpad_portname2;
std::string inoutpad_celltype, inoutpad_portname, inoutpad_portname2;
std::string widthparam, nameparam;
bool flag_bits = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
std::string arg = args[argidx];
if (arg == "-inpad" && argidx+2 < args.size()) {
inpad_celltype = args[++argidx];
inpad_portname = args[++argidx];
split_portname_pair(inpad_portname, inpad_portname2);
continue;
}
if (arg == "-outpad" && argidx+2 < args.size()) {
outpad_celltype = args[++argidx];
outpad_portname = args[++argidx];
split_portname_pair(outpad_portname, outpad_portname2);
continue;
}
if (arg == "-inoutpad" && argidx+2 < args.size()) {
inoutpad_celltype = args[++argidx];
inoutpad_portname = args[++argidx];
split_portname_pair(inoutpad_portname, inoutpad_portname2);
continue;
}
if (arg == "-widthparam" && argidx+1 < args.size()) {
widthparam = args[++argidx];
continue;
}
if (arg == "-nameparam" && argidx+1 < args.size()) {
nameparam = args[++argidx];
continue;
}
if (arg == "-bits") {
flag_bits = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto module : design->selected_modules())
{
for (auto wire : module->selected_wires())
{
if (!wire->port_id)
continue;
std::string celltype, portname, portname2;
if (wire->port_input && !wire->port_output) {
if (inpad_celltype.empty()) {
log("Don't map input port %s.%s: Missing option -inpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
continue;
}
celltype = inpad_celltype;
portname = inpad_portname;
portname2 = inpad_portname2;
} else
if (!wire->port_input && wire->port_output) {
if (outpad_celltype.empty()) {
log("Don't map output port %s.%s: Missing option -outpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
continue;
}
celltype = outpad_celltype;
portname = outpad_portname;
portname2 = outpad_portname2;
} else
if (wire->port_input && wire->port_output) {
if (inoutpad_celltype.empty()) {
log("Don't map inout port %s.%s: Missing option -inoutpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
continue;
}
celltype = inoutpad_celltype;
portname = inoutpad_portname;
portname2 = inoutpad_portname2;
} else
log_abort();
if (!flag_bits && wire->width != 1 && widthparam.empty()) {
log("Don't map multi-bit port %s.%s: Missing option -widthparam or -bits.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
continue;
}
log("Mapping port %s.%s using %s.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name), celltype.c_str());
RTLIL::Wire *new_wire = NULL;
if (!portname2.empty()) {
new_wire = module->addWire(NEW_ID, wire);
module->swap_names(new_wire, wire);
}
if (flag_bits)
{
for (int i = 0; i < wire->width; i++)
{
RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(celltype));
cell->setPort(RTLIL::escape_id(portname), RTLIL::SigSpec(wire, i));
if (!portname2.empty())
cell->setPort(RTLIL::escape_id(portname2), RTLIL::SigSpec(new_wire, i));
if (!widthparam.empty())
cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(1);
if (!nameparam.empty())
cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(stringf("%s[%d]", RTLIL::id2cstr(wire->name), i));
cell->attributes["\\keep"] = RTLIL::Const(1);
}
}
else
{
RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(celltype));
cell->setPort(RTLIL::escape_id(portname), RTLIL::SigSpec(wire));
if (!portname2.empty())
cell->setPort(RTLIL::escape_id(portname2), RTLIL::SigSpec(new_wire));
if (!widthparam.empty())
cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(wire->width);
if (!nameparam.empty())
cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(RTLIL::id2cstr(wire->name));
cell->attributes["\\keep"] = RTLIL::Const(1);
}
wire->port_id = 0;
wire->port_input = false;
wire->port_output = false;
}
module->fixup_ports();
}
}
} IopadmapPass;
PRIVATE_NAMESPACE_END
<commit_msg>Fixed iopadmap help message<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
void split_portname_pair(std::string &port1, std::string &port2)
{
size_t pos = port1.find_first_of(':');
if (pos != std::string::npos) {
port2 = port1.substr(pos+1);
port1 = port1.substr(0, pos);
}
}
struct IopadmapPass : public Pass {
IopadmapPass() : Pass("iopadmap", "technology mapping of i/o pads (or buffers)") { }
virtual void help()
{
log("\n");
log(" iopadmap [options] [selection]\n");
log("\n");
log("Map module inputs/outputs to PAD cells from a library. This pass\n");
log("can only map to very simple PAD cells. Use 'techmap' to further map\n");
log("the resulting cells to more sophisticated PAD cells.\n");
log("\n");
log(" -inpad <celltype> <portname>[:<portname>]\n");
log(" Map module input ports to the given cell type with the\n");
log(" given output port name. if a 2nd portname is given, the\n");
log(" signal is passed through the pad call, using the 2nd\n");
log(" portname as input.\n");
log("\n");
log(" -outpad <celltype> <portname>[:<portname>]\n");
log(" -inoutpad <celltype> <portname>[:<portname>]\n");
log(" Similar to -inpad, but for output and inout ports.\n");
log("\n");
log(" -widthparam <param_name>\n");
log(" Use the specified parameter name to set the port width.\n");
log("\n");
log(" -nameparam <param_name>\n");
log(" Use the specified parameter to set the port name.\n");
log("\n");
log(" -bits\n");
log(" create individual bit-wide buffers even for ports that\n");
log(" are wider. (the default behavior is to create word-wide\n");
log(" buffers using -widthparam to set the word size on the cell.)\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header("Executing IOPADMAP pass (mapping inputs/outputs to IO-PAD cells).\n");
std::string inpad_celltype, inpad_portname, inpad_portname2;
std::string outpad_celltype, outpad_portname, outpad_portname2;
std::string inoutpad_celltype, inoutpad_portname, inoutpad_portname2;
std::string widthparam, nameparam;
bool flag_bits = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
std::string arg = args[argidx];
if (arg == "-inpad" && argidx+2 < args.size()) {
inpad_celltype = args[++argidx];
inpad_portname = args[++argidx];
split_portname_pair(inpad_portname, inpad_portname2);
continue;
}
if (arg == "-outpad" && argidx+2 < args.size()) {
outpad_celltype = args[++argidx];
outpad_portname = args[++argidx];
split_portname_pair(outpad_portname, outpad_portname2);
continue;
}
if (arg == "-inoutpad" && argidx+2 < args.size()) {
inoutpad_celltype = args[++argidx];
inoutpad_portname = args[++argidx];
split_portname_pair(inoutpad_portname, inoutpad_portname2);
continue;
}
if (arg == "-widthparam" && argidx+1 < args.size()) {
widthparam = args[++argidx];
continue;
}
if (arg == "-nameparam" && argidx+1 < args.size()) {
nameparam = args[++argidx];
continue;
}
if (arg == "-bits") {
flag_bits = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto module : design->selected_modules())
{
for (auto wire : module->selected_wires())
{
if (!wire->port_id)
continue;
std::string celltype, portname, portname2;
if (wire->port_input && !wire->port_output) {
if (inpad_celltype.empty()) {
log("Don't map input port %s.%s: Missing option -inpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
continue;
}
celltype = inpad_celltype;
portname = inpad_portname;
portname2 = inpad_portname2;
} else
if (!wire->port_input && wire->port_output) {
if (outpad_celltype.empty()) {
log("Don't map output port %s.%s: Missing option -outpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
continue;
}
celltype = outpad_celltype;
portname = outpad_portname;
portname2 = outpad_portname2;
} else
if (wire->port_input && wire->port_output) {
if (inoutpad_celltype.empty()) {
log("Don't map inout port %s.%s: Missing option -inoutpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
continue;
}
celltype = inoutpad_celltype;
portname = inoutpad_portname;
portname2 = inoutpad_portname2;
} else
log_abort();
if (!flag_bits && wire->width != 1 && widthparam.empty()) {
log("Don't map multi-bit port %s.%s: Missing option -widthparam or -bits.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
continue;
}
log("Mapping port %s.%s using %s.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name), celltype.c_str());
RTLIL::Wire *new_wire = NULL;
if (!portname2.empty()) {
new_wire = module->addWire(NEW_ID, wire);
module->swap_names(new_wire, wire);
}
if (flag_bits)
{
for (int i = 0; i < wire->width; i++)
{
RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(celltype));
cell->setPort(RTLIL::escape_id(portname), RTLIL::SigSpec(wire, i));
if (!portname2.empty())
cell->setPort(RTLIL::escape_id(portname2), RTLIL::SigSpec(new_wire, i));
if (!widthparam.empty())
cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(1);
if (!nameparam.empty())
cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(stringf("%s[%d]", RTLIL::id2cstr(wire->name), i));
cell->attributes["\\keep"] = RTLIL::Const(1);
}
}
else
{
RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(celltype));
cell->setPort(RTLIL::escape_id(portname), RTLIL::SigSpec(wire));
if (!portname2.empty())
cell->setPort(RTLIL::escape_id(portname2), RTLIL::SigSpec(new_wire));
if (!widthparam.empty())
cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(wire->width);
if (!nameparam.empty())
cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(RTLIL::id2cstr(wire->name));
cell->attributes["\\keep"] = RTLIL::Const(1);
}
wire->port_id = 0;
wire->port_input = false;
wire->port_output = false;
}
module->fixup_ports();
}
}
} IopadmapPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <graphics.h>
#include <windows.h>
#include <stdlib.h>
#define panjang 600
#define MAX_INPUT_LEN 15
//typedef struct{
//char *name;
//int score;
//int lives;
//}playerControl;
int kursor(int, int, int);
void tampilan();
void tampilan2();
void menuutama();
void player1();
void player2();
void menuplay();
void menuscore();
void howtoplay();
void aboutus();
void inputnama();
int main()
{
int gd=DETECT, gm;
initwindow(800,600);
menuutama();
getch();
closegraph();
return 0;
}
int kursor(int option, int x, int y)
{
int select=1, p=x+25, q=y+25;
int input;
readimagefile("picture/pacman1.bmp",x, y, p, q); //menampilkan lambang kursor
do
{
input=getch();
if(input==80) //80 kode ASCII kursor bawah
{
readimagefile("picture/black.bmp",x, y, p, q);
y=y+25;
q=q+25;
select++;
if(select>option)
{
y=y-(25*option);
q=q-(25*option);
select=1;
}
readimagefile("picture/pacman1.bmp",x, y, p, q);
}
if(input==72) //72 kode ASCII kursor atas
{
readimagefile("picture/black.bmp",x, y, p, q);
y=y-25;
q=q-25;
select--;
if (select<1)
{
y=y+(25*option);
q=q+(25*option);
select=option;
}
readimagefile("picture/pacman1.bmp",x, y, p, q);
}
}
while(input!=13);
return select;
}
void tampilan()
{
//setbkcolor(2);
setfillstyle(SOLID_FILL, 10);
readimagefile("picture/pecimen.bmp",100, 10 , 700, 210);
readimagefile("picture/pacman.bmp",50, 250, 300, 550);
}
void tampilan2()
{
//setbkcolor(2);
setfillstyle(SOLID_FILL, 10);
readimagefile("picture/pecimen.bmp",100, 10 , 700, 210);
readimagefile("picture/pacman2.bmp",0, 200, 150, 580);
readimagefile("picture/pacman2.bmp",650, 200, 800, 580);
}
void player1()
{
cleardevice();
tampilan();
//outtextxy(475,300,"1 player ");
inputnama();
}
void player2()
{
cleardevice();
tampilan();
//outtextxy(475,300,"2 player ");
inputnama();
}
void menuplay()
{
cleardevice();
tampilan();
//cleardevice();
setcolor(15);
settextstyle(9,HORIZ_DIR,2);
outtextxy(375,300, "PLAYER");
settextstyle(8,HORIZ_DIR,1);
setcolor(9);
outtextxy(390,350, "1 PLAYER");
outtextxy(390,375, "2 PLAYER");
setcolor(4);
outtextxy(370,400, "BACK TO MENU");
setcolor(15);
int player = kursor(3,325,350);
switch(player) //kursor di 4 posisi, x=50, y=32
{
case 1 : player1();break;
case 2 : player2();break;
case 3 : menuutama();break;
}
}
void menuscore()
{
cleardevice();
tampilan2();
outtextxy(400,300,"score: ");
setcolor(4);
outtextxy(370,570,"BACK TO MENU");
int skor = kursor(1,325,570);
switch(skor)
{
case 1 : menuutama();break;
}
}
void howtoplay()
{ int a=5,b=32,c=17;
cleardevice();
readimagefile("picture/pacman1.bmp",200, 5, 225, 30);
readimagefile("picture/pacman1.bmp",575, 5, 600, 30);
settextstyle(8,HORIZ_DIR,3);
outtextxy(320,5, "How To Play");
settextstyle(8,HORIZ_DIR,1);
outtextxy(a,b,"> Game ini dapat dimainkan 1 2 Orang ");
outtextxy(a,b+(1*c),"> Peci-men dikontrol menggunakan keyboard. ");
outtextxy(a,b+(2*c),"> Setiap player menggerakan 1 Peci-men. ? ");
outtextxy(a,b+(3*c),"> Kontrol Player 1 : ");
outtextxy(a+50,b+(4*c),"o Arrow atas untuk menggerakan ke atas ");
outtextxy(a+50,b+(5*c),"o Arrow bawah untuk menggerakan ke bawah ");
outtextxy(a+50,b+(6*c),"o Arrow kanan untuk menggerakan ke kanan ");
outtextxy(a+50,b+(7*c),"o Arrow kiri untuk menggerakan ke kiri ");
outtextxy(a,b+(8*c),"> Kontrol Player 2 : ");
outtextxy(a+50,b+(9*c),"o Tombol W untuk menggerakan ke atas ");
outtextxy(a+50,b+(10*c),"o Tombol S untuk menggerakan ke bawah ");
outtextxy(a+50,b+(11*c),"o Tombol D untuk menggerakan ke kanan ");
outtextxy(a+50,b+(12*c),"o Tombol A untuk menggerakan ke kiri ");
outtextxy(a,b+(13*c),"> Peci-Men tidak dapat menembus pembatas/dinding labirin ");
outtextxy(a,b+(14*c),"> Pada sisi kanan dan kiri ada pintu khusus yang membuat Peci-Men");
outtextxy(a,b+(15*c)," berpindah tempat / teleport dari satu sisi ke sisi lainnya. ");
outtextxy(a,b+(16*c),"> Setiap player diberikan 3 Nyawa ? Terdapat bonus / sesajen untuk");
outtextxy(a,b+(17*c)," menambah skor dan lives (nyawa) dari karakter Pac-Man yang dimainkan. ");
outtextxy(a,b+(18*c),"> Dalam mode multi-player, Peci-Men yang paling cepat menghabiskan");
outtextxy(a,b+(19*c)," dan mendapat skor yang paling tinggi menjadi pemenangnya ");
outtextxy(a,b+(20*c),"> Peci-Men dapat memakan musuh dengan memakan bonus, sehingga musuh");
outtextxy(a,b+(21*c)," berubah warna dan mencoba menghindari Peci-Men. ");
outtextxy(a,b+(22*c),"> Kondisi menang ditentukan saat semua Pac-Dot termakan oleh karakter");
outtextxy(a,b+(23*c)," Peci-Men ? Player akan dinyatakan kalah / Game Over jika Peci-Men");
outtextxy(a,b+(24*c)," terkena musuh.");
outtextxy(a,b+(25*c),"> Jika nyawa Peci-Men habis maka game akan dihentikan. ");
outtextxy(a,b+(26*c),"> Kemampuan tiap hantu : ");
outtextxy(a+50,b+(27*c),"o Tuyul : Lari cepat dan mengambil skor ") ;
outtextxy(a+50,b+(28*c),"o Kuntilanak : Bisa menembut 1 tembok ");
outtextxy(a+50,b+(29*c),"o Pocong : Meloncat 2 petak ");
outtextxy(a+50,b+(30*c),"o Tengkorak : Mengfreze peci-men ");
setcolor(4);
outtextxy(370,570,"BACK TO MENU");
int how = kursor(1,325,570);
switch(how)
{
case 1 : menuutama();break;
}
}
void aboutus()
{
cleardevice();
outtextxy(45,30, " AAA BBBBBBB OOOOO UUUU UUUU TTTTTTT UUUU UUUU SSSSSSS");
outtextxy(45,47, " AA AA BB BB OO OO UU UU TTT UU UU SS SS");
outtextxy(45,64, "AA AA BB BB OO OO UU UU TTT UU UU SS");
outtextxy(45,81, "AAAAAAA BBBBBB OO OO UU UU TTT UU UU SSSSSSS");
outtextxy(45,98, "AA AA BB BB OO OO UU UU TTT UU UU SS");
outtextxy(45,115,"AA AA BB BB OO OO UU UU TTT UU UU SS SS");
outtextxy(35,130,"AAAA AAAA BBBBBBB OOOOO UUUUUUU TTT UUUUUUU SSSSSSS ");
rectangle(20,164,755,270);
rectangle(20,270,755,490);
outtextxy(350,185,"<Leader>");
outtextxy(280,220,"Nama : Pega Kurniawan");
outtextxy(280,240,"NIM : 161511060");
outtextxy(25,300,"Nama : Auliya Aqma Dinilah");
outtextxy(25,320,"NIM : 161511006");
outtextxy(25,380,"Nama : Haya Utami Lutfi");
outtextxy(25,400,"NIM : 161511011");
outtextxy(400,300,"Nama : Achmad Fadhitya Muharram");
outtextxy(400,320,"NIM : 161511034");
outtextxy(400,380,"Nama : Fahmi Rosdiansyah Mahdani");
outtextxy(400,400,"NIM : 161511044");
outtextxy(280,440,"Nama : Muhamad Hisyam Anshory");
outtextxy(280,460,"NIM : 161511052");
setcolor(15);
settextstyle(8,HORIZ_DIR,1);
outtextxy(200,550,"Kelompok 9 - D3 Teknik Informatika");
outtextxy(250,570,"POLITEKNIK NEGERI BANDUNG");
setcolor(4);
outtextxy(350,505, "BACK TO MENU");
setcolor(15);
int player = kursor(1,325,500);
switch(player) //kursor di 4 posisi, x=50, y=32
{
case 1 : menuutama();break;
}
}
void menuutama()
{
cleardevice();
tampilan();
menu :
setcolor(15);
settextstyle(9,HORIZ_DIR,2);
outtextxy(385,300, "MENU");
settextstyle(8,HORIZ_DIR,1);
setcolor(9);
outtextxy(400,350, "PLAY");
outtextxy(395,375, "SCORE");
outtextxy(370,400, "HOW TO PLAY");
outtextxy(385,425, "ABOUT US");
setcolor(4);
outtextxy(400,450, "EXIT");
setcolor(15);
int menu = kursor(5,325,350);
switch(menu) //kursor di 5 posisi, x=350, y=350
{
case 1 : menuplay();break;
case 2 : menuscore ();break;
case 3 : howtoplay(); break;
case 4 : aboutus();break;
case 5 : exit;
}
}
void inputnama() {
char inputbuf[MAX_INPUT_LEN];
for(int idx=0;idx<MAX_INPUT_LEN;idx++)
inputbuf[idx]=0;
int input_pos = 0;
int the_end=0;
char c;
do
{
cleardevice();
readimagefile("picture/pecimen.bmp",100,10,700,160);
rectangle(100,250,700,400);
settextstyle(3, HORIZ_DIR,4);
outtextxy(280,260,"Nama Player:");
outtextxy (280, 300, inputbuf);
c = getch();
switch (c)
{
case 8: /* backspace */
if (input_pos)
{
input_pos--;
inputbuf[input_pos] = 0;
}
break;
case 13: /* return */
the_end = 1;
break;
case 27: /* Escape = Abort */
inputbuf[0] = 0;
the_end = 1;
break;
default:
if (input_pos < MAX_INPUT_LEN-1 && c >= ' ' && c <= '~')
{
inputbuf[input_pos] = c;
input_pos++;
inputbuf[input_pos] = 0;
}
}
} while (!the_end);
//getchar(playerControl player1.name);
}
<commit_msg>tampilan menu baru<commit_after>#include <stdio.h>
#include <graphics.h>
#include <windows.h>
#include <stdlib.h>
#define panjang 600
#define MAX_INPUT_LEN 15
//typedef struct{
//char *name;
//int score;
//int lives;
//}playerControl;
int kursor(int, int, int);
void tampilan();
void tampilan2();
void menuutama();
void player1();
void player2();
void menuplay();
void menuscore();
void howtoplay();
void aboutus();
void inputnama();
int main()
{
int gd=DETECT, gm;
initwindow(800,600);
menuutama();
getch();
closegraph();
return 0;
}
int kursor(int option, int x, int y)
{
int select=1, p=x+25, q=y+25;
int input;
readimagefile("picture/pacman1.bmp",x, y, p, q); //menampilkan lambang kursor
do
{
input=getch();
if(input==80) //80 kode ASCII kursor bawah
{
readimagefile("picture/black.bmp",x, y, p, q);
y=y+25;
q=q+25;
select++;
if(select>option)
{
y=y-(25*option);
q=q-(25*option);
select=1;
}
readimagefile("picture/pacman1.bmp",x, y, p, q);
}
if(input==72) //72 kode ASCII kursor atas
{
readimagefile("picture/black.bmp",x, y, p, q);
y=y-25;
q=q-25;
select--;
if (select<1)
{
y=y+(25*option);
q=q+(25*option);
select=option;
}
readimagefile("picture/pacman1.bmp",x, y, p, q);
}
}
while(input!=13);
return select;
}
void tampilan()
{
//setbkcolor(2);
setfillstyle(SOLID_FILL, 10);
readimagefile("picture/pecimen.bmp",100, 10 , 700, 210);
readimagefile("picture/pacman.bmp",50, 250, 300, 550);
}
void tampilan2()
{
//setbkcolor(2);
setfillstyle(SOLID_FILL, 10);
readimagefile("picture/pecimen.bmp",100, 10 , 700, 210);
readimagefile("picture/pacman2.bmp",0, 200, 150, 580);
readimagefile("picture/pacman2.bmp",650, 200, 800, 580);
}
void player1()
{
cleardevice();
tampilan();
//outtextxy(500,300,"1 player ");
inputnama();
}
void player2()
{
cleardevice();
tampilan();
//outtextxy(500,300,"2 player ");
inputnama();
}
void menuplay()
{
cleardevice();
tampilan();
//cleardevice();
setcolor(15);
settextstyle(9,HORIZ_DIR,2);
outtextxy(375,300, "PLAYER");
settextstyle(8,HORIZ_DIR,1);
setcolor(9);
outtextxy(390,355, "1 PLAYER");
outtextxy(390,382, "2 PLAYER");
setcolor(4);
outtextxy(370,408, "BACK TO MENU");
setcolor(15);
int player = kursor(3,325,350);
switch(player) //kursor di 4 posisi, x=50, y=32
{
case 1 : player1();break;
case 2 : player2();break;
case 3 : menuutama();break;
}
}
void menuscore()
{
cleardevice();
tampilan2();
outtextxy(400,300,"score: ");
setcolor(4);
outtextxy(370,570,"BACK TO MENU");
int skor = kursor(1,325,570);
switch(skor)
{
case 1 : menuutama();break;
}
}
void howtoplay()
{ int a=5,b=32,c=17;
cleardevice();
readimagefile("picture/pacman1.bmp",200, 5, 225, 30);
readimagefile("picture/pacman1.bmp",575, 5, 600, 30);
settextstyle(8,HORIZ_DIR,3);
outtextxy(320,5, "How To Play");
settextstyle(8,HORIZ_DIR,1);
outtextxy(a,b,"> Game ini dapat dimainkan 1 2 Orang ");
outtextxy(a,b+(1*c),"> Peci-men dikontrol menggunakan keyboard. ");
outtextxy(a,b+(2*c),"> Setiap player menggerakan 1 Peci-men. ");
outtextxy(a,b+(3*c),"> Kontrol Player 1 : ");
outtextxy(a+50,b+(4*c),"o Arrow atas untuk menggerakan ke atas ");
outtextxy(a+50,b+(5*c),"o Arrow bawah untuk menggerakan ke bawah ");
outtextxy(a+50,b+(6*c),"o Arrow kanan untuk menggerakan ke kanan ");
outtextxy(a+50,b+(7*c),"o Arrow kiri untuk menggerakan ke kiri ");
outtextxy(a,b+(8*c),"> Kontrol Player 2 : ");
outtextxy(a+50,b+(9*c),"o Tombol W untuk menggerakan ke atas ");
outtextxy(a+50,b+(10*c),"o Tombol S untuk menggerakan ke bawah ");
outtextxy(a+50,b+(11*c),"o Tombol D untuk menggerakan ke kanan ");
outtextxy(a+50,b+(12*c),"o Tombol A untuk menggerakan ke kiri ");
outtextxy(a,b+(13*c),"> Peci-Men tidak dapat menembus pembatas/dinding labirin ");
outtextxy(a,b+(14*c),"> Pada sisi kanan dan kiri ada pintu khusus yang membuat Peci-Men");
outtextxy(a,b+(15*c)," berpindah tempat / teleport dari satu sisi ke sisi lainnya. ");
outtextxy(a,b+(16*c),"> Setiap player diberikan 3 Nyawa ? Terdapat bonus / sesajen untuk");
outtextxy(a,b+(17*c)," menambah skor dan lives (nyawa) dari karakter Pac-Man yang dimainkan. ");
outtextxy(a,b+(18*c),"> Dalam mode multi-player, Peci-Men yang paling cepat menghabiskan");
outtextxy(a,b+(19*c)," dan mendapat skor yang paling tinggi menjadi pemenangnya ");
outtextxy(a,b+(20*c),"> Peci-Men dapat memakan musuh dengan memakan bonus, sehingga musuh");
outtextxy(a,b+(21*c)," berubah warna dan mencoba menghindari Peci-Men. ");
outtextxy(a,b+(22*c),"> Kondisi menang ditentukan saat semua Pac-Dot termakan oleh karakter");
outtextxy(a,b+(23*c)," Peci-Men ? Player akan dinyatakan kalah / Game Over jika Peci-Men");
outtextxy(a,b+(24*c)," terkena musuh.");
outtextxy(a,b+(25*c),"> Jika nyawa Peci-Men habis maka game akan dihentikan. ");
outtextxy(a,b+(26*c),"> Kemampuan tiap hantu : ");
outtextxy(a+50,b+(27*c),"o Tuyul : Lari cepat dan mengambil skor ") ;
outtextxy(a+50,b+(28*c),"o Kuntilanak : Bisa menembut 1 tembok ");
outtextxy(a+50,b+(29*c),"o Pocong : Meloncat 2 petak ");
outtextxy(a+50,b+(30*c),"o Tengkorak : Mengfreze peci-men ");
setcolor(4);
outtextxy(370,570,"BACK TO MENU");
int how = kursor(1,325,570);
switch(how)
{
case 1 : menuutama();break;
}
}
void aboutus()
{
cleardevice();
outtextxy(45,30, " AAA BBBBBBB OOOOO UUUU UUUU TTTTTTT UUUU UUUU SSSSSSS");
outtextxy(45,47, " AA AA BB BB OO OO UU UU TTT UU UU SS SS");
outtextxy(45,64, "AA AA BB BB OO OO UU UU TTT UU UU SS");
outtextxy(45,81, "AAAAAAA BBBBBB OO OO UU UU TTT UU UU SSSSSSS");
outtextxy(45,98, "AA AA BB BB OO OO UU UU TTT UU UU SS");
outtextxy(45,115,"AA AA BB BB OO OO UU UU TTT UU UU SS SS");
outtextxy(35,130,"AAAA AAAA BBBBBBB OOOOO UUUUUUU TTT UUUUUUU SSSSSSS ");
rectangle(20,164,755,270);
rectangle(20,270,755,490);
outtextxy(350,185,"<Leader>");
outtextxy(280,220,"Nama : Pega Kurniawan");
outtextxy(280,240,"NIM : 161511060");
outtextxy(25,300,"Nama : Auliya Aqma Dinilah");
outtextxy(25,320,"NIM : 161511006");
outtextxy(25,380,"Nama : Haya Utami Lutfi");
outtextxy(25,400,"NIM : 161511011");
outtextxy(400,300,"Nama : Achmad Fadhitya Muharram");
outtextxy(400,320,"NIM : 161511034");
outtextxy(400,380,"Nama : Fahmi Rosdiansyah Mahdani");
outtextxy(400,400,"NIM : 161511044");
outtextxy(280,440,"Nama : Muhamad Hisyam Anshory");
outtextxy(280,460,"NIM : 161511052");
setcolor(15);
settextstyle(8,HORIZ_DIR,1);
outtextxy(200,550,"Kelompok 9 - D3 Teknik Informatika");
outtextxy(250,570,"POLITEKNIK NEGERI BANDUNG");
setcolor(4);
outtextxy(350,505, "BACK TO MENU");
setcolor(15);
int player = kursor(1,325,500);
switch(player) //kursor di 4 posisi, x=50, y=32
{
case 1 : menuutama();break;
}
}
void menuutama()
{
cleardevice();
tampilan();
menu :
setcolor(15);
rectangle(350,280,505,340);
settextstyle(9,HORIZ_DIR,2);
outtextxy(385,300, "MENU");
settextstyle(8,HORIZ_DIR,1);
setcolor(9);
outtextxy(400,355, "PLAY");
outtextxy(395,380, "SCORE");
outtextxy(370,406, "HOW TO PLAY");
outtextxy(385,430, "ABOUT US");
setcolor(4);
outtextxy(400,458, "EXIT");
setcolor(15);
int menu = kursor(5,325,350);
switch(menu) //kursor di 5 posisi, x=350, y=350
{
case 1 : menuplay();break;
case 2 : menuscore ();break;
case 3 : howtoplay(); break;
case 4 : aboutus();break;
case 5 : exit;
}
}
void inputnama() {
char inputbuf[MAX_INPUT_LEN];
for(int idx=0;idx<MAX_INPUT_LEN;idx++)
inputbuf[idx]=0;
int input_pos = 0;
int the_end=0;
char c;
do
{
cleardevice();
readimagefile("picture/pecimen.bmp",100,10,700,160);
rectangle(100,250,700,400);
settextstyle(3, HORIZ_DIR,4);
outtextxy(280,260,"Nama Player:");
outtextxy (280, 300, inputbuf);
c = getch();
switch (c)
{
case 8: /* backspace */
if (input_pos)
{
input_pos--;
inputbuf[input_pos] = 0;
}
break;
case 13: /* return */
the_end = 1;
break;
case 27: /* Escape = Abort */
inputbuf[0] = 0;
the_end = 1;
break;
default:
if (input_pos < MAX_INPUT_LEN-1 && c >= ' ' && c <= '~')
{
inputbuf[input_pos] = c;
input_pos++;
inputbuf[input_pos] = 0;
}
}
} while (!the_end);
//getchar(playerControl player1.name);
}
<|endoftext|>
|
<commit_before>/*
* menuQA.C
*
*
* Created by schutz on 01/08/08.
* Copyright 2008 CERN. All rights reserved.
*fQA
*/
gROOT->Reset("a") ;
TControlBar * fQA = NULL ;
TControlBar * fDet = NULL ;
TControlBar * fHist = NULL ;
const Int_t fRun = atoi(gSystem->Getenv("RUNNUM")) ;
AliQA * fQAResult = NULL ;
TCanvas * fCa = NULL ;
void menuQA()
{
cout << AliQA::GetQAResultFileName() << endl ;
TFile * qaResultFile = TFile::Open("QA.root") ; //AliQA::GetQAResultFileName() ) ;
if ( ! qaResultFile ) {
printf("File %s not found in current directory\n", AliQA::GetQAResultFileName() ) ;
return ;
}
fQAResult = (AliQA *)qaResultFile->Get("QA") ;
if ( ! fQAResult ) {
printf("QA object not found in %s\n", AliQA::GetQAResultFileName() ) ;
return ;
}
TFile * qaDataFile = TFile::Open(Form("Merged.QA.%d.root", fRun)) ;
if ( ! qaDataFile ) {
printf("File Merged.QA.%d.root not found in current directory\n", fRun) ;
return ;
}
if (fQA)
delete fQA ;
fQA = new TControlBar("vertical", Form("Active detectors in Run %d", fRun), 40, 20);
fQA->SetButtonWidth(400) ;
fQA->AddButton("Clean Screen", "Cls()", "Clean the screen");
// search active detectors
TList * listOfDetectors = qaDataFile->GetListOfKeys() ;
for (Int_t det = 0 ; det < listOfDetectors->GetEntries() ; det++) {
char * detName = listOfDetectors->At(det)->GetName() ;
if (fQAResult->IsSetAny(AliQA::GetDetIndex(detName)))
char * buttonName = Form("QA SIGNALLED !! : %s", detName) ;
else
char * buttonName = Form("QA OK : %s", detName) ;
fQA->AddButton(buttonName, Form("MakeDetMenu(\"%s\")", detName), Form("Display the QA histograms for %s", detName));
}
fQA->Show();
}
void MakeDetMenu(char * detName)
{
if (fDet)
delete fDet ;
if (fHist)
delete fHist ;
if (fCa)
delete fCa ;
fDet = new TControlBar("vertical", detName, 9000, 8000);
fDet->SetButtonWidth(300) ;
// serach all the QA tasks
TDirectory * save = gDirectory ;
gDirectory->cd(detName) ;
TList * listOfTasks = gDirectory->GetListOfKeys() ;
for (Int_t task = 0 ; task < listOfTasks->GetEntries() ; task++) {
TString taskName = listOfTasks->At(task)->GetName() ;
AliQA::ALITASK_t tt = AliQA::kNULLTASK ;
if (taskName.Contains(AliQA::GetTaskName(AliQA::kRAWS)) )
tt = AliQA::kRAW ;
else if (taskName.Contains(AliQA::GetTaskName(AliQA::kRECPOINTS)) ||
taskName.Contains(AliQA::GetTaskName(AliQA::kESDs)) )
tt = AliQA::kREC ;
else if (taskName.Contains(AliQA::GetTaskName(AliQA::kHITS)) ||
taskName.Contains(AliQA::GetTaskName(AliQA::kSDIGITS)) ||
taskName.Contains(AliQA::GetTaskName(AliQA::kDIGITS)) )
tt = AliQA::kSIM ;
if (fQAResult->IsSetAny(AliQA::GetDetIndex(detName), tt))
char * buttonName = Form("QA SIGNALLED !! : %s", taskName.Data()) ;
else
char * buttonName = Form("QA OK : %s", taskName.Data()) ;
fDet->AddButton(buttonName, Form("MakeTaskMenu(\"%s\", \"%s\")", detName, taskName.Data()), Form("Display the QA histograms for %s", taskName.Data()));
}
fDet->Show() ;
gDirectory = save ;
}
void MakeTaskMenu(char * detName, char * taskName )
{
if (fHist)
delete fHist ;
if (fCa)
delete fCa ;
fHist = new TControlBar("vertical", Form("QA histos for %s/%s", detName, taskName), 900, 300);
fHist->SetButtonWidth(300) ;
fHist->AddButton("ALL", Form("DisplayAll(\"%s\", \"%s\")", detName, taskName), Form("Display the QA histograms for %s", detName));
TDirectory * save = gDirectory ;
gDirectory->cd(Form("%s/%s", detName, taskName)) ;
TList * listOfHistos = gDirectory->GetListOfKeys() ;
for (Int_t h = 0 ; h < listOfHistos->GetEntries() ; h++) {
char * hName = listOfHistos->At(h)->GetName() ;
fHist->AddButton(hName, Form("Display(\"%s\")", hName), Form("Display the QA histograms %s", hName));
}
fHist->Show() ;
gDirectory = save ;
}
void Display(char * hName)
{
if (fCa)
delete fCa ;
cout << Display << " " << hName << endl ;
fCa = new TCanvas(hName, "test", 800, 600) ;
fCa->SetLogy() ;
TH1 * hh = dynamic_cast<TH1*>(gDirectory->FindObjectAny(hName));
if (hh) {
hh->Draw() ;
fCa->Modified() ;
fCa->Update() ;
}
}
void DisplayAll(char * detName, char * taskName)
{
cout << Display << " " << detName << endl ;
TDirectory * save = gDirectory ;
gDirectory->cd(Form("%s/%s", detName, taskName)) ;
TList * listOfHistos = gDirectory->GetListOfKeys() ;
Int_t nHisto = listOfHistos->GetEntries() ;
Int_t ny = TMath::Sqrt(nHisto) ;
Int_t nx = nHisto / ny + 1 ;
if (fCa)
delete fCa ;
fCa = new TCanvas(Form("QA %s in %s", taskName, detName), Form("QA %s in %s", taskName, detName), nx*300, ny*300) ;
fCa->Divide(nx, ny) ;
for (Int_t h = 0 ; h < listOfHistos->GetEntries() ; h++) {
char * hName = listOfHistos->At(h)->GetName() ;
TH1 * hh = dynamic_cast<TH1*>(gDirectory->FindObjectAny(hName));
TPad * pad = fCa->cd(h+1) ;
pad->SetLogy() ;
if (hh) {
hh->Draw() ;
fCa->Modified() ;
fCa->Update() ;
}
}
fCa->Modified() ;
fCa->Update() ;
gDirectory = save ;
}
void Cls()
{
if (fDet)
delete fDet ;
if (fHist)
delete fHist ;
if (fCa)
delete fCa ;
}
<commit_msg>typo<commit_after>/*
* menuQA.C
*
*
* Created by schutz on 01/08/08.
* Copyright 2008 CERN. All rights reserved.
*fQA
*/
gROOT->Reset("a") ;
TControlBar * fQA = NULL ;
TControlBar * fDet = NULL ;
TControlBar * fHist = NULL ;
const Int_t fRun = atoi(gSystem->Getenv("RUNNUM")) ;
AliQA * fQAResult = NULL ;
TCanvas * fCa = NULL ;
void menuQA()
{
cout << AliQA::GetQAResultFileName() << endl ;
TFile * qaResultFile = TFile::Open("QA.root") ; //AliQA::GetQAResultFileName() ) ;
if ( ! qaResultFile ) {
printf("File %s not found in current directory\n", AliQA::GetQAResultFileName() ) ;
return ;
}
fQAResult = (AliQA *)qaResultFile->Get("QA") ;
if ( ! fQAResult ) {
printf("QA object not found in %s\n", AliQA::GetQAResultFileName() ) ;
return ;
}
TFile * qaDataFile = TFile::Open(Form("Merged.QA.%d.root", fRun)) ;
if ( ! qaDataFile ) {
printf("File Merged.QA.%d.root not found in current directory\n", fRun) ;
return ;
}
if (fQA)
delete fQA ;
fQA = new TControlBar("vertical", Form("Active detectors in Run %d", fRun), 40, 20);
fQA->SetButtonWidth(400) ;
fQA->AddButton("Clean Screen", "Cls()", "Clean the screen");
// search active detectors
TList * listOfDetectors = qaDataFile->GetListOfKeys() ;
for (Int_t det = 0 ; det < listOfDetectors->GetEntries() ; det++) {
char * detName = listOfDetectors->At(det)->GetName() ;
if (fQAResult->IsSetAny(AliQA::GetDetIndex(detName)))
char * buttonName = Form("QA SIGNALLED !! : %s", detName) ;
else
char * buttonName = Form("QA OK : %s", detName) ;
fQA->AddButton(buttonName, Form("MakeDetMenu(\"%s\")", detName), Form("Display the QA histograms for %s", detName));
}
fQA->Show();
}
void MakeDetMenu(char * detName)
{
if (fDet)
delete fDet ;
if (fHist)
delete fHist ;
if (fCa)
delete fCa ;
fDet = new TControlBar("vertical", detName, 9000, 8000);
fDet->SetButtonWidth(300) ;
// serach all the QA tasks
TDirectory * save = gDirectory ;
gDirectory->cd(detName) ;
TList * listOfTasks = gDirectory->GetListOfKeys() ;
for (Int_t task = 0 ; task < listOfTasks->GetEntries() ; task++) {
TString taskName = listOfTasks->At(task)->GetName() ;
AliQA::ALITASK_t tt = AliQA::kNULLTASK ;
if (taskName.Contains(AliQA::GetTaskName(AliQA::kRAWS)) )
tt = AliQA::kRAW ;
else if (taskName.Contains(AliQA::GetTaskName(AliQA::kRECPOINTS)) ||
taskName.Contains(AliQA::GetTaskName(AliQA::kESDS)) )
tt = AliQA::kREC ;
else if (taskName.Contains(AliQA::GetTaskName(AliQA::kHITS)) ||
taskName.Contains(AliQA::GetTaskName(AliQA::kSDIGITS)) ||
taskName.Contains(AliQA::GetTaskName(AliQA::kDIGITS)) )
tt = AliQA::kSIM ;
if (fQAResult->IsSetAny(AliQA::GetDetIndex(detName), tt))
char * buttonName = Form("QA SIGNALLED !! : %s", taskName.Data()) ;
else
char * buttonName = Form("QA OK : %s", taskName.Data()) ;
fDet->AddButton(buttonName, Form("MakeTaskMenu(\"%s\", \"%s\")", detName, taskName.Data()), Form("Display the QA histograms for %s", taskName.Data()));
}
fDet->Show() ;
gDirectory = save ;
}
void MakeTaskMenu(char * detName, char * taskName )
{
if (fHist)
delete fHist ;
if (fCa)
delete fCa ;
fHist = new TControlBar("vertical", Form("QA histos for %s/%s", detName, taskName), 900, 300);
fHist->SetButtonWidth(300) ;
fHist->AddButton("ALL", Form("DisplayAll(\"%s\", \"%s\")", detName, taskName), Form("Display the QA histograms for %s", detName));
TDirectory * save = gDirectory ;
gDirectory->cd(Form("%s/%s", detName, taskName)) ;
TList * listOfHistos = gDirectory->GetListOfKeys() ;
for (Int_t h = 0 ; h < listOfHistos->GetEntries() ; h++) {
char * hName = listOfHistos->At(h)->GetName() ;
fHist->AddButton(hName, Form("Display(\"%s\")", hName), Form("Display the QA histograms %s", hName));
}
fHist->Show() ;
gDirectory = save ;
}
void Display(char * hName)
{
if (fCa)
delete fCa ;
cout << Display << " " << hName << endl ;
fCa = new TCanvas(hName, "test", 800, 600) ;
fCa->SetLogy() ;
TH1 * hh = dynamic_cast<TH1*>(gDirectory->FindObjectAny(hName));
if (hh) {
hh->Draw() ;
fCa->Modified() ;
fCa->Update() ;
}
}
void DisplayAll(char * detName, char * taskName)
{
cout << Display << " " << detName << endl ;
TDirectory * save = gDirectory ;
gDirectory->cd(Form("%s/%s", detName, taskName)) ;
TList * listOfHistos = gDirectory->GetListOfKeys() ;
Int_t nHisto = listOfHistos->GetEntries() ;
Int_t ny = TMath::Sqrt(nHisto) ;
Int_t nx = nHisto / ny + 1 ;
if (fCa)
delete fCa ;
fCa = new TCanvas(Form("QA %s in %s", taskName, detName), Form("QA %s in %s", taskName, detName), nx*300, ny*300) ;
fCa->Divide(nx, ny) ;
for (Int_t h = 0 ; h < listOfHistos->GetEntries() ; h++) {
char * hName = listOfHistos->At(h)->GetName() ;
TH1 * hh = dynamic_cast<TH1*>(gDirectory->FindObjectAny(hName));
TPad * pad = fCa->cd(h+1) ;
pad->SetLogy() ;
if (hh) {
hh->Draw() ;
fCa->Modified() ;
fCa->Update() ;
}
}
fCa->Modified() ;
fCa->Update() ;
gDirectory = save ;
}
void Cls()
{
if (fDet)
delete fDet ;
if (fHist)
delete fHist ;
if (fCa)
delete fCa ;
}
<|endoftext|>
|
<commit_before>#ifndef TEST_MEMORY_CLEANUP
#define TEST_MEMORY_CLEANUP
#include <mapnik/warning.hpp>
MAPNIK_DISABLE_WARNING_PUSH
#include <mapnik/warning_ignore.hpp>
#if defined(HAVE_LIBXML2)
#include <libxml/parser.h>
#include <libxml/entities.h>
#include <libxml/globals.h>
#endif
#if defined(HAVE_CAIRO)
#include <cairo.h>
#endif
#include <unicode/uclean.h>
#ifdef MAPNIK_USE_PROJ4
#include <proj_api.h>
#endif
MAPNIK_DISABLE_WARNING_POP
namespace testing {
inline void run_cleanup()
{
// only call this once, on exit
// to make sure valgrind output is clean
// http://xmlsoft.org/xmlmem.html
#if defined(HAVE_LIBXML2)
xmlCleanupCharEncodingHandlers();
xmlCleanupEncodingAliases();
xmlCleanupGlobals();
xmlCleanupParser();
xmlCleanupThreads();
xmlCleanupInputCallbacks();
xmlCleanupOutputCallbacks();
xmlCleanupMemory();
#endif
#if defined(HAVE_CAIRO)
// http://cairographics.org/manual/cairo-Error-handling.html#cairo-debug-reset-static-data
cairo_debug_reset_static_data();
#endif
// http://icu-project.org/apiref/icu4c/uclean_8h.html#a93f27d0ddc7c196a1da864763f2d8920
u_cleanup();
#ifdef MAPNIK_USE_PROJ4
// http://trac.osgeo.org/proj/ticket/149
#if PJ_VERSION >= 480
pj_clear_initcache();
#endif
// https://trac.osgeo.org/proj/wiki/ProjAPI#EnvironmentFunctions
pj_deallocate_grids();
#endif
}
}
#endif
<commit_msg>Remove proj4 related stuff<commit_after>#ifndef TEST_MEMORY_CLEANUP
#define TEST_MEMORY_CLEANUP
#include <mapnik/warning.hpp>
MAPNIK_DISABLE_WARNING_PUSH
#include <mapnik/warning_ignore.hpp>
#if defined(HAVE_LIBXML2)
#include <libxml/parser.h>
#include <libxml/entities.h>
#include <libxml/globals.h>
#endif
#if defined(HAVE_CAIRO)
#include <cairo.h>
#endif
#include <unicode/uclean.h>
MAPNIK_DISABLE_WARNING_POP
namespace testing {
inline void run_cleanup()
{
// only call this once, on exit
// to make sure valgrind output is clean
// http://xmlsoft.org/xmlmem.html
#if defined(HAVE_LIBXML2)
xmlCleanupCharEncodingHandlers();
xmlCleanupEncodingAliases();
xmlCleanupGlobals();
xmlCleanupParser();
xmlCleanupThreads();
xmlCleanupInputCallbacks();
xmlCleanupOutputCallbacks();
xmlCleanupMemory();
#endif
#if defined(HAVE_CAIRO)
// http://cairographics.org/manual/cairo-Error-handling.html#cairo-debug-reset-static-data
cairo_debug_reset_static_data();
#endif
// http://icu-project.org/apiref/icu4c/uclean_8h.html#a93f27d0ddc7c196a1da864763f2d8920
u_cleanup();
}
}
#endif
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "catch.hpp"
#define DLL_SVM_SUPPORT
#include "dll/dyn_rbm.hpp"
#include "dll/dyn_dbn.hpp"
#include "dll/stochastic_gradient_descent.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE( "dyn_dbn/mnist_1", "dbn::simple" ) {
using dbn_t =
dll::dyn_dbn_desc<
dll::dbn_dyn_layers<
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t,
dll::dyn_rbm_desc<dll::momentum>::rbm_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t
>>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>(
std::make_tuple(28*28,100),
std::make_tuple(100,200),
std::make_tuple(200,10));
dbn->pretrain(dataset.training_images, 20);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 1.0);
}
<commit_msg>New test<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "catch.hpp"
#define DLL_SVM_SUPPORT
#include "dll/dyn_rbm.hpp"
#include "dll/dyn_dbn.hpp"
#include "dll/stochastic_gradient_descent.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE( "dyn_dbn/mnist_1", "dbn::simple" ) {
using dbn_t =
dll::dyn_dbn_desc<
dll::dbn_dyn_layers<
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t,
dll::dyn_rbm_desc<dll::momentum>::rbm_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t
>>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>(
std::make_tuple(28*28,100),
std::make_tuple(100,200),
std::make_tuple(200,10));
dbn->pretrain(dataset.training_images, 20);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 1.0);
}
TEST_CASE( "dyn_dbn/mnist_2", "dbn::parallel" ) {
using dbn_t =
dll::dyn_dbn_desc<
dll::dbn_dyn_layers<
dll::dyn_rbm_desc<dll::momentum, dll::parallel, dll::init_weights>::rbm_t,
dll::dyn_rbm_desc<dll::momentum, dll::parallel>::rbm_t,
dll::dyn_rbm_desc<dll::momentum, dll::parallel, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t
>>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>(
std::make_tuple(28*28,100),
std::make_tuple(100,200),
std::make_tuple(200,10));
dbn->pretrain(dataset.training_images, 20);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 1.0);
}
<|endoftext|>
|
<commit_before>#include <silicium/bridge.hpp>
#include <silicium/consume.hpp>
#include <boost/optional.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/test/unit_test.hpp>
#include <lua.hpp>
namespace Si
{
struct lua_deleter
{
void operator()(lua_State *L) const
{
lua_close(L);
}
};
std::unique_ptr<lua_State, lua_deleter> open_lua()
{
auto L = std::unique_ptr<lua_State, lua_deleter>(luaL_newstate());
if (!L)
{
throw std::bad_alloc();
}
return L;
}
typedef Si::observer<lua_Integer> yield_destination;
static int yield(lua_State *L)
{
yield_destination &dest = *static_cast<yield_destination *>(lua_touserdata(L, lua_upvalueindex(1)));
lua_Integer element = lua_tointeger(L, 1);
dest.got_element(element);
return lua_yield(L, 0);
}
BOOST_AUTO_TEST_CASE(lua)
{
auto L = open_lua();
lua_State * const coro = lua_newthread(L.get());
BOOST_REQUIRE_EQUAL(0, luaL_loadstring(coro, "return function (yield) yield(4) yield(5) end"));
if (0 != lua_pcall(coro, 0, 1, 0))
{
throw std::runtime_error(lua_tostring(L.get(), -1));
}
Si::bridge<lua_Integer> yielded;
lua_pushlightuserdata(coro, &static_cast<yield_destination &>(yielded));
lua_pushcclosure(coro, yield, 1);
boost::optional<lua_Integer> got;
auto consumer = Si::consume<lua_Integer>([&got](boost::optional<lua_Integer> element)
{
BOOST_REQUIRE(element);
got = element;
});
{
yielded.async_get_one(consumer);
int rc = lua_resume(coro, 1);
if (LUA_YIELD != rc)
{
throw std::runtime_error(lua_tostring(coro, -1));
}
BOOST_CHECK_EQUAL(boost::make_optional<lua_Integer>(4), got);
}
{
yielded.async_get_one(consumer);
int rc = lua_resume(coro, 1);
if (LUA_YIELD != rc)
{
throw std::runtime_error(lua_tostring(coro, -1));
}
BOOST_CHECK_EQUAL(boost::make_optional<lua_Integer>(5), got);
}
}
}
namespace Si
{
inline void swap_top(lua_State &lua)
{
lua_pushvalue(&lua, -2);
lua_remove(&lua, -3);
}
struct pinned_value
{
pinned_value() BOOST_NOEXCEPT
{
}
pinned_value(pinned_value &&other) BOOST_NOEXCEPT
: lua(other.lua)
{
*this = std::move(other);
}
explicit pinned_value(lua_State &lua, int idx)
: lua(&lua)
{
push_key(*this);
lua_pushvalue(&lua, idx);
lua_settable(&lua, LUA_REGISTRYINDEX);
}
~pinned_value() BOOST_NOEXCEPT
{
if (!lua)
{
return;
}
remove_this();
}
pinned_value &operator = (pinned_value &&other) BOOST_NOEXCEPT
{
if (lua)
{
remove_this();
}
else
{
lua = other.lua;
}
if (!other.lua)
{
lua = nullptr;
return *this;
}
assert(lua == other.lua);
push_key(other);
lua_gettable(lua, LUA_REGISTRYINDEX);
push_key(*this);
swap_top(*lua);
lua_settable(lua, LUA_REGISTRYINDEX);
return *this;
}
private:
lua_State *lua = nullptr;
BOOST_DELETED_FUNCTION(pinned_value(pinned_value const &))
BOOST_DELETED_FUNCTION(pinned_value &operator = (pinned_value const &))
void remove_this()
{
push_key(*this);
lua_pushnil(lua);
lua_settable(lua, LUA_REGISTRYINDEX);
}
void push_key(pinned_value &pin)
{
lua_pushlightuserdata(lua, &pin);
}
};
template <class Element, class ElementFromLua>
struct lua_thread : public observable<Element>
{
using element_type = Element;
explicit lua_thread(lua_State &thread, ElementFromLua from_lua)
: s(std::make_shared<state>(thread, std::move(from_lua)))
{
}
virtual void async_get_one(observer<element_type> &receiver) SILICIUM_OVERRIDE
{
s->receiver = &receiver;
int rc;
if (s->was_resumed)
{
rc = lua_resume(s->thread, 0);
}
else
{
s->was_resumed = true;
void *bound_state = lua_newuserdata(s->thread, sizeof(weak_state));
new (static_cast<weak_state *>(bound_state)) weak_state(s);
//TODO error handling
//TODO reuse the metatable
lua_newtable(s->thread);
lua_pushcfunction(s->thread, garbage_collect_weak_state);
lua_setfield(s->thread, -2, "__gc");
lua_setmetatable(s->thread, -2);
lua_pushcclosure(s->thread, lua_thread::yield, 1);
rc = lua_resume(s->thread, 1);
}
if (LUA_YIELD == rc)
{
return;
}
if (rc != 0)
{
throw std::logic_error("error handling not implemented yet");
}
if (s->receiver)
{
exchange(s->receiver, nullptr)->ended();
}
}
virtual void cancel() SILICIUM_OVERRIDE
{
assert(s->receiver);
s.reset();
}
private:
struct state
{
lua_State *thread = nullptr;
ElementFromLua from_lua;
bool was_resumed = false;
observer<element_type> *receiver = nullptr;
pinned_value thread_pin;
explicit state(lua_State &thread, ElementFromLua from_lua)
: thread(&thread)
, from_lua(std::move(from_lua))
{
lua_pushthread(&thread);
thread_pin = pinned_value(thread, -1);
lua_pop(&thread, 1);
}
};
typedef std::weak_ptr<state> weak_state;
std::shared_ptr<state> s;
static int yield(lua_State *thread)
{
weak_state * const bound_state = static_cast<weak_state *>(lua_touserdata(thread, lua_upvalueindex(1)));
std::shared_ptr<state> locked_state = bound_state->lock();
if (!locked_state)
{
return 0;
}
assert(locked_state->receiver);
exchange(locked_state->receiver, nullptr)->got_element(locked_state->from_lua(*thread, -1));
return lua_yield(thread, 0);
}
static int garbage_collect_weak_state(lua_State *thread)
{
auto &ptr = *static_cast<weak_state *>(lua_touserdata(thread, 1));
ptr.~weak_state();
return 0;
}
};
template <class Element, class ElementFromLua>
auto make_lua_thread(lua_State &parent, ElementFromLua &&from_lua) -> lua_thread<Element, typename std::decay<ElementFromLua>::type>
{
lua_State * const coro = lua_newthread(&parent);
lua_xmove(&parent, coro, 1);
return lua_thread<Element, typename std::decay<ElementFromLua>::type>(parent, std::forward<ElementFromLua>(from_lua));
}
}
namespace Si
{
BOOST_AUTO_TEST_CASE(lua_thread_observable)
{
auto L = open_lua();
BOOST_REQUIRE_EQUAL(0, luaL_loadstring(L.get(), "return function (yield) yield(4) yield(5) end"));
if (0 != lua_pcall(L.get(), 0, 1, 0))
{
throw std::runtime_error(lua_tostring(L.get(), -1));
}
auto thread = Si::make_lua_thread<lua_Integer>(*L, [](lua_State &lua, int idx) -> lua_Integer { return lua_tointeger(&lua, idx); });
std::vector<lua_Integer> generated;
auto consumer = Si::consume<lua_Integer>([&generated](boost::optional<lua_Integer> element)
{
BOOST_REQUIRE(element);
generated.emplace_back(*element);
});
thread.async_get_one(consumer);
BOOST_REQUIRE_EQUAL(1U, generated.size());
//make sure that the Lua thread is kept alive properly by trying to collect it before the next resume
lua_gc(L.get(), LUA_GCCOLLECT, 0);
thread.async_get_one(consumer);
BOOST_REQUIRE_EQUAL(2U, generated.size());
std::vector<lua_Integer> const expected{4, 5};
BOOST_CHECK(expected == generated);
}
}
<commit_msg>devirtualize lua_thread<commit_after>#include <silicium/bridge.hpp>
#include <silicium/consume.hpp>
#include <boost/optional.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/test/unit_test.hpp>
#include <lua.hpp>
namespace Si
{
struct lua_deleter
{
void operator()(lua_State *L) const
{
lua_close(L);
}
};
std::unique_ptr<lua_State, lua_deleter> open_lua()
{
auto L = std::unique_ptr<lua_State, lua_deleter>(luaL_newstate());
if (!L)
{
throw std::bad_alloc();
}
return L;
}
typedef Si::observer<lua_Integer> yield_destination;
static int yield(lua_State *L)
{
yield_destination &dest = *static_cast<yield_destination *>(lua_touserdata(L, lua_upvalueindex(1)));
lua_Integer element = lua_tointeger(L, 1);
dest.got_element(element);
return lua_yield(L, 0);
}
BOOST_AUTO_TEST_CASE(lua)
{
auto L = open_lua();
lua_State * const coro = lua_newthread(L.get());
BOOST_REQUIRE_EQUAL(0, luaL_loadstring(coro, "return function (yield) yield(4) yield(5) end"));
if (0 != lua_pcall(coro, 0, 1, 0))
{
throw std::runtime_error(lua_tostring(L.get(), -1));
}
Si::bridge<lua_Integer> yielded;
lua_pushlightuserdata(coro, &static_cast<yield_destination &>(yielded));
lua_pushcclosure(coro, yield, 1);
boost::optional<lua_Integer> got;
auto consumer = Si::consume<lua_Integer>([&got](boost::optional<lua_Integer> element)
{
BOOST_REQUIRE(element);
got = element;
});
{
yielded.async_get_one(consumer);
int rc = lua_resume(coro, 1);
if (LUA_YIELD != rc)
{
throw std::runtime_error(lua_tostring(coro, -1));
}
BOOST_CHECK_EQUAL(boost::make_optional<lua_Integer>(4), got);
}
{
yielded.async_get_one(consumer);
int rc = lua_resume(coro, 1);
if (LUA_YIELD != rc)
{
throw std::runtime_error(lua_tostring(coro, -1));
}
BOOST_CHECK_EQUAL(boost::make_optional<lua_Integer>(5), got);
}
}
}
namespace Si
{
inline void swap_top(lua_State &lua)
{
lua_pushvalue(&lua, -2);
lua_remove(&lua, -3);
}
struct pinned_value
{
pinned_value() BOOST_NOEXCEPT
{
}
pinned_value(pinned_value &&other) BOOST_NOEXCEPT
: lua(other.lua)
{
*this = std::move(other);
}
explicit pinned_value(lua_State &lua, int idx)
: lua(&lua)
{
push_key(*this);
lua_pushvalue(&lua, idx);
lua_settable(&lua, LUA_REGISTRYINDEX);
}
~pinned_value() BOOST_NOEXCEPT
{
if (!lua)
{
return;
}
remove_this();
}
pinned_value &operator = (pinned_value &&other) BOOST_NOEXCEPT
{
if (lua)
{
remove_this();
}
else
{
lua = other.lua;
}
if (!other.lua)
{
lua = nullptr;
return *this;
}
assert(lua == other.lua);
push_key(other);
lua_gettable(lua, LUA_REGISTRYINDEX);
push_key(*this);
swap_top(*lua);
lua_settable(lua, LUA_REGISTRYINDEX);
return *this;
}
private:
lua_State *lua = nullptr;
BOOST_DELETED_FUNCTION(pinned_value(pinned_value const &))
BOOST_DELETED_FUNCTION(pinned_value &operator = (pinned_value const &))
void remove_this()
{
push_key(*this);
lua_pushnil(lua);
lua_settable(lua, LUA_REGISTRYINDEX);
}
void push_key(pinned_value &pin)
{
lua_pushlightuserdata(lua, &pin);
}
};
template <class Element, class ElementFromLua>
struct lua_thread
{
using element_type = Element;
explicit lua_thread(lua_State &thread, ElementFromLua from_lua)
: s(std::make_shared<state>(thread, std::move(from_lua)))
{
}
void async_get_one(observer<element_type> &receiver)
{
s->receiver = &receiver;
int rc;
if (s->was_resumed)
{
rc = lua_resume(s->thread, 0);
}
else
{
s->was_resumed = true;
void *bound_state = lua_newuserdata(s->thread, sizeof(weak_state));
new (static_cast<weak_state *>(bound_state)) weak_state(s);
//TODO error handling
//TODO reuse the metatable
lua_newtable(s->thread);
lua_pushcfunction(s->thread, garbage_collect_weak_state);
lua_setfield(s->thread, -2, "__gc");
lua_setmetatable(s->thread, -2);
lua_pushcclosure(s->thread, lua_thread::yield, 1);
rc = lua_resume(s->thread, 1);
}
if (LUA_YIELD == rc)
{
return;
}
if (rc != 0)
{
throw std::logic_error("error handling not implemented yet");
}
if (s->receiver)
{
exchange(s->receiver, nullptr)->ended();
}
}
void cancel()
{
assert(s->receiver);
s.reset();
}
private:
struct state
{
lua_State *thread = nullptr;
ElementFromLua from_lua;
bool was_resumed = false;
observer<element_type> *receiver = nullptr;
pinned_value thread_pin;
explicit state(lua_State &thread, ElementFromLua from_lua)
: thread(&thread)
, from_lua(std::move(from_lua))
{
lua_pushthread(&thread);
thread_pin = pinned_value(thread, -1);
lua_pop(&thread, 1);
}
};
typedef std::weak_ptr<state> weak_state;
std::shared_ptr<state> s;
static int yield(lua_State *thread)
{
weak_state * const bound_state = static_cast<weak_state *>(lua_touserdata(thread, lua_upvalueindex(1)));
std::shared_ptr<state> locked_state = bound_state->lock();
if (!locked_state)
{
return 0;
}
assert(locked_state->receiver);
exchange(locked_state->receiver, nullptr)->got_element(locked_state->from_lua(*thread, -1));
return lua_yield(thread, 0);
}
static int garbage_collect_weak_state(lua_State *thread)
{
auto &ptr = *static_cast<weak_state *>(lua_touserdata(thread, 1));
ptr.~weak_state();
return 0;
}
};
template <class Element, class ElementFromLua>
auto make_lua_thread(lua_State &parent, ElementFromLua &&from_lua) -> lua_thread<Element, typename std::decay<ElementFromLua>::type>
{
lua_State * const coro = lua_newthread(&parent);
lua_xmove(&parent, coro, 1);
return lua_thread<Element, typename std::decay<ElementFromLua>::type>(parent, std::forward<ElementFromLua>(from_lua));
}
}
namespace Si
{
BOOST_AUTO_TEST_CASE(lua_thread_observable)
{
auto L = open_lua();
BOOST_REQUIRE_EQUAL(0, luaL_loadstring(L.get(), "return function (yield) yield(4) yield(5) end"));
if (0 != lua_pcall(L.get(), 0, 1, 0))
{
throw std::runtime_error(lua_tostring(L.get(), -1));
}
auto thread = Si::make_lua_thread<lua_Integer>(*L, [](lua_State &lua, int idx) -> lua_Integer { return lua_tointeger(&lua, idx); });
std::vector<lua_Integer> generated;
auto consumer = Si::consume<lua_Integer>([&generated](boost::optional<lua_Integer> element)
{
BOOST_REQUIRE(element);
generated.emplace_back(*element);
});
thread.async_get_one(consumer);
BOOST_REQUIRE_EQUAL(1U, generated.size());
//make sure that the Lua thread is kept alive properly by trying to collect it before the next resume
lua_gc(L.get(), LUA_GCCOLLECT, 0);
thread.async_get_one(consumer);
BOOST_REQUIRE_EQUAL(2U, generated.size());
std::vector<lua_Integer> const expected{4, 5};
BOOST_CHECK(expected == generated);
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) Sjors Gielen, 2010
* See LICENSE for license.
*/
#include "perl_callbacks.h"
#include "embedperl.h"
#include <assert.h>
#define MAX_EMBED_PERL 10
// #define DEBUG
// Totally thread-unsafe...
static EmbedPerl *ePerl[MAX_EMBED_PERL];
static int numEmbedPerl = 0;
extern "C" {
void xs_init(pTHX);
/***** CALLBACKS *****/
#define FOR_EVERY_EMBED(UNIQUEID,CALLBACK) \
for( int i = 0; i < numEmbedPerl; ++i ) \
if( strcmp(ePerl[i]->uniqueid(),UNIQUEID)==0 && ePerl[i]->CALLBACK )
void emoteEmbed(const char *uniqueid, const char *receiver, const char *message)
{
#ifdef DEBUG
printf("***Callback*** Send emote to %s (on %s): %s\n", receiver, uniqueid, message);
#endif
FOR_EVERY_EMBED(uniqueid,emoteCallback) {
ePerl[i]->emoteCallback( uniqueid, receiver, message, ePerl[i]->data );
return;
}
fprintf(stderr,"[CallbackError] No handler for Emote callback (uniqueid=%s)\n", uniqueid);
}
void privmsgEmbed(const char *uniqueid, const char *receiver, const char *message)
{
#ifdef DEBUG
printf("***Callback*** Send privmsg to %s (on %s): %s\n", receiver, uniqueid, message);
#endif
FOR_EVERY_EMBED(uniqueid,privmsgCallback) {
ePerl[i]->privmsgCallback( uniqueid, receiver, message, ePerl[i]->data );
return;
}
fprintf(stderr,"[CallbackError] No handler for Privmsg callback (uniqueid=%s)\n", uniqueid);
}
const char *getPropertyEmbed(const char *uniqueid, const char *variable)
{
FOR_EVERY_EMBED(uniqueid,getPropertyCallback) {
return ePerl[i]->getPropertyCallback( uniqueid, variable, ePerl[i]->data );
}
}
void setPropertyEmbed(const char *uniqueid, const char *variable, const char *value)
{
FOR_EVERY_EMBED(uniqueid,setPropertyCallback) {
ePerl[i]->setPropertyCallback( uniqueid, variable, value, ePerl[i]->data );
return;
}
}
void unsetPropertyEmbed(const char *uniqueid, const char *variable)
{
FOR_EVERY_EMBED(uniqueid,unsetPropertyCallback) {
ePerl[i]->unsetPropertyCallback( uniqueid, variable, ePerl[i]->data );
return;
}
}
const char *getNickEmbed(const char *uniqueid)
{
FOR_EVERY_EMBED(uniqueid,getNickCallback) {
return ePerl[i]->getNickCallback( ePerl[i]->data );
}
}
void sendWhoisEmbed(const char *uniqueid, const char *who)
{
FOR_EVERY_EMBED(uniqueid,sendWhoisCallback) {
ePerl[i]->sendWhoisCallback( who, ePerl[i]->data );
return;
}
}
void joinEmbed(const char *uniqueid, const char *channel)
{
FOR_EVERY_EMBED(uniqueid,joinCallback) {
ePerl[i]->joinCallback( channel, ePerl[i]->data );
return;
}
}
void partEmbed(const char *uniqueid, const char *channel)
{
FOR_EVERY_EMBED(uniqueid,partCallback) {
ePerl[i]->partCallback( channel, ePerl[i]->data );
return;
}
}
/***** END CALLBACKS ****/
}
EmbedPerl::EmbedPerl(const char *uniqueid)
: emoteCallback(0)
, privmsgCallback(0)
, getPropertyCallback(0)
, setPropertyCallback(0)
, unsetPropertyCallback(0)
, sendWhoisCallback(0)
, joinCallback(0)
, partCallback(0)
, getNickCallback(0)
{
if( MAX_EMBED_PERL == numEmbedPerl )
{
fprintf(stderr, "Too many EmbedPerls. Raise MAX_EMBED_PERL\n");
abort();
}
for( int i = 0; i < numEmbedPerl; ++i )
{
if( strcmp(ePerl[i]->uniqueid(), uniqueid) == 0 )
{
fprintf(stderr,"EmbedPerl created for a duplicate uniqueid '%s'.\n",
uniqueid);
abort();
}
}
uniqueid_ = strdup(uniqueid);
ePerl[numEmbedPerl++] = this;
my_perl = perl_alloc();
perl_construct(my_perl);
char *argv[] = {"", "dazeus2_api_emulate.pl"};
perl_parse(my_perl, xs_init, 1, argv, NULL);
init();
}
EmbedPerl::~EmbedPerl()
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl destructor\n");
#endif
perl_destruct(my_perl);
perl_free(my_perl);
}
const char *EmbedPerl::uniqueid() const
{
return uniqueid_;
}
void EmbedPerl::setCallbacks( void (*emoteCallback) (const char*, const char*, const char*, void*),
void (*privmsgCallback)(const char*, const char*, const char*, void*),
const char* (*getPropertyCallback)(const char*, const char*, void*),
void (*setPropertyCallback)(const char*, const char*, const char*, void*),
void (*unsetPropertyCallback)(const char*, const char*, void*),
void (*sendWhoisCallback)(const char*, void*),
void (*joinCallback)(const char*, void*),
void (*partCallback)(const char*, void*),
const char* (*getNickCallback)(void*),
void *data )
{
this->emoteCallback = emoteCallback;
this->privmsgCallback = privmsgCallback;
this->getPropertyCallback = getPropertyCallback;
this->setPropertyCallback = setPropertyCallback;
this->unsetPropertyCallback = unsetPropertyCallback;
this->sendWhoisCallback = sendWhoisCallback;
this->joinCallback = joinCallback;
this->partCallback = partCallback;
this->getNickCallback = getNickCallback;
this->data = data;
}
#define PREPARE_CALL \
int argn = 0; \
dSP; \
ENTER; \
SAVETMPS; \
PUSHMARK(SP);
#define DO_CALL(NAME) \
PUTBACK; \
call_pv(NAME, G_SCALAR); \
SPAGAIN;
#define END_CALL \
PUTBACK; \
FREETMPS; \
LEAVE;
void EmbedPerl::init()
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::init()\n");
#endif
PREPARE_CALL;
XPUSHs( newSVpv(uniqueid_, strlen(uniqueid_)));
DO_CALL( "init" );
END_CALL;
}
void EmbedPerl::message(const char *from, const char *to, const char *msg)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::message(%s,%s,%s)\n", from, to, msg);
#endif
PREPARE_CALL;
XPUSHs( newSVpv(from, strlen(from)) );
XPUSHs( newSVpv(to, strlen(to)) );
XPUSHs( newSVpv(msg, strlen(msg)) );
XPUSHs( newSVpv(msg, strlen(msg)) );
DO_CALL("message");
int result = POPi;
END_CALL;
#ifdef DEBUG
fprintf(stderr, "... message(...)=%d\n", result);
#endif
}
void EmbedPerl::whois(char const *nick, int isIdentified)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::whois(%s,%d)\n", nick, isIdentified);
#endif
PREPARE_CALL;
XPUSHs( newSVpv(nick, strlen(nick)) );
XPUSHs( newSVpv(isIdentified == 1 ? "1" : "0", strlen("1")));
DO_CALL( "whois" );
int result = POPi;
END_CALL;
#ifdef DEBUG
fprintf(stderr, ".. whois(...)=%d\n", result);
#endif
}
bool EmbedPerl::loadModule(const char *module)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::loadModule(%s)", module);
#endif
PREPARE_CALL;
XPUSHs( newSVpv(module, strlen(module)) );
DO_CALL("loadModule");
int result = POPi;
END_CALL;
#ifdef DEBUG
fprintf(stderr, "=%d\n", result);
#endif
return result != 0;
}
void EmbedPerl::join(const char *channel, const char *who)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::join(%s, %s)\n", channel, who);
#endif
PREPARE_CALL;
XPUSHs( newSVpv(channel, strlen(channel)) );
XPUSHs( newSVpv(who, strlen(who)) );
DO_CALL("join");
END_CALL;
}
void EmbedPerl::nick(const char *who, const char *new_nick)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::nick(%s, %s)\n", who, new_nick);
#endif
PREPARE_CALL;
XPUSHs( newSVpv(who, strlen(who)) );
XPUSHs( newSVpv(new_nick, strlen(new_nick)) );
DO_CALL("nick");
END_CALL;
}
void EmbedPerl::connected()
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::connected()\n");
#endif
PREPARE_CALL;
DO_CALL("connected");
END_CALL;
}
/**
* 'names' should be space separated!
*/
void EmbedPerl::namesReceived(const char *channel, const char *names)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::namesReceived(%s, %s)\n", channel, names);
#endif
PREPARE_CALL;
XPUSHs( newSVpv(channel, strlen(channel)) );
XPUSHs( newSVpv(names, strlen(names)) );
DO_CALL("namesReceived");
END_CALL;
}
/**
* Call this method every second
*/
void EmbedPerl::tick()
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::tick()\n");
#endif
PREPARE_CALL;
DO_CALL("tick");
END_CALL;
}
<commit_msg>Change all function parameters into mortals<commit_after>/**
* Copyright (c) Sjors Gielen, 2010
* See LICENSE for license.
*/
#include "perl_callbacks.h"
#include "embedperl.h"
#include <assert.h>
#define MAX_EMBED_PERL 10
// #define DEBUG
// Totally thread-unsafe...
static EmbedPerl *ePerl[MAX_EMBED_PERL];
static int numEmbedPerl = 0;
extern "C" {
void xs_init(pTHX);
/***** CALLBACKS *****/
#define FOR_EVERY_EMBED(UNIQUEID,CALLBACK) \
for( int i = 0; i < numEmbedPerl; ++i ) \
if( strcmp(ePerl[i]->uniqueid(),UNIQUEID)==0 && ePerl[i]->CALLBACK )
void emoteEmbed(const char *uniqueid, const char *receiver, const char *message)
{
#ifdef DEBUG
printf("***Callback*** Send emote to %s (on %s): %s\n", receiver, uniqueid, message);
#endif
FOR_EVERY_EMBED(uniqueid,emoteCallback) {
ePerl[i]->emoteCallback( uniqueid, receiver, message, ePerl[i]->data );
return;
}
fprintf(stderr,"[CallbackError] No handler for Emote callback (uniqueid=%s)\n", uniqueid);
}
void privmsgEmbed(const char *uniqueid, const char *receiver, const char *message)
{
#ifdef DEBUG
printf("***Callback*** Send privmsg to %s (on %s): %s\n", receiver, uniqueid, message);
#endif
FOR_EVERY_EMBED(uniqueid,privmsgCallback) {
ePerl[i]->privmsgCallback( uniqueid, receiver, message, ePerl[i]->data );
return;
}
fprintf(stderr,"[CallbackError] No handler for Privmsg callback (uniqueid=%s)\n", uniqueid);
}
const char *getPropertyEmbed(const char *uniqueid, const char *variable)
{
FOR_EVERY_EMBED(uniqueid,getPropertyCallback) {
return ePerl[i]->getPropertyCallback( uniqueid, variable, ePerl[i]->data );
}
}
void setPropertyEmbed(const char *uniqueid, const char *variable, const char *value)
{
FOR_EVERY_EMBED(uniqueid,setPropertyCallback) {
ePerl[i]->setPropertyCallback( uniqueid, variable, value, ePerl[i]->data );
return;
}
}
void unsetPropertyEmbed(const char *uniqueid, const char *variable)
{
FOR_EVERY_EMBED(uniqueid,unsetPropertyCallback) {
ePerl[i]->unsetPropertyCallback( uniqueid, variable, ePerl[i]->data );
return;
}
}
const char *getNickEmbed(const char *uniqueid)
{
FOR_EVERY_EMBED(uniqueid,getNickCallback) {
return ePerl[i]->getNickCallback( ePerl[i]->data );
}
}
void sendWhoisEmbed(const char *uniqueid, const char *who)
{
FOR_EVERY_EMBED(uniqueid,sendWhoisCallback) {
ePerl[i]->sendWhoisCallback( who, ePerl[i]->data );
return;
}
}
void joinEmbed(const char *uniqueid, const char *channel)
{
FOR_EVERY_EMBED(uniqueid,joinCallback) {
ePerl[i]->joinCallback( channel, ePerl[i]->data );
return;
}
}
void partEmbed(const char *uniqueid, const char *channel)
{
FOR_EVERY_EMBED(uniqueid,partCallback) {
ePerl[i]->partCallback( channel, ePerl[i]->data );
return;
}
}
/***** END CALLBACKS ****/
}
EmbedPerl::EmbedPerl(const char *uniqueid)
: emoteCallback(0)
, privmsgCallback(0)
, getPropertyCallback(0)
, setPropertyCallback(0)
, unsetPropertyCallback(0)
, sendWhoisCallback(0)
, joinCallback(0)
, partCallback(0)
, getNickCallback(0)
{
if( MAX_EMBED_PERL == numEmbedPerl )
{
fprintf(stderr, "Too many EmbedPerls. Raise MAX_EMBED_PERL\n");
abort();
}
for( int i = 0; i < numEmbedPerl; ++i )
{
if( strcmp(ePerl[i]->uniqueid(), uniqueid) == 0 )
{
fprintf(stderr,"EmbedPerl created for a duplicate uniqueid '%s'.\n",
uniqueid);
abort();
}
}
uniqueid_ = strdup(uniqueid);
ePerl[numEmbedPerl++] = this;
my_perl = perl_alloc();
perl_construct(my_perl);
char *argv[] = {"", "dazeus2_api_emulate.pl"};
perl_parse(my_perl, xs_init, 1, argv, NULL);
init();
}
EmbedPerl::~EmbedPerl()
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl destructor\n");
#endif
perl_destruct(my_perl);
perl_free(my_perl);
}
const char *EmbedPerl::uniqueid() const
{
return uniqueid_;
}
void EmbedPerl::setCallbacks( void (*emoteCallback) (const char*, const char*, const char*, void*),
void (*privmsgCallback)(const char*, const char*, const char*, void*),
const char* (*getPropertyCallback)(const char*, const char*, void*),
void (*setPropertyCallback)(const char*, const char*, const char*, void*),
void (*unsetPropertyCallback)(const char*, const char*, void*),
void (*sendWhoisCallback)(const char*, void*),
void (*joinCallback)(const char*, void*),
void (*partCallback)(const char*, void*),
const char* (*getNickCallback)(void*),
void *data )
{
this->emoteCallback = emoteCallback;
this->privmsgCallback = privmsgCallback;
this->getPropertyCallback = getPropertyCallback;
this->setPropertyCallback = setPropertyCallback;
this->unsetPropertyCallback = unsetPropertyCallback;
this->sendWhoisCallback = sendWhoisCallback;
this->joinCallback = joinCallback;
this->partCallback = partCallback;
this->getNickCallback = getNickCallback;
this->data = data;
}
#define PREPARE_CALL \
int argn = 0; \
dSP; \
ENTER; \
SAVETMPS; \
PUSHMARK(SP);
#define DO_CALL(NAME) \
PUTBACK; \
call_pv(NAME, G_SCALAR); \
SPAGAIN;
#define END_CALL \
PUTBACK; \
FREETMPS; \
LEAVE;
void EmbedPerl::init()
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::init()\n");
#endif
PREPARE_CALL;
XPUSHs(sv_2mortal(newSVpv(uniqueid_, strlen(uniqueid_))));
DO_CALL( "init" );
END_CALL;
}
void EmbedPerl::message(const char *from, const char *to, const char *msg)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::message(%s,%s,%s)\n", from, to, msg);
#endif
PREPARE_CALL;
XPUSHs(sv_2mortal(newSVpv(from, strlen(from)) ));
XPUSHs(sv_2mortal(newSVpv(to, strlen(to)) ));
XPUSHs(sv_2mortal(newSVpv(msg, strlen(msg)) ));
XPUSHs(sv_2mortal(newSVpv(msg, strlen(msg)) ));
DO_CALL("message");
int result = POPi;
END_CALL;
#ifdef DEBUG
fprintf(stderr, "... message(...)=%d\n", result);
#endif
}
void EmbedPerl::whois(char const *nick, int isIdentified)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::whois(%s,%d)\n", nick, isIdentified);
#endif
PREPARE_CALL;
XPUSHs(sv_2mortal(newSVpv(nick, strlen(nick)) ));
XPUSHs(sv_2mortal(newSVpv(isIdentified == 1 ? "1" : "0", strlen("1"))));
DO_CALL( "whois" );
int result = POPi;
END_CALL;
#ifdef DEBUG
fprintf(stderr, ".. whois(...)=%d\n", result);
#endif
}
bool EmbedPerl::loadModule(const char *module)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::loadModule(%s)", module);
#endif
PREPARE_CALL;
XPUSHs(sv_2mortal(newSVpv(module, strlen(module)) ));
DO_CALL("loadModule");
int result = POPi;
END_CALL;
#ifdef DEBUG
fprintf(stderr, "=%d\n", result);
#endif
return result != 0;
}
void EmbedPerl::join(const char *channel, const char *who)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::join(%s, %s)\n", channel, who);
#endif
PREPARE_CALL;
XPUSHs(sv_2mortal(newSVpv(channel, strlen(channel)) ));
XPUSHs(sv_2mortal(newSVpv(who, strlen(who)) ));
DO_CALL("join");
END_CALL;
}
void EmbedPerl::nick(const char *who, const char *new_nick)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::nick(%s, %s)\n", who, new_nick);
#endif
PREPARE_CALL;
XPUSHs(sv_2mortal(newSVpv(who, strlen(who)) ));
XPUSHs(sv_2mortal(newSVpv(new_nick, strlen(new_nick)) ));
DO_CALL("nick");
END_CALL;
}
void EmbedPerl::connected()
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::connected()\n");
#endif
PREPARE_CALL;
DO_CALL("connected");
END_CALL;
}
/**
* 'names' should be space separated!
*/
void EmbedPerl::namesReceived(const char *channel, const char *names)
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::namesReceived(%s, %s)\n", channel, names);
#endif
PREPARE_CALL;
XPUSHs(sv_2mortal(newSVpv(channel, strlen(channel)) ));
XPUSHs(sv_2mortal(newSVpv(names, strlen(names)) ));
DO_CALL("namesReceived");
END_CALL;
}
/**
* Call this method every second
*/
void EmbedPerl::tick()
{
#ifdef DEBUG
fprintf(stderr, "EmbedPerl::tick()\n");
#endif
PREPARE_CALL;
DO_CALL("tick");
END_CALL;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <system.hpp>
#include <graphics.hpp>
#include <print.hpp>
#include <malloc.hpp>
namespace {
uint32_t* z_buffer = nullptr;
uint64_t width = 0;
uint64_t height = 0;
uint64_t x_shift = 0;
uint64_t y_shift = 0;
uint64_t bytes_per_scan_line = 0;
uint64_t red_shift = 0;
uint64_t green_shift = 0;
uint64_t blue_shift = 0;
uint32_t make_color(uint8_t r, uint8_t g, uint8_t b){
return (r << red_shift) + (g << green_shift) + (b << blue_shift);
}
void fill_buffer(uint32_t color){
auto where = 0;
for(size_t j = 0; j < height; ++j){
for(size_t i = 0; i < width; ++i){
z_buffer[where + i] = color;
}
where += y_shift;
}
}
void draw_rect(size_t x, size_t y, size_t w, size_t h, uint32_t color){
auto where = x + y * y_shift;
for(size_t j = 0; j < h; ++j){
for(size_t i = 0; i < w; ++i){
z_buffer[where + i] = color;
}
where += y_shift;
}
}
void paint_cursor(){
auto x = graphics::mouse_x();
auto y = graphics::mouse_y();
auto color = make_color(255, 0, 0);
draw_rect(x, y, 5, 5, color);
}
} // end of anonnymous namespace
int main(int /*argc*/, char* /*argv*/[]){
width = graphics::get_width();
height = graphics::get_height();
x_shift = graphics::get_x_shift();
y_shift = graphics::get_y_shift();
bytes_per_scan_line = graphics::get_bytes_per_scan_line();
red_shift = graphics::get_red_shift();
green_shift = graphics::get_green_shift();
blue_shift = graphics::get_blue_shift();
size_t total_size = height * bytes_per_scan_line;
printf("total_size: %u\n",total_size);
auto buffer = new char[total_size];
z_buffer = reinterpret_cast<uint32_t*>(buffer);
auto white = make_color(255, 255, 255);
while(true){
fill_buffer(white);
paint_cursor();
graphics::redraw(buffer);
sleep_ms(10);
}
delete[] buffer;
exit(0);
}
<commit_msg>Sleep a bit less<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <system.hpp>
#include <graphics.hpp>
#include <print.hpp>
#include <malloc.hpp>
namespace {
uint32_t* z_buffer = nullptr;
uint64_t width = 0;
uint64_t height = 0;
uint64_t x_shift = 0;
uint64_t y_shift = 0;
uint64_t bytes_per_scan_line = 0;
uint64_t red_shift = 0;
uint64_t green_shift = 0;
uint64_t blue_shift = 0;
uint32_t make_color(uint8_t r, uint8_t g, uint8_t b){
return (r << red_shift) + (g << green_shift) + (b << blue_shift);
}
void fill_buffer(uint32_t color){
auto where = 0;
for(size_t j = 0; j < height; ++j){
for(size_t i = 0; i < width; ++i){
z_buffer[where + i] = color;
}
where += y_shift;
}
}
void draw_rect(size_t x, size_t y, size_t w, size_t h, uint32_t color){
auto where = x + y * y_shift;
for(size_t j = 0; j < h; ++j){
for(size_t i = 0; i < w; ++i){
z_buffer[where + i] = color;
}
where += y_shift;
}
}
void paint_cursor(){
auto x = graphics::mouse_x();
auto y = graphics::mouse_y();
auto color = make_color(255, 0, 0);
draw_rect(x, y, 5, 5, color);
}
} // end of anonnymous namespace
int main(int /*argc*/, char* /*argv*/[]){
width = graphics::get_width();
height = graphics::get_height();
x_shift = graphics::get_x_shift();
y_shift = graphics::get_y_shift();
bytes_per_scan_line = graphics::get_bytes_per_scan_line();
red_shift = graphics::get_red_shift();
green_shift = graphics::get_green_shift();
blue_shift = graphics::get_blue_shift();
size_t total_size = height * bytes_per_scan_line;
printf("total_size: %u\n",total_size);
auto buffer = new char[total_size];
z_buffer = reinterpret_cast<uint32_t*>(buffer);
auto white = make_color(255, 255, 255);
while(true){
fill_buffer(white);
paint_cursor();
graphics::redraw(buffer);
sleep_ms(5);
}
delete[] buffer;
exit(0);
}
<|endoftext|>
|
<commit_before>/**
* DP
*/
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.empty()) return 0;
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> f(m, vector<int>(n));
for (int i = 0; i < n; ++i) f[0][i] = matrix[0][i] == '1';
for (int i = 1; i < m; ++i) f[i][0] = matrix[i][0] == '1';
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j) {
if (matrix[i][j] == '0') continue;
f[i][j] = 1 + min(f[i-1][j], min(f[i-1][j-1], f[i][j-1]));
}
int ans = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) ans = max(ans, f[i][j]);
return ans*ans;
}
};<commit_msg>Update 221.cpp<commit_after>/**
* DP
*
*/
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.empty()) return 0;
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> f(m, vector<int>(n));
for (int i = 0; i < n; ++i) f[0][i] = matrix[0][i] == '1';
for (int i = 1; i < m; ++i) f[i][0] = matrix[i][0] == '1';
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j) {
if (matrix[i][j] == '0') continue;
f[i][j] = 1 + min(f[i-1][j], min(f[i-1][j-1], f[i][j-1]));
}
int ans = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) ans = max(ans, f[i][j]);
return ans*ans;
}
};
// Conclusion:
//
<|endoftext|>
|
<commit_before>/*
* String, Design
*
*/
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string encoded = "";
for (const string& s: strs) {
int len = s.size();
encoded += to_string(len) + "/" + s;
}
return encoded;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> decoded;
int pos = 0;
while (pos < s.size()) {
int slashPos = s.find_first_of('/', pos);
int len = stoi(s.substr(pos, slashPos - pos));
pos = slashPos + 1;
decoded.push_back(s.substr(pos, len));
pos += len;
}
return decoded;
}
};
// Conlcusion:
<commit_msg>Update 271.cpp<commit_after>/*
* String, Design
*
*/
// version 1:
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string encoded;
for(const auto &s : strs) {
int len = s.size();
encoded += to_string(len) + '/' + s;
}
return encoded;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> decoded;
int i = 0, n = s.size();
while(i < n) {
int start = i;
while(i < n && s[i] != '/') i++; // find the position of '/'
int len = stoi(s.substr(start, i-start));
start = ++i;
decoded.push_back(s.substr(start, len));
i += len;
}
return decoded;
}
};
// version 2:
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string encoded = "";
for (const string& s: strs) {
int len = s.size();
encoded += to_string(len) + "/" + s;
}
return encoded;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> decoded;
int pos = 0;
while (pos < s.size()) {
int slashPos = s.find_first_of('/', pos);
int len = stoi(s.substr(pos, slashPos - pos));
pos = slashPos + 1;
decoded.push_back(s.substr(pos, len));
pos += len;
}
return decoded;
}
};
// Conlcusion:
<|endoftext|>
|
<commit_before>#include "stdafx.h"
App app;
std::string g_type = "mesh";
static float CalcRadius(const Mesh* m)
{
const Block& b = m->GetRawDatas();
float maxSq = 0;
for (auto& it : b.vertices) {
float sq = lengthSq(it.xyz);
maxSq = std::max(maxSq, sq);
}
return std::sqrt(maxSq);
}
App::App()
{
meshId = MeshMan::INVALID_MMID;
}
void App::Draw()
{
AF_PROFILE_RANGE(AppDraw);
IVec2 scrSize = systemMisc.GetScreenSize();
float f = 1000;
float n = 1;
float aspect = (float)scrSize.x / scrSize.y;
Mat proj = perspectiveLH(45.0f * (float)M_PI / 180.0f, aspect, n, f);
matrixMan.Set(MatrixMan::PROJ, proj);
/*
MeshXAnimResult r;
MeshX* mesh = (MeshX*)meshMan.Get(meshId);
if (mesh) {
double now = GetTime();
mesh->CalcAnimation(0, now, r);
float wrappedTime = float(now - floor(now));
auto normToRad = [](float n) { return n * float(M_PI * 2); };
mesh->Draw(r, translate(0, radius * 1.5f, 0) * q2m(Quat(Vec3(0, 0, 1.0f), normToRad(wrappedTime))));
mesh->Draw(r, translate(radius * 2.0f, 0, 0) * q2m(Quat(Vec3(0, 1.0f, 0), normToRad(wrappedTime))));
}
*/
AFCommandList& cmd = afGetCommandList();
appRenderTarget.BeginRenderToThis();
moduleManager.Draw3DAll(cmd, appRenderTarget);
luaMan.Draw3D();
meshRenderer.Flush();
skyMan.Draw(cmd);
luaMan.Draw2D(cmd);
moduleManager.Draw2DAll(cmd, appRenderTarget);
appRenderTarget.EndRenderToThis();
afBeginRenderToSwapChain();
cmd.SetRenderStates(copyPSO);
stockObjects.ApplyFullScreenVertexBuffer(cmd);
cmd.SetTexture(appRenderTarget.GetTexture(), 0);
cmd.Draw(4);
fontMan.Draw(cmd, systemMisc.GetScreenSize());
afEndRenderToSwapChain();
}
static const SamplerType samplers[] =
{
AFST_POINT_WRAP,
};
void App::Create()
{
#ifdef _MSC_VER
GoMyDir();
// SetCurrentDirectoryA("D:\\bitbucket\\Janken\\Program\\pack\\assets");
#endif
#ifdef GL_TRUE
glClearColor(0.0f, 0.0f, 0.5f, 1.0f);
glClearDepthf(0); // for left-handed coordinate
#endif
meshRenderer.Create();
fontMan.Create();
spriteRenderer.Create();
stockObjects.Create();
luaMan.Create();
appRenderTarget.Init(systemMisc.GetScreenSize(), AFF_R8G8B8A8_UNORM, AFF_AUTO_DEPTH_STENCIL);
#if defined(AF_GLES) || defined(AF_VULKAN)
int numElements = 0;
const InputElement* elements = stockObjects.GetFullScreenInputElements(numElements);
copyPSO.Create("glow_copy", numElements, elements, 0, arrayparam(samplers));
#else
copyPSO.Create("copy_rgba", 0, nullptr, 0, 0, nullptr);
#endif
}
void App::LoadMesh(const char* fileName)
{
meshId = meshMan.Create(fileName);
MeshX* mesh = (MeshX*)meshMan.Get(meshId);
if (mesh) {
float radius = CalcRadius(mesh);
float scale = std::max(0.00001f, radius);
devCamera.SetDistance(scale * 3);
}
g_type = "mesh";
}
void App::Destroy()
{
#if defined(AF_DX12) || defined(AF_VULKAN)
deviceMan.Flush();
#endif
luaMan.Destroy();
stockObjects.Destroy();
spriteRenderer.Destroy();
texMan.Destroy();
fontMan.Destroy();
meshRenderer.Destroy();
meshMan.Destroy();
skyMan.Destroy();
glow.Destroy();
letterBox.Destroy();
appRenderTarget.Destroy();
copyPSO.Destroy();
ClearMenu();
meshId = MeshMan::INVALID_MMID;
}
void App::Update()
{
{
AF_PROFILE_RANGE(Update);
systemMisc.lastUpdateTime = GetTime();
inputMan.Update();
matrixMan.Set(MatrixMan::VIEW, devCamera.CalcViewMatrix());
moduleManager.UpdateAll();
luaMan.Update();
fps.Update();
}
fontMan.DrawString(Vec2(20, 40), 20, SPrintf("FPS: %f", fps.Get()), 0xffffffff);
afProfiler.Print();
Draw();
}
<commit_msg>[DX12] Draw detailed profiling to find the bottleneck.<commit_after>#include "stdafx.h"
App app;
std::string g_type = "mesh";
static float CalcRadius(const Mesh* m)
{
const Block& b = m->GetRawDatas();
float maxSq = 0;
for (auto& it : b.vertices) {
float sq = lengthSq(it.xyz);
maxSq = std::max(maxSq, sq);
}
return std::sqrt(maxSq);
}
App::App()
{
meshId = MeshMan::INVALID_MMID;
}
void App::Draw()
{
IVec2 scrSize = systemMisc.GetScreenSize();
float f = 1000;
float n = 1;
float aspect = (float)scrSize.x / scrSize.y;
Mat proj = perspectiveLH(45.0f * (float)M_PI / 180.0f, aspect, n, f);
matrixMan.Set(MatrixMan::PROJ, proj);
/*
MeshXAnimResult r;
MeshX* mesh = (MeshX*)meshMan.Get(meshId);
if (mesh) {
double now = GetTime();
mesh->CalcAnimation(0, now, r);
float wrappedTime = float(now - floor(now));
auto normToRad = [](float n) { return n * float(M_PI * 2); };
mesh->Draw(r, translate(0, radius * 1.5f, 0) * q2m(Quat(Vec3(0, 0, 1.0f), normToRad(wrappedTime))));
mesh->Draw(r, translate(radius * 2.0f, 0, 0) * q2m(Quat(Vec3(0, 1.0f, 0), normToRad(wrappedTime))));
}
*/
AFCommandList& cmd = afGetCommandList();
{
AF_PROFILE_RANGE(AppDrawOffscreen);
appRenderTarget.BeginRenderToThis();
moduleManager.Draw3DAll(cmd, appRenderTarget);
luaMan.Draw3D();
meshRenderer.Flush();
skyMan.Draw(cmd);
luaMan.Draw2D(cmd);
moduleManager.Draw2DAll(cmd, appRenderTarget);
appRenderTarget.EndRenderToThis();
}
{
AF_PROFILE_RANGE(AppDrawBeginSwapchain);
afBeginRenderToSwapChain();
}
{
AF_PROFILE_RANGE(AppDrawDrawSwapchain);
cmd.SetRenderStates(copyPSO);
stockObjects.ApplyFullScreenVertexBuffer(cmd);
cmd.SetTexture(appRenderTarget.GetTexture(), 0);
cmd.Draw(4);
}
{
AF_PROFILE_RANGE(AppDrawDrawFontToSwapchain);
fontMan.Draw(cmd, systemMisc.GetScreenSize());
}
{
AF_PROFILE_RANGE(AppDrawEndSwapchain);
afEndRenderToSwapChain();
}
}
static const SamplerType samplers[] =
{
AFST_POINT_WRAP,
};
void App::Create()
{
#ifdef _MSC_VER
GoMyDir();
// SetCurrentDirectoryA("D:\\bitbucket\\Janken\\Program\\pack\\assets");
#endif
#ifdef GL_TRUE
glClearColor(0.0f, 0.0f, 0.5f, 1.0f);
glClearDepthf(0); // for left-handed coordinate
#endif
meshRenderer.Create();
fontMan.Create();
spriteRenderer.Create();
stockObjects.Create();
luaMan.Create();
appRenderTarget.Init(systemMisc.GetScreenSize(), AFF_R8G8B8A8_UNORM, AFF_AUTO_DEPTH_STENCIL);
#if defined(AF_GLES) || defined(AF_VULKAN)
int numElements = 0;
const InputElement* elements = stockObjects.GetFullScreenInputElements(numElements);
copyPSO.Create("glow_copy", numElements, elements, 0, arrayparam(samplers));
#else
copyPSO.Create("copy_rgba", 0, nullptr, 0, 0, nullptr);
#endif
}
void App::LoadMesh(const char* fileName)
{
meshId = meshMan.Create(fileName);
MeshX* mesh = (MeshX*)meshMan.Get(meshId);
if (mesh) {
float radius = CalcRadius(mesh);
float scale = std::max(0.00001f, radius);
devCamera.SetDistance(scale * 3);
}
g_type = "mesh";
}
void App::Destroy()
{
#if defined(AF_DX12) || defined(AF_VULKAN)
deviceMan.Flush();
#endif
luaMan.Destroy();
stockObjects.Destroy();
spriteRenderer.Destroy();
texMan.Destroy();
fontMan.Destroy();
meshRenderer.Destroy();
meshMan.Destroy();
skyMan.Destroy();
glow.Destroy();
letterBox.Destroy();
appRenderTarget.Destroy();
copyPSO.Destroy();
ClearMenu();
meshId = MeshMan::INVALID_MMID;
}
void App::Update()
{
{
AF_PROFILE_RANGE(Update);
systemMisc.lastUpdateTime = GetTime();
inputMan.Update();
matrixMan.Set(MatrixMan::VIEW, devCamera.CalcViewMatrix());
moduleManager.UpdateAll();
luaMan.Update();
fps.Update();
}
fontMan.DrawString(Vec2(20, 40), 20, SPrintf("FPS: %f", fps.Get()), 0xffffffff);
afProfiler.Print();
Draw();
}
<|endoftext|>
|
<commit_before>#include "extconfig.h"
#include <utility>
#include <Eigen/Cholesky>
#include <cmath>
/*
* Member function definitions of TSEncoder template class.
* See tsencoder.h for template class declaration.
*/
template <size_t M, size_t N, size_t O>
TSEncoder<M, N, O>::TSEncoder(const TSEncoderConfig& config) :
m_events(),
m_event_index(0),
m_skip_order_counter(0),
m_A(decltype(m_A)::Ones()), /* elements in last column of time stamp matrix are always 1 */
m_P(decltype(m_P)::Zero()),
m_B(decltype(m_B)::Zero()),
m_T(decltype(m_T)::Ones()), /* last element of time vector is always 1 */
m_t0(0),
m_alpha(0.0f),
m_config(config),
m_count(0),
m_state(state_t::STOP),
m_index(index_t::NONE) { }
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::start() {
osalSysLock();
osalDbgAssert((extp->state == EXT_STOP) || (extp->state == EXT_ACTIVE),
"invalid state");
if (extp->state == EXT_STOP) {
extStartI(extp);
}
extChannelEnableSetModeI(extp, m_config.a, EXT_CH_MODE_BOTH_EDGES, ab_callback, this);
extChannelEnableSetModeI(extp, m_config.b, EXT_CH_MODE_BOTH_EDGES, ab_callback, this);
if (m_config.z == PAL_NOLINE) {
m_index = index_t::NONE;
} else {
extChannelEnableSetModeI(extp, m_config.z, EXT_CH_MODE_RISING_EDGE, index_callback, this);
m_index = index_t::NOTFOUND;
}
m_state = state_t::READY;
osalSysUnlock();
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::stop() {
osalSysLock();
m_state = state_t::STOP;
m_index = index_t::NONE;
extChannelDisableClearModeI(extp, PAL_PAD(m_config.a));
extChannelDisableClearModeI(extp, PAL_PAD(m_config.b));
if (m_config.z != PAL_NOLINE) {
extChannelDisableClearModeI(extp, PAL_PAD(m_config.z));
}
extStopIfChannelsDisabledI(extp);
osalSysUnlock();
}
template <size_t M, size_t N, size_t O>
typename TSEncoder<M, N, O>::state_t TSEncoder<M, N, O>::state() const {
return m_state;
}
template <size_t M, size_t N, size_t O>
typename TSEncoder<M, N, O>::index_t TSEncoder<M, N, O>::index() const volatile {
return m_index;
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::update_polynomial_fit() {
/*
* Redefine oldest event to be at time zero. Scale time so that difference
* in time from oldest to newest event is equal to 1.
*
* If the difference A(N - 1, 1) - A(0, 1) is too large, the value will be
* nonsensical due to uint rolling back to zero. The difference must also
* be less than int32_t_max as these values will be cast from uint32_t to
* int32_t.
*/
m_t0 = m_events[(m_event_index + 1) % N].first;
m_alpha = 1.0f / (m_events[m_event_index].first - m_t0);
for (unsigned int i = 0; i < N; ++i) {
m_A(i, M - 1) = m_alpha * (m_events[(m_event_index + i + 1) % N].first - m_t0);
m_B(i) = m_events[(m_event_index + i + 1) % N].second;
}
for (unsigned int i = 0; i < M - 1; ++i) {
m_A.col(M - 2 - i) = m_A.col(M - 1 - i).cwiseProduct(m_A.col(M - 1));
}
m_P.noalias() = (m_A.transpose() * m_A).ldlt().solve(
(m_A.transpose() * m_B.template cast<polycoeff_t>()));
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::update_estimate_time(rtcnt_t tc) {
polycoeff_t tcf = m_alpha * static_cast<polycoeff_t>(tc - m_t0);
m_T(M - 1) = tcf;
for (unsigned int i = 0; i < M - 1; ++i) {
m_T(M - 2 - i) = m_T(M - 1 - i) * tcf;
}
}
template <size_t M, size_t N, size_t O>
polycoeff_t TSEncoder<M, N, O>::position() const {
polycoeff_t x = m_P.transpose() * m_T;
polycoeff_t count = static_cast<polycoeff_t>(m_count);
if (std::abs(x - count) > 1.0f) {
return count;
}
return x;
}
// TODO: Validity of velocity and acceleration for large error in estimated
// position (i.e. position is adjusted due to a large amount of time without
// an encoder event).
template <size_t M, size_t N, size_t O>
polycoeff_t TSEncoder<M, N, O>::velocity() const {
Eigen::Matrix<tsenccnt_t, M, 1> velocity_coefficients;
for (int i = 0; i < M; ++i) {
velocity_coefficients(i) = M - i;
}
return velocity_coefficients.cwiseProduct(m_P.template top<M>()).transpose() *
m_T.template bottom<M>();
}
template <size_t M, size_t N, size_t O>
polycoeff_t TSEncoder<M, N, O>::acceleration() const {
Eigen::Matrix<tsenccnt_t, M - 1 , 1> acceleration_coefficients;
for (int i = 0; i < M - 1; ++i) {
acceleration_coefficients(i) = (M - i) * (M - i - 1);
}
return acceleration_coefficients.cwiseProduct(m_P.template top<M - 1>()).transpose() *
m_T.template bottom<M - 1>();
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::ab_callback(EXTDriver* extp, expchannel_t channel) {
(void)extp;
osalSysLockFromISR();
TSEncoder<M, N, O>* enc = reinterpret_cast<TSEncoder<M, N, O>*>(extGetChannelCallbackObject(channel));
if (((channel == PAL_PAD(enc->m_config.a)) &&
(palReadLine(enc->m_config.a) != palReadLine(enc->m_config.b))) ||
((channel == PAL_PAD(enc->m_config.b)) &&
(palReadLine(enc->m_config.a) == palReadLine(enc->m_config.b)))) {
++enc->m_count;
} else {
--enc->m_count;
}
enc->m_events[enc->m_event_index] = std::make_pair(chSysGetRealtimeCounterX(), enc->m_count);
enc->m_skip_order_counter = (enc->m_skip_order_counter + 1) % O;
if (enc->m_skip_order_counter == 0) {
enc->m_event_index = (enc->m_event_index + 1) % N;
}
osalSysUnlockFromISR();
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::index_callback(EXTDriver* extp, expchannel_t channel) {
osalSysLockFromISR();
TSEncoder<M, N, O>* enc = reinterpret_cast<TSEncoder<M, N, O>*>(extGetChannelCallbackObject(channel));
enc->m_count = 0;
enc->m_index = index_t::FOUND;
extChannelDisableClearModeI(extp, PAL_PAD(enc->m_config.z));
osalSysUnlockFromISR();
}
<commit_msg>Fix velocity and acceleration functions in TSEncoder<commit_after>#include "extconfig.h"
#include <utility>
#include <Eigen/Cholesky>
#include <cmath>
/*
* Member function definitions of TSEncoder template class.
* See tsencoder.h for template class declaration.
*/
template <size_t M, size_t N, size_t O>
TSEncoder<M, N, O>::TSEncoder(const TSEncoderConfig& config) :
m_events(),
m_event_index(0),
m_skip_order_counter(0),
m_A(decltype(m_A)::Ones()), /* elements in last column of time stamp matrix are always 1 */
m_P(decltype(m_P)::Zero()),
m_B(decltype(m_B)::Zero()),
m_T(decltype(m_T)::Ones()), /* last element of time vector is always 1 */
m_t0(0),
m_alpha(0.0f),
m_config(config),
m_count(0),
m_state(state_t::STOP),
m_index(index_t::NONE) { }
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::start() {
osalSysLock();
osalDbgAssert((extp->state == EXT_STOP) || (extp->state == EXT_ACTIVE),
"invalid state");
if (extp->state == EXT_STOP) {
extStartI(extp);
}
extChannelEnableSetModeI(extp, m_config.a, EXT_CH_MODE_BOTH_EDGES, ab_callback, this);
extChannelEnableSetModeI(extp, m_config.b, EXT_CH_MODE_BOTH_EDGES, ab_callback, this);
if (m_config.z == PAL_NOLINE) {
m_index = index_t::NONE;
} else {
extChannelEnableSetModeI(extp, m_config.z, EXT_CH_MODE_RISING_EDGE, index_callback, this);
m_index = index_t::NOTFOUND;
}
m_state = state_t::READY;
osalSysUnlock();
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::stop() {
osalSysLock();
m_state = state_t::STOP;
m_index = index_t::NONE;
extChannelDisableClearModeI(extp, PAL_PAD(m_config.a));
extChannelDisableClearModeI(extp, PAL_PAD(m_config.b));
if (m_config.z != PAL_NOLINE) {
extChannelDisableClearModeI(extp, PAL_PAD(m_config.z));
}
extStopIfChannelsDisabledI(extp);
osalSysUnlock();
}
template <size_t M, size_t N, size_t O>
typename TSEncoder<M, N, O>::state_t TSEncoder<M, N, O>::state() const {
return m_state;
}
template <size_t M, size_t N, size_t O>
typename TSEncoder<M, N, O>::index_t TSEncoder<M, N, O>::index() const volatile {
return m_index;
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::update_polynomial_fit() {
/*
* Redefine oldest event to be at time zero. Scale time so that difference
* in time from oldest to newest event is equal to 1.
*
* If the difference A(N - 1, 1) - A(0, 1) is too large, the value will be
* nonsensical due to uint rolling back to zero. The difference must also
* be less than int32_t_max as these values will be cast from uint32_t to
* int32_t.
*/
m_t0 = m_events[(m_event_index + 1) % N].first;
m_alpha = 1.0f / (m_events[m_event_index].first - m_t0);
for (unsigned int i = 0; i < N; ++i) {
m_A(i, M - 1) = m_alpha * (m_events[(m_event_index + i + 1) % N].first - m_t0);
m_B(i) = m_events[(m_event_index + i + 1) % N].second;
}
for (unsigned int i = 0; i < M - 1; ++i) {
m_A.col(M - 2 - i) = m_A.col(M - 1 - i).cwiseProduct(m_A.col(M - 1));
}
m_P.noalias() = (m_A.transpose() * m_A).ldlt().solve(
(m_A.transpose() * m_B.template cast<polycoeff_t>()));
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::update_estimate_time(rtcnt_t tc) {
polycoeff_t tcf = m_alpha * static_cast<polycoeff_t>(tc - m_t0);
m_T(M - 1) = tcf;
for (unsigned int i = 0; i < M - 1; ++i) {
m_T(M - 2 - i) = m_T(M - 1 - i) * tcf;
}
}
template <size_t M, size_t N, size_t O>
polycoeff_t TSEncoder<M, N, O>::position() const {
polycoeff_t x = m_P.transpose() * m_T;
polycoeff_t count = static_cast<polycoeff_t>(m_count);
if (std::abs(x - count) > 1.0f) {
return count;
}
return x;
}
// TODO: Validity of velocity and acceleration for large error in estimated
// position (i.e. position is adjusted due to a large amount of time without
// an encoder event).
template <size_t M, size_t N, size_t O>
polycoeff_t TSEncoder<M, N, O>::velocity() const {
Eigen::Matrix<tsenccnt_t, M, 1> velocity_coefficients;
for (unsigned int i = 0; i < M; ++i) {
velocity_coefficients(i) = M - i;
}
return velocity_coefficients.template cast<polycoeff_t>().cwiseProduct(
m_P.template head<M>()).transpose() * m_T.template tail<M>();
}
template <size_t M, size_t N, size_t O>
polycoeff_t TSEncoder<M, N, O>::acceleration() const {
Eigen::Matrix<tsenccnt_t, M - 1 , 1> acceleration_coefficients;
for (unsigned int i = 0; i < M - 1; ++i) {
acceleration_coefficients(i) = (M - i) * (M - i - 1);
}
return acceleration_coefficients.template cast<polycoeff_t>().cwiseProduct(
m_P.template head<M - 1>()).transpose() * m_T.template tail<M - 1>();
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::ab_callback(EXTDriver* extp, expchannel_t channel) {
(void)extp;
osalSysLockFromISR();
TSEncoder<M, N, O>* enc = reinterpret_cast<TSEncoder<M, N, O>*>(extGetChannelCallbackObject(channel));
if (((channel == PAL_PAD(enc->m_config.a)) &&
(palReadLine(enc->m_config.a) != palReadLine(enc->m_config.b))) ||
((channel == PAL_PAD(enc->m_config.b)) &&
(palReadLine(enc->m_config.a) == palReadLine(enc->m_config.b)))) {
++enc->m_count;
} else {
--enc->m_count;
}
enc->m_events[enc->m_event_index] = std::make_pair(chSysGetRealtimeCounterX(), enc->m_count);
enc->m_skip_order_counter = (enc->m_skip_order_counter + 1) % O;
if (enc->m_skip_order_counter == 0) {
enc->m_event_index = (enc->m_event_index + 1) % N;
}
osalSysUnlockFromISR();
}
template <size_t M, size_t N, size_t O>
void TSEncoder<M, N, O>::index_callback(EXTDriver* extp, expchannel_t channel) {
osalSysLockFromISR();
TSEncoder<M, N, O>* enc = reinterpret_cast<TSEncoder<M, N, O>*>(extGetChannelCallbackObject(channel));
enc->m_count = 0;
enc->m_index = index_t::FOUND;
extChannelDisableClearModeI(extp, PAL_PAD(enc->m_config.z));
osalSysUnlockFromISR();
}
<|endoftext|>
|
<commit_before>#ifndef UI_UILAYER_HPP
#define UI_UILAYER_HPP
#include "SDL.h"
namespace UI {
class Layer {
public:
static Layer *front;
virtual ~Layer();
virtual void handleEvent(SDL_Event const &evt);
virtual void draw();
};
}
#endif
<commit_msg>Fixed header guards on ui/layer.hpp.<commit_after>#ifndef UI_LAYER_HPP
#define UI_LAYER_HPP
#include "SDL.h"
namespace UI {
class Layer {
public:
static Layer *front;
virtual ~Layer();
virtual void handleEvent(SDL_Event const &evt);
virtual void draw();
};
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Base.hxx"
#include <assert.h>
#include <string.h>
const char *
base_tail(const char *uri, const char *base)
{
assert(uri != nullptr);
assert(base != nullptr);
const size_t uri_length = strlen(uri);
const size_t base_length = strlen(base);
return base_length > 0 && base[base_length - 1] == '/' &&
uri_length >= base_length && memcmp(uri, base, base_length) == 0
? uri + base_length
: nullptr;
}
const char *
require_base_tail(const char *uri, const char *base)
{
assert(uri != nullptr);
assert(base != nullptr);
assert(memcmp(base, uri, strlen(base)) == 0);
return uri + strlen(base);
}
size_t
base_string(const char *p, const char *tail)
{
assert(p != nullptr);
assert(tail != nullptr);
size_t length = strlen(p), tail_length = strlen(tail);
if (length == tail_length)
/* special case: zero-length prefix (not followed by a
slash) */
return memcmp(p, tail, length) == 0
? 0 : (size_t)-1;
return length > tail_length && p[length - tail_length - 1] == '/' &&
memcmp(p + length - tail_length, tail, tail_length) == 0
? length - tail_length
: (size_t)-1;
}
bool
is_base(const char *uri)
{
assert(uri != nullptr);
size_t length = strlen(uri);
return length > 0 && uri[length - 1] == '/';
}
<commit_msg>uri/Base: use StringAfterPrefix()<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Base.hxx"
#include "util/StringCompare.hxx"
#include <assert.h>
#include <string.h>
const char *
base_tail(const char *uri, const char *base)
{
assert(uri != nullptr);
assert(base != nullptr);
const size_t base_length = strlen(base);
if (base_length == 0 || base[base_length - 1] != '/')
/* not a valid base */
return nullptr;
return StringAfterPrefix(uri, {base, base_length});
}
const char *
require_base_tail(const char *uri, const char *base)
{
assert(uri != nullptr);
assert(base != nullptr);
assert(StringStartsWith(uri, base));
return uri + strlen(base);
}
size_t
base_string(const char *p, const char *tail)
{
assert(p != nullptr);
assert(tail != nullptr);
size_t length = strlen(p), tail_length = strlen(tail);
if (length == tail_length)
/* special case: zero-length prefix (not followed by a
slash) */
return memcmp(p, tail, length) == 0
? 0 : (size_t)-1;
return length > tail_length && p[length - tail_length - 1] == '/' &&
memcmp(p + length - tail_length, tail, tail_length) == 0
? length - tail_length
: (size_t)-1;
}
bool
is_base(const char *uri)
{
assert(uri != nullptr);
size_t length = strlen(uri);
return length > 0 && uri[length - 1] == '/';
}
<|endoftext|>
|
<commit_before>/**
* @file uuid.cc
* @author Bartek Kryza
* @copyright (C) 2017 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "uuid.h"
#include "base64.h"
#include <spdlog/fmt/fmt.h>
namespace one {
namespace client {
namespace util {
namespace uuid {
folly::fbstring uuidToSpaceId(const folly::fbstring &uuid)
{
folly::fbstring result;
folly::fbstring decodedUuid;
auto status = util::base64::base64_url_decode(uuid, decodedUuid);
if (status) {
std::vector<folly::StringPiece> v;
folly::split("#", decodedUuid, v);
if ((v[0] != "guid"))
throw std::invalid_argument("Invalid Onedata uuid format.");
auto spaceFragment = v[1];
if (spaceFragment.removePrefix("space_")) {
return spaceFragment.toString();
}
throw std::invalid_argument("Onedata uuid does not contain space id.");
}
throw std::invalid_argument("Base64 decoding of Onedata uuid failed.");
}
folly::fbstring spaceIdToSpaceUUID(const folly::fbstring &spaceId)
{
folly::fbstring result;
util::base64::base64_url_encode(
fmt::format(
"guid#space_{}#{}", spaceId.toStdString(), spaceId.toStdString()),
result);
return result;
}
} // namespace uuid
} // namespace util
} // namespace client
} // namespace one
<commit_msg>VFS-7360 Fixed UUID space_id parser<commit_after>/**
* @file uuid.cc
* @author Bartek Kryza
* @copyright (C) 2017 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "uuid.h"
#include "base64.h"
#include <spdlog/fmt/fmt.h>
namespace one {
namespace client {
namespace util {
namespace uuid {
folly::fbstring uuidToSpaceId(const folly::fbstring &uuid)
{
folly::fbstring result;
folly::fbstring decodedUuid;
auto status = util::base64::base64_url_decode(uuid, decodedUuid);
if (status) {
std::vector<folly::StringPiece> v;
folly::split("#", decodedUuid, v);
if ((v.size() < 3) || (v[0] != "guid" && v[0] != "shareGuid"))
throw std::invalid_argument("Invalid Onedata uuid format.");
return v[2].toString();
}
throw std::invalid_argument("Base64 decoding of Onedata uuid failed.");
}
folly::fbstring spaceIdToSpaceUUID(const folly::fbstring &spaceId)
{
folly::fbstring result;
util::base64::base64_url_encode(
fmt::format(
"guid#space_{}#{}", spaceId.toStdString(), spaceId.toStdString()),
result);
return result;
}
} // namespace uuid
} // namespace util
} // namespace client
} // namespace one
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2012 by INdT
* Copyright (C) 2014 Bacon2D Project
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
* @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
*/
#include "viewport.h"
#include "scene.h"
/*!
\qmltype Viewport
\inqmlmodule Bacon2D
\brief The visible portion of a larger \l Scene.
The Viewport is the visible area of a larger \l Scene and can be scrolled
horizontally or vertically showing different parts of the larger \l Scene.
*/
Viewport::Viewport(Scene *parent)
: Entity(parent)
, m_animationEasingCurve(QEasingCurve::Linear)
, m_xOffset(0.0f)
, m_yOffset(0.0f)
, m_contentWidth(0.0f)
, m_contentHeight(0.0f)
, m_maxXOffset(0.0f)
, m_maxYOffset(0.0f)
, m_scene(parent)
, m_animationDuration(100)
{
m_xGroupAnimation = new QParallelAnimationGroup(this);
m_yGroupAnimation = new QParallelAnimationGroup(this);
}
/*!
\qmlproperty float Viewport::xOffset
\brief This property holds the horizontal offset of the Viewport's x property from the
Scene's x property.
*/
float Viewport::xOffset()
{
return m_xOffset;
}
void Viewport::setXOffset(float xOffset)
{
xOffset = qBound<float>(0.0f, xOffset, m_maxXOffset);
// TODO create a heuristic function to calculate the animation duration
// when m_animationDuration < 0, according to this delta
// (bigger delta -> bigger animation duration)
//qreal delta = qAbs(m_xOffset - xOffset);
if (m_xOffset != xOffset) {
m_xOffset = xOffset;
if (m_scene) {
m_xGroupAnimation->clear();
QPropertyAnimation *xAnim = new QPropertyAnimation(m_scene, "x");
xAnim->setDuration(m_animationDuration); // TODO set duration according the offset value
xAnim->setEasingCurve(m_animationEasingCurve);
xAnim->setStartValue(m_scene->x());
xAnim->setEndValue(-m_xOffset);
m_xGroupAnimation->addAnimation(xAnim);
/* TODO: Fix this according to current layer scheme
QPropertyAnimation *xLayerAnimation = new QPropertyAnimation(m_scene->gameLayers(), "xOffset"); // TODO
xLayerAnimation->setDuration(m_animationDuration); // TODO
xLayerAnimation->setEasingCurve(m_animationEasingCurve);
xLayerAnimation->setStartValue(m_scene->gameLayers()->xOffset());
xLayerAnimation->setEndValue(m_xOffset);
m_xGroupAnimation->addAnimation(xLayerAnimation);
*/
m_xGroupAnimation->start();
}
emit xOffsetChanged();
}
}
/*!
\qmlproperty float Viewport::yOffset
\brief This property holds the vertical offset of the Viewport's y property from the
Scene's y property.
*/
float Viewport::yOffset()
{
return m_yOffset;
}
void Viewport::setYOffset(float yOffset)
{
yOffset = qBound<float>(0.0f, yOffset, m_maxYOffset);
if (m_yOffset != yOffset) {
m_yOffset = yOffset;
if (m_scene) {
m_yGroupAnimation->clear();
QPropertyAnimation *yAnim = new QPropertyAnimation(m_scene, "y");
yAnim->setDuration(m_animationDuration); // TODO set duration according the offset value
yAnim->setEasingCurve(m_animationEasingCurve);
yAnim->setStartValue(m_scene->y());
yAnim->setEndValue(-m_yOffset);
m_yGroupAnimation->addAnimation(yAnim);
/* TODO: Fix this according to current layer scheme
QPropertyAnimation *yLayerAnimation = new QPropertyAnimation(m_scene->gameLayers(), "yOffset"); // TODO
yLayerAnimation->setDuration(m_animationDuration); // TODO
yLayerAnimation->setEasingCurve(m_animationEasingCurve);
yLayerAnimation->setStartValue(m_scene->gameLayers()->yOffset());
yLayerAnimation->setEndValue(m_yOffset);
m_yGroupAnimation->addAnimation(yLayerAnimation);
*/
m_yGroupAnimation->start();
}
emit yOffsetChanged();
}
}
/*!
\qmlmethod Viewport::hScroll(float step)
\brief Scroll the Viewport horizontally by \a step
*/
void Viewport::hScroll(float step)
{
setXOffset(step);
}
/*!
\qmlmethod Viewport::yScroll(float step)
\brief Scroll the Viewport vertically by \a step
*/
void Viewport::vScroll(float step)
{
setYOffset(step);
}
float Viewport::contentWidth() const
{
return m_contentWidth;
}
void Viewport::setContentWidth(const float &contentWidth)
{
if (m_contentWidth != contentWidth) {
m_contentWidth = contentWidth;
emit contentWidthChanged();
}
}
float Viewport::contentHeight() const
{
return m_contentHeight;
}
void Viewport::setContentHeight(const float &contentHeight)
{
if (m_contentHeight != contentHeight) {
m_contentHeight = contentHeight;
emit contentHeightChanged();
}
}
/*!
\qmlproperty int Viewport::animationDuration
\brief Viewport scrolling uses an animation, the animationDuration
property sets the duration in milliseconds of that animation. You can
change this duration for smooth panning of the Viewport. The default
is 100ms.
*/
int Viewport::animationDuration() const
{
return m_animationDuration;
}
void Viewport::setAnimationDuration(const int &animationDuration)
{
if (m_animationDuration != animationDuration) {
m_animationDuration = animationDuration;
emit animationDurationChanged();
}
}
void Viewport::setScene(Scene *scene)
{
m_scene = scene;
scene->setParentItem(this);
setContentWidth(scene->width());
setContentHeight(scene->height());
setVisible(true);
updateMaxOffsets();
}
void Viewport::updateMaxOffsets()
{
m_maxXOffset = m_contentWidth - width();
m_maxYOffset = m_contentHeight - height();
}
<commit_msg>Fixed typo in docstring for Viewport::vScroll<commit_after>/**
* Copyright (C) 2012 by INdT
* Copyright (C) 2014 Bacon2D Project
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
* @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
*/
#include "viewport.h"
#include "scene.h"
/*!
\qmltype Viewport
\inqmlmodule Bacon2D
\brief The visible portion of a larger \l Scene.
The Viewport is the visible area of a larger \l Scene and can be scrolled
horizontally or vertically showing different parts of the larger \l Scene.
*/
Viewport::Viewport(Scene *parent)
: Entity(parent)
, m_animationEasingCurve(QEasingCurve::Linear)
, m_xOffset(0.0f)
, m_yOffset(0.0f)
, m_contentWidth(0.0f)
, m_contentHeight(0.0f)
, m_maxXOffset(0.0f)
, m_maxYOffset(0.0f)
, m_scene(parent)
, m_animationDuration(100)
{
m_xGroupAnimation = new QParallelAnimationGroup(this);
m_yGroupAnimation = new QParallelAnimationGroup(this);
}
/*!
\qmlproperty float Viewport::xOffset
\brief This property holds the horizontal offset of the Viewport's x property from the
Scene's x property.
*/
float Viewport::xOffset()
{
return m_xOffset;
}
void Viewport::setXOffset(float xOffset)
{
xOffset = qBound<float>(0.0f, xOffset, m_maxXOffset);
// TODO create a heuristic function to calculate the animation duration
// when m_animationDuration < 0, according to this delta
// (bigger delta -> bigger animation duration)
//qreal delta = qAbs(m_xOffset - xOffset);
if (m_xOffset != xOffset) {
m_xOffset = xOffset;
if (m_scene) {
m_xGroupAnimation->clear();
QPropertyAnimation *xAnim = new QPropertyAnimation(m_scene, "x");
xAnim->setDuration(m_animationDuration); // TODO set duration according the offset value
xAnim->setEasingCurve(m_animationEasingCurve);
xAnim->setStartValue(m_scene->x());
xAnim->setEndValue(-m_xOffset);
m_xGroupAnimation->addAnimation(xAnim);
/* TODO: Fix this according to current layer scheme
QPropertyAnimation *xLayerAnimation = new QPropertyAnimation(m_scene->gameLayers(), "xOffset"); // TODO
xLayerAnimation->setDuration(m_animationDuration); // TODO
xLayerAnimation->setEasingCurve(m_animationEasingCurve);
xLayerAnimation->setStartValue(m_scene->gameLayers()->xOffset());
xLayerAnimation->setEndValue(m_xOffset);
m_xGroupAnimation->addAnimation(xLayerAnimation);
*/
m_xGroupAnimation->start();
}
emit xOffsetChanged();
}
}
/*!
\qmlproperty float Viewport::yOffset
\brief This property holds the vertical offset of the Viewport's y property from the
Scene's y property.
*/
float Viewport::yOffset()
{
return m_yOffset;
}
void Viewport::setYOffset(float yOffset)
{
yOffset = qBound<float>(0.0f, yOffset, m_maxYOffset);
if (m_yOffset != yOffset) {
m_yOffset = yOffset;
if (m_scene) {
m_yGroupAnimation->clear();
QPropertyAnimation *yAnim = new QPropertyAnimation(m_scene, "y");
yAnim->setDuration(m_animationDuration); // TODO set duration according the offset value
yAnim->setEasingCurve(m_animationEasingCurve);
yAnim->setStartValue(m_scene->y());
yAnim->setEndValue(-m_yOffset);
m_yGroupAnimation->addAnimation(yAnim);
/* TODO: Fix this according to current layer scheme
QPropertyAnimation *yLayerAnimation = new QPropertyAnimation(m_scene->gameLayers(), "yOffset"); // TODO
yLayerAnimation->setDuration(m_animationDuration); // TODO
yLayerAnimation->setEasingCurve(m_animationEasingCurve);
yLayerAnimation->setStartValue(m_scene->gameLayers()->yOffset());
yLayerAnimation->setEndValue(m_yOffset);
m_yGroupAnimation->addAnimation(yLayerAnimation);
*/
m_yGroupAnimation->start();
}
emit yOffsetChanged();
}
}
/*!
\qmlmethod Viewport::hScroll(float step)
\brief Scroll the Viewport horizontally by \a step
*/
void Viewport::hScroll(float step)
{
setXOffset(step);
}
/*!
\qmlmethod Viewport::vScroll(float step)
\brief Scroll the Viewport vertically by \a step
*/
void Viewport::vScroll(float step)
{
setYOffset(step);
}
float Viewport::contentWidth() const
{
return m_contentWidth;
}
void Viewport::setContentWidth(const float &contentWidth)
{
if (m_contentWidth != contentWidth) {
m_contentWidth = contentWidth;
emit contentWidthChanged();
}
}
float Viewport::contentHeight() const
{
return m_contentHeight;
}
void Viewport::setContentHeight(const float &contentHeight)
{
if (m_contentHeight != contentHeight) {
m_contentHeight = contentHeight;
emit contentHeightChanged();
}
}
/*!
\qmlproperty int Viewport::animationDuration
\brief Viewport scrolling uses an animation, the animationDuration
property sets the duration in milliseconds of that animation. You can
change this duration for smooth panning of the Viewport. The default
is 100ms.
*/
int Viewport::animationDuration() const
{
return m_animationDuration;
}
void Viewport::setAnimationDuration(const int &animationDuration)
{
if (m_animationDuration != animationDuration) {
m_animationDuration = animationDuration;
emit animationDurationChanged();
}
}
void Viewport::setScene(Scene *scene)
{
m_scene = scene;
scene->setParentItem(this);
setContentWidth(scene->width());
setContentHeight(scene->height());
setVisible(true);
updateMaxOffsets();
}
void Viewport::updateMaxOffsets()
{
m_maxXOffset = m_contentWidth - width();
m_maxYOffset = m_contentHeight - height();
}
<|endoftext|>
|
<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/http/client/HttpClient.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HeaderFieldList.h>
#include <xzero/net/TcpEndPoint.h>
#include <xzero/executor/NativeScheduler.h>
#include <xzero/net/DnsClient.h>
#include <xzero/io/FileUtil.h>
#include <xzero/Application.h>
#include <xzero/RuntimeError.h>
#include <xzero/Uri.h>
#include <xzero/Flags.h>
#include <xzero/logging.h>
#include <unordered_map>
#include "sysconfig.h"
#include <iostream>
#include <unistd.h>
// #define PACKAGE_VERSION X0_VERSION
#define PACKAGE_HOMEPAGE_URL "https://xzero.io"
#define DEBUG(msg...) logDebug("xurl", msg)
#define TRACE(msg...) logTrace("xurl", msg)
using namespace xzero;
using namespace xzero::http;
using namespace xzero::http::client;
using xzero::http::HttpRequestInfo;
using xzero::http::HttpVersion;
using xzero::http::HeaderField;
class ServicePortMapping { // {{{
public:
ServicePortMapping();
void loadFile(const std::string& path = "/etc/services");
void loadContent(const std::string& content);
int tcp(const std::string& name);
int udp(const std::string& name);
private:
std::unordered_map<std::string, int> tcp_;
std::unordered_map<std::string, int> udp_;
};
ServicePortMapping::ServicePortMapping()
: tcp_() {
tcp_["http"] = 80;
tcp_["https"] = 443;
}
int ServicePortMapping::tcp(const std::string& name) {
auto i = tcp_.find(name);
if (i != tcp_.end())
return i->second;
RAISE(RuntimeError, "Unknown service '%s'", name.c_str());
}
// }}}
class XUrl {
public:
XUrl();
int run(int argc, const char* argv[]);
private:
void addRequestHeader(const std::string& value);
Uri makeUri(const std::string& url);
IPAddress getIPAddress(const std::string& host);
int getPort(const Uri& uri);
void query(const Uri& uri);
private:
NativeScheduler scheduler_;
Flags flags_;
DnsClient dns_;
Duration connectTimeout_;
Duration readTimeout_;
Duration writeTimeout_;
http::HeaderFieldList requestHeaders_;
};
XUrl::XUrl()
: scheduler_(CatchAndLogExceptionHandler("xurl")),
flags_(),
dns_(),
connectTimeout_(4_seconds),
readTimeout_(60_seconds),
writeTimeout_(10_seconds)
{
Application::logToStderr(LogLevel::Info);
requestHeaders_.push_back("User-Agent", "xurl/" PACKAGE_VERSION);
flags_.defineBool("help", 'h', "Prints this help.");
flags_.defineBool("head", 'I', "Performs a HEAD request");
flags_.defineString("output", 'o', "PATH", "Write response body to given file.");
flags_.defineString("log-level", 0, "STRING", "Log level.", "info");
flags_.defineString("method", 'X', "METHOD", "HTTP method", "GET");
flags_.defineNumber("connect-timeout", 0, "MS", "TCP connect() timeout", 10_seconds .milliseconds());
flags_.defineString("upload-file", 'T', "PATH", "Uploads given file.", "");
flags_.defineString("header", 'H', "HEADER", "Adds a custom request header",
None(),
std::bind(&XUrl::addRequestHeader, this, std::placeholders::_1));
flags_.defineBool("ipv4", '4', "Favor IPv4 for TCP/IP communication.");
flags_.defineBool("ipv6", '6', "Favor IPv6 for TCP/IP communication.");
flags_.enableParameters("URL", "URL to query");
}
void XUrl::addRequestHeader(const std::string& field) {
requestHeaders_.push_back(HeaderField::parse(field));
}
int XUrl::run(int argc, const char* argv[]) {
std::error_code ec = flags_.parse(argc, argv);
if (ec) {
fprintf(stderr, "Failed to parse flags. %s\n", ec.message().c_str());
return 1;
}
Logger::get()->setMinimumLogLevel(make_loglevel(flags_.getString("log-level")));
if (flags_.getBool("help")) {
std::cerr
<< "xurl: Xzero HTTP Client" PACKAGE_VERSION
<< " [" PACKAGE_HOMEPAGE_URL "]" << std::endl
<< "Copyright (c) 2009-2017 by Christian Parpart <christian@parpart.family>" << std::endl
<< std::endl
<< "Usage: xurl [options ...]" << std::endl
<< std::endl
<< "Options:" << std::endl
<< flags_.helpText() << std::endl;
return 0;
}
if (flags_.parameters().empty()) {
logError("xurl", "No URL given.");
return 1;
}
if (flags_.parameters().size() != 1) {
logError("xurl", "Too many URLs given.");
}
Uri uri = makeUri(flags_.parameters()[0]);
query(uri);
return 0;
}
Uri XUrl::makeUri(const std::string& url) {
Uri uri(url);
if (uri.path() == "")
uri.setPath("/");
return uri;
}
IPAddress XUrl::getIPAddress(const std::string& host) {
std::vector<IPAddress> ipaddresses = dns_.ipv4(host);
if (ipaddresses.empty())
RAISE(RuntimeError, "Could not resolve %s.", host.c_str());
return ipaddresses.front();
}
int XUrl::getPort(const Uri& uri) {
if (uri.port())
return uri.port();
return ServicePortMapping().tcp(uri.scheme());
}
void XUrl::query(const Uri& uri) {
IPAddress ipaddr = getIPAddress(uri.host());
int port = getPort(uri);
InetAddress inetAddr(ipaddr, port);
Duration keepAlive = 8_seconds;
const bool secure = false; // HTTP ?
TRACE("getting request method");
std::string method = flags_.getString("method");
TRACE("getting request head?");
if (flags_.getBool("head")) {
method = "HEAD";
}
TRACE("getting request body");
HugeBuffer body;
if (!flags_.getString("upload-file").empty()) {
method = "PUT";
body = FileUtil::read(flags_.getString("upload-file"));
}
requestHeaders_.overwrite("Host", uri.hostAndPort());
HttpRequest req(HttpVersion::VERSION_1_1,
method,
uri.pathAndQuery(),
requestHeaders_,
secure,
std::move(body));
logInfo("xurl", "$0 $1 HTTP/$2",
req.unparsedMethod(), req.unparsedUri(), req.version());
for (const HeaderField& field: req.headers()) {
logInfo("xurl", "< $0: $1", field.name(), field.value());
}
HttpClient httpClient(
&scheduler_, inetAddr,
connectTimeout_, readTimeout_, writeTimeout_,
keepAlive);
Future<HttpClient::Response> f = httpClient.send(req);
f.onSuccess([](HttpClient::Response& response) {
logInfo("xurl", "HTTP/$0 $1 $2", response.version(),
(int) response.status(),
response.reason());
for (const HeaderField& field: response.headers()) {
logInfo("xurl", "> $0: $1", field.name(), field.value());
}
const BufferRef& content = response.content().getBuffer();
write(STDOUT_FILENO, content.data(), content.size());
});
f.onFailure([](std::error_code ec) {
logError("xurl", "connect() failed. $0", ec.message());
});
scheduler_.runLoop();
}
int main(int argc, const char* argv[]) {
XUrl app;
return app.run(argc, argv);
}
<commit_msg>[xurl] spacing<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/http/client/HttpClient.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HeaderFieldList.h>
#include <xzero/net/TcpEndPoint.h>
#include <xzero/executor/NativeScheduler.h>
#include <xzero/net/DnsClient.h>
#include <xzero/io/FileUtil.h>
#include <xzero/Application.h>
#include <xzero/RuntimeError.h>
#include <xzero/Uri.h>
#include <xzero/Flags.h>
#include <xzero/logging.h>
#include <unordered_map>
#include "sysconfig.h"
#include <iostream>
#include <unistd.h>
// #define PACKAGE_VERSION X0_VERSION
#define PACKAGE_HOMEPAGE_URL "https://xzero.io"
#define DEBUG(msg...) logDebug("xurl", msg)
#define TRACE(msg...) logTrace("xurl", msg)
using namespace xzero;
using namespace xzero::http;
using namespace xzero::http::client;
using xzero::http::HttpRequestInfo;
using xzero::http::HttpVersion;
using xzero::http::HeaderField;
class ServicePortMapping { // {{{
public:
ServicePortMapping();
void loadFile(const std::string& path = "/etc/services");
void loadContent(const std::string& content);
int tcp(const std::string& name);
int udp(const std::string& name);
private:
std::unordered_map<std::string, int> tcp_;
std::unordered_map<std::string, int> udp_;
};
ServicePortMapping::ServicePortMapping()
: tcp_() {
tcp_["http"] = 80;
tcp_["https"] = 443;
}
int ServicePortMapping::tcp(const std::string& name) {
auto i = tcp_.find(name);
if (i != tcp_.end())
return i->second;
RAISE(RuntimeError, "Unknown service '%s'", name.c_str());
}
// }}}
class XUrl {
public:
XUrl();
int run(int argc, const char* argv[]);
private:
void addRequestHeader(const std::string& value);
Uri makeUri(const std::string& url);
IPAddress getIPAddress(const std::string& host);
int getPort(const Uri& uri);
void query(const Uri& uri);
private:
NativeScheduler scheduler_;
Flags flags_;
DnsClient dns_;
Duration connectTimeout_;
Duration readTimeout_;
Duration writeTimeout_;
http::HeaderFieldList requestHeaders_;
};
XUrl::XUrl()
: scheduler_(CatchAndLogExceptionHandler("xurl")),
flags_(),
dns_(),
connectTimeout_(4_seconds),
readTimeout_(60_seconds),
writeTimeout_(10_seconds)
{
Application::logToStderr(LogLevel::Info);
requestHeaders_.push_back("User-Agent", "xurl/" PACKAGE_VERSION);
flags_.defineBool("help", 'h', "Prints this help.");
flags_.defineBool("head", 'I', "Performs a HEAD request");
flags_.defineString("output", 'o', "PATH", "Write response body to given file.");
flags_.defineString("log-level", 0, "STRING", "Log level.", "info");
flags_.defineString("method", 'X', "METHOD", "HTTP method", "GET");
flags_.defineNumber("connect-timeout", 0, "MS", "TCP connect() timeout", 10_seconds .milliseconds());
flags_.defineString("upload-file", 'T', "PATH", "Uploads given file.", "");
flags_.defineString("header", 'H', "HEADER", "Adds a custom request header",
None(),
std::bind(&XUrl::addRequestHeader, this, std::placeholders::_1));
flags_.defineBool("ipv4", '4', "Favor IPv4 for TCP/IP communication.");
flags_.defineBool("ipv6", '6', "Favor IPv6 for TCP/IP communication.");
flags_.enableParameters("URL", "URL to query");
}
void XUrl::addRequestHeader(const std::string& field) {
requestHeaders_.push_back(HeaderField::parse(field));
}
int XUrl::run(int argc, const char* argv[]) {
std::error_code ec = flags_.parse(argc, argv);
if (ec) {
fprintf(stderr, "Failed to parse flags. %s\n", ec.message().c_str());
return 1;
}
Logger::get()->setMinimumLogLevel(make_loglevel(flags_.getString("log-level")));
if (flags_.getBool("help")) {
std::cerr
<< "xurl: Xzero HTTP Client" PACKAGE_VERSION
<< " [" PACKAGE_HOMEPAGE_URL "]" << std::endl
<< "Copyright (c) 2009-2017 by Christian Parpart <christian@parpart.family>" << std::endl
<< std::endl
<< "Usage: xurl [options ...]" << std::endl
<< std::endl
<< "Options:" << std::endl
<< flags_.helpText() << std::endl;
return 0;
}
if (flags_.parameters().empty()) {
logError("xurl", "No URL given.");
return 1;
}
if (flags_.parameters().size() != 1) {
logError("xurl", "Too many URLs given.");
}
Uri uri = makeUri(flags_.parameters()[0]);
query(uri);
return 0;
}
Uri XUrl::makeUri(const std::string& url) {
Uri uri(url);
if (uri.path() == "")
uri.setPath("/");
return uri;
}
IPAddress XUrl::getIPAddress(const std::string& host) {
std::vector<IPAddress> ipaddresses = dns_.ipv4(host);
if (ipaddresses.empty())
RAISE(RuntimeError, "Could not resolve %s.", host.c_str());
return ipaddresses.front();
}
int XUrl::getPort(const Uri& uri) {
if (uri.port())
return uri.port();
return ServicePortMapping().tcp(uri.scheme());
}
void XUrl::query(const Uri& uri) {
IPAddress ipaddr = getIPAddress(uri.host());
int port = getPort(uri);
InetAddress inetAddr(ipaddr, port);
Duration keepAlive = 8_seconds;
const bool secure = false; // HTTP ?
TRACE("getting request method");
std::string method = flags_.getString("method");
TRACE("getting request head?");
if (flags_.getBool("head")) {
method = "HEAD";
}
TRACE("getting request body");
HugeBuffer body;
if (!flags_.getString("upload-file").empty()) {
method = "PUT";
body = FileUtil::read(flags_.getString("upload-file"));
}
requestHeaders_.overwrite("Host", uri.hostAndPort());
HttpRequest req(HttpVersion::VERSION_1_1,
method,
uri.pathAndQuery(),
requestHeaders_,
secure,
std::move(body));
logInfo("xurl", "$0 $1 HTTP/$2",
req.unparsedMethod(), req.unparsedUri(), req.version());
for (const HeaderField& field: req.headers()) {
logInfo("xurl", "< $0: $1", field.name(), field.value());
}
HttpClient httpClient(&scheduler_, inetAddr,
connectTimeout_, readTimeout_, writeTimeout_,
keepAlive);
Future<HttpClient::Response> f = httpClient.send(req);
f.onSuccess([](HttpClient::Response& response) {
logInfo("xurl", "HTTP/$0 $1 $2", response.version(),
(int) response.status(),
response.reason());
for (const HeaderField& field: response.headers()) {
logInfo("xurl", "> $0: $1", field.name(), field.value());
}
const BufferRef& content = response.content().getBuffer();
write(STDOUT_FILENO, content.data(), content.size());
});
f.onFailure([](std::error_code ec) {
logError("xurl", "connect() failed. $0", ec.message());
});
scheduler_.runLoop();
}
int main(int argc, const char* argv[]) {
XUrl app;
return app.run(argc, argv);
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "stx/application.h"
#include "stx/logging.h"
#include "stx/random.h"
#include "stx/thread/eventloop.h"
#include "stx/thread/threadpool.h"
#include "stx/thread/FixedSizeThreadPool.h"
#include "stx/io/TerminalOutputStream.h"
#include "stx/wallclock.h"
#include "stx/json/json.h"
#include "stx/json/jsonrpc.h"
#include "stx/http/httpclient.h"
#include "stx/http/HTTPSSEResponseHandler.h"
#include "stx/cli/CLI.h"
#include "stx/cli/flagparser.h"
#include "stx/cli/term.h"
using namespace stx;
stx::thread::EventLoop ev;
String loadAuth(const cli::FlagParser& global_flags) {
auto auth_file_path = FileUtil::joinPaths(getenv("HOME"), ".z1auth");
if (FileUtil::exists(auth_file_path)) {
return FileUtil::read(auth_file_path).toString();
} else {
if (global_flags.isSet("auth_token")) {
return global_flags.getString("auth_token");
} else {
RAISE(
kRuntimeError,
"no auth token found - you must either call 'zli login' or pass the "
"--auth_token flag");
}
}
}
void cmd_run(
const cli::FlagParser& global_flags,
const cli::FlagParser& cmd_flags) {
const auto& argv = cmd_flags.getArgv();
if (argv.size() != 1) {
RAISE(kUsageError, "usage: $ zli run <script.js>");
}
if (!(StringUtil::endsWith(argv[0], "js") ||
StringUtil::endsWith(argv[0], "sql"))) {
RAISE(kUsageError, "unsupported file format");
}
auto stdout_os = OutputStream::getStdout();
auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());
try {
auto program_source = FileUtil::read(argv[0]);
bool finished = false;
bool error = false;
String error_string;
bool line_dirty = false;
bool is_tty = stderr_os->isTTY();
auto event_handler = [&] (const http::HTTPSSEEvent& ev) {
if (ev.name.isEmpty()) {
return;
}
if (ev.name.get() == "status") {
auto obj = json::parseJSON(ev.data);
auto tasks_completed = json::objectGetUInt64(obj, "num_tasks_completed");
auto tasks_total = json::objectGetUInt64(obj, "num_tasks_total");
auto tasks_running = json::objectGetUInt64(obj, "num_tasks_running");
auto progress = json::objectGetFloat(obj, "progress");
auto status_line = StringUtil::format(
"[$0/$1] $2 tasks running ($3%)",
tasks_completed.isEmpty() ? 0 : tasks_completed.get(),
tasks_total.isEmpty() ? 0 : tasks_total.get(),
tasks_running.isEmpty() ? 0 : tasks_running.get(),
progress.isEmpty() ? 0 : progress.get() * 100);
if (is_tty) {
stderr_os->eraseLine();
stderr_os->print("\r" + status_line);
line_dirty = true;
} else {
stderr_os->print(status_line + "\n");
}
return;
}
if (line_dirty) {
stderr_os->eraseLine();
stderr_os->print("\r");
line_dirty = false;
}
if (ev.name.get() == "job_started") {
//stderr_os->printYellow(">> Job started\n");
return;
}
if (ev.name.get() == "job_finished") {
finished = true;
return;
}
if (ev.name.get() == "error") {
error = true;
error_string = URI::urlDecode(ev.data);
return;
}
if (ev.name.get() == "result") {
stdout_os->write(URI::urlDecode(ev.data));
return;
}
if (ev.name.get() == "log") {
stderr_os->print(URI::urlDecode(ev.data) + "\n");
return;
}
};
std::string url;
//run mapreduce
if (StringUtil::endsWith(argv[0], "js")) {
url = StringUtil::format(
"http://$0/api/v1/mapreduce/execute",
global_flags.getString("api_host"));
}
//run sql query
if (StringUtil::endsWith(argv[0], "sql")) {
url = StringUtil::format(
"http://$0/api/v1/sql_stream?query=$1",
global_flags.getString("api_host"),
URI::urlEncode(program_source.toString()));
program_source.clear();
}
auto auth_token = loadAuth(global_flags);
http::HTTPMessage::HeaderList auth_headers;
auth_headers.emplace_back(
"Authorization",
StringUtil::format("Token $0", auth_token));
if (is_tty) {
stderr_os->print("Launching job...");
line_dirty = true;
} else {
stderr_os->print("Launching job...\n");
}
http::HTTPClient http_client;
auto req = http::HTTPRequest::mkPost(url, program_source, auth_headers);
auto res = http_client.executeRequest(
req,
http::HTTPSSEResponseHandler::getFactory(event_handler));
if (line_dirty) {
stderr_os->eraseLine();
stderr_os->print("\r");
}
if (res.statusCode() != 200) {
error = true;
error_string = "HTTP Error: " + res.body().toString();
}
if (!finished && !error) {
error = true;
error_string = "connection to server lost";
}
if (error) {
stderr_os->print(
"ERROR:",
{ TerminalStyle::RED, TerminalStyle::UNDERSCORE });
stderr_os->print(" " + error_string + "\n");
exit(1);
} else {
stderr_os->printGreen("Job successfully completed\n");
exit(0);
}
} catch (const StandardException& e) {
stderr_os->print(
"ERROR:",
{ TerminalStyle::RED, TerminalStyle::UNDERSCORE });
stderr_os->print(StringUtil::format(" $0\n", e.what()));
exit(1);
}
}
void cmd_login(
const cli::FlagParser& global_flags,
const cli::FlagParser& cmd_flags) {
Term term;
term.print(">> Username: ");
auto username = term.readLine();
term.print(">> Password (will not be echoed): ");
auto password = term.readPassword();
term.print("\n");
try {
auto url = StringUtil::format(
"http://$0/api/v1/auth/login",
global_flags.getString("api_host"));
auto authdata = StringUtil::format(
"userid=$0&password=$1",
URI::urlEncode(username),
URI::urlEncode(password));
http::HTTPClient http_client;
auto req = http::HTTPRequest::mkPost(url, authdata);
auto res = http_client.executeRequest(req);
switch (res.statusCode()) {
case 200: {
auto json = json::parseJSON(res.body());
auto auth_token = json::objectGetString(json, "auth_token");
if (!auth_token.isEmpty()) {
{
auto auth_file_path = FileUtil::joinPaths(getenv("HOME"), ".z1auth");
auto file = File::openFile(
auth_file_path,
File::O_WRITE | File::O_CREATEOROPEN | File::O_TRUNCATE);
file.write(auth_token.get());
}
term.printGreen("Login successful\n");
exit(0);
}
/* fallthrough */
}
case 401: {
term.printRed("Invalid credentials, please try again\n");
exit(1);
}
default:
RAISEF(kRuntimeError, "HTTP Error: $0", res.body().toString());
}
} catch (const StandardException& e) {
term.print("ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE });
term.print(StringUtil::format(" $0\n", e.what()));
exit(1);
}
}
void cmd_version(
const cli::FlagParser& global_flags,
const cli::FlagParser& cmd_flags) {
auto stdout_os = OutputStream::getStdout();
stdout_os->write("zli v0.0.1\n");
}
int main(int argc, const char** argv) {
stx::Application::init();
stx::Application::logToStderr();
stx::cli::FlagParser flags;
flags.defineFlag(
"api_host",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"api.zscale.io",
"api host",
"<host>");
flags.defineFlag(
"auth_token",
stx::cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"auth token",
"<token>");
flags.defineFlag(
"loglevel",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
cli::CLI cli;
/* command: run */
auto run_cmd = cli.defineCommand("run");
run_cmd->onCall(std::bind(&cmd_run, flags, std::placeholders::_1));
/* command: login */
auto login_cmd = cli.defineCommand("login");
login_cmd->onCall(std::bind(&cmd_login, flags, std::placeholders::_1));
/* command: version */
auto version_cmd = cli.defineCommand("version");
version_cmd->onCall(std::bind(&cmd_version, flags, std::placeholders::_1));
//mr_execute_cmd->flags().defineFlag(
// "api_host",
// stx::cli::FlagParser::T_STRING,
// false,
// NULL,
// "api.zscale.io",
// "api host",
// "<host>");
cli.call(flags.getArgv());
return 0;
}
<commit_msg>zli: split run into runJS and runSQL<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "stx/application.h"
#include "stx/logging.h"
#include "stx/random.h"
#include "stx/thread/eventloop.h"
#include "stx/thread/threadpool.h"
#include "stx/thread/FixedSizeThreadPool.h"
#include "stx/io/TerminalOutputStream.h"
#include "stx/wallclock.h"
#include "stx/json/json.h"
#include "stx/json/jsonrpc.h"
#include "stx/http/httpclient.h"
#include "stx/http/HTTPSSEResponseHandler.h"
#include "stx/cli/CLI.h"
#include "stx/cli/flagparser.h"
#include "stx/cli/term.h"
using namespace stx;
stx::thread::EventLoop ev;
String loadAuth(const cli::FlagParser& global_flags) {
auto auth_file_path = FileUtil::joinPaths(getenv("HOME"), ".z1auth");
if (FileUtil::exists(auth_file_path)) {
return FileUtil::read(auth_file_path).toString();
} else {
if (global_flags.isSet("auth_token")) {
return global_flags.getString("auth_token");
} else {
RAISE(
kRuntimeError,
"no auth token found - you must either call 'zli login' or pass the "
"--auth_token flag");
}
}
}
void runJS(
const cli::FlagParser& global_flags,
const String& file) {
auto stdout_os = OutputStream::getStdout();
auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());
try {
auto program_source = FileUtil::read(file);
bool finished = false;
bool error = false;
String error_string;
bool line_dirty = false;
bool is_tty = stderr_os->isTTY();
auto event_handler = [&] (const http::HTTPSSEEvent& ev) {
if (ev.name.isEmpty()) {
return;
}
if (ev.name.get() == "status") {
auto obj = json::parseJSON(ev.data);
auto tasks_completed = json::objectGetUInt64(obj, "num_tasks_completed");
auto tasks_total = json::objectGetUInt64(obj, "num_tasks_total");
auto tasks_running = json::objectGetUInt64(obj, "num_tasks_running");
auto progress = json::objectGetFloat(obj, "progress");
auto status_line = StringUtil::format(
"[$0/$1] $2 tasks running ($3%)",
tasks_completed.isEmpty() ? 0 : tasks_completed.get(),
tasks_total.isEmpty() ? 0 : tasks_total.get(),
tasks_running.isEmpty() ? 0 : tasks_running.get(),
progress.isEmpty() ? 0 : progress.get() * 100);
if (is_tty) {
stderr_os->eraseLine();
stderr_os->print("\r" + status_line);
line_dirty = true;
} else {
stderr_os->print(status_line + "\n");
}
return;
}
if (line_dirty) {
stderr_os->eraseLine();
stderr_os->print("\r");
line_dirty = false;
}
if (ev.name.get() == "job_started") {
//stderr_os->printYellow(">> Job started\n");
return;
}
if (ev.name.get() == "job_finished") {
finished = true;
return;
}
if (ev.name.get() == "error") {
error = true;
error_string = URI::urlDecode(ev.data);
return;
}
if (ev.name.get() == "result") {
stdout_os->write(URI::urlDecode(ev.data));
return;
}
if (ev.name.get() == "log") {
stderr_os->print(URI::urlDecode(ev.data) + "\n");
return;
}
};
auto url = StringUtil::format(
"http://$0/api/v1/mapreduce/execute",
global_flags.getString("api_host"));
auto auth_token = loadAuth(global_flags);
http::HTTPMessage::HeaderList auth_headers;
auth_headers.emplace_back(
"Authorization",
StringUtil::format("Token $0", auth_token));
if (is_tty) {
stderr_os->print("Launching job...");
line_dirty = true;
} else {
stderr_os->print("Launching job...\n");
}
http::HTTPClient http_client;
auto req = http::HTTPRequest::mkPost(url, program_source, auth_headers);
auto res = http_client.executeRequest(
req,
http::HTTPSSEResponseHandler::getFactory(event_handler));
if (line_dirty) {
stderr_os->eraseLine();
stderr_os->print("\r");
}
if (res.statusCode() != 200) {
error = true;
error_string = "HTTP Error: " + res.body().toString();
}
if (!finished && !error) {
error = true;
error_string = "connection to server lost";
}
if (error) {
stderr_os->print(
"ERROR:",
{ TerminalStyle::RED, TerminalStyle::UNDERSCORE });
stderr_os->print(" " + error_string + "\n");
exit(1);
} else {
stderr_os->printGreen("Job successfully completed\n");
exit(0);
}
} catch (const StandardException& e) {
stderr_os->print(
"ERROR:",
{ TerminalStyle::RED, TerminalStyle::UNDERSCORE });
stderr_os->print(StringUtil::format(" $0\n", e.what()));
exit(1);
}
}
void runSQL(const String& file) {
auto stdout_os = OutputStream::getStdout();
auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());
stderr_os->printGreen("run SQL");
}
void cmd_run(
const cli::FlagParser& global_flags,
const cli::FlagParser& cmd_flags) {
const auto& argv = cmd_flags.getArgv();
if (argv.size() != 1) {
RAISE(kUsageError, "usage: $ zli run <script.js>");
}
if (StringUtil::endsWith(argv[0], "js")) {
runJS(global_flags, argv[0]);
return;
}
if (StringUtil::endsWith(argv[0], "sql")) {
runSQL(argv[0]);
return;
}
RAISE(kUsageError, "unsupported file format");
}
void cmd_login(
const cli::FlagParser& global_flags,
const cli::FlagParser& cmd_flags) {
Term term;
term.print(">> Username: ");
auto username = term.readLine();
term.print(">> Password (will not be echoed): ");
auto password = term.readPassword();
term.print("\n");
try {
auto url = StringUtil::format(
"http://$0/api/v1/auth/login",
global_flags.getString("api_host"));
auto authdata = StringUtil::format(
"userid=$0&password=$1",
URI::urlEncode(username),
URI::urlEncode(password));
http::HTTPClient http_client;
auto req = http::HTTPRequest::mkPost(url, authdata);
auto res = http_client.executeRequest(req);
switch (res.statusCode()) {
case 200: {
auto json = json::parseJSON(res.body());
auto auth_token = json::objectGetString(json, "auth_token");
if (!auth_token.isEmpty()) {
{
auto auth_file_path = FileUtil::joinPaths(getenv("HOME"), ".z1auth");
auto file = File::openFile(
auth_file_path,
File::O_WRITE | File::O_CREATEOROPEN | File::O_TRUNCATE);
file.write(auth_token.get());
}
term.printGreen("Login successful\n");
exit(0);
}
/* fallthrough */
}
case 401: {
term.printRed("Invalid credentials, please try again\n");
exit(1);
}
default:
RAISEF(kRuntimeError, "HTTP Error: $0", res.body().toString());
}
} catch (const StandardException& e) {
term.print("ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE });
term.print(StringUtil::format(" $0\n", e.what()));
exit(1);
}
}
void cmd_version(
const cli::FlagParser& global_flags,
const cli::FlagParser& cmd_flags) {
auto stdout_os = OutputStream::getStdout();
stdout_os->write("zli v0.0.1\n");
}
int main(int argc, const char** argv) {
stx::Application::init();
stx::Application::logToStderr();
stx::cli::FlagParser flags;
flags.defineFlag(
"api_host",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"api.zscale.io",
"api host",
"<host>");
flags.defineFlag(
"auth_token",
stx::cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"auth token",
"<token>");
flags.defineFlag(
"loglevel",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
cli::CLI cli;
/* command: run */
auto run_cmd = cli.defineCommand("run");
run_cmd->onCall(std::bind(&cmd_run, flags, std::placeholders::_1));
/* command: login */
auto login_cmd = cli.defineCommand("login");
login_cmd->onCall(std::bind(&cmd_login, flags, std::placeholders::_1));
/* command: version */
auto version_cmd = cli.defineCommand("version");
version_cmd->onCall(std::bind(&cmd_version, flags, std::placeholders::_1));
//mr_execute_cmd->flags().defineFlag(
// "api_host",
// stx::cli::FlagParser::T_STRING,
// false,
// NULL,
// "api.zscale.io",
// "api host",
// "<host>");
cli.call(flags.getArgv());
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <utility>
namespace zbs {
template <typename T> class func;
template <typename R, typename ...Args>
class func<R (Args...)> {
static R _invoke_func(void *data, Args &&...args) {
auto fp = reinterpret_cast<R (*)(Args...)>(data);
return (*fp)(std::forward<Args>(args)...);
}
template <typename T>
static R _invoke_obj(void *data, Args &&...args) {
auto obj = reinterpret_cast<T*>(data);
return (*obj)(std::forward<Args>(args)...);
}
template <typename T>
static R _invoke_const_obj(void *data, Args &&...args) {
auto obj = reinterpret_cast<const T*>(data);
return (*obj)(std::forward<Args>(args)...);
}
R (*_invoker)(void*, Args&&...);
void *_data;
public:
template <typename T>
func(T &obj): _invoker(_invoke_obj<T>),
_data(reinterpret_cast<void*>(&obj)) {}
template <typename T>
func(const T &obj): _invoker(_invoke_const_obj<T>),
_data(reinterpret_cast<void*>(const_cast<T*>(&obj))) {}
func(R (*fp)(Args...)): _invoker(_invoke_func),
_data(reinterpret_cast<void*>(fp)) {}
func(const func&) = default;
func(func&&) = default;
func &operator=(const func&) = default;
func &operator=(func&&) = default;
R operator()(Args ...args) const {
return (*_invoker)(_data, std::forward<Args>(args)...);
}
};
} // namespace zbs
<commit_msg>Replace unnecessary reinterpret_casts with static_cast.<commit_after>#pragma once
#include <utility>
namespace zbs {
template <typename T> class func;
template <typename R, typename ...Args>
class func<R (Args...)> {
static R _invoke_func(void *data, Args &&...args) {
auto fp = reinterpret_cast<R (*)(Args...)>(data);
return (*fp)(std::forward<Args>(args)...);
}
template <typename T>
static R _invoke_obj(void *data, Args &&...args) {
auto obj = static_cast<T*>(data);
return (*obj)(std::forward<Args>(args)...);
}
template <typename T>
static R _invoke_const_obj(void *data, Args &&...args) {
auto obj = static_cast<const T*>(data);
return (*obj)(std::forward<Args>(args)...);
}
R (*_invoker)(void*, Args&&...);
void *_data;
public:
template <typename T>
func(T &obj): _invoker(_invoke_obj<T>),
_data(static_cast<void*>(&obj)) {}
template <typename T>
func(const T &obj): _invoker(_invoke_const_obj<T>),
_data(static_cast<void*>(const_cast<T*>(&obj))) {}
func(R (*fp)(Args...)): _invoker(_invoke_func),
_data(reinterpret_cast<void*>(fp)) {}
func(const func&) = default;
func(func&&) = default;
func &operator=(const func&) = default;
func &operator=(func&&) = default;
R operator()(Args ...args) const {
return (*_invoker)(_data, std::forward<Args>(args)...);
}
};
} // namespace zbs
<|endoftext|>
|
<commit_before>#ifndef SUCCINCT_GRAPH_SG_HPP
#define SUCCINCT_GRAPH_SG_HPP
#include <iostream>
#include <fstream>
#include <map>
#include "cpp/vg.pb.h"
#include "sdsl/bit_vectors.hpp"
#include "sdsl/enc_vector.hpp"
#include "sdsl/dac_vector.hpp"
#include "sdsl/vlc_vector.hpp"
#include "sdsl/wavelet_trees.hpp"
//#include "sdsl/csa_bitcompressed.hpp"
#include "sdsl/csa_wt.hpp"
#include "sdsl/suffix_arrays.hpp"
namespace xg {
using namespace std;
using namespace sdsl;
using namespace vg;
class Traversal {
public:
int64_t id;
bool rev;
Traversal(int64_t i, bool r) : id(i), rev(r) { }
};
class XGPath;
typedef pair<int64_t, bool> Side;
class XG {
public:
XG(void) : start_marker('#'),
end_marker('$'),
seq_length(0),
node_count(0),
edge_count(0),
path_count(0) { }
~XG(void) { }
XG(istream& in);
void from_vg(istream& in, bool print_graph = false);
void load(istream& in);
size_t serialize(std::ostream& out,
sdsl::structure_tree_node* v = NULL,
std::string name = "");
size_t seq_length;
size_t node_count;
size_t edge_count;
size_t path_count;
/*
required API to integrate with vg
metadata:
index->name
ranges:
index->get_range(first, last, *graph);
index->expand_context(*graph, context_step);
index->get_connected_nodes(*graph);
*/
size_t id_to_rank(int64_t id);
int64_t rank_to_id(size_t rank);
size_t max_node_rank(void);
Node node(int64_t id); // gets node sequence
string node_sequence(int64_t id);
vector<Edge> edges_to(int64_t id);
vector<Edge> edges_from(int64_t id);
size_t node_rank_as_entity(int64_t id);
size_t edge_rank_as_entity(int64_t id1, int64_t id2);
bool entity_is_node(size_t rank);
size_t entity_rank_as_node_rank(size_t rank);
bool has_edge(int64_t id1, int64_t id2);
Path path(const string& name);
size_t path_rank(const string& name);
size_t max_path_rank(void);
string path_name(size_t rank);
vector<size_t> paths_of_entity(size_t rank);
vector<size_t> paths_of_node(int64_t id);
vector<size_t> paths_of_edge(int64_t id1, int64_t id2);
map<string, Mapping> node_mappings(int64_t id);
bool path_contains_node(const string& name, int64_t id);
bool path_contains_edge(const string& name, int64_t id1, int64_t id2);
bool path_contains_entity(const string& name, size_t rank);
void add_paths_to_graph(map<int64_t, Node*>& nodes, Graph& g);
size_t node_occs_in_path(int64_t id, const string& name);
size_t node_position_in_path(int64_t id, const string& name);
int64_t node_at_path_position(const string& name, size_t pos);
size_t path_length(const string& name);
void neighborhood(int64_t id, size_t steps, Graph& g);
//void for_path_range(string& name, int64_t start, int64_t stop, function<void(Node)> lambda);
void get_path_range(string& name, int64_t start, int64_t stop, Graph& g);
void expand_context(Graph& g, size_t steps);
void get_connected_nodes(Graph& g);
void get_id_range(int64_t id1, int64_t id2, Graph& g);
char start_marker;
char end_marker;
private:
// sequence/integer vector
int_vector<> s_iv;
// node starts in sequence, provides id schema
// rank_1(i) = id
// select_1(id) = i
bit_vector s_bv; // node positions in siv
rank_support_v<1> s_bv_rank;
bit_vector::select_1_type s_bv_select;
// compressed version, unused...
rrr_vector<> s_cbv;
rrr_vector<>::rank_1_type s_cbv_rank;
rrr_vector<>::select_1_type s_cbv_select;
// maintain old ids from input, ranked as in s_iv and s_bv
int_vector<> i_iv;
// maintain forward links
int_vector<> f_iv;
bit_vector f_bv;
rank_support_v<1> f_bv_rank;
bit_vector::select_1_type f_bv_select;
bit_vector f_from_start_bv;
bit_vector f_to_end_bv;
sd_vector<> f_from_start_cbv;
sd_vector<> f_to_end_cbv;
// and the same data in the reverse direction
int_vector<> t_iv;
bit_vector t_bv;
rank_support_v<1> t_bv_rank;
bit_vector::select_1_type t_bv_select;
// these bit vectors are only used during construction
// perhaps they should be moved?
bit_vector t_from_start_bv;
bit_vector t_to_end_bv;
// used at runtime
sd_vector<> t_from_start_cbv;
sd_vector<> t_to_end_cbv;
// edge table, allows o(1) determination of edge existence
int_vector<> e_iv;
//csa_wt<> e_csa;
csa_sada<> e_csa;
// allows lookups of id->rank mapping
wt_int<> i_wt;
// paths: serialized as bitvectors over nodes and edges
int_vector<> pn_iv; // path names
csa_wt<> pn_csa; // path name compressed suffix array
bit_vector pn_bv; // path name starts in uncompressed version of csa
rank_support_v<1> pn_bv_rank;
bit_vector::select_1_type pn_bv_select;
int_vector<> pi_iv; // path ids by rank in the path names
// probably these should get compressed, for when we have whole genomes with many chromosomes
// the growth in required memory is quadratic but the stored matrix is sparse
vector<XGPath*> paths; // path entity membership
// entity->path membership
int_vector<> ep_iv;
bit_vector ep_bv; // entity delimiters in ep_iv
rank_support_v<1> ep_bv_rank;
bit_vector::select_1_type ep_bv_select;
};
class XGPath {
public:
XGPath(void) : member_count(0) { }
~XGPath(void) { }
XGPath(const string& path_name,
const vector<Traversal>& path,
size_t entity_count,
XG& graph,
map<int64_t, string>& node_label);
string name;
size_t member_count;
sd_vector<> members;
wt_int<> ids;
sd_vector<> directions; // forward or backward through nodes
int_vector<> positions;
bit_vector offsets;
rank_support_v<1> offsets_rank;
bit_vector::select_1_type offsets_select;
void load(istream& in);
size_t serialize(std::ostream& out,
sdsl::structure_tree_node* v = NULL,
std::string name = "");
};
Mapping new_mapping(const string& name, int64_t id);
void parse_region(const string& target, string& name, int64_t& start, int64_t& end);
void to_text(ostream& out, Graph& graph);
}
#endif
<commit_msg>we have now matched the API used in vg<commit_after>#ifndef SUCCINCT_GRAPH_SG_HPP
#define SUCCINCT_GRAPH_SG_HPP
#include <iostream>
#include <fstream>
#include <map>
#include "cpp/vg.pb.h"
#include "sdsl/bit_vectors.hpp"
#include "sdsl/enc_vector.hpp"
#include "sdsl/dac_vector.hpp"
#include "sdsl/vlc_vector.hpp"
#include "sdsl/wavelet_trees.hpp"
//#include "sdsl/csa_bitcompressed.hpp"
#include "sdsl/csa_wt.hpp"
#include "sdsl/suffix_arrays.hpp"
namespace xg {
using namespace std;
using namespace sdsl;
using namespace vg;
class Traversal {
public:
int64_t id;
bool rev;
Traversal(int64_t i, bool r) : id(i), rev(r) { }
};
class XGPath;
typedef pair<int64_t, bool> Side;
class XG {
public:
XG(void) : start_marker('#'),
end_marker('$'),
seq_length(0),
node_count(0),
edge_count(0),
path_count(0) { }
~XG(void) { }
XG(istream& in);
void from_vg(istream& in, bool print_graph = false);
void load(istream& in);
size_t serialize(std::ostream& out,
sdsl::structure_tree_node* v = NULL,
std::string name = "");
size_t seq_length;
size_t node_count;
size_t edge_count;
size_t path_count;
size_t id_to_rank(int64_t id);
int64_t rank_to_id(size_t rank);
size_t max_node_rank(void);
Node node(int64_t id); // gets node sequence
string node_sequence(int64_t id);
vector<Edge> edges_to(int64_t id);
vector<Edge> edges_from(int64_t id);
size_t node_rank_as_entity(int64_t id);
size_t edge_rank_as_entity(int64_t id1, int64_t id2);
bool entity_is_node(size_t rank);
size_t entity_rank_as_node_rank(size_t rank);
bool has_edge(int64_t id1, int64_t id2);
Path path(const string& name);
size_t path_rank(const string& name);
size_t max_path_rank(void);
string path_name(size_t rank);
vector<size_t> paths_of_entity(size_t rank);
vector<size_t> paths_of_node(int64_t id);
vector<size_t> paths_of_edge(int64_t id1, int64_t id2);
map<string, Mapping> node_mappings(int64_t id);
bool path_contains_node(const string& name, int64_t id);
bool path_contains_edge(const string& name, int64_t id1, int64_t id2);
bool path_contains_entity(const string& name, size_t rank);
void add_paths_to_graph(map<int64_t, Node*>& nodes, Graph& g);
size_t node_occs_in_path(int64_t id, const string& name);
size_t node_position_in_path(int64_t id, const string& name);
int64_t node_at_path_position(const string& name, size_t pos);
size_t path_length(const string& name);
void neighborhood(int64_t id, size_t steps, Graph& g);
//void for_path_range(string& name, int64_t start, int64_t stop, function<void(Node)> lambda);
void get_path_range(string& name, int64_t start, int64_t stop, Graph& g);
void expand_context(Graph& g, size_t steps);
void get_connected_nodes(Graph& g);
void get_id_range(int64_t id1, int64_t id2, Graph& g);
char start_marker;
char end_marker;
private:
// sequence/integer vector
int_vector<> s_iv;
// node starts in sequence, provides id schema
// rank_1(i) = id
// select_1(id) = i
bit_vector s_bv; // node positions in siv
rank_support_v<1> s_bv_rank;
bit_vector::select_1_type s_bv_select;
// compressed version, unused...
rrr_vector<> s_cbv;
rrr_vector<>::rank_1_type s_cbv_rank;
rrr_vector<>::select_1_type s_cbv_select;
// maintain old ids from input, ranked as in s_iv and s_bv
int_vector<> i_iv;
// maintain forward links
int_vector<> f_iv;
bit_vector f_bv;
rank_support_v<1> f_bv_rank;
bit_vector::select_1_type f_bv_select;
bit_vector f_from_start_bv;
bit_vector f_to_end_bv;
sd_vector<> f_from_start_cbv;
sd_vector<> f_to_end_cbv;
// and the same data in the reverse direction
int_vector<> t_iv;
bit_vector t_bv;
rank_support_v<1> t_bv_rank;
bit_vector::select_1_type t_bv_select;
// these bit vectors are only used during construction
// perhaps they should be moved?
bit_vector t_from_start_bv;
bit_vector t_to_end_bv;
// used at runtime
sd_vector<> t_from_start_cbv;
sd_vector<> t_to_end_cbv;
// edge table, allows o(1) determination of edge existence
int_vector<> e_iv;
//csa_wt<> e_csa;
csa_sada<> e_csa;
// allows lookups of id->rank mapping
wt_int<> i_wt;
// paths: serialized as bitvectors over nodes and edges
int_vector<> pn_iv; // path names
csa_wt<> pn_csa; // path name compressed suffix array
bit_vector pn_bv; // path name starts in uncompressed version of csa
rank_support_v<1> pn_bv_rank;
bit_vector::select_1_type pn_bv_select;
int_vector<> pi_iv; // path ids by rank in the path names
// probably these should get compressed, for when we have whole genomes with many chromosomes
// the growth in required memory is quadratic but the stored matrix is sparse
vector<XGPath*> paths; // path entity membership
// entity->path membership
int_vector<> ep_iv;
bit_vector ep_bv; // entity delimiters in ep_iv
rank_support_v<1> ep_bv_rank;
bit_vector::select_1_type ep_bv_select;
};
class XGPath {
public:
XGPath(void) : member_count(0) { }
~XGPath(void) { }
XGPath(const string& path_name,
const vector<Traversal>& path,
size_t entity_count,
XG& graph,
map<int64_t, string>& node_label);
string name;
size_t member_count;
sd_vector<> members;
wt_int<> ids;
sd_vector<> directions; // forward or backward through nodes
int_vector<> positions;
bit_vector offsets;
rank_support_v<1> offsets_rank;
bit_vector::select_1_type offsets_select;
void load(istream& in);
size_t serialize(std::ostream& out,
sdsl::structure_tree_node* v = NULL,
std::string name = "");
};
Mapping new_mapping(const string& name, int64_t id);
void parse_region(const string& target, string& name, int64_t& start, int64_t& end);
void to_text(ostream& out, Graph& graph);
}
#endif
<|endoftext|>
|
<commit_before>#include "CountCompleteTreeNodes.hpp"
int CountCompleteTreeNodes::countNodes(TreeNode* root)
{
if (root == nullptr)
return 0;
if (root->left == nullptr)
return 1;
if (root->right == nullptr)
return 2;
TreeNode* ln = root;
int ld = 0;
while (ln != nullptr) {
ld++;
ln = ln->left;
}
TreeNode* rn = root;
int rd = 0;
while (rn != nullptr) {
rd++;
rn = rn->right;
}
if (ld == rd)
return (1 << ld) - 1;
else
return 1 + countNodes(root->left) + countNodes(root->right);
}
<commit_msg>Refine Problem 222. Count Complete Tree Nodes<commit_after>#include "CountCompleteTreeNodes.hpp"
int CountCompleteTreeNodes::countNodes(TreeNode* root)
{
int hl = 0, hr = 0;
TreeNode* l = root, *r = root;
while (l) {
hl++;
l = l->left;
}
while (r) {
hr++;
r = r->right;
}
if (hl == hr)
return (1 << hl) - 1;
else
return countNodes(root->left) + countNodes(root->right) + 1;
}
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <Dataflow/Network/PortManager.h>
#include <Dataflow/Network/ModuleStateInterface.h>
#include <Dataflow/Network/DataflowInterfaces.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/NullModuleState.h>
#include <Core/Logging/ConsoleLogger.h>
#include <Core/Logging/Log.h>
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Engine::State;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Datatypes;
std::string SCIRun::Dataflow::Networks::to_string(const ModuleInfoProvider& m)
{
return m.get_module_name() + " [" + m.get_id().id_ + "]";
}
/*static*/ int Module::instanceCount_ = 0;
/*static*/ LoggerHandle Module::defaultLogger_(new ConsoleLogger);
/*static*/ void Module::resetInstanceCount() { instanceCount_ = 0; }
Module::Module(const ModuleLookupInfo& info,
bool hasUi,
AlgorithmFactoryHandle algoFactory,
ModuleStateFactoryHandle stateFactory,
const std::string& version)
: info_(info),
id_(info_.module_name_, instanceCount_++),
has_ui_(hasUi),
state_(stateFactory ? stateFactory->make_state(info.module_name_) : new NullModuleState)
{
iports_.set_module(this);
oports_.set_module(this);
setLogger(defaultLogger_);
Log& log = Log::get();
log << DEBUG_LOG << "Module created: " << info.module_name_ << " with id: " << id_;
if (algoFactory)
{
algo_ = algoFactory->create(get_module_name(), this);
if (algo_)
log << DEBUG_LOG << "Module algorithm initialized: " << info.module_name_;
}
log.flush();
setExecutionState(ModuleInterface::Waiting);
}
Module::~Module()
{
}
ModuleStateFactoryHandle Module::defaultStateFactory_;
AlgorithmFactoryHandle Module::defaultAlgoFactory_;
LoggerHandle Module::getLogger() const { return log_ ? log_ : defaultLogger_; }
OutputPortHandle Module::getOutputPort(const PortId& id) const
{
return oports_[id];
}
InputPortHandle Module::getInputPort(const PortId& id) const
{
return iports_[id];
}
size_t Module::num_input_ports() const
{
return iports_.size();
}
size_t Module::num_output_ports() const
{
return oports_.size();
}
void Module::do_execute() throw()
{
executeBegins_(id_);
status("STARTING MODULE: " + id_.id_);
setExecutionState(ModuleInterface::Executing);
try
{
execute();
}
catch(const std::bad_alloc&)
{
error("MODULE ERROR: bad_alloc caught");
}
catch (Core::ExceptionBase& e)
{
//TODO: this block is repetitive (logging-wise) if the macros are used to log AND throw an exception with the same message. Figure out a reasonable condition to enable it.
//if (false)
{
std::ostringstream ostr;
ostr << "Caught exception: " << e.typeName();
ostr << "\n";
ostr << "Message: " << e.what() << std::endl;
error(ostr.str());
}
//TODO: condition this block on logging level
if (false)
{
std::ostringstream ostrExtra;
ostrExtra << "TODO! Following error info will be filtered later, it's too technical for general audiences.\n";
ostrExtra << boost::diagnostic_information(e) << std::endl;
error(ostrExtra.str());
}
}
catch (const std::exception& e)
{
error(std::string("MODULE ERROR: std::exception caught: ") + e.what());
}
catch (...)
{
error("MODULE ERROR: unhandled exception caught");
}
// Call finish on all ports.
//iports_.apply(boost::bind(&PortInterface::finish, _1));
//oports_.apply(boost::bind(&PortInterface::finish, _1));
status("MODULE FINISHED: " + id_.id_);
executeEnds_(id_);
setExecutionState(ModuleInterface::Completed);
}
ModuleStateHandle Module::get_state()
{
return state_;
}
void Module::set_state(ModuleStateHandle state)
{
state_ = state;
}
AlgorithmBase& Module::algo()
{
if (!algo_)
error("Null algorithm object, make sure AlgorithmFactory knows about this module's algorithm types.");
ENSURE_NOT_NULL(algo_, "Null algorithm!");
return *algo_;
}
size_t Module::add_input_port(InputPortHandle h)
{
return iports_.add(h);
}
size_t Module::add_output_port(OutputPortHandle h)
{
return oports_.add(h);
}
bool Module::hasInputPort(const PortId& id) const
{
return iports_.hasPort(id);
}
bool Module::hasOutputPort(const PortId& id) const
{
return oports_.hasPort(id);
}
DatatypeHandleOption Module::get_input_handle(const PortId& id)
{
//TODO test...
if (!iports_.hasPort(id))
{
BOOST_THROW_EXCEPTION(PortNotFoundException() << Core::ErrorMessage("Input port not found: " + id.toString()));
}
if (iports_[id]->isDynamic())
{
BOOST_THROW_EXCEPTION(InvalidInputPortRequestException() << Core::ErrorMessage("Input port " + id.toString() + " is dynamic, get_dynamic_input_handles must be called."));
}
return iports_[id]->getData();
}
std::vector<DatatypeHandleOption> Module::get_dynamic_input_handles(const PortId& id)
{
//TODO test...
if (!iports_.hasPort(id))
{
BOOST_THROW_EXCEPTION(PortNotFoundException() << Core::ErrorMessage("Input port not found: " + id.toString()));
}
if (!iports_[id]->isDynamic())
{
BOOST_THROW_EXCEPTION(InvalidInputPortRequestException() << Core::ErrorMessage("Input port " + id.toString() + " is static, get_input_handle must be called."));
}
auto portsWithName = iports_[id.name];
std::vector<DatatypeHandleOption> options;
auto getData = [](InputPortHandle input) { return input->getData(); };
std::transform(portsWithName.begin(), portsWithName.end(), std::back_inserter(options), getData);
return options;
}
void Module::send_output_handle(const PortId& id, DatatypeHandle data)
{
//TODO test...
if (!oports_.hasPort(id))
{
THROW_OUT_OF_RANGE("Output port does not exist: " + id.toString());
}
oports_[id]->sendData(data);
}
std::vector<InputPortHandle> Module::findInputPortsWithName(const std::string& name) const
{
return iports_[name];
}
std::vector<OutputPortHandle> Module::findOutputPortsWithName(const std::string& name) const
{
return oports_[name];
}
std::vector<InputPortHandle> Module::inputPorts() const
{
return iports_.view();
}
std::vector<OutputPortHandle> Module::outputPorts() const
{
return oports_.view();
}
Module::Builder::Builder()
{
}
Module::Builder::SinkMaker Module::Builder::sink_maker_;
Module::Builder::SourceMaker Module::Builder::source_maker_;
/*static*/ void Module::Builder::use_sink_type(Module::Builder::SinkMaker func) { sink_maker_ = func; }
/*static*/ void Module::Builder::use_source_type(Module::Builder::SourceMaker func) { source_maker_ = func; }
class DummyModule : public Module
{
public:
explicit DummyModule(const ModuleLookupInfo& info) : Module(info) {}
virtual void execute()
{
std::ostringstream ostr;
ostr << "Module " << get_module_name() << " executing for " << 3.14 << " seconds." << std::endl;
status(ostr.str());
}
virtual void setStateDefaults() {}
};
Module::Builder& Module::Builder::with_name(const std::string& name)
{
if (!module_)
{
ModuleLookupInfo info;
info.module_name_ = name;
module_.reset(new DummyModule(info));
}
return *this;
}
Module::Builder& Module::Builder::using_func(ModuleMaker create)
{
if (!module_)
module_.reset(create());
return *this;
}
Module::Builder& Module::Builder::setStateDefaults()
{
if (module_)
module_->setStateDefaults();
return *this;
}
Module::Builder& Module::Builder::add_input_port(const Port::ConstructionParams& params)
{
if (module_)
{
addInputPortImpl(*module_, params);
}
return *this;
}
void Module::Builder::addInputPortImpl(Module& module, const Port::ConstructionParams& params)
{
DatatypeSinkInterfaceHandle sink(sink_maker_ ? sink_maker_() : 0);
InputPortHandle port(boost::make_shared<InputPort>(module_.get(), params, sink));
port->setIndex(module_->add_input_port(port));
}
Module::Builder& Module::Builder::add_output_port(const Port::ConstructionParams& params)
{
if (module_)
{
DatatypeSourceInterfaceHandle source(source_maker_ ? source_maker_() : 0);
OutputPortHandle port(boost::make_shared<OutputPort>(module_.get(), params, source));
port->setIndex(module_->add_output_port(port));
}
return *this;
}
PortId Module::Builder::cloneInputPort(ModuleHandle module, const PortId& id)
{
Module* m = dynamic_cast<Module*>(module.get());
if (m)
{
InputPortHandle newPort(m->getInputPort(id)->clone());
newPort->setIndex(m->add_input_port(newPort));
return newPort->id();
}
THROW_INVALID_ARGUMENT("Don't know how to clone ports on other Module types");
}
void Module::Builder::removeInputPort(ModuleHandle module, const PortId& id)
{
Module* m = dynamic_cast<Module*>(module.get());
if (m)
{
m->removeInputPort(id);
}
}
ModuleHandle Module::Builder::build()
{
return module_;
}
boost::signals2::connection Module::connectExecuteBegins(const ExecuteBeginsSignalType::slot_type& subscriber)
{
return executeBegins_.connect(subscriber);
}
boost::signals2::connection Module::connectExecuteEnds(const ExecuteEndsSignalType::slot_type& subscriber)
{
return executeEnds_.connect(subscriber);
}
boost::signals2::connection Module::connectErrorListener(const ErrorSignalType::slot_type& subscriber)
{
return errorSignal_.connect(subscriber);
}
void Module::setUiVisible(bool visible)
{
if (uiToggleFunc_)
uiToggleFunc_(visible);
}
void Module::setLogger(SCIRun::Core::Logging::LoggerHandle log)
{
log_ = log;
if (algo_)
algo_->setLogger(log);
}
void Module::setUpdaterFunc(SCIRun::Core::Algorithms::AlgorithmStatusReporter::UpdaterFunc func)
{
updaterFunc_ = func;
if (algo_)
algo_->setUpdaterFunc(func);
}
bool Module::oport_connected(const PortId& id) const
{
if (!oports_.hasPort(id))
return false;
auto port = oports_[id];
return port->nconnections() > 0;
}
void Module::removeInputPort(const PortId& id)
{
iports_.remove(id);
}
void Module::setStateBoolFromAlgo(AlgorithmParameterName name)
{
get_state()->setValue(name, algo().get(name).getBool());
}
void Module::setAlgoIntFromState(AlgorithmParameterName name)
{
algo().set(name, get_state()->getValue(name).getInt());
}
void Module::setAlgoBoolFromState(AlgorithmParameterName name)
{
algo().set(name, get_state()->getValue(name).getBool());
}
void Module::setStateIntFromAlgo(AlgorithmParameterName name)
{
get_state()->setValue(name, algo().get(name).getInt());
}<commit_msg>Fix attempt for deleted dynamic port data<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <Dataflow/Network/PortManager.h>
#include <Dataflow/Network/ModuleStateInterface.h>
#include <Dataflow/Network/DataflowInterfaces.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/NullModuleState.h>
#include <Core/Logging/ConsoleLogger.h>
#include <Core/Logging/Log.h>
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Engine::State;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Datatypes;
std::string SCIRun::Dataflow::Networks::to_string(const ModuleInfoProvider& m)
{
return m.get_module_name() + " [" + m.get_id().id_ + "]";
}
/*static*/ int Module::instanceCount_ = 0;
/*static*/ LoggerHandle Module::defaultLogger_(new ConsoleLogger);
/*static*/ void Module::resetInstanceCount() { instanceCount_ = 0; }
Module::Module(const ModuleLookupInfo& info,
bool hasUi,
AlgorithmFactoryHandle algoFactory,
ModuleStateFactoryHandle stateFactory,
const std::string& version)
: info_(info),
id_(info_.module_name_, instanceCount_++),
has_ui_(hasUi),
state_(stateFactory ? stateFactory->make_state(info.module_name_) : new NullModuleState)
{
iports_.set_module(this);
oports_.set_module(this);
setLogger(defaultLogger_);
Log& log = Log::get();
log << DEBUG_LOG << "Module created: " << info.module_name_ << " with id: " << id_;
if (algoFactory)
{
algo_ = algoFactory->create(get_module_name(), this);
if (algo_)
log << DEBUG_LOG << "Module algorithm initialized: " << info.module_name_;
}
log.flush();
setExecutionState(ModuleInterface::Waiting);
}
Module::~Module()
{
}
ModuleStateFactoryHandle Module::defaultStateFactory_;
AlgorithmFactoryHandle Module::defaultAlgoFactory_;
LoggerHandle Module::getLogger() const { return log_ ? log_ : defaultLogger_; }
OutputPortHandle Module::getOutputPort(const PortId& id) const
{
return oports_[id];
}
InputPortHandle Module::getInputPort(const PortId& id) const
{
return iports_[id];
}
size_t Module::num_input_ports() const
{
return iports_.size();
}
size_t Module::num_output_ports() const
{
return oports_.size();
}
void Module::do_execute() throw()
{
executeBegins_(id_);
status("STARTING MODULE: " + id_.id_);
setExecutionState(ModuleInterface::Executing);
try
{
execute();
}
catch(const std::bad_alloc&)
{
error("MODULE ERROR: bad_alloc caught");
}
catch (Core::ExceptionBase& e)
{
//TODO: this block is repetitive (logging-wise) if the macros are used to log AND throw an exception with the same message. Figure out a reasonable condition to enable it.
//if (false)
{
std::ostringstream ostr;
ostr << "Caught exception: " << e.typeName();
ostr << "\n";
ostr << "Message: " << e.what() << std::endl;
error(ostr.str());
}
//TODO: condition this block on logging level
if (false)
{
std::ostringstream ostrExtra;
ostrExtra << "TODO! Following error info will be filtered later, it's too technical for general audiences.\n";
ostrExtra << boost::diagnostic_information(e) << std::endl;
error(ostrExtra.str());
}
}
catch (const std::exception& e)
{
error(std::string("MODULE ERROR: std::exception caught: ") + e.what());
}
catch (...)
{
error("MODULE ERROR: unhandled exception caught");
}
// Call finish on all ports.
//iports_.apply(boost::bind(&PortInterface::finish, _1));
//oports_.apply(boost::bind(&PortInterface::finish, _1));
status("MODULE FINISHED: " + id_.id_);
executeEnds_(id_);
setExecutionState(ModuleInterface::Completed);
}
ModuleStateHandle Module::get_state()
{
return state_;
}
void Module::set_state(ModuleStateHandle state)
{
state_ = state;
}
AlgorithmBase& Module::algo()
{
if (!algo_)
error("Null algorithm object, make sure AlgorithmFactory knows about this module's algorithm types.");
ENSURE_NOT_NULL(algo_, "Null algorithm!");
return *algo_;
}
size_t Module::add_input_port(InputPortHandle h)
{
return iports_.add(h);
}
size_t Module::add_output_port(OutputPortHandle h)
{
return oports_.add(h);
}
bool Module::hasInputPort(const PortId& id) const
{
return iports_.hasPort(id);
}
bool Module::hasOutputPort(const PortId& id) const
{
return oports_.hasPort(id);
}
DatatypeHandleOption Module::get_input_handle(const PortId& id)
{
//TODO test...
if (!iports_.hasPort(id))
{
BOOST_THROW_EXCEPTION(PortNotFoundException() << Core::ErrorMessage("Input port not found: " + id.toString()));
}
if (iports_[id]->isDynamic())
{
BOOST_THROW_EXCEPTION(InvalidInputPortRequestException() << Core::ErrorMessage("Input port " + id.toString() + " is dynamic, get_dynamic_input_handles must be called."));
}
return iports_[id]->getData();
}
std::vector<DatatypeHandleOption> Module::get_dynamic_input_handles(const PortId& id)
{
//TODO test...
auto portsWithName = iports_[id.name]; //will throw if empty
if (!portsWithName[0]->isDynamic())
{
BOOST_THROW_EXCEPTION(InvalidInputPortRequestException() << Core::ErrorMessage("Input port " + id.toString() + " is static, get_input_handle must be called."));
}
std::vector<DatatypeHandleOption> options;
auto getData = [](InputPortHandle input) { return input->getData(); };
std::transform(portsWithName.begin(), portsWithName.end(), std::back_inserter(options), getData);
return options;
}
void Module::send_output_handle(const PortId& id, DatatypeHandle data)
{
//TODO test...
if (!oports_.hasPort(id))
{
THROW_OUT_OF_RANGE("Output port does not exist: " + id.toString());
}
oports_[id]->sendData(data);
}
std::vector<InputPortHandle> Module::findInputPortsWithName(const std::string& name) const
{
return iports_[name];
}
std::vector<OutputPortHandle> Module::findOutputPortsWithName(const std::string& name) const
{
return oports_[name];
}
std::vector<InputPortHandle> Module::inputPorts() const
{
return iports_.view();
}
std::vector<OutputPortHandle> Module::outputPorts() const
{
return oports_.view();
}
Module::Builder::Builder()
{
}
Module::Builder::SinkMaker Module::Builder::sink_maker_;
Module::Builder::SourceMaker Module::Builder::source_maker_;
/*static*/ void Module::Builder::use_sink_type(Module::Builder::SinkMaker func) { sink_maker_ = func; }
/*static*/ void Module::Builder::use_source_type(Module::Builder::SourceMaker func) { source_maker_ = func; }
class DummyModule : public Module
{
public:
explicit DummyModule(const ModuleLookupInfo& info) : Module(info) {}
virtual void execute()
{
std::ostringstream ostr;
ostr << "Module " << get_module_name() << " executing for " << 3.14 << " seconds." << std::endl;
status(ostr.str());
}
virtual void setStateDefaults() {}
};
Module::Builder& Module::Builder::with_name(const std::string& name)
{
if (!module_)
{
ModuleLookupInfo info;
info.module_name_ = name;
module_.reset(new DummyModule(info));
}
return *this;
}
Module::Builder& Module::Builder::using_func(ModuleMaker create)
{
if (!module_)
module_.reset(create());
return *this;
}
Module::Builder& Module::Builder::setStateDefaults()
{
if (module_)
module_->setStateDefaults();
return *this;
}
Module::Builder& Module::Builder::add_input_port(const Port::ConstructionParams& params)
{
if (module_)
{
addInputPortImpl(*module_, params);
}
return *this;
}
void Module::Builder::addInputPortImpl(Module& module, const Port::ConstructionParams& params)
{
DatatypeSinkInterfaceHandle sink(sink_maker_ ? sink_maker_() : 0);
InputPortHandle port(boost::make_shared<InputPort>(module_.get(), params, sink));
port->setIndex(module_->add_input_port(port));
}
Module::Builder& Module::Builder::add_output_port(const Port::ConstructionParams& params)
{
if (module_)
{
DatatypeSourceInterfaceHandle source(source_maker_ ? source_maker_() : 0);
OutputPortHandle port(boost::make_shared<OutputPort>(module_.get(), params, source));
port->setIndex(module_->add_output_port(port));
}
return *this;
}
PortId Module::Builder::cloneInputPort(ModuleHandle module, const PortId& id)
{
Module* m = dynamic_cast<Module*>(module.get());
if (m)
{
InputPortHandle newPort(m->getInputPort(id)->clone());
newPort->setIndex(m->add_input_port(newPort));
return newPort->id();
}
THROW_INVALID_ARGUMENT("Don't know how to clone ports on other Module types");
}
void Module::Builder::removeInputPort(ModuleHandle module, const PortId& id)
{
Module* m = dynamic_cast<Module*>(module.get());
if (m)
{
m->removeInputPort(id);
}
}
ModuleHandle Module::Builder::build()
{
return module_;
}
boost::signals2::connection Module::connectExecuteBegins(const ExecuteBeginsSignalType::slot_type& subscriber)
{
return executeBegins_.connect(subscriber);
}
boost::signals2::connection Module::connectExecuteEnds(const ExecuteEndsSignalType::slot_type& subscriber)
{
return executeEnds_.connect(subscriber);
}
boost::signals2::connection Module::connectErrorListener(const ErrorSignalType::slot_type& subscriber)
{
return errorSignal_.connect(subscriber);
}
void Module::setUiVisible(bool visible)
{
if (uiToggleFunc_)
uiToggleFunc_(visible);
}
void Module::setLogger(SCIRun::Core::Logging::LoggerHandle log)
{
log_ = log;
if (algo_)
algo_->setLogger(log);
}
void Module::setUpdaterFunc(SCIRun::Core::Algorithms::AlgorithmStatusReporter::UpdaterFunc func)
{
updaterFunc_ = func;
if (algo_)
algo_->setUpdaterFunc(func);
}
bool Module::oport_connected(const PortId& id) const
{
if (!oports_.hasPort(id))
return false;
auto port = oports_[id];
return port->nconnections() > 0;
}
void Module::removeInputPort(const PortId& id)
{
iports_.remove(id);
}
void Module::setStateBoolFromAlgo(AlgorithmParameterName name)
{
get_state()->setValue(name, algo().get(name).getBool());
}
void Module::setAlgoIntFromState(AlgorithmParameterName name)
{
algo().set(name, get_state()->getValue(name).getInt());
}
void Module::setAlgoBoolFromState(AlgorithmParameterName name)
{
algo().set(name, get_state()->getValue(name).getBool());
}
void Module::setStateIntFromAlgo(AlgorithmParameterName name)
{
get_state()->setValue(name, algo().get(name).getInt());
}<|endoftext|>
|
<commit_before>// {{{ Copyright notice
/* Copyright (c) 2007-2009, Adam Harvey
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// }}}
#include "PropertyDialog.h"
#include "SourceTextCtrl.h"
#include "Languages.h"
#include <algorithm>
#include <string>
#include <wx/artprov.h>
#include <wx/log.h>
#include <wx/tipwin.h>
#include "ID.h"
using namespace Languages;
// {{{ Event table
BEGIN_EVENT_TABLE(SourceTextCtrl, wxStyledTextCtrl)
EVT_CONTEXT_MENU(SourceTextCtrl::OnContextMenu)
EVT_LEFT_DCLICK(SourceTextCtrl::OnDoubleClick)
EVT_MENU(wxID_COPY, SourceTextCtrl::OnCopy)
EVT_MENU(wxID_SELECTALL, SourceTextCtrl::OnSelectAll)
EVT_MENU(ID_SOURCETEXTCTRL_EXAMINE_VALUE, SourceTextCtrl::OnExamineValue)
EVT_MENU(ID_SOURCETEXTCTRL_RUN_TO_HERE, SourceTextCtrl::OnRunToHere)
EVT_MENU(ID_SOURCETEXTCTRL_TOGGLE_BREAKPOINT, SourceTextCtrl::OnToggleBreakpoint)
EVT_STC_DWELLEND(wxID_ANY, SourceTextCtrl::OnDwellEnd)
EVT_STC_DWELLSTART(wxID_ANY, SourceTextCtrl::OnDwellStart)
EVT_STC_MARGINCLICK(wxID_ANY, SourceTextCtrl::OnMarginClick)
END_EVENT_TABLE()
// }}}
// {{{ SourceTextCtrl::SourceTextCtrl(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style, const wxString &name)
SourceTextCtrl::SourceTextCtrl(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style, const wxString &name) : wxStyledTextCtrl(parent, id, pos, size, style, name), menuPos(wxSTC_INVALID_POSITION), menuShown(false), tipWindow(NULL) {
config = wxConfigBase::Get();
handler = dynamic_cast<SourceTextCtrlHandler *>(parent);
wxFont font(DefaultFont());
StyleSetFont(wxSTC_STYLE_DEFAULT, font);
SetMarginType(0, wxSTC_MARGIN_NUMBER);
SetMarginWidth(0, TextWidth(wxSTC_STYLE_LINENUMBER, wxT("99999")));
SetMarginSensitive(0, true);
SetMarginType(1, wxSTC_MARGIN_SYMBOL);
SetMarginWidth(1, 16);
SetMarginSensitive(1, true);
MarkerDefine(MARKER_BREAKPOINT, wxSTC_MARK_CIRCLE, wxT("red"), wxT("red"));
MarkerDefine(MARKER_CURRENT, wxSTC_MARK_ARROW, wxT("green"), wxT("green"));
SetMouseDwellTime(1000);
SetReadOnly(true);
UsePopUp(false);
}
// }}}
// {{{ void SourceTextCtrl::AddBreakpoint(int line)
void SourceTextCtrl::AddBreakpoint(int line) {
if (handler) {
handler->BreakpointAdd(line + 1);
}
breakpoints.push_back(line);
MarkerAdd(line, MARKER_BREAKPOINT);
}
// }}}
// {{{ wxFont SourceTextCtrl::DefaultFont()
wxFont SourceTextCtrl::DefaultFont() {
static wxConfigBase *config = wxConfigBase::Get();
long defaultSize = 10;
long defaultStyle = wxFONTSTYLE_NORMAL;
long defaultWeight = wxFONTWEIGHT_NORMAL;
wxFont font(defaultSize, wxFONTFAMILY_TELETYPE, defaultStyle, defaultWeight);
wxString defaultFace(font.GetFaceName());
font.SetFaceName(config->Read(wxT("SourcePanel/FontFace"), defaultFace));
font.SetPointSize(config->Read(wxT("SourcePanel/FontSize"), defaultSize));
font.SetStyle(config->Read(wxT("SourcePanel/FontStyle"), defaultStyle));
font.SetWeight(config->Read(wxT("SourcePanel/FontWeight"), defaultWeight));
return font;
}
// }}}
// {{{ void SourceTextCtrl::RemoveBreakpoint(int line)
void SourceTextCtrl::RemoveBreakpoint(int line) {
if (handler) {
handler->BreakpointRemove(line + 1);
}
for (BreakpointList::iterator i = breakpoints.begin(); i != breakpoints.end(); i++) {
if (*i == line) {
breakpoints.erase(i);
break;
}
}
MarkerDelete(line, MARKER_BREAKPOINT);
}
// }}}
// {{{ void SourceTextCtrl::SetBreakpointStyle(int line, bool isSet)
void SourceTextCtrl::SetBreakpointStyle(int line, bool isSet) {
MarkerDelete(--line, MARKER_ALL);
if (isSet) {
if (line != current) {
MarkerAdd(line, MARKER_BREAKPOINT);
}
}
else if (line == current) {
MarkerAdd(line, MARKER_CURRENT);
}
}
// }}}
// {{{ void SourceTextCtrl::SetLexerLanguage(const wxString &language)
void SourceTextCtrl::SetLexerLanguage(const wxString &language) {
StyleClearAll();
wxStyledTextCtrl::SetLexerLanguage(language.Lower());
SetLexerOptions(GetLexer());
SetStyleOptions(GetLexer());
}
// }}}
// {{{ void SourceTextCtrl::SetLine(int line)
void SourceTextCtrl::SetLine(int line) {
// Convert the 1-indexed value from DBGp to a 0-indexed value.
int start = PositionFromLine(--line);
current = line;
Freeze();
GotoPos(start);
MarkerDeleteAll(MARKER_CURRENT);
MarkerAdd(line, MARKER_CURRENT);
Thaw();
}
// }}}
// {{{ void SourceTextCtrl::SetSource(const wxString &source, int line)
void SourceTextCtrl::SetSource(const wxString &source, int line) {
breakpoints.clear();
Freeze();
SetReadOnly(false);
SetText(source);
if (line == -1) {
GotoPos(0);
current = -1;
}
else {
SetLine(line);
}
SetReadOnly(true);
Thaw();
}
// }}}
// {{{ DBGp::Property *SourceTextCtrl::GetPropertyAtPosition(const wxPosition &pos)
DBGp::Property *SourceTextCtrl::GetPropertyAtPosition(int pos) {
if (pos != wxSTC_INVALID_POSITION && handler) {
/* We need to pull out the individual token for the variable
* under the mouse, if any. */
int line = LineFromPosition(pos);
int col = pos - PositionFromLine(line);
wxString name(GetLine(line));
size_t pos;
// TODO: This should be language specific.
static const wxString varChars(wxT("abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_->.$[]'"));
pos = name.find_first_not_of(varChars, col);
if (pos != std::string::npos) {
name = name.Left(pos);
}
pos = name.find_last_not_of(varChars);
if (pos != std::string::npos && pos < name.Length()) {
name = name.Mid(pos + 1);
}
return handler->GetProperty(name);
}
return NULL;
}
// }}}
// {{{ void SourceTextCtrl::OnCopy(wxCommandEvent &event)
void SourceTextCtrl::OnCopy(wxCommandEvent &event) {
Copy();
}
// }}}
// {{{ void SourceTextCtrl::OnContextMenu(wxContextMenuEvent &event)
void SourceTextCtrl::OnContextMenu(wxContextMenuEvent &event) {
wxMenu menu;
wxPoint pos(event.GetPosition() - GetScreenPosition());
menuPos = PositionFromPoint(pos);
wxLogDebug(wxT("Point is line %d"), LineFromPosition(menuPos));
menu.Append(wxID_COPY);
menu.Append(wxID_SELECTALL);
if (menuPos != wxSTC_INVALID_POSITION) {
DBGp::Property *prop = GetPropertyAtPosition(menuPos);
menu.AppendSeparator();
if (prop) {
menu.Append(ID_SOURCETEXTCTRL_EXAMINE_VALUE, _("E&xamine Value"));
}
menu.Append(ID_SOURCETEXTCTRL_RUN_TO_HERE, _("&Run to Here"));
if (handler) {
menu.Append(ID_SOURCETEXTCTRL_TOGGLE_BREAKPOINT, _("Toggle &Breakpoint"));
}
}
menuShown = true;
PopupMenu(&menu);
menuShown = false;
}
// }}}
// {{{ void SourceTextCtrl::OnDoubleClick(wxMouseEvent &event)
void SourceTextCtrl::OnDoubleClick(wxMouseEvent &event) {
int pos = PositionFromPointClose(event.GetPosition().x, event.GetPosition().y);
if (pos != wxSTC_INVALID_POSITION) {
ToggleBreakpoint(LineFromPosition(pos));
}
}
// }}}
// {{{ void SourceTextCtrl::OnDwellEnd(wxStyledTextEvent &event)
void SourceTextCtrl::OnDwellEnd(wxStyledTextEvent &event) {
if (tipWindow) {
tipWindow->Destroy();
tipWindow = NULL;
}
}
// }}}
// {{{ void SourceTextCtrl::OnDwellStart(wxStyledTextEvent &event)
void SourceTextCtrl::OnDwellStart(wxStyledTextEvent &event) {
/* If we're showing a context menu, we don't want this to fire at all,
* so we'll save a roundtrip back to the debugging engine and get out
* now. */
if (menuShown) {
return;
}
DBGp::Property *prop = GetPropertyAtPosition(event.GetPosition());
if (prop) {
wxString text;
text << prop->GetFullName() << wxT(" (") << prop->GetType().GetName() << wxT(") : ");
if (prop->HasChildren()) {
/* We'll do a shallow dump. People can look at
* the properties panel and dialog (or the
* context menu I, er, haven't implemented yet)
* if they want detailed information. */
const DBGp::Property::PropertyMap children = prop->GetChildren();
for (DBGp::Property::PropertyMap::const_iterator i = children.begin(); i != children.end(); i++) {
DBGp::Property *child = i->second;
text << wxT("\n") << child->GetName() << wxT(" (") << child->GetType().GetName() << wxT(") : ");
if (child->HasChildren()) {
text << _("<complex data structure>");
}
else {
text << child->GetData();
}
}
}
else {
text << prop->GetData();
}
tipWindow = new wxTipWindow(this, text, 640, &tipWindow);
tipWindow->SetBoundingRect(wxRect(-1, -1, -1, -1));
}
}
// }}}
// {{{ void SourceTextCtrl::OnExamineValue(wxCommandEvent &event)
void SourceTextCtrl::OnExamineValue(wxCommandEvent &event) {
DBGp::Property *prop = GetPropertyAtPosition(menuPos);
if (prop) {
PropertyDialog pd(this, wxID_ANY, prop);
pd.ShowModal();
}
}
// }}}
// {{{ void SourceTextCtrl::OnMarginClick(wxStyledTextEvent &event)
void SourceTextCtrl::OnMarginClick(wxStyledTextEvent &event) {
ToggleBreakpoint(LineFromPosition(event.GetPosition()));
}
// }}}
// {{{ void SourceTextCtrl::OnRunToHere(wxCommandEvent &event)
void SourceTextCtrl::OnRunToHere(wxCommandEvent &event) {
if (handler) {
handler->BreakpointAdd(LineFromPosition(menuPos) + 1, true);
}
}
// }}}
// {{{ void SourceTextCtrl::OnSelectAll(wxCommandEvent &event)
void SourceTextCtrl::OnSelectAll(wxCommandEvent &event) {
SelectAll();
}
// }}}
// {{{ void SourceTextCtrl::OnToggleBreakpoint(wxCommandEvent &event)
void SourceTextCtrl::OnToggleBreakpoint(wxCommandEvent &event) {
ToggleBreakpoint(LineFromPosition(menuPos));
}
// }}}
// {{{ void SourceTextCtrl::SetLexerOptions(int lexer)
void SourceTextCtrl::SetLexerOptions(int lexer) {
for (const Lexers *l = lexers; l->lexer != -1; l++) {
if (l->lexer == lexer) {
SetKeyWords(4, l->keywords);
SetStyleBits(l->bits);
}
}
}
// }}}
// {{{ void SourceTextCtrl::SetStyleOptions(int lexer)
void SourceTextCtrl::SetStyleOptions(int lexer) {
for (const TokenTypes *t = tokenTypes; t->token != END; t++) {
if (t->lexer == lexer) {
switch (t->token) {
case COMMENT:
StyleSetForeground(t->stcType, wxT("blue"));
break;
case KEYWORD:
StyleSetBold(t->stcType, true);
StyleSetForeground(t->stcType, wxT("dark green"));
break;
case LITERAL:
StyleSetForeground(t->stcType, wxT("magenta"));
break;
case OPERATOR:
StyleSetBold(t->stcType, true);
StyleSetForeground(t->stcType, wxT("brown"));
break;
case DEFAULT:
case IDENTIFIER:
default:
;
}
}
}
}
// }}}
// {{{ void SourceTextCtrl::ToggleBreakpoint(int line)
void SourceTextCtrl::ToggleBreakpoint(int line) {
if (std::count(breakpoints.begin(), breakpoints.end(), line) > 0) {
RemoveBreakpoint(line);
}
else {
AddBreakpoint(line);
}
}
// }}}
// vim:set fdm=marker ts=8 sw=8 noet cin:
<commit_msg>Improved tooltip display for complex properties.<commit_after>// {{{ Copyright notice
/* Copyright (c) 2007-2009, Adam Harvey
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// }}}
#include "PropertyDialog.h"
#include "SourceTextCtrl.h"
#include "Languages.h"
#include <algorithm>
#include <string>
#include <wx/artprov.h>
#include <wx/log.h>
#include <wx/tipwin.h>
#include "ID.h"
using namespace Languages;
// {{{ Event table
BEGIN_EVENT_TABLE(SourceTextCtrl, wxStyledTextCtrl)
EVT_CONTEXT_MENU(SourceTextCtrl::OnContextMenu)
EVT_LEFT_DCLICK(SourceTextCtrl::OnDoubleClick)
EVT_MENU(wxID_COPY, SourceTextCtrl::OnCopy)
EVT_MENU(wxID_SELECTALL, SourceTextCtrl::OnSelectAll)
EVT_MENU(ID_SOURCETEXTCTRL_EXAMINE_VALUE, SourceTextCtrl::OnExamineValue)
EVT_MENU(ID_SOURCETEXTCTRL_RUN_TO_HERE, SourceTextCtrl::OnRunToHere)
EVT_MENU(ID_SOURCETEXTCTRL_TOGGLE_BREAKPOINT, SourceTextCtrl::OnToggleBreakpoint)
EVT_STC_DWELLEND(wxID_ANY, SourceTextCtrl::OnDwellEnd)
EVT_STC_DWELLSTART(wxID_ANY, SourceTextCtrl::OnDwellStart)
EVT_STC_MARGINCLICK(wxID_ANY, SourceTextCtrl::OnMarginClick)
END_EVENT_TABLE()
// }}}
// {{{ SourceTextCtrl::SourceTextCtrl(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style, const wxString &name)
SourceTextCtrl::SourceTextCtrl(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style, const wxString &name) : wxStyledTextCtrl(parent, id, pos, size, style, name), menuPos(wxSTC_INVALID_POSITION), menuShown(false), tipWindow(NULL) {
config = wxConfigBase::Get();
handler = dynamic_cast<SourceTextCtrlHandler *>(parent);
wxFont font(DefaultFont());
StyleSetFont(wxSTC_STYLE_DEFAULT, font);
SetMarginType(0, wxSTC_MARGIN_NUMBER);
SetMarginWidth(0, TextWidth(wxSTC_STYLE_LINENUMBER, wxT("99999")));
SetMarginSensitive(0, true);
SetMarginType(1, wxSTC_MARGIN_SYMBOL);
SetMarginWidth(1, 16);
SetMarginSensitive(1, true);
MarkerDefine(MARKER_BREAKPOINT, wxSTC_MARK_CIRCLE, wxT("red"), wxT("red"));
MarkerDefine(MARKER_CURRENT, wxSTC_MARK_ARROW, wxT("green"), wxT("green"));
SetMouseDwellTime(1000);
SetReadOnly(true);
UsePopUp(false);
}
// }}}
// {{{ void SourceTextCtrl::AddBreakpoint(int line)
void SourceTextCtrl::AddBreakpoint(int line) {
if (handler) {
handler->BreakpointAdd(line + 1);
}
breakpoints.push_back(line);
MarkerAdd(line, MARKER_BREAKPOINT);
}
// }}}
// {{{ wxFont SourceTextCtrl::DefaultFont()
wxFont SourceTextCtrl::DefaultFont() {
static wxConfigBase *config = wxConfigBase::Get();
long defaultSize = 10;
long defaultStyle = wxFONTSTYLE_NORMAL;
long defaultWeight = wxFONTWEIGHT_NORMAL;
wxFont font(defaultSize, wxFONTFAMILY_TELETYPE, defaultStyle, defaultWeight);
wxString defaultFace(font.GetFaceName());
font.SetFaceName(config->Read(wxT("SourcePanel/FontFace"), defaultFace));
font.SetPointSize(config->Read(wxT("SourcePanel/FontSize"), defaultSize));
font.SetStyle(config->Read(wxT("SourcePanel/FontStyle"), defaultStyle));
font.SetWeight(config->Read(wxT("SourcePanel/FontWeight"), defaultWeight));
return font;
}
// }}}
// {{{ void SourceTextCtrl::RemoveBreakpoint(int line)
void SourceTextCtrl::RemoveBreakpoint(int line) {
if (handler) {
handler->BreakpointRemove(line + 1);
}
for (BreakpointList::iterator i = breakpoints.begin(); i != breakpoints.end(); i++) {
if (*i == line) {
breakpoints.erase(i);
break;
}
}
MarkerDelete(line, MARKER_BREAKPOINT);
}
// }}}
// {{{ void SourceTextCtrl::SetBreakpointStyle(int line, bool isSet)
void SourceTextCtrl::SetBreakpointStyle(int line, bool isSet) {
MarkerDelete(--line, MARKER_ALL);
if (isSet) {
if (line != current) {
MarkerAdd(line, MARKER_BREAKPOINT);
}
}
else if (line == current) {
MarkerAdd(line, MARKER_CURRENT);
}
}
// }}}
// {{{ void SourceTextCtrl::SetLexerLanguage(const wxString &language)
void SourceTextCtrl::SetLexerLanguage(const wxString &language) {
StyleClearAll();
wxStyledTextCtrl::SetLexerLanguage(language.Lower());
SetLexerOptions(GetLexer());
SetStyleOptions(GetLexer());
}
// }}}
// {{{ void SourceTextCtrl::SetLine(int line)
void SourceTextCtrl::SetLine(int line) {
// Convert the 1-indexed value from DBGp to a 0-indexed value.
int start = PositionFromLine(--line);
current = line;
Freeze();
GotoPos(start);
MarkerDeleteAll(MARKER_CURRENT);
MarkerAdd(line, MARKER_CURRENT);
Thaw();
}
// }}}
// {{{ void SourceTextCtrl::SetSource(const wxString &source, int line)
void SourceTextCtrl::SetSource(const wxString &source, int line) {
breakpoints.clear();
Freeze();
SetReadOnly(false);
SetText(source);
if (line == -1) {
GotoPos(0);
current = -1;
}
else {
SetLine(line);
}
SetReadOnly(true);
Thaw();
}
// }}}
// {{{ DBGp::Property *SourceTextCtrl::GetPropertyAtPosition(const wxPosition &pos)
DBGp::Property *SourceTextCtrl::GetPropertyAtPosition(int pos) {
if (pos != wxSTC_INVALID_POSITION && handler) {
/* We need to pull out the individual token for the variable
* under the mouse, if any. */
int line = LineFromPosition(pos);
int col = pos - PositionFromLine(line);
wxString name(GetLine(line));
size_t pos;
// TODO: This should be language specific.
static const wxString varChars(wxT("abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_->.$[]'"));
pos = name.find_first_not_of(varChars, col);
if (pos != std::string::npos) {
name = name.Left(pos);
}
pos = name.find_last_not_of(varChars);
if (pos != std::string::npos && pos < name.Length()) {
name = name.Mid(pos + 1);
}
return handler->GetProperty(name);
}
return NULL;
}
// }}}
// {{{ void SourceTextCtrl::OnCopy(wxCommandEvent &event)
void SourceTextCtrl::OnCopy(wxCommandEvent &event) {
Copy();
}
// }}}
// {{{ void SourceTextCtrl::OnContextMenu(wxContextMenuEvent &event)
void SourceTextCtrl::OnContextMenu(wxContextMenuEvent &event) {
wxMenu menu;
wxPoint pos(event.GetPosition() - GetScreenPosition());
menuPos = PositionFromPoint(pos);
wxLogDebug(wxT("Point is line %d"), LineFromPosition(menuPos));
menu.Append(wxID_COPY);
menu.Append(wxID_SELECTALL);
if (menuPos != wxSTC_INVALID_POSITION) {
DBGp::Property *prop = GetPropertyAtPosition(menuPos);
menu.AppendSeparator();
if (prop) {
menu.Append(ID_SOURCETEXTCTRL_EXAMINE_VALUE, _("E&xamine Value"));
}
menu.Append(ID_SOURCETEXTCTRL_RUN_TO_HERE, _("&Run to Here"));
if (handler) {
menu.Append(ID_SOURCETEXTCTRL_TOGGLE_BREAKPOINT, _("Toggle &Breakpoint"));
}
}
menuShown = true;
PopupMenu(&menu);
menuShown = false;
}
// }}}
// {{{ void SourceTextCtrl::OnDoubleClick(wxMouseEvent &event)
void SourceTextCtrl::OnDoubleClick(wxMouseEvent &event) {
int pos = PositionFromPointClose(event.GetPosition().x, event.GetPosition().y);
if (pos != wxSTC_INVALID_POSITION) {
ToggleBreakpoint(LineFromPosition(pos));
}
}
// }}}
// {{{ void SourceTextCtrl::OnDwellEnd(wxStyledTextEvent &event)
void SourceTextCtrl::OnDwellEnd(wxStyledTextEvent &event) {
if (tipWindow) {
tipWindow->Destroy();
tipWindow = NULL;
}
}
// }}}
// {{{ void SourceTextCtrl::OnDwellStart(wxStyledTextEvent &event)
void SourceTextCtrl::OnDwellStart(wxStyledTextEvent &event) {
/* If we're showing a context menu, we don't want this to fire at all,
* so we'll save a roundtrip back to the debugging engine and get out
* now. */
if (menuShown) {
return;
}
DBGp::Property *prop = GetPropertyAtPosition(event.GetPosition());
if (prop) {
wxString text;
text << prop->GetFullName() << wxT(" (") << prop->GetType().GetName() << wxT(") : ");
if (prop->HasChildren()) {
/* We'll do a shallow dump. People can look at
* the properties panel and dialog (or the
* context menu I, er, haven't implemented yet)
* if they want detailed information. */
const DBGp::Property::PropertyMap children = prop->GetChildren();
for (DBGp::Property::PropertyMap::const_iterator i = children.begin(); i != children.end(); i++) {
DBGp::Property *child = i->second;
text << wxT("\n\t") << child->GetName() << wxT(" (") << child->GetType().GetName() << wxT(") : ");
if (child->HasChildren()) {
text << _("<complex data structure>");
}
else {
text << child->GetData();
}
}
}
else {
text << prop->GetData();
}
tipWindow = new wxTipWindow(this, text, 640, &tipWindow);
tipWindow->SetBoundingRect(wxRect(-1, -1, -1, -1));
}
}
// }}}
// {{{ void SourceTextCtrl::OnExamineValue(wxCommandEvent &event)
void SourceTextCtrl::OnExamineValue(wxCommandEvent &event) {
DBGp::Property *prop = GetPropertyAtPosition(menuPos);
if (prop) {
PropertyDialog pd(this, wxID_ANY, prop);
pd.ShowModal();
}
}
// }}}
// {{{ void SourceTextCtrl::OnMarginClick(wxStyledTextEvent &event)
void SourceTextCtrl::OnMarginClick(wxStyledTextEvent &event) {
ToggleBreakpoint(LineFromPosition(event.GetPosition()));
}
// }}}
// {{{ void SourceTextCtrl::OnRunToHere(wxCommandEvent &event)
void SourceTextCtrl::OnRunToHere(wxCommandEvent &event) {
if (handler) {
handler->BreakpointAdd(LineFromPosition(menuPos) + 1, true);
}
}
// }}}
// {{{ void SourceTextCtrl::OnSelectAll(wxCommandEvent &event)
void SourceTextCtrl::OnSelectAll(wxCommandEvent &event) {
SelectAll();
}
// }}}
// {{{ void SourceTextCtrl::OnToggleBreakpoint(wxCommandEvent &event)
void SourceTextCtrl::OnToggleBreakpoint(wxCommandEvent &event) {
ToggleBreakpoint(LineFromPosition(menuPos));
}
// }}}
// {{{ void SourceTextCtrl::SetLexerOptions(int lexer)
void SourceTextCtrl::SetLexerOptions(int lexer) {
for (const Lexers *l = lexers; l->lexer != -1; l++) {
if (l->lexer == lexer) {
SetKeyWords(4, l->keywords);
SetStyleBits(l->bits);
}
}
}
// }}}
// {{{ void SourceTextCtrl::SetStyleOptions(int lexer)
void SourceTextCtrl::SetStyleOptions(int lexer) {
for (const TokenTypes *t = tokenTypes; t->token != END; t++) {
if (t->lexer == lexer) {
switch (t->token) {
case COMMENT:
StyleSetForeground(t->stcType, wxT("blue"));
break;
case KEYWORD:
StyleSetBold(t->stcType, true);
StyleSetForeground(t->stcType, wxT("dark green"));
break;
case LITERAL:
StyleSetForeground(t->stcType, wxT("magenta"));
break;
case OPERATOR:
StyleSetBold(t->stcType, true);
StyleSetForeground(t->stcType, wxT("brown"));
break;
case DEFAULT:
case IDENTIFIER:
default:
;
}
}
}
}
// }}}
// {{{ void SourceTextCtrl::ToggleBreakpoint(int line)
void SourceTextCtrl::ToggleBreakpoint(int line) {
if (std::count(breakpoints.begin(), breakpoints.end(), line) > 0) {
RemoveBreakpoint(line);
}
else {
AddBreakpoint(line);
}
}
// }}}
// vim:set fdm=marker ts=8 sw=8 noet cin:
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include "plan_service_capability.h"
#include <moveit/planning_pipeline/planning_pipeline.h>
#include <moveit/move_group/capability_names.h>
move_group::MoveGroupPlanService::MoveGroupPlanService() : MoveGroupCapability("MotionPlanService")
{
}
void move_group::MoveGroupPlanService::initialize()
{
plan_service_ =
root_node_handle_.advertiseService(PLANNER_SERVICE_NAME, &MoveGroupPlanService::computePlanService, this);
}
bool move_group::MoveGroupPlanService::computePlanService(moveit_msgs::GetMotionPlan::Request& req,
moveit_msgs::GetMotionPlan::Response& res)
{
ROS_INFO("Received new planning service request...");
// before we start planning, ensure that we have the latest robot state received...
context_->planning_scene_monitor_->waitForCurrentRobotState(ros::Time::now());
context_->planning_scene_monitor_->updateFrameTransforms();
bool solved = false;
planning_scene_monitor::LockedPlanningSceneRO ps(context_->planning_scene_monitor_);
try
{
planning_interface::MotionPlanResponse mp_res;
context_->planning_pipeline_->generatePlan(ps, req.motion_plan_request, mp_res);
mp_res.getMessage(res.motion_plan_response);
}
catch (std::exception& ex)
{
ROS_ERROR("Planning pipeline threw an exception: %s", ex.what());
res.motion_plan_response.error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE;
}
return true;
}
#include <class_loader/class_loader.hpp>
CLASS_LOADER_REGISTER_CLASS(move_group::MoveGroupPlanService, move_group::MoveGroupCapability)
<commit_msg>disable waitForCurrentRobotState() for PlanService capability (#923)<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include "plan_service_capability.h"
#include <moveit/planning_pipeline/planning_pipeline.h>
#include <moveit/move_group/capability_names.h>
move_group::MoveGroupPlanService::MoveGroupPlanService() : MoveGroupCapability("MotionPlanService")
{
}
void move_group::MoveGroupPlanService::initialize()
{
plan_service_ =
root_node_handle_.advertiseService(PLANNER_SERVICE_NAME, &MoveGroupPlanService::computePlanService, this);
}
bool move_group::MoveGroupPlanService::computePlanService(moveit_msgs::GetMotionPlan::Request& req,
moveit_msgs::GetMotionPlan::Response& res)
{
ROS_INFO("Received new planning service request...");
// before we start planning, ensure that we have the latest robot state received...
// for now disable this (see https://github.com/ros-planning/moveit/issues/868)
// context_->planning_scene_monitor_->waitForCurrentRobotState(ros::Time::now());
context_->planning_scene_monitor_->updateFrameTransforms();
bool solved = false;
planning_scene_monitor::LockedPlanningSceneRO ps(context_->planning_scene_monitor_);
try
{
planning_interface::MotionPlanResponse mp_res;
context_->planning_pipeline_->generatePlan(ps, req.motion_plan_request, mp_res);
mp_res.getMessage(res.motion_plan_response);
}
catch (std::exception& ex)
{
ROS_ERROR("Planning pipeline threw an exception: %s", ex.what());
res.motion_plan_response.error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE;
}
return true;
}
#include <class_loader/class_loader.hpp>
CLASS_LOADER_REGISTER_CLASS(move_group::MoveGroupPlanService, move_group::MoveGroupCapability)
<|endoftext|>
|
<commit_before>
class Solution {
public:
/**
* @param heights: a vector of integers
* @return: an integer
*/
int maxArea(vector<int> &height) {
int max = 0, area;
int start = 0, end = height.size() - 1;
// substructure
// perfect attribute
// minimum border decide when length is fixeds
while (start < end) {
if (height[start] > height[end]) {
area = height[end] * (end - start);
end --;
} else {
area = height[start] * (end - start);
start ++;
}
if (area > max) {
max = area;
}
}
return max;
}
};<commit_msg>Proving 383<commit_after>
class Solution {
public:
/**
* @param heights: a vector of integers
* @return: an integer
*/
int maxArea(vector<int> &height) {
int max = 0, area;
int start = 0, end = height.size() - 1;
// substructure
// perfect attribute
// minimum border decide when length is fixed
while (start < end) {
if (height[start] > height[end]) {
area = height[end] * (end - start);
end --;
} else {
area = height[start] * (end - start);
start ++;
}
if (area > max) {
max = area;
}
}
return max;
}
};
// Total Runtime: 51 ms<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/SDKString.h"
#include "../Characters/String_Constant.h"
#include "../Characters/Tokenize.h"
#include "CommandLine.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using Characters::String_Constant;
/*
********************************************************************************
******************* Execution::InvalidCommandLineArgument **********************
********************************************************************************
*/
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument ()
: StringException (String_Constant (L"Invalid Command Argument"))
, fMessage ()
, fArgument ()
{
}
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument (const String& message)
: StringException (message.As<wstring> ())
, fMessage (message)
, fArgument ()
{
}
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument (const String& message, const String& argument)
: StringException (message.As<wstring> ())
, fMessage (message)
, fArgument (argument)
{
}
/*
********************************************************************************
************************* Execution::ParseCommandLine **************************
********************************************************************************
*/
Sequence<String> Execution::ParseCommandLine (const String& cmdLine)
{
Sequence<String> result;
// super quickie hack impl
result = Characters::Tokenize<String> (cmdLine, String_Constant(L" "));
return result;
}
Sequence<String> Execution::ParseCommandLine (int argc, const char* argv[])
{
Require (argc >= 0);
Sequence<String> results;
for (int i = 0; i < argc; ++i) {
results.push_back (String::FromNarrowSDKString (argv[i]));
}
return results;
}
Sequence<String> Execution::ParseCommandLine (int argc, const wchar_t* argv[])
{
Require (argc >= 0);
Sequence<String> results;
for (int i = 0; i < argc; ++i) {
results.push_back (argv[i]);
}
return results;
}
/*
********************************************************************************
****************** Execution::MatchesCommandLineArgument ***********************
********************************************************************************
*/
namespace {
String Simplify2Compare_ (const String& actualArg)
{
return actualArg.StripAll ([](Characters::Character c) -> bool { return c == '-' or c == '/'; }).ToLowerCase ();
}
}
bool Execution::MatchesCommandLineArgument (const String& actualArg, const String& matchesArgPattern)
{
// Command-line arguments must start with - or / (windows only)
if (actualArg.empty ()) {
return false;
}
#if qPlatform_Windows
if (actualArg[0] != '-' and actualArg[0] != '/') {
return false;
}
#else
if (actualArg[0] != '-') {
return false;
}
#endif
return Simplify2Compare_ (actualArg) == Simplify2Compare_ (matchesArgPattern);
}
bool Execution::MatchesCommandLineArgument (const String& actualArg, const String& matchesArgPattern, String* associatedArgResult)
{
Require (matchesArgPattern.GetLength () > 0 and matchesArgPattern[matchesArgPattern.GetLength () - 1] == '=');
AssertNotImplemented ();
// must first strip everything after the '=' in the actualarg, and then similar to first overload...
return false;
}
bool Execution::MatchesCommandLineArgument (const Iterable<String>& argList, const String& matchesArgPattern)
{
return argList.FindFirstThat ([matchesArgPattern] (String i) ->bool { return Execution::MatchesCommandLineArgument (i, matchesArgPattern); });
}
bool Execution::MatchesCommandLineArgument (const Iterable<String>& argList, const String& matchesArgPattern, String* associatedArgResult)
{
return argList.FindFirstThat ([matchesArgPattern, associatedArgResult] (String i) -> bool { return Execution::MatchesCommandLineArgument (i, matchesArgPattern); });
}
<commit_msg>fixed Execution::MatchesCommandLineArgument/3 (returing result)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/SDKString.h"
#include "../Characters/String_Constant.h"
#include "../Characters/Tokenize.h"
#include "CommandLine.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using Characters::String_Constant;
/*
********************************************************************************
******************* Execution::InvalidCommandLineArgument **********************
********************************************************************************
*/
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument ()
: StringException (String_Constant (L"Invalid Command Argument"))
, fMessage ()
, fArgument ()
{
}
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument (const String& message)
: StringException (message.As<wstring> ())
, fMessage (message)
, fArgument ()
{
}
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument (const String& message, const String& argument)
: StringException (message.As<wstring> ())
, fMessage (message)
, fArgument (argument)
{
}
/*
********************************************************************************
************************* Execution::ParseCommandLine **************************
********************************************************************************
*/
Sequence<String> Execution::ParseCommandLine (const String& cmdLine)
{
Sequence<String> result;
// super quickie hack impl
result = Characters::Tokenize<String> (cmdLine, String_Constant(L" "));
return result;
}
Sequence<String> Execution::ParseCommandLine (int argc, const char* argv[])
{
Require (argc >= 0);
Sequence<String> results;
for (int i = 0; i < argc; ++i) {
results.push_back (String::FromNarrowSDKString (argv[i]));
}
return results;
}
Sequence<String> Execution::ParseCommandLine (int argc, const wchar_t* argv[])
{
Require (argc >= 0);
Sequence<String> results;
for (int i = 0; i < argc; ++i) {
results.push_back (argv[i]);
}
return results;
}
/*
********************************************************************************
****************** Execution::MatchesCommandLineArgument ***********************
********************************************************************************
*/
namespace {
String Simplify2Compare_ (const String& actualArg)
{
return actualArg.StripAll ([](Characters::Character c) -> bool { return c == '-' or c == '/'; }).ToLowerCase ();
}
}
bool Execution::MatchesCommandLineArgument (const String& actualArg, const String& matchesArgPattern)
{
// Command-line arguments must start with - or / (windows only)
if (actualArg.empty ()) {
return false;
}
#if qPlatform_Windows
if (actualArg[0] != '-' and actualArg[0] != '/') {
return false;
}
#else
if (actualArg[0] != '-') {
return false;
}
#endif
return Simplify2Compare_ (actualArg) == Simplify2Compare_ (matchesArgPattern);
}
bool Execution::MatchesCommandLineArgument (const String& actualArg, const String& matchesArgPattern, String* associatedArgResult)
{
Require (matchesArgPattern.GetLength () > 0 and matchesArgPattern[matchesArgPattern.GetLength () - 1] == '=');
AssertNotImplemented ();
// must first strip everything after the '=' in the actualarg, and then similar to first overload...
return false;
}
bool Execution::MatchesCommandLineArgument (const Iterable<String>& argList, const String& matchesArgPattern)
{
return argList.FindFirstThat ([matchesArgPattern] (String i) ->bool { return Execution::MatchesCommandLineArgument (i, matchesArgPattern); });
}
bool Execution::MatchesCommandLineArgument (const Iterable<String>& argList, const String& matchesArgPattern, String* associatedArgResult)
{
auto i = argList.FindFirstThat ([matchesArgPattern, associatedArgResult] (String i) -> bool { return Execution::MatchesCommandLineArgument (i, matchesArgPattern); });
if (i != argList.end ()) {
++i;
if (i == argList.end ()) {
Execution::DoThrow (InvalidCommandLineArgument ());
}
else {
if (associatedArgResult != nullptr) {
*associatedArgResult = *i;
}
}
return true;
}
return false;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.