<commit_before>/*************************************************************************
 *
 *  $RCSfile: formbrowsertools.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-25 16:03:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_
#define _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

//............................................................................
namespace pcr
{
//............................................................................

    ::rtl::OUString GetUIHeadlineName(sal_Int16 _nClassId, const ::com::sun::star::uno::Any& _rUnoObject);

//............................................................................
} // namespace pcr
//............................................................................

#endif // _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_

<commit_msg>INTEGRATION: CWS eforms2 (1.2.156); FILE MERGED 2004/07/21 07:50:18 fs 1.2.156.2: #i31762# +LessPropertyByHandle 2004/04/26 11:43:39 fs 1.2.156.1: +FindPropertyByHandle<commit_after>/*************************************************************************
 *
 *  $RCSfile: formbrowsertools.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-16 12:05:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_
#define _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#include <functional>

//............................................................................
namespace pcr
{
//............................................................................

    ::rtl::OUString GetUIHeadlineName(sal_Int16 _nClassId, const ::com::sun::star::uno::Any& _rUnoObject);

    struct FindPropertyByHandle : public ::std::unary_function< ::com::sun::star::beans::Property, bool >
    {
    private:
        sal_Int32 m_nId;

    public:
        FindPropertyByHandle( sal_Int32 _nId ) : m_nId ( _nId ) { }
        bool operator()( const ::com::sun::star::beans::Property& _rProp ) const
        {
            return m_nId == _rProp.Handle;
        }
    };

    struct LessPropertyByHandle : public ::std::binary_function< ::com::sun::star::beans::Property, ::com::sun::star::beans::Property, bool >
    {
        bool operator()( const ::com::sun::star::beans::Property& _rLHS, const ::com::sun::star::beans::Property& _rRHS ) const
        {
            return _rLHS.Handle < _rRHS.Handle;
        }
    };

//............................................................................
} // namespace pcr
//............................................................................

#endif // _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_

<|endoftext|>


<commit_before>/*
    Copyright (C) 2008, 2009 Nokia Corporation and/or its subsidiary(-ies)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "config.h"
#include "SourcePoolQt.h"

#ifdef QT_BUILD_SCRIPT_LIB

#include "SourceCode.h"
#include "Debugger.h"

namespace JSC {

    void SourcePool::startEvaluating(const SourceCode& source)
    {
        int id = source.provider()->asID();

        codes.insert(id,source.toString());

        currentScript.push(id);
        scriptRef.insert(id,ScriptActivCount());

        if (debug)
            debug->scriptLoad(id,source.toString(),source.provider()->url(),source.firstLine());
    }

    void SourcePool::stopEvaluating(const SourceCode& source)
    {
        int id = source.provider()->asID();
        int cid = currentScript.pop();

        if (scriptRef.contains(id)) {
            ScriptActivCount info = scriptRef.take(id);
            if (info.getCount()) {
                //we can't remove info from scriptRef
                info.isActive = false;
                scriptRef.insert(id,info);
            } else {
                //we are unloading source code
                if (debug)
                    debug->scriptUnload(id);
            }
        }
    }

    SourcePool::SourcePoolToken* SourcePool::objectRegister()
    {
        if (currentScript.isEmpty()) {
            return 0;
        }

        int id = currentScript.top();

        SourcePoolToken* token = new SourcePoolToken(id,this);

        ScriptActivCount info = scriptRef.take(id);

        info.incCount();
        scriptRef.insert(id,info);
        return token;
    }

    void SourcePool::objectUnregister(const SourcePool::SourcePoolToken *token)
    {
        int id = token->id;

        ScriptActivCount info = scriptRef.take(id);
        info.decCount();
        if (info.isActive) {
            scriptRef.insert(id,info);
        } else {
            if (info.getCount() == 0) {
                //remove from scriptRef (script is not active and there is no objects connected)
                if(debug)
                    debug->scriptUnload(id);
            } else {
                scriptRef.insert(id,info);
            }
        }

    }

    void SourcePool::setDebugger(JSC::Debugger *debugger) { this->debug = debugger; }
    Debugger* SourcePool::debugger() { return debug; }

} //namespace JSC

#endif //QT_BUILD_SCRIPT_LIB
<commit_msg>Clean up<commit_after>/*
    Copyright (C) 2008, 2009 Nokia Corporation and/or its subsidiary(-ies)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "config.h"
#include "SourcePoolQt.h"

#ifdef QT_BUILD_SCRIPT_LIB

#include "SourceCode.h"
#include "Debugger.h"

namespace JSC {

    void SourcePool::startEvaluating(const SourceCode& source)
    {
        int id = source.provider()->asID();

        codes.insert(id,source.toString());

        currentScript.push(id);
        scriptRef.insert(id,ScriptActivCount());

        if (debug)
            debug->scriptLoad(id,source.toString(),source.provider()->url(),source.firstLine());
    }

    void SourcePool::stopEvaluating(const SourceCode& source)
    {
        int id = source.provider()->asID();
        currentScript.pop();

        if (scriptRef.contains(id)) {
            ScriptActivCount info = scriptRef.take(id);
            if (info.getCount()) {
                //we can't remove info from scriptRef
                info.isActive = false;
                scriptRef.insert(id,info);
            } else {
                //we are unloading source code
                if (debug)
                    debug->scriptUnload(id);
            }
        }
    }

    SourcePool::SourcePoolToken* SourcePool::objectRegister()
    {
        if (currentScript.isEmpty()) {
            return 0;
        }

        int id = currentScript.top();

        SourcePoolToken* token = new SourcePoolToken(id,this);

        ScriptActivCount info = scriptRef.take(id);

        info.incCount();
        scriptRef.insert(id,info);
        return token;
    }

    void SourcePool::objectUnregister(const SourcePool::SourcePoolToken *token)
    {
        int id = token->id;

        ScriptActivCount info = scriptRef.take(id);
        info.decCount();
        if (info.isActive) {
            scriptRef.insert(id,info);
        } else {
            if (info.getCount() == 0) {
                //remove from scriptRef (script is not active and there is no objects connected)
                if(debug)
                    debug->scriptUnload(id);
            } else {
                scriptRef.insert(id,info);
            }
        }

    }

    void SourcePool::setDebugger(JSC::Debugger *debugger) { this->debug = debugger; }
    Debugger* SourcePool::debugger() { return debug; }

} //namespace JSC

#endif //QT_BUILD_SCRIPT_LIB
<|endoftext|>


<commit_before>/*
 * Valuations.cc
 *
 * Copyright (C) 2018 OpenCog Foundation
 *
 * Author: Nil Geisweiller
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "Valuations.h"

#include "Miner.h"

#include <opencog/util/Logger.h>
#include <opencog/util/oc_assert.h>
#include <opencog/atoms/base/Atom.h>
#include <opencog/atoms/pattern/PatternLink.h>
#include <opencog/atoms/core/LambdaLink.h>
#include <opencog/atomutils/TypeUtils.h>

#include <boost/range/algorithm/find.hpp>

namespace opencog
{

////////////////////
// ValuationsBase //
////////////////////

ValuationsBase::ValuationsBase(const Variables& vars) : variables(vars) {}

ValuationsBase::ValuationsBase() {}

bool ValuationsBase::novar() const
{
	return variables.empty();
}

Handle ValuationsBase::front_variable() const
{
	return variables.varseq[0];
}

Handle ValuationsBase::variable(unsigned i) const
{
	return variables.varseq[i];
}

unsigned ValuationsBase::index(const Handle& var) const
{
	return variables.index.at(var);
}

unsigned ValuationsBase::size() const
{
	return 0;
}

//////////////////
// SCValuations //
//////////////////

SCValuations::SCValuations(const Variables& vars, const Handle& satset)
	: ValuationsBase(vars)
{
	if (satset)
	{
		OC_ASSERT(satset->get_type() == SET_LINK);
		for (const Handle& vals : satset->getOutgoingSet())
		{
			if (vars.size() == 1)
				valuations.push_back({vals});
			else
				valuations.push_back(vals->getOutgoingSet());
		}
	}
}

SCValuations SCValuations::erase_front() const
{
	return erase(front_variable());
}

SCValuations SCValuations::erase(const Handle& var) const
{
	// No variable, just return itself
	if (not variables.is_in_varset(var))
		return *this;

	// Remove variable
	Variables nvars(variables);
	nvars.erase(var);
	auto it = boost::find(variables.varseq, var);
	int dst = std::distance(variables.varseq.begin(), it);
	SCValuations nvals(nvars);
	if (not nvals.novar())
	{
		for (HandleSeq vals : valuations)
		{
			vals.erase(std::next(vals.begin(), dst));
			nvals.valuations.push_back(vals);
		}
	}
	return nvals;
}

HandleUCounter SCValuations::values(const Handle& var) const
{
	return values(index(var));
}

HandleUCounter SCValuations::values(unsigned var_idx) const
{
	HandleUCounter vals;
	for (const HandleSeq& valuation : valuations)
		vals[valuation[var_idx]]++;
	return vals;
}

bool SCValuations::operator==(const SCValuations& other) const
{
	return variables == other.variables;
}

bool SCValuations::operator<(const SCValuations& other) const
{
	return variables < other.variables;
}

unsigned SCValuations::size() const
{
	return valuations.size();
}

////////////////
// Valuations //
////////////////

Valuations::Valuations(const Handle& pattern, const HandleSet& texts)
	: ValuationsBase(Miner::get_variables(pattern))
{
	for (const Handle& cp : Miner::get_component_patterns(pattern))
	{
		Handle satset = Miner::restricted_satisfying_set(cp, texts);
		scvs.insert(SCValuations(Miner::get_variables(cp), satset));
	}
	setup_size();
}

Valuations::Valuations(const Variables& vars, const SCValuationsSet& sc)
	: ValuationsBase(vars), scvs(sc)
{
	setup_size();
}

Valuations::Valuations(const Variables& vars)
	: ValuationsBase(vars), _size(0) {}

Valuations Valuations::erase_front() const
{
	// Take remaining variables
	Variables nvars(variables);
	Handle var = front_variable();
	nvars.erase(var);
	Valuations nvals(nvars);

	// Move values from remaining variables to new Valuations
	for (const SCValuations& scv : scvs)
	{
		SCValuations nscvals(scv.erase(var));
		if (not nscvals.novar())
			nvals.scvs.insert(nscvals);
	}

	// Keep the previous size as we still need to consider those
	// combinations
	nvals._size = _size;

	// Return new Valuations
	return nvals;
}

const SCValuations& Valuations::get_scvaluations(const Handle& var) const
{
	for (const SCValuations& scv : scvs)
		if (scv.variables.is_in_varset(var))
			return scv;
	throw RuntimeException(TRACE_INFO, "There's likely a bug");
}

unsigned Valuations::size() const
{
	return _size;
}

void Valuations::setup_size()
{
	_size = scvs.empty() ? 0 : 1;
	for (const SCValuations& scv : scvs)
		_size *= scv.size();
}

std::string oc_to_string(const SCValuations& scv, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "variables:" << std::endl
	   << oc_to_string(scv.variables, indent + OC_TO_STRING_INDENT);
	ss << indent << "valuations:" << std::endl
	   << oc_to_string(scv.valuations, indent + OC_TO_STRING_INDENT);
	return ss.str();
}

std::string oc_to_string(const SCValuationsSet& scvs, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << scvs.size() << std::endl;
	int i = 0;
	for (const auto& scv : scvs)
	{
		ss << indent << "scvaluations [" << i << "]:" << std::endl
		   << oc_to_string(scv, indent + OC_TO_STRING_INDENT);
		++i;
	}
	return ss.str();
}

std::string oc_to_string(const Valuations& valuations, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << valuations.size() << std::endl;
	ss << indent << "variables:" << std::endl
	   << oc_to_string(valuations.variables, indent + OC_TO_STRING_INDENT);
	ss << indent << "scvaluations set:" << std::endl
	   << oc_to_string(valuations.scvs, indent + OC_TO_STRING_INDENT);
	return ss.str();
}

std::string oc_to_string(const HandleValuationsMap& h2vals, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << h2vals.size() << std::endl;
	int i = 0;
	for (const auto& hv : h2vals)
	{
		ss << indent << "atom [" << i << "]:" << std::endl
		   << oc_to_string(hv.first, indent + OC_TO_STRING_INDENT);
		ss << indent << "valuations [" << i << "]:" << std::endl
		   << oc_to_string(hv.second, indent + OC_TO_STRING_INDENT);
		++i;
	}
	return ss.str();
}

} // namespace opencog
<commit_msg>Fix restricted_satisfying_set call in Valuations ctor<commit_after>/*
 * Valuations.cc
 *
 * Copyright (C) 2018 OpenCog Foundation
 *
 * Author: Nil Geisweiller
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "Valuations.h"

#include "Miner.h"

#include <opencog/util/Logger.h>
#include <opencog/util/oc_assert.h>
#include <opencog/atoms/base/Atom.h>
#include <opencog/atoms/pattern/PatternLink.h>
#include <opencog/atoms/core/LambdaLink.h>
#include <opencog/atomutils/TypeUtils.h>

#include <boost/range/algorithm/find.hpp>

namespace opencog
{

////////////////////
// ValuationsBase //
////////////////////

ValuationsBase::ValuationsBase(const Variables& vars) : variables(vars) {}

ValuationsBase::ValuationsBase() {}

bool ValuationsBase::novar() const
{
	return variables.empty();
}

Handle ValuationsBase::front_variable() const
{
	return variables.varseq[0];
}

Handle ValuationsBase::variable(unsigned i) const
{
	return variables.varseq[i];
}

unsigned ValuationsBase::index(const Handle& var) const
{
	return variables.index.at(var);
}

unsigned ValuationsBase::size() const
{
	return 0;
}

//////////////////
// SCValuations //
//////////////////

SCValuations::SCValuations(const Variables& vars, const Handle& satset)
	: ValuationsBase(vars)
{
	if (satset)
	{
		OC_ASSERT(satset->get_type() == SET_LINK);
		for (const Handle& vals : satset->getOutgoingSet())
		{
			if (vars.size() == 1)
				valuations.push_back({vals});
			else
				valuations.push_back(vals->getOutgoingSet());
		}
	}
}

SCValuations SCValuations::erase_front() const
{
	return erase(front_variable());
}

SCValuations SCValuations::erase(const Handle& var) const
{
	// No variable, just return itself
	if (not variables.is_in_varset(var))
		return *this;

	// Remove variable
	Variables nvars(variables);
	nvars.erase(var);
	auto it = boost::find(variables.varseq, var);
	int dst = std::distance(variables.varseq.begin(), it);
	SCValuations nvals(nvars);
	if (not nvals.novar())
	{
		for (HandleSeq vals : valuations)
		{
			vals.erase(std::next(vals.begin(), dst));
			nvals.valuations.push_back(vals);
		}
	}
	return nvals;
}

HandleUCounter SCValuations::values(const Handle& var) const
{
	return values(index(var));
}

HandleUCounter SCValuations::values(unsigned var_idx) const
{
	HandleUCounter vals;
	for (const HandleSeq& valuation : valuations)
		vals[valuation[var_idx]]++;
	return vals;
}

bool SCValuations::operator==(const SCValuations& other) const
{
	return variables == other.variables;
}

bool SCValuations::operator<(const SCValuations& other) const
{
	return variables < other.variables;
}

unsigned SCValuations::size() const
{
	return valuations.size();
}

////////////////
// Valuations //
////////////////

Valuations::Valuations(const Handle& pattern, const HandleSet& texts)
	: ValuationsBase(Miner::get_variables(pattern))
{
	for (const Handle& cp : Miner::get_component_patterns(pattern))
	{
		Handle satset = Miner::restricted_satisfying_set(cp, texts, texts.size());
		scvs.insert(SCValuations(Miner::get_variables(cp), satset));
	}
	setup_size();
}

Valuations::Valuations(const Variables& vars, const SCValuationsSet& sc)
	: ValuationsBase(vars), scvs(sc)
{
	setup_size();
}

Valuations::Valuations(const Variables& vars)
	: ValuationsBase(vars), _size(0) {}

Valuations Valuations::erase_front() const
{
	// Take remaining variables
	Variables nvars(variables);
	Handle var = front_variable();
	nvars.erase(var);
	Valuations nvals(nvars);

	// Move values from remaining variables to new Valuations
	for (const SCValuations& scv : scvs)
	{
		SCValuations nscvals(scv.erase(var));
		if (not nscvals.novar())
			nvals.scvs.insert(nscvals);
	}

	// Keep the previous size as we still need to consider those
	// combinations
	nvals._size = _size;

	// Return new Valuations
	return nvals;
}

const SCValuations& Valuations::get_scvaluations(const Handle& var) const
{
	for (const SCValuations& scv : scvs)
		if (scv.variables.is_in_varset(var))
			return scv;
	throw RuntimeException(TRACE_INFO, "There's likely a bug");
}

unsigned Valuations::size() const
{
	return _size;
}

void Valuations::setup_size()
{
	_size = scvs.empty() ? 0 : 1;
	for (const SCValuations& scv : scvs)
		_size *= scv.size();
}

std::string oc_to_string(const SCValuations& scv, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "variables:" << std::endl
	   << oc_to_string(scv.variables, indent + OC_TO_STRING_INDENT);
	ss << indent << "valuations:" << std::endl
	   << oc_to_string(scv.valuations, indent + OC_TO_STRING_INDENT);
	return ss.str();
}

std::string oc_to_string(const SCValuationsSet& scvs, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << scvs.size() << std::endl;
	int i = 0;
	for (const auto& scv : scvs)
	{
		ss << indent << "scvaluations [" << i << "]:" << std::endl
		   << oc_to_string(scv, indent + OC_TO_STRING_INDENT);
		++i;
	}
	return ss.str();
}

std::string oc_to_string(const Valuations& valuations, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << valuations.size() << std::endl;
	ss << indent << "variables:" << std::endl
	   << oc_to_string(valuations.variables, indent + OC_TO_STRING_INDENT);
	ss << indent << "scvaluations set:" << std::endl
	   << oc_to_string(valuations.scvs, indent + OC_TO_STRING_INDENT);
	return ss.str();
}

std::string oc_to_string(const HandleValuationsMap& h2vals, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << h2vals.size() << std::endl;
	int i = 0;
	for (const auto& hv : h2vals)
	{
		ss << indent << "atom [" << i << "]:" << std::endl
		   << oc_to_string(hv.first, indent + OC_TO_STRING_INDENT);
		ss << indent << "valuations [" << i << "]:" << std::endl
		   << oc_to_string(hv.second, indent + OC_TO_STRING_INDENT);
		++i;
	}
	return ss.str();
}

} // namespace opencog
<|endoftext|>


<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include <functional>

#include "fill_disruption_from_database.h"
#include <pqxx/pqxx>
#include "utils/exception.h"
#include "utils/logger.h"

#include <boost/format.hpp>
#include <boost/algorithm/string/join.hpp>

namespace navitia {

void fill_disruption_from_database(const std::string& connection_string,
        navitia::type::PT_Data& pt_data, type::MetaData &meta, const std::vector<std::string>& contributors) {
    std::unique_ptr<pqxx::connection> conn;
    try{
        conn = std::unique_ptr<pqxx::connection>(new pqxx::connection(connection_string));
    }catch(const pqxx::pqxx_exception& e){
        throw navitia::exception(std::string("Unable to connect to chaos database: ")
                + std::string(e.base().what()));
    }
    pqxx::work work(*conn, "loading disruptions");

    size_t offset = 0,
           items_per_request = 100;
    DisruptionDatabaseReader reader(pt_data, meta);
    pqxx::result result;
    std::string contributors_array = boost::algorithm::join(contributors, ", ");
    do{
        std::string request = (boost::format(
               "SELECT "
               // Disruptions field
               "     d.id as disruption_id, d.reference as disruption_reference, d.note as disruption_note,"
               "     d.status as disruption_status,"
               "     extract(epoch from d.start_publication_date) :: bigint as disruption_start_publication_date,"
               "     extract(epoch from d.end_publication_date) :: bigint as disruption_end_publication_date,"
               "     extract(epoch from d.created_at) :: bigint as disruption_created_at,"
               "     extract(epoch from d.updated_at) :: bigint as disruption_updated_at,"
               "     co.contributor_code as contributor,"
               // Cause fields
               "     c.id as cause_id, c.wording as cause_wording,"
               "     c.is_visible as cause_visible,"
               "     extract(epoch from c.created_at) :: bigint as cause_created_at,"
               "     extract(epoch from c.updated_at) :: bigint as cause_updated_at,"
               // Tag fields
               "     t.id as tag_id, t.name as tag_name, t.is_visible as tag_is_visible,"
               "     extract(epoch from t.created_at) :: bigint as tag_created_at,"
               "     extract(epoch from t.updated_at) :: bigint as tag_updated_at,"
               // Impact fields
               "     i.id as impact_id, i.status as impact_status, i.disruption_id as impact_disruption_id,"
               "     extract(epoch from i.created_at) :: bigint as impact_created_at,"
               "     extract(epoch from i.updated_at) :: bigint as impact_updated_at,"
               // Application period fields
               "     a.id as application_id,"
               "     extract(epoch from a.start_date) :: bigint as application_start_date,"
               "     extract(epoch from a.end_date) :: bigint as application_end_date,"
               // Severity fields
               "     s.id as severity_id, s.wording as severity_wording, s.color as severity_color,"
               "     s.is_visible as severity_is_visible, s.priority as severity_priority,"
               "     s.effect as severity_effect,"
               "     extract(epoch from s.created_at) :: bigint as severity_created_at,"
               "     extract(epoch from s.updated_at) :: bigint as severity_updated_at,"
               // Ptobject fields
               "     p.id as ptobject_id, p.type as ptobject_type, p.uri as ptobject_uri,"
               "     extract(epoch from p.created_at) :: bigint as ptobject_created_at,"
               "     extract(epoch from p.updated_at) :: bigint as ptobject_updated_at,"
               // Ptobject line_section optional fields
               "     ls_line.uri as ls_line_uri,"
               "     extract(epoch from ls_line.created_at) :: bigint as ls_line_created_at,"
               "     extract(epoch from ls_line.updated_at) :: bigint as ls_line_updated_at,"
               "     ls_start.uri as ls_start_uri,"
               "     extract(epoch from ls_start.created_at) :: bigint as ls_start_created_at,"
               "     extract(epoch from ls_start.updated_at) :: bigint as ls_start_updated_at,"
               "     ls_end.uri as ls_end_uri,"
               "     extract(epoch from ls_end.created_at) :: bigint as ls_end_created_at,"
               "     extract(epoch from ls_end.updated_at) :: bigint as ls_end_updated_at,"
               // Message fields
               "     m.id as message_id, m.text as message_text,"
               "     extract(epoch from m.created_at) :: bigint as message_created_at,"
               "     extract(epoch from m.updated_at) :: bigint as message_updated_at,"
               // Channel fields
               "     ch.id as channel_id, ch.name as channel_name,"
               "     ch.content_type as channel_content_type, ch.max_size as channel_max_size,"
               "     extract(epoch from ch.created_at) :: bigint as channel_created_at,"
               "     extract(epoch from ch.updated_at) :: bigint as channel_updated_at"
               "     FROM disruption AS d"
               "     JOIN contributor AS co ON d.contributor_id = co.id"
               "     JOIN cause AS c ON (c.id = d.cause_id)"
               "     LEFT JOIN associate_disruption_tag ON associate_disruption_tag.disruption_id = d.id"
               "     LEFT JOIN tag AS t ON associate_disruption_tag.tag_id = t.id"
               "     JOIN impact AS i ON i.disruption_id = d.id"
               "     JOIN application_periods AS a ON a.impact_id = i.id"
               "     JOIN severity AS s ON s.id = i.severity_id"
               "     JOIN associate_impact_pt_object ON associate_impact_pt_object.impact_id = i.id"
               "     JOIN pt_object AS p ON associate_impact_pt_object.pt_object_id = p.id"
               "     LEFT JOIN line_section ON p.id = line_section.object_id"
               "     LEFT JOIN pt_object AS ls_line ON line_section.line_object_id = ls_line.id"
               "     LEFT JOIN pt_object AS ls_start ON line_section.start_object_id = ls_start.id"
               "     LEFT JOIN pt_object AS ls_end ON line_section.end_object_id = ls_end.id"
               "     LEFT JOIN message AS m ON m.impact_id = i.id"
               "     LEFT JOIN channel AS ch ON m.channel_id = ch.id"
               "     WHERE co.contributor_code = ANY('{%s}')" // it's like a "IN" but won't crash if empty
               "     AND d.status = 'published'"
               "     AND i.status = 'published'"
               "     ORDER BY d.id, c.id, t.id, i.id, a.id, p.id, m.id, ch.id"
               "     LIMIT %i OFFSET %i"
               " ;") % contributors_array % items_per_request % offset).str();

        result = work.exec(request);
        for (auto res : result) {
            reader(res);
        }

        offset += result.size();
    }while(result.size() > 0);
    reader.finalize();

    LOG4CPLUS_INFO(log4cplus::Logger::getInstance("Logger"),offset << " disruptions loaded");
}

void DisruptionDatabaseReader::finalize() {
    if (disruption && disruption->id() != "") {
        add_disruption(*disruption, pt_data, meta);
    }
}

}
<commit_msg>Kraken: add some logs<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include <functional>

#include "fill_disruption_from_database.h"
#include <pqxx/pqxx>
#include "utils/exception.h"
#include "utils/logger.h"

#include <boost/format.hpp>
#include <boost/algorithm/string/join.hpp>

namespace navitia {

void fill_disruption_from_database(const std::string& connection_string,
        navitia::type::PT_Data& pt_data, type::MetaData &meta, const std::vector<std::string>& contributors) {
    std::unique_ptr<pqxx::connection> conn;
    try{
        conn = std::unique_ptr<pqxx::connection>(new pqxx::connection(connection_string));
    }catch(const pqxx::pqxx_exception& e){
        throw navitia::exception(std::string("Unable to connect to chaos database: ")
                + std::string(e.base().what()));
    }
    pqxx::work work(*conn, "loading disruptions");

    size_t offset = 0,
           items_per_request = 100;
    DisruptionDatabaseReader reader(pt_data, meta);
    pqxx::result result;
    std::string contributors_array = boost::algorithm::join(contributors, ", ");
    LOG4CPLUS_INFO(log4cplus::Logger::getInstance("Logger"), "Reading disruptions from database");
    do{
        std::string request = (boost::format(
               "SELECT "
               // Disruptions field
               "     d.id as disruption_id, d.reference as disruption_reference, d.note as disruption_note,"
               "     d.status as disruption_status,"
               "     extract(epoch from d.start_publication_date) :: bigint as disruption_start_publication_date,"
               "     extract(epoch from d.end_publication_date) :: bigint as disruption_end_publication_date,"
               "     extract(epoch from d.created_at) :: bigint as disruption_created_at,"
               "     extract(epoch from d.updated_at) :: bigint as disruption_updated_at,"
               "     co.contributor_code as contributor,"
               // Cause fields
               "     c.id as cause_id, c.wording as cause_wording,"
               "     c.is_visible as cause_visible,"
               "     extract(epoch from c.created_at) :: bigint as cause_created_at,"
               "     extract(epoch from c.updated_at) :: bigint as cause_updated_at,"
               // Tag fields
               "     t.id as tag_id, t.name as tag_name, t.is_visible as tag_is_visible,"
               "     extract(epoch from t.created_at) :: bigint as tag_created_at,"
               "     extract(epoch from t.updated_at) :: bigint as tag_updated_at,"
               // Impact fields
               "     i.id as impact_id, i.status as impact_status, i.disruption_id as impact_disruption_id,"
               "     extract(epoch from i.created_at) :: bigint as impact_created_at,"
               "     extract(epoch from i.updated_at) :: bigint as impact_updated_at,"
               // Application period fields
               "     a.id as application_id,"
               "     extract(epoch from a.start_date) :: bigint as application_start_date,"
               "     extract(epoch from a.end_date) :: bigint as application_end_date,"
               // Severity fields
               "     s.id as severity_id, s.wording as severity_wording, s.color as severity_color,"
               "     s.is_visible as severity_is_visible, s.priority as severity_priority,"
               "     s.effect as severity_effect,"
               "     extract(epoch from s.created_at) :: bigint as severity_created_at,"
               "     extract(epoch from s.updated_at) :: bigint as severity_updated_at,"
               // Ptobject fields
               "     p.id as ptobject_id, p.type as ptobject_type, p.uri as ptobject_uri,"
               "     extract(epoch from p.created_at) :: bigint as ptobject_created_at,"
               "     extract(epoch from p.updated_at) :: bigint as ptobject_updated_at,"
               // Ptobject line_section optional fields
               "     ls_line.uri as ls_line_uri,"
               "     extract(epoch from ls_line.created_at) :: bigint as ls_line_created_at,"
               "     extract(epoch from ls_line.updated_at) :: bigint as ls_line_updated_at,"
               "     ls_start.uri as ls_start_uri,"
               "     extract(epoch from ls_start.created_at) :: bigint as ls_start_created_at,"
               "     extract(epoch from ls_start.updated_at) :: bigint as ls_start_updated_at,"
               "     ls_end.uri as ls_end_uri,"
               "     extract(epoch from ls_end.created_at) :: bigint as ls_end_created_at,"
               "     extract(epoch from ls_end.updated_at) :: bigint as ls_end_updated_at,"
               // Message fields
               "     m.id as message_id, m.text as message_text,"
               "     extract(epoch from m.created_at) :: bigint as message_created_at,"
               "     extract(epoch from m.updated_at) :: bigint as message_updated_at,"
               // Channel fields
               "     ch.id as channel_id, ch.name as channel_name,"
               "     ch.content_type as channel_content_type, ch.max_size as channel_max_size,"
               "     extract(epoch from ch.created_at) :: bigint as channel_created_at,"
               "     extract(epoch from ch.updated_at) :: bigint as channel_updated_at"
               "     FROM disruption AS d"
               "     JOIN contributor AS co ON d.contributor_id = co.id"
               "     JOIN cause AS c ON (c.id = d.cause_id)"
               "     LEFT JOIN associate_disruption_tag ON associate_disruption_tag.disruption_id = d.id"
               "     LEFT JOIN tag AS t ON associate_disruption_tag.tag_id = t.id"
               "     JOIN impact AS i ON i.disruption_id = d.id"
               "     JOIN application_periods AS a ON a.impact_id = i.id"
               "     JOIN severity AS s ON s.id = i.severity_id"
               "     JOIN associate_impact_pt_object ON associate_impact_pt_object.impact_id = i.id"
               "     JOIN pt_object AS p ON associate_impact_pt_object.pt_object_id = p.id"
               "     LEFT JOIN line_section ON p.id = line_section.object_id"
               "     LEFT JOIN pt_object AS ls_line ON line_section.line_object_id = ls_line.id"
               "     LEFT JOIN pt_object AS ls_start ON line_section.start_object_id = ls_start.id"
               "     LEFT JOIN pt_object AS ls_end ON line_section.end_object_id = ls_end.id"
               "     LEFT JOIN message AS m ON m.impact_id = i.id"
               "     LEFT JOIN channel AS ch ON m.channel_id = ch.id"
               "     WHERE co.contributor_code = ANY('{%s}')" // it's like a "IN" but won't crash if empty
               "     AND d.status = 'published'"
               "     AND i.status = 'published'"
               "     ORDER BY d.id, c.id, t.id, i.id, a.id, p.id, m.id, ch.id"
               "     LIMIT %i OFFSET %i"
               " ;") % contributors_array % items_per_request % offset).str();

        result = work.exec(request);
        for (auto res : result) {
            reader(res);
        }

        offset += result.size();
    }while(result.size() > 0);
    LOG4CPLUS_INFO(log4cplus::Logger::getInstance("Logger"),"Loading " << offset << " disruptions");
    reader.finalize();
    LOG4CPLUS_INFO(log4cplus::Logger::getInstance("Logger"),offset << " disruptions loaded");
}

void DisruptionDatabaseReader::finalize() {
    if (disruption && disruption->id() != "") {
        add_disruption(*disruption, pt_data, meta);
    }
}

}
<|endoftext|>


<commit_before>#ifndef RECURSE_RESPONSE_HPP
#define RECURSE_RESPONSE_HPP

#include <QHash>
#include <QJsonDocument>
#include <functional>

class Response
{

public:
    //!
    //! \brief get
    //! Returns the HTTP response header specified by key
    //!
    //! \param QString case-insensitive key of the header
    //! \return QString header
    //!
    QString getHeader(const QString &key)
    {
        return m_headers[key.toLower()];
    }

    //!
    //! \brief set
    //! Sets the response HTTP header to value.
    //!
    //! \param QString key of the header
    //! \param QString value for the header
    //! \return Response chainable
    //!
    Response &setHeader(const QString &key, const QString &value)
    {
        m_headers[key] = value;
        return *this;
    }

    //!
    //! \brief status
    //! Get HTTP response status
    //!
    //! \return quint16 status
    //!
    quint16 status() const
    {
        return m_status;
    }

    //!
    //! \brief status
    //! Set HTTP response status
    //!
    //! \param quint16 status
    //! \return Response chainable
    //!
    Response &status(quint16 status)
    {
        m_status = status;
        return *this;
    }

    //!
    //! \brief type
    //! Get the Content-Type HTTP header
    //!
    //! \return QString MIME content-type
    //!
    QString type() const
    {
        return m_headers["content-type"];
    }

    //!
    //! \brief type
    //! Sets Content-Type HTTP header
    //!
    //! \param QString MIME type
    //! \return Response chainable
    //!
    Response &type(const QString &type)
    {
        m_headers["content-type"] = type;
        return *this;
    }

    //!
    //! \brief body
    //! Get current response body data content, useful for upstream middleware
    //!
    //! \return QString response content
    //!
    QString body() const
    {
        return m_body;
    }

    //!
    //! \brief body
    //! Set response content, overrides existing
    //!
    //! \param QString body
    //! \return  Response chainable
    //!
    Response &body(const QString &body)
    {
        m_body = body;
        return *this;
    }

    //!
    //! \brief write
    //! Appends data to existing content (set by write() or body())
    //!
    //! \param QString data to be added
    //! \return Response chainable
    //!
    Response &write(const QString &data)
    {
        m_body += data;
        return *this;
    }

    //!
    //! \brief send
    //! Sends actual data to client
    //!
    //! \param QString body optional, if provided this is sent instead of current data in buffer
    //!
    void send(const QString &body = "")
    {
        if (body.size())
            m_body = body;

        end();
    }

    //!
    //! \brief send
    //! Overloaded function, allows sending QJsonDocument
    //!
    //! \param body
    //!
    void send(const QJsonDocument &body)
    {
        type("application/json");
        m_body = body.toJson(QJsonDocument::Compact);

        end();
    }

    //! brief redirect
    //! Perform a 302 redirect to `url`.
    //!
    //! the string "back" is used to provide Referrer support
    //! when Referrer is not present `alt` is used
    //!
    //! Examples:
    //!
    //!    redirect('back');
    //!    redirect('back', '/index.html');
    //!    redirect('/login');
    //!    redirect('http://google.com');
    //!
    //! To override status or body set them before calling redirect
    //!
    //!     status(301).body("Redirecting...").redirect("http://www.google.com")
    //!
    //! \param url to redirect to
    //! \param alt used when referrer is not present, "/" by default

    void redirect(const QString &url, const QString &alt = "/")
    {
        // set location
        if (url == "back")
        {
            const QString &referrer = getHeader("referrer");

            if (!referrer.isEmpty())
                setHeader("Location", referrer);
            else
                setHeader("Location", alt);
        }
        else
        {
            setHeader("Location", url);
        }

        // set redirect status if not set
        // https://tools.ietf.org/html/rfc7231#section-6.4
        if (status() < 300 || status() > 308)
            status(302);

        // set body if not set
        if (body().isEmpty())
            body("This page has moved to " % url);

        end();
    }

    //!
    //! \brief end
    //! final function responsible for sending data
    //! this is bound to Recurse::end function, from recurse.hpp
    //! ctx->response.end = std::bind(&Recurse::end, this, ctx);
    //!
    std::function<void()> end;

    //!
    //! \brief method
    //! Response method, eg: GET
    //!
    QString method;

    //!
    //! \brief protocol
    //! Response protocol, eg: HTTP
    //!
    QString protocol;

    //!
    //! \brief http codes
    //!
    QHash<quint16, QString> http_codes{
        { 100, "Continue" },
        { 101, "Switching Protocols" },
        { 200, "OK" },
        { 201, "Created" },
        { 202, "Accepted" },
        { 203, "Non-Authoritative Information" },
        { 204, "No Content" },
        { 205, "Reset Content" },
        { 206, "Partial Content" },
        { 300, "Multiple Choices" },
        { 301, "Moved Permanently" },
        { 302, "Found" },
        { 303, "See Other" },
        { 304, "Not Modified" },
        { 305, "Use Proxy" },
        { 307, "Temporary Redirect" },
        { 400, "Bad Request" },
        { 401, "Unauthorized" },
        { 402, "Payment Required" },
        { 403, "Forbidden" },
        { 404, "Not Found" },
        { 405, "Method Not Allowed" },
        { 406, "Not Acceptable" },
        { 407, "Proxy Authentication Required" },
        { 408, "Request Time-out" },
        { 409, "Conflict" },
        { 410, "Gone" },
        { 411, "Length Required" },
        { 412, "Precondition Failed" },
        { 413, "Request Entity Too Large" },
        { 414, "Request-URI Too Large" },
        { 415, "Unsupported Media Type" },
        { 416, "Requested range not satisfiable" },
        { 417, "Expectation Failed" },
        { 500, "Internal Server Error" },
        { 501, "Not Implemented" },
        { 502, "Bad Gateway" },
        { 503, "Service Unavailable" },
        { 504, "Gateway Time-out" },
        { 505, "HTTP Version not supported" }
    };

    //!
    //! \brief create_reply
    //! create reply for sending to client
    //!
    //! \return QString reply to be sent
    //!
    QString create_reply();

private:
    //!
    //! \brief m_status
    //! HTTP response status
    //!
    quint16 m_status = 200;

    //!
    //! \brief header
    //! holds all header data as key/value
    //!

    QHash<QString, QString> m_headers;
    //!
    //! \brief m_body
    //! HTTP response content
    //!
    QString m_body;
};

// https://tools.ietf.org/html/rfc7230#page-19
inline QString Response::create_reply()
{
    QString reply = this->protocol % " " % QString::number(this->status()) % " "
    % this->http_codes[this->status()] % "\r\n";

    // set content length
    m_headers["content-length"] = QString::number(this->body().size());

    // set content type if not set
    if (!m_headers.contains("content-type"))
        m_headers["content-type"] = "text/plain";

    // set custom header fields
    for (auto i = m_headers.constBegin(); i != m_headers.constEnd(); ++i)
        reply = reply % i.key() % ": " % i.value() % "\r\n";

    reply += "\r\n";

    if (this->body().size())
        reply += this->body();

    return reply;
}

#endif
<commit_msg>doxygen tag fix<commit_after>#ifndef RECURSE_RESPONSE_HPP
#define RECURSE_RESPONSE_HPP

#include <QHash>
#include <QJsonDocument>
#include <functional>

class Response
{

public:
    //!
    //! \brief get
    //! Returns the HTTP response header specified by key
    //!
    //! \param QString case-insensitive key of the header
    //! \return QString header
    //!
    QString getHeader(const QString &key)
    {
        return m_headers[key.toLower()];
    }

    //!
    //! \brief set
    //! Sets the response HTTP header to value.
    //!
    //! \param QString key of the header
    //! \param QString value for the header
    //! \return Response chainable
    //!
    Response &setHeader(const QString &key, const QString &value)
    {
        m_headers[key] = value;
        return *this;
    }

    //!
    //! \brief status
    //! Get HTTP response status
    //!
    //! \return quint16 status
    //!
    quint16 status() const
    {
        return m_status;
    }

    //!
    //! \brief status
    //! Set HTTP response status
    //!
    //! \param quint16 status
    //! \return Response chainable
    //!
    Response &status(quint16 status)
    {
        m_status = status;
        return *this;
    }

    //!
    //! \brief type
    //! Get the Content-Type HTTP header
    //!
    //! \return QString MIME content-type
    //!
    QString type() const
    {
        return m_headers["content-type"];
    }

    //!
    //! \brief type
    //! Sets Content-Type HTTP header
    //!
    //! \param QString MIME type
    //! \return Response chainable
    //!
    Response &type(const QString &type)
    {
        m_headers["content-type"] = type;
        return *this;
    }

    //!
    //! \brief body
    //! Get current response body data content, useful for upstream middleware
    //!
    //! \return QString response content
    //!
    QString body() const
    {
        return m_body;
    }

    //!
    //! \brief body
    //! Set response content, overrides existing
    //!
    //! \param QString body
    //! \return  Response chainable
    //!
    Response &body(const QString &body)
    {
        m_body = body;
        return *this;
    }

    //!
    //! \brief write
    //! Appends data to existing content (set by write() or body())
    //!
    //! \param QString data to be added
    //! \return Response chainable
    //!
    Response &write(const QString &data)
    {
        m_body += data;
        return *this;
    }

    //!
    //! \brief send
    //! Sends actual data to client
    //!
    //! \param QString body optional, if provided this is sent instead of current data in buffer
    //!
    void send(const QString &body = "")
    {
        if (body.size())
            m_body = body;

        end();
    }

    //!
    //! \brief send
    //! Overloaded function, allows sending QJsonDocument
    //!
    //! \param body
    //!
    void send(const QJsonDocument &body)
    {
        type("application/json");
        m_body = body.toJson(QJsonDocument::Compact);

        end();
    }

    //! \brief redirect
    //! Perform a 302 redirect to `url`.
    //!
    //! the string "back" is used to provide Referrer support
    //! when Referrer is not present `alt` is used
    //!
    //! Examples:
    //!
    //!    redirect('back');
    //!    redirect('back', '/index.html');
    //!    redirect('/login');
    //!    redirect('http://google.com');
    //!
    //! To override status or body set them before calling redirect
    //!
    //!     status(301).body("Redirecting...").redirect("http://www.google.com")
    //!
    //! \param url to redirect to
    //! \param alt used when referrer is not present, "/" by default

    void redirect(const QString &url, const QString &alt = "/")
    {
        // set location
        if (url == "back")
        {
            const QString &referrer = getHeader("referrer");

            if (!referrer.isEmpty())
                setHeader("Location", referrer);
            else
                setHeader("Location", alt);
        }
        else
        {
            setHeader("Location", url);
        }

        // set redirect status if not set
        // https://tools.ietf.org/html/rfc7231#section-6.4
        if (status() < 300 || status() > 308)
            status(302);

        // set body if not set
        if (body().isEmpty())
            body("This page has moved to " % url);

        end();
    }

    //!
    //! \brief end
    //! final function responsible for sending data
    //! this is bound to Recurse::end function, from recurse.hpp
    //! ctx->response.end = std::bind(&Recurse::end, this, ctx);
    //!
    std::function<void()> end;

    //!
    //! \brief method
    //! Response method, eg: GET
    //!
    QString method;

    //!
    //! \brief protocol
    //! Response protocol, eg: HTTP
    //!
    QString protocol;

    //!
    //! \brief http codes
    //!
    QHash<quint16, QString> http_codes{
        { 100, "Continue" },
        { 101, "Switching Protocols" },
        { 200, "OK" },
        { 201, "Created" },
        { 202, "Accepted" },
        { 203, "Non-Authoritative Information" },
        { 204, "No Content" },
        { 205, "Reset Content" },
        { 206, "Partial Content" },
        { 300, "Multiple Choices" },
        { 301, "Moved Permanently" },
        { 302, "Found" },
        { 303, "See Other" },
        { 304, "Not Modified" },
        { 305, "Use Proxy" },
        { 307, "Temporary Redirect" },
        { 400, "Bad Request" },
        { 401, "Unauthorized" },
        { 402, "Payment Required" },
        { 403, "Forbidden" },
        { 404, "Not Found" },
        { 405, "Method Not Allowed" },
        { 406, "Not Acceptable" },
        { 407, "Proxy Authentication Required" },
        { 408, "Request Time-out" },
        { 409, "Conflict" },
        { 410, "Gone" },
        { 411, "Length Required" },
        { 412, "Precondition Failed" },
        { 413, "Request Entity Too Large" },
        { 414, "Request-URI Too Large" },
        { 415, "Unsupported Media Type" },
        { 416, "Requested range not satisfiable" },
        { 417, "Expectation Failed" },
        { 500, "Internal Server Error" },
        { 501, "Not Implemented" },
        { 502, "Bad Gateway" },
        { 503, "Service Unavailable" },
        { 504, "Gateway Time-out" },
        { 505, "HTTP Version not supported" }
    };

    //!
    //! \brief create_reply
    //! create reply for sending to client
    //!
    //! \return QString reply to be sent
    //!
    QString create_reply();

private:
    //!
    //! \brief m_status
    //! HTTP response status
    //!
    quint16 m_status = 200;

    //!
    //! \brief header
    //! holds all header data as key/value
    //!

    QHash<QString, QString> m_headers;
    //!
    //! \brief m_body
    //! HTTP response content
    //!
    QString m_body;
};

// https://tools.ietf.org/html/rfc7230#page-19
inline QString Response::create_reply()
{
    QString reply = this->protocol % " " % QString::number(this->status()) % " "
    % this->http_codes[this->status()] % "\r\n";

    // set content length
    m_headers["content-length"] = QString::number(this->body().size());

    // set content type if not set
    if (!m_headers.contains("content-type"))
        m_headers["content-type"] = "text/plain";

    // set custom header fields
    for (auto i = m_headers.constBegin(); i != m_headers.constEnd(); ++i)
        reply = reply % i.key() % ": " % i.value() % "\r\n";

    reply += "\r\n";

    if (this->body().size())
        reply += this->body();

    return reply;
}

#endif
<|endoftext|>


<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file sigma_point_additive_update_policy.hpp
 * \date July 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__FILTER__GAUSSIAN__SIGMA_POINT_ADDITIVE_UPDATE_POLICY_HPP
#define FL__FILTER__GAUSSIAN__SIGMA_POINT_ADDITIVE_UPDATE_POLICY_HPP

#include <Eigen/Dense>

#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/filter/gaussian/transform/point_set.hpp>
#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>

namespace fl
{

// Forward declarations
template <typename...> class SigmaPointUpdatePolicy;

template <
    typename SigmaPointQuadrature,
    typename AdditiveObservationFunction
>
class SigmaPointUpdatePolicy<
          SigmaPointQuadrature,
          Additive<AdditiveObservationFunction>>
{
public:
    typedef typename AdditiveObservationFunction::State State;
    typedef typename AdditiveObservationFunction::Obsrv Obsrv;

    enum : signed int
    {
        NumberOfPoints = SigmaPointQuadrature
                             ::number_of_points(SizeOf<State>::Value)
    };

    typedef PointSet<State, NumberOfPoints> StatePointSet;
    typedef PointSet<Obsrv, NumberOfPoints> ObsrvPointSet;

    template <
        typename Belief
    >
    void operator()(const AdditiveObservationFunction& obsrv_function,
                    const SigmaPointQuadrature& quadrature,
                    const Belief& prior_belief,
                    const Obsrv& obsrv,
                    Belief& posterior_belief)
    {
        auto&& h = [=](const State& x)
        {
           return obsrv_function.expected_observation(x);
        };

        quadrature.integrate_to_points(h, prior_belief, X, Z);

        auto&& prediction = Z.center();
        auto&& Z_c = Z.points();
        auto&& W = X.covariance_weights_vector();
        auto&& X_c = X.centered_points();

        auto innovation = (obsrv - prediction).eval();
        auto cov_xx = (X_c * W.asDiagonal() * X_c.transpose()).eval();
        auto cov_yy = (Z_c * W.asDiagonal() * Z_c.transpose()
                       + obsrv_function.noise_covariance()).eval();
        auto cov_xy = (X_c * W.asDiagonal() * Z_c.transpose()).eval();
        auto K = (cov_xy * cov_yy.inverse()).eval();

        posterior_belief.mean(X.mean() + K * innovation);
        posterior_belief.covariance(cov_xx - K * cov_yy * K.transpose());
    }

protected:
    StatePointSet X;
    ObsrvPointSet Z;
};

}

#endif
<commit_msg>Implements Descriptor<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file sigma_point_additive_update_policy.hpp
 * \date July 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__FILTER__GAUSSIAN__SIGMA_POINT_ADDITIVE_UPDATE_POLICY_HPP
#define FL__FILTER__GAUSSIAN__SIGMA_POINT_ADDITIVE_UPDATE_POLICY_HPP

#include <Eigen/Dense>

#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/filter/gaussian/transform/point_set.hpp>
#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>

namespace fl
{

// Forward declarations
template <typename...> class SigmaPointUpdatePolicy;

template <
    typename SigmaPointQuadrature,
    typename AdditiveObservationFunction
>
class SigmaPointUpdatePolicy<
          SigmaPointQuadrature,
          Additive<AdditiveObservationFunction>>
    : public Descriptor
{
public:
    typedef typename AdditiveObservationFunction::State State;
    typedef typename AdditiveObservationFunction::Obsrv Obsrv;

    enum : signed int
    {
        NumberOfPoints = SigmaPointQuadrature
                             ::number_of_points(SizeOf<State>::Value)
    };

    typedef PointSet<State, NumberOfPoints> StatePointSet;
    typedef PointSet<Obsrv, NumberOfPoints> ObsrvPointSet;

    template <
        typename Belief
    >
    void operator()(const AdditiveObservationFunction& obsrv_function,
                    const SigmaPointQuadrature& quadrature,
                    const Belief& prior_belief,
                    const Obsrv& obsrv,
                    Belief& posterior_belief)
    {
        auto&& h = [=](const State& x)
        {
           return obsrv_function.expected_observation(x);
        };

        quadrature.integrate_to_points(h, prior_belief, X, Z);

        auto&& prediction = Z.center();
        auto&& Z_c = Z.points();
        auto&& W = X.covariance_weights_vector();
        auto&& X_c = X.centered_points();

        auto innovation = (obsrv - prediction).eval();
        auto cov_xx = (X_c * W.asDiagonal() * X_c.transpose()).eval();
        auto cov_yy = (Z_c * W.asDiagonal() * Z_c.transpose()
                       + obsrv_function.noise_covariance()).eval();
        auto cov_xy = (X_c * W.asDiagonal() * Z_c.transpose()).eval();
        auto K = (cov_xy * cov_yy.inverse()).eval();

        posterior_belief.mean(X.mean() + K * innovation);
        posterior_belief.covariance(cov_xx - K * cov_yy * K.transpose());
    }

    virtual std::string name() const
    {
        return "SigmaPointUpdatePolicy<"
                + list_arguments(
                       "SigmaPointQuadrature",
                       "Additive<AdditiveObservationFunction>")
                + ">";
    }

    virtual std::string description() const
    {
        return "Sigma Point based filter update policy for observation model"
               " with additive noise";
    }

protected:
    StatePointSet X;
    ObsrvPointSet Z;
};

}

#endif

<|endoftext|>


<commit_before>/*******************************************************************************
 * c7a/api/bootstrap.hpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_API_BOOTSTRAP_HEADER
#define C7A_API_BOOTSTRAP_HEADER

#include <c7a/api/context.hpp>

namespace c7a {

//! Executes the given job startpoint with a context instance
//! startpoint may be called multiple times with concurrent threads.
static int Execute(int argc, char* argv[], std::function<int(Context&)> job_startpoint)
{
    Context ctx;
    return job_startpoint(ctx);
}

} // namespace c7a

#endif // !C7A_API_BOOTSTRAP_HEADER

/******************************************************************************/
<commit_msg>simple argument parsing<commit_after>/*******************************************************************************
 * c7a/api/bootstrap.hpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_API_BOOTSTRAP_HEADER
#define C7A_API_BOOTSTRAP_HEADER

#include <tuple>

#include <c7a/api/context.hpp>

namespace c7a {
namespace bootstrap {

std::tuple<int, size_t, std::vector<std::string> > ParseArgs(int argc, char* argv[])
{
    //replace with arbitrary compex implementation
    size_t my_rank;
    std::vector<std::string> endpoints;
    if (argc > 2) {
        my_rank = atoi(argv[1]);
        endpoints.assign(argv + 2, argv + argc);
    }
    else if (argc == 2) {
        std::cerr << "Wrong number of arguments. Must be 0 or > 1";
        return std::make_tuple(-1, my_rank, endpoints);
    }
    else {
        my_rank = 0;
        endpoints.push_back("127.0.0.1:1234");
    }
    return std::make_tuple(0, my_rank, endpoints);
}
}   //namespace bootstrap

//! Executes the given job startpoint with a context instance.
//! Startpoint may be called multiple times with concurrent threads and
//! different context instances.
//!
//! \returns result of word_count if bootstrapping was successfull, -1 otherwise.
static int Execute(int argc, char* argv[], std::function<int(Context&)> job_startpoint)
{
    size_t my_rank;
    std::vector<std::string> endpoints;
    int result;
    std::tie(result, my_rank, endpoints) = bootstrap::ParseArgs(argc, argv);
    if (result != 0)
        return -1;

    if (my_rank >= endpoints.size()) {
        std::cerr << "endpoint list (" <<
            endpoints.size() <<
            " entries) does not include my rank (" <<
            my_rank << ")" << std::endl;
        return -1;
    }

    std::cout << "executing " << argv[0] << " with rank " << my_rank << " and endpoints ";
    for (const auto& ep : endpoints)
        std::cout << ep << " ";
    std::cout << std::endl;

    Context ctx;
    return job_startpoint(ctx);
}

} // namespace bootstrap

#endif // !C7A_API_BOOTSTRAP_HEADER

/******************************************************************************/
<|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

     char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
