<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (C) 2010 LinBox
 *
 * Time-stamp: <16 Dec 10 17:48:13 Jean-Guillaume.Dumas@imag.fr>
 *
 * 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 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., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*! @file tests-test-cradomain.C
 * @ingroup tests
 * @brief tests LinBox::ChineseRemainer
 * @test tests LinBox::ChineseRemainer (see \ref CRA)
 */

#include <linbox/algorithms/cra-domain.h>
#include <linbox/field/modular-double.h>
#include "linbox/algorithms/blas-domain.h"
#include "linbox/algorithms/cra-early-multip.h"
#include "linbox/algorithms/cra-full-multip.h"
#include "linbox/algorithms/cra-full-multip-fixed.h"
#include "linbox/randiter/random-prime.h"

struct Interator {
	std::vector<Integer> _v;
	double maxsize;

	Interator(const std::vector<Integer>& v) :
		_v(v), maxsize(0.0)
	{
		for(std::vector<Integer>::const_iterator it=_v.begin();
		    it != _v.end(); ++it) {
			double ds = naturallog(*it);
			maxsize = (maxsize<ds?ds:maxsize);
		}
	}

	Interator(int n, int s) :
		_v(n), maxsize(0.0)
	{
		for(std::vector<Integer>::iterator it=_v.begin();
		    it != _v.end(); ++it) {
			Integer::random(*it, s);
			double ds = naturallog(*it);
			maxsize = (maxsize<ds?ds:maxsize);
		}
	}

	const std::vector<Integer>& getVector() { return _v; }
	const double getLogSize() { return maxsize; }

	template<typename Field>
	std::vector<typename Field::Element>& operator()(std::vector<typename Field::Element>& v,
							 const Field& F) const
	{
		v.resize(_v.size());
		std::vector<Integer>::const_iterator vit=_v.begin();
		typename std::vector<typename Field::Element>::iterator eit=v.begin();
		for( ; vit != _v.end(); ++vit, ++eit)
			F.init(*eit, *vit);
		return v;
	}
};

struct InteratorIt;
namespace LinBox
{
	template<class Element> struct CRATemporaryVectorTrait<InteratorIt , Element> {
		typedef typename std::vector<double>::iterator Type_t;
	};
}

struct InteratorIt : public Interator {

	mutable std::vector<double> _C;

	InteratorIt(const std::vector<Integer>& v) :
		Interator(v), _C(v.size())
	{}
	InteratorIt(int n, int s) :
		Interator(n,s), _C(n)
	{}

	template<typename Iterator, typename Field>
	Iterator& operator()(Iterator& res, const Field& F) const
	{
		std::vector<Integer>::const_iterator vit=this->_v.begin();
		std::vector<double>::iterator eit=_C.begin();
		for( ; vit != _v.end(); ++vit, ++eit)
			F.init(*eit, *vit);
		return res=_C.begin();
	}

};

template<typename Field> struct InteratorBlas;
namespace LinBox
{
    template<class Element,class Field> struct CRATemporaryVectorTrait<InteratorBlas<Field> , Element> {
        typedef typename LinBox::BlasMatrix<Element>::pointer Type_t;
    };
}

template<typename Field>
struct InteratorBlas : public Interator {
    typedef typename Field::Element Element;
    typedef LinBox::BlasMatrix<Element> Matrix;
    typedef typename Matrix::pointer Pointer;
    mutable Matrix _C;

    InteratorBlas(const std::vector<Integer>& v) : Interator(v), _C(v.size(),1) {}
    InteratorBlas(int n, int s) : Interator(n,s), _C(n,1) {}

    Pointer& operator()(Pointer& res, const Field& F) const {
        std::vector<Integer>::const_iterator vit=this->_v.begin();
        res = _C.getWritePointer();
        for( ; vit != _v.end(); ++vit, ++res)
            F.init(*res, *vit);

        return res=_C.getWritePointer();
    }

};

bool TestCra(int N, int S, size_t seed)
{

    std::ostream &report = LinBox::commentator.report
                (LinBox::Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);

    report << "TestCra(" << N << ',' << S << ',' << seed << ')' << std::endl;
    Integer::seeding(seed);

    Interator iteration(N, S);
    InteratorIt iterationIt(iteration.getVector());
    LinBox::RandomPrimeIterator genprime( 24, seed );

    bool pass = true;

    report << "ChineseRemainder<EarlyMultipCRA>(4)" << std::endl;
    {
        LinBox::ChineseRemainder< LinBox::EarlyMultipCRA< LinBox::Modular<double> > > craEM(4UL);
        std::vector<Integer> ResEM(N);
        craEM( ResEM, iteration, genprime);
        bool locpass = std::equal( ResEM.begin(), ResEM.end(), iteration.getVector().begin() );
        if (locpass) report << "ChineseRemainder<EarlyMultipCRA>(4)" << ", passed."  << std::endl;
        else report << "***ERROR***: ChineseRemainder<EarlyMultipCRA>(4)" << "***ERROR***"  << std::endl;
        pass = pass && locpass;
    }

    report << "ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << std::endl;
    {
        LinBox::ChineseRemainder< LinBox::FullMultipCRA< LinBox::Modular<double> > > craFM( iteration.getLogSize() );
        std::vector<Integer> ResFM(N);
        craFM( ResFM, iteration, genprime);
        bool locpass = std::equal( ResFM.begin(), ResFM.end(), iteration.getVector().begin() );
        if (locpass) report << "ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << ", passed."  << std::endl;
        else report << "***ERROR***: ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << "***ERROR***"  << std::endl;
        pass = pass && locpass;
    }

    report << "ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << std::endl;
    {
        LinBox::ChineseRemainder< LinBox::FullMultipFixedCRA< LinBox::Modular<double> > > craFMF( std::pair<size_t,double>(N,iterationIt.getLogSize()) );
        std::vector<Integer> ResFMF(N);
        std::vector<Integer>::iterator ResIT= ResFMF.begin();
        craFMF( ResIT, iterationIt, genprime);
        bool locpass = std::equal( iterationIt.getVector().begin(), iterationIt.getVector().end(), ResFMF.begin() );
        if (locpass) report << "ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << ", passed."  << std::endl;
        else report << "***ERROR***: ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << "***ERROR***"  << std::endl;
        pass = pass && locpass;
    }

    report << "ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << std::endl;
    {
        LinBox::ChineseRemainder< LinBox::FullMultipFixedCRA< LinBox::Modular<double> > > craFMFBM( std::pair<size_t,double>(N,iterationIt.getLogSize()) );
        LinBox::BlasMatrix<Integer> ResFMFBM(N,1);
        craFMFBM( ResFMFBM.getWritePointer(), iterationIt, genprime);

        bool locpass = std::equal( iterationIt.getVector().begin(), iterationIt.getVector().end(), ResFMFBM.getWritePointer() );

        if (locpass) report << "ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << ", passed."  << std::endl;
        else
            report << "***ERROR***: ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << " ***ERROR***"  << std::endl;

        pass = pass && locpass;
    }

    if (pass) report << "TestCra(" << N << ',' << S << ')' << ", passed." << std::endl;
    else
        report << "***ERROR***: TestCra(" << N << ',' << S << ')' << " ***ERROR***" << std::endl;

    return pass;
}

#include "test-common.h"
#include "linbox/util/timer.h"

int main (int argc, char **argv)
{
	static size_t n = 1000;
	static size_t s = 30;
        static size_t seed = LinBox::BaseTimer::seed();
	static int iterations = 20;

        static Argument args[] = {
                { 'n', "-n N", "Set dimension of test vectors to NxN.", TYPE_INT
, &n },
                { 's', "-s S", "Set size of test integers.", TYPE_INT
, &s },
                { 'z', "-z Z", "Set seed.", TYPE_INT
, &seed },
                { 'i', "-i I", "Perform each test for I iterations.",     TYPE_INT, &iterations },
                { '\0' }
        };

	parseArguments (argc, argv, args);

	commentator.start("CRA-Domain test suite", "CRADom");
	bool pass = true;

	for(int i=0; pass && i<iterations; ++i)
		pass &= TestCra(n,s,seed);

	commentator.stop(MSG_STATUS (pass), (const char *) 0,"CRA-Domain test suite");
	return pass ? 0 : -1;
}
<commit_msg>pass &=<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (C) 2010 LinBox
 *
 * Time-stamp: <16 Dec 10 18:13:45 Jean-Guillaume.Dumas@imag.fr>
 *
 * 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 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., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*! @file tests-test-cradomain.C
 * @ingroup tests
 * @brief tests LinBox::ChineseRemainer
 * @test tests LinBox::ChineseRemainer (see \ref CRA)
 */

#include <linbox/algorithms/cra-domain.h>
#include <linbox/field/modular-double.h>
#include "linbox/algorithms/blas-domain.h"
#include "linbox/algorithms/cra-early-multip.h"
#include "linbox/algorithms/cra-full-multip.h"
#include "linbox/algorithms/cra-full-multip-fixed.h"
#include "linbox/randiter/random-prime.h"

struct Interator {
	std::vector<Integer> _v;
	double maxsize;

	Interator(const std::vector<Integer>& v) :
		_v(v), maxsize(0.0)
	{
		for(std::vector<Integer>::const_iterator it=_v.begin();
		    it != _v.end(); ++it) {
			double ds = naturallog(*it);
			maxsize = (maxsize<ds?ds:maxsize);
		}
	}

	Interator(int n, int s) :
		_v(n), maxsize(0.0)
	{
		for(std::vector<Integer>::iterator it=_v.begin();
		    it != _v.end(); ++it) {
			Integer::random(*it, s);
			double ds = naturallog(*it);
			maxsize = (maxsize<ds?ds:maxsize);
		}
	}

	const std::vector<Integer>& getVector() { return _v; }
	const double getLogSize() { return maxsize; }

	template<typename Field>
	std::vector<typename Field::Element>& operator()(std::vector<typename Field::Element>& v,
							 const Field& F) const
	{
		v.resize(_v.size());
		std::vector<Integer>::const_iterator vit=_v.begin();
		typename std::vector<typename Field::Element>::iterator eit=v.begin();
		for( ; vit != _v.end(); ++vit, ++eit)
			F.init(*eit, *vit);
		return v;
	}
};

struct InteratorIt;
namespace LinBox
{
	template<class Element> struct CRATemporaryVectorTrait<InteratorIt , Element> {
		typedef typename std::vector<double>::iterator Type_t;
	};
}

struct InteratorIt : public Interator {

	mutable std::vector<double> _C;

	InteratorIt(const std::vector<Integer>& v) :
		Interator(v), _C(v.size())
	{}
	InteratorIt(int n, int s) :
		Interator(n,s), _C(n)
	{}

	template<typename Iterator, typename Field>
	Iterator& operator()(Iterator& res, const Field& F) const
	{
		std::vector<Integer>::const_iterator vit=this->_v.begin();
		std::vector<double>::iterator eit=_C.begin();
		for( ; vit != _v.end(); ++vit, ++eit)
			F.init(*eit, *vit);
		return res=_C.begin();
	}

};

