text:
/*  Sirikata
 *  Entity.cpp
 *
 *  Copyright (c) 2009, Patrick Reiter Horn
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *  * Neither the name of Sirikata nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <boost/lexical_cast.hpp>
#include <sirikata/ogre/Entity.hpp>
#include <sirikata/ogre/OgreRenderer.hpp>
#include <sirikata/ogre/OgreHeaders.hpp>
#include <sirikata/ogre/Lights.hpp>
#include <sirikata/core/transfer/URL.hpp>
#include <sirikata/ogre/Util.hpp>
#include <OgreEntity.h>
#include <OgreSubEntity.h>
#include <OgreBillboardSet.h>
#include <OgreAnimationState.h>
#include <OgreMeshManager.h>

using namespace Sirikata::Transfer;

namespace Sirikata {
namespace Graphics {

using namespace Sirikata::Mesh;

EntityListener::~EntityListener() {
}

class ReplaceTexture {
	const String &mFrom;
	const String &mTo;
public:
	ReplaceTexture(const String &from, const String &to)
		: mFrom(from),
		  mTo(to) {
	}
	bool operator()(Ogre::TextureUnitState *tus) {
		if (tus->getTextureName() == mFrom) {
			tus->setTextureName(mTo);
		}
		return false;
	}
};

class ShouldReplaceTexture {
    const TextureBindingsMap &mFrom;
public:
    ShouldReplaceTexture(const TextureBindingsMap &from)
     : mFrom(from)
    {
    }
    bool operator()(Ogre::TextureUnitState *tus) {
        if (mFrom.find(tus->getTextureName()) != mFrom.end()) {
            return true;
        }
        return false;
    }
};

template <class Functor>
bool forEachTexture(const Ogre::MaterialPtr &material, Functor func) {
	int numTechniques = material->getNumTechniques();
	for (int whichTechnique = 0; whichTechnique < numTechniques; whichTechnique++) {
		Ogre::Technique *tech = material->getTechnique(whichTechnique);
		int numPasses = tech->getNumPasses();
		for (int whichPass = 0; whichPass < numPasses; whichPass++) {
			Ogre::Pass *pass = tech->getPass(whichPass);
			int numTUS = pass->getNumTextureUnitStates();
			for (int whichTUS = 0; whichTUS < numTUS; whichTUS++) {
				Ogre::TextureUnitState *tus = pass->getTextureUnitState(whichTUS);
				if (func(tus)) {
					return true;
				}
			}
		}
	}
	return false;
}

Entity::Entity(OgreRenderer *scene, const String& name)
 : mScene(scene),
   mName(name),
   mOgreObject(NULL),
   mSceneNode(scene->getSceneManager()->createSceneNode( ogreMeshName(name) )),
   mMovingIter(scene->mMovingEntities.end()),
   mVisible(true),
   mCurrentAnimation(NULL),
   mInitialAnimationName(""),
   mMeshLoaded(false)
{
    mSceneNode->setInheritScale(false);
    addToScene(NULL);

    bool successful = scene->mSceneEntities.insert(
        OgreRenderer::SceneEntitiesMap::value_type(mName, this)).second;

    assert (successful == true);

    unload();
}

Entity::~Entity() {
    Ogre::Entity * toDestroy=getOgreEntity();
    init(NULL);
    if (toDestroy) {
        getScene()->getSceneManager()->destroyEntity(toDestroy);

    }

    OgreRenderer::SceneEntitiesMap::iterator iter =
        mScene->mSceneEntities.find(mName);
    if (iter != mScene->mSceneEntities.end()) {
        // will fail while in the OgreRenderer destructor.
        mScene->mSceneEntities.erase(iter);
    }
    if (mMovingIter != mScene->mMovingEntities.end()) {
        mScene->mMovingEntities.erase(mMovingIter);
        mMovingIter = mScene->mMovingEntities.end();
    }

    bool mobVal = false;
    removeFromScene(&mobVal);
    init(NULL);
    mSceneNode->detachAllObjects();
    /* detaches all children from the scene.
       There should be none, as the server should have adjusted their parents.
     */
    mSceneNode->removeAllChildren();
    mScene->getSceneManager()->destroySceneNode(mSceneNode);
}

std::string Entity::ogreMeshName(const String& name) {
    return "Mesh:"+name;
}
std::string Entity::ogreMovableName()const{
    return ogreMeshName(id());
}

Entity *Entity::fromMovableObject(Ogre::MovableObject *movable) {
    return Ogre::any_cast<Entity*>(movable->getUserAny());
}

Ogre::Entity* Entity::getOgreEntity() const {
    return dynamic_cast<Ogre::Entity*>(mOgreObject);
}
Ogre::BillboardSet* Entity::getOgreBillboard() const {
    return dynamic_cast<Ogre::BillboardSet*>(mOgreObject);
}

void Entity::init(Ogre::MovableObject *obj) {
    if (mOgreObject) {
        mSceneNode->detachObject(mOgreObject);
    }
    mOgreObject = obj;
    if (obj) {
        mOgreObject->setUserAny(Ogre::Any(this));
        mSceneNode->attachObject(obj);
        updateScale( this->bounds().radius() );
        updateVisibility();
    }
}

void Entity::updateScale(float scale) {
    if (mSceneNode == NULL || mOgreObject == NULL) return;
    mSceneNode->setScale( 1.f, 1.f, 1.f );
    float rad = mOgreObject->getBoundingRadius();
    float rad_factor = scale / rad;
    mSceneNode->setScale( rad_factor, rad_factor, rad_factor );
}

void Entity::setDynamic(bool dyn) {
    const std::list<Entity*>::iterator end = mScene->mMovingEntities.end();
    if (!dyn) {
        if (mMovingIter != end) {
            SILOG(ogre,detailed,"Removed "<<this<<" from moving entities queue.");
            mScene->mMovingEntities.erase(mMovingIter);
            mMovingIter = end;
        }
    } else {
        if (mMovingIter == end) {
            SILOG(ogre,detailed,"Added "<<this<<" to moving entities queue.");
            mMovingIter = mScene->mMovingEntities.insert(end, this);
        }
    }
}

void Entity::checkDynamic() {
    bool isDyn = this->isDynamic();
    setDynamic(isDyn);
}

void Entity::setVisible(bool vis) {
    mVisible = vis;
    updateVisibility();
}

void Entity::setAnimation(const String& name, bool* mobileVal)
{
    // Disable current animation if we have one
    if (mCurrentAnimation) {
        mCurrentAnimation->setEnabled(false);
        mCurrentAnimation = NULL;
        if (mobileVal)
            setDynamic(mobileVal);
        else
            setDynamic(isMobile());
    }

    if (name.empty()) return;

    if (mOgreObject == NULL || mMeshLoaded == false) {
      mInitialAnimationName = name;
      return;
    }

    if (mAnimationList.count(name) == 0) {
      return;
    }

    // Find and enable new animation
    Ogre::Entity* ent = getOgreEntity();
    if (ent == NULL)  {
        SILOG(ogre,error,"Tried to set animation on non-mesh.");
        return;
    }
    Ogre::AnimationState* state = ent->getAnimationState(name);
    if (state == NULL) {
        SILOG(ogre,error,"Tried to set animation to non-existant track.");
        return;
    }

    state->setEnabled(true);
    state->setLoop(true);
    state->setTimePosition(0.f);
    mCurrentAnimation = state;

    checkDynamic();
}

void Entity::updateVisibility() {
    mSceneNode->setVisible(mVisible, true);
}

void Entity::removeFromScene(bool* checkMobile)
{
    Ogre::SceneNode *oldParent = mSceneNode->getParentSceneNode();
    if (oldParent) {
        oldParent->removeChild(mSceneNode);
    }
    // Force dynamicity off
    setAnimation("",checkMobile);
    setDynamic(false);
}
void Entity::addToScene(Ogre::SceneNode *newParent) {
    if (newParent == NULL) {
        newParent = mScene->getSceneManager()->getRootSceneNode();
    }
    removeFromScene();
    newParent->addChild(mSceneNode);
    checkDynamic();
}

bool Entity::isDynamic() const {
    return (mCurrentAnimation != NULL);
}

void Entity::tick(const Time& t, const Duration& deltaTime) {
    if (mCurrentAnimation)
        mCurrentAnimation->addTime(deltaTime.seconds());

    checkDynamic();
}

void Entity::setOgrePosition(const Vector3d &pos) {
    //SILOG(ogre,detailed,"setOgrePosition "<<this<<" to "<<pos);
    Ogre::Vector3 ogrepos = toOgre(pos, getScene()->getOffset());
    const Ogre::Vector3 &scale = mSceneNode->getScale();
    mSceneNode->setPosition(ogrepos);
}

void Entity::setOgreOrientation(const Quaternion &orient) {
    //SILOG(ogre,detailed,"setOgreOrientation "<<this<<" to "<<orient);
    mSceneNode->setOrientation(toOgre(orient));
}

Vector3d Entity::getOgrePosition() {
    if (mScene == NULL) assert(false);
    return fromOgre(mSceneNode->getPosition(), mScene->getOffset());
}

Quaternion Entity::getOgreOrientation() {
    return fromOgre(mSceneNode->getOrientation());
}

void Entity::fixTextures() {
	Ogre::Entity *ent = getOgreEntity();
	if (!ent) {
		return;
	}
	SILOG(ogre,detailed,"Fixing texture for "<<id());
	int numSubEntities = ent->getNumSubEntities();
	for (ReplacedMaterialMap::iterator iter = mReplacedMaterials.begin();
			iter != mReplacedMaterials.end();
			++iter) {
		int whichSubEntity = iter->first;
		if (whichSubEntity >= numSubEntities) {
			SILOG(ogre,fatal,"Original material map not cleared when mesh changed. which = " << whichSubEntity << " num = " << numSubEntities);
			continue;
		}
		Ogre::SubEntity *subEnt = ent->getSubEntity(whichSubEntity);
		Ogre::MaterialPtr origMaterial = iter->second.second;
		subEnt->setMaterial(origMaterial);
		SILOG(ogre,detailed,"Resetting a material "<<id());
	}
	mReplacedMaterials.clear();
	for (int whichSubEntity = 0; whichSubEntity < numSubEntities; whichSubEntity++) {
		Ogre::SubEntity *subEnt = ent->getSubEntity(whichSubEntity);
		Ogre::MaterialPtr material = subEnt->getMaterial();
		if (forEachTexture(material, ShouldReplaceTexture(mTextureBindings))) {
			SILOG(ogre,detailed,"Replacing a material "<<id());
			Ogre::MaterialPtr newMaterial = material->clone(material->getName()+id(), false, Ogre::String());
			String newTexture;
			for (TextureBindingsMap::const_iterator iter = mTextureBindings.begin();
					iter != mTextureBindings.end();
					++iter) {
				SILOG(ogre,detailed,"Replacing a texture "<<id()<<" : "<<iter->first<<" -> "<<iter->second);
				forEachTexture(newMaterial, ReplaceTexture(iter->first, iter->second));
				newTexture = iter->second;
			}
			mReplacedMaterials.insert(
				ReplacedMaterialMap::value_type(whichSubEntity, std::pair<String, Ogre::MaterialPtr>(newTexture, newMaterial)));
			subEnt->setMaterial(newMaterial);
		}
	}
}

void Entity::bindTexture(const std::string &textureName, const String& objId) {
	mTextureBindings[textureName] = objId;
	fixTextures();
}
void Entity::unbindTexture(const std::string &textureName) {
	TextureBindingsMap::iterator iter = mTextureBindings.find(textureName);
	if (iter != mTextureBindings.end()) {
		mTextureBindings.erase(iter);
	}
	fixTextures();
}

namespace {

// If a mesh had already been downloaded (by us or someone else), we have
// the hash, *and* the object still exists, we should be able to just add it
// to the scene.
bool ogreHasAsset(const String& meshname) {
    Ogre::MeshPtr mp = Ogre::MeshManager::getSingleton().getByName(meshname);
    return !mp.isNull();
}

}

void Entity::beginLoad() {
    // first reset any animations.
    setAnimation("");

    setDynamic(isMobile());
    if (mCurrentAnimation) {
      mCurrentAnimation->setEnabled(false);
      mCurrentAnimation = NULL;
    }
    mAnimationList.clear();

    // Clear out any old data if we have any left
    unload();
}

