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.

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <vector>
#include <boost/scoped_ptr.hpp>

#include "common/init.h"
#include "exec/row-batch-list.h"
#include "runtime/descriptors.h"
#include "runtime/mem-pool.h"
#include "runtime/mem-tracker.h"
#include "runtime/string-value.h"
#include "runtime/tuple-row.h"
#include "service/fe-support.h"
#include "service/frontend.h"
#include "util/runtime-profile-counters.h"
#include "testutil/desc-tbl-builder.h"
#include "testutil/gtest-util.h"

#include "common/names.h"

using namespace impala;

namespace impala {

// For computing tuple mem layouts.
scoped_ptr<Frontend> fe;

class RowBatchListTest : public testing::Test {
 public:
  RowBatchListTest() {}

 protected:
  MemTracker tracker_;
  ObjectPool pool_;
  RowDescriptor* desc_;

  virtual void SetUp() {
    DescriptorTblBuilder builder(fe.get(), &pool_);
    builder.DeclareTuple() << TYPE_INT;
    DescriptorTbl* desc_tbl = builder.Build();
    vector<bool> nullable_tuples(1, false);
    vector<TTupleId> tuple_id(1, (TTupleId) 0);
    desc_ = pool_.Add(new RowDescriptor(*desc_tbl, tuple_id, nullable_tuples));
  }

  RowBatch* CreateRowBatch(int start, int end) {
    int num_rows = end - start + 1;
    RowBatch* batch = pool_.Add(new RowBatch(*desc_, num_rows, &tracker_));
    int32_t* tuple_mem = reinterpret_cast<int32_t*>(
        batch->tuple_data_pool()->Allocate(sizeof(int32_t) * num_rows));

    for (int i = start; i <= end; ++i) {
      int idx = batch->AddRow();
      TupleRow* row = batch->GetRow(idx);
      *tuple_mem = i;
      row->SetTuple(0, reinterpret_cast<Tuple*>(tuple_mem));

      batch->CommitLastRow();
      tuple_mem++;
    }
    return batch;
  }

  // Validate that row contains the expected value
  void ValidateMatch(TupleRow* row, int32_t expected) {
    EXPECT_EQ(expected, *reinterpret_cast<int32_t*>(row->GetTuple(0)));
  }

  void FullScan(RowBatchList* list, int start, int end) {
    EXPECT_LT(start, end);
    RowBatchList::TupleRowIterator it = list->Iterator();
    int i = start;
    while (!it.AtEnd()) {
      EXPECT_TRUE(it.GetRow() != NULL);
      ValidateMatch(it.GetRow(), i);
      it.Next();
      ++i;
    }
    EXPECT_EQ(end, i - 1);
  }
};

// This tests inserts the rows [0->5] to list. It validates that they are all there.
TEST_F(RowBatchListTest, BasicTest) {
  RowBatchList row_list;
  RowBatch* batch = CreateRowBatch(0, 5);
  row_list.AddRowBatch(batch);
  EXPECT_EQ(row_list.total_num_rows(), 6);

  // Do a full table scan and validate returned pointers
  FullScan(&row_list, 0, 5);
}

// This tests an empty batch is handled correctly.
TEST_F(RowBatchListTest, EmptyBatchTest) {
  const int ALLOC_SIZE = 128;
  RowBatchList row_list;
  RowBatch* batch1 = pool_.Add(new RowBatch(*desc_, 1, &tracker_));
  batch1->tuple_data_pool()->Allocate(ALLOC_SIZE);
  DCHECK_EQ(ALLOC_SIZE, batch1->tuple_data_pool()->total_allocated_bytes());

  row_list.AddRowBatch(batch1);
  EXPECT_EQ(row_list.total_num_rows(), 0);
  RowBatchList::TupleRowIterator it = row_list.Iterator();
  EXPECT_TRUE(it.AtEnd());

  // IMPALA-4049: list should transfer resources attached to empty batch.
  RowBatch* batch2 = pool_.Add(new RowBatch(*desc_, 1, &tracker_));
  DCHECK_EQ(0, batch2->tuple_data_pool()->total_allocated_bytes());
  row_list.TransferResourceOwnership(batch2);
  DCHECK_EQ(0, batch1->tuple_data_pool()->total_allocated_bytes());
  DCHECK_EQ(ALLOC_SIZE, batch2->tuple_data_pool()->total_allocated_bytes());
}

// This tests inserts 100 row batches of 1024 rows each to list.  It validates that they
// are all there.
TEST_F(RowBatchListTest, MultipleRowBatchesTest) {
  RowBatchList row_list;

  int BATCH_SIZE = 1024;
  for (int batch_idx = 0; batch_idx < 100; ++batch_idx) {
    int batch_start = batch_idx * BATCH_SIZE;
    int batch_end = batch_start + BATCH_SIZE - 1;
    RowBatch* batch = CreateRowBatch(batch_start, batch_end);
    row_list.AddRowBatch(batch);
    EXPECT_EQ(row_list.total_num_rows(), batch_end + 1);
    FullScan(&row_list, 0, batch_end);
  }
}

}

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  InitCommonRuntime(argc, argv, true, impala::TestInfo::BE_TEST);
  InitFeSupport();
  fe.reset(new Frontend());
  return RUN_ALL_TESTS();
}

max_stars_repo_name: michaelhkw/impala

max_issues_repo_name: michaelhkw/impala

max_forks_repo_name: michaelhkw/impala