template<typename Field> struct InteratorBlas;
namespace LinBox
{
    template<class Element,class Field> struct CRATemporaryVectorTrait<InteratorBlas<Field> , Element> {
        typedef typename LinBox::BlasMatrix<Element>::pointer Type_t;
    };
}

template<typename Field>
struct InteratorBlas : public Interator {
    typedef typename Field::Element Element;
    typedef LinBox::BlasMatrix<Element> Matrix;
    typedef typename Matrix::pointer Pointer;
    mutable Matrix _C;

    InteratorBlas(const std::vector<Integer>& v) : Interator(v), _C(v.size(),1) {}
    InteratorBlas(int n, int s) : Interator(n,s), _C(n,1) {}

    Pointer& operator()(Pointer& res, const Field& F) const {
        std::vector<Integer>::const_iterator vit=this->_v.begin();
        res = _C.getWritePointer();
        for( ; vit != _v.end(); ++vit, ++res)
            F.init(*res, *vit);

        return res=_C.getWritePointer();
    }

};

bool TestCra(int N, int S, size_t seed)
{

    std::ostream &report = LinBox::commentator.report
                (LinBox::Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);

    report << "TestCra(" << N << ',' << S << ',' << seed << ')' << std::endl;
    Integer::seeding(seed);

    Interator iteration(N, S);
    InteratorIt iterationIt(iteration.getVector());
    LinBox::RandomPrimeIterator genprime( 24, seed );

    bool pass = true;

    report << "ChineseRemainder<EarlyMultipCRA>(4)" << std::endl;
    {
        LinBox::ChineseRemainder< LinBox::EarlyMultipCRA< LinBox::Modular<double> > > craEM(4UL);
        std::vector<Integer> ResEM(N);
        craEM( ResEM, iteration, genprime);
        bool locpass = std::equal( ResEM.begin(), ResEM.end(), iteration.getVector().begin() );
        if (locpass) report << "ChineseRemainder<EarlyMultipCRA>(4)" << ", passed."  << std::endl;
        else report << "***ERROR***: ChineseRemainder<EarlyMultipCRA>(4)" << "***ERROR***"  << std::endl;
        pass &= locpass;
    }

    report << "ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << std::endl;
    {
        LinBox::ChineseRemainder< LinBox::FullMultipCRA< LinBox::Modular<double> > > craFM( iteration.getLogSize() );
        std::vector<Integer> ResFM(N);
        craFM( ResFM, iteration, genprime);
        bool locpass = std::equal( ResFM.begin(), ResFM.end(), iteration.getVector().begin() );
        if (locpass) report << "ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << ", passed."  << std::endl;
        else report << "***ERROR***: ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << "***ERROR***"  << std::endl;
        pass &= locpass;
    }

    report << "ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << std::endl;
    {
        LinBox::ChineseRemainder< LinBox::FullMultipFixedCRA< LinBox::Modular<double> > > craFMF( std::pair<size_t,double>(N,iterationIt.getLogSize()) );
        std::vector<Integer> ResFMF(N);
        std::vector<Integer>::iterator ResIT= ResFMF.begin();
        craFMF( ResIT, iterationIt, genprime);
        bool locpass = std::equal( iterationIt.getVector().begin(), iterationIt.getVector().end(), ResFMF.begin() );
        if (locpass) report << "ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << ", passed."  << std::endl;
        else report << "***ERROR***: ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << "***ERROR***"  << std::endl;
        pass &= locpass;
    }

    report << "ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << std::endl;
    {
        LinBox::ChineseRemainder< LinBox::FullMultipFixedCRA< LinBox::Modular<double> > > craFMFBM( std::pair<size_t,double>(N,iterationIt.getLogSize()) );
        LinBox::BlasMatrix<Integer> ResFMFBM(N,1);
        craFMFBM( ResFMFBM.getWritePointer(), iterationIt, genprime);

        bool locpass = std::equal( iterationIt.getVector().begin(), iterationIt.getVector().end(), ResFMFBM.getWritePointer() );

        if (locpass) report << "ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << ", passed."  << std::endl;
        else
            report << "***ERROR***: ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << " ***ERROR***"  << std::endl;

        pass &= locpass;
    }

    if (pass) report << "TestCra(" << N << ',' << S << ')' << ", passed." << std::endl;
    else
        report << "***ERROR***: TestCra(" << N << ',' << S << ')' << " ***ERROR***" << std::endl;

    return pass;
}

#include "test-common.h"
#include "linbox/util/timer.h"

int main (int argc, char **argv)
{
	static size_t n = 1000;
	static size_t s = 30;
        static size_t seed = LinBox::BaseTimer::seed();
	static int iterations = 20;

        static Argument args[] = {
                { 'n', "-n N", "Set dimension of test vectors to NxN.", TYPE_INT
, &n },
                { 's', "-s S", "Set size of test integers.", TYPE_INT
, &s },
                { 'z', "-z Z", "Set seed.", TYPE_INT
, &seed },
                { 'i', "-i I", "Perform each test for I iterations.",     TYPE_INT, &iterations },
                { '\0' }
        };

	parseArguments (argc, argv, args);

	commentator.start("CRA-Domain test suite", "CRADom");
	bool pass = true;

	for(int i=0; pass && i<iterations; ++i)
		pass &= TestCra(n,s,seed);

	commentator.stop(MSG_STATUS (pass), (const char *) 0,"CRA-Domain test suite");
	return pass ? 0 : -1;
}
<|endoftext|>


<commit_before>// https://www.facebook.com/hackercup/problem/1424196571244550/
// Facebook Hacker Cup 2016 Round 1
// Boomerang Tournament
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;

int n;
int in[16][16];
int memo[16][1<<16];

void input() {
    cin >> n;
    for (int r = 0; r < n ; r++) {
        for (int c = 0; c < n ; c++) {
            cin >> in[r][c];
        }
    }
}

int next(int v) {
    unsigned int t = (v | (v - 1)) + 1;
    return (int)(t | ((((t & -t) / (v & -v)) >> 1) - 1));
}

int win(int i, int flag) {
    int &result = memo[i][flag];
    if ((1<<i) & flag) return result;

    int temp = flag;
    while (temp) {
        int index = __builtin_ctz(temp);
        if (memo[index][flag] && in[i][index]) {
            result = 1;
            break;
        }
        temp &= temp - 1;
    }
    return result;
}

void set_each(int a, int b) {
    int index = a | b;
    for (int i = 0; i < n; i++) {
        if (memo[i][index] == 1 || !(index & (1<<i))) continue;
        if (win(i, a) && win(i, b)) {
            memo[i][index] = 1;
        }
    }
}

int calc_best() {
    memset(memo, 0, sizeof(memo));

    const int limit = 1 << n;
    for (int r = 0; r < n ; r++) {
        memo[r][1<<r] = 1; // itself
    }

    for (int num = 1; num < n; num <<= 1) { // for (1, 2, 4, 8, 16)
        vector<int> v;
        int flag = (1 << num) - 1;
        while (flag < limit) {
            v.push_back(flag);
            flag = next(flag);
        }

        for (int a : v) {
            for (int b : v) {
                if (a <= b) continue; // only b < a
                if (__builtin_popcount(a|b) != (num << 1)) continue;
                set_each(a, b);
            }
        }
    }
    return 0;
}

int worst(int x) {
    for (int i = 0; i < n; i++) {
        if (i != x && in[x][i] == 0) return ((n >> 1) + 1);
    }
    return 1;
}

int best(int me) {
    const int rank [] = {1, 2, 3, 5, 9};
    const int limit = 1 << n;
    int i(0), num(n);
    for (; 0 < num; num >>= 1, i++) {
        int flag = (1 << num) - 1;
        while (flag < limit) {
            if (flag & (1<<me) && memo[me][flag]) return rank[i];
            flag = next(flag);
        }
    }

    return rank[i];
}

void solve() {
    calc_best();
    for (int i = 0; i < n; i++) {
        printf("%d %d\n", best(i), worst(i));
    }
}

int main() {
    int t; cin >> t;
    for (int i = 1; i <= t; i++) {
        input();
        printf("Case #%d:\n", i);
        solve();
    }
    return 0;
}

<commit_msg>Update main.cpp<commit_after>// https://www.facebook.com/hackercup/problem/1424196571244550/
// Facebook Hacker Cup 2016 Round 1
// Boomerang Tournament
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;

int n;
int in[16][16];
int memo[16][1<<16];

void input() {
    cin >> n;
    for (int r = 0; r < n ; r++) {
        for (int c = 0; c < n ; c++) {
            cin >> in[r][c];
        }
    }
}

int next(int v) {
    unsigned int t = (v | (v - 1)) + 1;
    return (int)(t | ((((t & -t) / (v & -v)) >> 1) - 1));
}

int win(int i, int flag) {
    int &result = memo[i][flag];
    if ((1<<i) & flag) return result;

    int temp = flag;
    while (temp) {
        int index = __builtin_ctz(temp);
        if (memo[index][flag] && in[i][index]) {
            result = 1;
            break;
        }
        temp &= temp - 1;
    }
    return result;
}

void set_each(int a, int b) {
    int index = a | b;
    for (int i = 0; i < n; i++) {
        if (memo[i][index] == 1 || !(index & (1<<i))) continue;
        if (win(i, a) && win(i, b)) {
            memo[i][index] = 1;
        }
    }
}

int calc_best() {
    memset(memo, 0, sizeof(memo));

    const int limit = 1 << n;
    for (int r = 0; r < n ; r++) {
        memo[r][1<<r] = 1; // itself
    }

    for (int num = 1; num < n; num <<= 1) { // for (1, 2, 4, 8, 16)
        vector<int> v;
        int flag = (1 << num) - 1;
        while (flag < limit) {
            v.push_back(flag);
            flag = next(flag);
        }

        for (int a : v) {
            for (int b : v) {
                if (a <= b) continue; // only b < a
                if (a & b) continue;
                set_each(a, b);
            }
        }
    }
    return 0;
}

int worst(int x) {
    for (int i = 0; i < n; i++) {
        if (i != x && in[x][i] == 0) return ((n >> 1) + 1);
    }
    return 1;
}

int best(int me) {
    const int rank [] = {1, 2, 3, 5, 9};
    const int limit = 1 << n;
    int i(0), num(n);
    for (; 0 < num; num >>= 1, i++) {
        int flag = (1 << num) - 1;
        while (flag < limit) {
            if (flag & (1<<me) && memo[me][flag]) return rank[i];
            flag = next(flag);
        }
    }

    return rank[i];
}

void solve() {
    calc_best();
    for (int i = 0; i < n; i++) {
        printf("%d %d\n", best(i), worst(i));
    }
}

int main() {
    int t; cin >> t;
    for (int i = 1; i <= t; i++) {
        input();
        printf("Case #%d:\n", i);
        solve();
    }
    return 0;
}