fprintf (stdout,"%s -> %d/n",s1,strlen(s1) );

	return 0;
}

#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

     char s1[]= "Hello, Mel. Today is sunday. Let's go party!";

	strcat(s1, "Melaniya!");
fprintf (stdout,"%s -> %d/n",s1,strlen(s1) );
	return 0;
}

Добавя "strcat":
strcat(s1, "- From team! :)");

Сравнява "strcmp":
strcmp("Hello", "Hello") = 0
strcmp(s1, "Hello") = 1
strcmp("Hello", s1) = -1

<commit_msg>Update experians.cpp<commit_after>#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

     char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
fprintf (stdout,"%s -> %d/n",s1,strlen(s1) );

	return 0;
}

=============================================================

#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

     char s1[]= "Hello, Mel. Today is sunday. Let's go party!";

	strcat(s1, "Melaniya!");
fprintf (stdout,"%s -> %d/n",s1,strlen(s1) );
	return 0;
}

===============================================

Добавя "strcat":
strcat(s1, "- From team! :)");

================================================

Сравнява "strcmp":
strcmp("Hello", "Hello") = 0
strcmp(s1, "Hello") = 1
strcmp("Hello", s1) = -1

================================================

<|endoftext|>


<commit_before>/*
 * BLAKE2.hpp: The BLAKE2 Hash function.
 *
 * Copyright (c) 2015-2016 Masashi Fujita
 */