void Entity::loadEmpty() {
    beginLoad();
    mMeshLoaded = false;
}

void Entity::loadMesh(Mesh::MeshdataPtr meshdata, const String& meshname, const std::set<String>& animations)
{
    beginLoad();

    mAnimationList = animations;

    if (!ogreHasAsset(meshname)) {
        SILOG(ogre, error, "Requested load of asset that hasn't been loaded into Ogre (" << meshname << ")");
        return;
    }

    Ogre::Entity* new_entity = NULL;
    try {
      try {
        new_entity = getScene()->getSceneManager()->createEntity(
            ogreMovableName(), meshname);
      } catch (Ogre::InvalidParametersException &) {
        SILOG(ogre,error,"Got invalid parameters");
        throw;
      }
    } catch (...) {
        SILOG(ogre,error,"Failed to load mesh "<< meshname << " (id "<<id()<<")!");
        return;
    }

    SILOG(ogre,detailed,"Bounding box: " << new_entity->getBoundingBox());

    unsigned int num_subentities=new_entity->getNumSubEntities();
    SHA256 random_seed=SHA256::computeDigest(id());
    const SHA256::Digest &digest=random_seed.rawData();
    Ogre::Vector4 parallax_steps(getScene()->parallaxSteps(), getScene()->parallaxShadowSteps(),0.0,1.0);
    unsigned short av=digest[0]+256*(unsigned short)digest[1];
    unsigned short bv=digest[2]+256*(unsigned short)digest[3];
    unsigned short cv=digest[4]+256*(unsigned short)digest[5];
    unsigned short dv=digest[6]+256*(unsigned short)digest[7];
    unsigned short ev=digest[8]+256*(unsigned short)digest[9];
    unsigned short fv=digest[10]+256*(unsigned short)digest[11];
    Ogre::Vector4 random_values((float)av/65535.0f,(float)bv/65535.0f,(float)cv/65535.0f,1.0);
    random_values.x=random_values.x*.0+1.0;//fixme: make this per object
    random_values.y=random_values.y*.0+1.0;
    random_values.z=random_values.z*.0+1.0;
    for (unsigned int subent=0;subent<num_subentities;++subent) {
        new_entity->getSubEntity(subent)->setCustomParameter(0,random_values);
        new_entity->getSubEntity(subent)->setCustomParameter(1,parallax_steps);
    }

    init(new_entity);
    fixTextures();

    mMeshLoaded = true;

    if (!mInitialAnimationName.empty()) {
      setAnimation(mInitialAnimationName);
      mInitialAnimationName = "";
    }

    notify(&EntityListener::entityLoaded, this, true);
}

void Entity::loadBillboard(Mesh::BillboardPtr bboard, const String& bbtexname)
{
    beginLoad();

    // With the material in place, create the Billboard(Set)
    Ogre::BillboardSet* new_bbs = NULL;
    try {
      try {
          new_bbs = getScene()->getSceneManager()->createBillboardSet(ogreMovableName(), 1);
          std::string matname = bbtexname;
          new_bbs->setMaterialName(matname);
          if (bboard->facing == Mesh::Billboard::FACING_FIXED)
              new_bbs->setBillboardType(Ogre::BBT_PERPENDICULAR_COMMON);
          else if (bboard->facing == Mesh::Billboard::FACING_CAMERA)
              new_bbs->setBillboardType(Ogre::BBT_POINT);
          new_bbs->setDefaultWidth( (bboard->aspectRatio > 0.f) ? bboard->aspectRatio : 1.f);
          new_bbs->setDefaultHeight(1.f);
          new_bbs->createBillboard(Ogre::Vector3(0,0,0), Ogre::ColourValue(1.f, 1.f, 1.f, 1.f));
          // The BillboardSet ends up with some bizarre settings for
          // bounds. Force them to be what we want manually: radius =
          // 1 and bounds for the box that fit in there (1/sqrt(3) sides)
          new_bbs->setBounds(Ogre::AxisAlignedBox(Ogre::Vector3(-.57735f, -.57735f, -.57735f), Ogre::Vector3(.57735f, .57735f, .57735f)), 1.f);
      } catch (Ogre::InvalidParametersException &) {
        SILOG(ogre,error,"Got invalid parameters");
        throw;
      }
    } catch (...) {
        SILOG(ogre,error,"Failed to load billboard "<< bbtexname << " (id "<<id()<<")!");
        return;
    }

    SILOG(ogre,detailed,"Bounding box: " << new_bbs->getBoundingBox());

    init(new_bbs);
    fixTextures();

    notify(&EntityListener::entityLoaded, this, true);
}

void Entity::loadFailed() {
    notify(&EntityListener::entityLoaded, this, false);
}

void Entity::unload() {
    if (getOgreEntity()) unloadMesh();
    else if (getOgreBillboard()) unloadBillboard();
}

void Entity::unloadMesh() {
    Ogre::Entity* meshObj = getOgreEntity();
    init(NULL);
    if (meshObj) {
        getScene()->getSceneManager()->destroyEntity(meshObj);
        mOgreObject=NULL;
    }
    // Even though these are common in both, we only want to do them if we had
    // an entity.
    mReplacedMaterials.clear();

    mMeshLoaded = false;
}

void Entity::unloadBillboard() {
    Ogre::BillboardSet* bbObj = getOgreBillboard();
    init(NULL);
    if (bbObj) {
        getScene()->getSceneManager()->destroyBillboardSet(bbObj);
        mOgreObject = NULL;
    }
    // Even though these are common in both, we only want to do them if we had
    // an entity.
    mReplacedMaterials.clear();
}

void Entity::setSelected(bool selected) {
      mSceneNode->showBoundingBox(selected);
}

const std::vector<String> Entity::getAnimationList() {
  std::vector<String> animations;
  for (std::set<String>::iterator it = mAnimationList.begin(); it != mAnimationList.end(); it++) {
    animations.push_back(*it);
  }

  return animations;
}

}
}

max_stars_repo_name: pathorn/sirikata

max_issues_repo_name: pathorn/sirikata

max_forks_repo_name: pathorn/sirikata


text:
// Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file parelm_test.cpp
/// \brief Add your file description here.

//#define MCRL2_LPS_PARELM_DEBUG

#include "mcrl2/data/consistency.h"
#include "mcrl2/data/detail/test_rewriters.h"
#include "mcrl2/lps/multi_action.h"
#include "mcrl2/lps/print.h"
#include <boost/test/minimal.hpp>
#include <iostream>
#include <string>

using namespace mcrl2;
using namespace mcrl2::data;
using namespace mcrl2::lps;

/// \brief Returns a data variable of type Nat with a given name
/// \param name A string
/// \return A data variable of type Nat with a given name
data::variable nat(const std::string& name)
{
  return data::variable(core::identifier_string(name), data::sort_nat::nat());
}

process::action act(const std::string& name, data_expression_list parameters)
{
  std::vector<sort_expression> sorts;
  for (const auto & parameter : parameters)
  {
    sorts.push_back(parameter.sort());
  }
  process::action_label label(name, sort_expression_list(sorts.begin(), sorts.end()));
  return process::action(label, parameters);
}

void test_multi_actions(const process::action_list& a, const process::action_list& b, const data_expression& expected_result = data::undefined_data_expression())
{
  std::cout << "--- test_multi_actions ---" << std::endl;
  data_expression result = equal_multi_actions(multi_action(a), multi_action(b));
  std::cout << "a               = " << lps::pp(a) << std::endl;
  std::cout << "b               = " << lps::pp(b) << std::endl;
  std::cout << "result          = " << lps::pp(result) << std::endl;
  std::cout << "expected_result = " << lps::pp(expected_result) << std::endl;
  BOOST_CHECK(expected_result == data::undefined_data_expression() || result == expected_result);
}

void test_equal_multi_actions()
{
  namespace d = data;

  data_expression d1 = nat("d1");
  data_expression d2 = nat("d2");
  data_expression d3 = nat("d3");
  data_expression d4 = nat("d4");
  process::action_list a1  ( { act("a", data_expression_list({ d1 })) });
  process::action_list a2  ( { act("a", data_expression_list({ d2 })) });
  process::action_list b1  ( { act("b", data_expression_list({ d1 })) });
  process::action_list b2  ( { act("b", data_expression_list({ d2 })) });
  process::action_list a11 ( { act("a", data_expression_list({ d1 })), act("a", data_expression_list({ d1 })) });
  process::action_list a12 ( { act("a", data_expression_list({ d1 })), act("a", data_expression_list({ d2 })) });
  process::action_list a21 ( { act("a", data_expression_list({ d2 })), act("a", data_expression_list({ d1 })) });
  process::action_list a22 ( { act("a", data_expression_list({ d2 })), act("a", data_expression_list({ d2 })) });
  process::action_list a34 ( { act("a", data_expression_list({ d3 })), act("a", data_expression_list({ d4 })) });
  process::action_list a12b1 ( { act("a", data_expression_list({ d1 })), act("a", data_expression_list({ d2 })), act("b", data_expression_list({ d1 })) });
  process::action_list a34b2 ( { act("a", data_expression_list({ d3 })), act("a", data_expression_list({ d4 })), act("b", data_expression_list({ d2 })) });
  test_multi_actions(a1,  a1, d::true_());
  test_multi_actions(a1,  a2, d::equal_to(d1, d2));
  test_multi_actions(a11, a11, d::true_());
  test_multi_actions(a12, a21, d::true_());
  test_multi_actions(a21, a12, d::true_());
  test_multi_actions(a11, a22, d::equal_to(d1, d2));
  test_multi_actions(a1, a12,  d::false_());
  test_multi_actions(a1, b1,   d::false_());
  test_multi_actions(a12, a34);
  test_multi_actions(a12b1, a34b2);

  data_expression m1 = equal_multi_actions(multi_action(a12), multi_action(a34));
  data_expression m2 = equal_multi_actions(multi_action(a34), multi_action(a12));
  data_expression n1 = data::detail::normalize_equality(m1);
  data_expression n2 = data::detail::normalize_equality(m2);
  data_expression p1 = data::detail::normalize_and_or(n1);
  data_expression p2 = data::detail::normalize_and_or(n2);
  std::cout << "m1 = " << data::pp(m1) << std::endl;
  std::cout << "m2 = " << data::pp(m2) << std::endl;
  std::cout << "n1 = " << data::pp(n1) << std::endl;
  std::cout << "n2 = " << data::pp(n2) << std::endl;
  std::cout << "p1 = " << data::pp(p1) << std::endl;
  std::cout << "p2 = " << data::pp(p2) << std::endl;
  BOOST_CHECK(p1 == p2);
}

void test_pp()
{
  data_expression d1 = nat("d1");
  data_expression d2 = nat("d2");
  process::action_list a1  ( { act("a", data_expression_list({ d1 })) });
  process::action_list a2  ( { act("a", data_expression_list({ d2 })) });
  process::action_list b1  ( { act("b", data_expression_list({ d1 })) });
  process::action_list a11 ( { act("a", data_expression_list({ d1 })), act("a", data_expression_list({ d1 })) });
  multi_action m(a11);
  std::string s = lps::pp(m);
  std::cout << "s = " << s << std::endl;
  BOOST_CHECK(s == "a(d1)|a(d1)");
}

int test_main(int argc, char* argv[])
{
  test_equal_multi_actions();
  test_pp();

  return 0;
}

ext: cpp


text:
#ifndef WUNDERGROUNDINTERFACE_H
#define WUNDERGROUNDINTERFACE_H

#include "WeatherDataInterface.hh"

#include <string>

#include <boost/date_time/posix_time/posix_time_types.hpp>

#include <Poco/URI.h>

class WUndergroundInterface : public WeatherDataInterface
{
public:
   explicit WUndergroundInterface(const std::string & apiKey, const std::string & location) :
      WeatherDataInterface(apiKey, location) {}

private:
   std::vector<WeatherDataInterface::TemporalMeasurement<double>>
   doGetForecastedMinimumDailyDewpoints(
         const boost::posix_time::time_period   & period,
         const boost::posix_time::time_duration & timeout) override;

   std::string obtainJSON(
      const Poco::URI                        & uri,
      const boost::posix_time::time_duration & timeout) const;

private:
   static const std::string WU_API_URL;
};