<|endoftext|>


<commit_before>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka 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 3 of the License, or
* (at your option) any later version.
*
* alpaka 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 alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/

#include <alpaka/alpaka.hpp>                        // alpaka::exec::create
#include <alpaka/integ/MeasureKernelRunTime.hpp>    // measureKernelRunTimeMs
#include <alpaka/integ/accs/EnabledAccs.hpp>        // EnabledAccs

#include <iostream>                                 // std::cout
#include <typeinfo>                                 // typeid
#include <vector>                                   // std::vector

//#############################################################################
//! A kernel using atomicOp, syncBlockThreads, getBlockSharedExternMem, getIdx, getWorkDiv and global memory to compute a (useless) result.
//! \tparam TAcc The accelerator environment to be executed on.
//! \tparam TnumUselessWork The number of useless calculations done in each kernel execution.
//#############################################################################
template<
    typename TnumUselessWork>
class SharedMemKernel
{
public:
    //-----------------------------------------------------------------------------
    //! Constructor.
    //-----------------------------------------------------------------------------
    SharedMemKernel(
        std::uint32_t const mult = 2) :
        m_mult(mult)
    {}

    //-----------------------------------------------------------------------------
    //! The kernel.
    //-----------------------------------------------------------------------------
    ALPAKA_NO_HOST_ACC_WARNING
    template<
        typename TAcc>
    ALPAKA_FN_ACC auto operator()(
        TAcc const & acc,
        std::uint32_t * const puiBlockRetVals,
        std::uint32_t const mult2) const
    -> void
    {
        static_assert(
            alpaka::dim::Dim<TAcc>::value == 1,
            "The SharedMemKernel expects 1-dimensional indices!");

        // The number of threads in this block.
        std::size_t const blockThreadCount(alpaka::workdiv::getWorkDiv<alpaka::Block, alpaka::Threads>(acc)[0u]);

        // Get the extern allocated shared memory.
        std::uint32_t * const pBlockShared(acc.template getBlockSharedExternMem<std::uint32_t>());

        // Get some shared memory (allocate a second buffer directly afterwards to check for some synchronization bugs).
        //std::uint32_t * const pBlockShared1(alpaka::block::shared::allocArr<std::uint32_t, TnumUselessWork::value>());
        //std::uint32_t * const pBlockShared2(alpaka::block::shared::allocArr<std::uint32_t, TnumUselessWork::value>());

        // Calculate linearized index of the thread in the block.
        std::size_t const blockThreadIdx1d(alpaka::idx::getIdx<alpaka::Block, alpaka::Threads>(acc)[0u]);

        // Fill the shared block with the thread ids [1+X, 2+X, 3+X, ..., #Threads+X].
        std::uint32_t iSum1(static_cast<std::uint32_t>(blockThreadIdx1d+1));
        for(std::uint32_t i(0); i<TnumUselessWork::value; ++i)
        {
            iSum1 += i;
        }
        pBlockShared[blockThreadIdx1d] = iSum1;

        // Synchronize all threads because now we are writing to the memory again but inverse.
        alpaka::block::sync::syncBlockThreads(acc);

        // Do something useless.
        std::uint32_t iSum2(static_cast<std::uint32_t>(blockThreadIdx1d));
        for(std::uint32_t i(0); i<TnumUselessWork::value; ++i)
        {
            iSum2 -= i;
        }
        // Add the inverse so that every cell is filled with [#Threads, #Threads, ..., #Threads].
        pBlockShared[(blockThreadCount-1)-blockThreadIdx1d] += iSum2;

        // Synchronize all threads again.
        alpaka::block::sync::syncBlockThreads(acc);

        // Now add up all the cells atomically and write the result to cell 0 of the shared memory.
        if(blockThreadIdx1d > 0)
        {
            alpaka::atomic::atomicOp<alpaka::atomic::op::Add>(acc, &pBlockShared[0], pBlockShared[blockThreadIdx1d]);
        }

        alpaka::block::sync::syncBlockThreads(acc);

        // Only master writes result to global memory.
        if(blockThreadIdx1d==0)
        {
            // Calculate linearized block id.
            std::size_t const blockIdx(alpaka::idx::getIdx<alpaka::Grid, alpaka::Blocks>(acc)[0u]);

            puiBlockRetVals[blockIdx] = pBlockShared[0] * m_mult * mult2;
        }
    }

public:
    std::uint32_t const m_mult;
};

namespace alpaka
{
    namespace kernel
    {
        namespace traits
        {
            //#############################################################################
            //! The trait for getting the size of the block shared extern memory for a kernel.
            //#############################################################################
            template<
                typename TnumUselessWork,
                typename TAcc>
            struct BlockSharedExternMemSizeBytes<
                SharedMemKernel<TnumUselessWork>,
                TAcc>
            {
                //-----------------------------------------------------------------------------
                //! \return The size of the shared memory allocated for a block.
                //-----------------------------------------------------------------------------
                template<
                    typename TVec,
                    typename... TArgs>
                ALPAKA_FN_HOST static auto getBlockSharedExternMemSizeBytes(
                    TVec const & blockElemExtent,
                    TArgs && ...)
                -> std::uint32_t
                {
                    return blockElemExtent.prod() * sizeof(std::uint32_t);
                }
            };
        }
    }
}

//#############################################################################
//! Profiles the example kernel and checks the result.
//#############################################################################
template<
    typename TnumUselessWork>
struct SharedMemTester
{
    template<
        typename TAcc,
        typename TSize,
        typename TVal>
    auto operator()(
        TSize const numElements,
        TVal const mult2)
    -> void
    {
        std::cout << std::endl;
        std::cout << "################################################################################" << std::endl;

        // Create the kernel function object.
        SharedMemKernel<TnumUselessWork> kernel(42);

        // Select a device to execute on.
        alpaka::dev::Dev<TAcc> devAcc(
            alpaka::dev::DevMan<TAcc>::getDevByIdx(0));

        // Get a stream on this device.
        alpaka::integ::Stream<alpaka::dev::Dev<TAcc>> stream(devAcc);

        // Set the grid blocks extent.
        alpaka::workdiv::WorkDivMembers<alpaka::dim::DimInt<1u>, TSize> const workDiv(
            alpaka::workdiv::getValidWorkDiv<TAcc>(
                devAcc,
                numElements,
                static_cast<TSize>(1u),
                false,
                alpaka::workdiv::GridBlockExtentSubDivRestrictions::Unrestricted));

        std::cout
            << "SharedMemTester("
            << " accelerator: " << alpaka::acc::getAccName<TAcc>()
            << ", kernel: " << typeid(kernel).name()
            << ", workDiv: " << workDiv
            << ")" << std::endl;

        TSize const gridBlocksCount(
            alpaka::workdiv::getWorkDiv<alpaka::Grid, alpaka::Blocks>(workDiv)[0u]);
        TSize const blockThreadCount(
            alpaka::workdiv::getWorkDiv<alpaka::Block, alpaka::Threads>(workDiv)[0u]);

        // An array for the return values calculated by the blocks.
        std::vector<TVal> blockRetVals(gridBlocksCount, static_cast<TVal>(0));

        // Allocate accelerator buffers and copy.
        TSize const resultElemCount(gridBlocksCount);
        auto blockRetValsAcc(alpaka::mem::buf::alloc<TVal, TSize>(devAcc, resultElemCount));
        alpaka::mem::view::copy(stream, blockRetValsAcc, blockRetVals, resultElemCount);

        // Create the executor task.
        auto const exec(alpaka::exec::create<TAcc>(
            workDiv,
            kernel,
            alpaka::mem::view::getPtrNative(blockRetValsAcc),
            mult2));

        // Profile the kernel execution.
        std::cout << "Execution time: "
            << alpaka::integ::measureKernelRunTimeMs(
                stream,
                exec)
            << " ms"
            << std::endl;

        // Copy back the result.
        alpaka::mem::view::copy(stream, blockRetVals, blockRetValsAcc, resultElemCount);

        // Wait for the stream to finish the memory operation.
        alpaka::wait::wait(stream);

        // Assert that the results are correct.
        TVal const correctResult(
            static_cast<TVal>(blockThreadCount*blockThreadCount)
            * kernel.m_mult
            * mult2);

        bool resultCorrect(true);
        for(std::size_t i(0); i<gridBlocksCount; ++i)
        {
            if(blockRetVals[i] != correctResult)
            {
                std::cout << "blockRetVals[" << i << "] == " << blockRetVals[i] << " != " << correctResult << std::endl;
                resultCorrect = false;
            }
        }

        if(resultCorrect)
        {
            std::cout << "Execution results correct!" << std::endl;
        }

        std::cout << "################################################################################" << std::endl;

        allResultsCorrect = allResultsCorrect && resultCorrect;
    }

public:
    bool allResultsCorrect = true;
};