#pragma once
#ifndef blake2_hpp__4a9213114a5fd6c034b25abd47c90326
#define blake2_hpp__4a9213114a5fd6c034b25abd47c90326    1

#include <cstddef>
#include <cstdint>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <array>
#include <memory>

namespace BLAKE2 {

    const size_t        BLOCK_SIZE = 128 ;      // Messages are processed per BLOCK_SIZE unit.

    class Digest ;

    using parameter_block_t = std::array<uint8_t, 64> ;

    const size_t OFF_DIGEST_LENGTH   =  0
               , OFF_KEY_LENGTH      =  1
               , OFF_FANOUT_COUNT    =  2
               , OFF_DEPTH           =  3
               , OFF_LEAF_LENGTH     =  4
               , OFF_NODE_OFFSET     =  8
               , OFF_NODE_DEPTH      = 16
               , OFF_INNER_LENGTH    = 17
               , OFF_SALT            = 32
               , OFF_PERSONALIZATION = 48 ;
    const size_t MAX_SALT_LENGTH = 16 ;
    const size_t MAX_PERSONALIZATION_LENGTH = 16 ;

    class Parameter {
    public:
        typedef Parameter       self_t ;
    private:
        parameter_block_t       p_ ;
    public:
        Parameter () ;

        Parameter (const Parameter &param) : Parameter { param.p_ } {
            /* NO-OP */
        }

