<commit_before>/*
 * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

#include <aws/external/gtest.h>

#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/utils/memory/AWSMemory.h>
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/CreateSecurityGroupRequest.h>
#include <aws/ec2/model/CreateSecurityGroupResponse.h>
#include <aws/ec2/model/CreateVpcRequest.h>
#include <aws/ec2/model/CreateVpcResponse.h>
#include <aws/ec2/model/DeleteSecurityGroupRequest.h>
#include <aws/ec2/model/DeleteVpcRequest.h>
#include <aws/ec2/model/DescribeSecurityGroupsRequest.h>
#include <aws/ec2/model/DescribeSecurityGroupsResponse.h>
#include <aws/ec2/model/DescribeSpotFleetRequestsRequest.h>
#include <aws/ec2/model/DescribeSpotFleetRequestsResponse.h>
#include <aws/ec2/model/DescribeVpcsRequest.h>
#include <aws/ec2/model/DescribeVpcsResponse.h>

#include <chrono>
#include <thread>

using namespace Aws::Auth;
using namespace Aws::Http;
using namespace Aws::Client;

namespace
{

static const char* ALLOCATION_TAG = "EC2Tests";
static const char* SECURITY_GROUP_NAME = "CppSDKIntegrationTestSecurityGroup";

class EC2OperationTest : public ::testing::Test
{

protected:

    enum class ObjectState {
        Ready,
        Nonexistent
    };

    std::shared_ptr<Aws::EC2::EC2Client> m_EC2Client;

    Aws::String m_vpcId;

    virtual void SetUp()
    {
        ClientConfiguration config;
        config.scheme = Scheme::HTTPS;
        config.region = Aws::Region::US_EAST_1;

        m_EC2Client = Aws::MakeShared<Aws::EC2::EC2Client>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), config);

        Aws::EC2::Model::CreateVpcRequest createVpcRequest;
        createVpcRequest.SetCidrBlock("0.0.0.0/0");
        createVpcRequest.SetInstanceTenancy(Aws::EC2::Model::Tenancy::default_);

        auto createOutcome = m_EC2Client->CreateVpc(createVpcRequest);
        ASSERT_TRUE(createOutcome.IsSuccess());

        m_vpcId = createOutcome.GetResult().GetVpc().GetVpcId();

        DeleteSecurityGroup(SECURITY_GROUP_NAME);
    }

    virtual void TearDown()
    {
        DeleteSecurityGroup(SECURITY_GROUP_NAME);
        DeleteVpc(m_vpcId);

        m_EC2Client = nullptr;
    }

    void DeleteSecurityGroup(const Aws::String& groupName)
    {
        Aws::EC2::Model::DeleteSecurityGroupRequest deleteRequest;
        deleteRequest.SetGroupName(groupName);

        m_EC2Client->DeleteSecurityGroup(deleteRequest);
        WaitOnSecurityGroupState(groupName, ObjectState::Nonexistent);
    }

    void WaitOnSecurityGroupState(const Aws::String& groupName, ObjectState objectState)
    {
        Aws::EC2::Model::DescribeSecurityGroupsRequest describeRequest;
        describeRequest.AddGroupNames(groupName);

        bool finished = false;
        while(!finished)
        {
            auto describeOutcome = m_EC2Client->DescribeSecurityGroups(describeRequest);
            if (describeOutcome.IsSuccess())
            {
                const Aws::Vector< Aws::EC2::Model::SecurityGroup >& groups = describeOutcome.GetResult().GetSecurityGroups();
                bool exists = std::find_if(groups.cbegin(), groups.cend(), [](const Aws::EC2::Model::SecurityGroup& group){ return group.GetGroupName() == SECURITY_GROUP_NAME; }) != groups.cend();
                finished = (objectState == ObjectState::Nonexistent && !exists) || (objectState == ObjectState::Ready && exists);
            }

            if (!finished)
            {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        }
    }

    void DeleteVpc(const Aws::String vpcId)
    {
        Aws::EC2::Model::DeleteVpcRequest deleteVpcRequest;
        deleteVpcRequest.SetVpcId(vpcId);

        auto deleteOutcome = m_EC2Client->DeleteVpc(deleteVpcRequest);
        ASSERT_TRUE(deleteOutcome.IsSuccess());

        WaitOnVpcState(vpcId, ObjectState::Nonexistent);
    }

    void WaitOnVpcState(const Aws::String& vpcId, ObjectState objectState)
    {
        Aws::EC2::Model::DescribeVpcsRequest describeRequest;
        describeRequest.AddVpcIds(vpcId);

        bool finished = false;
        while(!finished)
        {
            auto describeOutcome = m_EC2Client->DescribeVpcs(describeRequest);
            if (describeOutcome.IsSuccess())
            {
                const Aws::Vector< Aws::EC2::Model::Vpc >& vpcs = describeOutcome.GetResult().GetVpcs();
                bool exists = std::find_if(vpcs.cbegin(), vpcs.cend(), [vpcId](const Aws::EC2::Model::Vpc& vpc){ return vpc.GetVpcId() == vpcId; }) != vpcs.cend();
                finished = (objectState == ObjectState::Nonexistent && !exists) || (objectState == ObjectState::Ready && exists);
            }

            if (!finished)
            {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        }
    }

};
} // anonymous namespace

TEST_F(EC2OperationTest, DescribeSpotFleet)
{
    Aws::EC2::Model::DescribeSpotFleetRequestsRequest request;

    auto outcome = m_EC2Client->DescribeSpotFleetRequests(request);
    ASSERT_TRUE(outcome.IsSuccess());
}

TEST_F(EC2OperationTest, CreateSecurityGroup)
{
    Aws::EC2::Model::CreateSecurityGroupRequest createRequest;
    createRequest.SetGroupName(SECURITY_GROUP_NAME);
    createRequest.SetDescription("A dummy description");

    auto createOutcome = m_EC2Client->CreateSecurityGroup(createRequest);
    ASSERT_TRUE(createOutcome.IsSuccess());
}

<commit_msg>Test updates<commit_after>/*
 * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

#include <aws/external/gtest.h>

#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/utils/memory/AWSMemory.h>
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/CreateSecurityGroupRequest.h>
#include <aws/ec2/model/CreateSecurityGroupResponse.h>
#include <aws/ec2/model/CreateVpcRequest.h>
#include <aws/ec2/model/CreateVpcResponse.h>
#include <aws/ec2/model/DeleteSecurityGroupRequest.h>
#include <aws/ec2/model/DeleteVpcRequest.h>
#include <aws/ec2/model/DescribeSecurityGroupsRequest.h>
#include <aws/ec2/model/DescribeSecurityGroupsResponse.h>
#include <aws/ec2/model/DescribeSpotFleetRequestsRequest.h>
#include <aws/ec2/model/DescribeSpotFleetRequestsResponse.h>
#include <aws/ec2/model/DescribeVpcsRequest.h>
#include <aws/ec2/model/DescribeVpcsResponse.h>

#include <chrono>
#include <thread>

using namespace Aws::Auth;
using namespace Aws::Http;
using namespace Aws::Client;

namespace
{

static const char* ALLOCATION_TAG = "EC2Tests";
static const char* SECURITY_GROUP_NAME = "CppSDKIntegrationTestSecurityGroup";

class EC2OperationTest : public ::testing::Test
{

protected:

    enum class ObjectState {
        Ready,
        Nonexistent
    };

    std::shared_ptr<Aws::EC2::EC2Client> m_EC2Client;

    Aws::String m_vpcId;

    virtual void SetUp()
    {
        ClientConfiguration config;
        config.scheme = Scheme::HTTPS;
        config.region = Aws::Region::US_EAST_1;

        m_EC2Client = Aws::MakeShared<Aws::EC2::EC2Client>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), config);

        Aws::EC2::Model::CreateVpcRequest createVpcRequest;
        createVpcRequest.SetCidrBlock("0.0.0.0/0");
        createVpcRequest.SetInstanceTenancy(Aws::EC2::Model::Tenancy::default_);

        auto createOutcome = m_EC2Client->CreateVpc(createVpcRequest);
        ASSERT_TRUE(createOutcome.IsSuccess());

        m_vpcId = createOutcome.GetResult().GetVpc().GetVpcId();
        WaitOnVpcState(m_vpcId, ObjectState::Ready);

        DeleteSecurityGroup(SECURITY_GROUP_NAME);
    }

    virtual void TearDown()
    {
        DeleteSecurityGroup(SECURITY_GROUP_NAME);
        DeleteVpc(m_vpcId);

        m_EC2Client = nullptr;
    }

    void DeleteSecurityGroup(const Aws::String& groupName)
    {
        Aws::EC2::Model::DeleteSecurityGroupRequest deleteRequest;
        deleteRequest.SetGroupName(groupName);

        m_EC2Client->DeleteSecurityGroup(deleteRequest);
        WaitOnSecurityGroupState(groupName, ObjectState::Nonexistent);
    }

    void WaitOnSecurityGroupState(const Aws::String& groupName, ObjectState objectState)
    {
        Aws::EC2::Model::DescribeSecurityGroupsRequest describeRequest;
        describeRequest.AddGroupNames(groupName);

        bool finished = false;
        while(!finished)
        {
            auto describeOutcome = m_EC2Client->DescribeSecurityGroups(describeRequest);
            if (describeOutcome.IsSuccess())
            {
                const Aws::Vector< Aws::EC2::Model::SecurityGroup >& groups = describeOutcome.GetResult().GetSecurityGroups();
                bool exists = std::find_if(groups.cbegin(), groups.cend(), [](const Aws::EC2::Model::SecurityGroup& group){ return group.GetGroupName() == SECURITY_GROUP_NAME; }) != groups.cend();
                finished = (objectState == ObjectState::Nonexistent && !exists) || (objectState == ObjectState::Ready && exists);
            }
            else if (describeOutcome.GetError().GetErrorType() == Aws::EC2::EC2Errors::INVALID_GROUP__NOT_FOUND)
            {
                finished = objectState == ObjectState::Nonexistent;
            }

            if (!finished)
            {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        }
    }

    void DeleteVpc(const Aws::String vpcId)
    {
        Aws::EC2::Model::DeleteVpcRequest deleteVpcRequest;
        deleteVpcRequest.SetVpcId(vpcId);

        auto deleteOutcome = m_EC2Client->DeleteVpc(deleteVpcRequest);
        ASSERT_TRUE(deleteOutcome.IsSuccess());

        WaitOnVpcState(vpcId, ObjectState::Nonexistent);
    }

    void WaitOnVpcState(const Aws::String& vpcId, ObjectState objectState)
    {
        Aws::EC2::Model::DescribeVpcsRequest describeRequest;
        describeRequest.AddVpcIds(vpcId);

        bool finished = false;
        while(!finished)
        {
            auto describeOutcome = m_EC2Client->DescribeVpcs(describeRequest);
            if (describeOutcome.IsSuccess())
            {
                const Aws::Vector< Aws::EC2::Model::Vpc >& vpcs = describeOutcome.GetResult().GetVpcs();
                bool exists = std::find_if(vpcs.cbegin(), vpcs.cend(), [vpcId](const Aws::EC2::Model::Vpc& vpc){ return vpc.GetVpcId() == vpcId; }) != vpcs.cend();
                finished = (objectState == ObjectState::Nonexistent && !exists) || (objectState == ObjectState::Ready && exists);
            }
            else if (describeOutcome.GetError().GetErrorType() == Aws::EC2::EC2Errors::INVALID_VPC_I_D__NOT_FOUND)
            {
                finished = objectState == ObjectState::Nonexistent;
            }

            if (!finished)
            {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        }
    }

};
} // anonymous namespace

TEST_F(EC2OperationTest, DescribeSpotFleet)
{
    Aws::EC2::Model::DescribeSpotFleetRequestsRequest request;

    auto outcome = m_EC2Client->DescribeSpotFleetRequests(request);
    ASSERT_TRUE(outcome.IsSuccess());
}

TEST_F(EC2OperationTest, CreateSecurityGroup)
{
    Aws::EC2::Model::CreateSecurityGroupRequest createRequest;
    createRequest.SetGroupName(SECURITY_GROUP_NAME);
    createRequest.SetDescription("A dummy description");

    auto createOutcome = m_EC2Client->CreateSecurityGroup(createRequest);
    ASSERT_TRUE(createOutcome.IsSuccess());
}

<|endoftext|>


<commit_before>/*
 Copyright (c) 2012, The Cinder Project, All rights reserved.
 Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#define ASIO_STANDALONE 1
#include "asio/asio.hpp"

#include "cinder/app/App.h"
#include "cinder/app/Renderer.h"
#include "cinder/Camera.h"
#include "cinder/System.h"
#include "cinder/Utilities.h"
#include "cinder/Timeline.h"
#include "cinder/Thread.h"
#include "cinder/Log.h"

#if defined( CINDER_COCOA )
	#if defined( CINDER_MAC )
		#import "cinder/app/CinderView.h"
		#import <Cocoa/Cocoa.h>
	#endif
	#include "cinder/cocoa/CinderCocoa.h"
#elif defined( CINDER_WINRT )
	#include "cinder/app/AppImplWinRT.h"
	#include <thread>
	#include <filesystem>
#elif defined( CINDER_MSW )
	#include "cinder/app/AppImplMsw.h"
#endif

using namespace std;

namespace cinder { namespace app {

#if defined( CINDER_COCOA )
	void*	App::sAutoReleasePool = 0;
#endif

// Static instance of App, effectively a singleton
App*	App::sInstance;
static std::thread::id	sPrimaryThreadId = std::this_thread::get_id();

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// App::Settings
App::Settings::Settings()
{
	mShouldQuit = false;
	mPowerManagement = false;
	mFrameRateEnabled = true;
	mFrameRate = 60.0f;
	mEnableHighDensityDisplay = false;
	mEnableMultiTouch = false;
}

void App::Settings::disableFrameRate()
{
	mFrameRateEnabled = false;
}

void App::Settings::setFrameRate( float frameRate )
{
	mFrameRate = frameRate;
}

void App::Settings::enablePowerManagement( bool powerManagement )
{
	mPowerManagement = powerManagement;
}

void App::Settings::prepareWindow( const Window::Format &format )
{
	mWindowFormats.push_back( format );
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// App::App
App::App()
	: mFrameCount( 0 ), mAverageFps( 0 ), mFpsSampleInterval( 1 ), mTimer( true ), mTimeline( Timeline::create() )
{
	mFpsLastSampleFrame = 0;
	mFpsLastSampleTime = 0;

	mIo = shared_ptr<asio::io_service>( new asio::io_service() );
	mIoWork = shared_ptr<asio::io_service::work>( new asio::io_service::work( *mIo ) );

	// due to an issue with boost::filesystem's static initialization on Windows,
	// it's necessary to create a fs::path here in case of secondary threads doing the same thing simultaneously
#if (defined( CINDER_MSW ) || defined ( CINDER_WINRT ))
	fs::path dummyPath( "dummy" );
#endif
}

App::~App()
{
	mIo->stop();
}

void App::privateSetup__()
{
	mTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );

	setup();
}

void App::privateUpdate__()
{
	mFrameCount++;

<<<<<<< HEAD
#if !defined( CINDER_WINRT )
	// service asio::io_service
=======
>>>>>>> removed #if guards for boost::asio::io_service on WinRT, it should be possible to support now.
	mIo->poll();

	if( getNumWindows() > 0 ) {
		WindowRef mainWin = getWindowIndex( 0 );
		if( mainWin )
			mainWin->getRenderer()->makeCurrentContext();
	}

	mSignalUpdate();

	update();

	mTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );

	double now = mTimer.getSeconds();
	if( now > mFpsLastSampleTime + mFpsSampleInterval ) {
		//calculate average Fps over sample interval
		uint32_t framesPassed = mFrameCount - mFpsLastSampleFrame;
		mAverageFps = (float)(framesPassed / (now - mFpsLastSampleTime));

		mFpsLastSampleTime = now;
		mFpsLastSampleFrame = mFrameCount;
	}
}

void App::emitShutdown()
{
	mSignalShutdown();
	shutdown();
}

void App::emitWillResignActive()
{
	mSignalWillResignActive();
}

void App::emitDidBecomeActive()
{
	mSignalDidBecomeActive();
}

std::ostream& App::console()
{
	return Platform::get()->console();
}

bool App::isPrimaryThread()
{
	return std::this_thread::get_id() == sPrimaryThreadId;
}

void App::dispatchAsync( const std::function<void()> &fn )
{
	io_service().post( fn );
}

Surface	App::copyWindowSurface()
{
	return getWindow()->getRenderer()->copyWindowSurface( getWindow()->toPixels( getWindow()->getBounds() ) );
}

Surface	App::copyWindowSurface( const Area &area )
{
	Area clippedArea = area.getClipBy( getWindowBounds() );
	return getWindow()->getRenderer()->copyWindowSurface( clippedArea );
}

RendererRef App::findSharedRenderer( RendererRef searchRenderer ) const
{
	if( ! searchRenderer )
		return RendererRef();

	for( size_t winIdx = 0; winIdx < getNumWindows(); ++winIdx ) {
		RendererRef thisRenderer = getWindowIndex( winIdx )->getRenderer();
		if( thisRenderer && (typeid( *thisRenderer ) == typeid(*searchRenderer)) )
			return getWindowIndex( winIdx )->getRenderer();
	}

	return RendererRef(); // didn't find one
}

// These are called by application instantiation macros
void App::prepareLaunch()
{
#if defined( CINDER_COCOA )
    sAutoReleasePool = [[NSAutoreleasePool alloc] init];
#endif
}

void App::executeLaunch( App *app, RendererRef defaultRenderer, const char *title, int argc, char * const argv[] )
{
	sInstance = app;
	app->mDefaultRenderer = defaultRenderer;

	try {
		app->launch( title, argc, argv );
	}
	catch( std::exception &exc ) {
		CI_LOG_E( "Uncaught exception, type: " << ci::System::demangleTypeName( typeid( exc ).name() ) << ", what : " << exc.what() );
		throw;
	}
}

void App::cleanupLaunch()
{
#if defined( CINDER_COCOA )
    sAutoReleasePool = [[NSAutoreleasePool alloc] init];
#endif
}

} } // namespace cinder::app<commit_msg>remove no long needed platform specific includes<commit_after>/*
 Copyright (c) 2012, The Cinder Project, All rights reserved.
 Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#define ASIO_STANDALONE 1
#include "asio/asio.hpp"

#include "cinder/app/App.h"
#include "cinder/app/Renderer.h"
#include "cinder/Camera.h"
#include "cinder/System.h"
#include "cinder/Utilities.h"
#include "cinder/Timeline.h"
#include "cinder/Thread.h"
#include "cinder/Log.h"

using namespace std;

namespace cinder { namespace app {

#if defined( CINDER_COCOA )
	void*	App::sAutoReleasePool = 0;
#endif

// Static instance of App, effectively a singleton
App*	App::sInstance;
static std::thread::id	sPrimaryThreadId = std::this_thread::get_id();

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// App::Settings
App::Settings::Settings()
{
	mShouldQuit = false;
	mPowerManagement = false;
	mFrameRateEnabled = true;
	mFrameRate = 60.0f;
	mEnableHighDensityDisplay = false;
	mEnableMultiTouch = false;
}

void App::Settings::disableFrameRate()
{
	mFrameRateEnabled = false;
}

void App::Settings::setFrameRate( float frameRate )
{
	mFrameRate = frameRate;
}

void App::Settings::enablePowerManagement( bool powerManagement )
{
	mPowerManagement = powerManagement;
}

void App::Settings::prepareWindow( const Window::Format &format )
{
	mWindowFormats.push_back( format );
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// App::App
App::App()
	: mFrameCount( 0 ), mAverageFps( 0 ), mFpsSampleInterval( 1 ), mTimer( true ), mTimeline( Timeline::create() )
{
	mFpsLastSampleFrame = 0;
	mFpsLastSampleTime = 0;

	mIo = shared_ptr<asio::io_service>( new asio::io_service() );
	mIoWork = shared_ptr<asio::io_service::work>( new asio::io_service::work( *mIo ) );

	// due to an issue with boost::filesystem's static initialization on Windows,
	// it's necessary to create a fs::path here in case of secondary threads doing the same thing simultaneously
#if (defined( CINDER_MSW ) || defined ( CINDER_WINRT ))
	fs::path dummyPath( "dummy" );
#endif
}

App::~App()
{
	mIo->stop();
}

void App::privateSetup__()
{
	mTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );

	setup();
}

void App::privateUpdate__()
{
	mFrameCount++;

<<<<<<< HEAD
#if !defined( CINDER_WINRT )
	// service asio::io_service
=======
>>>>>>> removed #if guards for boost::asio::io_service on WinRT, it should be possible to support now.
	mIo->poll();

	if( getNumWindows() > 0 ) {
		WindowRef mainWin = getWindowIndex( 0 );
		if( mainWin )
			mainWin->getRenderer()->makeCurrentContext();
	}

	mSignalUpdate();

	update();

	mTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );

	double now = mTimer.getSeconds();
	if( now > mFpsLastSampleTime + mFpsSampleInterval ) {
		//calculate average Fps over sample interval
		uint32_t framesPassed = mFrameCount - mFpsLastSampleFrame;
		mAverageFps = (float)(framesPassed / (now - mFpsLastSampleTime));

		mFpsLastSampleTime = now;
		mFpsLastSampleFrame = mFrameCount;
	}
}

void App::emitShutdown()
{
	mSignalShutdown();
	shutdown();
}

void App::emitWillResignActive()
{
	mSignalWillResignActive();
}

void App::emitDidBecomeActive()
{
	mSignalDidBecomeActive();
}

std::ostream& App::console()
{
	return Platform::get()->console();
}

bool App::isPrimaryThread()
{
	return std::this_thread::get_id() == sPrimaryThreadId;
}

void App::dispatchAsync( const std::function<void()> &fn )
{
	io_service().post( fn );
}

Surface	App::copyWindowSurface()
{
	return getWindow()->getRenderer()->copyWindowSurface( getWindow()->toPixels( getWindow()->getBounds() ) );
}

Surface	App::copyWindowSurface( const Area &area )
{
	Area clippedArea = area.getClipBy( getWindowBounds() );
	return getWindow()->getRenderer()->copyWindowSurface( clippedArea );
}

RendererRef App::findSharedRenderer( RendererRef searchRenderer ) const
{
	if( ! searchRenderer )
		return RendererRef();

	for( size_t winIdx = 0; winIdx < getNumWindows(); ++winIdx ) {
		RendererRef thisRenderer = getWindowIndex( winIdx )->getRenderer();
		if( thisRenderer && (typeid( *thisRenderer ) == typeid(*searchRenderer)) )
			return getWindowIndex( winIdx )->getRenderer();
	}

	return RendererRef(); // didn't find one
}

// These are called by application instantiation macros
void App::prepareLaunch()
{
#if defined( CINDER_COCOA )
    sAutoReleasePool = [[NSAutoreleasePool alloc] init];
#endif
}

void App::executeLaunch( App *app, RendererRef defaultRenderer, const char *title, int argc, char * const argv[] )
{
	sInstance = app;
	app->mDefaultRenderer = defaultRenderer;

	try {
		app->launch( title, argc, argv );
	}
	catch( std::exception &exc ) {
		CI_LOG_E( "Uncaught exception, type: " << ci::System::demangleTypeName( typeid( exc ).name() ) << ", what : " << exc.what() );
		throw;
	}
}

void App::cleanupLaunch()
{
#if defined( CINDER_COCOA )
    sAutoReleasePool = [[NSAutoreleasePool alloc] init];
#endif
}

} } // namespace cinder::app<|endoftext|>


<commit_before>/*
 * Copyright 2017, Andrej Kislovskij
 *
 * This is PUBLIC DOMAIN software so use at your own risk as it comes
 * with no warranties. This code is yours to share, use and modify without
 * any restrictions or obligations.
 *
 * For more information see conwrap/LICENSE or refer refer to http://unlicense.org
 *
 * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)
 */