//-----------------------------------------------------------------------------
//! Program entry point.
//-----------------------------------------------------------------------------
auto main()
-> int
{
    try
    {
        std::cout << std::endl;
        std::cout << "################################################################################" << std::endl;
        std::cout << "                            alpaka sharedMem test                               " << std::endl;
        std::cout << "################################################################################" << std::endl;
        std::cout << std::endl;

        // Logs the enabled accelerators.
        alpaka::integ::accs::writeEnabledAccs<alpaka::dim::DimInt<1u>, std::uint32_t>(std::cout);

        std::cout << std::endl;

        using TnumUselessWork = std::integral_constant<std::size_t, 100u>;
        std::uint32_t const mult2(5u);

        SharedMemTester<TnumUselessWork> sharedMemTester;

        // Execute the kernel on all enabled accelerators.
        alpaka::core::forEachType<
            alpaka::integ::accs::EnabledAccs<alpaka::dim::DimInt<1u>, std::uint32_t>>(
                sharedMemTester,
                static_cast<std::uint32_t>(512u),
                mult2);

        return sharedMemTester.allResultsCorrect ? EXIT_SUCCESS : EXIT_FAILURE;
    }
    catch(std::exception const & e)
    {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch(...)
    {
        std::cerr << "Unknown Exception" << std::endl;
        return EXIT_FAILURE;
    }
}
<commit_msg>update example with new shared memory interface<commit_after>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka 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 3 of the License, or
* (at your option) any later version.
*
* alpaka 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 alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/

#include <alpaka/alpaka.hpp>                        // alpaka::exec::create
#include <alpaka/integ/MeasureKernelRunTime.hpp>    // measureKernelRunTimeMs
#include <alpaka/integ/accs/EnabledAccs.hpp>        // EnabledAccs

#include <iostream>                                 // std::cout
#include <typeinfo>                                 // typeid
#include <vector>                                   // std::vector

//#############################################################################
//! A kernel using atomicOp, syncBlockThreads, getBlockSharedExternMem, getIdx, getWorkDiv and global memory to compute a (useless) result.
//! \tparam TAcc The accelerator environment to be executed on.
//! \tparam TnumUselessWork The number of useless calculations done in each kernel execution.
//#############################################################################
template<
    typename TnumUselessWork>
class SharedMemKernel
{
public:
    //-----------------------------------------------------------------------------
    //! Constructor.
    //-----------------------------------------------------------------------------
    SharedMemKernel(
        std::uint32_t const mult = 2) :
        m_mult(mult)
    {}

    //-----------------------------------------------------------------------------
    //! The kernel.
    //-----------------------------------------------------------------------------
    ALPAKA_NO_HOST_ACC_WARNING
    template<
        typename TAcc>
    ALPAKA_FN_ACC auto operator()(
        TAcc const & acc,
        std::uint32_t * const puiBlockRetVals,
        std::uint32_t const mult2) const
    -> void
    {
        static_assert(
            alpaka::dim::Dim<TAcc>::value == 1,
            "The SharedMemKernel expects 1-dimensional indices!");

        // The number of threads in this block.
        std::size_t const blockThreadCount(alpaka::workdiv::getWorkDiv<alpaka::Block, alpaka::Threads>(acc)[0u]);

        // Get the extern allocated shared memory.
        std::uint32_t * const pBlockShared(acc.template getBlockSharedExternMem<std::uint32_t>());

        // Get some shared memory (allocate a second buffer directly afterwards to check for some synchronization bugs).
        //std::uint32_t * const pBlockShared1(alpaka::block::shared::allocArr<std::uint32_t, TnumUselessWork::value,__COUNTER__>());
        //std::uint32_t * const pBlockShared2(alpaka::block::shared::allocArr<std::uint32_t, TnumUselessWork::value,__COUNTER__>());

        // Calculate linearized index of the thread in the block.
        std::size_t const blockThreadIdx1d(alpaka::idx::getIdx<alpaka::Block, alpaka::Threads>(acc)[0u]);

        // Fill the shared block with the thread ids [1+X, 2+X, 3+X, ..., #Threads+X].
        std::uint32_t iSum1(static_cast<std::uint32_t>(blockThreadIdx1d+1));
        for(std::uint32_t i(0); i<TnumUselessWork::value; ++i)
        {
            iSum1 += i;
        }
        pBlockShared[blockThreadIdx1d] = iSum1;

        // Synchronize all threads because now we are writing to the memory again but inverse.
        alpaka::block::sync::syncBlockThreads(acc);

        // Do something useless.
        std::uint32_t iSum2(static_cast<std::uint32_t>(blockThreadIdx1d));
        for(std::uint32_t i(0); i<TnumUselessWork::value; ++i)
        {
            iSum2 -= i;
        }
        // Add the inverse so that every cell is filled with [#Threads, #Threads, ..., #Threads].
        pBlockShared[(blockThreadCount-1)-blockThreadIdx1d] += iSum2;

        // Synchronize all threads again.
        alpaka::block::sync::syncBlockThreads(acc);

        // Now add up all the cells atomically and write the result to cell 0 of the shared memory.
        if(blockThreadIdx1d > 0)
        {
            alpaka::atomic::atomicOp<alpaka::atomic::op::Add>(acc, &pBlockShared[0], pBlockShared[blockThreadIdx1d]);
        }

        alpaka::block::sync::syncBlockThreads(acc);

        // Only master writes result to global memory.
        if(blockThreadIdx1d==0)
        {
            // Calculate linearized block id.
            std::size_t const blockIdx(alpaka::idx::getIdx<alpaka::Grid, alpaka::Blocks>(acc)[0u]);

            puiBlockRetVals[blockIdx] = pBlockShared[0] * m_mult * mult2;
        }
    }

public:
    std::uint32_t const m_mult;
};

namespace alpaka
{
    namespace kernel
    {
        namespace traits
        {
            //#############################################################################
            //! The trait for getting the size of the block shared extern memory for a kernel.
            //#############################################################################
            template<
                typename TnumUselessWork,
                typename TAcc>
            struct BlockSharedExternMemSizeBytes<
                SharedMemKernel<TnumUselessWork>,
                TAcc>
            {
                //-----------------------------------------------------------------------------
                //! \return The size of the shared memory allocated for a block.
                //-----------------------------------------------------------------------------
                template<
                    typename TVec,
                    typename... TArgs>
                ALPAKA_FN_HOST static auto getBlockSharedExternMemSizeBytes(
                    TVec const & blockElemExtent,
                    TArgs && ...)
                -> std::uint32_t
                {
                    return blockElemExtent.prod() * sizeof(std::uint32_t);
                }
            };
        }
    }
}

//#############################################################################
//! Profiles the example kernel and checks the result.
//#############################################################################
template<
    typename TnumUselessWork>
struct SharedMemTester
{
    template<
        typename TAcc,
        typename TSize,
        typename TVal>
    auto operator()(
        TSize const numElements,
        TVal const mult2)
    -> void
    {
        std::cout << std::endl;
        std::cout << "################################################################################" << std::endl;

        // Create the kernel function object.
        SharedMemKernel<TnumUselessWork> kernel(42);

        // Select a device to execute on.
        alpaka::dev::Dev<TAcc> devAcc(
            alpaka::dev::DevMan<TAcc>::getDevByIdx(0));

        // Get a stream on this device.
        alpaka::integ::Stream<alpaka::dev::Dev<TAcc>> stream(devAcc);

        // Set the grid blocks extent.
        alpaka::workdiv::WorkDivMembers<alpaka::dim::DimInt<1u>, TSize> const workDiv(
            alpaka::workdiv::getValidWorkDiv<TAcc>(
                devAcc,
                numElements,
                static_cast<TSize>(1u),
                false,
                alpaka::workdiv::GridBlockExtentSubDivRestrictions::Unrestricted));

        std::cout
            << "SharedMemTester("
            << " accelerator: " << alpaka::acc::getAccName<TAcc>()
            << ", kernel: " << typeid(kernel).name()
            << ", workDiv: " << workDiv
            << ")" << std::endl;

        TSize const gridBlocksCount(
            alpaka::workdiv::getWorkDiv<alpaka::Grid, alpaka::Blocks>(workDiv)[0u]);
        TSize const blockThreadCount(
            alpaka::workdiv::getWorkDiv<alpaka::Block, alpaka::Threads>(workDiv)[0u]);

        // An array for the return values calculated by the blocks.
        std::vector<TVal> blockRetVals(gridBlocksCount, static_cast<TVal>(0));

        // Allocate accelerator buffers and copy.
        TSize const resultElemCount(gridBlocksCount);
        auto blockRetValsAcc(alpaka::mem::buf::alloc<TVal, TSize>(devAcc, resultElemCount));
        alpaka::mem::view::copy(stream, blockRetValsAcc, blockRetVals, resultElemCount);

        // Create the executor task.
        auto const exec(alpaka::exec::create<TAcc>(
            workDiv,
            kernel,
            alpaka::mem::view::getPtrNative(blockRetValsAcc),
            mult2));

        // Profile the kernel execution.
        std::cout << "Execution time: "
            << alpaka::integ::measureKernelRunTimeMs(
                stream,
                exec)
            << " ms"
            << std::endl;

        // Copy back the result.
        alpaka::mem::view::copy(stream, blockRetVals, blockRetValsAcc, resultElemCount);

        // Wait for the stream to finish the memory operation.
        alpaka::wait::wait(stream);

        // Assert that the results are correct.
        TVal const correctResult(
            static_cast<TVal>(blockThreadCount*blockThreadCount)
            * kernel.m_mult
            * mult2);

        bool resultCorrect(true);
        for(std::size_t i(0); i<gridBlocksCount; ++i)
        {
            if(blockRetVals[i] != correctResult)
            {
                std::cout << "blockRetVals[" << i << "] == " << blockRetVals[i] << " != " << correctResult << std::endl;
                resultCorrect = false;
            }
        }

        if(resultCorrect)
        {
            std::cout << "Execution results correct!" << std::endl;
        }

        std::cout << "################################################################################" << std::endl;

        allResultsCorrect = allResultsCorrect && resultCorrect;
    }

public:
    bool allResultsCorrect = true;
};

//-----------------------------------------------------------------------------
//! Program entry point.
//-----------------------------------------------------------------------------
auto main()
-> int
{
    try
    {
        std::cout << std::endl;
        std::cout << "################################################################################" << std::endl;
        std::cout << "                            alpaka sharedMem test                               " << std::endl;
        std::cout << "################################################################################" << std::endl;
        std::cout << std::endl;

        // Logs the enabled accelerators.
        alpaka::integ::accs::writeEnabledAccs<alpaka::dim::DimInt<1u>, std::uint32_t>(std::cout);

        std::cout << std::endl;

        using TnumUselessWork = std::integral_constant<std::size_t, 100u>;
        std::uint32_t const mult2(5u);

        SharedMemTester<TnumUselessWork> sharedMemTester;

        // Execute the kernel on all enabled accelerators.
        alpaka::core::forEachType<
            alpaka::integ::accs::EnabledAccs<alpaka::dim::DimInt<1u>, std::uint32_t>>(
                sharedMemTester,
                static_cast<std::uint32_t>(512u),
                mult2);

        return sharedMemTester.allResultsCorrect ? EXIT_SUCCESS : EXIT_FAILURE;
    }
    catch(std::exception const & e)
    {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch(...)
    {
        std::cerr << "Unknown Exception" << std::endl;
        return EXIT_FAILURE;
    }
}
<|endoftext|>


<commit_before>#include "SoundManager.hpp"
#include "ResourceManager.hpp"
#include <svc/Timer.hpp>
#include <svc/ServiceLocator.hpp>
#include <boost/bind.hpp>

SoundManager::SoundManager()
{
    ServiceLocator::timer().callEvery(
        sf::seconds(10), boost::bind(&SoundManager::tidy, this));
}

SoundManager::~SoundManager()
{
}

SoundManager::FadedMusic::FadedMusic(
	VFileMusic& music, float target, sf::Time fadeDuration):
	target(target),
	music(&music),
	increment(target - music.getVolume() / fadeDuration.asSeconds())
{
	music.setVolume(100 - target);
}

SoundManager::FadedMusic& SoundManager::FadedMusic::operator= (FadedMusic&& rhs)
{
	target = rhs.target;
	increment = rhs.increment;
	music = std::move(rhs.music);
	return *this;
}

bool SoundManager::FadedMusic::fade()
{
	float const newVolume = music->getVolume() + increment;
	music->setVolume(newVolume);
    if (increment < 0 ? newVolume <= target : newVolume >= target) {
        music->setVolume(target);
		return true;
    }
	return false;
}

void SoundManager::playSound(std::string const& name)
{

	playSound(resMng<sf::SoundBuffer>().keepLoaded(name));
}

void SoundManager::playSound(ResourceTraits<sf::SoundBuffer>::Ptr const& buf)
{
	std::unique_ptr<AutoSound> snd(new AutoSound);
	snd->setResource(buf);
	snd->play();
	playSound(*snd.release());
}

void SoundManager::playSound(AutoSound& sound)
{
	m_playingSounds.push_back(&sound);
}

void  SoundManager::setBackgroundMusic(std::string const& name, sf::Time fadeDuration)
{
	std::unique_ptr<VFileMusic> music(new VFileMusic);
    music->stream.open(name);
    music->openFromStream(music->stream);
	music->play();
    setBackgroundMusic(*music.release(), fadeDuration);
}

void SoundManager::setBackgroundMusic(VFileMusic& music, sf::Time fadeDuration)
{
    m_previousMusic = FadedMusic(*m_currentMusic.music.release(), 0, fadeDuration);
	m_currentMusic = FadedMusic(music, 100, fadeDuration);
}

void SoundManager::tidy()
{
	m_playingSounds.erase(
		std::remove_if(m_playingSounds.begin(), m_playingSounds.end(),
			[](AutoSound& snd) { return snd.getStatus() != sf::Sound::Playing; }),
		m_playingSounds.end());
}

void SoundManager::fade()
{
    if (!m_previousMusic.music)
        return;

    m_previousMusic.fade();
	if (m_currentMusic.fade())
        m_previousMusic.music.reset();
}
<commit_msg>SoundManager: Don't connect to timer (done by main()).<commit_after>#include "SoundManager.hpp"
#include "ResourceManager.hpp"
#include <boost/bind.hpp>

SoundManager::SoundManager()
{
}

SoundManager::~SoundManager()
{
}

SoundManager::FadedMusic::FadedMusic(
	VFileMusic& music, float target, sf::Time fadeDuration):
	target(target),
	music(&music),
	increment(target - music.getVolume() / fadeDuration.asSeconds())
{
	music.setVolume(100 - target);
}

SoundManager::FadedMusic& SoundManager::FadedMusic::operator= (FadedMusic&& rhs)
{
	target = rhs.target;
	increment = rhs.increment;
	music = std::move(rhs.music);
	return *this;
}

bool SoundManager::FadedMusic::fade()
{
	float const newVolume = music->getVolume() + increment;
	music->setVolume(newVolume);
    if (increment < 0 ? newVolume <= target : newVolume >= target) {
        music->setVolume(target);
		return true;
    }
	return false;
}

void SoundManager::playSound(std::string const& name)
{

	playSound(resMng<sf::SoundBuffer>().keepLoaded(name));
}

void SoundManager::playSound(ResourceTraits<sf::SoundBuffer>::Ptr const& buf)
{
	std::unique_ptr<AutoSound> snd(new AutoSound);
	snd->setResource(buf);
	snd->play();
	playSound(*snd.release());
}

void SoundManager::playSound(AutoSound& sound)
{
	m_playingSounds.push_back(&sound);
}

void  SoundManager::setBackgroundMusic(std::string const& name, sf::Time fadeDuration)
{
	std::unique_ptr<VFileMusic> music(new VFileMusic);
    music->stream.open(name);
    music->openFromStream(music->stream);
	music->play();
    setBackgroundMusic(*music.release(), fadeDuration);
}

void SoundManager::setBackgroundMusic(VFileMusic& music, sf::Time fadeDuration)
{
    m_previousMusic = FadedMusic(*m_currentMusic.music.release(), 0, fadeDuration);
	m_currentMusic = FadedMusic(music, 100, fadeDuration);
}

void SoundManager::tidy()
{
	m_playingSounds.erase(
		std::remove_if(m_playingSounds.begin(), m_playingSounds.end(),
			[](AutoSound& snd) { return snd.getStatus() != sf::Sound::Playing; }),
		m_playingSounds.end());
}

void SoundManager::fade()
{
    if (!m_previousMusic.music)
        return;

    m_previousMusic.fade();
	if (m_currentMusic.fade())
        m_previousMusic.music.reset();
}
<|endoftext|>


<commit_before>#include <stack>
#include <string>
#include <string.h>

using namespace std;

bool IsOp(const char ch)
{
	return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
bool IsEqualOrGreat(char ch1, char ch2)
{
	if(ch1 == '+' || ch1 == '-')
	{
		if(ch2 == '+' || ch2 == '-')
		{
			return true;
		}
		return false;
	}
	return true;
}

int main()
{
	const int kInputSize = 1024;
	char input[kInputSize];
	while(scanf("%s", input) == 1)
	{
		stack<char> op;
		stack<string> prefix;
		int input_size = static_cast<int>(strlen(input));
		for(int index = input_size - 1; index >= 0; )
		{
			if(isdigit(input[index]))
			{
				int begin_index = index - 1;
				for(; begin_index >= 0 && isdigit(input[begin_index]); --begin_index);
				if(begin_index < 0)
				{
					prefix.push(string(input, index + 1));
					break;
				}
				else if(begin_index == 0)
				{
					if(input[0] != '-')
					{
						prefix.push(string(input + 1, index));
						index = 0;
					}
					else
					{
						prefix.push(string(input, index + 1));
						break;
					}
				}
				else
				{
					if(IsOp(input[begin_index - 1]) && input[begin_index] == '-')
					{
						prefix.push(string(input + begin_index, index - begin_index + 1));
						index = begin_index - 1;
					}
					else
					{
						prefix.push(string(input + begin_index + 1, index - begin_index));
						index = begin_index;
					}
				}
			}
			else if(IsOp(input[index]))
			{
				if(op.empty() == true || op.top() == ')' || IsEqualOrGreat(input[index], op.top()))
				{
					op.push(input[index]);
					--index;
				}
				else
				{
					prefix.push(string(&op.top(), 1));
					op.pop();
					continue;
				}
			}
			else
			{
				if(input[index] == ')')
				{
					op.push(input[index]);
				}
				else
				{
					while(op.top() != ')')
					{
						prefix.push(string(&op.top(), 1));
						op.pop();
					}
					op.pop();
				}
				--index;
			}
		}
		while(op.empty() == false)
		{
			prefix.push(string(&op.top(), 1));
			op.pop();
		}
		while(prefix.empty() == false)
		{
			printf("%s", prefix.top().data());
			prefix.pop();
		}
		printf("\n");
	}
}
<commit_msg>docs: encapsaulate function<commit_after>#include <stack>
#include <string>
#include <string.h>

using namespace std;

bool IsOp(const char ch)
{
	return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
bool IsOp(const string &str)
{
	return str == "+" || str == "-" || str == "*" || str == "/";
}
bool IsEqualOrGreat(char ch1, char ch2)
{
	if(ch1 == '+' || ch1 == '-')
	{
		if(ch2 == '+' || ch2 == '-')
		{
			return true;
		}
		return false;
	}
	return true;
}

void CalculatePrefix(stack<string> &prefix)
{
	stack<int> cal;
	while(prefix.empty() == false)
	{
		string str = prefix.top();
		prefix.pop();
		if(IsOp(str) == false)
		{
			cal.push(atoi(str.data()));
		}
		else
		{
			int lhs = cal.top();
			cal.pop();
			int rhs = cal.top();
			cal.pop();
			switch(*str.data())
			{
			case '+':
				lhs += rhs;
				break;
			case '-':
				lhs -= rhs;
				break;
			case '*':
				lhs *= rhs;
				break;
			case '/':
				lhs /= rhs;
			}
			cal.push(lhs);
		}
	}
	printf("\nResult is: %d\n", cal.top());
}
void InfixToPrefix(const char *infix)
{
	stack<char> op;
	stack<string> prefix;
	int input_size = static_cast<int>(strlen(infix));
	for(int index = input_size - 1; index >= 0; )
	{
		if(isdigit(infix[index]))
		{
			int begin_index = index - 1;
			for(; begin_index >= 0 && isdigit(infix[begin_index]); --begin_index);
			if(begin_index < 0)
			{
				prefix.push(string(infix, index + 1));
				break;
			}
			else if(begin_index == 0)
			{
				if(infix[0] != '-')
				{
					prefix.push(string(infix + 1, index));
					index = 0;
				}
				else
				{
					prefix.push(string(infix, index + 1));
					break;
				}
			}
			else
			{
				if(IsOp(infix[begin_index - 1]) && infix[begin_index] == '-')
				{
					prefix.push(string(infix + begin_index, index - begin_index + 1));
					index = begin_index - 1;
				}
				else
				{
					prefix.push(string(infix + begin_index + 1, index - begin_index));
					index = begin_index;
				}
			}
		}
		else if(IsOp(infix[index]))
		{
			if(op.empty() == true || op.top() == ')' || IsEqualOrGreat(infix[index], op.top()))
			{
				op.push(infix[index]);
				--index;
			}
			else
			{
				prefix.push(string(&op.top(), 1));
				op.pop();
				continue;
			}
		}
		else
		{
			if(infix[index] == ')')
			{
				op.push(infix[index]);
			}
			else
			{
				while(op.top() != ')')
				{
					prefix.push(string(&op.top(), 1));
					op.pop();
				}
				op.pop();
			}
			--index;
		}
	}
	while(op.empty() == false)
	{
		prefix.push(string(&op.top(), 1));
		op.pop();
	}
	stack<string> temp;
	printf("Prefix is: ");
	while(prefix.empty() == false)
	{
		temp.push(prefix.top());
		printf("%s,", prefix.top().data());
		prefix.pop();
	}
	CalculatePrefix(temp);
}

int main()
{
	const int kInputSize = 1024;
	char infix[kInputSize];
	while(scanf("%s", infix) == 1)
	{
		InfixToPrefix(infix);
	}
}
/*
-23+((4+56)*78)+-5+6*-78+123
**********************************
Prefix is: +,+,+,+,-23,*,+,4,56,78,-5,*,6,-78,123,
Result is: 4307
*/
<|endoftext|>


<commit_before>/*
 * writer.cpp
 *
 */

#include "writer.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include "timer_factory.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>

#include "cache.h"
#include "csv.h"
#include "grib.h"
#include "neons.h"
#include "querydata.h"
#include "radon.h"

using namespace himan::plugin;

writer::writer() : itsWriteOptions()
{
	itsLogger = std::unique_ptr<logger>(logger_factory::Instance()->GetLog("writer"));
}

bool writer::CreateFile(info& theInfo, std::shared_ptr<const plugin_configuration> conf, std::string& theOutputFile)
{
	namespace fs = boost::filesystem;

	itsWriteOptions.configuration = conf;

	if (theOutputFile.empty())
	{
		theOutputFile = util::MakeFileName(itsWriteOptions.configuration->FileWriteOption(), theInfo);
	}

	fs::path pathname(theOutputFile);

	if (!pathname.parent_path().empty() && !fs::is_directory(pathname.parent_path()))
	{
		fs::create_directories(pathname.parent_path());
	}

	switch (itsWriteOptions.configuration->OutputFileType())
	{
		case kGRIB:
		case kGRIB1:
		case kGRIB2:
		{
			auto theGribWriter = GET_PLUGIN(grib);

			theOutputFile += ".grib";

			if (itsWriteOptions.configuration->OutputFileType() == kGRIB2)
			{
				theOutputFile += "2";
			}

			if (itsWriteOptions.configuration->FileCompression() == kGZIP)
			{
				theOutputFile += ".gz";
			}
			else if (itsWriteOptions.configuration->FileCompression() == kBZIP2)
			{
				theOutputFile += ".bz2";
			}

			theGribWriter->WriteOptions(itsWriteOptions);
			return
			    theGribWriter->ToFile(theInfo, theOutputFile,
			                          (itsWriteOptions.configuration->FileWriteOption() == kSingleFile) ? true : false);

			break;
		}
		case kQueryData:
		{
			if (theInfo.Grid()->Type() == kReducedGaussian)
			{
				itsLogger->Error("Reduced gaussian grid cannot be written to querydata");
				return false;
			}

			auto theWriter = GET_PLUGIN(querydata);
			theWriter->WriteOptions(itsWriteOptions);

			theOutputFile += ".fqd";

			return theWriter->ToFile(theInfo, theOutputFile);

			break;
		}
		case kNetCDF:
			break;

		case kCSV:
		{
			auto theWriter = GET_PLUGIN(csv);
			theWriter->WriteOptions(itsWriteOptions);

			theOutputFile += ".csv";

			return theWriter->ToFile(theInfo, theOutputFile);
			break;
		}
		// Must have this or compiler complains
		default:
			throw std::runtime_error(ClassName() + ": Invalid file type: " +
			                         HPFileTypeToString.at(itsWriteOptions.configuration->OutputFileType()));
			break;
	}

	return false;
}

bool writer::ToFile(info& theInfo, std::shared_ptr<const plugin_configuration> conf, const std::string& theOriginalOutputFile)
{
	std::unique_ptr<himan::timer> t = std::unique_ptr<himan::timer>(timer_factory::Instance()->GetTimer());

	if (conf->StatisticsEnabled())
	{
		t->Start();
	}

	bool ret = true;
	std::string theOutputFile = theOriginalOutputFile; // This is modified

	if (conf->FileWriteOption() != kCacheOnly)
	{

		// When writing previ to database, no file is needed. In all other cases we have to create
		// a file.

		if (theInfo.Producer().Class() == kGridClass ||
		    (theInfo.Producer().Class() == kPreviClass && conf->FileWriteOption() != kDatabase))
		{
			ret = CreateFile(theInfo, conf, theOutputFile);
		}

		if (ret && conf->FileWriteOption() == kDatabase)
		{
			HPDatabaseType dbtype = conf->DatabaseType();

			if (dbtype == kNeons || dbtype == kNeonsAndRadon)
			{
				auto n = GET_PLUGIN(neons);

				ret = n->Save(theInfo, theOutputFile);

				if (!ret)
				{
					itsLogger->Warning("Saving file information to neons failed");
				}
			}

			if (dbtype == kRadon || dbtype == kNeonsAndRadon)
			{
				auto r = GET_PLUGIN(radon);

				// Try to save file information to radon
				try
				{
					ret = r->Save(theInfo, theOutputFile);

					if (!ret)
					{
						itsLogger->Error("Writing to radon failed");
					}
				}
				catch (const std::exception& e)
				{
					itsLogger->Error("Writing to radon failed: " + std::string(e.what()));
				}
				catch (...)
				{
					itsLogger->Error("Writing to radon failed: general exception");
				}
			}
		}
	}

	if (conf->UseCache())
	{
		std::shared_ptr<cache> c = GET_PLUGIN(cache);

		c->Insert(theInfo);
	}

	if (conf->StatisticsEnabled())
	{
		t->Stop();

		conf->Statistics()->AddToWritingTime(t->GetTime());
	}

	return ret;
}

write_options writer::WriteOptions() const { return itsWriteOptions; }
void writer::WriteOptions(const write_options& theWriteOptions) { itsWriteOptions = theWriteOptions; }
<commit_msg>Data that is not written to file is pinned to cache.<commit_after>/*
 * writer.cpp
 *
 */

#include "writer.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include "timer_factory.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>

#include "cache.h"
#include "csv.h"
#include "grib.h"
#include "neons.h"
#include "querydata.h"
#include "radon.h"

using namespace himan::plugin;

writer::writer() : itsWriteOptions()
{
	itsLogger = std::unique_ptr<logger>(logger_factory::Instance()->GetLog("writer"));
}

bool writer::CreateFile(info& theInfo, std::shared_ptr<const plugin_configuration> conf, std::string& theOutputFile)
{
	namespace fs = boost::filesystem;

	itsWriteOptions.configuration = conf;

	if (theOutputFile.empty())
	{
		theOutputFile = util::MakeFileName(itsWriteOptions.configuration->FileWriteOption(), theInfo);
	}

	fs::path pathname(theOutputFile);

	if (!pathname.parent_path().empty() && !fs::is_directory(pathname.parent_path()))
	{
		fs::create_directories(pathname.parent_path());
	}

	switch (itsWriteOptions.configuration->OutputFileType())
	{
		case kGRIB:
		case kGRIB1:
		case kGRIB2:
		{
			auto theGribWriter = GET_PLUGIN(grib);

			theOutputFile += ".grib";

			if (itsWriteOptions.configuration->OutputFileType() == kGRIB2)
			{
				theOutputFile += "2";
			}

			if (itsWriteOptions.configuration->FileCompression() == kGZIP)
			{
				theOutputFile += ".gz";
			}
			else if (itsWriteOptions.configuration->FileCompression() == kBZIP2)
			{
				theOutputFile += ".bz2";
			}

			theGribWriter->WriteOptions(itsWriteOptions);
			return theGribWriter->ToFile(
			    theInfo, theOutputFile,
			    (itsWriteOptions.configuration->FileWriteOption() == kSingleFile) ? true : false);

			break;
		}
		case kQueryData:
		{
			if (theInfo.Grid()->Type() == kReducedGaussian)
			{
				itsLogger->Error("Reduced gaussian grid cannot be written to querydata");
				return false;
			}

			auto theWriter = GET_PLUGIN(querydata);
			theWriter->WriteOptions(itsWriteOptions);

			theOutputFile += ".fqd";

			return theWriter->ToFile(theInfo, theOutputFile);

			break;
		}
		case kNetCDF:
			break;

		case kCSV:
		{
			auto theWriter = GET_PLUGIN(csv);
			theWriter->WriteOptions(itsWriteOptions);

			theOutputFile += ".csv";

			return theWriter->ToFile(theInfo, theOutputFile);
			break;
		}
		// Must have this or compiler complains
		default:
			throw std::runtime_error(ClassName() + ": Invalid file type: " +
			                         HPFileTypeToString.at(itsWriteOptions.configuration->OutputFileType()));
			break;
	}

	return false;
}

bool writer::ToFile(info& theInfo, std::shared_ptr<const plugin_configuration> conf,
                    const std::string& theOriginalOutputFile)
{
	std::unique_ptr<himan::timer> t = std::unique_ptr<himan::timer>(timer_factory::Instance()->GetTimer());

	if (conf->StatisticsEnabled())
	{
		t->Start();
	}

	bool ret = true;
	std::string theOutputFile = theOriginalOutputFile;  // This is modified

	if (conf->FileWriteOption() != kCacheOnly)
	{
		// When writing previ to database, no file is needed. In all other cases we have to create
		// a file.

		if (theInfo.Producer().Class() == kGridClass ||
		    (theInfo.Producer().Class() == kPreviClass && conf->FileWriteOption() != kDatabase))
		{
			ret = CreateFile(theInfo, conf, theOutputFile);
		}

		if (ret && conf->FileWriteOption() == kDatabase)
		{
			HPDatabaseType dbtype = conf->DatabaseType();

			if (dbtype == kNeons || dbtype == kNeonsAndRadon)
			{
				auto n = GET_PLUGIN(neons);

				ret = n->Save(theInfo, theOutputFile);

				if (!ret)
				{
					itsLogger->Warning("Saving file information to neons failed");
				}
			}

			if (dbtype == kRadon || dbtype == kNeonsAndRadon)
			{
				auto r = GET_PLUGIN(radon);

				// Try to save file information to radon
				try
				{
					ret = r->Save(theInfo, theOutputFile);

					if (!ret)
					{
						itsLogger->Error("Writing to radon failed");
					}
				}
				catch (const std::exception& e)
				{
					itsLogger->Error("Writing to radon failed: " + std::string(e.what()));
				}
				catch (...)
				{
					itsLogger->Error("Writing to radon failed: general exception");
				}
			}
		}
	}

	if (conf->UseCache())
	{
		std::shared_ptr<cache> c = GET_PLUGIN(cache);

		// Pin those items that are not written to file at all
		// so they can't be removed from cache if cache size is limited
		c->Insert(theInfo, (conf->FileWriteOption() == kCacheOnly));
	}

	if (conf->StatisticsEnabled())
	{
		t->Stop();

		conf->Statistics()->AddToWritingTime(t->GetTime());
	}

	return ret;
}

write_options writer::WriteOptions() const { return itsWriteOptions; }
void writer::WriteOptions(const write_options& theWriteOptions) { itsWriteOptions = theWriteOptions; }
<|endoftext|>


<commit_before>#include "svgInterpolation.h"

//--------------------------------------------------------------
void svgInterpolation::setup(){

  selectedId = -1;

  ofDirectory dir;

  shapeSize = 500;

  ofLogNotice("svgInterpolation") << "load SVG from formes_interpol";
  dir.listDir("formes_interpol/");
  dir.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order
  ofLogNotice("svgInterpolation") << "found " << (int)dir.size() << " images to load.";

  for(int i = 0; i < (int)dir.size(); i++){
    // if ( i == 0 ) cout << "load : " << dir.getPath(i) << endl;
    ofxSVG svg;
    svg.load(dir.getPath(i));
    ofLogNotice("svgInterpolation") << "loading : " << dir.getPath(i);
    ofPolyline myLine;
    ofVec2f ptMin = ofVec2f(1000.,1000.), ptMax = ofVec2f(-1000.,-1000.);

    ofLogVerbose("svgInterpolation") << "shape " << i << " has " << svg.getNumPath() << " paths";

    for (int j = 0; j < svg.getNumPath(); j++){
      ofPath p = svg.getPathAt(j);
      // svg defaults to non zero winding which doesn't look so good as contours
      p.setPolyWindingMode(OF_POLY_WINDING_ODD);
      vector<ofPolyline>& lines = const_cast<vector<ofPolyline>&>(p.getOutline());

      for(int k=0;k<(int)lines.size();k++){
        ofPolyline line=lines[k];
        for(int n=0;n<line.size();n++){

          ofVec3f pt = line[n];
          pt/=40;
          pt-=1.;
          ptMin.x = std::min(pt.x, ptMin.x);
          ptMin.y = std::min(pt.y, ptMin.y);
          ptMax.x = std::max(pt.x, ptMax.x);
          ptMax.y = std::max(pt.y, ptMax.y);

          myLine.addVertex(pt);
        }
      }
    }
    // myLine.close();
    lines.push_back(myLine.getResampledByCount(shapeSize));
    ofLogVerbose("svgInterpolation") << "min : " << ptMin.x << " " << ptMin.y;
    ofLogVerbose("svgInterpolation") << "max : " << ptMax.x << " " << ptMax.y;
  }

  ofLogNotice("svgInterpolation") << "load SVG from formes_statiques" << endl;
  dir.listDir("formes_statiques/");
  dir.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order

  for(int i = 0; i < (int)dir.size(); i++){
    ofxSVG svg;
    svg.load(dir.getPath(i));
    ofLogNotice("svgInterpolation") << "load : " << dir.getPath(i) << "with " << svg.getNumPath() << " paths" << endl;
    ofPolyline myLine;
    ofVec2f ptMin = ofVec2f(1000.,1000.), ptMax = ofVec2f(-1000.,-1000.);

    for (int i = 0; i < svg.getNumPath(); i++){
      ofPath p = svg.getPathAt(i);
      // svg defaults to non zero winding which doesn't look so good as contours
      p.setPolyWindingMode(OF_POLY_WINDING_ODD);
      vector<ofPolyline>& lines = const_cast<vector<ofPolyline>&>(p.getOutline());
      ofLogNotice("svgInterpolation") << "path " << i << " has " << lines.size() << " points " << endl;
      for(int k=0;k<(int)lines.size();k++){
        ofPolyline line=lines[k];
        for(int n=0;n<line.size();n++){

          ofVec3f pt = line[n];
          ptMin.x = std::min(pt.x, ptMin.x);
          ptMin.y = std::min(pt.y, ptMin.y);
          ptMax.x = std::max(pt.x, ptMax.x);
          ptMax.y = std::max(pt.y, ptMax.y);

          myLine.addVertex(pt);
        }
      }
      ofLogVerbose("svgInterpolation") << "normalize shape" << endl;
      ofVec2f offset, amplitude;
      float scale;
      offset = (ptMin + ptMax) /2.;
      amplitude = (ptMax - ptMin)/2;
      scale = max(amplitude.x,amplitude.y);
      for (auto & pt : myLine){
      	pt-=offset;
      	pt/=scale;
      	ofLogVerbose("svgInterpolation") << pt.x << ";" << pt.y << endl;
      }
    // myLine.close();

    static_lines.push_back(myLine.getResampledByCount(shapeSize));
    }
  }
}

//--------------------------------------------------------------
bool svgInterpolation::updateBool(){
  return multiInterpolation() || draw_static();
}

//--------------------------------------------------------------
void svgInterpolation::draw(){

  ofDrawBitmapString(ofToString(ofGetFrameRate()),20,20);
  ofPushMatrix();
  ofTranslate(ofGetWidth() / 2., ofGetHeight() / 2.);
  ofScale(ofGetHeight() / 3., ofGetHeight() / 3., 1.);
  ofNoFill();

  ofBeginShape();
  for (int j = 0; j < interpolatedLine.size(); j++){
    ofVertex(interpolatedLine[j]);
  }
  if ( interpolatedLine.size() ) ofVertex(interpolatedLine[0]);
  ofEndShape();

  ofPopMatrix();
}

bool svgInterpolation::multiInterpolation(){

  if ( !dirtyFlag ) return false;

  interpolatedLine.clear();

/*
  ofLogNotice("svgInterpolation") << "nombre de formes chargées : " << lines.size() << endl;
  ofLogNotice("svgInterpolation") << "taille de coeff : " << coeff.size() << endl;
*/

  for (int i = 0; i < shapeSize; i++){
    ofVec3f pt;
    for (int j = 0; j < min(lines.size(), coeff.size()); j++){
      pt += coeff[j] * lines[j][i]; // [0] assumes that there is only one line on each ofPolyLine
    }
    interpolatedLine.addVertex(pt);
  }

  ofVec3f ptMin(999999. ,999999.);
  ofVec3f ptMax(-999999.,-999999.);
  // get the bounding box of the shape
  for ( ofVec3f pt : interpolatedLine ){
    ptMin.x = min(pt.x,ptMin.x);
    ptMin.y = min(pt.y,ptMin.y);
    ptMax.x = max(pt.x,ptMax.x);
    ptMax.y = max(pt.y,ptMax.y);
  }
  ofLogVerbose("svgInterpolation") << "ptMin : " << ptMin.x << " \t " << ptMin.y << endl;
  ofLogVerbose("svgInterpolation") << "ptMax : " << ptMax.x << " \t " << ptMax.y << endl;

  ofVec3f offset, diff;
  float scale;
  // scale and translate shape to center on (0.0;0.0)))))))
  offset = (ptMax + ptMin)/2.;
  diff = ptMax - ptMin;
  scale = max(diff.x,diff.y) / 2.;

  ofLogVerbose("svgInterpolation") << "scale : " << scale << endl;
  ofLogVerbose("svgInterpolation") << "offset : " << offset << endl;
  ofLogVerbose("svgInterpolation") << "normalized line : " << endl;
  int i(0);
  for ( ofVec3f& pt : interpolatedLine ){
    pt -= offset;
    pt /= scale;
    ofLogVerbose("svgInterpolation") << i++ << " : " << pt.x << " \t " << pt.y << endl;
  }

  // interpolatedLine = interpolatedLine.getResampledByCount(shapeSize);
  ofLogVerbose("svgInterpolation") << "interpolatedLine.size() : " << interpolatedLine.size() << endl;

  dirtyFlag=false;

  return true;
}

bool svgInterpolation::draw_static(){
  if ( selectedId < 0 ) return false;
  if ( selectedId > (static_lines.size() - 1)) return false;

  interpolatedLine.clear();
  interpolatedLine = static_lines[selectedId];

  selectedId = -1;
  return true;
}
<commit_msg>change verbosity level<commit_after>#include "svgInterpolation.h"

//--------------------------------------------------------------
void svgInterpolation::setup(){

  selectedId = -1;

  ofDirectory dir;

  shapeSize = 500;

  ofLogNotice("svgInterpolation") << "load SVG from formes_interpol";
  dir.listDir("formes_interpol/");
  dir.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order
  ofLogNotice("svgInterpolation") << "found " << (int)dir.size() << " images to load.";

  for(int i = 0; i < (int)dir.size(); i++){
    // if ( i == 0 ) cout << "load : " << dir.getPath(i) << endl;
    ofxSVG svg;
    svg.load(dir.getPath(i));
    ofLogNotice("svgInterpolation") << "loading : " << dir.getPath(i);
    ofPolyline myLine;
    ofVec2f ptMin = ofVec2f(1000.,1000.), ptMax = ofVec2f(-1000.,-1000.);

    ofLogNotice("svgInterpolation") << "shape " << i << " has " << svg.getNumPath() << " paths";

    for (int j = 0; j < svg.getNumPath(); j++){
      ofPath p = svg.getPathAt(j);
      // svg defaults to non zero winding which doesn't look so good as contours
      p.setPolyWindingMode(OF_POLY_WINDING_ODD);
      vector<ofPolyline>& lines = const_cast<vector<ofPolyline>&>(p.getOutline());

      for(int k=0;k<(int)lines.size();k++){
        ofPolyline line=lines[k];
        for(int n=0;n<line.size();n++){

          ofVec3f pt = line[n];
          pt/=40;
          pt-=1.;
          ptMin.x = std::min(pt.x, ptMin.x);
          ptMin.y = std::min(pt.y, ptMin.y);
          ptMax.x = std::max(pt.x, ptMax.x);
          ptMax.y = std::max(pt.y, ptMax.y);

          myLine.addVertex(pt);
        }
      }
    }
    // myLine.close();
    lines.push_back(myLine.getResampledByCount(shapeSize));
    ofLogVerbose("svgInterpolation") << "min : " << ptMin.x << " " << ptMin.y;
    ofLogVerbose("svgInterpolation") << "max : " << ptMax.x << " " << ptMax.y;
  }

  ofLogNotice("svgInterpolation") << "load SVG from formes_statiques" << endl;
  dir.listDir("formes_statiques/");
  dir.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order

  for(int i = 0; i < (int)dir.size(); i++){
    ofxSVG svg;
    svg.load(dir.getPath(i));
    ofLogNotice("svgInterpolation") << "load : " << dir.getPath(i) << "with " << svg.getNumPath() << " paths" << endl;
    ofPolyline myLine;
    ofVec2f ptMin = ofVec2f(1000.,1000.), ptMax = ofVec2f(-1000.,-1000.);

    for (int i = 0; i < svg.getNumPath(); i++){
      ofPath p = svg.getPathAt(i);
      // svg defaults to non zero winding which doesn't look so good as contours
      p.setPolyWindingMode(OF_POLY_WINDING_ODD);
      vector<ofPolyline>& lines = const_cast<vector<ofPolyline>&>(p.getOutline());
      ofLogNotice("svgInterpolation") << "path " << i << " has " << lines.size() << " points " << endl;
      for(int k=0;k<(int)lines.size();k++){
        ofPolyline line=lines[k];
        for(int n=0;n<line.size();n++){

          ofVec3f pt = line[n];
          ptMin.x = std::min(pt.x, ptMin.x);
          ptMin.y = std::min(pt.y, ptMin.y);
          ptMax.x = std::max(pt.x, ptMax.x);
          ptMax.y = std::max(pt.y, ptMax.y);

          myLine.addVertex(pt);
        }
      }
      ofLogVerbose("svgInterpolation") << "normalize shape" << endl;
      ofVec2f offset, amplitude;
      float scale;
      offset = (ptMin + ptMax) /2.;
      amplitude = (ptMax - ptMin)/2;
      scale = max(amplitude.x,amplitude.y);
      for (auto & pt : myLine){
      	pt-=offset;
      	pt/=scale;
      	ofLogVerbose("svgInterpolation") << pt.x << ";" << pt.y << endl;
      }
    // myLine.close();

    static_lines.push_back(myLine.getResampledByCount(shapeSize));
    }
  }
}

//--------------------------------------------------------------
bool svgInterpolation::updateBool(){
  return multiInterpolation() || draw_static();
}

//--------------------------------------------------------------
void svgInterpolation::draw(){

  ofDrawBitmapString(ofToString(ofGetFrameRate()),20,20);
  ofPushMatrix();
  ofTranslate(ofGetWidth() / 2., ofGetHeight() / 2.);
  ofScale(ofGetHeight() / 3., ofGetHeight() / 3., 1.);
  ofNoFill();

  ofBeginShape();
  for (int j = 0; j < interpolatedLine.size(); j++){
    ofVertex(interpolatedLine[j]);
  }
  if ( interpolatedLine.size() ) ofVertex(interpolatedLine[0]);
  ofEndShape();

  ofPopMatrix();
}

bool svgInterpolation::multiInterpolation(){

  if ( !dirtyFlag ) return false;

  interpolatedLine.clear();

/*
  ofLogNotice("svgInterpolation") << "nombre de formes chargées : " << lines.size() << endl;
  ofLogNotice("svgInterpolation") << "taille de coeff : " << coeff.size() << endl;
*/

  for (int i = 0; i < shapeSize; i++){
    ofVec3f pt;
    for (int j = 0; j < min(lines.size(), coeff.size()); j++){
      pt += coeff[j] * lines[j][i]; // [0] assumes that there is only one line on each ofPolyLine
    }
    interpolatedLine.addVertex(pt);
  }

  ofVec3f ptMin(999999. ,999999.);
  ofVec3f ptMax(-999999.,-999999.);
  // get the bounding box of the shape
  for ( ofVec3f pt : interpolatedLine ){
    ptMin.x = min(pt.x,ptMin.x);
    ptMin.y = min(pt.y,ptMin.y);
    ptMax.x = max(pt.x,ptMax.x);
    ptMax.y = max(pt.y,ptMax.y);
  }
  ofLogVerbose("svgInterpolation") << "ptMin : " << ptMin.x << " \t " << ptMin.y << endl;
  ofLogVerbose("svgInterpolation") << "ptMax : " << ptMax.x << " \t " << ptMax.y << endl;

  ofVec3f offset, diff;
  float scale;
  // scale and translate shape to center on (0.0;0.0)))))))
  offset = (ptMax + ptMin)/2.;
  diff = ptMax - ptMin;
  scale = max(diff.x,diff.y) / 2.;

  ofLogVerbose("svgInterpolation") << "scale : " << scale << endl;
  ofLogVerbose("svgInterpolation") << "offset : " << offset << endl;
  ofLogVerbose("svgInterpolation") << "normalized line : " << endl;
  int i(0);
  for ( ofVec3f& pt : interpolatedLine ){
    pt -= offset;
    pt /= scale;
    ofLogVerbose("svgInterpolation") << i++ << " : " << pt.x << " \t " << pt.y << endl;
  }

  // interpolatedLine = interpolatedLine.getResampledByCount(shapeSize);
  ofLogVerbose("svgInterpolation") << "interpolatedLine.size() : " << interpolatedLine.size() << endl;

  dirtyFlag=false;

  return true;
}

bool svgInterpolation::draw_static(){
  if ( selectedId < 0 ) return false;
  if ( selectedId > (static_lines.size() - 1)) return false;

  interpolatedLine.clear();
  interpolatedLine = static_lines[selectedId];

  selectedId = -1;
  return true;
}
<|endoftext|>


<commit_before><commit_msg>error C2061: syntax error : identifier 'uint64_t'<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *        Caolán McNamara <caolanm@redhat.com> (Red Hat, Inc.)
 * Portions created by the Initial Developer are Copyright (C) 2011 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Caolán McNamara <caolanm@redhat.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <osl/file.hxx>
#include <ucbhelper/configurationkeys.hxx>
#include <ucbhelper/contentbroker.hxx>
#include <vcl/builder.hxx>
#include <vcl/dialog.hxx>
#include <vcl/svapp.hxx>

class UIPreviewApp : public Application
{
public:
    virtual int Main();
};

using namespace com::sun::star;

int UIPreviewApp::Main()
{
    std::vector<rtl::OUString> uifiles;
    for (sal_uInt16 i = 0; i < GetCommandLineParamCount(); ++i)
    {
        rtl::OUString aFileUrl;
        osl::File::getFileURLFromSystemPath(GetCommandLineParam(i), aFileUrl);
        uifiles.push_back(aFileUrl);
    }

    if (uifiles.empty())
    {
        fprintf(stderr, "Usage: ui-previewer file.ui\n");
        return EXIT_FAILURE;
    }

    uno::Reference<uno::XComponentContext> xContext =
        cppu::defaultBootstrap_InitialComponentContext();
    uno::Reference<lang::XMultiComponentFactory> xFactory =
        xContext->getServiceManager();
    uno::Reference<lang::XMultiServiceFactory> xSFactory =
        uno::Reference<lang::XMultiServiceFactory> (xFactory, uno::UNO_QUERY_THROW);
    comphelper::setProcessServiceFactory(xSFactory);

    // Create UCB.
    uno::Sequence< uno::Any > aArgs(2);
    aArgs[ 0 ] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY1_LOCAL));
    aArgs[ 1 ] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY2_OFFICE));
    ::ucbhelper::ContentBroker::initialize(xSFactory, aArgs);

    try
    {
        VclBuilder aBuilder(NULL, uifiles[0]);
        Window *pWindow = aBuilder.get_widget_root();
        Dialog *pDialog = dynamic_cast<Dialog*>(pWindow);
        if (pDialog)
        {
            pDialog->SetText(rtl::OUString("LibreOffice ui-previewer"));
            pDialog->SetStyle(pDialog->GetStyle()|WB_CLOSEABLE);
            pDialog->Execute();
        }
        else
        {
            fprintf(stderr, "to-do: no toplevel dialog, make one\n");
        }
    }
    catch (const uno::Exception &e)
    {
        fprintf(stderr, "fatal error: %s\n", rtl::OUStringToOString(e.Message, osl_getThreadTextEncoding()).getStr());
    }
    return false;

    ::ucbhelper::ContentBroker::deinitialize();

    return EXIT_SUCCESS;
}