        Parameter (const parameter_block_t &param) ;

        uint_fast8_t    GetDigestLength () const {
            return p_ [OFF_DIGEST_LENGTH] ;
        }

        self_t &        SetDigestLength (uint8_t value) {
            p_ [OFF_DIGEST_LENGTH] = value ;
            return *this ;
        }

        uint_fast8_t    GetKeyLength () const {
            return p_ [OFF_KEY_LENGTH] ;
        }

        self_t &        SetKeyLength (uint8_t value) {
            p_ [OFF_KEY_LENGTH] = value ;
            return *this ;
        }

        uint_fast8_t    GetFanoutCount () const {
            return p_ [OFF_FANOUT_COUNT] ;
        }

        self_t &        SetFanoutCount (uint8_t value) {
            p_ [OFF_FANOUT_COUNT] = value ;
            return *this ;
        }

        uint_fast8_t    GetDepth () const {
            return p_ [OFF_DEPTH] ;
        }

        self_t &        SetDepth (uint8_t value) {
            p_ [OFF_DEPTH] = value ;
            return *this ;
        }

        uint_fast32_t   GetLeafLength () const {
            return ( (static_cast<uint32_t> (p_ [OFF_LEAF_LENGTH + 0]) <<  0)
                   | (static_cast<uint32_t> (p_ [OFF_LEAF_LENGTH + 1]) <<  8)
                   | (static_cast<uint32_t> (p_ [OFF_LEAF_LENGTH + 2]) << 16)
                   | (static_cast<uint32_t> (p_ [OFF_LEAF_LENGTH + 3]) << 24));
        }