#pragma once

#include <cstddef>   // std::size_t
#include <FLAC++/encoder.h>
#include <string>

#include "slim/log/log.hpp"
#include "slim/util/AsyncWriter.hpp"
#include "slim/util/BufferedAsyncWriter.hpp"

namespace slim
{
	namespace flac
	{
		class Encoder : protected FLAC::Encoder::Stream
		{
			public:
				explicit Encoder(unsigned int c, unsigned int s, unsigned int bs, unsigned int bv, std::reference_wrapper<util::AsyncWriter> w, bool h)
				: channels{c}
				, sampleRate{s}
				, bitsPerSample{bs}
				, bitsPerValue{bv}
				, bufferedWriter{w}
				{
					// do not validate FLAC encoded stream if it produces the same result
					if (!set_verify(false))
					{
						throw Exception("Could not disable FLAC stream verification");
					}

					// setting maximum possible compression level
					if (set_compression_level(8))
					{
						throw Exception("Could not set compression level");
					}

					// setting amount of channels
					if (set_channels(channels))
					{
						throw Exception("Could not set amount of channels");
					}

					// setting sampling rate
					if (set_sample_rate(sampleRate))
					{
						throw Exception("Could not set sampling rate");
					}

					// FLAC encoding support max 24 bits per value
					auto b{bitsPerValue};
					if (b > 24)
					{
						LOG(WARNING) << LABELS{"flac"} << "PCM data will be scaled to 24 bits values, which is max bit depth supported by FLAC";

						b         = 24;
						downScale = true;
					}

					// setting sampling rate
					if (set_bits_per_sample(b))
					{
						throw Exception("Could not set bits per sample");
					}

					// choosing big enough number of expected samples for streaming purpose
					if (set_total_samples_estimate(0xFFFFFFFF))
					{
						throw Exception("Could not set estimated amount of samples");
					}

					// initializing FLAC encoder
					auto init_status{init()};
					if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
					{
						throw Exception(FLAC__StreamEncoderInitStatusString[init_status]);
					}
				}

