<commit_before>
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkCanvas.h"
#include "SkRRect.h"
#include "SkSurface.h"
#include "Test.h"

#if SK_SUPPORT_GPU
#include "GrContextFactory.h"
#else
class GrContextFactory;
class GrContext;
#endif

enum SurfaceType {
    kRaster_SurfaceType,
    kGpu_SurfaceType,
    kPicture_SurfaceType
};

static SkSurface* createSurface(SurfaceType surfaceType, GrContext* context) {
    static const SkImage::Info imageSpec = {
        10,  // width
        10,  // height
        SkImage::kPMColor_ColorType,
        SkImage::kPremul_AlphaType
    };

    switch (surfaceType) {
    case kRaster_SurfaceType:
        return SkSurface::NewRaster(imageSpec);
    case kGpu_SurfaceType:
#if SK_SUPPORT_GPU
        SkASSERT(NULL != context);
        return SkSurface::NewRenderTarget(context, imageSpec);
#else
        SkASSERT(0);
#endif
    case kPicture_SurfaceType:
        return SkSurface::NewPicture(10, 10);
    }
    SkASSERT(0);
    return NULL;
}

static void TestSurfaceCopyOnWrite(skiatest::Reporter* reporter, SurfaceType surfaceType,
                                   GrContext* context) {
    // Verify that the right canvas commands trigger a copy on write
    SkSurface* surface = createSurface(surfaceType, context);
    SkAutoTUnref<SkSurface> aur_surface(surface);
    SkCanvas* canvas = surface->getCanvas();

    const SkRect testRect =
        SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
                         SkIntToScalar(4), SkIntToScalar(5));
    SkMatrix testMatrix;
    testMatrix.reset();
    testMatrix.setScale(SkIntToScalar(2), SkIntToScalar(3));

    SkPath testPath;
    testPath.addRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
                                      SkIntToScalar(2), SkIntToScalar(1)));

    const SkIRect testIRect = SkIRect::MakeXYWH(0, 0, 2, 1);

    SkRegion testRegion;
    testRegion.setRect(testIRect);

    const SkColor testColor = 0x01020304;
    const SkPaint testPaint;
    const SkPoint testPoints[3] = {
        {SkIntToScalar(0), SkIntToScalar(0)},
        {SkIntToScalar(2), SkIntToScalar(1)},
        {SkIntToScalar(0), SkIntToScalar(2)}
    };
    const size_t testPointCount = 3;

    SkBitmap testBitmap;
    testBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
    testBitmap.allocPixels();

    SkRRect testRRect;
    testRRect.setRectXY(testRect, SK_Scalar1, SK_Scalar1);

    SkString testText("Hello World");
    const SkPoint testPoints2[] = {
        { SkIntToScalar(0), SkIntToScalar(1) },
        { SkIntToScalar(1), SkIntToScalar(1) },
        { SkIntToScalar(2), SkIntToScalar(1) },
        { SkIntToScalar(3), SkIntToScalar(1) },
        { SkIntToScalar(4), SkIntToScalar(1) },
        { SkIntToScalar(5), SkIntToScalar(1) },
        { SkIntToScalar(6), SkIntToScalar(1) },
        { SkIntToScalar(7), SkIntToScalar(1) },
        { SkIntToScalar(8), SkIntToScalar(1) },
        { SkIntToScalar(9), SkIntToScalar(1) },
        { SkIntToScalar(10), SkIntToScalar(1) },
    };

#define EXPECT_COPY_ON_WRITE(command)                               \
    {                                                               \
        SkImage* imageBefore = surface->newImageSnapshot();         \
        SkAutoTUnref<SkImage> aur_before(imageBefore);              \
        canvas-> command ;                                          \
        SkImage* imageAfter = surface->newImageSnapshot();          \
        SkAutoTUnref<SkImage> aur_after(imageAfter);                \
        REPORTER_ASSERT(reporter, imageBefore != imageAfter);       \
    }

    EXPECT_COPY_ON_WRITE(clear(testColor))
    EXPECT_COPY_ON_WRITE(drawPaint(testPaint))
    EXPECT_COPY_ON_WRITE(drawPoints(SkCanvas::kPoints_PointMode, testPointCount, testPoints, \
        testPaint))
    EXPECT_COPY_ON_WRITE(drawOval(testRect, testPaint))
    EXPECT_COPY_ON_WRITE(drawRect(testRect, testPaint))
    EXPECT_COPY_ON_WRITE(drawRRect(testRRect, testPaint))
    EXPECT_COPY_ON_WRITE(drawPath(testPath, testPaint))
    EXPECT_COPY_ON_WRITE(drawBitmap(testBitmap, 0, 0))
    EXPECT_COPY_ON_WRITE(drawBitmapRect(testBitmap, NULL, testRect))
    EXPECT_COPY_ON_WRITE(drawBitmapMatrix(testBitmap, testMatrix, NULL))
    EXPECT_COPY_ON_WRITE(drawBitmapNine(testBitmap, testIRect, testRect, NULL))
    EXPECT_COPY_ON_WRITE(drawSprite(testBitmap, 0, 0, NULL))
    EXPECT_COPY_ON_WRITE(drawText(testText.c_str(), testText.size(), 0, 1, testPaint))
    EXPECT_COPY_ON_WRITE(drawPosText(testText.c_str(), testText.size(), testPoints2, \
        testPaint))
    EXPECT_COPY_ON_WRITE(drawTextOnPath(testText.c_str(), testText.size(), testPath, NULL, \
        testPaint))
}

static void TestSurfaceWritableAfterSnapshotRelease(skiatest::Reporter* reporter,
                                                    SurfaceType surfaceType,
                                                    GrContext* context) {
    // This test succeeds by not triggering an assertion.
    // The test verifies that the surface remains writable (usable) after
    // acquiring and releasing a snapshot without triggering a copy on write.
    SkSurface* surface = createSurface(surfaceType, context);
    SkAutoTUnref<SkSurface> aur_surface(surface);
    SkCanvas* canvas = surface->getCanvas();
    canvas->clear(1);
    surface->newImageSnapshot()->unref();  // Create and destroy SkImage
    canvas->clear(2);
}

static void TestGetTexture(skiatest::Reporter* reporter,
                                 SurfaceType surfaceType,
                                 GrContext* context) {
    SkAutoTUnref<SkSurface> surface(createSurface(surfaceType, context));
    SkAutoTUnref<SkImage> image(surface->newImageSnapshot());
    GrTexture* texture = image->getTexture();
    if (surfaceType == kGpu_SurfaceType) {
        REPORTER_ASSERT(reporter, NULL != texture);
        REPORTER_ASSERT(reporter, 0 != texture->getTextureHandle());
    } else {
        REPORTER_ASSERT(reporter, NULL == texture);
    }
    surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);
    REPORTER_ASSERT(reporter, image->getTexture() == texture);
}

static void TestSurfaceNoCanvas(skiatest::Reporter* reporter,
                                          SurfaceType surfaceType,
                                          GrContext* context,
                                          SkSurface::ContentChangeMode mode) {
    // Verifies the robustness of SkSurface for handling use cases where calls
    // are made before a canvas is created.
    {
        // Test passes by not asserting
        SkSurface* surface = createSurface(surfaceType, context);
        SkAutoTUnref<SkSurface> aur_surface(surface);
        surface->notifyContentWillChange(mode);
        surface->validate();
    }
    {
        SkSurface* surface = createSurface(surfaceType, context);
        SkAutoTUnref<SkSurface> aur_surface(surface);
        SkImage* image1 = surface->newImageSnapshot();
        SkAutoTUnref<SkImage> aur_image1(image1);
        image1->validate();
        surface->validate();
        surface->notifyContentWillChange(mode);
        image1->validate();
        surface->validate();
        SkImage* image2 = surface->newImageSnapshot();
        SkAutoTUnref<SkImage> aur_image2(image2);
        image2->validate();
        surface->validate();
        REPORTER_ASSERT(reporter, image1 != image2);
    }

}

static void TestSurface(skiatest::Reporter* reporter, GrContextFactory* factory) {
    TestSurfaceCopyOnWrite(reporter, kRaster_SurfaceType, NULL);
    TestSurfaceCopyOnWrite(reporter, kPicture_SurfaceType, NULL);
    TestSurfaceWritableAfterSnapshotRelease(reporter, kRaster_SurfaceType, NULL);
    TestSurfaceWritableAfterSnapshotRelease(reporter, kPicture_SurfaceType, NULL);
    TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kDiscard_ContentChangeMode);
    TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kRetain_ContentChangeMode);
    TestGetTexture(reporter, kRaster_SurfaceType, NULL);
    TestGetTexture(reporter, kPicture_SurfaceType, NULL);
#if SK_SUPPORT_GPU
    if (NULL != factory) {
        GrContext* context = factory->get(GrContextFactory::kNative_GLContextType);
        TestSurfaceCopyOnWrite(reporter, kGpu_SurfaceType, context);
        TestSurfaceWritableAfterSnapshotRelease(reporter, kGpu_SurfaceType, context);
        TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kDiscard_ContentChangeMode);
        TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kRetain_ContentChangeMode);
        TestGetTexture(reporter, kGpu_SurfaceType, context);
    }
#endif
}

#include "TestClassDef.h"
DEFINE_GPUTESTCLASS("Surface", SurfaceTestClass, TestSurface)
<commit_msg>Build fix for SurfaceTest on non-gpu platforms<commit_after>
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkCanvas.h"
#include "SkRRect.h"
#include "SkSurface.h"
#include "Test.h"

#if SK_SUPPORT_GPU
#include "GrContextFactory.h"
#else
class GrContextFactory;
class GrContext;
#endif

enum SurfaceType {
    kRaster_SurfaceType,
    kGpu_SurfaceType,
    kPicture_SurfaceType
};