        self_t &        SetLeafLength (uint32_t value) {
            p_ [OFF_LEAF_LENGTH + 0] = static_cast<uint8_t> (value >>  0) ;
            p_ [OFF_LEAF_LENGTH + 1] = static_cast<uint8_t> (value >>  8) ;
            p_ [OFF_LEAF_LENGTH + 2] = static_cast<uint8_t> (value >> 16) ;
            p_ [OFF_LEAF_LENGTH + 3] = static_cast<uint8_t> (value >> 24) ;
            return *this ;
        }

        uint_fast64_t GetNodeOffset () const {
            return ( (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 0]) <<  0)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 1]) <<  8)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 2]) << 16)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 3]) << 24)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 4]) << 32)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 5]) << 40)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 6]) << 48)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 7]) << 56));
        }

        self_t &        SetNodeOffset (uint64_t value) {
            p_ [OFF_NODE_OFFSET + 0] = static_cast<uint8_t> (value >>  0) ;
            p_ [OFF_NODE_OFFSET + 1] = static_cast<uint8_t> (value >>  8) ;
            p_ [OFF_NODE_OFFSET + 2] = static_cast<uint8_t> (value >> 16) ;
            p_ [OFF_NODE_OFFSET + 3] = static_cast<uint8_t> (value >> 24) ;
            p_ [OFF_NODE_OFFSET + 4] = static_cast<uint8_t> (value >> 32) ;
            p_ [OFF_NODE_OFFSET + 5] = static_cast<uint8_t> (value >> 40) ;
            p_ [OFF_NODE_OFFSET + 6] = static_cast<uint8_t> (value >> 48) ;
            p_ [OFF_NODE_OFFSET + 7] = static_cast<uint8_t> (value >> 56) ;
            return *this ;
        }

        uint_fast8_t    GetNodeDepth () const {
            return p_ [OFF_NODE_DEPTH] ;
        }

        self_t &        SetNodeDepth (uint8_t value) {
            p_ [OFF_NODE_DEPTH] = value ;
            return *this ;
        }

        const void *    GetSalt () const {
            return &p_ [OFF_SALT] ;
        }

        self_t &        SetSalt (const void *salt, size_t length) ;

        const void *    GetPersonalization () const {
            return &p_ [OFF_PERSONALIZATION] ;
        }

        self_t &        SetPersonalization (const void *data, size_t length) ;

        const parameter_block_t &       GetParameterBlock () const {
            return p_ ;
        }

        void    CopyTo (parameter_block_t &param) const ;

        operator const parameter_block_t & () const {
            return p_ ;
        }
    } ;

    /**
     * 512bits digest value.
     */
    class Digest {
    public:
        static constexpr size_t SIZE = 64 ;     // # of bytes in digest.
    private:
        std::array<uint8_t, SIZE>   h_ ;
    public:
        Digest () {
            h_.fill (0) ;
        }

        Digest (uint64_t h0, uint64_t h1, uint64_t h2, uint64_t h3,
                uint64_t h4, uint64_t h5, uint64_t h6, uint64_t h7) ;

        Digest (const Digest &src) {
            h_ = src.h_ ;
        }

        Digest &        Assign (const Digest &src) {
            h_ = src.h_ ;
            return *this ;
        }

        Digest &        operator = (const Digest &src) {
            return Assign (src) ;
        }

        void    CopyTo (void *buffer, size_t buffer_length) const ;

        const uint8_t * GetBytes () const {
            return h_.data () ;
        }

        const uint8_t * data () const {
            return h_.data () ;
        }

        constexpr size_t size () const {
            return h_.size () ;
        }

        uint_fast8_t    At (size_t offset) const {
            return h_ [offset] ;
        }

        uint_fast8_t    operator [] (size_t offset) const {
            return h_ [offset] ;
        }

        uint_fast64_t   GetUInt64 (size_t idx) const ;
    public:
        static constexpr size_t digestSize () {
            return SIZE ;
        }

        static bool     IsEqual (const Digest &a, const Digest &b) {
            return a.h_ == b.h_ ;
        }
    } ;

    class Generator {
    private:
        enum {
            BIT_FINALIZED = 0,
            BIT_LAST_NODE = 1
        } ;
        static const size_t     BUFFER_SIZE = 2 * BLOCK_SIZE ;
    private:
        uint64_t        h_ [8] ;
        uint64_t        t0_ ;
        uint64_t        t1_ ;
        int32_t         used_ ;
        uint32_t        flags_ ;
        std::unique_ptr<std::array<uint8_t, BUFFER_SIZE> >  buffer_ ;
        /*
         * buffer_ --> +----------------+
         *             |                |
         *             :    128bytes    :
         *             |                |
         *             +----------------+
         *             |                |
         *             :    128bytes    :
         *             |                |
         *             +----------------+
         * Note: Due to last block compression scheme, we must hold the last message.
         */
    public:
        ~Generator () ;

        Generator (const parameter_block_t &param) ;

        Generator (const parameter_block_t &param, const void *key, size_t key_len) ;

        Generator &     Update (const void *data, size_t size) ;

        Digest  Finalize () ;
    private:
        bool    IsFinalized () const {
            return (flags_ & (1u << BIT_FINALIZED)) != 0 ;
        }

        bool    IsLastNode () const {
            return (flags_ & (1u << BIT_LAST_NODE)) != 0 ;
        }
    } ;

    void    InitializeChain (uint64_t *chain) ;
    void    InitializeChain (uint64_t *chain, const parameter_block_t &param) ;

    void    Compress ( uint64_t *   chain
                     , const void * message
                     , uint64_t     t0
                     , uint64_t     t1
                     , uint64_t     f0
                     , uint64_t     f1);

    /**
     * Convenience function for generating a digest.
     *
     * @param key Key to apply
     * @param key_length Key length
     * @param data Data to compute digest
     * @param data_length Data length
     *
     * @return Computed digest
     */
    Digest  Apply (const void *key, size_t key_length, const void *data, size_t data_length) ;

    /**
     * Convenience function for generating a digest.
     *
     * @param param Generation parameters
     * @param key Key to apply
     * @param key_length Key length
     * @param data Data to compute digest
     * @param data_length Data length
     *
     * @return Computed digest.
     */
    Digest  Apply (const parameter_block_t &param, const void *key, size_t key_length, const void *data, size_t data_length) ;
}