UIPreviewApp aApp;

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>allow previewing trees without toplevel windows<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *        Caolán McNamara <caolanm@redhat.com> (Red Hat, Inc.)
 * Portions created by the Initial Developer are Copyright (C) 2011 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Caolán McNamara <caolanm@redhat.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <osl/file.hxx>
#include <ucbhelper/configurationkeys.hxx>
#include <ucbhelper/contentbroker.hxx>
#include <vcl/builder.hxx>
#include <vcl/dialog.hxx>
#include <vcl/svapp.hxx>

class UIPreviewApp : public Application
{
public:
    virtual int Main();
};

using namespace com::sun::star;

int UIPreviewApp::Main()
{
    std::vector<rtl::OUString> uifiles;
    for (sal_uInt16 i = 0; i < GetCommandLineParamCount(); ++i)
    {
        rtl::OUString aFileUrl;
        osl::File::getFileURLFromSystemPath(GetCommandLineParam(i), aFileUrl);
        uifiles.push_back(aFileUrl);
    }

    if (uifiles.empty())
    {
        fprintf(stderr, "Usage: ui-previewer file.ui\n");
        return EXIT_FAILURE;
    }

    uno::Reference<uno::XComponentContext> xContext =
        cppu::defaultBootstrap_InitialComponentContext();
    uno::Reference<lang::XMultiComponentFactory> xFactory =
        xContext->getServiceManager();
    uno::Reference<lang::XMultiServiceFactory> xSFactory =
        uno::Reference<lang::XMultiServiceFactory> (xFactory, uno::UNO_QUERY_THROW);
    comphelper::setProcessServiceFactory(xSFactory);

    // Create UCB.
    uno::Sequence< uno::Any > aArgs(2);
    aArgs[ 0 ] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY1_LOCAL));
    aArgs[ 1 ] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY2_OFFICE));
    ::ucbhelper::ContentBroker::initialize(xSFactory, aArgs);

    try
    {
        Dialog *pDialog = new Dialog(NULL, WB_STDDIALOG);

        {
            VclBuilder aBuilder(pDialog, uifiles[0]);
            Dialog *pRealDialog = dynamic_cast<Dialog*>(aBuilder.get_widget_root());

            if (!pRealDialog)
                pRealDialog = pDialog;

            if (pRealDialog)
            {
                pRealDialog->SetText(rtl::OUString("LibreOffice ui-previewer"));
                pRealDialog->SetStyle(pDialog->GetStyle()|WB_CLOSEABLE);
                pRealDialog->Execute();
            }
        }

        delete pDialog;
    }
    catch (const uno::Exception &e)
    {
        fprintf(stderr, "fatal error: %s\n", rtl::OUStringToOString(e.Message, osl_getThreadTextEncoding()).getStr());
    }
    return false;

    ::ucbhelper::ContentBroker::deinitialize();

    return EXIT_SUCCESS;
}