text:
/*
	This file is part of solidity.

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

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

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

#include <test/yulPhaser/TestHelpers.h>

#include <tools/yulPhaser/Mutations.h>

#include <tools/yulPhaser/SimulationRNG.h>

#include <boost/test/unit_test.hpp>

#include <algorithm>
#include <vector>

using namespace std;

namespace solidity::phaser::test
{

BOOST_AUTO_TEST_SUITE(Phaser)
BOOST_AUTO_TEST_SUITE(MutationsTest)
BOOST_AUTO_TEST_SUITE(GeneRandomisationTest)

BOOST_AUTO_TEST_CASE(geneRandomisation_should_iterate_over_genes_and_replace_them_with_random_ones_with_given_probability)
{
	Chromosome chromosome("fcCUnDvejs");
	function<Mutation> mutation01 = geneRandomisation(0.1);
	function<Mutation> mutation05 = geneRandomisation(0.5);
	function<Mutation> mutation10 = geneRandomisation(1.0);

	SimulationRNG::reset(1);
	BOOST_TEST(countDifferences(mutation01(chromosome), chromosome), 2);
	BOOST_TEST(countDifferences(mutation05(chromosome), chromosome), 5);
	BOOST_TEST(countDifferences(mutation10(chromosome), chromosome), 7);
	SimulationRNG::reset(2);
	BOOST_TEST(countDifferences(mutation01(chromosome), chromosome), 1);
	BOOST_TEST(countDifferences(mutation05(chromosome), chromosome), 3);
	BOOST_TEST(countDifferences(mutation10(chromosome), chromosome), 9);
}

BOOST_AUTO_TEST_CASE(geneRandomisation_should_return_identical_chromosome_if_probability_is_zero)
{
	Chromosome chromosome("fcCUnDvejsrmV");
	function<Mutation> mutation = geneRandomisation(0.0);

	BOOST_TEST(mutation(chromosome) == chromosome);
}

BOOST_AUTO_TEST_CASE(geneDeletion_should_iterate_over_genes_and_delete_them_with_given_probability)
{
	Chromosome chromosome("fcCUnDvejs");
	function<Mutation> mutation01 = geneDeletion(0.1);
	function<Mutation> mutation05 = geneDeletion(0.5);

	SimulationRNG::reset(1);
	//                                                               fcCUnDvejs
	BOOST_TEST(mutation01(chromosome) == Chromosome(stripWhitespace("fcCU Dvejs")));
	BOOST_TEST(mutation05(chromosome) == Chromosome(stripWhitespace("     D ejs")));
	SimulationRNG::reset(2);
	BOOST_TEST(mutation01(chromosome) == Chromosome(stripWhitespace("fcUnDvejs")));
	BOOST_TEST(mutation05(chromosome) == Chromosome(stripWhitespace("  Un    s")));
}

BOOST_AUTO_TEST_CASE(geneDeletion_should_return_identical_chromosome_if_probability_is_zero)
{
	Chromosome chromosome("fcCUnDvejsrmV");
	function<Mutation> mutation = geneDeletion(0.0);

	BOOST_TEST(mutation(chromosome) == chromosome);
}

BOOST_AUTO_TEST_CASE(geneDeletion_should_delete_all_genes_if_probability_is_one)
{
	Chromosome chromosome("fcCUnDvejsrmV");
	function<Mutation> mutation = geneDeletion(1.0);

	BOOST_TEST(mutation(chromosome) == Chromosome(""));
}

BOOST_AUTO_TEST_CASE(geneAddition_should_iterate_over_gene_positions_and_insert_new_genes_with_given_probability)
{
	Chromosome chromosome("fcCUnDvejs");
	function<Mutation> mutation01 = geneAddition(0.1);
	function<Mutation> mutation05 = geneAddition(0.5);

	SimulationRNG::reset(1);
	//                                                                 f  c  C  U  n  D  v  e  j  s
	BOOST_TEST(mutation01(chromosome) == Chromosome(stripWhitespace("  f  c  C  UC n  D  v  e  jx s")));  //  20% more
	BOOST_TEST(mutation05(chromosome) == Chromosome(stripWhitespace("j f  cu C  U  ne D  v  eI j  sf"))); //  50% more
	SimulationRNG::reset(2);
	BOOST_TEST(mutation01(chromosome) == Chromosome(stripWhitespace("  f  cu C  U  n  D  v  e  j  s")));  //  10% more
	BOOST_TEST(mutation05(chromosome) == Chromosome(stripWhitespace("L f  ce Cv U  n  D  v  e  jO s")));  //  40% more
}

BOOST_AUTO_TEST_CASE(geneAddition_should_be_able_to_insert_before_first_position)
{
	SimulationRNG::reset(7);
	Chromosome chromosome("fcCUnDvejs");
	function<Mutation> mutation = geneAddition(0.1);

	Chromosome mutatedChromosome = mutation(chromosome);
	BOOST_TEST(mutatedChromosome.length() > chromosome.length());

	vector<string> suffix(
		mutatedChromosome.optimisationSteps().end() - chromosome.length(),
		mutatedChromosome.optimisationSteps().end()
	);
	BOOST_TEST(suffix == chromosome.optimisationSteps());
}

BOOST_AUTO_TEST_CASE(geneAddition_should_be_able_to_insert_after_last_position)
{
	SimulationRNG::reset(81);
	Chromosome chromosome("fcCUnDvejs");
	function<Mutation> mutation = geneAddition(0.1);

	Chromosome mutatedChromosome = mutation(chromosome);
	BOOST_TEST(mutatedChromosome.length() > chromosome.length());

	vector<string> prefix(
		mutatedChromosome.optimisationSteps().begin(),
		mutatedChromosome.optimisationSteps().begin() + chromosome.length()
	);
	BOOST_TEST(prefix == chromosome.optimisationSteps());
}

BOOST_AUTO_TEST_CASE(geneAddition_should_return_identical_chromosome_if_probability_is_zero)
{
	Chromosome chromosome("fcCUnDvejsrmV");
	function<Mutation> mutation = geneAddition(0.0);

	BOOST_TEST(mutation(chromosome) == chromosome);
}

BOOST_AUTO_TEST_CASE(geneAddition_should_insert_genes_at_all_positions_if_probability_is_one)
{
	Chromosome chromosome("fcCUnDvejsrmV");
	function<Mutation> mutation = geneAddition(1.0);

	Chromosome mutatedChromosome = mutation(chromosome);
	BOOST_TEST(mutatedChromosome.length() == chromosome.length() * 2 + 1);

	vector<string> originalGenes;
	for (size_t i = 0; i < mutatedChromosome.length() - 1; ++i)
		if (i % 2 == 1)
			originalGenes.push_back(mutatedChromosome.optimisationSteps()[i]);

	BOOST_TEST(Chromosome(originalGenes) == chromosome);
}

BOOST_AUTO_TEST_CASE(alternativeMutations_should_choose_between_mutations_with_given_probability)
{
	SimulationRNG::reset(1);
	Chromosome chromosome("a");
	function<Mutation> mutation = alternativeMutations(
		0.8,
		wholeChromosomeReplacement(Chromosome("c")),
		wholeChromosomeReplacement(Chromosome("f"))
	);

	size_t cCount = 0;
	size_t fCount = 0;
	for (size_t i = 0; i < 10; ++i)
	{
		Chromosome mutatedChromosome = mutation(chromosome);
		cCount += static_cast<int>(mutatedChromosome == Chromosome("c"));
		fCount += static_cast<int>(mutatedChromosome == Chromosome("f"));
	}

	// This particular seed results in 7 "c"s out of 10 which looks plausible given the 80% chance.
	BOOST_TEST(cCount == 7);
	BOOST_TEST(fCount == 3);
}

BOOST_AUTO_TEST_CASE(alternativeMutations_should_always_choose_first_mutation_if_probability_is_one)
{
	Chromosome chromosome("a");
	function<Mutation> mutation = alternativeMutations(
		1.0,
		wholeChromosomeReplacement(Chromosome("c")),
		wholeChromosomeReplacement(Chromosome("f"))
	);

	for (size_t i = 0; i < 10; ++i)
		BOOST_TEST(mutation(chromosome) == Chromosome("c"));
}

BOOST_AUTO_TEST_CASE(alternativeMutations_should_always_choose_second_mutation_if_probability_is_zero)
{
	Chromosome chromosome("a");
	function<Mutation> mutation = alternativeMutations(
		0.0,
		wholeChromosomeReplacement(Chromosome("c")),
		wholeChromosomeReplacement(Chromosome("f"))
	);

	for (size_t i = 0; i < 10; ++i)
		BOOST_TEST(mutation(chromosome) == Chromosome("f"));
}

BOOST_AUTO_TEST_CASE(randomPointCrossover_should_swap_chromosome_parts_at_random_point)
{
	function<Crossover> crossover = randomPointCrossover();

	SimulationRNG::reset(1);
	Chromosome result1 = crossover(Chromosome("aaaaaaaaaa"), Chromosome("cccccc"));
	BOOST_TEST(result1 == Chromosome("aaaccc"));

	SimulationRNG::reset(1);
	Chromosome result2 = crossover(Chromosome("cccccc"), Chromosome("aaaaaaaaaa"));
	BOOST_TEST(result2 == Chromosome("cccaaaaaaa"));
}

BOOST_AUTO_TEST_CASE(randomPointCrossover_should_only_consider_points_available_on_both_chromosomes)
{
	SimulationRNG::reset(1);
	function<Crossover> crossover = randomPointCrossover();

	for (size_t i = 0; i < 30; ++i)
	{
		Chromosome result1 = crossover(Chromosome("aaa"), Chromosome("TTTTTTTTTTTTTTTTTTTT"));
		Chromosome result2 = crossover(Chromosome("TTTTTTTTTTTTTTTTTTTT"), Chromosome("aaa"));
		BOOST_TEST((
			result1 == Chromosome("TTTTTTTTTTTTTTTTTTTT") ||
			result1 == Chromosome("aTTTTTTTTTTTTTTTTTTT") ||
			result1 == Chromosome("aaTTTTTTTTTTTTTTTTTT") ||
			result1 == Chromosome("aaaTTTTTTTTTTTTTTTTT")
		));
		BOOST_TEST((
			result2 == Chromosome("aaa") ||
			result2 == Chromosome("Taa") ||
			result2 == Chromosome("TTa") ||
			result2 == Chromosome("TTT")
		));
	}
}

BOOST_AUTO_TEST_CASE(randomPointCrossover_should_never_split_at_position_zero_if_chromosomes_are_splittable)
{
	SimulationRNG::reset(1);
	function<Crossover> crossover = randomPointCrossover();

	for (size_t i = 0; i < 30; ++i)
	{
		Chromosome result1 = crossover(Chromosome("aa"), Chromosome("TTTTTTTTTTTTTTTTTTTT"));
		Chromosome result2 = crossover(Chromosome("TTTTTTTTTTTTTTTTTTTT"), Chromosome("aa"));
		BOOST_TEST(result1 != Chromosome("TTTTTTTTTTTTTTTTTTTT"));
		BOOST_TEST(result2 != Chromosome("aa"));
	}
}

BOOST_AUTO_TEST_CASE(randomPointCrossover_should_never_split_at_position_zero_if_chromosomes_are_not_empty)
{
	SimulationRNG::reset(1);
	function<Crossover> crossover = randomPointCrossover();

	for (size_t i = 0; i < 30; ++i)
	{
		Chromosome result1 = crossover(Chromosome("a"), Chromosome("T"));
		Chromosome result2 = crossover(Chromosome("T"), Chromosome("a"));
		BOOST_TEST(result1 == Chromosome("a"));
		BOOST_TEST(result2 == Chromosome("T"));
	}
}

BOOST_AUTO_TEST_CASE(randomPointCrossover_should_work_even_if_one_chromosome_is_unsplittable)
{
	function<Crossover> crossover = randomPointCrossover();

	SimulationRNG::reset(1);
	BOOST_CHECK(crossover(Chromosome("ff"), Chromosome("a")) == Chromosome("f"));
	BOOST_CHECK(crossover(Chromosome("a"), Chromosome("ff")) == Chromosome("af"));
}

BOOST_AUTO_TEST_CASE(randomPointCrossover_should_split_at_position_zero_only_if_at_least_one_chromosome_is_empty)
{
	Chromosome empty("");
	Chromosome unsplittable("a");
	Chromosome splittable("aaaa");
	function<Crossover> crossover = randomPointCrossover();

	SimulationRNG::reset(1);
	BOOST_CHECK(crossover(empty, empty) == empty);
	BOOST_CHECK(crossover(unsplittable, empty) == empty);
	BOOST_CHECK(crossover(empty, unsplittable) == unsplittable);
	BOOST_CHECK(crossover(splittable, empty) == empty);
	BOOST_CHECK(crossover(empty, splittable) == splittable);
}

BOOST_AUTO_TEST_CASE(fixedPointCrossover_should_swap_chromosome_parts_at_given_point)
{
	Chromosome result1 = fixedPointCrossover(0.8)(Chromosome("aaaaaaaaaa"), Chromosome("cccccccccc"));
	Chromosome result2 = fixedPointCrossover(0.8)(Chromosome("cccccccccc"), Chromosome("aaaaaaaaaa"));
	BOOST_TEST(result1 == Chromosome("aaaaaaaacc"));
	BOOST_TEST(result2 == Chromosome("ccccccccaa"));
}

BOOST_AUTO_TEST_CASE(fixedPointCrossover_should_determine_crossover_point_based_on_length_of_shorter_chromosome)
{
	Chromosome result1 = fixedPointCrossover(0.4)(Chromosome("aaaaa"), Chromosome("cccccccccc"));
	Chromosome result2 = fixedPointCrossover(0.4)(Chromosome("cccccccccc"), Chromosome("aaaaa"));
	BOOST_TEST(result1 == Chromosome("aacccccccc"));
	BOOST_TEST(result2 == Chromosome("ccaaa"));
}

BOOST_AUTO_TEST_CASE(fixedPointCrossover_should_round_split_point)
{
	Chromosome result1 = fixedPointCrossover(0.49)(Chromosome("aaaaa"), Chromosome("ccccc"));
	Chromosome result2 = fixedPointCrossover(0.49)(Chromosome("ccccc"), Chromosome("aaaaa"));
	BOOST_TEST(result1 == Chromosome("aaccc"));
	BOOST_TEST(result2 == Chromosome("ccaaa"));

	Chromosome result3 = fixedPointCrossover(0.50)(Chromosome("aaaaa"), Chromosome("ccccc"));
	Chromosome result4 = fixedPointCrossover(0.50)(Chromosome("ccccc"), Chromosome("aaaaa"));
	BOOST_TEST(result3 == Chromosome("aaacc"));
	BOOST_TEST(result4 == Chromosome("cccaa"));

	Chromosome result5 = fixedPointCrossover(0.51)(Chromosome("aaaaa"), Chromosome("ccccc"));
	Chromosome result6 = fixedPointCrossover(0.51)(Chromosome("ccccc"), Chromosome("aaaaa"));
	BOOST_TEST(result5 == Chromosome("aaacc"));
	BOOST_TEST(result6 == Chromosome("cccaa"));
}

BOOST_AUTO_TEST_CASE(fixedPointCrossover_should_split_at_position_zero_if_explicitly_requested)
{
	Chromosome result1 = fixedPointCrossover(0.0)(Chromosome("aaaaa"), Chromosome("cccccccccc"));
	Chromosome result2 = fixedPointCrossover(0.0)(Chromosome("cccccccccc"), Chromosome("aaaaa"));
	BOOST_TEST(result1 == Chromosome("cccccccccc"));
	BOOST_TEST(result2 == Chromosome("aaaaa"));
}

BOOST_AUTO_TEST_CASE(fixedPointCrossover_should_split_at_end_of_shorter_chromosome_if_crossover_point_is_after_last_position)
{
	Chromosome result1 = fixedPointCrossover(1.0)(Chromosome("aaaaa"), Chromosome("cccccccccc"));
	Chromosome result2 = fixedPointCrossover(1.0)(Chromosome("cccccccccc"), Chromosome("aaaaa"));
	BOOST_TEST(result1 == Chromosome("aaaaaccccc"));
	BOOST_TEST(result2 == Chromosome("ccccc"));
}

BOOST_AUTO_TEST_CASE(fixedPointCrossover_should_select_correct_split_point_for_unsplittable_chromosomes)
{
	function<Crossover> crossover00 = fixedPointCrossover(0.0);
	BOOST_CHECK(crossover00(Chromosome("fff"), Chromosome("a")) == Chromosome("a"));
	BOOST_CHECK(crossover00(Chromosome("a"), Chromosome("fff")) == Chromosome("fff"));

	BOOST_CHECK(crossover00(Chromosome("f"), Chromosome("a")) == Chromosome("a"));

	function<Crossover> crossover10 = fixedPointCrossover(1.0);
	BOOST_CHECK(crossover10(Chromosome("fff"), Chromosome("a")) == Chromosome("f"));
	BOOST_CHECK(crossover10(Chromosome("a"), Chromosome("fff")) == Chromosome("aff"));

	BOOST_CHECK(crossover10(Chromosome("f"), Chromosome("a")) == Chromosome("f"));
}

BOOST_AUTO_TEST_CASE(fixedPointCrossover_should_always_use_position_zero_as_split_point_when_chromosome_empty)
{
	Chromosome empty("");
	Chromosome unsplittable("f");
	Chromosome splittable("aaaa");

	function<Crossover> crossover00 = fixedPointCrossover(0.0);
	BOOST_CHECK(crossover00(empty, empty) == empty);
	BOOST_CHECK(crossover00(unsplittable, empty) == empty);
	BOOST_CHECK(crossover00(empty, unsplittable) == unsplittable);
	BOOST_CHECK(crossover00(splittable, empty) == empty);
	BOOST_CHECK(crossover00(empty, splittable) == splittable);

	function<Crossover> crossover10 = fixedPointCrossover(1.0);
	BOOST_CHECK(crossover10(empty, empty) == empty);
	BOOST_CHECK(crossover10(unsplittable, empty) == empty);
	BOOST_CHECK(crossover10(empty, unsplittable) == unsplittable);
	BOOST_CHECK(crossover10(splittable, empty) == empty);
	BOOST_CHECK(crossover10(empty, splittable) == splittable);
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()

}

ext: cpp

max_stars_repo_name: MrChico/solidity

max_issues_repo_name: MrChico/solidity

max_forks_repo_name: MrChico/solidity


text:
///////////////////////////////////////////////////////////////////////////////
//
// ping.cpp
//
// Copyright (c) 2011-2013 Eric Lombrozo
//
// 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.

#include <CoinNodeSocket.h>

#include <iostream>
#include <string>
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/condition_variable.hpp>

using namespace Coin;
using namespace std;

// Change these to use a different network
namespace listener_network
{
    const uint32_t MAGIC_BYTES = 0xd9b4bef9ul;
    const uint32_t PROTOCOL_VERSION = 60002;
    const uint8_t ADDRESS_VERSION = 0x00;
    const uint8_t MULTISIG_ADDRESS_VERSION = 0x05;
};

const unsigned char DEFAULT_Ipv6[] = {0,0,0,0,0,0,0,0,0,0,255,255,127,0,0,1};

boost::mutex mutex;
boost::condition_variable gotVersion;
bool bGotVersion = false;

void MessageHandler(CoinNodeSocket* pNodeSocket, const CoinNodeMessage& message)
{
    if (string(message.getCommand()) == "version") {
        cout << message.toIndentedString() << endl;
        boost::unique_lock<boost::mutex> lock(mutex);
        bGotVersion = true;
        gotVersion.notify_all();
    }
}

int main(int argc, char* argv[])
{
    if (argc < 3) {
        cout << "Usage: " << argv[0] << " <host> <port> [magic_bytes=0xd9b4bef9ul]" << endl
             << "  Pings a bitcoin-like node and gets the version information." << endl;
        return 0;
    }
    uint16_t port = strtoul(argv[2], NULL, 10);

    NetworkAddress address(NODE_NETWORK, DEFAULT_Ipv6, port);

    CoinNodeSocket nodeSocket;

    try {
        nodeSocket.open(MessageHandler, listener_network::MAGIC_BYTES, listener_network::PROTOCOL_VERSION, argv[1], port);
        nodeSocket.doHandshake(listener_network::PROTOCOL_VERSION, NODE_NETWORK, time(NULL), address, address, 0, "", 0);
        nodeSocket.waitOnHandshakeComplete();

        boost::unique_lock<boost::mutex> lock(mutex);
        while (!bGotVersion) gotVersion.wait(lock);
    }
    catch (const exception& e) {
        cout << e.what() << endl;
    }
}

max_stars_repo_name: anypath/CoinVault

max_stars_repo_licenses: Unlicense OpenSSL MIT

max_issues_repo_name: anypath/CoinVault

max_issues_repo_licenses: Unlicense OpenSSL MIT

max_forks_repo_name: anypath/CoinVault

max_forks_repo_licenses: Unlicense OpenSSL MIT


text:
#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <boost/algorithm/string/predicate.hpp>

#include <blackhole/attribute.hpp>
#include <blackhole/attributes.hpp>
#include <blackhole/extensions/writer.hpp>
#include <blackhole/formatter.hpp>
#include <blackhole/formatter/tskv.hpp>
#include <blackhole/record.hpp>
#include <blackhole/stdext/string_view.hpp>

#include "src/formatter/tskv.cpp"

#include "mocks/node.hpp"
#include "mocks/registry.hpp"

namespace blackhole {
inline namespace v1 {
namespace formatter {
namespace {

using ::testing::Return;
using ::testing::StrictMock;

TEST(tskv_t, Format) {
    auto formatter = builder<tskv_t>()
        .build();

    const string_view message("value");
    const attribute_pack pack;
    record_t record(0, message, pack);
    record.activate();

    const auto timestamp = record.timestamp();
    const auto time = record_t::clock_type::to_time_t(timestamp);
    std::tm tm;
    ::gmtime_r(&time, &tm);
    char buffer[128];
    const auto len = std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S %z", &tm);
    std::ostringstream stream;
    // Timestamp are formatted using default value.
    stream << "tskv"
        << "\ttimestamp=" << std::string(buffer, len)
        << "\tseverity=" << 0
        << "\tpid=" << ::getpid()
        << "\ttid="
#ifdef __linux__
        << std::hex << std::internal << std::showbase << std::setw(2) << std::setfill('0')
#endif
        << std::this_thread::get_id()
        << "\tmessage=value";

    writer_t writer;
    formatter->format(record, writer);

    EXPECT_EQ(stream.str(), writer.result().to_string());
}

TEST(tskv_t, FormatWithAttributes) {
    auto formatter = builder<tskv_t>()
        .build();

    const string_view message("value");
    const attribute_list attributes{{"id", 42}, {"key", "value"}};
    const attribute_pack pack{attributes};
    record_t record(0, message, pack);

    writer_t writer;
    formatter->format(record, writer);

    std::ostringstream suffix;
    suffix << "\tmessage=value"
        << "\tid=42"
        << "\tkey=value";

    EXPECT_TRUE(boost::ends_with(writer.result().to_string(), suffix.str()));
}

TEST(tskv_t, FormatWithCreate) {
    auto formatter = builder<tskv_t>()
        .create("tskv_format", "cocaine")
        .build();

    const string_view message("value");
    const attribute_pack pack;
    record_t record(0, message, pack);
    record.activate();

    const auto timestamp = record.timestamp();
    const auto time = record_t::clock_type::to_time_t(timestamp);
    std::tm tm;
    ::gmtime_r(&time, &tm);
    char buffer[128];
    const auto len = std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S %z", &tm);
    std::ostringstream stream;
    // Timestamp are formatted using default value.
    stream << "tskv"
        << "\ttskv_format=cocaine"
        << "\ttimestamp=" << std::string(buffer, len)
        << "\tseverity=" << 0
        << "\tpid=" << ::getpid()
        << "\ttid="
#ifdef __linux__
        << std::hex << std::internal << std::showbase << std::setw(2) << std::setfill('0')
#endif
        << std::this_thread::get_id()
        << "\tmessage=value";

    writer_t writer;
    formatter->format(record, writer);

    EXPECT_EQ(stream.str(), writer.result().to_string());
}

TEST(tskv_t, Escape) {
    auto formatter = builder<tskv_t>()
        .build();

    const string_view message(
        "\x07""bell"
        "\x08""backspace"
        "\x09""tab"
        "\x0a""line feed"
        "\x0b""vtab"
        "\x0c""form feed"
        "\x0d""carriage return"
        "\x1b""escape"
    );
    const attribute_pack pack;
    record_t record(0, message, pack);

    writer_t writer;
    formatter->format(record, writer);

    std::ostringstream suffix;
    suffix << "message=\\abell\\bbackspace\\ttab\\nline feed\\vvtab\\fform feed\\rcarriage return\\eescape";

    EXPECT_TRUE(boost::ends_with(writer.result().to_string(), suffix.str()));
}

TEST(tskv_t, EscapeKey) {
    auto formatter = builder<tskv_t>()
        .build();

    const string_view message("value");
    const attribute_list attributes{{"with=eq", 42}};
    const attribute_pack pack{attributes};
    record_t record(0, message, pack);

    writer_t writer;
    formatter->format(record, writer);

    std::ostringstream suffix;
    suffix << "message=value\twith\\=eq=42";

    EXPECT_TRUE(boost::ends_with(writer.result().to_string(), suffix.str()));
}

TEST(tskv_t, FormatTimestampWithTimezone) {
    auto formatter = builder<tskv_t>()
        .timestamp("timestamp", "%Y-%m-%d %H:%M:%S")
        .timestamp("timezone", "%z")
        .build();

    const string_view message("value");
    const attribute_pack pack;
    record_t record(0, message, pack);
    record.activate();

    const auto timestamp = record.timestamp();
    const auto time = record_t::clock_type::to_time_t(timestamp);
    std::tm tm;
    ::gmtime_r(&time, &tm);
    char buffer[128];
    auto len = std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm);
    std::ostringstream stream;
    stream << "\ttimestamp=" << std::string(buffer, len);
    len = std::strftime(buffer, sizeof(buffer), "%z", &tm);
    stream << "\ttimezone=" << std::string(buffer, len);

    writer_t writer;
    formatter->format(record, writer);

    EXPECT_TRUE(boost::contains(writer.result().to_string(), stream.str()));
}

TEST(tskv_t, Rename) {
    auto formatter = builder<tskv_t>()
        .rename("message", "@message")
        .build();

    const string_view message("value");
    const attribute_pack pack;
    record_t record(0, message, pack);

    writer_t writer;
    formatter->format(record, writer);

    std::ostringstream suffix;
    suffix << "@message=value";

    EXPECT_TRUE(boost::ends_with(writer.result().to_string(), suffix.str()));
}

TEST(tskv_t, Remove) {
    auto formatter = builder<tskv_t>()
        .remove("message")
        .build();

    const string_view message("value");
    const attribute_pack pack;
    record_t record(0, message, pack);

    writer_t writer;
    formatter->format(record, writer);

    EXPECT_FALSE(boost::contains(writer.result().to_string(), "message"));
    EXPECT_FALSE(boost::contains(writer.result().to_string(), "message=value"));
}

TEST(tskv_t, FormatTimestampWithTimezoneUsingLocaltime) {
    auto formatter = builder<tskv_t>()
        .timestamp("timestamp", "%Y-%m-%d %H:%M:%S", false)
        .timestamp("timezone", "%z", false)
        .build();

    const string_view message("value");
    const attribute_pack pack;
    record_t record(0, message, pack);
    record.activate();

    const auto timestamp = record.timestamp();
    const auto time = record_t::clock_type::to_time_t(timestamp);
    std::tm tm;
    ::localtime_r(&time, &tm);
    char buffer[128];
    auto len = std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm);
    std::ostringstream stream;
    stream << "\ttimestamp=" << std::string(buffer, len);
    len = std::strftime(buffer, sizeof(buffer), "%z", &tm);
    stream << "\ttimezone=" << std::string(buffer, len);

    writer_t writer;
    formatter->format(record, writer);

    EXPECT_TRUE(boost::contains(writer.result().to_string(), stream.str()));
}

TEST(factory, Type) {
    EXPECT_EQ("tskv", factory<tskv_t>().type());
}

} // namespace
} // namespace formatter
} // namespace v1
} // namespace blackhole

max_stars_repo_name: JakariaBlaine/blackhole

max_issues_repo_name: JakariaBlaine/blackhole

max_forks_repo_name: JakariaBlaine/blackhole


text:
/**
 * Created by cmd-keen
 * on netbook
 * at So 12. Jun 14:39:11 CEST 2016
 */