static SkSurface* createSurface(SurfaceType surfaceType, GrContext* context) {
    static const SkImage::Info imageSpec = {
        10,  // width
        10,  // height
        SkImage::kPMColor_ColorType,
        SkImage::kPremul_AlphaType
    };

    switch (surfaceType) {
    case kRaster_SurfaceType:
        return SkSurface::NewRaster(imageSpec);
    case kGpu_SurfaceType:
#if SK_SUPPORT_GPU
        SkASSERT(NULL != context);
        return SkSurface::NewRenderTarget(context, imageSpec);
#else
        SkASSERT(0);
#endif
    case kPicture_SurfaceType:
        return SkSurface::NewPicture(10, 10);
    }
    SkASSERT(0);
    return NULL;
}

static void TestSurfaceCopyOnWrite(skiatest::Reporter* reporter, SurfaceType surfaceType,
                                   GrContext* context) {
    // Verify that the right canvas commands trigger a copy on write
    SkSurface* surface = createSurface(surfaceType, context);
    SkAutoTUnref<SkSurface> aur_surface(surface);
    SkCanvas* canvas = surface->getCanvas();

    const SkRect testRect =
        SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
                         SkIntToScalar(4), SkIntToScalar(5));
    SkMatrix testMatrix;
    testMatrix.reset();
    testMatrix.setScale(SkIntToScalar(2), SkIntToScalar(3));

    SkPath testPath;
    testPath.addRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
                                      SkIntToScalar(2), SkIntToScalar(1)));

    const SkIRect testIRect = SkIRect::MakeXYWH(0, 0, 2, 1);

    SkRegion testRegion;
    testRegion.setRect(testIRect);

    const SkColor testColor = 0x01020304;
    const SkPaint testPaint;
    const SkPoint testPoints[3] = {
        {SkIntToScalar(0), SkIntToScalar(0)},
        {SkIntToScalar(2), SkIntToScalar(1)},
        {SkIntToScalar(0), SkIntToScalar(2)}
    };
    const size_t testPointCount = 3;

    SkBitmap testBitmap;
    testBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
    testBitmap.allocPixels();

    SkRRect testRRect;
    testRRect.setRectXY(testRect, SK_Scalar1, SK_Scalar1);

    SkString testText("Hello World");
    const SkPoint testPoints2[] = {
        { SkIntToScalar(0), SkIntToScalar(1) },
        { SkIntToScalar(1), SkIntToScalar(1) },
        { SkIntToScalar(2), SkIntToScalar(1) },
        { SkIntToScalar(3), SkIntToScalar(1) },
        { SkIntToScalar(4), SkIntToScalar(1) },
        { SkIntToScalar(5), SkIntToScalar(1) },
        { SkIntToScalar(6), SkIntToScalar(1) },
        { SkIntToScalar(7), SkIntToScalar(1) },
        { SkIntToScalar(8), SkIntToScalar(1) },
        { SkIntToScalar(9), SkIntToScalar(1) },
        { SkIntToScalar(10), SkIntToScalar(1) },
    };

#define EXPECT_COPY_ON_WRITE(command)                               \
    {                                                               \
        SkImage* imageBefore = surface->newImageSnapshot();         \
        SkAutoTUnref<SkImage> aur_before(imageBefore);              \
        canvas-> command ;                                          \
        SkImage* imageAfter = surface->newImageSnapshot();          \
        SkAutoTUnref<SkImage> aur_after(imageAfter);                \
        REPORTER_ASSERT(reporter, imageBefore != imageAfter);       \
    }

    EXPECT_COPY_ON_WRITE(clear(testColor))
    EXPECT_COPY_ON_WRITE(drawPaint(testPaint))
    EXPECT_COPY_ON_WRITE(drawPoints(SkCanvas::kPoints_PointMode, testPointCount, testPoints, \
        testPaint))
    EXPECT_COPY_ON_WRITE(drawOval(testRect, testPaint))
    EXPECT_COPY_ON_WRITE(drawRect(testRect, testPaint))
    EXPECT_COPY_ON_WRITE(drawRRect(testRRect, testPaint))
    EXPECT_COPY_ON_WRITE(drawPath(testPath, testPaint))
    EXPECT_COPY_ON_WRITE(drawBitmap(testBitmap, 0, 0))
    EXPECT_COPY_ON_WRITE(drawBitmapRect(testBitmap, NULL, testRect))
    EXPECT_COPY_ON_WRITE(drawBitmapMatrix(testBitmap, testMatrix, NULL))
    EXPECT_COPY_ON_WRITE(drawBitmapNine(testBitmap, testIRect, testRect, NULL))
    EXPECT_COPY_ON_WRITE(drawSprite(testBitmap, 0, 0, NULL))
    EXPECT_COPY_ON_WRITE(drawText(testText.c_str(), testText.size(), 0, 1, testPaint))
    EXPECT_COPY_ON_WRITE(drawPosText(testText.c_str(), testText.size(), testPoints2, \
        testPaint))
    EXPECT_COPY_ON_WRITE(drawTextOnPath(testText.c_str(), testText.size(), testPath, NULL, \
        testPaint))
}

static void TestSurfaceWritableAfterSnapshotRelease(skiatest::Reporter* reporter,
                                                    SurfaceType surfaceType,
                                                    GrContext* context) {
    // This test succeeds by not triggering an assertion.
    // The test verifies that the surface remains writable (usable) after
    // acquiring and releasing a snapshot without triggering a copy on write.
    SkSurface* surface = createSurface(surfaceType, context);
    SkAutoTUnref<SkSurface> aur_surface(surface);
    SkCanvas* canvas = surface->getCanvas();
    canvas->clear(1);
    surface->newImageSnapshot()->unref();  // Create and destroy SkImage
    canvas->clear(2);
}

#if SK_SUPPORT_GPU
static void TestGetTexture(skiatest::Reporter* reporter,
                                 SurfaceType surfaceType,
                                 GrContext* context) {
    SkAutoTUnref<SkSurface> surface(createSurface(surfaceType, context));
    SkAutoTUnref<SkImage> image(surface->newImageSnapshot());
    GrTexture* texture = image->getTexture();
    if (surfaceType == kGpu_SurfaceType) {
        REPORTER_ASSERT(reporter, NULL != texture);
        REPORTER_ASSERT(reporter, 0 != texture->getTextureHandle());
    } else {
        REPORTER_ASSERT(reporter, NULL == texture);
    }
    surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);
    REPORTER_ASSERT(reporter, image->getTexture() == texture);
}
#endif

static void TestSurfaceNoCanvas(skiatest::Reporter* reporter,
                                          SurfaceType surfaceType,
                                          GrContext* context,
                                          SkSurface::ContentChangeMode mode) {
    // Verifies the robustness of SkSurface for handling use cases where calls
    // are made before a canvas is created.
    {
        // Test passes by not asserting
        SkSurface* surface = createSurface(surfaceType, context);
        SkAutoTUnref<SkSurface> aur_surface(surface);
        surface->notifyContentWillChange(mode);
        surface->validate();
    }
    {
        SkSurface* surface = createSurface(surfaceType, context);
        SkAutoTUnref<SkSurface> aur_surface(surface);
        SkImage* image1 = surface->newImageSnapshot();
        SkAutoTUnref<SkImage> aur_image1(image1);
        image1->validate();
        surface->validate();
        surface->notifyContentWillChange(mode);
        image1->validate();
        surface->validate();
        SkImage* image2 = surface->newImageSnapshot();
        SkAutoTUnref<SkImage> aur_image2(image2);
        image2->validate();
        surface->validate();
        REPORTER_ASSERT(reporter, image1 != image2);
    }

}

static void TestSurface(skiatest::Reporter* reporter, GrContextFactory* factory) {
    TestSurfaceCopyOnWrite(reporter, kRaster_SurfaceType, NULL);
    TestSurfaceCopyOnWrite(reporter, kPicture_SurfaceType, NULL);
    TestSurfaceWritableAfterSnapshotRelease(reporter, kRaster_SurfaceType, NULL);
    TestSurfaceWritableAfterSnapshotRelease(reporter, kPicture_SurfaceType, NULL);
    TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kDiscard_ContentChangeMode);
    TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kRetain_ContentChangeMode);
#if SK_SUPPORT_GPU
    TestGetTexture(reporter, kRaster_SurfaceType, NULL);
    TestGetTexture(reporter, kPicture_SurfaceType, NULL);
    if (NULL != factory) {
        GrContext* context = factory->get(GrContextFactory::kNative_GLContextType);
        TestSurfaceCopyOnWrite(reporter, kGpu_SurfaceType, context);
        TestSurfaceWritableAfterSnapshotRelease(reporter, kGpu_SurfaceType, context);
        TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kDiscard_ContentChangeMode);
        TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kRetain_ContentChangeMode);
        TestGetTexture(reporter, kGpu_SurfaceType, context);
    }
#endif
}

#include "TestClassDef.h"
DEFINE_GPUTESTCLASS("Surface", SurfaceTestClass, TestSurface)
<|endoftext|>


<commit_before>#include <iostream>
using namespace std;
template <typename T>
struct Node
{
    T data;
    Node<T>* next;
};

template <typename T>
class CyclicList
{
    Node<T>* end;
    void copy(const CyclicList&);
    void del();
public:
    CyclicList();
    CyclicList(const CyclicList&);
    CyclicList& operator=(const CyclicList&);
    ~CyclicList();
    void addElement(const T&);
    bool removeElement(T&);
    void print() const;
};

template <typename T>
void CyclicList<T>::copy(const CyclicList& other)
{
    Node<T>* temp = new Node<T>;
    end = other.end;
    temp = other.end->next;
    while(temp->next != other.end)
    {
        addElement(temp->data);
        temp = temp->next;
        end->next = temp;
    }
}

template <typename T>
CyclicList<T>& CyclicList<T>::operator=(const CyclicList& other)
{
    del();
    copy(other);
    return *this;
}