UIPreviewApp aApp;

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cstring>

#include "OpenCLHelper.h"
#include "stringhelper.h"
#include "Timer.h"

using namespace std;

int main( int argc, char *argv[] ) {
    int its = atoi(argv[1] );
    int workgroupSize = atoi( argv[2] );

    cout << "its: " << its << " workgroupsize: " << workgroupSize << endl;

    string kernelSource = R"DELIM(
        kernel void test(global float *stuff) {
            float a = stuff[get_global_id(0)];
            float b = stuff[1];
            float c = stuff[2];
            #pragma unroll 100
            for( int i = 0; i < N_ITERATIONS; i++ ) {
                a = a * b + c;
            }
            stuff[get_global_id(0)] = a;
        }
    )DELIM";

    OpenCLHelper *cl = OpenCLHelper::createForFirstGpuOtherwiseCpu();
    CLKernel *kernel = cl->buildKernelFromString( kernelSource, "test", "-cl-opt-disable -D N_ITERATIONS=" + toString( its ) );

    Timer timer;
    float stuff[2048];
    for( int i = 0; i < 2048; i++ ) {
        stuff[i] = 2.0f;
    }
    stuff[1] = 2.0f;
    stuff[2] = -2.0f;
    kernel->inout( 2048, stuff );
    kernel->run_1d( workgroupSize, workgroupSize );
    cl->finish();
    timer.timeCheck("After kernel");
    cout << stuff[0] << " " << stuff[1] << endl;

    delete kernel;
    delete cl;

    return 0;
}