inline bool operator == (const BLAKE2::Digest &a, const BLAKE2::Digest &b) {
    return BLAKE2::Digest::IsEqual (a, b) ;
}

inline bool operator != (const BLAKE2::Digest &a, const BLAKE2::Digest &b) {
    return (! BLAKE2::Digest::IsEqual (a, b)) ;
}

#endif  /* blake2_hpp__4a9213114a5fd6c034b25abd47c90326 */
<commit_msg>feat: Add `begin`/`end` for easy element iteration<commit_after>/*
 * BLAKE2.hpp: The BLAKE2 Hash function.
 *
 * Copyright (c) 2015-2016 Masashi Fujita
 */
#pragma once
#ifndef blake2_hpp__4a9213114a5fd6c034b25abd47c90326
#define blake2_hpp__4a9213114a5fd6c034b25abd47c90326    1

#include <cstddef>
#include <cstdint>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <array>
#include <memory>

namespace BLAKE2 {

    const size_t        BLOCK_SIZE = 128 ;      // Messages are processed per BLOCK_SIZE unit.

    class Digest ;

    using parameter_block_t = std::array<uint8_t, 64> ;

    const size_t OFF_DIGEST_LENGTH   =  0
               , OFF_KEY_LENGTH      =  1
               , OFF_FANOUT_COUNT    =  2
               , OFF_DEPTH           =  3
               , OFF_LEAF_LENGTH     =  4
               , OFF_NODE_OFFSET     =  8
               , OFF_NODE_DEPTH      = 16
               , OFF_INNER_LENGTH    = 17
               , OFF_SALT            = 32
               , OFF_PERSONALIZATION = 48 ;
    const size_t MAX_SALT_LENGTH = 16 ;
    const size_t MAX_PERSONALIZATION_LENGTH = 16 ;