#include <boost/test/unit_test.hpp>
#include "Network/TestConnection.h"
#include "Network/StoreSender.h"
#include "Network/StoreReceiver.h"
#include <string>
#include <iostream>
using namespace std;
namespace utf = boost::unit_test;

BOOST_AUTO_TEST_SUITE(global);

BOOST_AUTO_TEST_CASE(checkStoreSender) {
	StoreSender sender;

	string data = "abcdefghij";
	sender.sent(data.data(), data.length());

	BOOST_CHECK( sender.wasCalled() );
	BOOST_CHECK( sender.dataSent() == data );
}

BOOST_AUTO_TEST_CASE(checkSend) {

	TestConnection sendConnection, receiveConnection;
	sendConnection.pair( receiveConnection );
	receiveConnection.pair( sendConnection );

	string data = "abcdefghij";

	StoreSender sender;
	//receiveConnection.read( , data.length() );
	sendConnection.write( sender, data.data(), data.length() );
	BOOST_CHECK( sender.wasCalled() );
	BOOST_CHECK( sender.dataSent() == data );
}

BOOST_AUTO_TEST_CASE(checkReceivedAfter) {

	TestConnection sendConnection, receiveConnection;
	sendConnection.pair( receiveConnection );
	receiveConnection.pair( sendConnection );

	string data = "abcdefghij";

	StoreSender sender;
	StoreReceiver receiver;

	sendConnection.write( sender, data.data(), data.length() );
	BOOST_CHECK( sender.wasCalled() );
	BOOST_CHECK_EQUAL( sender.dataSent(), data );

	receiveConnection.read( receiver, data.length() );
	BOOST_CHECK( receiver.getDataReceived() == data );
	BOOST_CHECK( receiver.getSizeReceived() == data.length() );
}

BOOST_AUTO_TEST_CASE(checkReceivedBefore) {

	TestConnection sendConnection, receiveConnection;
	sendConnection.pair( receiveConnection );
	receiveConnection.pair( sendConnection );

	string data = "abcdefghij";
	string firstPart = "abc";
	string secondPart = "defghij";

	StoreSender sender;
	StoreReceiver receiver;

	receiveConnection.read( receiver, data.length() );
	sendConnection.write( sender, data.data(), 3 );
	BOOST_CHECK( sender.wasCalled() );
	BOOST_CHECK_EQUAL( sender.dataSent(), firstPart );

	BOOST_CHECK_EQUAL( receiver.isCalled(), false );
}

BOOST_AUTO_TEST_CASE( receiveMultipleTimes ) {

	TestConnection sendConnection, receiveConnection;
	sendConnection.pair( receiveConnection );
	receiveConnection.pair( sendConnection );

	StoreSender sender;
	StoreReceiver receiver;

	string data = "abcdefghijklmnopqrstuvwxyz";
	for(unsigned index = 0 ; (index+1) * 4 < data.length() ; ++index) {
		receiveConnection.read(receiver, 4);
	}

	unsigned writtenBytes = 0;
	for(unsigned index = 0 ; (index+1) * 3 < data.length() ; ++index) {
		sendConnection.write( sender, data.substr(index * 3, 3).data(), 3);

		writtenBytes += 3;
		if(writtenBytes >= 4) {

			BOOST_CHECK_EQUAL( receiver.isCalled(), true );
			writtenBytes -= 4;
			receiver.resetCalled();

		} else {
			BOOST_CHECK_EQUAL( receiver.isCalled(), false );
		}
	}
}

BOOST_AUTO_TEST_SUITE_END();