template <typename T>
void CyclicList<T>::del()
{
    T data;
    while(removeElement(data))
    {
        cout<<"data deleted: "<<data<<endl;
    }
}

template <typename T>
CyclicList<T>::CyclicList()
{
    end = NULL;
}

template <typename T>
CyclicList<T>::CyclicList(const CyclicList& other)
{
    end = new Node<T>;
    copy(other);
}

template <typename T>
void CyclicList<T>::addElement(const T& _data)
{
    if(end == NULL)
    {
		end = new Node<T>;
        end->data = _data;
        end->next = end;
    }
    else
    {
        Node<T>* temp = new Node<T>;
        temp->data = _data;
        temp->next = end->next;
        end->next = temp;
    }
}

template <typename T>
bool CyclicList<T>::removeElement(T& _data)
{
    if(end != NULL)
    {
        Node<T>* temp = new Node<T>;
        temp = end->next;

        end->next = temp->next;
        _data = temp->data;
        if(end == temp)
        {
            end = NULL;
            return 1;
        }
        delete[] temp;
        return 1;
    }
    return 0;
}

template <typename T>
void CyclicList<T>::print() const
{
    Node<T>* temp = new Node<T>;
    temp = end->next;
    while(temp != end)
    {
        cout<<temp->data<<' ';
        temp = temp->next;
    }
    cout<<end->data; //
}

template <typename T>
CyclicList<T>::~CyclicList()
{
    del();
}

int main()
{
    CyclicList<int> a;
    a.addElement(1);
    a.addElement(2);
    a.addElement(3);
    int asd = 1;
    a.removeElement(asd);
    cout<<asd<<endl;
	a.print();
    CyclicList<int> b(a);
    cout<<endl<<"CyclicList(&): ";
    b.print();
    CyclicList<int> c;
    cout<<endl<<"operator=(a): ";
    c = a;
    b.print();
    cout<<endl;
}
<commit_msg>exam 13.04.2014<commit_after>#include <iostream>
using namespace std;
template <typename T>
struct Node
{
    T data;
    Node<T>* next;
};

template <typename T>
class CyclicList
{
    Node<T>* end;
    void copy(const CyclicList&);
    void del();
public:
    CyclicList();
    CyclicList(const CyclicList&);
    CyclicList& operator=(const CyclicList&);
    ~CyclicList();
    void addElement(const T&);
    bool removeElement(T&);
    void print() const;
};

template <typename T>
void CyclicList<T>::copy(const CyclicList& other)
{
    Node<T>* temp = new Node<T>;
    end = other.end;
    temp = other.end->next;
    while(temp->next != other.end)
    {
        addElement(temp->data);
        temp = temp->next;
        end->next = temp;
    }
}

template <typename T>
CyclicList<T>& CyclicList<T>::operator=(const CyclicList& other)
{
    if(this != &other)
    {
        del();
        copy(other);
    }
    return *this;
}

template <typename T>
void CyclicList<T>::del()
{
    T data;
    while(removeElement(data))
    {
        cout<<"data deleted: "<<data<<endl;
    }
}

template <typename T>
CyclicList<T>::CyclicList()
{
    end = NULL;
}

template <typename T>
CyclicList<T>::CyclicList(const CyclicList& other)
{
    end = new Node<T>;
    copy(other);
}

template <typename T>
void CyclicList<T>::addElement(const T& _data)
{
    if(end == NULL)
    {
        end = new Node<T>;
        end->data = _data;
        end->next = end;
    }
    else
    {
        Node<T>* temp = new Node<T>;
        temp->data = _data;
        temp->next = end->next;
        end->next = temp;
    }
}

template <typename T>
bool CyclicList<T>::removeElement(T& _data)
{
    if(end != NULL)
    {
        Node<T>* temp = new Node<T>;
        temp = end->next;

        end->next = temp->next;
        _data = temp->data;
        if(end == temp)
        {
            end = NULL;
            return 1;
        }
        delete[] temp;
        return 1;
    }
    return 0;
}

template <typename T>
void CyclicList<T>::print() const
{
    Node<T>* temp = new Node<T>;
    temp = end->next;
    while(temp != end)
    {
        cout<<temp->data<<' ';
        temp = temp->next;
    }
    cout<<end->data; //
}

template <typename T>
CyclicList<T>::~CyclicList()
{
    del();
}

int main()
{
    CyclicList<int> a;
    a.addElement(1);
    a.addElement(2);
    a.addElement(3);
    int asd = 1;
    a.removeElement(asd);
    cout<<asd<<endl;
    a.print();
    CyclicList<int> b(a);
    cout<<endl<<"CyclicList(&): ";
    b.print();
    CyclicList<int> c;
    cout<<endl<<"operator=(a): ";
    c = a;
    b = a;
    b.print();
    cout<<endl;
}
<|endoftext|>


<commit_before>// $Id$

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

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
***********************************************************************/

#ifdef WIN32

#include <sstream>
#include "ConfusionNet.h"
#include "FactorCollection.h"
#include "Util.h"

// for Windows. not implemented
#pragma warning(disable:4716)

ConfusionNet::ConfusionNet(FactorCollection* p) : InputType(),m_factorCollection(p)
{
	assert(false);
}

ConfusionNet::~ConfusionNet()
{
	assert(false);
}

void ConfusionNet::SetFactorCollection(FactorCollection *p)
{
	assert(false);
}
bool ConfusionNet::ReadF(std::istream& in,const std::vector<FactorType>& factorOrder,int format) {
	assert(false);
}

int ConfusionNet::Read(std::istream& in,const std::vector<FactorType>& factorOrder, FactorCollection &factorCollection)
{
	assert(false);
}

void ConfusionNet::String2Word(const std::string& s,Word& w,const std::vector<FactorType>& factorOrder) {
	assert(false);
}

bool ConfusionNet::ReadFormat0(std::istream& in,const std::vector<FactorType>& factorOrder) {
	assert(false);
}
bool ConfusionNet::ReadFormat1(std::istream& in,const std::vector<FactorType>& factorOrder) {
	assert(false);
}

void ConfusionNet::Print(std::ostream& out) const {
	assert(false);
}

Phrase ConfusionNet::GetSubString(const WordsRange&) const {
	assert(false);
}
const FactorArray& ConfusionNet::GetFactorArray(size_t) const {
	assert(false);
}

std::ostream& operator<<(std::ostream& out,const ConfusionNet& cn)
{
	assert(false);
}

TargetPhraseCollection const* ConfusionNet::CreateTargetPhraseCollection(PhraseDictionaryBase const& d,const WordsRange& r) const
{
	assert(false);
}
TranslationOptionCollection* ConfusionNet::CreateTranslationOptionCollection() const
{
	assert(false);
}

#pragma warning(default:4716)

#endif<commit_msg>remove confusionNet for win32<commit_after><|endoftext|>


<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2018 INRIA.
 *
 * 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.
*/
/*! \file NonSmoothDynamicalSystem.hpp
 * \brief container for DynamicalSystem and Interaction
 */
#ifndef LinearComplementaritySystemsNSDS_H
#define LinearComplementaritySystemsNSDS_H

#include "SiconosPointers.hpp"
#include "Topology.hpp"
#include "DynamicalSystem.hpp"
#include "NonSmoothDynamicalSystem.hpp"
#include "ComplementarityConditionNSL.hpp"
#include "SiconosFwd.hpp"
#include "FirstOrderLinearTIR.hpp"

/** the LinearComplementaritySystemsNSDS_H inherits frim NDSD
    for a direct instanciation of a LCS
*/
class LinearComplementaritySystemsNSDS: public NonSmoothDynamicalSystem
{

private:
  /** serialization hooks
  */
  ACCEPT_SERIALIZATION(LinearComplementaritySystemsNSDS);

  /* a first order linear TI dynamical systems */
  SP::FirstOrderLinearTIDS _ds;
  /* a first order linear TI relation */
  SP::FirstOrderLinearTIR _relation;
  /* a complementarity condition */
  SP::ComplementarityConditionNSL _nslaw;
  /* an interaction*/
  SP::Interaction _interaction;

public:

  /** default constructor
   */
  LinearComplementaritySystemsNSDS();

  /** constructor with t0 and T
   * \param t0 initial time
   * \param T final time
   */
  LinearComplementaritySystemsNSDS(double t0, double T,  SP::SiconosVector x0,
                                   SP::SimpleMatrix A,  SP::SimpleMatrix B,
                                   SP::SimpleMatrix C,  SP::SimpleMatrix D,
                                   SP::SiconosVector a,  SP::SiconosVector b);

  /** destructor
   */
  ~LinearComplementaritySystemsNSDS();

  // --- GETTERS/SETTERS ---

  SP::FirstOrderLinearTIDS ds()
  {
    return _ds;
  };

  SP::FirstOrderLinearTIR relation()
  {
    return _relation;
  };

  SP::ComplementarityConditionNSL nslaw()
  {
    return _nslaw;
  };
  SP::Interaction interaction()
  {
    return _interaction;
  };

};

#endif
<commit_msg>[kernel] add implementation of default destructor<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2018 INRIA.
 *
 * 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.
*/
/*! \file NonSmoothDynamicalSystem.hpp
 * \brief container for DynamicalSystem and Interaction
 */
#ifndef LinearComplementaritySystemsNSDS_H
#define LinearComplementaritySystemsNSDS_H

#include "SiconosPointers.hpp"
#include "Topology.hpp"
#include "DynamicalSystem.hpp"
#include "NonSmoothDynamicalSystem.hpp"
#include "ComplementarityConditionNSL.hpp"
#include "SiconosFwd.hpp"
#include "FirstOrderLinearTIR.hpp"

/** the LinearComplementaritySystemsNSDS_H inherits frim NDSD
    for a direct instanciation of a LCS
*/
class LinearComplementaritySystemsNSDS: public NonSmoothDynamicalSystem
{

private:
  /** serialization hooks
  */
  ACCEPT_SERIALIZATION(LinearComplementaritySystemsNSDS);