#endif /* WUNDERGROUNDINTERFACE_HH_ */

ext: hh

max_stars_repo_name: tweej/DewPointDetector

max_issues_repo_name: tweej/DewPointDetector

max_forks_repo_name: tweej/DewPointDetector


text:
/*
 * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
 *
 * Distributed under under the Apache License, version 2.0 (the "License").
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
#include <cetty/buffer/Unpooled.h>

#include <boost/integer.hpp>

#include <cetty/Types.h>

#include <cetty/buffer/ChannelBuffer.h>
#include <cetty/buffer/HeapChannelBuffer.h>
#include <cetty/buffer/SlicedChannelBuffer.h>
#include <cetty/buffer/CompositeChannelBuffer.h>

#include <cetty/util/StlUtil.h>
#include <cetty/util/Exception.h>
#include <cetty/util/StringPiece.h>
#include <cetty/util/NestedDiagnosticContext.h>

namespace cetty {
namespace buffer {

using namespace cetty::util;

ChannelBufferPtr Unpooled::EMPTY_BUFFER =
    ChannelBufferPtr(new HeapChannelBuffer(0, 0, 0));

ChannelBufferPtr Unpooled::buffer(int initialCapacity, int aheadBytes, int maxCapacity) {
    if (initialCapacity == 0) {
        return EMPTY_BUFFER;
    }

    return ChannelBufferPtr(new HeapChannelBuffer(initialCapacity, aheadBytes, maxCapacity));

    return EMPTY_BUFFER;
}

cetty::buffer::ChannelBufferPtr Unpooled::buffer() {
    return buffer(256, 0);
}

cetty::buffer::ChannelBufferPtr Unpooled::buffer(int initialCapacity) {
    return buffer(initialCapacity, 0);
}

ChannelBufferPtr Unpooled::wrappedBuffer(std::string* str) {
    char* bytes = stringAsArray(str);
    return wrappedBuffer(bytes, 0, static_cast<int>(str->size()));
}

ChannelBufferPtr Unpooled::wrappedBuffer(char* bytes, int length) {
    if (NULL == bytes || length <= 0) {
        return EMPTY_BUFFER;
    }

    return new HeapChannelBuffer(bytes, length);
}

ChannelBufferPtr Unpooled::wrappedBuffer(char* bytes, int offset, int length) {
    if (length == 0) {
        return EMPTY_BUFFER;
    }

    if (offset == 0) {
        return wrappedBuffer(bytes, length);
    }

    return new SlicedChannelBuffer(wrappedBuffer(bytes, length), offset, length);
}

ChannelBufferPtr Unpooled::wrappedBuffer(const std::vector<ChannelBufferPtr>& buffers) {
    if (buffers.size() == 0) { return EMPTY_BUFFER; }

    std::vector<ChannelBufferPtr> buffs;

    for (size_t i = 0; i < buffers.size(); ++i) {
        if (!buffers[i]->readable()) { continue; }

        if (!buffs.empty() && buffers[i]->order() != buffs[0]->order()) {
            // TODO: release resources.
            throw InvalidArgumentException("inconsistent byte order");
        }

        boost::intrusive_ptr<CompositeChannelBuffer> compositeChannelBuff =
            boost::dynamic_pointer_cast<CompositeChannelBuffer>(buffers[i]);

        if (compositeChannelBuff) {
            // Expand nested composition.
            std::vector<ChannelBufferPtr> vec
                = compositeChannelBuff->decompose();

            buffs.insert(buffs.end(), vec.begin(), vec.end());
        }
        else {
            // An ordinary buffer (non-composite)
            buffs.push_back(buffers[i]->slice());
        }
    }

    if (buffs.empty()) {
        return EMPTY_BUFFER;
    }
    else if (buffs.size() == 1) {
        return buffs[0];
    }

    return compositeBuffer(buffs);
}

ChannelBufferPtr
Unpooled::wrappedBuffer(const ChannelBufferPtr& buffer) {
    if (buffer && buffer->readable()) {
        return buffer->slice();
    }
    else {
        return EMPTY_BUFFER;
    }
}

ChannelBufferPtr
Unpooled::wrappedBuffer(const ChannelBufferPtr& buffer0,
                        const ChannelBufferPtr& buffer1) {
    std::vector<ChannelBufferPtr> buffers;

    if (buffer0 && buffer0->readable()) { buffers.push_back(buffer0); }

    if (buffer1 && buffer1->readable()) { buffers.push_back(buffer1); }

    if (buffers.empty()) { return EMPTY_BUFFER; }

    return wrappedBuffer(buffers);
}

ChannelBufferPtr
Unpooled::wrappedBuffer(const ChannelBufferPtr& buffer0,
                        const ChannelBufferPtr& buffer1,
                        const ChannelBufferPtr& buffer2) {
    std::vector<ChannelBufferPtr> buffers;

    if (buffer0 && buffer0->readable()) { buffers.push_back(buffer0); }

    if (buffer1 && buffer1->readable()) { buffers.push_back(buffer1); }

    if (buffer2 && buffer2->readable()) { buffers.push_back(buffer2); }

    if (buffers.empty()) { return EMPTY_BUFFER; }

    return wrappedBuffer(buffers);
}

ChannelBufferPtr
Unpooled::compositeBuffer(const std::vector<ChannelBufferPtr>& components) {
    switch (components.size()) {
    case 0:
        return EMPTY_BUFFER;

    case 1:
        return components[0];

    default:
        return ChannelBufferPtr(
                   new CompositeChannelBuffer(components));
    }
}

ChannelBufferPtr Unpooled::copiedBuffer(const char* bytes, int length) {
    return copiedBuffer(StringPiece(bytes, length));
}

ChannelBufferPtr Unpooled::copiedBuffer(const StringPiece& bytes) {
    if (bytes.empty()) {
        return EMPTY_BUFFER;
    }

    int newCapacity = bytes.length();
    char* newBytes = new char[newCapacity];
    memcpy(newBytes, bytes.data(), newCapacity);

    return new HeapChannelBuffer(newBytes, newCapacity, MAX_INT32, true);
}

ChannelBufferPtr Unpooled::copiedBuffer(const StringPiece& bytes, int offset, int length) {
    if (length <= 0 || bytes.empty() || offset >= bytes.length()) {
        return EMPTY_BUFFER;
    }

    int newCapacity = bytes.length();
    char* newBytes = new char[newCapacity];
    memcpy(newBytes, bytes.data() + offset, newCapacity);

    return new HeapChannelBuffer(newBytes, newCapacity, MAX_INT32, true);
}

ChannelBufferPtr
Unpooled::copiedBuffer(const ChannelBufferPtr& buffer) {
    if (buffer && buffer->readable()) {
        return buffer->copy();
    }
    else {
        return EMPTY_BUFFER;
    }
}

ChannelBufferPtr
Unpooled::copiedBuffer(const ChannelBufferPtr& buffer0,
                       const ChannelBufferPtr& buffer1) {
    if (buffer0 && buffer0->readable()) {
        if (buffer1 && buffer1->readable()) {
            if (buffer1->order() != buffer0->order()) {
                throw InvalidArgumentException("inconsistent byte order");
            }

            return wrappedBuffer(buffer0->copy(), buffer1->copy());
        }
        else {
            return buffer0->copy();
        }
    }
    else {
        if (buffer1 && buffer1->readable()) {
            return buffer1->copy();
        }
        else {
            return EMPTY_BUFFER;
        }
    }
}

ChannelBufferPtr
Unpooled::copiedBuffer(const ChannelBufferPtr& buffer0,
                       const ChannelBufferPtr& buffer1,
                       const ChannelBufferPtr& buffer2) {
    std::vector<ChannelBufferPtr> buffers;

    if (buffer0 && buffer0->readable()) { buffers.push_back(buffer0->copy()); }

    if (buffer1 && buffer1->readable()) {
        if (buffers.size() > 1 && buffer1->order() != buffers[0]->order()) {
            throw InvalidArgumentException("inconsistent byte order");
        }

        buffers.push_back(buffer1->copy());
    }

    if (buffer2 && buffer2->readable()) {
        if (buffers.size() > 1 && buffer2->order() != buffers[0]->order()) {
            throw InvalidArgumentException("inconsistent byte order");
        }

        buffers.push_back(buffer2->copy());
    }

    if (buffers.empty()) {
        return EMPTY_BUFFER;
    }
    else if (buffers.size() == 1) {
        return buffers.front();
    }
    else {
        return wrappedBuffer(buffers);
    }
}

ChannelBufferPtr
Unpooled::copiedBuffer(const std::vector<ChannelBufferPtr>& buffers) {
    if (buffers.size() == 0) { return EMPTY_BUFFER; }

    std::vector<ChannelBufferPtr> buffs;

    for (size_t i = 0; i < buffers.size(); ++i) {
        if (!buffs.empty() && buffers[i]->order() != buffs[0]->order()) {
            throw InvalidArgumentException("inconsistent byte order");
        }

        buffs.push_back(Unpooled::copiedBuffer(buffers[i]));
    }

    if (buffs.empty()) {
        return EMPTY_BUFFER;
    }
    else if (buffs.size() == 1) {
        return buffs[0];
    }

    return wrappedBuffer(buffs);
}

}
}


text: #include <boost/hana/fwd/concept/functor.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef _LINGUISTIC_HYPHDSP_HXX_
#define _LINGUISTIC_HYPHDSP_HXX_

#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceDisplayName.hpp>
#include <com/sun/star/linguistic2/XHyphenator.hpp>
#include <com/sun/star/linguistic2/XPossibleHyphens.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp>
#include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp>

#include <uno/lbnames.h>			// CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase1.hxx>	// helper for implementations

#include <boost/shared_ptr.hpp>
#include <map>

#include "lngopt.hxx"
#include "linguistic/misc.hxx"
#include "defs.hxx"

class LngSvcMgr;

///////////////////////////////////////////////////////////////////////////

class HyphenatorDispatcher :
	public cppu::WeakImplHelper1
	<
		::com::sun::star::linguistic2::XHyphenator
	>,
	public LinguDispatcher
{
    typedef boost::shared_ptr< LangSvcEntries_Hyph >                LangSvcEntries_Hyph_Ptr_t;
    typedef std::map< LanguageType, LangSvcEntries_Hyph_Ptr_t >     HyphSvcByLangMap_t;
    HyphSvcByLangMap_t      aSvcMap;

	::com::sun::star::uno::Reference<
		::com::sun::star::beans::XPropertySet >						xPropSet;
	::com::sun::star::uno::Reference<
		::com::sun::star::linguistic2::XSearchableDictionaryList >	xDicList;

	LngSvcMgr	   &rMgr;

	// disallow copy-constructor and assignment-operator for now
	HyphenatorDispatcher(const HyphenatorDispatcher &);
	HyphenatorDispatcher & operator = (const HyphenatorDispatcher &);

	inline ::com::sun::star::uno::Reference<
		::com::sun::star::beans::XPropertySet >
			GetPropSet();
	inline ::com::sun::star::uno::Reference<
		::com::sun::star::linguistic2::XSearchableDictionaryList >
			GetDicList();

	void	ClearSvcList();

	com::sun::star::uno::Reference<
		::com::sun::star::linguistic2::XHyphenatedWord>
            buildHyphWord( const rtl::OUString rOrigWord,
                const ::com::sun::star::uno::Reference<
					::com::sun::star::linguistic2::XDictionaryEntry> &xEntry,
				sal_Int16 nLang, sal_Int16 nMaxLeading );

	com::sun::star::uno::Reference<
		::com::sun::star::linguistic2::XPossibleHyphens >
			buildPossHyphens( const ::com::sun::star::uno::Reference<
					::com::sun::star::linguistic2::XDictionaryEntry > &xEntry,
					sal_Int16 nLanguage );

public:
	HyphenatorDispatcher( LngSvcMgr &rLngSvcMgr );
	virtual ~HyphenatorDispatcher();

	// XSupportedLocales
    virtual ::com::sun::star::uno::Sequence<
			::com::sun::star::lang::Locale > SAL_CALL
		getLocales()
			throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
		hasLocale( const ::com::sun::star::lang::Locale& aLocale )
			throw(::com::sun::star::uno::RuntimeException);

	// XHyphenator
    virtual ::com::sun::star::uno::Reference<
			::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
		hyphenate( const ::rtl::OUString& aWord,
				const ::com::sun::star::lang::Locale& aLocale,
				sal_Int16 nMaxLeading,
				const ::com::sun::star::beans::PropertyValues& aProperties )
			throw(::com::sun::star::lang::IllegalArgumentException,
				  ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference<
			::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
		queryAlternativeSpelling( const ::rtl::OUString& aWord,
				const ::com::sun::star::lang::Locale& aLocale,
				sal_Int16 nIndex,
				const ::com::sun::star::beans::PropertyValues& aProperties )
			throw(::com::sun::star::lang::IllegalArgumentException,
				  ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference<
			::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL
		createPossibleHyphens(
				const ::rtl::OUString& aWord,
				const ::com::sun::star::lang::Locale& aLocale,
				const ::com::sun::star::beans::PropertyValues& aProperties )
			throw(::com::sun::star::lang::IllegalArgumentException,
				  ::com::sun::star::uno::RuntimeException);

	// LinguDispatcher
	virtual void
		SetServiceList( const ::com::sun::star::lang::Locale &rLocale,
				const ::com::sun::star::uno::Sequence<
					rtl::OUString > &rSvcImplNames );
	virtual ::com::sun::star::uno::Sequence< rtl::OUString >
		GetServiceList( const ::com::sun::star::lang::Locale &rLocale ) const;
	virtual DspType
		GetDspType() const;
};

inline ::com::sun::star::uno::Reference<
	::com::sun::star::beans::XPropertySet >
		HyphenatorDispatcher::GetPropSet()
{
	return xPropSet.is() ?
				xPropSet : xPropSet = ::linguistic::GetLinguProperties();
}

inline ::com::sun::star::uno::Reference<
	::com::sun::star::linguistic2::XSearchableDictionaryList >
		HyphenatorDispatcher::GetDicList()
{
	return xDicList.is() ?
				xDicList : xDicList = ::linguistic::GetSearchableDictionaryList();
}

///////////////////////////////////////////////////////////////////////////

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
// Copyright 2018 The Beam Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "external_pow.h"
#include "stratum.h"
#include "p2p/line_protocol.h"
#include "utility/io/tcpstream.h"
#include "utility/io/timer.h"
#include "utility/helpers.h"

#include <boost/program_options.hpp>

#ifndef LOG_VERBOSE_ENABLED
#define LOG_VERBOSE_ENABLED 0
#endif
#include "utility/logger.h"

namespace po = boost::program_options;

namespace beam {

static const unsigned RECONNECT_TIMEOUT = 1000;

class StratumClient : public stratum::ParserCallback {
    std::unique_ptr<IExternalPOW> _miner;
    io::Reactor& _reactor;
    io::Address _serverAddress;
    std::string _apiKey;
    LineProtocol _lineProtocol;
    io::TcpStream::Ptr _connection;
    io::Timer::Ptr _timer;
    std::string _lastJobID;
    Merkle::Hash _lastJobInput;
    Block::PoW _lastFoundBlock;
    bool _blockSent;
    bool _tls;
    bool _fakeSolver;

public:
    StratumClient(io::Reactor& reactor, const io::Address& serverAddress, std::string apiKey, bool no_tls, bool fake) :
        _reactor(reactor),
        _serverAddress(serverAddress),
        _apiKey(std::move(apiKey)),
        _lineProtocol(
            BIND_THIS_MEMFN(on_raw_message),
            BIND_THIS_MEMFN(on_write)
        ),
        _timer(io::Timer::create(_reactor)),
        _blockSent(false),
        _tls(!no_tls),
        _fakeSolver(fake)
    {
        _timer->start(0, false, BIND_THIS_MEMFN(on_reconnect));
        _miner = IExternalPOW::create_local_solver(fake);
    }

private:
    bool on_raw_message(void* data, size_t size) {
        LOG_DEBUG() << "got " << std::string((char*)data, size-1);
        return stratum::parse_json_msg(data, size, *this);
    }

    bool fill_job_info(const stratum::Job& job) {
        bool ok = false;
        std::vector<uint8_t> buf = from_hex(job.input, &ok);
        if (!ok || buf.size() != 32) return false;
        memcpy(_lastJobInput.m_pData, buf.data(), 32);
        _lastJobID = job.id;
        return true;
    }

    bool on_message(const stratum::Job& job) override {
        Block::PoW pow;
        pow.m_Difficulty.m_Packed = job.difficulty;

        LOG_INFO() << "new job here: id=" << job.id;

        if (!fill_job_info(job)) return false;

        _miner->new_job(
            _lastJobID, _lastJobInput, pow, job.height,
            BIND_THIS_MEMFN(on_block_found),
            []() { return false; }
        );

        return true;
    }

    bool on_message(const stratum::Result& res) override {
        if (res.code < 0) {
            return on_stratum_error(res.code);
        }
        LOG_DEBUG() << "ignoring result message, code=" << res.code << " description=" << res.description;
        return true;
    }

    IExternalPOW::BlockFoundResult on_block_found() {
        std::string jobID;
		Height h;
        _miner->get_last_found_block(jobID, h, _lastFoundBlock);
        if (jobID != _lastJobID) {
            LOG_INFO() << "solution expired" << TRACE(jobID);
            return IExternalPOW::solution_expired;
        }

        //char buf[72];
        //LOG_DEBUG() << "input=" << to_hex(buf, _lastJobInput.m_pData, 32);

        if (!_fakeSolver && !_lastFoundBlock.IsValid(_lastJobInput.m_pData, 32, h)) {
            LOG_ERROR() << "solution is invalid, id=" << _lastJobID;
            return IExternalPOW::solution_rejected;
        }
        LOG_INFO() << "block found id=" << _lastJobID;

        _blockSent = false;
        send_last_found_block();
        return IExternalPOW::solution_accepted;
    }

    void send_last_found_block() {
        if (_blockSent || !_connection || !_connection->is_connected()) return;
        stratum::Solution sol(_lastJobID, _lastFoundBlock);
        if (!stratum::append_json_msg(_lineProtocol, sol)) {
            LOG_ERROR() << "Internal error";
            _reactor.stop();
            return;
        }
        _lineProtocol.finalize();
    }

    bool on_stratum_error(stratum::ResultCode code) override {
        if (code == stratum::login_failed) {
            LOG_ERROR() << "login to " << _serverAddress << " failed, try again later";
            return false;
        }

        // TODO what to do with other errors
        LOG_ERROR() << "got stratum error: " << code << " " << stratum::get_result_msg(code);
        return true;
    }

    bool on_unsupported_stratum_method(stratum::Method method) override {
        LOG_INFO() << "ignoring unsupported stratum method: " << stratum::get_method_str(method);
        return true;
    }

    void on_write(io::SharedBuffer&& msg) {
        if (_connection) {
            LOG_VERBOSE() << "writing " << std::string((const char*)msg.data, msg.size - 1);
            auto result = _connection->write(msg);
            if (!result) {
                on_disconnected(result.error());
            } else {
                _blockSent = true; //TODO ???
            }
        } else {
            LOG_DEBUG() << "ignoring message, no connection";
        }
    }

    void on_disconnected(io::ErrorCode error) {
        LOG_INFO() << "disconnected, error=" << io::error_str(error) << ", rescheduling";
        _connection.reset();
        _timer->start(RECONNECT_TIMEOUT, false, BIND_THIS_MEMFN(on_reconnect));
    }

    void on_reconnect() {
        LOG_INFO() << "connecting to " << _serverAddress;
        if (!_reactor.tcp_connect(_serverAddress, 1, BIND_THIS_MEMFN(on_connected), 10000, _tls)) {
            LOG_ERROR() << "connect attempt failed, rescheduling";
            _timer->start(RECONNECT_TIMEOUT, false, BIND_THIS_MEMFN(on_reconnect));
        }
    }

    void on_connected(uint64_t, io::TcpStream::Ptr&& newStream, io::ErrorCode errorCode) {
        if (errorCode != 0) {
            on_disconnected(errorCode);
            return;
        }

        LOG_INFO() << "connected to " << _serverAddress;
        _connection = std::move(newStream);
        _connection->enable_keepalive(2);
        _connection->enable_read(BIND_THIS_MEMFN(on_stream_data));

        if (!stratum::append_json_msg(_lineProtocol, stratum::Login(_apiKey))) {
            LOG_ERROR() << "Internal error";
            _reactor.stop();
        }
        if (!_blockSent) {
            _lineProtocol.finalize();
        } else {
            send_last_found_block();
        }
    }

    bool on_stream_data(io::ErrorCode errorCode, void* data, size_t size) {
        if (errorCode != 0) {
            on_disconnected(errorCode);
            return false;
        }
        if (!_lineProtocol.new_data_from_stream(data, size)) {
            LOG_ERROR() << "closing connection";
            _reactor.stop();
            return false;
        }
        return true;
    }
};

} //namespace

struct Options {
    std::string apiKey;
    std::string serverAddress;
    bool no_tls=false;
    bool fake=false;
    int logLevel=LOG_LEVEL_DEBUG;
    unsigned logRotationPeriod = 3*60*60*1000; // 3 hours
};

static bool parse_cmdline(int argc, char* argv[], Options& o);

int main(int argc, char* argv[]) {
    using namespace beam;

    Options options;
    if (!parse_cmdline(argc, argv, options)) {
        return 1;
    }
    std::string logFilePrefix("miner_client_");
    logFilePrefix += std::to_string(uv_os_getpid());
    logFilePrefix += "_";
    auto logger = Logger::create(LOG_LEVEL_INFO, options.logLevel, options.logLevel, logFilePrefix, "logs");
    int retCode = 0;
    try {
        io::Reactor::Ptr reactor = io::Reactor::create();
        io::Address connectTo;
        if (!connectTo.resolve(options.serverAddress.c_str())) {
            throw std::runtime_error(std::string("cannot resolve server address ") + options.serverAddress);
        }
        io::Reactor::Scope scope(*reactor);
        io::Reactor::GracefulIntHandler gih(*reactor);
        io::Timer::Ptr logRotateTimer = io::Timer::create(*reactor);
        logRotateTimer->start(
            options.logRotationPeriod, true, []() { Logger::get()->rotate(); }
        );
        StratumClient client(*reactor, connectTo, options.apiKey, options.no_tls, options.fake);
        reactor->run();
        LOG_INFO() << "stopping...";
    } catch (const std::exception& e) {
        LOG_ERROR() << "EXCEPTION: " << e.what();
        retCode = 255;
    } catch (...) {
        LOG_ERROR() << "NON_STD EXCEPTION";
        retCode = 255;
    }
    return retCode;
}

bool parse_cmdline(int argc, char* argv[], Options& o) {

    po::options_description cliOptions("Remote miner options");
    cliOptions.add_options()
    ("help", "list of all options")
    ("server", po::value<std::string>(&o.serverAddress)->required(), "server address")
    ("key", po::value<std::string>(&o.apiKey)->required(), "api key")
    ("no-tls", po::bool_switch(&o.no_tls)->default_value(false), "disable tls")
    ("fake", po::bool_switch(&o.fake)->default_value(false), "fake POW just to test protocol")
    ;

#ifdef NDEBUG
    o.logLevel = LOG_LEVEL_DEBUG;
#else
#if LOG_VERBOSE_ENABLED
    o.logLevel = LOG_LEVEL_VERBOSE;
#else
    o.logLevel = LOG_LEVEL_DEBUG;
#endif
#endif

    po::variables_map vm;
    try
    {
        po::store(po::command_line_parser(argc, argv) // value stored first is preferred
                  .options(cliOptions)
                  .style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing)
                  .run(), vm);

        if (vm.count("help")) {
            std::cout << cliOptions << std::endl;
            return false;
        }

        vm.notify();

        return true;
    } catch (const po::error& ex) {
        std::cerr << ex.what() << "\n" << cliOptions;
    } catch (const std::exception& ex) {
        std::cerr << ex.what();
    } catch (...) {
        std::cerr << "NON_STD EXCEPTION";
    }

    return false;
}


text:
/*
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * Copyright (c) 2020 Andrey Semashev
 */