    class Parameter {
    public:
        typedef Parameter       self_t ;
    private:
        parameter_block_t       p_ ;
    public:
        Parameter () ;

        Parameter (const Parameter &param) : Parameter { param.p_ } {
            /* NO-OP */
        }

        Parameter (const parameter_block_t &param) ;

        uint_fast8_t    GetDigestLength () const {
            return p_ [OFF_DIGEST_LENGTH] ;
        }

        self_t &        SetDigestLength (uint8_t value) {
            p_ [OFF_DIGEST_LENGTH] = value ;
            return *this ;
        }

        uint_fast8_t    GetKeyLength () const {
            return p_ [OFF_KEY_LENGTH] ;
        }

        self_t &        SetKeyLength (uint8_t value) {
            p_ [OFF_KEY_LENGTH] = value ;
            return *this ;
        }

        uint_fast8_t    GetFanoutCount () const {
            return p_ [OFF_FANOUT_COUNT] ;
        }

        self_t &        SetFanoutCount (uint8_t value) {
            p_ [OFF_FANOUT_COUNT] = value ;
            return *this ;
        }

        uint_fast8_t    GetDepth () const {
            return p_ [OFF_DEPTH] ;
        }

        self_t &        SetDepth (uint8_t value) {
            p_ [OFF_DEPTH] = value ;
            return *this ;
        }

        uint_fast32_t   GetLeafLength () const {
            return ( (static_cast<uint32_t> (p_ [OFF_LEAF_LENGTH + 0]) <<  0)
                   | (static_cast<uint32_t> (p_ [OFF_LEAF_LENGTH + 1]) <<  8)
                   | (static_cast<uint32_t> (p_ [OFF_LEAF_LENGTH + 2]) << 16)
                   | (static_cast<uint32_t> (p_ [OFF_LEAF_LENGTH + 3]) << 24));
        }

        self_t &        SetLeafLength (uint32_t value) {
            p_ [OFF_LEAF_LENGTH + 0] = static_cast<uint8_t> (value >>  0) ;
            p_ [OFF_LEAF_LENGTH + 1] = static_cast<uint8_t> (value >>  8) ;
            p_ [OFF_LEAF_LENGTH + 2] = static_cast<uint8_t> (value >> 16) ;
            p_ [OFF_LEAF_LENGTH + 3] = static_cast<uint8_t> (value >> 24) ;
            return *this ;
        }