			   ~Encoder()
				{
					if (!finish())
					{
						LOG(ERROR) << LABELS{"flac"} << "Error while closing encoder: " << get_state().as_cstring();
					}
				}

				Encoder(const Encoder&) = delete;             // non-copyable
				Encoder& operator=(const Encoder&) = delete;  // non-assignable
				Encoder(Encoder&&) = delete;                  // non-movable
				Encoder& operator=(Encoder&&) = delete;       // non-assign-movable

				auto encode(unsigned char* data, const std::size_t size)
				{
					std::size_t encoded{0};

					// do not feed encoder with more data if there is no room in transfer buffer
					if (bufferedWriter.isBufferAvailable())
					{
						std::size_t bytesPerSample{bitsPerSample >> 3};
						std::size_t samples{size / bytesPerSample};
						std::size_t frames{samples / channels};

						// if values contain more than 24 bits then downscaling to 24 bits, which is max supported by FLAC
						if (downScale)
						{
							for (std::size_t i = 0; i < size; i += bytesPerSample)
							{
								data[i] = 0;
							}
						}

						// TODO: generialize based on parameters (bitsPerFrame and bitsPerValue)
						// coverting data S32_LE to S24_LE by shifting data by 1 byte
						if (frames > 1 && !process_interleaved((const FLAC__int32*)(data + 1), frames - 1))
						{
							LOG(ERROR) << LABELS{"flac"} << get_state().as_cstring();
						}

						// handling the last frame separately; requred due to data shift
						if (frames > 0)
						{
							unsigned char lastFrame[8] =
							{
								data[size - 7],
								data[size - 6],
								data[size - 5],
								0,
								data[size - 3],
								data[size - 2],
								data[size - 1],
								0
							};

							if (!process_interleaved((const FLAC__int32*)lastFrame, 1))
							{
								LOG(ERROR) << LABELS{"flac"} << get_state().as_cstring();
							}
						}

						// notifing the caller about amount of data processed
						encoded = size;
					}
					else
					{
						LOG(WARNING) << LABELS{"flac"} << "Transfer buffer is full - skipping PCM chunk";
					}

					return encoded;
				}

				auto getMIME()
				{
					return std::string{"audio/flac"};
				}

			protected:
				virtual ::FLAC__StreamEncoderWriteStatus write_callback(const FLAC__byte* data, std::size_t size, unsigned samples, unsigned current_frame) override
				{
					bufferedWriter.writeAsync(data, size, [](auto error, auto written)
					{
						if (error)
						{
							LOG(ERROR) << LABELS{"flac"} << "Error while encoded data transfer: " << error.message();
						}
					});

					return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
				}

			private:
				unsigned int                  channels;
				unsigned int                  sampleRate;
				unsigned int                  bitsPerSample;
				unsigned int                  bitsPerValue;
				bool                          downScale{false};
				// TODO: parametrize
				util::BufferedAsyncWriter<10> bufferedWriter;
		};
	}
}
<commit_msg>Refactoring FLAC streamer<commit_after>/*
 * Copyright 2017, Andrej Kislovskij
 *
 * This is PUBLIC DOMAIN software so use at your own risk as it comes
 * with no warranties. This code is yours to share, use and modify without
 * any restrictions or obligations.
 *
 * For more information see conwrap/LICENSE or refer refer to http://unlicense.org
 *
 * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)
 */

#pragma once

#include <cstddef>   // std::size_t
#include <FLAC++/encoder.h>
#include <string>

#include "slim/log/log.hpp"
#include "slim/util/AsyncWriter.hpp"
#include "slim/util/BufferedAsyncWriter.hpp"