/*!
 * \file   atomic/detail/core_arch_operations.hpp
 *
 * This header defines core atomic operations, including the emulated version.
 */

#ifndef BOOST_ATOMIC_DETAIL_CORE_ARCH_OPERATIONS_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_CORE_ARCH_OPERATIONS_HPP_INCLUDED_

#include <boost/atomic/detail/core_arch_operations_fwd.hpp>
#include <boost/atomic/detail/core_operations_emulated.hpp>
#include <boost/atomic/detail/config.hpp>
#include <boost/atomic/detail/platform.hpp>
#include <boost/atomic/detail/storage_traits.hpp>

#if defined(BOOST_ATOMIC_DETAIL_CORE_ARCH_BACKEND_HEADER)
#include BOOST_ATOMIC_DETAIL_CORE_ARCH_BACKEND_HEADER(boost/atomic/detail/core_arch_ops_)
#endif

#include <boost/atomic/detail/header.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {
namespace atomics {
namespace detail {

//! Default specialization that falls back to lock-based implementation
template< std::size_t Size, bool Signed, bool Interprocess >
struct core_arch_operations :
    public core_operations_emulated< Size, storage_traits< Size >::alignment, Signed, Interprocess >
{
};

} // namespace detail
} // namespace atomics
} // namespace boost