text:
// Andrew Naplavkov

#ifndef BARK_GEOMETRY_ISTREAM_HPP
#define BARK_GEOMETRY_ISTREAM_HPP

#include <bark/detail/wkb.hpp>
#include <bark/geometry/detail/utility.hpp>
#include <bark/geometry/geometry.hpp>
#include <boost/mpl/map.hpp>
#include <functional>

namespace bark::geometry {

/// WKB visitor
class istream {
    wkb::istream data_;
    linestring cached_path_;

public:
    using path_t = std::reference_wrapper<decltype(cached_path_)>;

    explicit istream(blob_view data) : data_{data} {}

    template <class T>
    auto read()
    {
        return T::accept(data_, *this);
    }

    point operator()(double x, double y) { return {x, y}; }

    path_t operator()(uint32_t count, wkb::path)
    {
        cached_path_.clear();
        cached_path_.reserve(count);
        return cached_path_;
    }

    void operator()(path_t& sum, const point& item, wkb::path)
    {
        sum.get().push_back(item);
    }

    template <class T>
    typename boost::mpl::at<
        boost::mpl::map<boost::mpl::pair<wkb::path, polygon>,
                        boost::mpl::pair<wkb::point, multi_point>,
                        boost::mpl::pair<wkb::linestring, multi_linestring>,
                        boost::mpl::pair<wkb::polygon, multi_polygon>,
                        boost::mpl::pair<wkb::geometry, geometry_collection>>,
        T>::type
    operator()(uint32_t, wkb::chain<T>)
    {
        return {};
    }

    template <class Sum, class Item, class T>
    void operator()(Sum& sum, const Item& item, T)
    {
        sum.push_back(item);
    }

    void operator()(polygon& sum, const path_t& item, wkb::chain<wkb::path>)
    {
        push_ring(sum, item.get());
    }

    template <class T, uint32_t Code>
    void operator()(wkb::tagged<T, Code>)
    {
    }

    template <class Result, class T>
    Result operator()(Result&& res, T)
    {
        return std::forward<Result>(res);
    }

    linestring operator()(const path_t& res, wkb::linestring) { return res; }

    template <class Result>
    geometry operator()(Result&& res, wkb::geometry)
    {
        return std::forward<Result>(res);
    }
};

}  // namespace bark::geometry

#endif  // BARK_GEOMETRY_ISTREAM_HPP

ext: hpp

max_stars_repo_name: storm-ptr/bark

max_issues_repo_name: storm-ptr/bark

max_forks_repo_name: storm-ptr/bark


text:
#ifndef NNQS_OPTIMIZERS_ADAM_HPP
#define NNQS_OPTIMIZERS_ADAM_HPP
#include <Eigen/Dense>
#include <type_traits>
#include "Utilities/type_traits.hpp"
#include "Optimizers/Optimizer.hpp"

namespace yannq
{

template <typename T>
class Adam
	: public OptimizerGeometry<T>
{
public:
	using typename OptimizerGeometry<T>::RealT;
	using typename OptimizerGeometry<T>::Vector;
	using typename OptimizerGeometry<T>::RealVector;

private:
	const double alpha_;
	const double beta1_;
	const double beta2_;
	const double eps_;

	int t_;
	Vector m_;
	RealVector v_;

public:
	static constexpr double DEFAULT_PARAMS[] = {1e-3, 0.9, 0.999, 1e-8};

	static nlohmann::json defaultParams()
	{
		return nlohmann::json
		{
			{"name", "Adam"},
			{"alhpa", DEFAULT_PARAMS[0]},
			{"beta1", DEFAULT_PARAMS[1]},
			{"beta2", DEFAULT_PARAMS[2]},
			{"eps", DEFAULT_PARAMS[3]},
		};
	}

	nlohmann::json desc() const override
	{
		return nlohmann::json
		{
			{"name", "Adam"},
			{"alhpa", alpha_},
			{"beta1", beta1_},
			{"beta2", beta2_},
			{"eps", eps_},
		};
	}

	Adam(const nlohmann::json& params)
		: alpha_(params.value("alpha", DEFAULT_PARAMS[0])),
			beta1_(params.value("beta1", DEFAULT_PARAMS[1])),
			beta2_(params.value("beta2", DEFAULT_PARAMS[2])),
			eps_(params.value("eps", DEFAULT_PARAMS[3])),
			t_{0}
	{
	}

	Adam(double alpha = DEFAULT_PARAMS[0], double beta1 = DEFAULT_PARAMS[1], double beta2 = DEFAULT_PARAMS[2], double eps = DEFAULT_PARAMS[3])
		: alpha_(alpha), beta1_(beta1), beta2_(beta2), eps_(eps), t_{0}
	{
	}

	Vector getUpdate(const Vector& grad, const Vector& oloc) override
	{
		auto norm = [](T x) -> RealT { return std::norm(x); };

		if(t_ ==0)
		{
			m_ = Vector::Zero(grad.rows());
			v_ = RealVector::Zero(grad.rows());
		}
		++t_;

		m_ *= beta1_;
		m_ += (1-beta1_)*grad;

		RealVector g2 = oloc.unaryExpr(norm);
		v_ *= beta2_;
		v_ += (1-beta2_)*g2;

		double epsnorm = eps_*sqrt(1.0-pow(beta2_,t_));
		RealVector denom = v_.unaryExpr([epsnorm](RealT x){ return sqrt(x)+epsnorm; });

		double alphat = alpha_*sqrt(1.0-pow(beta2_,t_))/(1.0-pow(beta1_,t_));

		return -alphat*m_.cwiseQuotient(denom);
	}
};

template<typename T>
constexpr double Adam<T>::DEFAULT_PARAMS[];

} //namespace yannq
#endif//NNQS_OPTIMIZERS_ADAM_HPP

max_stars_repo_name: cecri/yannq

max_issues_repo_name: cecri/yannq

max_forks_repo_name: cecri/yannq


text:
//==============================================================================
//         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_DISPATCH_META_TERMINAL_OF_HPP_INCLUDED
#define BOOST_DISPATCH_META_TERMINAL_OF_HPP_INCLUDED

/*!
 * \file
 * \brief Defines the \c boost::dispatch::meta::terminal_of \metafunction
 */

#include <boost/config.hpp>

namespace boost { namespace dispatch { namespace meta
{
  /*!
   * \ingroup metafunctions
   * For any type, returns a type which can act as a proto terminal in an
   * expression template context
   *
   * \tparam Type type to convert into a terminal
   */
  template<class T> struct terminal_of { typedef T type; };

  template<class T> struct terminal_of<T const> : terminal_of<T> {};
  template<class T> struct terminal_of<T&> : terminal_of<T> {};
#ifndef BOOST_NO_RVALUE_REFERENCES
  template<class T> struct terminal_of<T&&> : terminal_of<T> {};
#endif

} } }

#endif


text:
#ifndef BLUB_LOG_LOGGER_HPP
#define BLUB_LOG_LOGGER_HPP

#include "blub/core/globals.hpp"

#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>

#include <ostream>

namespace blub
{
namespace log
{
    enum class severity
    {
        out,
        warning,
        error
    };

    inline std::ostream& operator<< (std::ostream& strm, blub::log::severity severity_)
    {
        static const char* strings[] =
        {
            "out",
            "warning",
            "error",
        };
        std::size_t castedLevel(static_cast< std::size_t >(severity_));
        if (castedLevel < sizeof(strings) / sizeof(*strings))
        {
            strm << strings[castedLevel];
        }
        else
        {
            strm << castedLevel;
        }

        return strm;
    }

    class logger : public boost::log::sources::severity_logger_mt<blub::log::severity>
    {
    public:
        typedef boost::log::sources::severity_logger_mt<blub::log::severity> t_base;

        logger(const blub::string &moduleName);
		~logger() {;}
    };
}
}

#endif // BLUB_LOG_LOGGER_HPP


text:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <omp.h>
#include <Eigen/Eigen>
#include "utils.h"
#include "json.h"

using json = nlohmann::json;
using namespace lass;

struct CameraData {
    CameraData() {
        qcw.setIdentity();
        pcw.setZero();
        focal = 0;
    }
    std::string filename;
    Eigen::Quaterniond qcw;
    Eigen::Vector3d pcw;
    double focal;
};

inline void repaint_color(cv::Mat &img) {
    for (int i = 0; i < img.rows; ++i) {
        for (int j = 0; j < img.cols; ++j) {
            auto &c = img.at<cv::Vec3b>(i, j);
            if (c[1] == 0 && c[2] == 0) continue;
            uint32_t unique_key = (uint32_t(c[0]) << 16) + (uint32_t(c[1]) << 8) + uint32_t(c[2]);
            hash_colormap(c[0], c[1], c[2], unique_key);
        }
    }
}

// args path_to_source_images path_to_raycast_images path_to_tran_test_list_json_base_dir src_img_format(jpg or png)
int main(int argc, char **argv) {
    const std::string json_base_dir = "/home/ybbbbt/Dropbox/LandmarkSegmentation/draw_figures";
    // read cameras
    std::vector<CameraData> camera_list;
    {
        json j;
        std::ifstream ifs(json_base_dir + "/out_extrinsics.json");
        ifs >> j;
        for (auto &e : j.items()) {
            CameraData cd;
            cd.filename = e.key();
            Eigen::Matrix4d Tcw;
            auto &m = e.value();
            Tcw << m[0], m[1], m[2], m[3],
                m[4], m[5], m[6], m[7],
                m[8], m[9], m[10], m[11],
                0, 0, 0, 1;
            cd.qcw = Eigen::Quaterniond(Tcw.block<3, 3>(0, 0));
            cd.pcw = Eigen::Vector3d(Tcw.block<3, 1>(0, 3));
            if (e.value().size() == 13) {
                cd.focal = e.value()[12];
            }
            camera_list.emplace_back(std::move(cd));
        }
    }
    // read cluster centers
    std::vector<Eigen::Vector3d> centers;
    {
        json j;
        std::ifstream ifs(json_base_dir + "/id2centers.json");
        ifs >> j;
        for (auto &e : j.items()) {
            centers.emplace_back(e.value()[0], e.value()[1], e.value()[2]);
        }
        print_var(centers.size());
    }
    for (int i = 0; i < camera_list.size(); ++i) {
        const auto &cam = camera_list[i];
        if (cam.filename != "seq3/frame00039.png") continue;
        std::string name = cam.filename;
        // std::cout << name << std::endl;
        cv::Mat img_src = cv::imread("/home/ybbbbt/Dropbox/LandmarkSegmentation/draw_figures/frame00039.png");
        cv::Mat img_cast = cv::imread("/home/ybbbbt/Dropbox/LandmarkSegmentation/draw_figures/frame00039.seg.png");
        cv::Mat img_orig_seg = img_cast.clone();
        // blend color
        repaint_color(img_cast);
        double cx = img_src.cols / 2, cy = img_src.rows / 2;
        int new_width = img_src.cols / 2, new_height = img_src.rows / 2;
        auto sz = cv::Size(new_width, new_height);
        cv::resize(img_src, img_src, sz);
        cv::resize(img_cast, img_cast, sz);
        cv::resize(img_orig_seg, img_orig_seg, sz);
        cv::Mat img_blend;
        cv::addWeighted(img_src, 0.5, img_cast, 0.5, 0.0, img_blend);
        // project to images
        for (int idx_center = 1; idx_center < centers.size(); idx_center++) {
            Eigen::Vector3d &center = centers[idx_center];
            Eigen::Vector3d pt_c = cam.qcw * center + cam.pcw;
            if (pt_c.z() < 0) continue;
            Eigen::Vector2d pt_2d = pt_c.hnormalized();
            pt_2d = {pt_2d.x() * cam.focal + cx, pt_2d.y() * cam.focal + cy};
            pt_2d /= 2.0;
            if (pt_2d.x() < 0 || pt_2d.x() > new_width - 1 || pt_2d.y() < 0 || pt_2d.y() > new_height - 1) continue;
            // check if label consist with segmentation (remove invisible projections)
            auto &color = img_orig_seg.at<cv::Vec3b>(std::round(pt_2d.y()), std::round(pt_2d.x()));
            int label = int(color[1]) * 256 + int(color[2]);
            if (label != idx_center) continue;
            cv::Point2f pt(float(pt_2d.x()), float(pt_2d.y()));
            // cv::circle(img_blend, pt, 3, cv::Scalar(0, 0, 255), 1, cv::LINE_AA);
            cv::drawMarker(img_blend, pt, cv::Scalar(0, 0, 255), cv::MARKER_CROSS, 15, 2, cv::LINE_AA);

            if (1) {
                // test add offset
                Eigen::Quaterniond qcw = cam.qcw;
                Eigen::Vector3d pcw = cam.pcw;
                Eigen::Vector3d pt_c = qcw * center + pcw + Eigen::Vector3d(1, 0, 0);
                if (pt_c.z() < 0) continue;
                Eigen::Vector2d pt_2d = pt_c.hnormalized();
                pt_2d = {pt_2d.x() * cam.focal + cx, pt_2d.y() * cam.focal + cy};
                pt_2d /= 2.0;
                if (pt_2d.x() < 0 || pt_2d.x() > new_width - 1 || pt_2d.y() < 0 || pt_2d.y() > new_height - 1) continue;
                cv::Point2f pt(float(pt_2d.x()), float(pt_2d.y()));
                // cv::circle(img_blend, pt, 3, cv::Scalar(0, 0, 255), 1, cv::LINE_AA);
                cv::drawMarker(img_blend, pt, cv::Scalar(0, 255, 0), cv::MARKER_CROSS, 15, 2, cv::LINE_AA);
            }
        }
        name = name.substr(0, name.length() - 3) + "jpg";
        cv::imshow("vis", img_blend);
        cv::waitKey(0);
        int ret = system(("mkdir -p " + name.substr(0, name.find_last_of("/"))).c_str());
        cv::imwrite(name, img_blend);
        static int count = 0;
        if (count % 10 == 0) {
            fprintf(stdout, "\r%d / %zu", count, camera_list.size());
            fflush(stdout);
        }
        count++;
    }

    return 0;
}