        uint_fast64_t GetNodeOffset () const {
            return ( (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 0]) <<  0)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 1]) <<  8)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 2]) << 16)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 3]) << 24)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 4]) << 32)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 5]) << 40)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 6]) << 48)
                   | (static_cast<uint64_t> (p_ [OFF_NODE_OFFSET + 7]) << 56));
        }

        self_t &        SetNodeOffset (uint64_t value) {
            p_ [OFF_NODE_OFFSET + 0] = static_cast<uint8_t> (value >>  0) ;
            p_ [OFF_NODE_OFFSET + 1] = static_cast<uint8_t> (value >>  8) ;
            p_ [OFF_NODE_OFFSET + 2] = static_cast<uint8_t> (value >> 16) ;
            p_ [OFF_NODE_OFFSET + 3] = static_cast<uint8_t> (value >> 24) ;
            p_ [OFF_NODE_OFFSET + 4] = static_cast<uint8_t> (value >> 32) ;
            p_ [OFF_NODE_OFFSET + 5] = static_cast<uint8_t> (value >> 40) ;
            p_ [OFF_NODE_OFFSET + 6] = static_cast<uint8_t> (value >> 48) ;
            p_ [OFF_NODE_OFFSET + 7] = static_cast<uint8_t> (value >> 56) ;
            return *this ;
        }

        uint_fast8_t    GetNodeDepth () const {
            return p_ [OFF_NODE_DEPTH] ;
        }

        self_t &        SetNodeDepth (uint8_t value) {
            p_ [OFF_NODE_DEPTH] = value ;
            return *this ;
        }

        const void *    GetSalt () const {
            return &p_ [OFF_SALT] ;
        }

        self_t &        SetSalt (const void *salt, size_t length) ;

        const void *    GetPersonalization () const {
            return &p_ [OFF_PERSONALIZATION] ;
        }

        self_t &        SetPersonalization (const void *data, size_t length) ;

        const parameter_block_t &       GetParameterBlock () const {
            return p_ ;
        }

        void    CopyTo (parameter_block_t &param) const ;

        operator const parameter_block_t & () const {
            return p_ ;
        }
    } ;

    /**
     * 512bits digest value.
     */
    class Digest {
    public:
        static constexpr size_t SIZE = 64 ;     // # of bytes in digest.
    private:
        std::array<uint8_t, SIZE>   h_ ;
    public:
        Digest () {
            h_.fill (0) ;
        }

        Digest (uint64_t h0, uint64_t h1, uint64_t h2, uint64_t h3,
                uint64_t h4, uint64_t h5, uint64_t h6, uint64_t h7) ;

        Digest (const Digest &src) {
            h_ = src.h_ ;
        }

        Digest &        Assign (const Digest &src) {
            h_ = src.h_ ;
            return *this ;
        }

        Digest &        operator = (const Digest &src) {
            return Assign (src) ;
        }

        void    CopyTo (void *buffer, size_t buffer_length) const ;

        const uint8_t * GetBytes () const {
            return h_.data () ;
        }

        const uint8_t * data () const {
            return h_.data () ;
        }

        constexpr size_t size () const {
            return h_.size () ;
        }

        uint_fast8_t    At (size_t offset) const {
            return h_ [offset] ;
        }

        uint_fast8_t    operator [] (size_t offset) const {
            return h_ [offset] ;
        }

        uint_fast64_t   GetUInt64 (size_t idx) const ;

        auto begin () const {
            return h_.begin () ;
        }

        auto end () const {
            return h_.end () ;
        }
    public:
        static constexpr size_t digestSize () {
            return SIZE ;
        }

        static bool     IsEqual (const Digest &a, const Digest &b) {
            return a.h_ == b.h_ ;
        }
    } ;

    class Generator {
    private:
        enum {
            BIT_FINALIZED = 0,
            BIT_LAST_NODE = 1
        } ;
        static const size_t     BUFFER_SIZE = 2 * BLOCK_SIZE ;
    private:
        uint64_t        h_ [8] ;
        uint64_t        t0_ ;
        uint64_t        t1_ ;
        int32_t         used_ ;
        uint32_t        flags_ ;
        std::unique_ptr<std::array<uint8_t, BUFFER_SIZE> >  buffer_ ;
        /*
         * buffer_ --> +----------------+
         *             |                |
         *             :    128bytes    :
         *             |                |
         *             +----------------+
         *             |                |
         *             :    128bytes    :
         *             |                |
         *             +----------------+
         * Note: Due to last block compression scheme, we must hold the last message.
         */
    public:
        ~Generator () ;

        Generator (const parameter_block_t &param) ;

        Generator (const parameter_block_t &param, const void *key, size_t key_len) ;

        Generator &     Update (const void *data, size_t size) ;

        Digest  Finalize () ;
    private:
        bool    IsFinalized () const {
            return (flags_ & (1u << BIT_FINALIZED)) != 0 ;
        }

        bool    IsLastNode () const {
            return (flags_ & (1u << BIT_LAST_NODE)) != 0 ;
        }
    } ;

    void    InitializeChain (uint64_t *chain) ;
    void    InitializeChain (uint64_t *chain, const parameter_block_t &param) ;

    void    Compress ( uint64_t *   chain
                     , const void * message
                     , uint64_t     t0
                     , uint64_t     t1
                     , uint64_t     f0
                     , uint64_t     f1);

    /**
     * Convenience function for generating a digest.
     *
     * @param key Key to apply
     * @param key_length Key length
     * @param data Data to compute digest
     * @param data_length Data length
     *
     * @return Computed digest
     */
    Digest  Apply (const void *key, size_t key_length, const void *data, size_t data_length) ;

    /**
     * Convenience function for generating a digest.
     *
     * @param param Generation parameters
     * @param key Key to apply
     * @param key_length Key length
     * @param data Data to compute digest
     * @param data_length Data length
     *
     * @return Computed digest.
     */
    Digest  Apply (const parameter_block_t &param, const void *key, size_t key_length, const void *data, size_t data_length) ;
}

inline bool operator == (const BLAKE2::Digest &a, const BLAKE2::Digest &b) {
    return BLAKE2::Digest::IsEqual (a, b) ;
}

inline bool operator != (const BLAKE2::Digest &a, const BLAKE2::Digest &b) {
    return (! BLAKE2::Digest::IsEqual (a, b)) ;
}

#endif  /* blake2_hpp__4a9213114a5fd6c034b25abd47c90326 */
<|endoftext|>


<commit_before>
#include "queen.h"
#include "board.h"
void queen::setMoves(board* bin)
{

        for(int xdir = -1;xdir<=1;xdir+=2)
        {
                int x,y;
                for (int dis = 1; dis <= 7; dis++) {
                        x = getX() + xdir*dis;
                        y = getY();
                        if(inbounds(x,y) && bin -> isOccupied(x,y))
                        {
                                if(bin -> getTeam(x,y) != getTeam())
                                {
                                        addMove(x,y);
                                }
                                break;
                        }
                        if(inbounds(x,y))
                        {
                                addMove(x,y);
                        }
                        else
                        {
                                break;
                        }
                }
        }

        for(int ydir = -1; ydir<=1; ydir+=2)
        {
                int x,y;
                for (int dis = 1; dis <= 7; dis++) {
                        x = getX();
                        y = getY() + ydir*dis;

                        if(inbounds(x,y) && bin -> isOccupied(x,y))
                        {
                                if(bin -> getTeam(x,y) != getTeam())
                                {
                                        addMove(x,y);
                                }
                                break;
                        }
                        if(inbounds(x,y))
                        {
                                addMove(x,y);
                        }
                        else
                        {
                                break;
                        }
                }
        }

        for(int xdir = -1;xdir<=1;xdir+=2)
        {
                for(int ydir = -1;ydir<=1;ydir+=2)
                {
                        for (int dis = 1; dis <= 7; dis++)
                        {
                                int x;
                                int y;

                                x = getX() + xdir*dis;
                                y = getY() + ydir*dis;

                                if(inbounds(x,y) && bin -> isOccupied(x,y))
                                {
                                        if(bin -> getTeam(x,y) != getTeam())
                                        {
                                                addMove(x,y);
                                        }
                                        break;
                                }
                                if(inbounds(x,y))
                                {
                                        addMove(x,y);
                                }
                                else
                                {
                                        break;
                                }
                        }
                }
        }

}

void queen::print()
{
        if(getTeam())
                std::cout<<'q';
        else
                std::cout<<'Q';
}

std::vector<int*>* queen::getAttacks()
{
        return getMoves();
}

queen::queen(int x, int y, bool team) : piece(x,y,team)
{
        setType(QUEEN);
}
queen::~queen(){}<commit_msg>Added comments to the queen piece<commit_after>//Queen implementation file that allows the queen to move left, right, up, down and diagonal any number of spaces.
#include "queen.h"
#include "board.h"
void queen::setMoves(board* bin)
{

        for(int xdir = -1;xdir<=1;xdir+=2)
        {
                int x,y;
                for (int dis = 1; dis <= 7; dis++) {
                        x = getX() + xdir*dis; //allows the piece to move to the right
                        y = getY();
                        if(inbounds(x,y) && bin -> isOccupied(x,y))
                        { //if inbounds, adds move
                                if(bin -> getTeam(x,y) != getTeam())
                                {
                                        addMove(x,y);
                                }
                                break;
                        }
                        if(inbounds(x,y))
                        {
                                addMove(x,y);
                        }
                        else
                        {
                                break;
                        }
                }
        }

        for(int ydir = -1; ydir<=1; ydir+=2)
        {
                int x,y;
                for (int dis = 1; dis <= 7; dis++) {
                        x = getX();
                        y = getY() + ydir*dis; //allows the piece to move up or down

                        if(inbounds(x,y) && bin -> isOccupied(x,y))
                        { //checks to ensure the move is in the bounds of the board and not moving through other pieces
                                if(bin -> getTeam(x,y) != getTeam())
                                {
                                        addMove(x,y);
                                }
                                break;
                        }
                        if(inbounds(x,y))
                        {
                                addMove(x,y);
                        }
                        else
                        {
                                break;
                        }
                }
        }

        for(int xdir = -1;xdir<=1;xdir+=2)
        {
                for(int ydir = -1;ydir<=1;ydir+=2)
                {
                        for (int dis = 1; dis <= 7; dis++)
                        {
                                int x;
                                int y;

                                x = getX() + xdir*dis; //allows the piece to move diagonally
                                y = getY() + ydir*dis;

                                if(inbounds(x,y) && bin -> isOccupied(x,y))
                                {
                                        if(bin -> getTeam(x,y) != getTeam())
                                        {
                                                addMove(x,y);
                                        }
                                        break;
                                }
                                if(inbounds(x,y))
                                {
                                        addMove(x,y);
                                }
                                else
                                {
                                        break;
                                }
                        }
                }
        }

}

void queen::print() //prints the queen on the board, q or Q depending on black or white pieces
{
        if(getTeam())
                std::cout<<'q';
        else
                std::cout<<'Q';
}

std::vector<int*>* queen::getAttacks()
{
        return getMoves();
}

queen::queen(int x, int y, bool team) : piece(x,y,team)
{
        setType(QUEEN);
}
queen::~queen(){}
<|endoftext|>


<commit_before>#ifndef __COLORS
#define __COLORS

// Use it like:
//   std::cout << RED << "My red message" << RST << std::endl;
// Remember to issue RST to reset color.

#define RST "\x1B[0m"

#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"

#define BOLD "\x1B[1m"
#define UNDL "\x1B[4m"

#endif  // __COLORS
<commit_msg>No colors in non-TTY<commit_after>#ifndef __COLORS
#define __COLORS

#include <unistd.h>

// Use it like:
//   std::cout << RED << "My red message" << RST << std::endl;
// Remember to issue RST to reset color.

#define RST (isatty(1) ? "\x1B[0m" : "")

#define RED (isatty(1) ? "\x1B[31m" : "")
#define GRN (isatty(1) ? "\x1B[32m" : "")
#define YEL (isatty(1) ? "\x1B[33m" : "")
#define BLU (isatty(1) ? "\x1B[34m" : "")
#define MAG (isatty(1) ? "\x1B[35m" : "")
#define CYN (isatty(1) ? "\x1B[36m" : "")
#define WHT (isatty(1) ? "\x1B[37m" : "")

#define BOLD (isatty(1) ? "\x1B[1m" : "")
#define UNDL (isatty(1) ? "\x1B[4m" : "")

#endif  // __COLORS
<|endoftext|>