<commit_msg>testperf<commit_after>#include <iostream>
#include <string>
#include <cstring>

#include "OpenCLHelper.h"
#include "stringhelper.h"
#include "Timer.h"

using namespace std;

int main( int argc, char *argv[] ) {
    int its = atoi(argv[1] );
    int workgroupSize = atoi( argv[2] );

    cout << "its: " << its << " workgroupsize: " << workgroupSize << endl;

    string kernelSource = R"DELIM(
        kernel void test(global float *stuff) {
            float a = stuff[get_global_id(0)];
            float b = stuff[1024];
            float c = stuff[1025];
            #pragma unroll 100
            for( int i = 0; i < N_ITERATIONS; i++ ) {
                a = a * b + c;
            }
            stuff[get_global_id(0)] = a;
        }
    )DELIM";

    OpenCLHelper *cl = OpenCLHelper::createForFirstGpuOtherwiseCpu();
    CLKernel *kernel = cl->buildKernelFromString( kernelSource, "test", "-cl-opt-disable -D N_ITERATIONS=" + toString( its ) );

    Timer timer;
    float stuff[2048];
    for( int i = 0; i < 2048; i++ ) {
        stuff[i] = 2.0f;
    }
    stuff[1024] = 2.0f;
    stuff[1025] = -2.0f;
    kernel->inout( 2048, stuff );
    kernel->run_1d( workgroupSize, workgroupSize );
    cl->finish();
    timer.timeCheck("After kernel");
    cout << stuff[0] << " " << stuff[1] << endl;

    delete kernel;
    delete cl;

    return 0;
}

<|endoftext|>