ext: cc

max_stars_repo_name: asdiuzd/lass

max_issues_repo_name: asdiuzd/lass

max_forks_repo_name: asdiuzd/lass


text:
/// @file VOTableData.cc
///
/// @copyright (c) 2016 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
///
/// @author Daniel Collins <daniel.collins@csiro.au>

// Include own header file first
#include "VOTableData.h"

// Include package level header file
#include "askap_skymodel.h"

// System includes
#include <string>
#include <map>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

// ASKAPsoft includes
#include <askap/AskapError.h>
#include <askap/AskapLogging.h>

// Local package includes
#include "HealPixFacade.h"
#include "Utility.h"
#include "VOTableParser.h"

ASKAP_LOGGER(logger, ".VOTableData");

using namespace std;
using namespace askap::cp::sms;
using namespace askap::accessors;

boost::shared_ptr<VOTableData> VOTableData::create(
    string components_file,
    string polarisation_file,
    boost::int64_t healpix_order)
{
    // open components file
    VOTable components = VOTable::fromXML(components_file);
    ASKAPASSERT(components.getResource().size() == 1ul);
    ASKAPASSERT(components.getResource()[0].getTables().size() == 1ul);
    const VOTableTable components_table = components.getResource()[0].getTables()[0];
    vector<VOTableField> fields = components_table.getFields();
    vector<VOTableRow> rows = components_table.getRows();
    const unsigned long num_components = rows.size();

    boost::shared_ptr<VOTableData> data(new VOTableData(num_components));
    ASKAPASSERT(data.get());

    map<string, size_t> componentsById;

    // TODO: will it be better to reverse the order of field and row iteration?
    // Typically there will be ~30 fields and ~1000 rows
    size_t row_index = 0;
    vector<VOTableRow>::iterator rit;
    // for each component row ...
    for (rit = rows.begin(), row_index = 0;
         rit != rows.end();
         rit++, row_index++) {
        const vector<std::string> rowData = rit->getCells();
        long field_index = 0;
        vector<VOTableField>::iterator fit;
        // for each field in the current row ...
        for (fit = fields.begin(), field_index = 0;
             fit != fields.end();
             fit++, field_index++) {
            parseComponentRowField(
                row_index,
                fit->getUCD(),
                fit->getName(),
                fit->getDatatype(),
                fit->getUnit(),
                rowData[field_index],
                data->itsComponents);
        }

        componentsById.insert(pair<string, size_t>(
            data->itsComponents[row_index].component_id,
            row_index));
    }

    // load polarisation file if it exists
    if (boost::filesystem::exists(polarisation_file))
    {
        // parse polarisation file
        VOTable polarisation = VOTable::fromXML(polarisation_file);
        ASKAPASSERT(polarisation.getResource().size() == 1ul);
        ASKAPASSERT(polarisation.getResource()[0].getTables().size() == 1ul);
        const VOTableTable polarisation_table = polarisation.getResource()[0].getTables()[0];
        vector<VOTableField> polfields = polarisation_table.getFields();
        vector<VOTableRow> polrows = polarisation_table.getRows();
        vector<VOTableRow>::iterator rit;
        // for each polarisation row ...
        for (rit = polrows.begin(); rit != polrows.end(); rit++) {
            const vector<std::string> rowData = rit->getCells();
            long field_index = 0;
            vector<VOTableField>::iterator fit;

            // create a new polarisation object
            boost::shared_ptr<datamodel::Polarisation> pPol(
                new datamodel::Polarisation());

            // parse each field in the current row ...
            for (fit = polfields.begin(), field_index = 0;
                fit != polfields.end();
                fit++, field_index++) {
                parsePolarisationRowField(
                    fit->getUCD(),
                    fit->getName(),
                    fit->getDatatype(),
                    fit->getUnit(),
                    rowData[field_index],
                    pPol);
            }

            // Now we have a complete polarisation object. Set it into the matching component
            data->itsComponents[componentsById[pPol->component_id]].polarisation = pPol;
        }
    }

    data->calcHealpixIndicies(healpix_order);

    return data;
}

VOTableData::VOTableData(unsigned long num_components) :
    itsComponents(num_components)
{
}

VOTableData::~VOTableData()
{
    ASKAPLOG_DEBUG_STR(logger, "dtor");
}

void VOTableData::calcHealpixIndicies(boost::int64_t healpix_order) {
    ASKAPLOG_DEBUG_STR(logger, "Starting HEALPix indexation");
    HealPixFacade hp(healpix_order);
    for (ComponentList::iterator it = itsComponents.begin(); it != itsComponents.end(); it++) {
        it->healpix_index = hp.calcHealPixIndex(Coordinate(it->ra, it->dec));
    }
    ASKAPLOG_DEBUG_STR(logger, "HEALPix indexation complete");
}

max_stars_repo_name: rtobar/askapsoft

max_issues_repo_name: ATNF/askapsoft

max_forks_repo_name: ATNF/askapsoft


text:
//  not_equal_to.hpp
//
//  (C) Copyright 2011 Vicente J. Botet Escriba
//  Use, modification and distribution are subject to 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).
//

#ifndef BOOST_RATIO_MPL_NOT_EQUAL_TO_HPP
#define BOOST_RATIO_MPL_NOT_EQUAL_TO_HPP

#include <boost/ratio/ratio.hpp>
#include <boost/ratio/mpl/numeric_cast.hpp>
#include <boost/mpl/not_equal_to.hpp>

namespace boost {
namespace mpl {

template<>
struct not_equal_to_impl< rational_c_tag,rational_c_tag >
{
    template< typename R1, typename R2 > struct apply
        : ratio_not_equal<R1, R2>
    {
    };
};
}
}

#endif  // BOOST_RATIO_MPL_NOT_EQUAL_TO_HPP


text:
/*
 *  Copyright 2011 Matthias Fuchs
 *
 *  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 <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include "stromx/runtime/Version.h"
#include "stromx/runtime/impl/XmlUtilities.h"

namespace stromx
{
    namespace runtime
    {
        namespace impl
        {
            using namespace xercesc;

            Xml2Str::Xml2Str(const XMLCh* const str)
            {
                m_str = XMLString::transcode(str);
            }

            Xml2Str::~Xml2Str()
            {
                XMLString::release(&m_str);
            }

            Xml2Str::operator const char*()
            {
                return m_str;
            }

            Str2Xml::Str2Xml(const char* const str)
            {
                m_xmlStr = XMLString::transcode(str);
            }

            Str2Xml::~Str2Xml()
            {
                XMLString::release(&m_xmlStr);
            }

            Str2Xml::operator const XMLCh*()
            {
                return m_xmlStr;
            }

            const std::string XmlUtilities::computePath(const std::string& filepath)
            {
                std::string path = boost::filesystem::path(filepath).parent_path().string();

                return path.empty() ? "." : path;
            }

            const std::string XmlUtilities::computeName(const std::string& filepath)
            {
                boost::filesystem::path path = boost::filesystem::path(filepath).filename();
                return path.string();
            }

            const std::string XmlUtilities::stripExtension(const std::string& filename)
            {
                std::size_t i = filename.find_first_of(".");

                if(i == std::string::npos)
                    return filename;

                return std::string (filename, 0, i);
            }

            const std::string XmlUtilities::computeExtension(const std::string& filename)
            {
                std::size_t i = filename.find_first_of(".");

                if(i == std::string::npos)
                    return "";

                return std::string (filename, i + 1);
            }
        }
    }
}

max_stars_repo_name: roteroktober/stromx

max_issues_repo_name: roteroktober/stromx

max_forks_repo_name: roteroktober/stromx


text: #include <boost/mpl/aux_/preprocessed/no_ctps/vector_c.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * Copyright 2014-2017 Jouni Roivas
 */

#include "blieng/configure.h"

#include <boost/algorithm/string.hpp>

#ifdef DATA_MUTEX_LOCK
#include <boost/thread/locks.hpp>
#include <boost/thread/lock_guard.hpp>
#endif
#include <boost/assert.hpp>

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

using blieng::Configure;

typedef std::pair<std::string, Configure::key_type_t> key_values_t;

Configure::Configure(
    boost::shared_ptr<blieng::BliengState> _state)
    : BliObject(),
    m_state(_state)
{
}

Configure::~Configure()
{
#ifdef DATA_MUTEX_LOCK
    boost::lock_guard<boost::mutex> keylock(key_mutex);
#endif

    keys.erase(keys.begin(), keys.end());
    opt_keys.erase(opt_keys.begin(), opt_keys.end());
}

bool Configure::load(
    const std::string &_config_file)
{
    std::string fname = m_state->m_data->findFile(_config_file);
    if (fname != "") {
        data_json = m_state->m_data->readJson(fname);
        parse();
        return true;
    }
    return false;
}

void Configure::addKey(
    const std::string &val,
    key_type_t key_type)
{
#ifdef DATA_MUTEX_LOCK
    boost::lock_guard<boost::mutex> keylock(key_mutex);
#endif

    keys[val] = key_type;
}

void Configure::addOptionalKey(
    const std::string &val,
    key_type_t key_type)
{
#ifdef DATA_MUTEX_LOCK
    boost::lock_guard<boost::mutex> keylock(key_mutex);
#endif

    opt_keys[val] = key_type;
}

bool Configure::validate() const
{
    for (key_values_t key : keys) {
        if (!isValue(key.first)) {
            std::cout << key.first << ": NOT FOUND\n";
            return false;
        }
    }
    return true;
}

bool Configure::validateValues() const
{
    for (key_values_t key : keys) {
        if (!isValue(key.first)) return false;

        if (key.second == Configure::KeyString)
            getStringValue(key.first);
        else if (key.second == Configure::KeyDouble)
            getDoubleValue(key.first);
        else if (key.second == Configure::KeyInt)
            getIntValue(key.first);
        else if (key.second == Configure::KeyUInt)
            getUIntValue(key.first);
        else if (key.second == Configure::KeyBool)
            getBoolValue(key.first);
        else if (key.second == Configure::KeyStringList)
            getListValue(key.first);
        else if (key.second == Configure::KeyIntList)
            getIntValues(key.first);
    }
    return true;
}

void Configure::parseStringList(std::string key, const BliengJson realval)
{
    if (realval.is_array()) {
        std::vector<std::string> list_data;

        for (std::string v : realval) {
            list_data.push_back(v);
        }

        setValue(key, list_data);
    }
}

void Configure::parseIntList(std::string key, const BliengJson realval)
{
    if (realval.is_array()) {
        std::vector<int> list_data;

        for (int v : realval) {
            list_data.push_back(v);
        }

        setValue(key, list_data);
    }
}

void Configure::parseBool(std::string key, const BliengJson realval)
{
    bool res = false;

    if (realval.is_boolean()) {
        res = realval;
    } else if (realval.is_number()) {
        int v = realval;
        res = (v == 1);
    } else if (realval.is_string()) {
        std::string sval = realval;
        boost::algorithm::to_lower(sval);
        if (sval == "yes" || sval == "on" ||
            sval == "true" || sval == "y") {
                res = true;
        }
    }
    setValue(key, res);
}