#include <boost/atomic/detail/footer.hpp>

#endif // BOOST_ATOMIC_DETAIL_CORE_ARCH_OPERATIONS_HPP_INCLUDED_


text:
#include <boost/test/unit_test.hpp>
#include "../src/RingBuffer.hpp"

namespace robot_remote_control {

/**
 * @brief helper function to fill buffer with increasing numbers
 */

void fillBuffer(unsigned int size, RingBuffer<int> *buffer, bool overwrite = false) {
    for (unsigned int i = 0; i < size; i++) {
        buffer->pushData(i, overwrite);
    }
}

/**
 * @brief helper function to check buffer content if it has increasing numbers
 * as defne to get proper line numbers wen errors occur
 */
#define CHECK_BUFFER(SIZE, BUFFER, STARTWITH) \
    { \
        int content; \
        for (unsigned int i = STARTWITH; i < STARTWITH+SIZE; i++) { \
            if (BUFFER.popData(&content)) { \
                BOOST_CHECK_EQUAL(content, i); \
            } else { \
                BOOST_CHECK_EQUAL(true, false); \
            } \
        } \
    }

BOOST_AUTO_TEST_CASE(return_correctly_on_pop) {
    RingBuffer<int> buffer(10);
    int data;

    // buffer is empty
    BOOST_CHECK_EQUAL(buffer.popData(&data), false);

    data = 0;
    buffer.pushData(data);
    // now buffer is not empty
    BOOST_CHECK_EQUAL(buffer.popData(&data), true);

    // buffer is empty
    BOOST_CHECK_EQUAL(buffer.popData(&data), false);
}

BOOST_AUTO_TEST_CASE(return_correctly_on_push) {
    RingBuffer<int> buffer(1);

    int i = 0;
    bool res1 = buffer.pushData(i);
    // now the buffer is full
    bool res2 = buffer.pushData(i);

    BOOST_CHECK_EQUAL(res1, true);
    BOOST_CHECK_EQUAL(res2, false);
}

BOOST_AUTO_TEST_CASE(push_pop) {
    RingBuffer<int> buffer(5);

    fillBuffer(2, &buffer);
    BOOST_CHECK_EQUAL(buffer.size(), 2);

    CHECK_BUFFER(2, buffer, 0);

    BOOST_CHECK_EQUAL(buffer.size(), 0);

    // no new items are added, until the buffer was read, so a size5 buffer schoud have 0-4
    fillBuffer(20, &buffer);

    BOOST_CHECK_EQUAL(buffer.size(), 5);

    // checks if first 5 are in order
    CHECK_BUFFER(5, buffer, 0);

    BOOST_CHECK_EQUAL(buffer.size(), 0);
}

BOOST_AUTO_TEST_CASE(push_pop_overwrite) {
    RingBuffer<int> buffer(5);

    fillBuffer(2, &buffer, true);
    BOOST_CHECK_EQUAL(buffer.size(), 2);

    CHECK_BUFFER(2, buffer, 0);

    BOOST_CHECK_EQUAL(buffer.size(), 0);

    // oldest items are overwritten so a size 5 buffer schoud have 15-19
    fillBuffer(20, &buffer, true);

    BOOST_CHECK_EQUAL(buffer.size(), 5);

    // checks if first 5 are in order
    CHECK_BUFFER(5, buffer, 15);

    BOOST_CHECK_EQUAL(buffer.size(), 0);
}

BOOST_AUTO_TEST_CASE(preserve_content_multiuse) {
    RingBuffer<int> buffer(10);

    for (int i = 0; i < 1000; i++) {
        if (!(i % 2)) {
            // run first
            fillBuffer(5, &buffer);
            CHECK_BUFFER(3, buffer, 0);
            BOOST_CHECK_EQUAL(buffer.size(), 2);
        } else {
            // run second
            fillBuffer(5, &buffer);
            // 2 left to read, startgin with 3
            CHECK_BUFFER(2, buffer, 3);
            CHECK_BUFFER(5, buffer, 0);
            BOOST_CHECK_EQUAL(buffer.size(), 0);
        }
    }
}

BOOST_AUTO_TEST_CASE(resize_buffer) {
    RingBuffer<int> buffer(1);

    BOOST_CHECK_EQUAL(buffer.capacity(), 1);

    fillBuffer(5, &buffer);  // further adds fail
    CHECK_BUFFER(1,  buffer, 0);  // has first value, push fails if buffer is full

    fillBuffer(5, &buffer, true);  // fill with overwrite
    CHECK_BUFFER(1, buffer, 4);  // has first value, push fails if buffer is full

    buffer.resize(10);
    BOOST_CHECK_EQUAL(buffer.capacity(), 10);

    fillBuffer(10, &buffer);  // fill
    CHECK_BUFFER(10, buffer, 0);  // check

    fillBuffer(10, &buffer);  // fill again
    buffer.resize(5);
    BOOST_CHECK_EQUAL(buffer.capacity(), 5);
    CHECK_BUFFER(5, buffer, 0);  // has oldest values (resize chops at the end of buffer)

    // works as before
    fillBuffer(5, &buffer);
    CHECK_BUFFER(5, buffer, 0);
}

}  // namespace robot_remote_control


text:
#include <iostream>
#include <vector>

#include <boost/filesystem.hpp>

int main(void) {

    std::vector<std::string> temp = {"test1", "test2"};

    std::cout << "Hello" << std::endl;

    boost::filesystem::path full_path(boost::filesystem::current_path());
    std::cout << "Current path is : " << full_path << std::endl;

    return 0;
}

max_stars_repo_name: jaredsburrows/cplusplus-cmake-template

max_issues_repo_name: jaredsburrows/cplusplus-cmake-template

max_forks_repo_name: jaredsburrows/cplusplus-cmake-template


text:
// Copyright (C) 2018 Thejaka Amila Kanewala, Marcin Zalewski, Andrew Lumsdaine.

// Boost Software License - Version 1.0 - August 17th, 2003

// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:

// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//  Authors: Thejaka Kanewala
//           Andrew Lumsdaine

#ifndef PBGL2_GRAPH_STATS
#define PBGL2_GRAPH_STATS

#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/graph/parallel/thread_support.hpp> // for compare_and_swap
#include <boost/graph/distributed/owner_defs.hpp>

#include <iostream>
#include <fstream>
#include <mpi.h>

template <typename Graph>
class graph_stats {

private:
  int rank;

public:
  graph_stats() {
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  }

  void print_degree_distribution(const Graph& g) {
    std::string fname = "degree_dist_";
    fname += std::to_string(rank);
    fname += ".txt";

    std::ofstream degrfile;
    degrfile.open(fname);
    degrfile << "Vertices\t Degree\n";

    BGL_FORALL_VERTICES_T(v, g, Graph) {
      degrfile << v << "\t" << boost::out_degree(v, g) << "\n";
    }

    degrfile.close();
  }

};

#endif

max_stars_repo_name: thejkane/AGM

max_issues_repo_name: thejkane/AGM

max_forks_repo_name: thejkane/AGM


text:
/* -*- indent-tabs-mode: t -*- */
#ifndef BOOST_MPI3_PROCESS_HPP
#define BOOST_MPI3_PROCESS_HPP

#include "../mpi3/communicator.hpp"

#include <boost/optional.hpp>

#include "config/NODISCARD.hpp"

namespace boost {
namespace mpi3 {

using boost::optional;  // TODO(correaa) use std::optional in C++17

class process {
	communicator& comm_;
	int rank_;
	friend boost::mpi3::communicator;

	process(communicator& comm, int rank) : comm_{comm}, rank_{rank} {}

 public:
	communicator& comm() const {return comm_;}

	int rank() const{return rank_;}
	template<class T>
	optional<T> operator+=(T const& t) && {
		T val = comm_.reduce_value(t, std::plus<>{}, rank_);
		if(rank_ != comm_.rank()) {return {};}
		return optional<T>(val);
	}

	template<class T>
	process& operator>>(T& t) & {
		comm_.receive_n(&t, 1, rank_);
	//	comm_.receive_value(t, rank_);
		return *this;  // NOLINT(hicpp-move-const-arg,performance-move-const-arg) TODO(correaa)
	}
	template<class T>
	process&& operator&(T& t) && {
		comm_.broadcast_value(t, rank_);
		return std::move(*this);  // NOLINT(hicpp-move-const-arg,performance-move-const-arg) TODO(correaa)
	}
};

template<class T>
auto operator<<(process&& p, const T& value) -> decltype(std::move(p << value)) {
	return std::move(p << value);
}

template<class T>
auto operator>>(process&& p, T&& value) -> decltype(std::declval<process&>() >> value) {
	return p >> value;
}

template<class T>
process& operator<<(process& self, T const& t) {
	self.comm().send_value(t, self.rank());
	return self;
}

inline auto communicator::operator[](int rank) -> process {return {*this, rank};}

template<class T>
auto operator&(communicator& comm, T&& t)
->decltype(comm.all_to_all(begin(std::forward<T>(t))), std::forward<T>(t)) {
	assert( t.size() == comm.size() );
//	using std::begin;
	auto e = comm.all_to_all(begin(std::forward<T>(t)));
	using std::end;
	assert( e == end(t) );
	return std::forward<T>(t);
}

template<class T>
//NODISCARD("do not ignore result when second argument is const")
auto operator&(communicator& comm, T const& t)
->decltype(comm.all_to_all(t.begin(), std::declval<T>().begin()), T(comm.size())) {
	assert(t.size() == comm.size());
	T ret(comm.size());
	comm.all_to_all(t.begin(), ret.begin());
	return ret;
}

template<class T>
auto operator||(process&& self, T& t) {self.comm().broadcast_value(t, self.rank());}

template<class T>
communicator& operator>>(communicator& comm, T& t) {
	comm.receive_n(&t, 1);
//	comm.receive_value(t);
	return comm;
}
template<class T>
std::vector<T> operator|=(communicator& comm, T const& t) {
	return comm.all_gather_value(t);
}

template<class T>
std::vector<T> operator|=(process&& self, T const& t) {
	return self.comm().gather_value(t, self.rank());
}

template<class T>
std::pair<T, process> communicator::max_location(T const& t) {
	auto const ml = max_loc(t);
	return std::pair<T, process>{
		ml.value,
		process{*this, ml.location}
	};
}

}  // end namespace mpi3
}  // end namespace boost

//#ifdef _TEST_BOOST_MPI3_PROCESS

//#include "../mpi3/main.hpp"

////#include "alf/boost/multi_array/serialization.hpp"

//#include<boost/serialization/vector.hpp>
//#include<boost/multi_array.hpp>

//#include<boost/archive/xml_iarchive.hpp>
//#include<boost/archive/xml_oarchive.hpp>

//#include<fstream>

//namespace mpi3 = boost::mpi3;
//using std::cout;

//template<class T>
//bool save_xml(std::string file, T const& ma){
//	std::ofstream ofs(file.c_str()); assert(ofs);
//	boost::archive::xml_oarchive oa(ofs);
//	oa << boost::serialization::make_nvp(file.c_str(), ma);
//	return ofs.good();
//}