namespace slim
{
	namespace flac
	{
		class Encoder : protected FLAC::Encoder::Stream
		{
			public:
				explicit Encoder(unsigned int c, unsigned int s, unsigned int bs, unsigned int bv, std::reference_wrapper<util::AsyncWriter> w, bool h)
				: channels{c}
				, sampleRate{s}
				, bitsPerSample{bs}
				, bitsPerValue{bv}
				, bufferedWriter{w}
				{
					// do not validate FLAC encoded stream if it produces the same result
					if (!set_verify(false))
					{
						throw Exception("Could not disable FLAC stream verification");
					}

					// setting maximum possible compression level
					if (!set_compression_level(8))
					{
						throw Exception("Could not set compression level");
					}

					// setting amount of channels
					if (!set_channels(channels))
					{
						throw Exception("Could not set amount of channels");
					}

					// setting sampling rate
					if (!set_sample_rate(sampleRate))
					{
						throw Exception("Could not set sampling rate");
					}

					// FLAC encoding support max 24 bits per value
					auto b{bitsPerValue};
					if (b > 24)
					{
						LOG(WARNING) << LABELS{"flac"} << "PCM data will be scaled to 24 bits values, which is max bit depth supported by FLAC";

						b         = 24;
						downScale = true;
					}

					// setting sampling rate
					if (!set_bits_per_sample(b))
					{
						throw Exception("Could not set bits per sample");
					}

					// choosing big enough number of expected samples for streaming purpose
					if (!set_total_samples_estimate(0xFFFFFFFF))
					{
						throw Exception("Could not set estimated amount of samples");
					}

					// initializing FLAC encoder
					auto init_status{init()};
					if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
					{
						throw Exception(FLAC__StreamEncoderInitStatusString[init_status]);
					}
				}

			   ~Encoder()
				{
					if (!finish())
					{
						LOG(ERROR) << LABELS{"flac"} << "Error while closing encoder: " << get_state().as_cstring();
					}
				}

				Encoder(const Encoder&) = delete;             // non-copyable
				Encoder& operator=(const Encoder&) = delete;  // non-assignable
				Encoder(Encoder&&) = delete;                  // non-movable
				Encoder& operator=(Encoder&&) = delete;       // non-assign-movable

				auto encode(unsigned char* data, const std::size_t size)
				{
					std::size_t encoded{0};

					// do not feed encoder with more data if there is no room in transfer buffer
					if (bufferedWriter.isBufferAvailable())
					{
						std::size_t bytesPerSample{bitsPerSample >> 3};
						std::size_t samples{size / bytesPerSample};
						std::size_t frames{samples / channels};

						// if values contain more than 24 bits then downscaling to 24 bits, which is max supported by FLAC
						if (downScale)
						{
							for (std::size_t i = 0; i < size; i += bytesPerSample)
							{
								data[i] = 0;
							}
						}

						// TODO: generialize based on parameters (bitsPerFrame and bitsPerValue)
						// coverting data S32_LE to S24_LE by shifting data by 1 byte
						if (frames > 1 && !process_interleaved((const FLAC__int32*)(data + 1), frames - 1))
						{
							LOG(ERROR) << LABELS{"flac"} << get_state().as_cstring();
						}

						// handling the last frame separately; requred due to data shift
						if (frames > 0)
						{
							unsigned char lastFrame[8] =
							{
								data[size - 7],
								data[size - 6],
								data[size - 5],
								0,
								data[size - 3],
								data[size - 2],
								data[size - 1],
								0
							};

							if (!process_interleaved((const FLAC__int32*)lastFrame, 1))
							{
								LOG(ERROR) << LABELS{"flac"} << get_state().as_cstring();
							}
						}

						// notifing the caller about amount of data processed
						encoded = size;
					}
					else
					{
						LOG(WARNING) << LABELS{"flac"} << "Transfer buffer is full - skipping PCM chunk";
					}

					return encoded;
				}

				auto getMIME()
				{
					return std::string{"audio/flac"};
				}

			protected:
				virtual ::FLAC__StreamEncoderWriteStatus write_callback(const FLAC__byte* data, std::size_t size, unsigned samples, unsigned current_frame) override
				{
					bufferedWriter.writeAsync(data, size, [](auto error, auto written)
					{
						if (error)
						{
							LOG(ERROR) << LABELS{"flac"} << "Error while encoded data transfer: " << error.message();
						}
					});

					return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
				}

			private:
				unsigned int                  channels;
				unsigned int                  sampleRate;
				unsigned int                  bitsPerSample;
				unsigned int                  bitsPerValue;
				bool                          downScale{false};
				// TODO: parametrize
				util::BufferedAsyncWriter<10> bufferedWriter;
		};
	}
}
<|endoftext|>


<commit_before>#include "app.hpp"
#include "solver.hpp"
#include "../build/config.hpp"

#include <cstring>

extern "C" {
#include "unistd.h"	// for 'isatty'
};

namespace CaDiCaL {

Solver * App::solver;

void App::usage () {
  fputs (
"usage: cadical [ <option> ... ] [ <input> [ <proof> ] ]\n"
"\n"
"where '<option>' is one of the following short options\n"
"\n"
"  -h         print this command line option summary\n"
"  -n         do not print witness\n"
"  -q         quiet (same as '--quiet')\n"
"  -v         more verbose messages (same as '--verbose')\n"
"\n"
"  -c         check witness on original formula\n"
"             for testing and debuging\n"
"\n"
"  -s <sol>   read solution in competition output format\n"
"             to check consistency of learned clauses\n"
"             during testing and debugging\n"
"\n"
"or '<option>' can be one of the following long options\n"
"\n",
  stdout);
  Options::usage ();
fputs (
"\n"
"The long options have their default value printed in brackets\n"
"after their description.  They can also be used in the form\n"
"'--<name>' which is equivalent to '--<name>=1' and in the form\n"
"'--no-<name>' which is equivalent to '--<name>=0'.\n"
"\n"
"Note that decimal integers are casted to 'double' and 'bool'\n"
"in the natural way, e.g., '1' is interpreted as 'true'.\n"
"\n"
"Then '<input>' is a (compressed) DIMACS file and '<output>'\n"
"is a file to store the DRAT proof.  If no '<proof>' file is\n"
"specified, then no proof is generated.  If no '<input>' is given\n"
"then '<stdin>' is used. If '-' is used as '<input>' then the\n"
"solver reads from '<stdin>'.  If '-' is specified for '<proof>'\n"
"then the proof is generated and printed to '<stdout>'.\n",
  stdout);
}

void App::check_satisfying_assignment (int (Solver::*assignment)(int)) {
  bool satisfied = false;
  size_t start = 0;
  for (size_t i = 0; i < solver->original.size (); i++) {
    int lit = solver->original[i];
    if (!lit) {
      if (!satisfied) {
        fflush (stdout);
        fputs ("*** cadical error: unsatisfied clause:\n", stderr);
        for (size_t j = start; j < i; j++)
          fprintf (stderr, "%d ", solver->original[j]);
        fputs ("0\n", stderr);
        fflush (stderr);
        abort ();
      }
      satisfied = false;
      start = i + 1;
    } else if (!satisfied && (solver->*assignment) (lit) > 0) satisfied = true;
  }
  MSG ("satisfying assignment checked");
}

void App::print_witness () {
  int c = 0;
  for (int i = 1; i <= solver->max_var; i++) {
    if (!c) File::print ('v'), c = 1;
    char str[20];
    sprintf (str, " %d", solver->val (i) < 0 ? -i : i);
    int l = strlen (str);
    if (c + l > 78) File::print ("\nv"), c = 1;
    File::print (str);
    c += l;
  }
  if (c) File::print ('\n');
  File::print ("v 0\n");
  fflush (stdout);
}

void App::banner () {
  SECTION ("banner");
  MSG ("CaDiCaL Radically Simplified CDCL SAT Solver");
  MSG ("Version " VERSION " " GITID);
  MSG ("Copyright (c) 2016 Armin Biere, JKU");
  MSG (COMPILE);
}

bool App::set (const char * arg) { return solver->opts.set (arg); }

int App::main (int argc, char ** argv) {
  File * dimacs = 0, * proof = 0, * solution = 0;
  bool trace_proof = false, binary_proof = true;
  const char * proof_name = 0;
  int i, res;
  solver = new Solver ();
  for (i = 1; i < argc; i++) {
    if (!strcmp (argv[i], "-h")) usage (), exit (0);
    else if (!strcmp (argv[i], "--version"))
      fputs (VERSION "\n", stdout), exit (0);
    else if (!strcmp (argv[i], "-")) {
      if (trace_proof) DIE ("too many arguments");
      else if (!dimacs) dimacs = File::read (stdin, "<stdin>");
      else trace_proof = true, proof_name = 0;
    } else if (!strcmp (argv[i], "-s")) {
      if (++i == argc) DIE ("argument to '-s' missing");
      if (solution) DIE ("multiple solution files");
      if (!(solution = File::read (argv[i])))
        DIE ("can not read solution file '%s'", argv[i]);
    } else if (!strcmp (argv[i], "-n")) set ("--no-witness");
    else if (!strcmp (argv[i], "-q")) set ("--quiet");
    else if (!strcmp (argv[i], "-v")) set ("--verbose");
    else if (!strcmp (argv[i], "-c")) set ("--check");
    else if (set (argv[i])) { /* nothing do be done */ }
    else if (argv[i][0] == '-') DIE ("invalid option '%s'", argv[i]);
    else if (trace_proof) DIE ("too many arguments");
    else if (dimacs) trace_proof = true, proof_name = argv[i];
    else if (!(dimacs = File::read (argv[i])))
      DIE ("can not open and read DIMACS file '%s'", argv[i]);
  }
  if (solution && !solver->opts.check) set ("--check");
  if (!dimacs) dimacs = File::read (stdin, "<stdin>");
  banner ();
  Signal::init (solver);
  SECTION ("parsing input");
  MSG ("reading DIMACS file from '%s'", dimacs->name ());
  Parser dimacs_parser (solver, dimacs);
  dimacs_parser.parse_dimacs ();
  delete dimacs;
  if (solution) {
    SECTION ("parsing solution");
    Parser solution_parser (solver, solution);
    MSG ("reading solution file from '%s'", solution->name ());
    solution_parser.parse_solution ();
    delete solution;
    check_satisfying_assignment (&Solver::sol);
  }
  solver->opts.print ();
  SECTION ("proof tracing");
  if (trace_proof) {
    if (!proof_name) {
      proof = File::write (stdout, "<stdout>");
      if (isatty (1) && solver->opts.binary) {
	MSG ("forcing non-binary proof: '<stdout>' connected to terminal");
	binary_proof = false;
      }
    } else if (!(proof = File::write (proof_name)))
      DIE ("can not open and write DRAT proof to '%s'", proof_name);
    if (binary_proof && !solver->opts.binary) binary_proof = false;
    MSG ("writing %s DRAT proof trace to '%s'",
      (binary_proof ? "binary" : "non-binary"), proof->name ());
    solver->proof = new Proof (solver, proof, binary_proof);
  } else MSG ("will not generate nor write DRAT proof");
  res = solver->solve ();
  if (proof) { delete proof; solver->proof = 0; }
  SECTION ("result");
  if (res == 10) {
    check_satisfying_assignment (&Solver::val);
    printf ("s SATISFIABLE\n");
    if (solver->opts.witness) print_witness ();
    fflush (stdout);
  } else {
    assert (res = 20);
    printf ("s UNSATISFIABLE\n");
    fflush (stdout);
  }
  Signal::reset ();
  solver->stats.print ();
  MSG ("exit %d", res);
  if (!solver->opts.leak) delete solver;
  solver = 0;
  return res;
}

};
<commit_msg>fixed usage<commit_after>#include "app.hpp"
#include "solver.hpp"
#include "../build/config.hpp"