void Configure::parse()
{
    if (!data_json.is_object()) return;

#ifdef DATA_MUTEX_LOCK
    boost::lock_guard<boost::mutex> keylock(key_mutex);
#endif

    // FIXME This is ugly
    for (auto data_key : JsonKeys(data_json)) {
        auto val = keys.find(data_key);
        auto val2 = opt_keys.find(data_key);
        if (val == keys.end()) val = opt_keys.find(data_key);

        if (val != keys.end() || val2 != opt_keys.end()) {
            const BliengJson realval = data_json[data_key];
            if (realval == nullptr) {}
            else if (val->second == Configure::KeyString) {
                if (realval.is_string()) {
                    std::string v = realval;
                    setValue(data_key, v);
                }
            }
            else if (val->second == Configure::KeyDouble) {
                if (realval.is_number_float()) {
                    double v = realval;
                    setValue(data_key, v);
                }
            }
            else if (val->second == Configure::KeyUInt) {
                if (realval.is_number()) {
                    unsigned int v = realval;
                    setValue(data_key, v);
                }
            }
            else if (val->second == Configure::KeyInt) {
                if (realval.is_number()) {
                    int v = realval;
                    setValue(data_key, v);
                }
            }
            else if (val->second == Configure::KeyBool) {
                if (realval.is_boolean()) {
                    bool v = realval;
                    setValue(data_key, v);
                }
            }
            else if (val->second == Configure::KeyStringList) {
                parseStringList(data_key, realval);
            }
            else if (val->second == Configure::KeyIntList) {
                parseIntList(data_key, realval);
            }
        }
    }
}

max_stars_repo_name: jroivas/blieng

max_issues_repo_name: jroivas/blieng

max_forks_repo_name: jroivas/blieng


text:
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "../TestUtils.hpp"

#include <Optimizer.hpp>
#include <Half.hpp>

#include <boost/test/unit_test.hpp>

using namespace armnn;

BOOST_AUTO_TEST_SUITE(Optimizer)
using namespace armnn::optimizations;

BOOST_AUTO_TEST_CASE(ConvertConstantsFloatToHalfTest)
{
    armnn::Graph graph;

    const armnn::TensorInfo info({ 1, 1, 1, 2 }, armnn::DataType::Float16);

    // Create const tensor from fp32 data
    unsigned int dims[] = { 4, 1, 1, 1 };
    std::vector<float> floatWeights{ 1.0f, 2.0f, 3.0f, 4.0f };
    armnn::ConstTensor weights(armnn::TensorInfo(4, dims, armnn::DataType::Float32), floatWeights);

    // Create simple test network
    auto input = graph.AddLayer<armnn::InputLayer>(0, "input");
    input->GetOutputSlot().SetTensorInfo(info);

    auto fc      = graph.AddLayer<armnn::FullyConnectedLayer>(armnn::FullyConnectedDescriptor(), "fc");
    fc->m_Weight = std::make_unique<armnn::ScopedCpuTensorHandle>(weights);
    fc->GetOutputSlot().SetTensorInfo(info);

    auto output = graph.AddLayer<armnn::OutputLayer>(1, "output");

    // Connect up the layers
    input->GetOutputSlot().Connect(fc->GetInputSlot(0));
    fc->GetOutputSlot().Connect(output->GetInputSlot(0));

    // Check tensor data type before conversion
    BOOST_CHECK(fc->m_Weight->GetTensorInfo().GetDataType() == armnn::DataType::Float32);

    // Run the optimizer
    armnn::Optimizer::Pass(graph, armnn::MakeOptimizations(ConvertConstantsFloatToHalf()));

    // Check tensor data type after conversion
    BOOST_CHECK(fc->m_Weight->GetTensorInfo().GetDataType() == armnn::DataType::Float16);

    // Check whether data matches expected fp16 data
    Half* data = fc->m_Weight->GetTensor<Half>();
    BOOST_CHECK(data[0] == Half(1.0f));
    BOOST_CHECK(data[1] == Half(2.0f));
    BOOST_CHECK(data[2] == Half(3.0f));
    BOOST_CHECK(data[3] == Half(4.0f));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: tom-gall/armnn

max_issues_repo_name: tom-gall/armnn

max_forks_repo_name: tom-gall/armnn


text:
#ifndef SRC_API_HANDLER_HPP
#define SRC_API_HANDLER_HPP

#pragma once

#include <Config.hpp>
#include <log/Log.hpp>

#include <boost/beast/http.hpp>
#include <chrono>
#include "Route.hpp"
#include "Types.hpp"

SAMP_API_BEGIN_NS

namespace http = boost::beast::http;    // from <boost/beast/http.hpp>

typedef http::request<http::dynamic_body> Request;
typedef http::response<http::dynamic_body> Response;

class SimpleRouteHandler {
public:
	SimpleRouteHandler() {}

	//virtual void Handle(Request& req, Response& response, Match& match, std::chrono::system_clock::time_point* p) {
	//	HandleRequest(req, response, match, p);
	//};
	//
	//virtual void HandleRequest(Request& req, Response& response, Match& match, std::chrono::system_clock::time_point* p) {
	//	Message data;
	//	data.type = "response";
	//	data.code = 200;
	//	data.message = "OK";
	//	Finalize(response, data, p);
	//
	//	const auto json = spotify::json::encode(data);
	//	boost::beast::ostream(response.body()) << json;
	//};

	virtual void HandleRequest(Request& req, Response& response, Match& match, std::chrono::system_clock::time_point* p) = 0;

	virtual void Finalize(Response& response, Message& message, std::chrono::system_clock::time_point* p) {
		response.set(http::field::content_type, "application/json");
		response.result(message.code);

		// Request response time
		auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - *p);
		message.time = milliseconds.count();
	}
};

class RequestInvalidHandler : public SimpleRouteHandler {
public:
	RequestInvalidHandler() : SimpleRouteHandler() {

	}

	void HandleRequest(Request& req, Response& response, Match& match, std::chrono::system_clock::time_point* p) {
		Message data;
		data.type = "invalid";
		data.code = 422;
		data.message = "Invalid";

		// Finalize
		Finalize(response, data, p);

		const auto json = spotify::json::encode(data);
		boost::beast::ostream(response.body()) << json;
	}

	void HandleRequest(Request& req, Response& response, Match& match, std::chrono::system_clock::time_point* p, Message& data) {
		// Finalize
		Finalize(response, data, p);

		const auto json = spotify::json::encode(data);
		boost::beast::ostream(response.body()) << json;
	}
};

template <class T>
class RouteHandler : public SimpleRouteHandler {
	typedef bool(*handler)(Request& req, Response& response, Match& match, T& ResponseData);
public:
	RouteHandler(handler func) : SimpleRouteHandler(), handler_(func) {

	}

	void HandleRequest(Request& req, Response& response, Match& match, std::chrono::system_clock::time_point* p) {
		T data;
		data.message = "OK";

		try {
			if (handler_(req, response, match, data)) {
				data.type = "response";
				data.code = 200;
			} else {
				data.code = 417;
				data.type = "error";
			}
		} catch (const spotify::json::decode_exception &e) {
			data.code = 500;
			data.message = fmt::format("Invalid request error: {}", e.what());
		}

		// Finalize
		Finalize(response, data, p);

		SAMP_DEBUG("Response message header: {} {} {} {}",
			      data.type, data.code, data.message, data.time);

		const auto json = spotify::json::encode(data);
		boost::beast::ostream(response.body()) << json;
	}
private:
	handler handler_;
};

class Handler {
public:
	void RegisterFunctions();

	void HandleRequest(Request& req, Response& response, std::string& remote, std::chrono::system_clock::time_point* p);
	bool Authorize(Request& req, std::string& remote);
	void ShowError(Request& req, Response& response, uint32_t code, std::string message, std::chrono::system_clock::time_point* p);

	void SetPassword(std::string& password) { password_ = password; }
	void SetSeed(uint32_t seed) { seed_ = seed; }
private:
	std::string password_;
	uint32_t seed_;

	//std::map<std::string, SimpleRouteHandler> routes_;
	std::map<std::string, std::unique_ptr<SimpleRouteHandler>> routes_;
	Route route_;
};

SAMP_API_END_NS

#endif


text: #include <boost/fusion/include/vector50.hpp>


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_UNIT_MODULE "nt2 boost.simd.arithmetic toolbox - rsqrt/scalar Mode"

//////////////////////////////////////////////////////////////////////////////
// unit test behavior of boost.simd.arithmetic components in scalar mode
//////////////////////////////////////////////////////////////////////////////
/// created by jt the 30/11/2010
///
#include <nt2/arithmetic/include/functions/rsqrt.hpp>
#include <nt2/arithmetic/include/functions/sqr.hpp>
#include <nt2/arithmetic/include/functions/rec.hpp>
#include <nt2/include/constants/i.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/dispatch/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/constant/constant.hpp>