//template<class T>
//bool load_xml(std::string file, T&& ma) try{
//	std::ifstream ifs(file.c_str()); assert(ifs);
//	boost::archive::xml_iarchive ia(ifs);
//	ia >> boost::serialization::make_nvp(file.c_str(), std::forward<T>(ma));
//	return ifs.good();
//}catch(std::exception& e){
//	throw std::runtime_error("cannot load from file `\n" + file + ": line 0:\n', because " + e.what() + ". Are the save and load type compatible?");
//}

//int mpi3::main(int argc, char* argv[], mpi3::communicator world){
//	assert(world.size() == 2);
//	if(world.rank() == 0){
//		int a = 7;
//		world[1] << a;
//	}else if(world.rank() == 1){
//		int a = -1;
//		world >> a; // any source (any tag)
//		assert(a == 7);
//	}
//	switch(world.rank()){
//		case 0: {
//			bool b = true;
//			world[1] << b;
//		} break;
//		case 1:{
//			bool b = false;
//			world >> b;
//			assert(b == true);
//		} break;
//	}
//	if(world.rank() == 0){
//		std::vector<double> v = {
//			1, 2, 3,
//			4, 5, 6,
//			7, 8, 9,
//			10, 11, 12
//		};
//		world[1] << v;
//	}else if(world.rank() == 1){
//		std::vector<double> v;
//		world >> v;
//		assert(( v == std::vector<double>{1,2,3,  4, 5, 6,  7,8,9, 10,11,12} ));
//	}
//	switch(world.rank()){
//		case 0:{
//			std::vector<bool> v = {false, true, false};
//			world[1] << v;
//		} break; case 1:{
//			std::vector<bool> v;
//			world >> v;
//			assert(( v == std::vector<bool>{false, true, false} ));
//		}
//	}
//#if 0
//	if(world.rank() == 0){
//		std::vector<double> v = {1,2,3,  4, 5, 6,  7,8,9,  10,11,12};
//		boost::multi_array<double, 2> ma(boost::extents[4][2]);
//		std::copy(v.begin(), v.begin() + 8, ma.data());
//		save_xml("process.xml", ma);
//		world[1] << ma;
//	}else if(world.rank() == 1){
//		boost::multi_array<double, 2> ma(boost::extents[4][2]);
//		world >> ma;
//	//	load_xml("process.xml", ma);
//		cout << ma.shape()[0] << " " << ma.shape()[1] << '\n';
//	//	assert( ma[2][2] == 8. );
//	}
//#endif
//	return 0;
//}
//#endif
#endif


text:
#ifndef GGL_CHEM_MOLECULECOMPONENT_GML_GRAMMAR_HH_
#define GGL_CHEM_MOLECULECOMPONENT_GML_GRAMMAR_HH_

#include <utility>
#include <vector>
#include <string>
#include <stdexcept>

#include "sgm/HashMap.hh"

#if HAVE_UNORDERED_MAP > 0
	#include <unordered_map>
#elif HAVE_TR1_UNORDERED_MAP > 0
	#include <tr1/unordered_map>
#elif HAVE_GNU_HASH_MAP > 0
	#include <ext/hash_map>
#else
	#include <map>
#endif

  // set spirit closure limit if neccessary
#if !defined(BOOST_SPIRIT_CLOSURE_LIMIT)
#define BOOST_SPIRIT_CLOSURE_LIMIT 5
#elif BOOST_SPIRIT_CLOSURE_LIMIT < 5
#error "GGL_CHEM_MOLECULECOMPONENT_GML_GRAMMAR : BOOST_SPIRIT_CLOSURE_LIMIT too low, has to be at least 5"
#endif

  // set phoenix limit if neccessary
#if !defined(PHOENIX_LIMIT)
#define PHOENIX_LIMIT 5
#elif PHOENIX_LIMIT < 5
#error "GGL_CHEM_MOLECULECOMPONENT_GML_GRAMMAR : PHOENIX_LIMIT too low, has to be at least 5"
#endif

#include <boost/version.hpp>
#if BOOST_VERSION >= 103800
#include <boost/spirit/include/classic.hpp>
#include <boost/spirit/include/phoenix1.hpp>
#include <boost/spirit/include/classic_actor.hpp>
#define NS_BOOSTSPIRIT boost::spirit::classic
#else
#include <boost/spirit.hpp>
#include <boost/spirit/phoenix.hpp>
#include <boost/spirit/actor.hpp>
#define NS_BOOSTSPIRIT boost::spirit
#endif

#include "ggl/chem/MoleculeComponent.hh"
#include "sgm/Pattern.hh"
#include "ggl/chem/MC_MC_Node.hh"

namespace ggl {
namespace chem {

	/*! @brief MoleculeComponent parser
	 *
	 * Parses a GML string representation of a
	 * ggl::MoleculeDecomposition::MoleculeComponent object. This includes its
	 * properties as well as the additional constraints needed for matching.
	 *
	 * Example :
	 *
	 * \verbatim
	   ======= GRAPH IN GML =========================

	   molcomp [
	     description " '-Cl' (attached to a primary carbon with no other clorine atoms attached)"
	     priority 4
	     energy  -11.7
	     node [ id 0 label "C" ]
	     node [ id 1 label "Cl" ]
	     edge [ source 0 target 1 label "-" ]
	     constrainAdj [
		    id 0
		    op =
		    count 1
		    nodeLabels [ label "Cl" ]
	     ]
	     constrainAdj [
	        id 0
	        op =
	        count 2
	        nodeLabels [ label "H" ]
	     ]
	   ]

	   ==============================================
	   \endverbatim
	 *
	 * @author Martin Mann (c) 2010 http://www.bioinf.uni-freiburg.de/~mmann/
	 *
	 */
	class MoleculeComponent_GML_grammar
	  : public NS_BOOSTSPIRIT::grammar< MoleculeComponent_GML_grammar >
	{
	protected:

		  //! type for mapping integers to size_t
		typedef
#if HAVE_UNORDERED_MAP > 0
		std::unordered_map<int, size_t>
#elif HAVE_TR1_UNORDERED_MAP > 0
		std::tr1::unordered_map<int, size_t>
#else
		std::map<int, size_t>
#endif
		MapIntSizeT;

	protected:

		  //! The boost core graph object that is filled to represent the next
		  //! parsed Rule.
	    MoleculeComponent& toFill;

	public:

		  //! Constructs the definitions of a GML graph grammar to parse
		  //! a GML graph string representation and to fill the encoded graph
		  //! into a given boost graph object.
		  //! @param toFill the object to add nodes and edges to
	    explicit MoleculeComponent_GML_grammar( MoleculeComponent & toFill );

	      //! Parses a GML string and generates a MoleculeComponent::PatternGraph object
	      //! @param GML_string the string to parse
	      //! @return pair.first = the graph encoding of the molecule
	      //!         pair.second = -1 if parsing was successfull,
	      //!         in error case it returns the string position that caused
	      //!         the parsing error
	      //! @throw std::invalid_argument in case a check fails
	    static
	    std::pair< MoleculeComponent, int >
	    parseGML( const std::string & GML_string ) throw (std::invalid_argument);

		  //! The definition of the GML grammar.
	    template <typename ScannerT>
	    struct definition
	    {
	    public:

	    	  //! Construction of the GML BNF grammar rules to parse a
	    	  //! MoleculeComponent
	    	  //! @param self access to the calling grammar
	    	definition( const MoleculeComponent_GML_grammar & self );

	    	  //! start parsing
	    	NS_BOOSTSPIRIT::rule<ScannerT> const&
	    	start() const;

	    protected:

	          //! the molecule component to be filled
	        MoleculeComponent& toFill;

			  //! Access to the node label property_map of toFill to set node labels
			boost::property_map< MoleculeComponent::PatternGraph, PropNodeLabel>::type
		    	nodeLabel;

			  //! Access to the edge label property_map of g2fill to set edge labels
			boost::property_map< MoleculeComponent::PatternGraph, PropEdgeLabel>::type
		    	edgeLabel;

	          //! the mapping of node IDs in the GML notation and their
	          //! corresponding node IDs in the created pattern graph
	        MapIntSizeT nodeMapping;

	          //! the rules to be parsed
	        NS_BOOSTSPIRIT::rule<ScannerT> molcomp, content, node, edge,
					compIDs, constrainAdjacency, constrainLabel, ringFragment;

	        // temporary data structures
			int curNodeID, curEdgeFromID, curEdgeToID;
			std::string curNodeLabel, curEdgeLabel;
			std::string curRingFragmentTypeString;
			// temporary constraint objects
			MC_MC_NodeAdjacency constrAdj;
			char constrAdjOp, constrLabelOp;
			MC_MC_NodeLabel constrLabel;
			MoleculeComponent::RingFragmentList curRingFragmentList;

			enum WhatList {
				Fill_constrAdj_NL,
				Fill_constrAdj_EL,
				Fill_constrLabel_NL,
				Fill_compIDs,
				Fill_ringFragments
			};

	        // helper functions

	        /*!
	          * Resets toFill to enable the detection of missing information
	          * within final_checks()
	          */
	        void clear_toFill(void);

	        /*!
	          * Performs final checks on toFill to ensure that the parse was
	          * correct
	          *
	          * @throw std::invalid_argument in case a check fails
	          */
	        void final_checks(void) throw (std::invalid_argument);

	        /*!
	          * Stores a node of the MoleculeComponent pattern graph.
	          * @throw std::invalid_argument in case a check fails
	          */
	        void store_node(void) throw (std::invalid_argument);

	        /*!
	          * Stores an edge of the MoleculeComponent pattern graph.
	          * @throw std::invalid_argument in case a check fails
	          */
	        void store_edge(void) throw (std::invalid_argument);

	        /*!
	          * Stores a node adjacency constraint of the MoleculeComponent
	          */
	        void store_constrAdj(void);

	        /*!
	          * Stores a node label constraint of the MoleculeComponent
	          */
	        void store_constrLabel(void);

	        /*!
	          * Inserts a string into a given string set
	          * @param list the encoding which list to be fill
	          */
	        void insert_to_list( WhatList list );

	    }; // end of description

	}; // end of MoleculeComponent_GML_grammar

} // namespace chem
} // namespace ggl

// include implementation
#include "ggl/chem/MoleculeComponent_GML_grammar.icc"

#endif /*GGL_CHEM_MOLECULECOMPONENT_GML_GRAMMAR_HH_*/

max_stars_repo_name: michaelapeterka/GGL

max_issues_repo_name: michaelapeterka/GGL

max_forks_repo_name: michaelapeterka/GGL