  /* a first order linear TI dynamical systems */
  SP::FirstOrderLinearTIDS _ds;
  /* a first order linear TI relation */
  SP::FirstOrderLinearTIR _relation;
  /* a complementarity condition */
  SP::ComplementarityConditionNSL _nslaw;
  /* an interaction*/
  SP::Interaction _interaction;

public:

  /** default constructor
   */
  LinearComplementaritySystemsNSDS();

  /** constructor with t0 and T
   * \param t0 initial time
   * \param T final time
   */
  LinearComplementaritySystemsNSDS(double t0, double T,  SP::SiconosVector x0,
                                   SP::SimpleMatrix A,  SP::SimpleMatrix B,
                                   SP::SimpleMatrix C,  SP::SimpleMatrix D,
                                   SP::SiconosVector a,  SP::SiconosVector b);

  /** destructor
   */
  ~LinearComplementaritySystemsNSDS(){};

  // --- GETTERS/SETTERS ---

  SP::FirstOrderLinearTIDS ds()
  {
    return _ds;
  };

  SP::FirstOrderLinearTIR relation()
  {
    return _relation;
  };

  SP::ComplementarityConditionNSL nslaw()
  {
    return _nslaw;
  };
  SP::Interaction interaction()
  {
    return _interaction;
  };

};

#endif
<|endoftext|>


<commit_before>#include "SystemImplBase.h"
#include "rhodes/JNIRhodes.h"