#include <cstring>

extern "C" {
#include "unistd.h"	// for 'isatty'
};

namespace CaDiCaL {

Solver * App::solver;

void App::usage () {
  fputs (
"usage: cadical [ <option> ... ] [ <input> [ <proof> ] ]\n"
"\n"
"where '<option>' is one of the following short options\n"
"\n"
"  -h         print this command line option summary\n"
"  -n         do not print witness\n"
"  -q         quiet (same as '--quiet')\n"
"  -v         more verbose messages (same as '--verbose')\n"
"\n"
"  -c         check witness on original formula\n"
"             for testing and debuging\n"
"\n"
"  -s <sol>   read solution in competition output format\n"
"             to check consistency of learned clauses\n"
"             during testing and debugging\n"
"\n"
"or '<option>' can be one of the following long options\n"
"\n",
  stdout);
  Options::usage ();
fputs (
"\n"
"The long options have their default value printed in brackets\n"
"after their description.  They can also be used in the form\n"
"'--<name>' which is equivalent to '--<name>=1' and in the form\n"
"'--no-<name>' which is equivalent to '--<name>=0'.\n"
"\n"
"Note that decimal integers are casted to 'double' and 'bool'\n"
"in the natural way, e.g., '1' is interpreted as 'true'.\n"
"\n"
"Then '<input>' has to be a DIMACS file and in '<output>' a DRAT\n"
"proof is saved.  If no '<proof>' file is specified, then no proof\n"
"is generated.  If no '<input>' is given then '<stdin>' is used.\n"
"If '-' is used as '<input>' then the solver reads from '<stdin>'.\n"
"If '-' is specified for '<proof> then a proof is generated and\n"
"printed to '<stdout>'.  The proof is by default stored in binary\n"
"format unless '--binary=0' or the proof is written to '<stdout>'\n"
"and '<stdout>' is connected to a terminal.\n"
"\n"
"The input is assumed to be compressed if it is given explicitly\n"
"and has a '.gz', '.bz2' or '.7z' suffix.  The same applies to the\n"
"output file.  For decompression helper commands 'gunzip', 'bzcat'\n"
"and '7z' are needed, and for proof compression
"and '7z' have to be in the path and are used through opening a pipe.\n",
  stdout);
}

void App::check_satisfying_assignment (int (Solver::*assignment)(int)) {
  bool satisfied = false;
  size_t start = 0;
  for (size_t i = 0; i < solver->original.size (); i++) {
    int lit = solver->original[i];
    if (!lit) {
      if (!satisfied) {
        fflush (stdout);
        fputs ("*** cadical error: unsatisfied clause:\n", stderr);
        for (size_t j = start; j < i; j++)
          fprintf (stderr, "%d ", solver->original[j]);
        fputs ("0\n", stderr);
        fflush (stderr);
        abort ();
      }
      satisfied = false;
      start = i + 1;
    } else if (!satisfied && (solver->*assignment) (lit) > 0) satisfied = true;
  }
  MSG ("satisfying assignment checked");
}

void App::print_witness () {
  int c = 0;
  for (int i = 1; i <= solver->max_var; i++) {
    if (!c) File::print ('v'), c = 1;
    char str[20];
    sprintf (str, " %d", solver->val (i) < 0 ? -i : i);
    int l = strlen (str);
    if (c + l > 78) File::print ("\nv"), c = 1;
    File::print (str);
    c += l;
  }
  if (c) File::print ('\n');
  File::print ("v 0\n");
  fflush (stdout);
}

void App::banner () {
  SECTION ("banner");
  MSG ("CaDiCaL Radically Simplified CDCL SAT Solver");
  MSG ("Version " VERSION " " GITID);
  MSG ("Copyright (c) 2016 Armin Biere, JKU");
  MSG (COMPILE);
}

bool App::set (const char * arg) { return solver->opts.set (arg); }

int App::main (int argc, char ** argv) {
  File * dimacs = 0, * proof = 0, * solution = 0;
  bool trace_proof = false, binary_proof = true;
  const char * proof_name = 0;
  int i, res;
  solver = new Solver ();
  for (i = 1; i < argc; i++) {
    if (!strcmp (argv[i], "-h")) usage (), exit (0);
    else if (!strcmp (argv[i], "--version"))
      fputs (VERSION "\n", stdout), exit (0);
    else if (!strcmp (argv[i], "-")) {
      if (trace_proof) DIE ("too many arguments");
      else if (!dimacs) dimacs = File::read (stdin, "<stdin>");
      else trace_proof = true, proof_name = 0;
    } else if (!strcmp (argv[i], "-s")) {
      if (++i == argc) DIE ("argument to '-s' missing");
      if (solution) DIE ("multiple solution files");
      if (!(solution = File::read (argv[i])))
        DIE ("can not read solution file '%s'", argv[i]);
    } else if (!strcmp (argv[i], "-n")) set ("--no-witness");
    else if (!strcmp (argv[i], "-q")) set ("--quiet");
    else if (!strcmp (argv[i], "-v")) set ("--verbose");
    else if (!strcmp (argv[i], "-c")) set ("--check");
    else if (set (argv[i])) { /* nothing do be done */ }
    else if (argv[i][0] == '-') DIE ("invalid option '%s'", argv[i]);
    else if (trace_proof) DIE ("too many arguments");
    else if (dimacs) trace_proof = true, proof_name = argv[i];
    else if (!(dimacs = File::read (argv[i])))
      DIE ("can not open and read DIMACS file '%s'", argv[i]);
  }
  if (solution && !solver->opts.check) set ("--check");
  if (!dimacs) dimacs = File::read (stdin, "<stdin>");
  banner ();
  Signal::init (solver);
  SECTION ("parsing input");
  MSG ("reading DIMACS file from '%s'", dimacs->name ());
  Parser dimacs_parser (solver, dimacs);
  dimacs_parser.parse_dimacs ();
  delete dimacs;
  if (solution) {
    SECTION ("parsing solution");
    Parser solution_parser (solver, solution);
    MSG ("reading solution file from '%s'", solution->name ());
    solution_parser.parse_solution ();
    delete solution;
    check_satisfying_assignment (&Solver::sol);
  }
  solver->opts.print ();
  SECTION ("proof tracing");
  if (trace_proof) {
    if (!proof_name) {
      proof = File::write (stdout, "<stdout>");
      if (isatty (1) && solver->opts.binary) {
	MSG ("forcing non-binary proof: '<stdout>' connected to terminal");
	binary_proof = false;
      }
    } else if (!(proof = File::write (proof_name)))
      DIE ("can not open and write DRAT proof to '%s'", proof_name);
    if (binary_proof && !solver->opts.binary) binary_proof = false;
    MSG ("writing %s DRAT proof trace to '%s'",
      (binary_proof ? "binary" : "non-binary"), proof->name ());
    solver->proof = new Proof (solver, proof, binary_proof);
  } else MSG ("will not generate nor write DRAT proof");
  res = solver->solve ();
  if (proof) { delete proof; solver->proof = 0; }
  SECTION ("result");
  if (res == 10) {
    check_satisfying_assignment (&Solver::val);
    printf ("s SATISFIABLE\n");
    if (solver->opts.witness) print_witness ();
    fflush (stdout);
  } else {
    assert (res = 20);
    printf ("s UNSATISFIABLE\n");
    fflush (stdout);
  }
  Signal::reset ();
  solver->stats.print ();
  MSG ("exit %d", res);
  if (!solver->opts.leak) delete solver;
  solver = 0;
  return res;
}

};
<|endoftext|>


<commit_before>#include <vector>
#include <string>
#include "util/winpath.hpp"

namespace cygscript {

class App
{
	int _argc;
	char* const* _argv;
	enum class Command { NONE, EXEC, REGISTER, UNREGISTER, LIST };
	Command _cmd;
	enum class RegisterType { USER, EVERYONE };
	RegisterType _regType;
	std::string _extension;
	std::string _iconPath;
	bool _force;
public:
	/**
	 * Constructor.
	 *
	 * @param const int argc Argc from main function
	 * @param char* const argv[] Argv from main function
	 */
	App(const int argc, char* const argv[]);

	/**
	 * Run application.
	 *
	 * @return int Exit code
	 */
	int run();

	/**
	 * Get Windows path to this application.
	 *
	 * @return WinPathW Windows path
	 */
	static WinPathW getPath();
private:
	/**
	 * Print application usage.
	 */
	void _printUsage(char* progname);

	/**
	 * Print application version.
	 */
	void _printVersion();

	/**
	 * Get the command line argumenst in wide strings.
	 *
	 * @return std::vector<std::wstring> List of arguments
	 */
	std::vector<std::wstring> _wideArgs();

	/**
	 * Check whether process is currently running as elevated.
	 *
	 * Prompts for elevation if not currently elevated.
	 */
	void _checkElevated();
};

}
<commit_msg>Add include guard<commit_after>#ifndef __APP_HPP__
#define __APP_HPP__

#include <vector>
#include <string>
#include "util/winpath.hpp"

namespace cygscript {

class App
{
	int _argc;
	char* const* _argv;
	enum class Command { NONE, EXEC, REGISTER, UNREGISTER, LIST };
	Command _cmd;
	enum class RegisterType { USER, EVERYONE };
	RegisterType _regType;
	std::string _extension;
	std::string _iconPath;
	bool _force;
public:
	/**
	 * Constructor.
	 *
	 * @param const int argc Argc from main function
	 * @param char* const argv[] Argv from main function
	 */
	App(const int argc, char* const argv[]);