text:
/*
 * Distrubuted under The MIT License (MIT)
 *
 * Copyright (c) 2016 Aaron Bishop
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef BREWPIPP_UTIL_BUFFERED_IO_HPP
#define BREWPIPP_UTIL_BUFFERED_IO_HPP

#include <memory>
#include <cstring>
#include <boost/system/system_error.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace brewpipp {
	namespace util {
		class AsyncImpl;

		class BufferedIO {
		public:
			class TimeoutException : public std::exception {
			public:
				TimeoutException() = default;
				const char* what() const throw() { return "Operation Timed Out"; }
			};

			//Async statements
			template<intptr_t N>
			void write(const char (&data) [N]) throw(boost::system::system_error) { write(data, data+N-1); }

			///Write data and return immediately
			void write(const char* data_begin, const char* data_end) throw(boost::system::system_error);

			///Wait until delim has been read or timeout has been reached
			std::string readStringUntil(const boost::posix_time::time_duration& timeout, const std::string& delim="\n") throw(boost::system::system_error, TimeoutException);

			void close() throw(boost::system::system_error);

			bool isOpen() const;

			void open() throw(boost::system::system_error);

			boost::system::error_code errorStatus() const;

			virtual ~BufferedIO();

		protected:
			BufferedIO(std::shared_ptr<AsyncImpl>&& impl);
			std::shared_ptr<AsyncImpl> pimpl;
		};
	}
}

#endif //BREWPIPP_UTIL_BUFFERED_IO_HPP


text:
//
//#include <boost\python.hpp>
//
//
//
//char const* greet()
//{
//	return "hello world";
//
//}
//
//BOOST_PYTHON_MODULE(boostDemo)
//{
//	using namespace boost::python;
//	def("greet", greet);
//}

max_stars_repo_name: rozentill/boostDemo

max_issues_repo_name: rozentill/boostDemo

max_forks_repo_name: rozentill/boostDemo


text:
#include "petresearchinstitute.h"
#include "aliencoinunits.h"
#include "ui_petresearchinstitute.h"
#include <QGridLayout>
#include <QPushButton>
#include <QDateTime>
#include "walletmodel.h"
#include "init.h"
#include "util.h"
#include "core_io.h"
#include "utilmoneystr.h"
#include <stdint.h>

#include "amount.h"
#include "base58.h"

#include "rpcserver.h"
#include "net.h"
#include "netbase.h"
#include "timedata.h"

#include "wallet.h"
#include "walletdb.h"

#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"

using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;

int petBorn = 99;

std::map<std::string, std::map<int, int>> petPropetyNumber{
    {"liliang"  , {{99, 0}, {-1, 2000}, {0, 1500}, {1, 1000}, {2, 500}, {3, 100}} },
    {"minjie"   , {{99, 0}, {-1, 2000}, {0, 1500}, {1, 1000}, {2, 500}, {3, 100}} },
    {"zhili"    , {{99, 0}, {-1, 2000}, {0, 1500}, {1, 1000}, {2, 500}, {3, 100}} },
    {"tongshuai", {{99, 0}, {-1, 200}, {0, 150}, {1, 100}, {2, 100}, {3, 100}} },
    {"gedang"   , {{99, 0}, {-1, 20}, {0, 15}, {1, 10}, {2, 10}, {3, 10}} },
    {"baoji"    , {{99, 0}, {-1, 20}, {0, 15}, {1, 10}, {2, 10}, {3, 10}} },
    {"yidong"   , {{99, 0}, {-1, 5}, {0, 3}, {1, 2}, {2, 2}, {3, 2}} },
    {"tiaoju"   , {{99, 0}, {-1, 5}, {0, 3}, {1, 2}, {2, 2}, {3, 2}} },
    {"gongju"   , {{99, 0}, {-1, 5}, {0, 3}, {1, 2}, {2, 2}, {3, 2}} },
    {"shunfa"   , {{99, 0}, {-1, 5}, {0, 3}, {1, 2}, {2, 2}, {3, 2}} },
    {"keji"     , {{99, 0}, {-1, 10}, {0, 8}, {1, 5}, {2, 5}, {3, 5}} },
    {"chaonengli", {{99, 0}, {-1, 10}, {0, 8}, {1, 5}, {2, 5}, {3, 5}} },
    {"tuanzhan" , {{99, 0}, {-1, 15}, {0, 10}, {1, 5}, {2, 5}, {3, 5}} },
    {"juejin"   , {{99, 0}, {-1, 20}, {0, 15}, {1, 10}, {2, 5}, {3, 1}} },
    };
std::map<std::string, int> petPropetyResult{
		{"liliang"	, 0},
		{"minjie"	, 0},
		{"zhili"	, 0},
		{"tongshuai", 0},
		{"gedang"	, 0},
		{"baoji"	, 0},
		{"yidong"	, 0},
		{"tiaoju"	, 0},
		{"gongju"	, 0},
		{"shunfa"	, 0},
		{"keji" 	, 0},
		{"chaonengli", 0},
		{"tuanzhan" , 0},
		{"juejin"	, 0},
		};

static QWidget* makePetFrameSpacer()
{
    QWidget* spacer = new QWidget();
    spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
    spacer->setStyleSheet("QWidget { background: rgb(30,32,36); }");
    return spacer;
}

PetResearchInstitute::PetResearchInstitute(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PetResearchInstitute),
	walletModel(0),
    leftPetWidget(0)
{
    ui->setupUi(this);

	// 在此出加入界面设计代码;
	// 水平布局;
	auto vgirdLayout = new QGridLayout();
	// 将主要显示的数据放置于中心;

	auto centerWidget = new QWidget(this);
	InitPetMainFrame(centerWidget);
	// 设置子窗口;
	// 添加一个空白;
	QSpacerItem* verticalSpacer1 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
	QSpacerItem* verticalSpacer2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
    // fix app crash when closing, think hSpacer1 was deleted twice.
    QSpacerItem* hSpacer1 = new QSpacerItem(40, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
	QSpacerItem* hSpacer2 = new QSpacerItem(40, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
	vgirdLayout->addItem(verticalSpacer1,0,0,1,3);
	vgirdLayout->addItem(hSpacer1,1,0,1,1);
	// 第二行第二列为主显示界面;
	vgirdLayout->addWidget(centerWidget, 1, 1, 1, 1);
    vgirdLayout->addItem(hSpacer2,1,2,1,1);
	vgirdLayout->addItem(verticalSpacer2,2,0,1,3);

	setLayout(vgirdLayout);
}

PetResearchInstitute::~PetResearchInstitute()
{
    delete ui;
}

void PetResearchInstitute::InitPetMainLeftWidget(QWidget* pLeftWidget)
{
	// 增加一个带图片的widget即可;
	if(pLeftWidget)
	{
		pLeftWidget->setMinimumSize(344,530);
		pLeftWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
		pLeftWidget->setStyleSheet("QWidget { border-image:url(:/images/gen0);}");

		auto righthLayout = new QHBoxLayout(pLeftWidget);
	}

}
void PetResearchInstitute::InitPetMainRightWidget(QWidget* pRightWidget)
{
	// 左侧是一个StackWidget;
	pRightWidget->setMinimumSize(408,480);
	pRightWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	pRightWidget->setStyleSheet("QWidget { background-color: rgba(255, 255, 255, 0); }");
	auto righthLayout = new QHBoxLayout(pRightWidget);
	righthLayout->setContentsMargins(3,0,3,0);
	righthLayout->setSpacing(0);
	attrWidget = new QStackedWidget(pRightWidget);
	attrWidget->setMinimumSize(408,480);
	// 设置Attr的相关属性;
	petAttrWidget = new PetAttrDialog(attrWidget);
	attrWidget->addWidget(petAttrWidget);
	petAttrWidget->setMinimumSize(408,480);
	petPowerWidget = new CombatPowerDialog(attrWidget);
	attrWidget->addWidget(petPowerWidget);
	petPowerWidget->setMinimumSize(408,480);
	petFeedWidget = new PetFeedDialog(attrWidget);
	attrWidget->addWidget(petFeedWidget);
	petFeedWidget->setMinimumSize(408,480);
	petHowtoplay = new HowToPlayDialog(attrWidget);
	attrWidget->addWidget(petHowtoplay);
	petHowtoplay->setMinimumSize(408,480);
	// 右侧是一个Actions;
	auto boxLayout = new QVBoxLayout(pRightWidget);
	QButtonGroup* btnGroup = new QButtonGroup(pRightWidget);
	// 设置两个Actor之间的间隔;
	btnAttr = new QPushButton(tr("属\n性"), pRightWidget);
	SetTabPushButtonSheet(btnAttr);
	btnGroup->addButton(btnAttr);
	boxLayout->addWidget(btnAttr);
	btnAttr->setChecked(true);
    connect(btnAttr, SIGNAL(toggled(bool)), this, SLOT(gotoPetAttr(bool)));

	// 添加到group中;
	btnPower = new QPushButton(tr("战\n力"), pRightWidget);
	SetTabPushButtonSheet(btnPower);
	btnGroup->addButton(btnPower);
	boxLayout->addWidget(btnPower);
    connect(btnPower, SIGNAL(toggled(bool)), this, SLOT(gotoPetPower(bool)));
	// 设置信号和槽

	auto btnFeed = new QPushButton(tr("喂\n养"), pRightWidget);
	SetTabPushButtonSheet(btnFeed);
	btnGroup->addButton(btnFeed);
	boxLayout->addWidget(btnFeed);
	connect(btnFeed, SIGNAL(toggled(bool)), this, SLOT(gotoPetFeed(bool)));
	// 设置信号和槽

	auto btnPlay = new QPushButton(tr("玩\n法"), pRightWidget);
	SetTabPushButtonSheet(btnPlay);
	btnGroup->addButton(btnPlay);
	boxLayout->addWidget(btnPlay);
	connect(btnPlay, SIGNAL(toggled(bool)), this, SLOT(gotoPetPlay(bool)));
	// 设置信号和槽
	// 将4个按钮放置到boxlayout;
	righthLayout->addWidget(attrWidget);
	// 添加子layout;
	righthLayout->addLayout(boxLayout);
}

void PetResearchInstitute::InitPetMainFrame(QWidget *pSubFrame)
{
	// 设置中心窗口的大小;
	pSubFrame->setMinimumSize(830, 530);
	pSubFrame->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	// 设置水平的layout;
	auto hLayOut = new QHBoxLayout(pSubFrame);
	hLayOut->setContentsMargins(3,0,3,0);
	// 中间设置28px的间隔;
    hLayOut->setSpacing(0);
	// 设置左侧的窗口;
	leftPetWidget = new QWidget(pSubFrame);
	InitPetMainLeftWidget(leftPetWidget);
	hLayOut->addWidget(leftPetWidget);
	rightPetWidget = new QWidget(pSubFrame);
	InitPetMainRightWidget(rightPetWidget);
	// 设计右侧的窗口;
	hLayOut->addWidget(rightPetWidget);

}

void PetResearchInstitute::ListSendToBoss(const CWalletTx& wtx, const string& strAccount, int nMinDepth,
                    const set<string>& destAddresses, CAmount desAmount, Array& ret, vector<CTx4Pet>& ret4pet)
{
    CAmount nFee;
    string strSentAccount;
    list<COutputEntry> listSent;

    isminefilter filter = ISMINE_SPENDABLE;

    wtx.GetSendAmounts(listSent, nFee, strSentAccount, filter);

    bool fAllAccounts = (strAccount == string("*"));
//    bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);

    // Sent
    if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
    {
        BOOST_FOREACH(const COutputEntry& soutEntry, listSent)
        {
            Object entry;
//            if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
//                entry.push_back(Pair("involvesWatchonly", true));
            //MaybePushAddress(entry, s.destination);
            CAliencoinAddress addr;

            if (addr.Set(soutEntry.destination)
                    && (destAddresses.find(addr.ToString()) != destAddresses.end()))
            {
                 entry.push_back(Pair("address", addr.ToString()));
            }
            else
                continue;

            int confirms = wtx.GetDepthInMainChain();
            CAmount txAmount = soutEntry.amount;
            if (confirms < nMinDepth ||  txAmount < (desAmount * COIN))
                continue;

            entry.push_back(Pair("time", wtx.GetTxTime()));
            entry.push_back(Pair("confirmations", confirms));
            entry.push_back(Pair("amount", ValueFromAmount(txAmount)));

            //entry.push_back(Pair("account", strSentAccount));
            //entry.push_back(Pair("category", "send"));
            //WalletTxToJSON(wtx, entry);

            uint256 hash = wtx.GetHash();
            entry.push_back(Pair("txid", hash.GetHex()));
            entry.push_back(Pair("vout", soutEntry.vout));

            CTx4Pet tx4pet;
            tx4pet.sendTime = wtx.GetTxTime();
            tx4pet.sendAmount = txAmount / COIN;
            tx4pet.sendTxid = hash.ToString();
            ret4pet.push_back(tx4pet);

            ret.push_back(entry);
            if (ret.size() > 0)
                break;
        }
    }
}

void PetResearchInstitute::ListSendToSeed(const CWalletTx& wtx, const string& strAccount, int nMinDepth,
                    const set<string>& destAddresses, CAmount desAmount, Array& ret, vector<CTx4Pet>& ret4pet)
{
    CAmount nFee;
    string strSentAccount;
    list<COutputEntry> listSent;

    isminefilter filter = ISMINE_SPENDABLE;

    wtx.GetSendAmounts(listSent, nFee, strSentAccount, filter);

    bool fAllAccounts = (strAccount == string("*"));

    // Sent
    if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
    {
        BOOST_FOREACH(const COutputEntry& soutEntry, listSent)
        {
            Object entry;
//            if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
//                entry.push_back(Pair("involvesWatchonly", true));
            //MaybePushAddress(entry, s.destination);
            CAliencoinAddress addr;

            if (addr.Set(soutEntry.destination)
                    && (destAddresses.find(addr.ToString()) != destAddresses.end()))
            {
                 entry.push_back(Pair("address", addr.ToString()));
            }
            else
                continue;

            int confirms = wtx.GetDepthInMainChain();
            CAmount txAmount = soutEntry.amount;
            if (confirms < nMinDepth ||  txAmount != (desAmount * COIN))
                continue;

            entry.push_back(Pair("time", wtx.GetTxTime()));
            entry.push_back(Pair("confirmations", confirms));
            entry.push_back(Pair("amount", ValueFromAmount(txAmount)));

            //entry.push_back(Pair("account", strSentAccount));
            //entry.push_back(Pair("category", "send"));
            //WalletTxToJSON(wtx, entry);

            uint256 hash = wtx.GetHash();
            entry.push_back(Pair("txid", hash.GetHex()));
            entry.push_back(Pair("vout", soutEntry.vout));

            CTx4Pet tx4pet;
            int txtime = wtx.GetTxTime();
            tx4pet.sendTime = txtime;
            tx4pet.sendAmount = txAmount / COIN;
            tx4pet.sendTxid = hash.ToString();

            if (ret4pet.size() > 0 && (txtime - ret4pet.back().sendTime) < vaid_interval)
                continue;

            ret4pet.push_back(tx4pet);
            ret.push_back(entry);

        }
    }
}

void PetResearchInstitute::ListSendToXiaohui(const CWalletTx& wtx, const string& strAccount, int nMinDepth,
                    const set<string>& destAddresses, CAmount desAmount, Array& ret, vector<CTx4Pet>& ret4pet)
{
    CAmount nFee;
    string strSentAccount;
    list<COutputEntry> listSent;
    isminefilter filter = ISMINE_SPENDABLE;
    wtx.GetSendAmounts(listSent, nFee, strSentAccount, filter);
    bool fAllAccounts = (strAccount == string("*"));

    if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
    {
        BOOST_FOREACH(const COutputEntry& soutEntry, listSent)
        {
            Object entry;
            CAliencoinAddress addr;

            if (addr.Set(soutEntry.destination)
                    && (destAddresses.find(addr.ToString()) != destAddresses.end()))
            {
                 entry.push_back(Pair("address", addr.ToString()));
            }
            else
                continue;

            int confirms = wtx.GetDepthInMainChain();
            CAmount txAmount = soutEntry.amount;
            if (confirms < nMinDepth ||  txAmount != (desAmount * COIN))
                continue;

            entry.push_back(Pair("time", wtx.GetTxTime()));
            entry.push_back(Pair("confirmations", confirms));
            entry.push_back(Pair("amount", ValueFromAmount(txAmount)));

            uint256 hash = wtx.GetHash();
            entry.push_back(Pair("txid", hash.GetHex()));
            entry.push_back(Pair("vout", soutEntry.vout));

            CTx4Pet tx4pet;
            tx4pet.sendTime = wtx.GetTxTime();
            tx4pet.sendAmount = txAmount / COIN;
            tx4pet.sendTxid = hash.ToString();
            ret4pet.push_back(tx4pet);

            ret.push_back(entry);
            if (ret.size() > 0)
                break;
        }
    }
}

void PetResearchInstitute::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)
{

	string strAccount = "*";

    Array ret4cli;
    vector<CTx4Pet> ret4pet;
    std::list<CAccountingEntry> acentries;
    CWallet::TxItems txOrdered;

    //查看宠物是否销毁
    //---------------------------------------------------------------------------------------//
    txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);

    for (CWallet::TxItems::iterator it = txOrdered.begin(); it != txOrdered.end(); ++it)
    {
        CWalletTx *const pwtx = (*it).second.first;
        if (pwtx != 0)
            ListSendToXiaohui(*pwtx, strAccount, confirms, xiaohuiAddress, xiaohuiAmount, ret4cli, ret4pet);
    }

    if (ret4pet.size() > 0)
    {
        string strDebugMsg = strprintf("debug,listsendtoxiaohui: %s, %s, %s ",
                                       ret4pet.front().sendTxid,
                                       ret4pet.front().sendTime,
                                       ret4pet.front().sendAmount);
        //LogPrintf(" : %s\n", strDebugMsg);
        petBorn = 444;
        this->leftPetWidget->setStyleSheet("QWidget { border-image:url(:/images/pet444);}");
        return;
    }

    //获取几代接口
    //---------------------------------------------------------------------------------------//
    ret4cli.clear();
    ret4pet.clear();
    acentries.clear();
    txOrdered.clear();

    txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
    for (CWallet::TxItems::iterator it = txOrdered.begin(); it != txOrdered.end(); ++it)
    {
        CWalletTx *const pwtx = (*it).second.first;
        if (pwtx != 0)
            ListSendToBoss(*pwtx, strAccount, confirms, bossAddress, firstAmount, ret4cli, ret4pet);
        if (ret4cli.size() > 0)
            break;
    }

    CAmount hitAmount = 0;
    if (ret4pet.size() > 0)
    {
        hitAmount = ret4pet.front().sendAmount;
        string strDebugMsg = strprintf("debug,listsendtoboss: %s, %s, %s ",
                                       ret4pet.front().sendTxid,
                                       ret4pet.front().sendTime,
                                       ret4pet.front().sendAmount);
       // LogPrintf(" : %s\n", strDebugMsg);
    }

    //根据计算几代结果，设置对应的图片
    //把图片放入对应目录，然后修改aliencoin.qrc文件
    //如下设置未领养的图片
    // TODO: for test, should be 100000
    switch (hitAmount)
    {
        case 1000000000:
            petBorn = -1;
            this->leftPetWidget->setStyleSheet("QWidget { border-image:url(:/images/pet-1);}");
            break;
        case 100000000:
            petBorn = 0;
            this->leftPetWidget->setStyleSheet("QWidget { border-image:url(:/images/pet0);}");
            break;
        case 10000000:
            petBorn = 1;
            this->leftPetWidget->setStyleSheet("QWidget { border-image:url(:/images/pet1);}");
            break;
        case 1000000:
            petBorn = 2;
            this->leftPetWidget->setStyleSheet("QWidget { border-image:url(:/images/pet2);}");
            break;
        case firstAmount:
            petBorn = 3;
            this->leftPetWidget->setStyleSheet("QWidget { border-image:url(:/images/pet3);}");
            break;
        default:
            petBorn = 99;
            this->leftPetWidget->setStyleSheet("QWidget { border-image:url(:/images/pet100);}");
    }

    //获取属性接口
    //---------------------------------------------------------------------------------------//
    ret4cli.clear();
    ret4pet.clear();
    acentries.clear();
    txOrdered.clear();

    txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
    for (CWallet::TxItems::iterator it = txOrdered.begin(); it != txOrdered.end(); ++it)
    {
        CWalletTx *const pwtx = (*it).second.first;
        if (pwtx != 0)
            ListSendToSeed(*pwtx, strAccount, confirms, feedAddresses, eachFeedAmount, ret4cli, ret4pet);
    }

    for (unsigned int i = 0; i < ret4pet.size(); i++)
    {
        string strDebugMsg = strprintf("debug,listsendtoseed: %d, %s, %s, %s ",
                                       i,
                                       ret4pet.at(i).sendTxid,
                                       ret4pet.at(i).sendTime,
                                       ret4pet.at(i).sendAmount);
        //LogPrintf(" : %s\n", strDebugMsg);
    }

    feedCount = ret4pet.size();
    if (petBorn != 99)
    {
        if (feedCount > 0)
        {
            int lastfeedtime = ret4pet.back().sendTime;
            nextfeedtime = lastfeedtime + vaid_interval + 60;
            QDateTime dtime = QDateTime::fromTime_t(nextfeedtime);
            QString strtime = dtime.toString("yyyy-MM-dd hh:mm:ss");

            petFeedWidget->setAttr(QString("下次可喂养时间: ") + strtime);
        }
        else
        {

            petFeedWidget->setAttr(QString("随时可以喂养"));
        }
    }
    else
    {

    }

    zhanli = 0;
    if(petBorn != 99)
    {
        dengji = feedCount;
    }

    std::map<std::string, int>::iterator iter;
    for (iter = petPropetyResult.begin(); iter != petPropetyResult.end(); ++iter)
    {
        iter->second = petPropetyNumber[iter->first][petBorn] * feedCount;
        zhanli += iter->second;
    }
    // 综合评估：
    // 战斗力=力量+敏捷+智力+格挡+暴击+移动+跳距+攻距+瞬发+科技熟练+超能力+团战指挥+统帅 (除去战力之外的其他相加)
    zhanli -= petPropetyResult["juejin"];

	//根据计算结果，setAttr设置对应的属性，目前只设置了两个属性，可以扩展该函数设置所有属性
	//setAttr 在petattrdialog.h定义
	//petattrdialog.cpp 实现，根据ui设置属性
//    {"liliang"  , 0},
//    {"minjie"   , 0},
//    {"zhili"    , 0},
//    {"tongshuai", 0},
//    {"gedang"   , 0},
//    {"baoji"    , 0},
//    {"yidong"   , 0},
//    {"tiaoju"   , 0},
//    {"gongju"   , 0},
//    {"shunfa"   , 0},
//    {"keji"     , 0},
//    {"chaonengli", 0},
//    {"tuanzhan" , 0},
//    {"juejin"   , 0},
    petAttrWidget->setAttr(petPropetyResult["liliang"], petPropetyResult["minjie"], petPropetyResult["zhili"],
            petPropetyResult["tongshuai"], petPropetyResult["gedang"], petPropetyResult["baoji"],
            petPropetyResult["yidong"], petPropetyResult["tiaoju"], petPropetyResult["gongju"],
            petPropetyResult["shunfa"], petPropetyResult["keji"], petPropetyResult["chaonengli"],
            petPropetyResult["tuanzhan"], petPropetyResult["juejin"],
            dengji);

    petPowerWidget->setAttr(zhanli);

    //LogPrintf("###监听事件, listen event!!!\n");

    ret4cli.clear();
    ret4pet.clear();
}

void PetResearchInstitute::setWalletModel(WalletModel *model)
{
    this->walletModel = model;
    if(model && model->getOptionsModel())
    {
        // Set up transaction list
		/*
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setLimit(NUM_ITEMS);
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->setShowInactive(false);
        filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);

        ui->listTransactions->setModel(filter);
        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
        */
        // Keep up to date with wallet

        setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),
                   model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
 //       connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)));

        //connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));

        //updateWatchOnlyLabels(model->haveWatchOnly());
        //connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));

    }

    // update the display unit, to not use the default ("ALC")
    //updateDisplayUnit();
}