NT2_TEST_CASE_TPL ( rsqrt_real__1_0,  BOOST_SIMD_REAL_TYPES)
{

  using nt2::rsqrt;
  using nt2::tag::rsqrt_;
  typedef typename std::complex<T> cT;
  typedef typename boost::dispatch::meta::as_integer<T>::type iT;
  typedef typename boost::dispatch::meta::call<rsqrt_(cT)>::type r_t;
  typedef typename nt2::meta::scalar_of<r_t>::type sr_t;
  typedef typename nt2::meta::scalar_of<r_t>::type ssr_t;
  typedef cT wished_r_t;

  // return type conformity test
  NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );
  std::cout << std::endl;
  double ulpd;
 ulpd=0.0;

  // std::cout << nt2::type_id(nt2::I<T>()) << std::endl;
  // specific values tests
   NT2_TEST_EQUAL(rsqrt(cT(1)), T(1));
   NT2_TEST_EQUAL(rsqrt(cT(nt2::Inf<T>())), cT(nt2::Zero<T>()));
   NT2_TEST_EQUAL(rsqrt(cT(nt2::Minf<T>())), cT(0, nt2::Zero<T>()));
   NT2_TEST_EQUAL(rsqrt(cT(nt2::Mone<T>())), cT(0, nt2::Mone<T>()));
   NT2_TEST_EQUAL(rsqrt(cT(nt2::Nan<T>())), cT(nt2::Nan<T>()));
   NT2_TEST_EQUAL(rsqrt(cT(nt2::One<T>())), cT(nt2::One<T>()));
   NT2_TEST_EQUAL(rsqrt(cT(nt2::Zero<T>())), cT(nt2::Zero<T>()));
   std::complex < T > a(1, 0);
   NT2_TEST_EQUAL(rsqrt(a), nt2::One<T>());
   std::complex < T > b(0, 1);
   NT2_TEST_EQUAL(rsqrt(b), cT(nt2::Sqrt_2o_2<T>(),nt2::Sqrt_2o_2<T>()));

  for(T i=-5; i <=  T(5) ; i+= T(0.5))
    {
      for(T j =-5; j < T(5); j+= T(0.5))
        {
          NT2_TEST_ULP_EQUAL(nt2::rec(nt2::sqr(nt2::rsqrt(cT(i, j)))), cT(i, j), 10);

} // end of test for floating_


text:
/**
 * @file
 * This file is part of SeisSol.
 *
 * @author Carsten Uphoff (c.uphoff AT tum.de, http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.)
 * @author Sebastian Wolf (wolf.sebastian AT in.tum.de, https://www5.in.tum.de/wiki/index.php/Sebastian_Wolf,_M.Sc.)
 *
 * @section LICENSE
 * Copyright (c) 2017 - 2020, SeisSol Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @section DESCRIPTION
 *
 **/
#include <Eigen/Eigenvalues>
#include <Kernels/precision.hpp>
#include <Initializer/typedefs.hpp>

#include <PUML/PUML.h>
#include <PUML/Downward.h>
#include <PUML/Upward.h>
#include "LtsWeights.h"

#include <Initializer/ParameterDB.h>
#include <Parallel/MPI.h>

#include <generated_code/init.h>

namespace seissol::initializers::time_stepping {

class FaceSorter {
private:
  std::vector<PUML::TETPUML::face_t> const &m_faces;

public:
  FaceSorter(std::vector<PUML::TETPUML::face_t> const &faces) : m_faces(faces) {}

  bool operator()(unsigned int a, unsigned int b) const {
    return m_faces[a].gid() < m_faces[b].gid();
  }
};

void LtsWeights::computeWeights(PUML::TETPUML const &mesh, double maximumAllowedTimeStep) {
  logInfo(seissol::MPI::mpi.rank()) << "Computing LTS weights.";

  // Note: Return value optimization is guaranteed while returning temp. objects in C++17
  m_mesh = &mesh;
  m_details = collectGlobalTimeStepDetails(maximumAllowedTimeStep);
  m_clusterIds = computeClusterIds();
  m_ncon = evaluateNumberOfConstraints();
  auto totalNumberOfReductions = enforceMaximumDifference();
  m_cellCosts = computeCostsPerTimestep();

  if (!m_vertexWeights.empty()) { m_vertexWeights.clear(); }
  m_vertexWeights.resize(m_clusterIds.size() * m_ncon);

  // calling virtual functions
  setVertexWeights();
  setAllowedImbalances();

  logInfo(seissol::MPI::mpi.rank()) << "Computing LTS weights. Done. " << utils::nospace << '('
                                    << totalNumberOfReductions << " reductions.)";
}

const int* LtsWeights::vertexWeights() const {
  assert(!m_vertexWeights.empty() && "vertex weights are not initialized");
  return m_vertexWeights.data();
}

const double* LtsWeights::imbalances() const {
  assert(!m_imbalances.empty() && "weight imbalances are not initialized");
  return m_imbalances.data();
}

int LtsWeights::nWeightsPerVertex() const {
  assert(m_ncon != std::numeric_limits<int>::infinity() && "num. constrains has not been initialized yet");
  return m_ncon;
}

void LtsWeights::computeMaxTimesteps(std::vector<double> const &pWaveVel,
                                     std::vector<double> &timeSteps, double maximumAllowedTimeStep) {
  std::vector<PUML::TETPUML::cell_t> const &cells = m_mesh->cells();
  std::vector<PUML::TETPUML::vertex_t> const &vertices = m_mesh->vertices();

  for (unsigned cell = 0; cell < cells.size(); ++cell) {
    // Compute insphere radius
    Eigen::Vector3d barycentre(0., 0., 0.);
    Eigen::Vector3d x[4];
    unsigned vertLids[4];
    PUML::Downward::vertices(*m_mesh, cells[cell], vertLids);
    for (unsigned vtx = 0; vtx < 4; ++vtx) {
      for (unsigned d = 0; d < 3; ++d) {
        x[vtx](d) = vertices[vertLids[vtx]].coordinate()[d];
      }
    }
    Eigen::Matrix4d A;
    A << x[0](0), x[0](1), x[0](2), 1.0,
        x[1](0), x[1](1), x[1](2), 1.0,
        x[2](0), x[2](1), x[2](2), 1.0,
        x[3](0), x[3](1), x[3](2), 1.0;

    double alpha = A.determinant();
    double Nabc = ((x[1] - x[0]).cross(x[2] - x[0])).norm();
    double Nabd = ((x[1] - x[0]).cross(x[3] - x[0])).norm();
    double Nacd = ((x[2] - x[0]).cross(x[3] - x[0])).norm();
    double Nbcd = ((x[2] - x[1]).cross(x[3] - x[1])).norm();
    double insphere = std::fabs(alpha) / (Nabc + Nabd + Nacd + Nbcd);

    // Compute maximum timestep (CFL=1)
    timeSteps[cell] = std::fmin(maximumAllowedTimeStep, 2.0 * insphere / (pWaveVel[cell] * (2 * CONVERGENCE_ORDER - 1)));
  }
}

int LtsWeights::getCluster(double timestep, double globalMinTimestep, unsigned rate) {
  if (rate == 1) {
    return 0;
  }

  double upper = rate * globalMinTimestep;

  int cluster = 0;
  while (upper <= timestep) {
    upper *= rate;
    ++cluster;
  }
  return cluster;
}

int LtsWeights::getBoundaryCondition(int const *boundaryCond, unsigned cell, unsigned face) {
  int bcCurrentFace = ((boundaryCond[cell] >> (face * 8)) & 0xFF);
  if (bcCurrentFace > 64) {
    bcCurrentFace = 3;
  }
  return bcCurrentFace;
}

int LtsWeights::ipow(int x, int y) {
  assert(y >= 0);

  if (y == 0) {
    return 1;
  }
  int result = x;
  while (--y) {
    result *= x;
  }
  return result;
}

LtsWeights::GlobalTimeStepDetails LtsWeights::collectGlobalTimeStepDetails(double maximumAllowedTimeStep) {

  const auto &cells = m_mesh->cells();
  std::vector<double> pWaveVel;
  pWaveVel.resize(cells.size());

  seissol::initializers::ElementBarycentreGeneratorPUML queryGen(*m_mesh);
  //up to now we only distinguish between anisotropic elastic any other isotropic material
#ifdef USE_ANISOTROPIC
  std::vector<seissol::model::AnisotropicMaterial> materials(cells.size());
  seissol::initializers::MaterialParameterDB<seissol::model::AnisotropicMaterial> parameterDB;
#elif defined(USE_POROELASTIC)
  std::vector<seissol::model::PoroElasticMaterial> materials(cells.size());
  seissol::initializers::MaterialParameterDB<seissol::model::PoroElasticMaterial> parameterDB;
#else
  std::vector<seissol::model::ElasticMaterial> materials(cells.size());
  seissol::initializers::MaterialParameterDB<seissol::model::ElasticMaterial> parameterDB;
#endif
  parameterDB.setMaterialVector(&materials);
  parameterDB.evaluateModel(m_velocityModel, queryGen);
  for (unsigned cell = 0; cell < cells.size(); ++cell) {
    pWaveVel[cell] = materials[cell].getMaxWaveSpeed();
  }

  GlobalTimeStepDetails details{};
  details.timeSteps.resize(cells.size());
  computeMaxTimesteps(pWaveVel, details.timeSteps, maximumAllowedTimeStep);

  double localMinTimestep = *std::min_element(details.timeSteps.begin(), details.timeSteps.end());
  double localMaxTimestep = *std::max_element(details.timeSteps.begin(), details.timeSteps.end());

#ifdef USE_MPI
  MPI_Allreduce(&localMinTimestep, &details.globalMinTimeStep, 1, MPI_DOUBLE, MPI_MIN, seissol::MPI::mpi.comm());
  MPI_Allreduce(&localMaxTimestep, &details.globalMaxTimeStep, 1, MPI_DOUBLE, MPI_MAX, seissol::MPI::mpi.comm());
#else
  details.globalMinTimeStep = localMinTimestep;
  details.globalMaxTimeStep = localMaxTimestep;
#endif
  return details;
}

std::vector<int> LtsWeights::computeClusterIds() {
  const auto &cells = m_mesh->cells();
  std::vector<int> clusterIds(cells.size(), 0);
  for (unsigned cell = 0; cell < cells.size(); ++cell) {
    clusterIds[cell] = getCluster(m_details.timeSteps[cell], m_details.globalMinTimeStep, m_rate);
  }
  return clusterIds;
}

std::vector<int> LtsWeights::computeCostsPerTimestep() {
  const auto &cells = m_mesh->cells();

  std::vector<int> cellCosts(cells.size());
  int const *boundaryCond = m_mesh->cellData(1);
  for (unsigned cell = 0; cell < cells.size(); ++cell) {
    int dynamicRupture = 0;
    int freeSurfaceWithGravity = 0;

    unsigned int faceids[4];
    PUML::Downward::faces(*m_mesh, cells[cell], faceids);

    for (unsigned face = 0; face < 4; ++face) {
      const auto faceType = static_cast<FaceType>(getBoundaryCondition(boundaryCond, cell, face));
      dynamicRupture += (faceType == FaceType::dynamicRupture) ? 1 : 0;
      freeSurfaceWithGravity += (faceType == FaceType::freeSurfaceGravity) ? 1 : 0;
    }

    const int costDynamicRupture = m_vertexWeightDynamicRupture * dynamicRupture;
    const int costDisplacement = m_vertexWeightFreeSurfaceWithGravity * freeSurfaceWithGravity;
    cellCosts[cell] = m_vertexWeightElement + costDynamicRupture + costDisplacement;
  }
  return cellCosts;
}

int LtsWeights::enforceMaximumDifference() {
  int totalNumberOfReductions = 0;
  int globalNumberOfReductions;
  do {
    int localNumberOfReductions = enforceMaximumDifferenceLocal();

#ifdef USE_MPI
    MPI_Allreduce(&localNumberOfReductions, &globalNumberOfReductions, 1, MPI_INT, MPI_SUM, seissol::MPI::mpi.comm());
#else
    globalNumberOfReductions = localNumberOfReductions;
#endif // USE_MPI
    totalNumberOfReductions += globalNumberOfReductions;
  } while (globalNumberOfReductions > 0);
  return totalNumberOfReductions;
}

int LtsWeights::enforceMaximumDifferenceLocal(int maxDifference) {
  int numberOfReductions = 0;

  std::vector<PUML::TETPUML::cell_t> const &cells = m_mesh->cells();
  std::vector<PUML::TETPUML::face_t> const &faces = m_mesh->faces();
  int const *boundaryCond = m_mesh->cellData(1);

#ifdef USE_MPI
  std::unordered_map<int, std::vector<int>> rankToSharedFaces;
  std::unordered_map<int, int> localFaceIdToLocalCellId;
#endif // USE_MPI

  for (unsigned cell = 0; cell < cells.size(); ++cell) {
    int timeCluster = m_clusterIds[cell];

    unsigned int faceids[4];
    PUML::Downward::faces(*m_mesh, cells[cell], faceids);
    for (unsigned f = 0; f < 4; ++f) {
      int difference = maxDifference;
      int boundary = getBoundaryCondition(boundaryCond, cell, f);
      // Continue for regular, dynamic rupture, and periodic boundary cells
      if (boundary == 0 || boundary == 3 || boundary == 6) {
        // We treat MPI neighbours later
        auto const &face = faces[faceids[f]];
        if (!face.isShared()) {
          int cellIds[2];
          PUML::Upward::cells(*m_mesh, face, cellIds);

          int neighbourCell = (cellIds[0] == static_cast<int>(cell)) ? cellIds[1] : cellIds[0];
          int otherTimeCluster = m_clusterIds[neighbourCell];

          if (boundary == 3) {
            difference = 0;
          }

          if (timeCluster > otherTimeCluster + difference) {
            timeCluster = otherTimeCluster + difference;
            ++numberOfReductions;
          }
        }
#ifdef USE_MPI
        else {
          rankToSharedFaces[face.shared()[0]].push_back(faceids[f]);
          localFaceIdToLocalCellId[faceids[f]] = cell;
        }
#endif // USE_MPI
      }
    }
    m_clusterIds[cell] = timeCluster;
  }

#ifdef USE_MPI
  FaceSorter faceSorter(faces);
  for (auto &sharedFaces: rankToSharedFaces) {
    std::sort(sharedFaces.second.begin(), sharedFaces.second.end(), faceSorter);
  }

  auto numExchanges = rankToSharedFaces.size();
  std::vector<MPI_Request> requests(2 * numExchanges);
  std::vector<std::vector<int>> ghost(numExchanges);
  std::vector<std::vector<int>> copy(numExchanges);

  auto exchange = rankToSharedFaces.begin();
  for (unsigned ex = 0; ex < numExchanges; ++ex) {
    auto exchangeSize = exchange->second.size();
    ghost[ex].resize(exchangeSize);
    copy[ex].resize(exchangeSize);

    for (unsigned n = 0; n < exchangeSize; ++n) {
      copy[ex][n] = m_clusterIds[localFaceIdToLocalCellId[exchange->second[n]]];
    }
    MPI_Isend(copy[ex].data(), exchangeSize, MPI_INT, exchange->first, 0, seissol::MPI::mpi.comm(), &requests[ex]);
    MPI_Irecv(ghost[ex].data(), exchangeSize, MPI_INT, exchange->first, 0, seissol::MPI::mpi.comm(),
              &requests[numExchanges + ex]);
    ++exchange;
  }

  MPI_Waitall(2 * numExchanges, requests.data(), MPI_STATUSES_IGNORE);

  exchange = rankToSharedFaces.begin();
  for (unsigned ex = 0; ex < numExchanges; ++ex) {
    auto exchangeSize = exchange->second.size();
    for (unsigned n = 0; n < exchangeSize; ++n) {
      int difference = maxDifference;
      int otherTimeCluster = ghost[ex][n];

      int cellIds[2];
      PUML::Upward::cells(*m_mesh, faces[exchange->second[n]], cellIds);
      int cell = (cellIds[0] >= 0) ? cellIds[0] : cellIds[1];

      unsigned int faceids[4];
      PUML::Downward::faces(*m_mesh, cells[cell], faceids);
      unsigned f = 0;
      for (; f < 4 && static_cast<int>(faceids[f]) != exchange->second[n]; ++f);
      assert(f != 4);

      int boundary = getBoundaryCondition(boundaryCond, cell, f);
      if (boundary == 3) {
        difference = 0;
      }

      if (m_clusterIds[cell] > otherTimeCluster + difference) {
        m_clusterIds[cell] = otherTimeCluster + difference;
        ++numberOfReductions;
      }
    }
    ++exchange;
  }

#endif // USE_MPI

  return numberOfReductions;
}
} // namespace seissol::initializers::time_stepping

max_stars_repo_name: fabian-kutschera/SeisSol

max_issues_repo_name: fabian-kutschera/SeisSol

max_forks_repo_name: fabian-kutschera/SeisSol


text:
/*
 *            Copyright 2009-2017 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      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.
 *
 */

// Overload of uBLAS prod function with MKL/GSL implementations

#include "egwbse.h"
#include <votca/xtp/esp2multipole.h>

#include <boost/format.hpp>
#include <boost/filesystem.hpp>

#include <boost/math/constants/constants.hpp>
#include <boost/numeric/ublas/symmetric.hpp>

using boost::format;
using namespace boost::filesystem;

namespace votca {
    namespace xtp {
        namespace ub = boost::numeric::ublas;

        // +++++++++++++++++++++++++++++ //
        // GWBSE MEMBER FUNCTIONS         //
        // +++++++++++++++++++++++++++++ //

        void EGWBSE::CleanUp() {

        }

        void EGWBSE::Initialize(Property *options) {

            // tasks to be done by IBSE: dft_input, dft_run, dft_parse, mgbft, bse_coupling
            _do_dft_input = false;
            _do_dft_run = false;
            _do_dft_parse = false;
            _do_gwbse = false;
            _do_esp=false;

            // update options with the VOTCASHARE defaults
            UpdateWithDefaults( options, "xtp" );
            ParseOptionsXML(options);

            // register all QM packages (Gaussian, turbomole, etc))
            QMPackageFactory::RegisterAll();

        }

        void EGWBSE::ParseOptionsXML(Property* options) {

            _maverick = (_nThreads == 1) ? true : false;
            string key = "options." + Identify();
            // job tasks
            string _tasks_string = options->get(key + ".tasks").as<string> ();
            if (_tasks_string.find("input") != std::string::npos) _do_dft_input = true;
            if (_tasks_string.find("dft") != std::string::npos) _do_dft_run = true;
            if (_tasks_string.find("parse") != std::string::npos) _do_dft_parse = true;
            if (_tasks_string.find("gwbse") != std::string::npos) _do_gwbse = true;
            if (_tasks_string.find("esp") != std::string::npos) _do_esp = true;

            key = "options."+Identify();

        if ( options->exists(key+".job_file")) {
            _jobfile = options->get(key+".job_file").as<string>();
        }
        else {
            throw std::runtime_error("Job-file not set. Abort.");
        }

            // options for gwbse
            key = "options." + Identify();
            string _gwbse_xml = options->get(key + ".gwbse_options").as<string> ();
            load_property_from_xml(_gwbse_options, _gwbse_xml.c_str());

            // options for dft package
            string _package_xml = options->get(key + ".dftpackage").as<string> ();
            //cout << endl << "... ... Parsing " << _package_xml << endl ;
            load_property_from_xml(_package_options, _package_xml.c_str());
            key = "package";
            _package = _package_options.get(key + ".name").as<string> ();

            //options for esp/partialcharges
            if (_do_esp){
                key = "options." + Identify();
                string _esp_xml = options->get(key + ".esp_options").as<string> ();
                load_property_from_xml(_esp_options, _esp_xml.c_str());
            }

        }

        void EGWBSE::WriteJobFile(ctp::Topology *top) {

    cout << endl << "... ... Writing job file: " << flush;
    std::ofstream ofs;
    ofs.open(_jobfile.c_str(), std::ofstream::out);
    if (!ofs.is_open()) throw runtime_error("\nERROR: bad file handle: " + _jobfile);

    ofs << "<jobs>" << endl;

    int jobCount = 0;

    std::vector<ctp::Segment*> segments=top->Segments();
    std::vector<ctp::Segment*>::iterator sit;
    for (sit = segments.begin(); sit != segments.end(); ++sit) {

        int id = ++jobCount;
        string tag = "";

        Property Input;
        Property *pInput = &Input.add("input","");
        Property *pSegment =  &pInput->add("segment" , (format("%1$s") % (*sit)->getId()).str() );
        pSegment->setAttribute<string>("type", (*sit)->getName() );
        pSegment->setAttribute<int>("id", (*sit)->getId() );
        ctp::Job job(id, tag, Input, ctp::Job::AVAILABLE );
        job.ToStream(ofs,"xml");
    }

    // CLOSE STREAM
    ofs << "</jobs>" << endl;
    ofs.close();

    cout << jobCount << " jobs" << flush;

}

        ctp::Job::JobResult EGWBSE::EvalJob(ctp::Topology *top, ctp::Job *job, ctp::QMThread *opThread) {

            Orbitals _orbitals;
            ctp::Job::JobResult jres = ctp::Job::JobResult();
            Property _job_input = job->getInput();
            list<Property*> lSegments = _job_input.Select("segment");

            vector < ctp::Segment* > segments;
            int segId = lSegments.front()->getAttribute<int>("id");
            string segType = lSegments.front()->getAttribute<string>("type");

            ctp::Segment *seg = top->getSegment(segId);
            assert(seg->getName() == segType);
            segments.push_back(seg);

            ctp::Logger* pLog = opThread->getLogger();

            CTP_LOG(ctp::logINFO, *pLog) << ctp::TimeStamp() << " Evaluating site " << seg->getId() << flush;

            string output;

            // directories and files
            path arg_path;
            string egwbse_work_dir = "OR_FILES";

            string frame_dir =  "frame_" + boost::lexical_cast<string>(top->getDatabaseId());
            string orb_file = (format("%1%_%2%%3%") % "molecule" % segId % ".orb").str();

            string _mol_dir = ( format("%1%%2%%3%") % "molecule" % "_" % segId ).str();
            string _package_append = _package + "_gwbse";
            string _qmpackage_work_dir = (arg_path / egwbse_work_dir / _package_append / frame_dir / _mol_dir).c_str();

            // get the corresponding object from the QMPackageFactory
            QMPackage *_qmpackage = QMPackages().Create(_package);
            // set a log file for the package
            _qmpackage->setLog(pLog);
            // set the run dir
            _qmpackage->setRunDir(_qmpackage_work_dir);
            // get the package options
            _qmpackage->Initialize(&_package_options);

            Property _job_summary;
            Property *_output_summary = &_job_summary.add("output", "");
            Property *_segment_summary = &_output_summary->add("segment", "");
            string segName = seg->getName();
            segId = seg->getId();
            _segment_summary->setAttribute("id", segId);
            _segment_summary->setAttribute("type", segName);

            // different tasks

            // create input for DFT
            if ( _do_dft_input ){
                boost::filesystem::create_directories( _qmpackage_work_dir );
                _qmpackage->WriteInputFile( segments );
            }

            bool _run_dft_status = false;
            if (_do_dft_run) {
                _run_dft_status = _qmpackage->Run();
                if (!_run_dft_status) {
                    output += "run failed; ";
                    CTP_LOG(ctp::logERROR, *pLog) << _qmpackage->getPackageName() << " run failed" << flush;
                    cout << *pLog;
                    jres.setOutput(output);
                    jres.setStatus(ctp::Job::FAILED);
                    delete _qmpackage;
                    return jres;
                }
            }

            // parse the log/orbitals files
            bool _parse_log_status = false;
            bool _parse_orbitals_status = false;
            if (_do_dft_parse) {
                _parse_log_status = _qmpackage->ParseLogFile(&_orbitals);

                if (!_parse_log_status) {
                    output += "log incomplete; ";
                    CTP_LOG(ctp::logERROR, *pLog) << "LOG parsing failed" << flush;
                    cout << *pLog;
                    jres.setOutput(output);
                    jres.setStatus(ctp::Job::FAILED);
                    delete _qmpackage;
                    return jres;
                }

                _parse_orbitals_status = _qmpackage->ParseOrbitalsFile(&_orbitals);

                if (!_parse_orbitals_status) {
                    output += "orbfile failed; ";
                    CTP_LOG(ctp::logERROR, *pLog) << "Orbitals parsing failed" << flush;
                    cout << *pLog;
                    jres.setOutput(output);
                    jres.setStatus(ctp::Job::FAILED);
                    delete _qmpackage;
                    return jres;
                }

            } // end of the parse orbitals/log
            else {

                    // load the DFT data from serialized orbitals object
                    string DIR = egwbse_work_dir + "/molecules_gwbse/" + frame_dir;
                    std::ifstream ifs((DIR + "/" + orb_file).c_str());
                    if (_do_gwbse){
                    CTP_LOG(ctp::logDEBUG, *pLog) << ctp::TimeStamp() << " Loading DFT data from " << DIR << "/" << orb_file << flush;
                    }
                    else {
                    CTP_LOG(ctp::logDEBUG, *pLog) << ctp::TimeStamp() << " Loading data from " << DIR << "/" << orb_file << flush;
                    }
                    boost::archive::binary_iarchive ia(ifs);
                    ia >> _orbitals;
                    ifs.close();
                }
            _qmpackage->CleanUp();
            delete _qmpackage;

            if (_do_gwbse) {

                GWBSE _gwbse=GWBSE(&_orbitals);

                _gwbse.setLogger(pLog);
                _gwbse.Initialize(&_gwbse_options);

                // define own logger for GW-BSE that is written into a runFolder logfile
                ctp::Logger gwbse_logger(ctp::logDEBUG);
                gwbse_logger.setMultithreading(false);
                _gwbse.setLogger(&gwbse_logger);
                gwbse_logger.setPreface(ctp::logINFO,    (format("\nGWBSE INF ...") ).str());
                gwbse_logger.setPreface(ctp::logERROR,   (format("\nGWBSE ERR ...") ).str());
                gwbse_logger.setPreface(ctp::logWARNING, (format("\nGWBSE WAR ...") ).str());
                gwbse_logger.setPreface(ctp::logDEBUG,   (format("\nGWBSE DBG ...") ).str());

                _gwbse.Evaluate();
                _gwbse.addoutput(_segment_summary);
                // write logger to log file
                std::ofstream ofs;
                string gwbse_logfile = _qmpackage_work_dir + "/gwbse.log";
                ofs.open(gwbse_logfile.c_str(), std::ofstream::out);
                if (!ofs.is_open()) {
                    throw runtime_error("Bad file handle: " + gwbse_logfile);
                }
                ofs << gwbse_logger << endl;
                ofs.close();

            }

            if (_do_esp){
                string mps_file="";
                Esp2multipole esp2multipole=Esp2multipole(pLog);;
                esp2multipole.Initialize(&_esp_options);
                string ESPDIR="MP_FILES/"+frame_dir+"/"+esp2multipole.GetIdentifier();
                esp2multipole.Extractingcharges(_orbitals);

                mps_file = (format("%1%_%2%_%3%.mps") % segType % segId % esp2multipole.GetIdentifier() ).str();
                boost::filesystem::create_directories( ESPDIR );
                esp2multipole.WritetoFile((ESPDIR + "/" + mps_file).c_str(),Identify());

                CTP_LOG(ctp::logDEBUG, *pLog) << "Written charges to " << (ESPDIR + "/" + mps_file).c_str() << flush;

                _segment_summary->add("partialcharges", (ESPDIR + "/" + mps_file).c_str());
            }
            CTP_LOG(ctp::logINFO, *pLog) << ctp::TimeStamp() << " Finished evaluating site " << seg->getId() << flush;

            if(_do_dft_parse ||_do_gwbse ){
            CTP_LOG(ctp::logDEBUG, *pLog) << "Saving data to " << orb_file << flush;
            string DIR = egwbse_work_dir + "/molecules_gwbse/" + frame_dir;
            boost::filesystem::create_directories(DIR);
            std::ofstream ofs((DIR + "/" + orb_file).c_str());
            boost::archive::binary_oarchive oa(ofs);

            oa << _orbitals;
            ofs.close();
            }

            // output of the JOB
            jres.setOutput(_job_summary);
            jres.setStatus(ctp::Job::COMPLETE);

            // dump the LOG

            return jres;
        }

    }

};

max_stars_repo_name: choudarykvsp/xtp

max_issues_repo_name: choudarykvsp/xtp

max_forks_repo_name: choudarykvsp/xtp