RHO_GLOBAL int rho_sysimpl_get_property(const char* szPropName, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL int rho_sys_set_sleeping(int sleeping);
RHO_GLOBAL void rho_sys_is_app_installed(const rho::String& appname, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_app_install(const rho::String& url, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_app_uninstall(const rho::String& appname, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_run_app(const rho::String& appname, const rho::String& params, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_bring_to_front();
RHO_GLOBAL void rho_sys_set_full_screen_mode(bool);
RHO_GLOBAL void rho_sys_get_full_screen_mode(rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_set_screen_auto_rotate_mode(bool enable);
RHO_GLOBAL void rho_sys_get_screen_auto_rotate_mode(rho::apiGenerator::CMethodResult& result);

namespace rho {

//----------------------------------------------------------------------------------------------------------------------

class CSystemImpl : public CSystemImplBase
{
    bool mScreenSleeping;
public:
    CSystemImpl() : CSystemImplBase(), mScreenSleeping(true) {}
    virtual ~CSystemImpl(){}

    virtual void getScreenWidth(rho::apiGenerator::CMethodResult& result);
    virtual void getScreenHeight(rho::apiGenerator::CMethodResult& result);
    virtual void getScreenOrientation(rho::apiGenerator::CMethodResult& result);
    virtual void getPpiX(rho::apiGenerator::CMethodResult& result);
    virtual void getPpiY(rho::apiGenerator::CMethodResult& result);
    virtual void getPhoneId(rho::apiGenerator::CMethodResult& result);
    virtual void getDeviceName(rho::apiGenerator::CMethodResult& result);
    virtual void getLocale(rho::apiGenerator::CMethodResult& result);
    virtual void getCountry(rho::apiGenerator::CMethodResult& result);
    virtual void getIsEmulator(rho::apiGenerator::CMethodResult& result);
    virtual void getHasCalendar(rho::apiGenerator::CMethodResult& result);
    virtual void getOemInfo(rho::apiGenerator::CMethodResult& result);
    virtual void getUuid(rho::apiGenerator::CMethodResult& result);
    virtual void getLockWindowSize(rho::apiGenerator::CMethodResult& result);
    virtual void setLockWindowSize(bool, rho::apiGenerator::CMethodResult& result);
    virtual void getKeyboardState(rho::apiGenerator::CMethodResult& result);
    virtual void setKeyboardState(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void getFullScreen(rho::apiGenerator::CMethodResult& result);
    virtual void setFullScreen(bool, rho::apiGenerator::CMethodResult& result);
    virtual void getScreenAutoRotate(rho::apiGenerator::CMethodResult& result);
    virtual void setScreenAutoRotate(bool, rho::apiGenerator::CMethodResult& result);
    virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& result);
    virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& result);
    virtual void setScreenSleeping(bool, rho::apiGenerator::CMethodResult& result);
    virtual void applicationInstall(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void isApplicationInstalled(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void applicationUninstall(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void openUrl(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void setWindowFrame(int, int, int, int, rho::apiGenerator::CMethodResult& result);
    virtual void setWindowPosition(int, int, rho::apiGenerator::CMethodResult& result);
    virtual void setWindowSize(int, int, rho::apiGenerator::CMethodResult& result);
    virtual void bringToFront(rho::apiGenerator::CMethodResult& result);
    virtual void runApplication(const rho::String&, const rho::String&, bool, rho::apiGenerator::CMethodResult& result);
    virtual void getHasCamera(rho::apiGenerator::CMethodResult& result);
    virtual void getPhoneNumber(rho::apiGenerator::CMethodResult& result);
    virtual void getHasNetwork(rho::apiGenerator::CMethodResult& result);
    virtual void getHasWifiNetwork(rho::apiGenerator::CMethodResult& result);
    virtual void getHasCellNetwork(rho::apiGenerator::CMethodResult& result);
    virtual void getDeviceOwnerName(rho::apiGenerator::CMethodResult& result);
    virtual void getDeviceOwnerEmail(rho::apiGenerator::CMethodResult& result);
    virtual void getOsVersion(rho::apiGenerator::CMethodResult& result);
    virtual void getIsSymbolDevice(rho::apiGenerator::CMethodResult& result);
    virtual void hideSplashScreen(rho::apiGenerator::CMethodResult& oResult);

};
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "SystemImpl"

//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenWidth(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("screen_width", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenHeight(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("screen_height", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenOrientation(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("screen_orientation", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getPpiX(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("ppi_x", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getPpiY(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("ppi_y", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getPhoneId(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("phone_id", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getDeviceName(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("device_name", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getLocale(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("locale", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getCountry(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("country", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getIsEmulator(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("is_emulator", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getHasCalendar(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("has_calendar", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getOemInfo(rho::apiGenerator::CMethodResult& result)
{
	rho_sysimpl_get_property("oem_info", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getUuid(rho::apiGenerator::CMethodResult& result)
{
	rho_sysimpl_get_property("uuid", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getLockWindowSize(rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setLockWindowSize(bool, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getKeyboardState(rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setKeyboardState(const rho::String&, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getFullScreen(rho::apiGenerator::CMethodResult& result)
{
    rho_sys_get_full_screen_mode(result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setFullScreen(bool fullmode, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_set_full_screen_mode(fullmode);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenAutoRotate(rho::apiGenerator::CMethodResult& result)
{
    rho_sys_get_screen_auto_rotate_mode(result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setScreenAutoRotate(bool mode, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_set_screen_auto_rotate_mode(mode);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("webview_framework", result);

}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& result)
{
    result.set(mScreenSleeping);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setScreenSleeping(bool flag, rho::apiGenerator::CMethodResult& result)
{
    mScreenSleeping = flag;
    rho_sys_set_sleeping(flag?1:0);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::applicationInstall(const rho::String& url, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_app_install(url, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::isApplicationInstalled(const rho::String& appname, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_is_app_installed(appname, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::applicationUninstall(const rho::String& appname, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_app_uninstall(appname, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::openUrl(const rho::String& url, rho::apiGenerator::CMethodResult& result)
{
    JNIEnv *env = jnienv();
    jclass clsRhodesService = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    jmethodID midOpenExternalUrl = getJNIClassStaticMethod(env, clsRhodesService, "openExternalUrl", "(Ljava/lang/String;)V");
    JNI_EXCEPTION_CHECK(env, result);

    jhstring jhUrl = rho_cast<jstring>(env, url);
    env->CallStaticVoidMethod(clsRhodesService, midOpenExternalUrl, jhUrl.get());

    JNI_EXCEPTION_CHECK(env, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setWindowFrame(int, int, int, int, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setWindowPosition(int, int, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setWindowSize(int, int, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& result)
{
    rho_sys_bring_to_front();
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::runApplication(const rho::String& app, const rho::String& params, bool blocking, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_run_app(app, params, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getHasCamera(CMethodResult& result)
{
    rho_sysimpl_get_property("has_camera", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getPhoneNumber(CMethodResult& result)
{
    rho_sysimpl_get_property("phone_number", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getHasNetwork(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("has_network", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::getHasWifiNetwork(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("has_wifi_network", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::getHasCellNetwork(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("has_cell_network", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getDeviceOwnerName(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("device_owner_name", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getDeviceOwnerEmail(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("device_owner_email", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getOsVersion(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("os_version", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::getIsSymbolDevice(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("is_symbol_device", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::hideSplashScreen(rho::apiGenerator::CMethodResult& result)
{
    JNIEnv *env = jnienv();
    jclass clsRhodesService = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    jmethodID mid = getJNIClassStaticMethod(env, clsRhodesService, "removeSplashScreen", "()V");
    JNI_EXCEPTION_CHECK(env, result);

    env->CallStaticVoidMethod(clsRhodesService, mid);

    JNI_EXCEPTION_CHECK(env, result);
}
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------

class CSystemFactory: public CSystemFactoryBase
{
public:
    ~CSystemFactory(){}

    ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};

//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------

extern "C" void Init_System()
{
    CSystemFactory::setInstance( new CSystemFactory() );
    Init_System_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoSystemApi");
}
//----------------------------------------------------------------------------------------------------------------------

}
<commit_msg>Update SystemImpl.cpp<commit_after>#include "SystemImplBase.h"
#include "rhodes/JNIRhodes.h"

RHO_GLOBAL int rho_sysimpl_get_property(const char* szPropName, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL int rho_sys_set_sleeping(int sleeping);
RHO_GLOBAL void rho_sys_is_app_installed(const rho::String& appname, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_app_install(const rho::String& url, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_app_uninstall(const rho::String& appname, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_run_app(const rho::String& appname, const rho::String& params, rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_bring_to_front();
RHO_GLOBAL void rho_sys_set_full_screen_mode(bool);
RHO_GLOBAL void rho_sys_get_full_screen_mode(rho::apiGenerator::CMethodResult& result);
RHO_GLOBAL void rho_sys_set_screen_auto_rotate_mode(bool enable);
RHO_GLOBAL void rho_sys_get_screen_auto_rotate_mode(rho::apiGenerator::CMethodResult& result);

namespace rho {

//----------------------------------------------------------------------------------------------------------------------

class CSystemImpl : public CSystemImplBase
{
    bool mScreenSleeping;
public:
    CSystemImpl() : CSystemImplBase(), mScreenSleeping(true) {}
    virtual ~CSystemImpl(){}

    virtual void getScreenWidth(rho::apiGenerator::CMethodResult& result);
    virtual void getScreenHeight(rho::apiGenerator::CMethodResult& result);
    virtual void getScreenOrientation(rho::apiGenerator::CMethodResult& result);
    virtual void getPpiX(rho::apiGenerator::CMethodResult& result);
    virtual void getPpiY(rho::apiGenerator::CMethodResult& result);
    virtual void getPhoneId(rho::apiGenerator::CMethodResult& result);
    virtual void getDeviceName(rho::apiGenerator::CMethodResult& result);
    virtual void getLocale(rho::apiGenerator::CMethodResult& result);
    virtual void getCountry(rho::apiGenerator::CMethodResult& result);
    virtual void getIsEmulator(rho::apiGenerator::CMethodResult& result);
    virtual void getHasCalendar(rho::apiGenerator::CMethodResult& result);
    virtual void getOemInfo(rho::apiGenerator::CMethodResult& result);
    virtual void getUuid(rho::apiGenerator::CMethodResult& result);
    virtual void getLockWindowSize(rho::apiGenerator::CMethodResult& result);
    virtual void setLockWindowSize(bool, rho::apiGenerator::CMethodResult& result);
    virtual void getKeyboardState(rho::apiGenerator::CMethodResult& result);
    virtual void setKeyboardState(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void getFullScreen(rho::apiGenerator::CMethodResult& result);
    virtual void setFullScreen(bool, rho::apiGenerator::CMethodResult& result);
    virtual void getScreenAutoRotate(rho::apiGenerator::CMethodResult& result);
    virtual void setScreenAutoRotate(bool, rho::apiGenerator::CMethodResult& result);
    virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& result);
    virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& result);
    virtual void setScreenSleeping(bool, rho::apiGenerator::CMethodResult& result);
    virtual void applicationInstall(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void isApplicationInstalled(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void applicationUninstall(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void openUrl(const rho::String&, rho::apiGenerator::CMethodResult& result);
    virtual void setWindowFrame(int, int, int, int, rho::apiGenerator::CMethodResult& result);
    virtual void setWindowPosition(int, int, rho::apiGenerator::CMethodResult& result);
    virtual void setWindowSize(int, int, rho::apiGenerator::CMethodResult& result);
    virtual void bringToFront(rho::apiGenerator::CMethodResult& result);
    virtual void runApplication(const rho::String&, const rho::String&, bool, rho::apiGenerator::CMethodResult& result);
    virtual void getHasCamera(rho::apiGenerator::CMethodResult& result);
    virtual void getPhoneNumber(rho::apiGenerator::CMethodResult& result);
    virtual void getHasNetwork(rho::apiGenerator::CMethodResult& result);
    virtual void getHasWifiNetwork(rho::apiGenerator::CMethodResult& result);
    virtual void getHasCellNetwork(rho::apiGenerator::CMethodResult& result);
    virtual void getDeviceOwnerName(rho::apiGenerator::CMethodResult& result);
    virtual void getDeviceOwnerEmail(rho::apiGenerator::CMethodResult& result);
    virtual void getOsVersion(rho::apiGenerator::CMethodResult& result);
    virtual void getIsSymbolDevice(rho::apiGenerator::CMethodResult& result);
    virtual void getIsMotorolaDevice(rho::apiGenerator::CMethodResult& result);
    virtual void hideSplashScreen(rho::apiGenerator::CMethodResult& oResult);

};
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "SystemImpl"

//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenWidth(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("screen_width", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenHeight(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("screen_height", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenOrientation(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("screen_orientation", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getPpiX(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("ppi_x", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getPpiY(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("ppi_y", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getPhoneId(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("phone_id", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getDeviceName(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("device_name", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getLocale(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("locale", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getCountry(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("country", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getIsEmulator(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("is_emulator", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getHasCalendar(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("has_calendar", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getOemInfo(rho::apiGenerator::CMethodResult& result)
{
	rho_sysimpl_get_property("oem_info", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getUuid(rho::apiGenerator::CMethodResult& result)
{
	rho_sysimpl_get_property("uuid", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getLockWindowSize(rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setLockWindowSize(bool, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getKeyboardState(rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setKeyboardState(const rho::String&, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getFullScreen(rho::apiGenerator::CMethodResult& result)
{
    rho_sys_get_full_screen_mode(result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setFullScreen(bool fullmode, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_set_full_screen_mode(fullmode);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenAutoRotate(rho::apiGenerator::CMethodResult& result)
{
    rho_sys_get_screen_auto_rotate_mode(result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setScreenAutoRotate(bool mode, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_set_screen_auto_rotate_mode(mode);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("webview_framework", result);

}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& result)
{
    result.set(mScreenSleeping);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setScreenSleeping(bool flag, rho::apiGenerator::CMethodResult& result)
{
    mScreenSleeping = flag;
    rho_sys_set_sleeping(flag?1:0);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::applicationInstall(const rho::String& url, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_app_install(url, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::isApplicationInstalled(const rho::String& appname, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_is_app_installed(appname, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::applicationUninstall(const rho::String& appname, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_app_uninstall(appname, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::openUrl(const rho::String& url, rho::apiGenerator::CMethodResult& result)
{
    JNIEnv *env = jnienv();
    jclass clsRhodesService = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    jmethodID midOpenExternalUrl = getJNIClassStaticMethod(env, clsRhodesService, "openExternalUrl", "(Ljava/lang/String;)V");
    JNI_EXCEPTION_CHECK(env, result);

    jhstring jhUrl = rho_cast<jstring>(env, url);
    env->CallStaticVoidMethod(clsRhodesService, midOpenExternalUrl, jhUrl.get());

    JNI_EXCEPTION_CHECK(env, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setWindowFrame(int, int, int, int, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setWindowPosition(int, int, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::setWindowSize(int, int, rho::apiGenerator::CMethodResult& result)
{
//    result.setError("not implemented at Android platform");
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& result)
{
    rho_sys_bring_to_front();
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::runApplication(const rho::String& app, const rho::String& params, bool blocking, rho::apiGenerator::CMethodResult& result)
{
    rho_sys_run_app(app, params, result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getHasCamera(CMethodResult& result)
{
    rho_sysimpl_get_property("has_camera", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getPhoneNumber(CMethodResult& result)
{
    rho_sysimpl_get_property("phone_number", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getHasNetwork(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("has_network", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::getHasWifiNetwork(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("has_wifi_network", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::getHasCellNetwork(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("has_cell_network", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getDeviceOwnerName(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("device_owner_name", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getDeviceOwnerEmail(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("device_owner_email", result);
}
//----------------------------------------------------------------------------------------------------------------------

void CSystemImpl::getOsVersion(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("os_version", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::getIsMotorolaDevice(rho::apiGenerator::CMethodResult& result)
{
	rho_sysimpl_get_property("is_symbol_device", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::getIsSymbolDevice(rho::apiGenerator::CMethodResult& result)
{
    rho_sysimpl_get_property("is_symbol_device", result);
}
//----------------------------------------------------------------------------------------------------------------------
void CSystemImpl::hideSplashScreen(rho::apiGenerator::CMethodResult& result)
{
    JNIEnv *env = jnienv();
    jclass clsRhodesService = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    jmethodID mid = getJNIClassStaticMethod(env, clsRhodesService, "removeSplashScreen", "()V");
    JNI_EXCEPTION_CHECK(env, result);

    env->CallStaticVoidMethod(clsRhodesService, mid);

    JNI_EXCEPTION_CHECK(env, result);
}
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------

class CSystemFactory: public CSystemFactoryBase
{
public:
    ~CSystemFactory(){}

    ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};

//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------

extern "C" void Init_System()
{
    CSystemFactory::setInstance( new CSystemFactory() );
    Init_System_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoSystemApi");
}
//----------------------------------------------------------------------------------------------------------------------

}
<|endoftext|>


<commit_before>#include <bts/blockchain/chain_database_impl.hpp>

namespace bts { namespace blockchain { namespace detail {

  class market_engine
  {
  public:
    market_engine( pending_chain_state_ptr ps, chain_database_impl& cdi );
    /** return true if execute was successful and applied */
    bool execute( asset_id_type quote_id, asset_id_type base_id, const fc::time_point_sec& timestamp );

  private:
    void push_market_transaction( const market_transaction& mtrx );

    void pay_current_short( market_transaction& mtrx,
                            asset_record& quote_asset,
                            asset_record& base_asset );
    void pay_current_bid( const market_transaction& mtrx, asset_record& quote_asset );
    void pay_current_cover( market_transaction& mtrx, asset_record& quote_asset );
    void pay_current_ask( const market_transaction& mtrx, asset_record& base_asset );

    bool get_next_short();
    bool get_next_bid();
    bool get_next_ask();
    asset get_current_cover_debt()const;
    asset get_cover_interest( const asset& principle )const;

    /**
      *  This method should not affect market execution or validation and
      *  is for historical purposes only.
      */
    void update_market_history( const asset& trading_volume,
                                const price& opening_price,
                                const price& closing_price,
                                const omarket_status& market_stat,
                                const fc::time_point_sec& timestamp );

    void cancel_current_short( market_transaction& mtrx, const asset_id_type& quote_asset_id );
    void cancel_all_shorts();

    pending_chain_state_ptr       _pending_state;
    pending_chain_state_ptr       _prior_state;
    chain_database_impl&          _db_impl;

    optional<market_order>        _current_bid;
    optional<market_order>        _current_ask;
    collateral_record             _current_collat_record;
    asset_id_type                 _quote_id;
    asset_id_type                 _base_id;
    market_status                 _market_stat;

    int                           _orders_filled = 0;

  public:
    vector<market_transaction>    _market_transactions;

  private:
    bts::db::cached_level_map< market_index_key, order_record >::iterator         _bid_itr;
    bts::db::cached_level_map< market_index_key, order_record >::iterator         _ask_itr;
    bts::db::cached_level_map< market_index_key, order_record >::iterator         _short_itr;
    bts::db::cached_level_map< market_index_key, collateral_record >::iterator    _collateral_itr;
  };

} } } // end namespace bts::blockchain::detail

<commit_msg>Make market_engine::cancel_all_shorts() public<commit_after>#include <bts/blockchain/chain_database_impl.hpp>

namespace bts { namespace blockchain { namespace detail {

  class market_engine
  {
  public:
    market_engine( pending_chain_state_ptr ps, chain_database_impl& cdi );
    /** return true if execute was successful and applied */
    bool execute( asset_id_type quote_id, asset_id_type base_id, const fc::time_point_sec& timestamp );

    void cancel_all_shorts();

  private:
    void push_market_transaction( const market_transaction& mtrx );

    void pay_current_short( market_transaction& mtrx,
                            asset_record& quote_asset,
                            asset_record& base_asset );
    void pay_current_bid( const market_transaction& mtrx, asset_record& quote_asset );
    void pay_current_cover( market_transaction& mtrx, asset_record& quote_asset );
    void pay_current_ask( const market_transaction& mtrx, asset_record& base_asset );

    bool get_next_short();
    bool get_next_bid();
    bool get_next_ask();
    asset get_current_cover_debt()const;
    asset get_cover_interest( const asset& principle )const;

    /**
      *  This method should not affect market execution or validation and
      *  is for historical purposes only.
      */
    void update_market_history( const asset& trading_volume,
                                const price& opening_price,
                                const price& closing_price,
                                const omarket_status& market_stat,
                                const fc::time_point_sec& timestamp );

    void cancel_current_short( market_transaction& mtrx, const asset_id_type& quote_asset_id );

    pending_chain_state_ptr       _pending_state;
    pending_chain_state_ptr       _prior_state;
    chain_database_impl&          _db_impl;

    optional<market_order>        _current_bid;
    optional<market_order>        _current_ask;
    collateral_record             _current_collat_record;
    asset_id_type                 _quote_id;
    asset_id_type                 _base_id;
    market_status                 _market_stat;

    int                           _orders_filled = 0;

  public:
    vector<market_transaction>    _market_transactions;

  private:
    bts::db::cached_level_map< market_index_key, order_record >::iterator         _bid_itr;
    bts::db::cached_level_map< market_index_key, order_record >::iterator         _ask_itr;
    bts::db::cached_level_map< market_index_key, order_record >::iterator         _short_itr;
    bts::db::cached_level_map< market_index_key, collateral_record >::iterator    _collateral_itr;
  };

} } } // end namespace bts::blockchain::detail
<|endoftext|>


<commit_before>/*
 * Author: Dino Wernli
 */

#include "listener/bmp_exporter.h"

#include <fstream>

#include "renderer/sampler/sampler.h"
#include "util/color3.h"

BmpExporter::BmpExporter(const std::string& file_name) : file_name_(file_name) {
}

BmpExporter::~BmpExporter() {
}

void BmpExporter::Update(const Sampler& sampler) {
  // Only export if the image is done.
  if (!sampler.IsDone()) {
    return;
  }

  LOG(INFO) << "Exporting image " << file_name_;

  const Image& image = sampler.image();
  std::ofstream file_stream(file_name_, std::ofstream::binary);

  const size_t width = image.SizeX();
  const size_t height = image.SizeY();
  const size_t filesize = 54 + 3*width*height;

  char file_header[14] = {'B','M',0,0,0,0,0,0,0,0,54,0,0,0};
  char info_header[40] = {40,0,0,0,0,0,0,0,0,0,0,0,1,0,24,0};

  file_header[2] = (char)(filesize);
  file_header[3] = (char)(filesize>> 8);
  file_header[4] = (char)(filesize>>16);
  file_header[5] = (char)(filesize>>24);

  info_header[4] = (char)(width);
  info_header[5] = (char)(width>> 8);
  info_header[6] = (char)(width>>16);
  info_header[7] = (char)(width>>24);
  info_header[8] = (char)(height);
  info_header[9] = (char)(height>> 8);
  info_header[10] = (char)(height>>16);
  info_header[11] = (char)(height>>24);

  file_stream.write(file_header, 14).write(info_header, 40);

  // Due to alignment, we must append the following number of bytes as padding.
  const size_t extra_bytes = (4 - (width * 3) % 4) % 4;
  char padding[3] = {0, 0, 0};

  for (size_t row = 0; row < height; ++row) {
    for (size_t col = 0; col < width; ++col) {
      const Color3& pixel = image.PixelAt(col, height - row - 1);
      char buffer[3] = { (char)(pixel.b() * 255),
                         (char)(pixel.g() * 255),
                         (char)(pixel.r() * 255) };
      file_stream.write(buffer, 3);
    }
    file_stream.write(padding, extra_bytes);
  }
  file_stream.close();
}
<commit_msg>Clean up the exporter code some more.<commit_after>/*
 * Author: Dino Wernli
 */

#include "listener/bmp_exporter.h"

#include <fstream>

#include "renderer/sampler/sampler.h"
#include "util/color3.h"

BmpExporter::BmpExporter(const std::string& file_name) : file_name_(file_name) {
}

BmpExporter::~BmpExporter() {
}

static void WriteHeader(size_t width, size_t height, std::ofstream* stream) {
  const size_t filesize = 54 + 3 * width * height;
  char file_header[14] = {'B','M',0,0,0,0,0,0,0,0,54,0,0,0};
  char info_header[40] = {40,0,0,0,0,0,0,0,0,0,0,0,1,0,24,0};

  file_header[2] = (char)(filesize);
  file_header[3] = (char)(filesize>> 8);
  file_header[4] = (char)(filesize>>16);
  file_header[5] = (char)(filesize>>24);

  info_header[4] = (char)(width);
  info_header[5] = (char)(width>> 8);
  info_header[6] = (char)(width>>16);
  info_header[7] = (char)(width>>24);
  info_header[8] = (char)(height);
  info_header[9] = (char)(height>> 8);
  info_header[10] = (char)(height>>16);
  info_header[11] = (char)(height>>24);

  stream->write(file_header, 14).write(info_header, 40);
}

void BmpExporter::Update(const Sampler& sampler) {
  // Only export if the image is done.
  if (!sampler.IsDone()) {
    return;
  }

  LOG(INFO) << "Exporting image " << file_name_;

  std::ofstream file_stream(file_name_, std::ofstream::binary);
  const Image& image = sampler.image();
  const size_t width = image.SizeX();
  const size_t height = image.SizeY();

  WriteHeader(width, height, &file_stream);

  // Due to alignment, we must append the following number of bytes as padding.
  const size_t extra_bytes = (4 - (width * 3) % 4) % 4;
  char padding[3] = {0, 0, 0};

  for (size_t y = 0; y < height; ++y) {
    for (size_t x = 0; x < width; ++x) {
      const Color3& pixel = image.PixelAt(x, height - y - 1);
      char buffer[3] = { (char)(pixel.b() * 255),
                         (char)(pixel.g() * 255),
                         (char)(pixel.r() * 255) };
      file_stream.write(buffer, 3);
    }
    file_stream.write(padding, extra_bytes);
  }
  file_stream.close();
}
<|endoftext|>


<commit_before>/*
 * Author: Dino Wernli
 */

#include "listener/ppm_exporter.h"

#include <fstream>

#include "renderer/sampler/sampler.h"
#include "util/color3.h"

// Transforms an intensity in range [0, 1] to an integer in
// {0, ..., kMaxPixelValue}.
unsigned int ScaleIntensity(Intensity intensity) {
  return intensity * PpmExporter::kMaxPixelValue;
}

PpmExporter::PpmExporter(std::string file_name) : file_name_(file_name) {
}

PpmExporter::~PpmExporter() {
}

void PpmExporter::Update(const Sampler& sampler) {
  // Only export if the image is done.
  if (!sampler.IsDone()) {
    return;
  }

  const Image& image = sampler.image();
  std::ofstream file_stream(file_name_);

  file_stream << kMagicNumber << std::endl;
  file_stream << image.SizeX() << " " << image.SizeY() << std::endl;
  file_stream << kMaxPixelValue << std::endl;

  for (size_t y = 0; y < image.SizeY(); ++y) {
    for (size_t x = 0; x < image.SizeX(); ++x) {
      const Color3& color = image.PixelAt(x, y);
      file_stream << ScaleIntensity(color.r()) << " "
                  << ScaleIntensity(color.g()) << " "
                  << ScaleIntensity(color.b()) << " ";
    }
    file_stream << std::endl;
  }
  file_stream << std::endl;
  file_stream.close();
}

const size_t PpmExporter::kMaxPixelValue = 255;

const std::string PpmExporter::kMagicNumber = "P3";
<commit_msg>Add logging statement for listener.<commit_after>/*
 * Author: Dino Wernli
 */

#include "listener/ppm_exporter.h"

#include <glog/logging.h>
#include <fstream>

#include "renderer/sampler/sampler.h"
#include "util/color3.h"

// Transforms an intensity in range [0, 1] to an integer in
// {0, ..., kMaxPixelValue}.
unsigned int ScaleIntensity(Intensity intensity) {
  return intensity * PpmExporter::kMaxPixelValue;
}

PpmExporter::PpmExporter(std::string file_name) : file_name_(file_name) {
}

PpmExporter::~PpmExporter() {
}

void PpmExporter::Update(const Sampler& sampler) {
  // Only export if the image is done.
  if (!sampler.IsDone()) {
    return;
  }

  LOG(INFO) << "Exporting image " << file_name_;

  const Image& image = sampler.image();
  std::ofstream file_stream(file_name_);

  file_stream << kMagicNumber << std::endl;
  file_stream << image.SizeX() << " " << image.SizeY() << std::endl;
  file_stream << kMaxPixelValue << std::endl;

  for (size_t y = 0; y < image.SizeY(); ++y) {
    for (size_t x = 0; x < image.SizeX(); ++x) {
      const Color3& color = image.PixelAt(x, y);
      file_stream << ScaleIntensity(color.r()) << " "
                  << ScaleIntensity(color.g()) << " "
                  << ScaleIntensity(color.b()) << " ";
    }
    file_stream << std::endl;
  }
  file_stream << std::endl;
  file_stream.close();
}

const size_t PpmExporter::kMaxPixelValue = 255;

const std::string PpmExporter::kMagicNumber = "P3";
<|endoftext|>


<commit_before>#pragma comment(linker, "/STACK:16777216")
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <climits>
#include <numeric>
#include <memory.h>
//#include <ctime>
//clock_t startTime=clock();
//fprintf(stderr,"time=%.3lfsec\n",0.001*(clock()-startTime));
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
typedef pair<double, double> pdd;
typedef vector<pdd> vpdd;
typedef vector<vpii> Graph;

#define fr(i,a,b) for(int i(a),_b(b);i<=_b;++i)
#define frd(i,a,b) for(int i(a),_b(b);i>=_b;--i)
#define rep(i,n) for(int i(0),_n(n);i<_n;++i)
#define reps(i,a) fr(i,0,sz(a)-1)
#define all(a) a.begin(),a.end()
#define pb push_back
#define mp make_pair
#define clr(x,a) memset(x,a,sizeof(x))
#define findx(a,x) (find(all(a),x)-a.begin())
#define two(X) (1LL<<(X))
#define contain(S,X) (((S)&two(X))!=0)

const int dr[]={0,-1,0,1,-1,1, 1,-1};
const int dc[]={1,0,-1,0, 1,1,-1,-1};
const double eps=1e-9;

template<class T> void print(const vector<T> &v){ostringstream os; for(int i=0; i<v.size(); ++i){if(i)os<<' ';os<<v[i];} cout<<os.str()<<endl;}
template<class T> int sz(const T&c){return (int)c.size();}
template<class T> void srt(T&c){sort(c.begin(),c.end());}
template<class T> void checkmin(T &a,T b){if(b<a) a=b;}
template<class T> void checkmax(T &a,T b){if(b>a) a=b;}
template<class T> T sqr(T x){return x*x;}
template<class T, class U> T cast (U x) { ostringstream os; os<<x; T res; istringstream is(os.str()); is>>res; return res; }
template<class T> vector<T> split(string s, string x=" ") {vector<T> res; for(int i=0;i<s.size();i++){string a; while(i<(int)s.size()&&x.find(s[i])==string::npos)a+=s[i++]; if(!a.empty())res.push_back(cast<T>(a));} return res;}
template<class T> bool inside(T r,T c,T R, T C){return r>=0 && r<R && c>=0 && c<C;}

int minu=-1;

void dfs1(vvi &g,const vi &p,int u, vb &vis){
	if(minu==-1 || p[minu]>p[u])minu=u;
	vis[u/2]=true;
	reps(i,g[u]){
		int v=g[u][i];
		if(minu==-1 || p[minu]>p[v])minu=v;
		if(vis[v/2])continue;
		dfs1(g,p,v,vis);
	}
	u=u^1;
	if(u<sz(g)){
		if(minu==-1 || p[minu]>p[u])minu=u;
		reps(i,g[u]){
			int v=g[u][i];
			if(minu==-1 || p[minu]>p[v])minu=v;
			if(vis[v/2])continue;
			dfs1(g,p,v,vis);
		}
	}
}

void dfs(vvi &g,string &s,int u, vb &vis){
	vis[u/2]=true;
	reps(i,g[u]){
		int v=g[u][i];
		if(vis[v/2])continue;
		if(s[u]==s[v])swap(s[v],s[v^1]);
		dfs(g,s,v,vis);
	}
	u=u^1;
	if(u<sz(g))
	reps(i,g[u]){
		int v=g[u][i];
		if(vis[v/2])continue;
		if(s[u]==s[v])swap(s[v],s[v^1]);
		dfs(g,s,v,vis);
	}
}

string solve(const vi &a, const vi &b){
	int n=sz(a);
	vi p(n);
	rep(i,n)p[a[i]]=i;
	vi c(n);
	rep(i,n)c[i]=p[b[i]];
	string s=string(n+n%2, 'A');
	rep(i,(n+1)/2)s[2*i+1]='B';

	vvi g(n);
	rep(i,n/2){
		int x=c[2*i];
		int y=c[2*i+1];
		g[x].pb(y);
		g[y].pb(x);
	}
	vb vis((n+1)/2);
	vb vis1((n+1)/2);
	rep(i,n){
		if(!vis[i/2]){
			minu=-1;
			dfs1(g,a,i,vis1);
			if((minu^1)<n && (a[minu]<a[minu^1] ^ s[minu]<s[minu^1]))swap(s[minu],s[minu^1]);
			dfs(g,s,minu,vis);
		}
	}

	string t=string(n,' ');
	rep(i,n)t[a[i]]=s[i];
	return t;
}

int main( int argc, char* argv[] ) {
	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	#endif

	int tc;
	scanf("%d", &tc);
	//tc=1000;
	while(tc--){
		int n;
		scanf("%d", &n);
		vi a(n);
		rep(i,n)scanf("%d", &a[i]);
		vi b(n);
		rep(i,n)scanf("%d", &b[i]);

		/*
		n=rand()%2000+1;
		//n=20000;
		vi a(n),b(n);
		rep(i,n)a[i]=b[i]=i;
		random_shuffle(all(a));
		random_shuffle(all(b));
		*/

		string t=solve(a,b);

		int z1=0,z2=0;
		int a1=0,b1=0;
		int a2=0,b2=0;
		rep(i,n){
			a1+=t[a[i]]=='A';
			b1+=t[a[i]]=='B';
			a2+=t[b[i]]=='A';
			b2+=t[b[i]]=='B';
			checkmax(z1,abs(a1-b1));
			checkmax(z2,abs(a2-b2));
		}

		if(z1>1||z2>1){
		print(a);
		print(b);
		cout<<"       "<<z1<<" "<<z2<<endl;
		exit(0);
		}

		cout<<t<<endl;
		//cout<<"       "<<z1<<" "<<z2<<endl;
	}
	//cout<<"ok"<<endl;

	return 0;
}
<commit_msg>update<commit_after><|endoftext|>


<commit_before>#include <string>

/*
public class TennisGame4 implements TennisGame {

    int serverScore;
    int receiverScore;
    String server;
    String receiver;

    public TennisGame4(String player1, String player2) {
        this.server = player1;
        this.receiver = player2;
    }

    @java.lang.Override
    public void wonPoint(String playerName) {
        if (server.equals(playerName))
            this.serverScore += 1;
        else
            this.receiverScore += 1;
    }

    @java.lang.Override
    public String getScore() {
        TennisResult result = new Deuce(
                this, new GameServer(
                        this, new GameReceiver(
                                this, new AdvantageServer(
                                        this, new AdvantageReceiver(
                                                this, new DefaultResult(this)))))).getResult();
        return result.format();
    }

    boolean receiverHasAdvantage() {
        return receiverScore >= 4 && (receiverScore - serverScore) == 1;
    }

    boolean serverHasAdvantage() {
        return serverScore >= 4 && (serverScore - receiverScore) == 1;
    }

    boolean receiverHasWon() {
        return receiverScore >= 4 && (receiverScore - serverScore) >= 2;
    }

    boolean serverHasWon() {
        return serverScore >= 4 && (serverScore - receiverScore) >= 2;
    }

    boolean isDeuce() {
        return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore);
    }
}

class TennisResult {
    String serverScore;
    String receiverScore;

    TennisResult(String serverScore, String receiverScore) {
        this.serverScore = serverScore;
        this.receiverScore = receiverScore;
    }

    String format() {
        if ("".equals(this.receiverScore))
            return this.serverScore;
        if (serverScore.equals(receiverScore))
            return serverScore + "-All";
        return this.serverScore + "-" + this.receiverScore;
    }
}

interface ResultProvider {
    TennisResult getResult();
}

class Deuce implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public Deuce(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.isDeuce())
            return new TennisResult("Deuce", "");
        return this.nextResult.getResult();
    }
}

class GameServer implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public GameServer(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.serverHasWon())
            return new TennisResult("Win for " + game.server, "");
        return this.nextResult.getResult();
    }
}

class GameReceiver implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public GameReceiver(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.receiverHasWon())
            return new TennisResult("Win for " + game.receiver, "");
        return this.nextResult.getResult();
    }
}

class AdvantageServer implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public AdvantageServer(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.serverHasAdvantage())
            return new TennisResult("Advantage " + game.server, "");
        return this.nextResult.getResult();
    }
}

class AdvantageReceiver implements ResultProvider {

    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public AdvantageReceiver(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.receiverHasAdvantage())
            return new TennisResult("Advantage " + game.receiver, "");
        return this.nextResult.getResult();
    }
}

class DefaultResult implements ResultProvider {

    private static final String[] scores = {"Love", "Fifteen", "Thirty", "Forty"};

    private final TennisGame4 game;

    public DefaultResult(TennisGame4 game) {
        this.game = game;
    }

    @Override
    public TennisResult getResult() {
        return new TennisResult(scores[game.serverScore], scores[game.receiverScore]);
    }
}
 */

class TennisResult {
public:
    TennisResult(std::string serverScore, std::string receiverScore) {
        this->serverScore = serverScore;
        this->receiverScore = receiverScore;
    }

    std::string format() {
        if ("" == this->receiverScore)
            return this->serverScore;
        if (serverScore == this->receiverScore)
            return serverScore + "-All";
        return this->serverScore + "-" + this->receiverScore;
    }

private:
    std::string serverScore;
    std::string receiverScore;
};

class ResultProvider {
public:
    virtual TennisResult getResult() const = 0;
    virtual ~ResultProvider() = default;
};

class TennisGame4 : ResultProvider {
public:
    int serverScore = 0, receiverScore = 0;
    std::string server;
    std::string receiver;

    TennisGame4(std::string player1, std::string player2) {
        this->server = player1;
        this->receiver = player2;
    }

    TennisResult getResult() const override;
    void wonPoint(std::string playerName);
    bool receiverHasAdvantage() const;
    bool serverHasAdvantage() const;
    bool receiverHasWon() const;
    bool serverHasWon() const;
    bool isDeuce() const;
};

class Deuce : ResultProvider {
public:
    Deuce(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

    TennisResult getResult() const override {
        if (game.isDeuce())
            return TennisResult("Deuce", "");
        return this->nextResult.getResult();
    }

private:
    TennisGame4 const & game;
    ResultProvider const & nextResult;
};

class GameServer : public ResultProvider {
public:
    GameServer(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

    TennisResult getResult() const override {
        if (game.serverHasWon())
            return TennisResult("Win for " + game.server, "");
        return nextResult.getResult();
    }

private:
    TennisGame4 const & game;
    ResultProvider const & nextResult;
};

class GameReceiver : public ResultProvider {
private:
    TennisGame4 const & game;
    ResultProvider const & nextResult;

public:
    GameReceiver(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

public:
    TennisResult getResult() const override {
        if (game.receiverHasWon())
            return TennisResult("Win for " + game.receiver, "");
        return this->nextResult.getResult();
    }
};

class AdvantageServer : public ResultProvider {
public:
    AdvantageServer(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

    TennisResult getResult() const override {
        if (game.serverHasAdvantage())
            return TennisResult("Advantage " + game.server, "");
        return this->nextResult.getResult();
    }

private:
    TennisGame4 const & game;
    ResultProvider const & nextResult;
};

class AdvantageReceiver : public ResultProvider {
public:
    AdvantageReceiver(TennisGame4 game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

    TennisResult getResult() const override {
        if (game.receiverHasAdvantage())
            return TennisResult("Advantage " + game.receiver, "");
        return this->nextResult.getResult();
    }

private:
    const TennisGame4 game;
    ResultProvider const & nextResult;
};

class DefaultResult : public ResultProvider {
public:
    explicit DefaultResult(TennisGame4 const & game) : game(game) { }

    TennisResult getResult() const override {
        return TennisResult(scores[game.serverScore], scores[game.receiverScore]);
    }

private:
    static const std::string scores[];
    TennisGame4 const & game;
};

const std::string DefaultResult::scores[] = {"Love", "Fifteen", "Thirty", "Forty"};

TennisResult TennisGame4::getResult() const {
    TennisGame4 const & thisGame = *this;
    TennisResult result = Deuce(
        thisGame, GameServer(
        thisGame, GameReceiver(
        thisGame, AdvantageServer(
        thisGame, AdvantageReceiver(
        thisGame, DefaultResult(thisGame)))))
    ).getResult();
    return result;
}

void TennisGame4::wonPoint(std::string playerName) {
    if (server == playerName)
        serverScore += 1;
    else
        receiverScore += 1;
}

bool TennisGame4::receiverHasAdvantage() const {
    return receiverScore >= 4 && (receiverScore - serverScore) == 1;
}

bool TennisGame4::serverHasAdvantage() const {
    return serverScore >= 4 && (serverScore - receiverScore) == 1;
}

bool TennisGame4::receiverHasWon() const {
    return receiverScore >= 4 && (receiverScore - serverScore) >= 2;
}

bool TennisGame4::serverHasWon() const {
    return serverScore >= 4 && (serverScore - receiverScore) >= 2;
}

bool TennisGame4::isDeuce() const {
    return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore);
}

std::string tennis_score(int player1Score, int player2Score) {
    int highestScore = player1Score >  player2Score ? player1Score : player2Score;
    TennisGame4 game("player1", "player2");
    for (int i = 0; i < highestScore; i++) {
        if (i < player1Score)
            game.wonPoint("player1");
        if (i < player2Score)
            game.wonPoint("player2");
    }
    TennisResult result = game.getResult();
    return result.format();
}
<commit_msg>Remove commented original Java code.<commit_after>#include <string>

class TennisResult {
public:
    TennisResult(std::string serverScore, std::string receiverScore) {
        this->serverScore = serverScore;
        this->receiverScore = receiverScore;
    }

    std::string format() {
        if ("" == this->receiverScore)
            return this->serverScore;
        if (serverScore == this->receiverScore)
            return serverScore + "-All";
        return this->serverScore + "-" + this->receiverScore;
    }

private:
    std::string serverScore;
    std::string receiverScore;
};

class ResultProvider {
public:
    virtual TennisResult getResult() const = 0;
    virtual ~ResultProvider() = default;
};

class TennisGame4 : ResultProvider {
public:
    int serverScore = 0, receiverScore = 0;
    std::string server;
    std::string receiver;

    TennisGame4(std::string player1, std::string player2) {
        this->server = player1;
        this->receiver = player2;
    }

    TennisResult getResult() const override;
    void wonPoint(std::string playerName);
    bool receiverHasAdvantage() const;
    bool serverHasAdvantage() const;
    bool receiverHasWon() const;
    bool serverHasWon() const;
    bool isDeuce() const;
};

class Deuce : ResultProvider {
public:
    Deuce(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

    TennisResult getResult() const override {
        if (game.isDeuce())
            return TennisResult("Deuce", "");
        return this->nextResult.getResult();
    }

private:
    TennisGame4 const & game;
    ResultProvider const & nextResult;
};

class GameServer : public ResultProvider {
public:
    GameServer(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

    TennisResult getResult() const override {
        if (game.serverHasWon())
            return TennisResult("Win for " + game.server, "");
        return nextResult.getResult();
    }

private:
    TennisGame4 const & game;
    ResultProvider const & nextResult;
};

class GameReceiver : public ResultProvider {
private:
    TennisGame4 const & game;
    ResultProvider const & nextResult;

public:
    GameReceiver(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

public:
    TennisResult getResult() const override {
        if (game.receiverHasWon())
            return TennisResult("Win for " + game.receiver, "");
        return this->nextResult.getResult();
    }
};

class AdvantageServer : public ResultProvider {
public:
    AdvantageServer(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

    TennisResult getResult() const override {
        if (game.serverHasAdvantage())
            return TennisResult("Advantage " + game.server, "");
        return this->nextResult.getResult();
    }

private:
    TennisGame4 const & game;
    ResultProvider const & nextResult;
};

class AdvantageReceiver : public ResultProvider {
public:
    AdvantageReceiver(TennisGame4 game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { }

    TennisResult getResult() const override {
        if (game.receiverHasAdvantage())
            return TennisResult("Advantage " + game.receiver, "");
        return this->nextResult.getResult();
    }

private:
    const TennisGame4 game;
    ResultProvider const & nextResult;
};

class DefaultResult : public ResultProvider {
public:
    explicit DefaultResult(TennisGame4 const & game) : game(game) { }

    TennisResult getResult() const override {
        return TennisResult(scores[game.serverScore], scores[game.receiverScore]);
    }

private:
    static const std::string scores[];
    TennisGame4 const & game;
};

const std::string DefaultResult::scores[] = {"Love", "Fifteen", "Thirty", "Forty"};

TennisResult TennisGame4::getResult() const {
    TennisGame4 const & thisGame = *this;
    TennisResult result = Deuce(
        thisGame, GameServer(
        thisGame, GameReceiver(
        thisGame, AdvantageServer(
        thisGame, AdvantageReceiver(
        thisGame, DefaultResult(thisGame)))))
    ).getResult();
    return result;
}

void TennisGame4::wonPoint(std::string playerName) {
    if (server == playerName)
        serverScore += 1;
    else
        receiverScore += 1;
}

bool TennisGame4::receiverHasAdvantage() const {
    return receiverScore >= 4 && (receiverScore - serverScore) == 1;
}

bool TennisGame4::serverHasAdvantage() const {
    return serverScore >= 4 && (serverScore - receiverScore) == 1;
}

bool TennisGame4::receiverHasWon() const {
    return receiverScore >= 4 && (receiverScore - serverScore) >= 2;
}

bool TennisGame4::serverHasWon() const {
    return serverScore >= 4 && (serverScore - receiverScore) >= 2;
}

bool TennisGame4::isDeuce() const {
    return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore);
}

std::string tennis_score(int player1Score, int player2Score) {
    int highestScore = player1Score >  player2Score ? player1Score : player2Score;
    TennisGame4 game("player1", "player2");
    for (int i = 0; i < highestScore; i++) {
        if (i < player1Score)
            game.wonPoint("player1");
        if (i < player2Score)
            game.wonPoint("player2");
    }
    TennisResult result = game.getResult();
    return result.format();
}
<|endoftext|>