	/**
	 * Run application.
	 *
	 * @return int Exit code
	 */
	int run();

	/**
	 * Get Windows path to this application.
	 *
	 * @return WinPathW Windows path
	 */
	static WinPathW getPath();
private:
	/**
	 * Print application usage.
	 */
	void _printUsage(char* progname);

	/**
	 * Print application version.
	 */
	void _printVersion();

	/**
	 * Get the command line argumenst in wide strings.
	 *
	 * @return std::vector<std::wstring> List of arguments
	 */
	std::vector<std::wstring> _wideArgs();

	/**
	 * Check whether process is currently running as elevated.
	 *
	 * Prompts for elevation if not currently elevated.
	 */
	void _checkElevated();
};

}

#endif
<|endoftext|>


<commit_before>#include <tiramisu/debug.h>
#include <tiramisu/core.h>

#include <string.h>
#include <Halide.h>

#include "baryon_wrapper.h"
#include "benchmarks.h"

using namespace tiramisu;

/*
 * The goal is to generate code that implements the reference.
 * baryon_ref.cpp
 */
void generate_function(std::string name, int size)
{
    tiramisu::global::set_default_tiramisu_options();

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------

    tiramisu::function function0(name);
    global::set_implicit_function(&function0);

    tiramisu::constant N_CONST("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, &function0);
    tiramisu::constant BT_CONST("BT", tiramisu::expr((int32_t) BT), p_int32, true, NULL, 0, &function0);
    tiramisu::constant a1("a1", tiramisu::expr((int32_t) 0), p_int32, true, NULL, 0, &function0);
    tiramisu::constant a2("a2", tiramisu::expr((int32_t) 0), p_int32, true, NULL, 0, &function0);
    tiramisu::constant a3("a3", tiramisu::expr((int32_t) 0), p_int32, true, NULL, 0, &function0);
    tiramisu::constant xp0("xp0", tiramisu::expr((int32_t) 0), p_int32, true, NULL, 0, &function0);
    tiramisu::constant KMAX("KMAX", tiramisu::expr((int32_t) BK), p_int32, true, NULL, 0, &function0);
    tiramisu::constant b0("b0", tiramisu::expr((int32_t) 0), p_int32, true, NULL, 0, &function0);
    tiramisu::constant b1("b1", tiramisu::expr((int32_t) 0), p_int32, true, NULL, 0, &function0);
    tiramisu::constant b2("b2", tiramisu::expr((int32_t) 0), p_int32, true, NULL, 0, &function0);

    tiramisu::var i3("i3"), i2("i2"), i1("i1"), k("k", 1, KMAX), t("t");
    tiramisu::input fc1("fc1", {k}, p_int32);
    tiramisu::input fc2("fc2", {k}, p_int32);
    tiramisu::input fc3("fc3", {k}, p_int32);
    tiramisu::computation S("{S[xp0, a1, t, i1, i2, i3, d1]}", tiramisu::expr(), false, p_float32, &function0);
    tiramisu::computation wp("{wp[k, b0, b1, b2]}", tiramisu::expr(), false, p_float32, &function0);

    tiramisu::computation d1("[BT, N, KMAX]->{d1[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and 1<=k<KMAX}", fc1(k), true, p_int32, &function0);
    tiramisu::computation d2("[BT, N, KMAX]->{d2[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and 1<=k<KMAX}", fc2(k), true, p_int32, &function0);
    tiramisu::computation d3("[BT, N, KMAX]->{d3[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and 1<=k<KMAX}", fc3(k), true, p_int32, &function0);

    tiramisu::computation Res0("[BT, N, KMAX]->{Res0[t, i1, i2, i3, k]: 0<=t<BT and 0<=i1<N and 0<=i2<N and 0<=i3<N and 1<=k<KMAX}", tiramisu::expr(), true, p_float32, &function0);
    Res0.set_expression(
			  S(xp0, a1, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d3(0,0,0,0,0))
			+ S(xp0, a1, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d1(0,0,0,0,0))
			+ S(xp0, a1, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d2(0,0,0,0,0))
		        - S(xp0, a1, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d3(0,0,0,0,0))
		        - S(xp0, a1, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d1(0,0,0,0,0))
		        - S(xp0, a1, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d2(0,0,0,0,0))
		);

    tiramisu::computation Res1("[BT, N]->{Res1[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and k=0}", tiramisu::expr((float) 0), true, p_float32, &function0);
    tiramisu::computation Res1_update_0("[BT, N, KMAX]->{Res1_update_0[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and 1<=k<KMAX}", tiramisu::expr(), true, p_float32, &function0);
    Res1_update_0.set_expression(Res1(t, i1, i2, i3, k-1) + wp(k, b2, b1, b0) * Res0(t, i1, i2, i3, k));

    tiramisu::computation Res2("[BT, N]->{Res2[t]: 0<=t<BT}", tiramisu::expr((float) 0), true, p_float32, &function0);
    tiramisu::computation Res2_update_0("[BT, N]->{Res2_update_0[t, i1, i2, i3]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N}", tiramisu::expr(), true, p_float32, &function0);
    Res2_update_0.set_expression(Res2_update_0(t, i1, i2, i3) + /* exp(i(i3*px+i2*py+i1*pz)) */ Res1(t, i1, i2, i3, 0));

    function0.add_context_constraints("[N, M, K,BT]->{:N=16}, BT=16");

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    tiramisu::buffer buf_fc1("buf_fc1", {KMAX}, tiramisu::p_int32, a_input, &function0);
    tiramisu::buffer buf_fc2("buf_fc2", {KMAX}, tiramisu::p_int32, a_input, &function0);
    tiramisu::buffer buf_fc3("buf_fc3", {KMAX}, tiramisu::p_int32, a_input, &function0);

    tiramisu::buffer buf_res0("buf_res0", {BZ}, tiramisu::p_float32, a_temporary, &function0);
    buf_res0.set_auto_allocate(false);
    tiramisu::computation *alloc_res0 = buf_res0.allocate_at(Res2, t);
    tiramisu::buffer buf_res1("buf_res1", {N_CONST}, tiramisu::p_float32, a_temporary, &function0);
    buf_res1.set_auto_allocate(false);
    tiramisu::computation *alloc_res1 = buf_res1.allocate_at(Res2, t);
    tiramisu::buffer buf_res2("buf_res2", {BT_CONST}, tiramisu::p_float32, a_output, &function0);
    tiramisu::buffer buf_d1("buf_d1", {KMAX}, tiramisu::p_int32, a_temporary, &function0);
    buf_d1.set_auto_allocate(false);
    tiramisu::computation *alloc_d1 = buf_d1.allocate_at(Res2, t);
    tiramisu::buffer buf_d2("buf_d2", {KMAX}, tiramisu::p_int32, a_temporary, &function0);
    buf_d2.set_auto_allocate(false);
    tiramisu::computation *alloc_d2 = buf_d2.allocate_at(Res2, t);
    tiramisu::buffer buf_d3("buf_d3", {KMAX}, tiramisu::p_int32, a_temporary, &function0);
    buf_d3.set_auto_allocate(false);
    tiramisu::computation *alloc_d3 = buf_d3.allocate_at(Res2, t);

    // S(d1, i3, i2, i1, t, a1, x’0)
    tiramisu::buffer buf_S("buf_S", {tiramisu::expr((int32_t) BARYON_P), tiramisu::expr((int32_t) BARYON_P), tiramisu::expr((int32_t) BARYON_P), N_CONST, N_CONST, N_CONST, tiramisu::expr((int32_t) BARYON_P1)}, tiramisu::p_float32, a_input, &function0);

    tiramisu::buffer buf_wp("buf_wp", {tiramisu::expr((int32_t) BARYON_N), tiramisu::expr((int32_t) BARYON_P), tiramisu::expr((int32_t) BARYON_P), tiramisu::expr((int32_t) BARYON_P)}, tiramisu::p_float32, a_input, &function0);

    fc1.store_in(&buf_fc1);
    fc2.store_in(&buf_fc2);
    fc3.store_in(&buf_fc3);
    d1.store_in(&buf_d1, {0});
    d2.store_in(&buf_d2, {0});
    d3.store_in(&buf_d3, {0});
    Res0.store_in(&buf_res0, {i3});
    Res1.store_in(&buf_res1, {i3});
    Res1_update_0.store_in(&buf_res1, {i3});
    Res2.store_in(&buf_res2, {t});
    Res2_update_0.store_in(&buf_res2, {t});
    S.store_in(&buf_S);
    wp.store_in(&buf_wp);

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------

    Res2.then(*alloc_res1, t)
	.then(*alloc_res0, t)
	.then(*alloc_d1, t)
	.then(*alloc_d2, t)
	.then(*alloc_d3, t)
	.then(Res1, i3)
	.then(d1, i3)
	.then(d2, k)
	.then(d3, k)
	.then(Res0, k)
	.then(Res1_update_0, k)
	.then(Res2_update_0, i2);

    Res0.tag_vector_level(i3, BARYON_N);
    Res2.tag_parallel_level(t);

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------

    function0.set_arguments({&buf_res2, &buf_S, &buf_wp, &buf_fc1, &buf_fc2, &buf_fc3});
    function0.gen_time_space_domain();
    function0.gen_isl_ast();
    function0.gen_halide_stmt();
    function0.gen_halide_obj("generated_" + std::string(TEST_NAME_STR) + ".o");
}

int main(int argc, char **argv)
{
    generate_function("tiramisu_generated_code", BARYON_N);

    return 0;
}
<commit_msg>Use new API for Baryon (step 2)<commit_after>#include <tiramisu/debug.h>
#include <tiramisu/core.h>

#include <string.h>
#include <Halide.h>

#include "baryon_wrapper.h"
#include "benchmarks.h"

using namespace tiramisu;

/*
 * The goal is to generate code that implements the reference.
 * baryon_ref.cpp
 */
void generate_function(std::string name, int size)
{
    tiramisu::global::set_default_tiramisu_options();

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------

    tiramisu::function function0(name);
    global::set_implicit_function(&function0);

    tiramisu::constant N_CONST("N", tiramisu::expr((int32_t) size));
    tiramisu::constant BT_CONST("BT", tiramisu::expr((int32_t) BT));
    tiramisu::constant a1("a1", tiramisu::expr((int32_t) 0));
    tiramisu::constant a2("a2", tiramisu::expr((int32_t) 0));
    tiramisu::constant a3("a3", tiramisu::expr((int32_t) 0));
    tiramisu::constant xp0("xp0", tiramisu::expr((int32_t) 0));
    tiramisu::constant KMAX("KMAX", tiramisu::expr((int32_t) BK));
    tiramisu::constant b0("b0", tiramisu::expr((int32_t) 0));
    tiramisu::constant b1("b1", tiramisu::expr((int32_t) 0));
    tiramisu::constant b2("b2", tiramisu::expr((int32_t) 0));

    tiramisu::var i3("i3"), i2("i2"), i1("i1"), k("k", 1, KMAX), t("t");
    tiramisu::input fc1("fc1", {k}, p_int32);
    tiramisu::input fc2("fc2", {k}, p_int32);
    tiramisu::input fc3("fc3", {k}, p_int32);
    tiramisu::computation S("{S[xp0, a1, t, i1, i2, i3, d1]}", tiramisu::expr(), false, p_float32, &function0);
    tiramisu::computation wp("{wp[k, b0, b1, b2]}", tiramisu::expr(), false, p_float32, &function0);

    tiramisu::computation d1("[BT, N, KMAX]->{d1[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and 1<=k<KMAX}", fc1(k), true, p_int32, &function0);
    tiramisu::computation d2("[BT, N, KMAX]->{d2[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and 1<=k<KMAX}", fc2(k), true, p_int32, &function0);
    tiramisu::computation d3("[BT, N, KMAX]->{d3[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and 1<=k<KMAX}", fc3(k), true, p_int32, &function0);

    tiramisu::computation Res0("[BT, N, KMAX]->{Res0[t, i1, i2, i3, k]: 0<=t<BT and 0<=i1<N and 0<=i2<N and 0<=i3<N and 1<=k<KMAX}", tiramisu::expr(), true, p_float32, &function0);
    Res0.set_expression(
			  S(xp0, a1, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d3(0,0,0,0,0))
			+ S(xp0, a1, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d1(0,0,0,0,0))
			+ S(xp0, a1, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d2(0,0,0,0,0))
		        - S(xp0, a1, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d3(0,0,0,0,0))
		        - S(xp0, a1, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d2(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d1(0,0,0,0,0))
		        - S(xp0, a1, t, i1, i2, i3, d1(0,0,0,0,0)) * S(xp0, a2, t, i1, i2, i3, d3(0,0,0,0,0)) * S(xp0, a3, t, i1, i2, i3, d2(0,0,0,0,0))
		);

    tiramisu::computation Res1("[BT, N]->{Res1[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and k=0}", tiramisu::expr((float) 0), true, p_float32, &function0);
    tiramisu::computation Res1_update_0("[BT, N, KMAX]->{Res1_update_0[t, i1, i2, i3, k]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N and 1<=k<KMAX}", tiramisu::expr(), true, p_float32, &function0);
    Res1_update_0.set_expression(Res1(t, i1, i2, i3, k-1) + wp(k, b2, b1, b0) * Res0(t, i1, i2, i3, k));

    tiramisu::computation Res2("[BT, N]->{Res2[t]: 0<=t<BT}", tiramisu::expr((float) 0), true, p_float32, &function0);
    tiramisu::computation Res2_update_0("[BT, N]->{Res2_update_0[t, i1, i2, i3]: 0<=t<BT and 0<=i3<N and 0<=i2<N and 0<=i1<N}", tiramisu::expr(), true, p_float32, &function0);
    Res2_update_0.set_expression(Res2_update_0(t, i1, i2, i3) + /* exp(i(i3*px+i2*py+i1*pz)) */ Res1(t, i1, i2, i3, 0));

    function0.add_context_constraints("[N, M, K,BT]->{:N=16}, BT=16");

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    tiramisu::buffer buf_fc1("buf_fc1", {KMAX}, tiramisu::p_int32, a_input, &function0);
    tiramisu::buffer buf_fc2("buf_fc2", {KMAX}, tiramisu::p_int32, a_input, &function0);
    tiramisu::buffer buf_fc3("buf_fc3", {KMAX}, tiramisu::p_int32, a_input, &function0);

    tiramisu::buffer buf_res0("buf_res0", {BZ}, tiramisu::p_float32, a_temporary, &function0);
    buf_res0.set_auto_allocate(false);
    tiramisu::computation *alloc_res0 = buf_res0.allocate_at(Res2, t);
    tiramisu::buffer buf_res1("buf_res1", {N_CONST}, tiramisu::p_float32, a_temporary, &function0);
    buf_res1.set_auto_allocate(false);
    tiramisu::computation *alloc_res1 = buf_res1.allocate_at(Res2, t);
    tiramisu::buffer buf_res2("buf_res2", {BT_CONST}, tiramisu::p_float32, a_output, &function0);
    tiramisu::buffer buf_d1("buf_d1", {KMAX}, tiramisu::p_int32, a_temporary, &function0);
    buf_d1.set_auto_allocate(false);
    tiramisu::computation *alloc_d1 = buf_d1.allocate_at(Res2, t);
    tiramisu::buffer buf_d2("buf_d2", {KMAX}, tiramisu::p_int32, a_temporary, &function0);
    buf_d2.set_auto_allocate(false);
    tiramisu::computation *alloc_d2 = buf_d2.allocate_at(Res2, t);
    tiramisu::buffer buf_d3("buf_d3", {KMAX}, tiramisu::p_int32, a_temporary, &function0);
    buf_d3.set_auto_allocate(false);
    tiramisu::computation *alloc_d3 = buf_d3.allocate_at(Res2, t);

    // S(d1, i3, i2, i1, t, a1, x’0)
    tiramisu::buffer buf_S("buf_S", {tiramisu::expr((int32_t) BARYON_P), tiramisu::expr((int32_t) BARYON_P), tiramisu::expr((int32_t) BARYON_P), N_CONST, N_CONST, N_CONST, tiramisu::expr((int32_t) BARYON_P1)}, tiramisu::p_float32, a_input, &function0);

    tiramisu::buffer buf_wp("buf_wp", {tiramisu::expr((int32_t) BARYON_N), tiramisu::expr((int32_t) BARYON_P), tiramisu::expr((int32_t) BARYON_P), tiramisu::expr((int32_t) BARYON_P)}, tiramisu::p_float32, a_input, &function0);

    fc1.store_in(&buf_fc1);
    fc2.store_in(&buf_fc2);
    fc3.store_in(&buf_fc3);
    d1.store_in(&buf_d1, {0});
    d2.store_in(&buf_d2, {0});
    d3.store_in(&buf_d3, {0});
    Res0.store_in(&buf_res0, {i3});
    Res1.store_in(&buf_res1, {i3});
    Res1_update_0.store_in(&buf_res1, {i3});
    Res2.store_in(&buf_res2, {t});
    Res2_update_0.store_in(&buf_res2, {t});
    S.store_in(&buf_S);
    wp.store_in(&buf_wp);

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------

    Res2.then(*alloc_res1, t)
	.then(*alloc_res0, t)
	.then(*alloc_d1, t)
	.then(*alloc_d2, t)
	.then(*alloc_d3, t)
	.then(Res1, i3)
	.then(d1, i3)
	.then(d2, k)
	.then(d3, k)
	.then(Res0, k)
	.then(Res1_update_0, k)
	.then(Res2_update_0, i2);

    Res0.tag_vector_level(i3, BARYON_N);
    Res2.tag_parallel_level(t);

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------

    function0.set_arguments({&buf_res2, &buf_S, &buf_wp, &buf_fc1, &buf_fc2, &buf_fc3});
    function0.gen_time_space_domain();
    function0.gen_isl_ast();
    function0.gen_halide_stmt();
    function0.gen_halide_obj("generated_" + std::string(TEST_NAME_STR) + ".o");
}

int main(int argc, char **argv)
{
    generate_function("tiramisu_generated_code", BARYON_N);

    return 0;
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include "args.h"

#include <stdlib.h>
#include <string.h>

#include <iostream>

Args::Args() {
  lr = 0.05;
  dim = 100;
  ws = 5;
  epoch = 5;
  minCount = 5;
  neg = 5;
  wordNgrams = 1;
  loss = loss_name::ns;
  model = model_name::sg;
  bucket = 2000000;
  minn = 3;
  maxn = 6;
  thread = 12;
  lrUpdateRate = 100;
  t = 1e-4;
  label = "__label__";
  verbose = 2;
}

void Args::parseArgs(int argc, char** argv) {
  std::string command(argv[1]);
  if (command == "supervised") {
    model = model_name::sup;
    loss = loss_name::softmax;
    minCount = 1;
    minn = 0;
    maxn = 0;
    lr = 0.1;
  } else if (command == "cbow") {
    model = model_name::cbow;
  }
  int ai = 2;
  while (ai < argc) {
    if (argv[ai][0] != '-') {
      std::cout << "Provided argument without a dash! Usage:" << std::endl;
      printHelp();
      exit(EXIT_FAILURE);
    }
    if (strcmp(argv[ai], "-h") == 0) {
      std::cout << "Here is the help! Usage:" << std::endl;
      printHelp();
      exit(EXIT_FAILURE);
    } else if (strcmp(argv[ai], "-input") == 0) {
      input = std::string(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-test") == 0) {
      test = std::string(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-output") == 0) {
      output = std::string(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-lr") == 0) {
      lr = atof(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-lrUpdateRate") == 0) {
      lrUpdateRate = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-dim") == 0) {
      dim = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-ws") == 0) {
      ws = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-epoch") == 0) {
      epoch = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-minCount") == 0) {
      minCount = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-neg") == 0) {
      neg = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-wordNgrams") == 0) {
      wordNgrams = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-loss") == 0) {
      if (strcmp(argv[ai + 1], "hs") == 0) {
        loss = loss_name::hs;
      } else if (strcmp(argv[ai + 1], "ns") == 0) {
        loss = loss_name::ns;
      } else if (strcmp(argv[ai + 1], "softmax") == 0) {
        loss = loss_name::softmax;
      } else {
        std::cout << "Unknown loss: " << argv[ai + 1] << std::endl;
        printHelp();
        exit(EXIT_FAILURE);
      }
    } else if (strcmp(argv[ai], "-bucket") == 0) {
      bucket = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-minn") == 0) {
      minn = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-maxn") == 0) {
      maxn = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-thread") == 0) {
      thread = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-t") == 0) {
      t = atof(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-label") == 0) {
      label = std::string(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-verbose") == 0) {
      verbose = atoi(argv[ai + 1]);
    } else {
      std::cout << "Unknown argument: " << argv[ai] << std::endl;
      printHelp();
      exit(EXIT_FAILURE);
    }
    ai += 2;
  }
  if (input.empty() || output.empty()) {
    std::cout << "Empty input or output path." << std::endl;
    printHelp();
    exit(EXIT_FAILURE);
  }
  if (wordNgrams <= 1 && maxn == 0) {
    bucket = 0;
  }
}

void Args::printHelp() {
  std::cout
    << "\n"
    << "The following arguments are mandatory:\n"
    << "  -input        training file path\n"
    << "  -output       output file path\n\n"
    << "The following arguments are optional:\n"
    << "  -lr           learning rate [" << lr << "]\n"
    << "  -lrUpdateRate change the rate of updates for the learning rate [" << lrUpdateRate << "]\n"
    << "  -dim          size of word vectors [" << dim << "]\n"
    << "  -ws           size of the context window [" << ws << "]\n"
    << "  -epoch        number of epochs [" << epoch << "]\n"
    << "  -minCount     minimal number of word occurences [" << minCount << "]\n"
    << "  -neg          number of negatives sampled [" << neg << "]\n"
    << "  -wordNgrams   max length of word ngram [" << wordNgrams << "]\n"
    << "  -loss         loss function {ns, hs, softmax} [ns]\n"
    << "  -bucket       number of buckets [" << bucket << "]\n"
    << "  -minn         min length of char ngram [" << minn << "]\n"
    << "  -maxn         max length of char ngram [" << maxn << "]\n"
    << "  -thread       number of threads [" << thread << "]\n"
    << "  -t            sampling threshold [" << t << "]\n"
    << "  -label        labels prefix [" << label << "]\n"
    << "  -verbose      verbosity level [" << verbose << "]\n"
    << std::endl;
}

void Args::save(std::ostream& out) {
  out.write((char*) &(dim), sizeof(int));
  out.write((char*) &(ws), sizeof(int));
  out.write((char*) &(epoch), sizeof(int));
  out.write((char*) &(minCount), sizeof(int));
  out.write((char*) &(neg), sizeof(int));
  out.write((char*) &(wordNgrams), sizeof(int));
  out.write((char*) &(loss), sizeof(loss_name));
  out.write((char*) &(model), sizeof(model_name));
  out.write((char*) &(bucket), sizeof(int));
  out.write((char*) &(minn), sizeof(int));
  out.write((char*) &(maxn), sizeof(int));
  out.write((char*) &(lrUpdateRate), sizeof(int));
  out.write((char*) &(t), sizeof(double));
}

void Args::load(std::istream& in) {
  in.read((char*) &(dim), sizeof(int));
  in.read((char*) &(ws), sizeof(int));
  in.read((char*) &(epoch), sizeof(int));
  in.read((char*) &(minCount), sizeof(int));
  in.read((char*) &(neg), sizeof(int));
  in.read((char*) &(wordNgrams), sizeof(int));
  in.read((char*) &(loss), sizeof(loss_name));
  in.read((char*) &(model), sizeof(model_name));
  in.read((char*) &(bucket), sizeof(int));
  in.read((char*) &(minn), sizeof(int));
  in.read((char*) &(maxn), sizeof(int));
  in.read((char*) &(lrUpdateRate), sizeof(int));
  in.read((char*) &(t), sizeof(double));
}
<commit_msg>Fix printHelp function<commit_after>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include "args.h"

#include <stdlib.h>
#include <string.h>

#include <iostream>

Args::Args() {
  lr = 0.05;
  dim = 100;
  ws = 5;
  epoch = 5;
  minCount = 5;
  neg = 5;
  wordNgrams = 1;
  loss = loss_name::ns;
  model = model_name::sg;
  bucket = 2000000;
  minn = 3;
  maxn = 6;
  thread = 12;
  lrUpdateRate = 100;
  t = 1e-4;
  label = "__label__";
  verbose = 2;
}

void Args::parseArgs(int argc, char** argv) {
  std::string command(argv[1]);
  if (command == "supervised") {
    model = model_name::sup;
    loss = loss_name::softmax;
    minCount = 1;
    minn = 0;
    maxn = 0;
    lr = 0.1;
  } else if (command == "cbow") {
    model = model_name::cbow;
  }
  int ai = 2;
  while (ai < argc) {
    if (argv[ai][0] != '-') {
      std::cout << "Provided argument without a dash! Usage:" << std::endl;
      printHelp();
      exit(EXIT_FAILURE);
    }
    if (strcmp(argv[ai], "-h") == 0) {
      std::cout << "Here is the help! Usage:" << std::endl;
      printHelp();
      exit(EXIT_FAILURE);
    } else if (strcmp(argv[ai], "-input") == 0) {
      input = std::string(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-test") == 0) {
      test = std::string(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-output") == 0) {
      output = std::string(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-lr") == 0) {
      lr = atof(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-lrUpdateRate") == 0) {
      lrUpdateRate = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-dim") == 0) {
      dim = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-ws") == 0) {
      ws = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-epoch") == 0) {
      epoch = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-minCount") == 0) {
      minCount = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-neg") == 0) {
      neg = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-wordNgrams") == 0) {
      wordNgrams = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-loss") == 0) {
      if (strcmp(argv[ai + 1], "hs") == 0) {
        loss = loss_name::hs;
      } else if (strcmp(argv[ai + 1], "ns") == 0) {
        loss = loss_name::ns;
      } else if (strcmp(argv[ai + 1], "softmax") == 0) {
        loss = loss_name::softmax;
      } else {
        std::cout << "Unknown loss: " << argv[ai + 1] << std::endl;
        printHelp();
        exit(EXIT_FAILURE);
      }
    } else if (strcmp(argv[ai], "-bucket") == 0) {
      bucket = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-minn") == 0) {
      minn = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-maxn") == 0) {
      maxn = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-thread") == 0) {
      thread = atoi(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-t") == 0) {
      t = atof(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-label") == 0) {
      label = std::string(argv[ai + 1]);
    } else if (strcmp(argv[ai], "-verbose") == 0) {
      verbose = atoi(argv[ai + 1]);
    } else {
      std::cout << "Unknown argument: " << argv[ai] << std::endl;
      printHelp();
      exit(EXIT_FAILURE);
    }
    ai += 2;
  }
  if (input.empty() || output.empty()) {
    std::cout << "Empty input or output path." << std::endl;
    printHelp();
    exit(EXIT_FAILURE);
  }
  if (wordNgrams <= 1 && maxn == 0) {
    bucket = 0;
  }
}

void Args::printHelp() {
  std::string lname = "ns";
  if (loss == loss_name::hs) lname = "hs";
  if (loss == loss_name::softmax) lname = "softmax";
  std::cout
    << "\n"
    << "The following arguments are mandatory:\n"
    << "  -input        training file path\n"
    << "  -output       output file path\n\n"
    << "The following arguments are optional:\n"
    << "  -lr           learning rate [" << lr << "]\n"
    << "  -lrUpdateRate change the rate of updates for the learning rate [" << lrUpdateRate << "]\n"
    << "  -dim          size of word vectors [" << dim << "]\n"
    << "  -ws           size of the context window [" << ws << "]\n"
    << "  -epoch        number of epochs [" << epoch << "]\n"
    << "  -minCount     minimal number of word occurences [" << minCount << "]\n"
    << "  -neg          number of negatives sampled [" << neg << "]\n"
    << "  -wordNgrams   max length of word ngram [" << wordNgrams << "]\n"
    << "  -loss         loss function {ns, hs, softmax} [" << lname << "]\n"
    << "  -bucket       number of buckets [" << bucket << "]\n"
    << "  -minn         min length of char ngram [" << minn << "]\n"
    << "  -maxn         max length of char ngram [" << maxn << "]\n"
    << "  -thread       number of threads [" << thread << "]\n"
    << "  -t            sampling threshold [" << t << "]\n"
    << "  -label        labels prefix [" << label << "]\n"
    << "  -verbose      verbosity level [" << verbose << "]\n"
    << std::endl;
}

void Args::save(std::ostream& out) {
  out.write((char*) &(dim), sizeof(int));
  out.write((char*) &(ws), sizeof(int));
  out.write((char*) &(epoch), sizeof(int));
  out.write((char*) &(minCount), sizeof(int));
  out.write((char*) &(neg), sizeof(int));
  out.write((char*) &(wordNgrams), sizeof(int));
  out.write((char*) &(loss), sizeof(loss_name));
  out.write((char*) &(model), sizeof(model_name));
  out.write((char*) &(bucket), sizeof(int));
  out.write((char*) &(minn), sizeof(int));
  out.write((char*) &(maxn), sizeof(int));
  out.write((char*) &(lrUpdateRate), sizeof(int));
  out.write((char*) &(t), sizeof(double));
}

void Args::load(std::istream& in) {
  in.read((char*) &(dim), sizeof(int));
  in.read((char*) &(ws), sizeof(int));
  in.read((char*) &(epoch), sizeof(int));
  in.read((char*) &(minCount), sizeof(int));
  in.read((char*) &(neg), sizeof(int));
  in.read((char*) &(wordNgrams), sizeof(int));
  in.read((char*) &(loss), sizeof(loss_name));
  in.read((char*) &(model), sizeof(model_name));
  in.read((char*) &(bucket), sizeof(int));
  in.read((char*) &(minn), sizeof(int));
  in.read((char*) &(maxn), sizeof(int));
  in.read((char*) &(lrUpdateRate), sizeof(int));
  in.read((char*) &(t), sizeof(double));
}
<|endoftext|>