void PetResearchInstitute::SetTabPushButtonSheet(QPushButton* pPushButton)
{
	if(!pPushButton) return;

	// 设置大小;
	pPushButton->setFixedWidth(56);

	pPushButton->setFixedHeight(99);
	//添加状态;

	pPushButton->setStyleSheet("QPushButton{border-image:url(:/images/btnnor);color: rgb(255, 255, 255);font: 20pt \"Arial\";}"
							   "QPushButton:hover{border-image:url(:/images/btnsel);color: rgb(132, 146, 166); font: 20pt \"Arial\";}"
							   "QPushButton:checked{border-image:url(:/images/btnsel);color: rgb(132, 146, 166); font: 20pt \"Arial\";}"
							   "QPushButton:pressed{border-image:url(:/images/btnsel);color: rgb(132, 146, 166); font: 20pt \"Arial\";}");
	pPushButton->setCheckable(true);

}

void PetResearchInstitute::gotoPetAttr(bool flag)
{
    if (attrWidget) attrWidget->setCurrentWidget(petAttrWidget);
}

void PetResearchInstitute::gotoPetPower(bool flag)
{
    if (attrWidget) attrWidget->setCurrentWidget(petPowerWidget);
}

void PetResearchInstitute::gotoPetFeed(bool flag)
{
    if (petFeedWidget) attrWidget->setCurrentWidget(petFeedWidget);
}
void PetResearchInstitute::gotoPetPlay(bool flag)
{
    if (attrWidget) attrWidget->setCurrentWidget(petHowtoplay);
}

max_stars_repo_name: waixingdun/Aliencoin

max_issues_repo_name: waixingdun/Aliencoin

max_forks_repo_name: waixingdun/Aliencoin