hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e63bee55ed587adeac07ed6bfe9ee359b3fad55a
| 1,495
|
cpp
|
C++
|
cpp/src/exercise/e0200/e0134.cpp
|
ajz34/LeetCodeLearn
|
70ff8a3c17199a100819b356735cd9b13ff166a7
|
[
"MIT"
] | null | null | null |
cpp/src/exercise/e0200/e0134.cpp
|
ajz34/LeetCodeLearn
|
70ff8a3c17199a100819b356735cd9b13ff166a7
|
[
"MIT"
] | null | null | null |
cpp/src/exercise/e0200/e0134.cpp
|
ajz34/LeetCodeLearn
|
70ff8a3c17199a100819b356735cd9b13ff166a7
|
[
"MIT"
] | null | null | null |
// https://leetcode-cn.com/problems/gas-station/
#include "extern.h"
class S0134 {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
if (gas.empty()) return -1;
for (int i = 0; i < gas.size(); ++i) {
gas[i] -= cost[i];
}
int total = 0;
int cnt = 0, result = 0, start_idx = -1;
bool in_cnt = false;
for (int i = 0; i < gas.size() * 2; ++i) {
int v = gas[i % gas.size()];
if (!in_cnt && v >= 0) {
in_cnt = true;
total = v;
cnt = 1;
start_idx = i % gas.size();
}
else if (in_cnt) {
if (total + v < 0) {
in_cnt = false;
result = max(result, cnt);
if (result >= gas.size())
return start_idx;
}
else {
++cnt;
total += v;
}
}
}
result = max(result, cnt);
if (result >= gas.size())
return start_idx;
else return -1;
}
};
TEST(e0200, e0134) {
vector<int> gas, cost;
gas = str_to_vec<int>("[1,2,3,4,5]");
cost = str_to_vec<int>("[3,4,5,1,2]");
ASSERT_EQ(S0134().canCompleteCircuit(gas, cost), 3);
gas = str_to_vec<int>("[2,3,4]");
cost = str_to_vec<int>("[3,4,3]");
ASSERT_EQ(S0134().canCompleteCircuit(gas, cost), -1);
}
| 28.75
| 65
| 0.419398
|
ajz34
|
e63c60d0a3e74969e72c64f8268ad43e80071be2
| 460
|
cpp
|
C++
|
drape/drape_tests/bingind_info_tests.cpp
|
bowlofstew/omim
|
8045157c95244aa8f862d47324df42a19b87e335
|
[
"Apache-2.0"
] | 4,879
|
2015-09-30T10:56:36.000Z
|
2022-03-31T18:43:03.000Z
|
drape/drape_tests/bingind_info_tests.cpp
|
bowlofstew/omim
|
8045157c95244aa8f862d47324df42a19b87e335
|
[
"Apache-2.0"
] | 7,549
|
2015-09-30T10:52:53.000Z
|
2022-03-31T22:04:22.000Z
|
drape/drape_tests/bingind_info_tests.cpp
|
bowlofstew/omim
|
8045157c95244aa8f862d47324df42a19b87e335
|
[
"Apache-2.0"
] | 1,493
|
2015-09-30T10:43:06.000Z
|
2022-03-21T09:16:49.000Z
|
#include "testing/testing.hpp"
#include "drape/binding_info.hpp"
using namespace dp;
UNIT_TEST(BindingInfoIDTest)
{
{
BindingInfo info(1, 1);
TEST_EQUAL(info.GetID(), 1, ());
}
{
BindingInfo info(1);
TEST_EQUAL(info.GetID(), 0, ());
}
}
UNIT_TEST(DynamicHandlingTest)
{
{
BindingInfo info(1);
TEST_EQUAL(info.IsDynamic(), false, ());
}
{
BindingInfo info(1, 1);
TEST_EQUAL(info.IsDynamic(), true, ());
}
}
| 14.375
| 44
| 0.613043
|
bowlofstew
|
e63dfdc5f76e9141f506421913a017b2b57aaf83
| 2,242
|
cpp
|
C++
|
Viewer/main.cpp
|
henfredemars/Lamina-Project
|
4dc547947c28a287714179893d3db75b2288e9b6
|
[
"MIT"
] | null | null | null |
Viewer/main.cpp
|
henfredemars/Lamina-Project
|
4dc547947c28a287714179893d3db75b2288e9b6
|
[
"MIT"
] | null | null | null |
Viewer/main.cpp
|
henfredemars/Lamina-Project
|
4dc547947c28a287714179893d3db75b2288e9b6
|
[
"MIT"
] | null | null | null |
//*******************************************************
/*Lamina Project: Graphic Visualization of Particles
I would like to give credit to the tutorials found in the following webpages:
http://www.lighthouse3d.com/tutorials/glut-tutorial/
http://lazyfoo.net/tutorials/OpenGL/index.php#Hello OpenGL
https://www3.ntu.edu.sg/home/ehchua/programming/opengl/CG_Examples.html
https://en.wikibooks.org/wiki/OpenGL_Programming/
*/
//*******************************************************
#include "LUtil.h"
#include <vector>
#include <string>
#include "../lib/sim/include/Database.h"
#include "../lib/sim/include/Particle.h"
#include "../lib/sim/include/LaminaParticle.h"
#include "../lib/sim/include/SourceParticle.h"
using namespace std;
void runMainLoop( int val );
int main( int argc, char* args[] ) {
string filename;
if (argc != 2) {
cout << "You need to specify a valid file, using test1.db as input instead\n";
filename = "test1.db";
}
else {
string str(args[1]);
filename = str;
}
//Initialize FreeGLUT
glutInit( &argc, args );
//Use OpenGL 2.1
glutInitContextVersion( 2, 1 );
//Create Double Buffered, Depth enabled, RGBA Window and Stencil enabled
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );
glutCreateWindow( "Project3" );
//Set keyboard handler function
glutKeyboardFunc( handleKeys );
//Set Mouse handler function
glutMouseFunc( handleMouse );
//Set rendering function
glutDisplayFunc( render );
//Set window resize function
glutReshapeFunc(reshape);
//Set mouse tracking function
glutPassiveMotionFunc( mouseMovement );
//Set main loop
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, 0 );
//Do initialization
if( !initGL( filename ) ) {
printf( "Unable to run graphics application!\n" );
return 1;
}
//Start GLUT main loop
glutMainLoop();
return 0;
}
void runMainLoop( int val ) {
//Rendering...
render();
//Run frames every 1/60 os second
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, val );
}
| 26.690476
| 86
| 0.628903
|
henfredemars
|
e63fd302503fcab3eb0a026adde5c4098535f023
| 4,239
|
hpp
|
C++
|
include/vop.hpp
|
zhu48/led_strip
|
f74f0663cbf5a8b68a54f54ce04691c45e03253b
|
[
"MIT"
] | null | null | null |
include/vop.hpp
|
zhu48/led_strip
|
f74f0663cbf5a8b68a54f54ce04691c45e03253b
|
[
"MIT"
] | null | null | null |
include/vop.hpp
|
zhu48/led_strip
|
f74f0663cbf5a8b68a54f54ce04691c45e03253b
|
[
"MIT"
] | null | null | null |
#ifndef VOP_HPP
#define VOP_HPP
#include <cstddef>
namespace vop {
/**
* Vector add two containers, putting the result into a third container.
*
* \tparam itr_l Iterator type of the left-hand-side addition operand container.
* \tparam itr_r Iterator type of the right-hand-side addition operand container.
* \tparam itr_sum Iterator type of the addition result container.
*
* \param sum Iterator into the addition result container.
* \param l Iterator into the left-hand-side addition operand container.
* \param r Iterator into the right-hand-side addition operand container.
* \param leng Number of elements to perform vector addition over.
*/
template<typename itr_l, typename itr_r, typename itr_sum>
constexpr void sum( itr_sum sum, itr_l l, itr_r r, std::size_t leng );
/**
* Take the vector minimum of two containers, putting the result into a third container.
*
* \tparam itr_l Iterator type of the left-hand-side minimization operand container.
* \tparam itr_r Iterator type of the right-hand-side minimization operand container.
* \tparam itr_min Iterator type of the minimization result container.
*
* \param min Iterator into the minimization result container.
* \param l Iterator into the left-hand-side minimization operand container.
* \param r Iterator into the right-hand-side minimization operand container.
* \param leng Number of elements to perform vector minimization over.
*/
template<typename itr_l, typename itr_r, typename itr_min>
constexpr void min( itr_min min, itr_l l, itr_r r, std::size_t leng );
/**
* Vector multiply a range by a scaler value.
*
* \tparam itr Iterator type of the range to multiply.
* \tparam scale_type Type of the scaler to multiply by.
*
* \param begin Iterator to the beginning of the range.
* \param end Iterator to one-past-the-end of the range.
* \param s The scaler to multiply by.
*/
template<typename itr, typename scale_type>
constexpr void mult( itr begin, itr end, scale_type s );
/**
* Take evenly-spaced samples from a range, and put the result into another range.
*
* \tparam stride The sample spacing.
* \tparam itr Iterator type of the range to sample.
* \tparam output_itr Iterator type of the range to store samples to.
*
* \param out_begin Iterator to the beginning of the range to write samples to.
* \param begin Iterator to the beginning of the range to take samples of.
* \param end Iterator to one-past-the-end of the range to take samples of.
*
* \return Returns an iterator to the next position in the output range.
*/
template<std::size_t stride, typename itr, typename output_itr>
constexpr output_itr sample( output_itr out_begin, itr begin, itr end );
/**
* Take evenly-spaced samples through a range of indices.
*
* Take evenly-spaced samples of the indices into a values range. For each sampled index, write
* the value in the values range at that index into the results range.
*
* \tparam stride The sample spacing.
* \tparam idx_itr Iterator type of the range containing index-type objects.
* \tparam val_itr Iterator type of the range containing the values to sample.
* \tparam output_itr Iterator type of the results range.
*
* \param out_begin Iterator to the beginning of the results range.
* \param idx_begin Iterator to the beginning of the index-containing range.
* \param idx_end Iterator to one-past-the-end of the index-containing range.
* \param values_begin Iterator to the beginning of the values range.
*
* \return Returns an iterator to the next position in the output range.
*/
template<std::size_t stride, typename idx_itr, typename val_itr, typename output_itr>
constexpr output_itr sample_by_index(
output_itr out_begin,
idx_itr idx_begin,
idx_itr idx_end,
val_itr values_begin
);
}
#include "vop.ipp"
#endif // #ifndef VOP_HPP
| 43.255102
| 99
| 0.681529
|
zhu48
|
e6441c8b37b7d62746b4b3b37a1f3808926c119f
| 2,226
|
hpp
|
C++
|
include/eagine/integer_range.hpp
|
matus-chochlik/eagine-core
|
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
|
[
"BSL-1.0"
] | 1
|
2022-01-25T10:31:51.000Z
|
2022-01-25T10:31:51.000Z
|
include/eagine/integer_range.hpp
|
matus-chochlik/eagine-core
|
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
|
[
"BSL-1.0"
] | null | null | null |
include/eagine/integer_range.hpp
|
matus-chochlik/eagine-core
|
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
|
[
"BSL-1.0"
] | null | null | null |
/// @file
///
/// Copyright Matus Chochlik.
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
///
#ifndef EAGINE_INTEGER_RANGE_HPP
#define EAGINE_INTEGER_RANGE_HPP
#include "iterator.hpp"
namespace eagine {
/// @brief Integer range type template usable in range-based loops.
/// @ingroup type_utils
///
/// Instances of this class can be used as the range in range-based for loops
/// instead of using, comparing and incrementing a for loop variable.
template <typename T>
class integer_range {
public:
/// @brief Default constructor.
/// @post empty()
/// @post begin() == end()
constexpr integer_range() noexcept = default;
/// @brief Initialization specifying the past the end integer value.
/// @post size() == e
constexpr integer_range(const T e) noexcept
: _end{e} {}
/// @brief Initialization specifying the begin and past the end integer values.
/// @post size() == e - b
constexpr integer_range(const T b, const T e) noexcept
: _begin{b}
, _end{e} {}
/// @brief Iterator type alias.
using iterator = selfref_iterator<T>;
/// @brief Iteration count type alias.
using size_type = decltype(std::declval<T>() - std::declval<T>());
/// @brief Indicates that the range is empty.
/// @see size
constexpr auto empty() const noexcept {
return _end == _begin;
}
/// @brief Returns the number of iteration steps in this range.
/// @see empty
constexpr auto size() const noexcept {
return _end - _begin;
}
/// @brief Returns the iterator to the start of the range.
constexpr auto begin() const noexcept -> iterator {
return {_begin};
}
/// @brief Returns the iterator past the end of the range.
constexpr auto end() const noexcept -> iterator {
return {_end};
}
private:
const T _begin{0};
const T _end{0};
};
/// @brief Deduction guide for integer_range.
/// @ingroup type_utils
template <typename B, typename E>
integer_range(B, E) -> integer_range<std::common_type_t<B, E>>;
} // namespace eagine
#endif // EAGINE_INTEGER_RANGE_HPP
| 27.481481
| 83
| 0.660827
|
matus-chochlik
|
e6463ce0d96cd56d96d6b0d963dfa3c44edc9660
| 629
|
cpp
|
C++
|
collision.cpp
|
CaptainDreamcast/Torchbearer
|
144a1d8eca66e994dc832fc4116431ea267e00d9
|
[
"MIT"
] | null | null | null |
collision.cpp
|
CaptainDreamcast/Torchbearer
|
144a1d8eca66e994dc832fc4116431ea267e00d9
|
[
"MIT"
] | null | null | null |
collision.cpp
|
CaptainDreamcast/Torchbearer
|
144a1d8eca66e994dc832fc4116431ea267e00d9
|
[
"MIT"
] | null | null | null |
#include "collision.h"
#include <prism/blitz.h>
static struct {
CollisionListData* mPlayerCollisionList;
CollisionListData* mObstacleCollisionList;
} gCollisionData;
void initCollisions()
{
gCollisionData.mPlayerCollisionList = addCollisionListToHandler();
gCollisionData.mObstacleCollisionList = addCollisionListToHandler();
addCollisionHandlerCheck(gCollisionData.mPlayerCollisionList, gCollisionData.mObstacleCollisionList);
}
CollisionListData* getPlayerCollisionList()
{
return gCollisionData.mPlayerCollisionList;
}
CollisionListData* getObstacleCollisionList()
{
return gCollisionData.mObstacleCollisionList;
}
| 25.16
| 102
| 0.844197
|
CaptainDreamcast
|
e646b1207910a2f5c038c30eb2ad659a8e39e21b
| 7,158
|
cpp
|
C++
|
src/HubLabelStore.cpp
|
dbahrdt/path_finder
|
1105966e5b50590acd9aca30ceb6922b0e40c259
|
[
"Apache-2.0"
] | 1
|
2021-03-12T23:18:30.000Z
|
2021-03-12T23:18:30.000Z
|
src/HubLabelStore.cpp
|
dbahrdt/path_finder
|
1105966e5b50590acd9aca30ceb6922b0e40c259
|
[
"Apache-2.0"
] | 8
|
2020-05-27T17:25:58.000Z
|
2020-05-29T10:39:54.000Z
|
src/HubLabelStore.cpp
|
dbahrdt/path_finder
|
1105966e5b50590acd9aca30ceb6922b0e40c259
|
[
"Apache-2.0"
] | 1
|
2020-10-19T09:01:09.000Z
|
2020-10-19T09:01:09.000Z
|
//
// Created by sokol on 23.01.20.
//
#include "path_finder/storage/HubLabelStore.h"
#include <cstring>
#include <execution>
#include <memory>
#include <path_finder/helper/Static.h>
#include <sstream>
#include <utility>
namespace pathFinder {
HubLabelStore::HubLabelStore(size_t numberOfLabels) {
m_forwardOffset = new OffsetElement[numberOfLabels];
m_backwardOffset = new OffsetElement[numberOfLabels];
m_backwardLabels = nullptr;
m_forwardLabels = nullptr;
this->m_numberOfLabels = numberOfLabels;
}
void HubLabelStore::store(const std::vector<CostNode> &label, NodeId id, EdgeDirection direction) {
auto &storePointer = direction ? m_forwardLabels : m_backwardLabels;
auto &offsetPointer = direction ? m_forwardOffset : m_backwardOffset;
auto &size = direction ? m_forwardLabelSize : m_backwardLabelSize;
offsetPointer[id] = OffsetElement{size, (uint32_t)label.size()};
{
auto * newData = new CostNode[size + label.size()];
std::copy(storePointer, storePointer+size, newData);
std::copy(label.begin(), label.end(), storePointer+size);
std::swap(newData, storePointer);
delete[] newData;
}
size += label.size();
}
void HubLabelStore::store(std::vector<HubLabelStore::IdLabelPair> &idLabels, EdgeDirection direction) {
size_t allocationSize = std::accumulate(
idLabels.begin(), idLabels.end(), (size_t)0,
[](size_t init, const HubLabelStore::IdLabelPair &idLabelPair) { return init + idLabelPair.second.size(); });
auto &storePointer = direction ? m_forwardLabels : m_backwardLabels;
auto &offsetPointer = direction ? m_forwardOffset : m_backwardOffset;
auto &size = direction ? m_forwardLabelSize : m_backwardLabelSize;
{
CostNode * newData = new CostNode[size + allocationSize];
std::copy(storePointer, storePointer+size, newData);
std::swap(newData, storePointer);
delete[] newData;
}
std::cout << "writing labels: 0/" << idLabels.size() << '\r';
int i = 0;
for (auto &&[id, label] : idLabels) {
offsetPointer[id] = OffsetElement{size, (uint32_t)label.size()};
std::memcpy(storePointer + size, label.data(), sizeof(CostNode) * label.size());
size += label.size();
label.clear();
char newLineChar = (i == idLabels.size() - 1) ? '\n' : '\r';
std::cout << "writing labels: " << ++i << '/' << idLabels.size() << newLineChar;
}
}
MyIterator<const CostNode *> HubLabelStore::retrieveIt(NodeId id, EdgeDirection direction) const {
if (id > m_numberOfLabels - 1)
throw std::runtime_error("[HublabelStore] node id does not exist.");
auto offsetElement = direction ? m_forwardOffset[id] : m_backwardOffset[id];
auto labelEnd = offsetElement.position + offsetElement.size;
const auto &storePointer = direction ? m_forwardLabels : m_backwardLabels;
return MyIterator<const CostNode *>(storePointer + offsetElement.position, storePointer + labelEnd);
}
std::vector<CostNode> HubLabelStore::retrieve(NodeId id, EdgeDirection direction) const {
if (id > m_numberOfLabels - 1)
throw std::runtime_error("[HublabelStore] node id does not exist.");
bool forward = (EdgeDirection::FORWARD == direction);
auto offsetElement = forward ? m_forwardOffset[id] : m_backwardOffset[id];
if (offsetElement.size == 0) {
return std::vector<CostNode>();
}
std::vector<CostNode> storeVec;
storeVec.reserve(offsetElement.size);
auto labelEnd = offsetElement.position + offsetElement.size;
volatile const auto &storePointer = forward ? m_forwardLabels : m_backwardLabels;
for (auto i = offsetElement.position; i < labelEnd; ++i) {
storeVec.push_back(storePointer[i]);
}
return storeVec;
}
void HubLabelStore::retrieve(NodeId id, EdgeDirection direction, CostNode *&storeVec, size_t &size) const {
if (id > m_numberOfLabels - 1)
throw std::runtime_error("[HublabelStore] node id does not exist.");
bool forward = (EdgeDirection::FORWARD == direction);
auto offsetElement = forward ? m_forwardOffset[id] : m_backwardOffset[id];
if (offsetElement.size == 0) {
storeVec = nullptr;
size = 0;
return;
}
auto labelEnd = offsetElement.position + offsetElement.size;
storeVec = new CostNode[offsetElement.size];
size = offsetElement.size;
const auto storePointer = forward ? m_forwardLabels : m_backwardLabels;
for (auto i = offsetElement.position, j = (size_t)0; i < labelEnd; ++i, ++j) {
storeVec[j] = storePointer[i];
}
}
size_t HubLabelStore::getNumberOfLabels() const { return m_numberOfLabels; }
HubLabelStore::HubLabelStore(HubLabelStoreInfo hubLabelStoreInfo) {
this->m_forwardLabels = hubLabelStoreInfo.forwardLabels;
this->m_backwardLabels = hubLabelStoreInfo.backwardLabels;
this->m_forwardOffset = hubLabelStoreInfo.forwardOffset;
this->m_backwardOffset = hubLabelStoreInfo.backwardOffset;
this->m_numberOfLabels = hubLabelStoreInfo.numberOfLabels;
this->m_forwardLabelSize = hubLabelStoreInfo.forwardLabelSize;
this->m_backwardLabelSize = hubLabelStoreInfo.backwardLabelSize;
this->m_forwardLabelsMMap = hubLabelStoreInfo.forwardLabelsMMap;
this->m_backwardLabelsMMap = hubLabelStoreInfo.backwardLabelsMMap;
this->m_forwardOffsetMMap = hubLabelStoreInfo.forwardOffsetMMap;
this->m_backwardOffsetMMap = hubLabelStoreInfo.backwardOffsetMMap;
this->calculatedUntilLevel = hubLabelStoreInfo.calculatedUntilLevel;
}
HubLabelStore::~HubLabelStore() {
Static::conditionalFree(m_forwardLabels, m_forwardLabelsMMap, m_forwardLabelSize * sizeof(CostNode));
Static::conditionalFree(m_backwardLabels, m_backwardLabelsMMap, m_backwardLabelSize * sizeof(CostNode));
Static::conditionalFree(m_forwardOffset, m_forwardOffsetMMap, m_numberOfLabels * sizeof(OffsetElement));
Static::conditionalFree(m_backwardOffset, m_backwardOffsetMMap, m_numberOfLabels * sizeof(OffsetElement));
}
size_t HubLabelStore::getForwardLabelsSize() const { return m_forwardLabelSize; }
size_t HubLabelStore::getBackwardLabelsSize() const { return m_backwardLabelSize; }
size_t HubLabelStore::getForwardOffsetSize() const { return m_numberOfLabels; }
size_t HubLabelStore::getBackwardOffsetSize() const { return m_numberOfLabels; }
[[maybe_unused]] std::string HubLabelStore::printStore() const {
std::stringstream ss;
for (NodeId i = 0; i < m_numberOfLabels; ++i) {
std::vector<CostNode> forwardVec = retrieve(i, EdgeDirection::FORWARD);
std::vector<CostNode> backwardVec = retrieve(i, EdgeDirection::BACKWARD);
ss << "label for id: " << i << '\n';
ss << "forward:" << '\n';
for (const auto &[id, cost, previousNode] : forwardVec) {
ss << id << ' ' << cost << ' ' << previousNode << '\n';
}
ss << "backward:" << '\n';
for (const auto &[id, cost, previousNode] : backwardVec) {
ss << id << ' ' << cost << ' ' << previousNode << '\n';
}
}
return ss.str();
}
std::shared_ptr<HubLabelStore> HubLabelStore::makeShared(size_t numberOfLabels) {
return std::make_shared<HubLabelStore>(numberOfLabels);
}
auto HubLabelStore::getSpaceConsumption() const -> size_t {
return (m_forwardLabelSize + m_backwardLabelSize) * sizeof(CostNode)
+ (m_numberOfLabels + m_numberOfLabels) * sizeof (OffsetElement);
};
} // namespace pathFinder
| 42.607143
| 115
| 0.732886
|
dbahrdt
|
e64a81619bd4cf65be3f5b3a96879a0d6555b8c8
| 4,717
|
hpp
|
C++
|
include/string/string_pool.hpp
|
Life4gal/galToolbox
|
14f213b015eba673e702ca0daaac21d35ad2c7e0
|
[
"Unlicense"
] | null | null | null |
include/string/string_pool.hpp
|
Life4gal/galToolbox
|
14f213b015eba673e702ca0daaac21d35ad2c7e0
|
[
"Unlicense"
] | null | null | null |
include/string/string_pool.hpp
|
Life4gal/galToolbox
|
14f213b015eba673e702ca0daaac21d35ad2c7e0
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <algorithm>
#include <memory>
#include <string_view>
#include <utils/assert.hpp>
#include <vector>
namespace gal::toolbox::string
{
template<typename CharType, bool isNullTerminate = true, typename CharTrait = std::char_traits<CharType>>
class string_block
{
public:
constexpr static bool is_null_terminate = isNullTerminate;
using view_type = std::basic_string_view<CharType, CharTrait>;
using value_type = typename view_type::value_type;
using size_type = typename view_type::size_type;
constexpr explicit string_block(size_type capacity)
: memory_(new value_type[capacity]),
capacity_(capacity),
size_(0) {}
[[nodiscard]] constexpr static size_type length_of(view_type str) noexcept
{
if constexpr (is_null_terminate)
{
return str.length() + 1;
}
else
{
return str.length();
}
}
[[nodiscard]] constexpr view_type append(view_type str)
{
// todo: shall we re-alloc more memory?
utils::gal_assert(storable(str), "There is not enough space for this string.");
const auto dest = memory_.get() + size_;
std::ranges::copy(str, dest);
if constexpr (is_null_terminate)
{
dest[str.length()] = 0;
}
size_ += length_of(str);
return {dest, str.length()};
}
[[nodiscard]] constexpr bool storable(view_type str) const noexcept
{
return available_space() >= length_of(str);
}
[[nodiscard]] constexpr size_type available_space() const noexcept
{
return capacity_ - size_;
}
[[nodiscard]] constexpr bool more_available_space_than(const string_block& other)
{
return available_space() > other.available_space();
}
private:
std::unique_ptr<value_type[]> memory_;
size_type capacity_;
size_type size_;
};
template<typename CharType, bool isNullTerminate = true, typename CharTrait = std::char_traits<CharType>>
class string_pool
{
public:
using block_type = string_block<CharType, isNullTerminate, CharTrait>;
using pool_type = std::vector<block_type>;
using view_type = typename block_type::view_type;
using value_type = typename block_type::value_type;
using size_type = typename block_type::size_type;
constexpr string_pool() = default;
constexpr explicit string_pool(size_type capacity)
: capacity_(capacity) {}
[[nodiscard]] constexpr view_type append(view_type str)
{
return append_str_into_block(str, find_or_create_block(str));
}
[[nodiscard]] constexpr size_type size() const noexcept
{
return pool_.size();
}
[[nodiscard]] constexpr size_type capacity() const noexcept
{
return capacity_;
}
// Only affect the block created after modification
constexpr void new_capacity(size_type capacity) noexcept
{
capacity_ = capacity;
}
private:
using block_iterator = typename pool_type::iterator;
[[nodiscard]] constexpr view_type append_str_into_block(view_type str, block_iterator pos)
{
const auto ret = pos->append(str);
shake_it(pos);
return ret;
}
[[nodiscard]] constexpr block_iterator find_or_create_block(view_type str)
{
if (const auto block = find_storable_block(str); block != pool_.end())
{
return block;
}
return create_storable_block(str);
}
[[nodiscard]] constexpr block_iterator find_first_possible_storable_block(view_type str) noexcept
{
if (pool_.size() > 2 && not std::ranges::prev(pool_.end(), 2)->storable(str))
{
return std::ranges::prev(pool_.end());
}
else
{
return pool_.begin();
}
}
[[nodiscard]] constexpr block_iterator find_storable_block(view_type str) noexcept
{
return std::ranges::lower_bound(
find_first_possible_storable_block(str),
pool_.end(),
true,
[](bool b, bool)
{ return b; },
[&str](const auto& block)
{ return not block.storable(str); });
}
[[nodiscard]] constexpr block_iterator create_storable_block(view_type str)
{
pool_.emplace_back(std::ranges::max(capacity_, block_type::length_of(str)));
return std::ranges::prev(pool_.end());
}
constexpr void shake_it(block_iterator block)
{
if (
block == pool_.begin() ||
block->more_available_space_than(*std::ranges::prev(block)))
{
return;
}
if (const auto it =
std::ranges::upper_bound(
pool_.begin(),
block,
block->available_space(),
[](const auto space, const auto curr)
{ return space < curr; },
[](const auto& b)
{ return b.available_space(); });
it != block)
{
std::ranges::rotate(it, block, std::ranges::next(block));
}
}
pool_type pool_;
const size_type capacity_ = 8196;
};
}// namespace gal::toolbox::string
| 24.696335
| 106
| 0.679669
|
Life4gal
|
e64c1c47e9dd2b799f5cfa689d48ce9a9eef9980
| 3,871
|
cpp
|
C++
|
src/component/text_component.cpp
|
equal-games/equal
|
acaf0d456d7b996dd2a6bc23150cd45ddf618296
|
[
"BSD-2-Clause",
"Apache-2.0"
] | 7
|
2019-08-07T21:27:27.000Z
|
2020-11-27T16:33:16.000Z
|
src/component/text_component.cpp
|
equal-games/equal
|
acaf0d456d7b996dd2a6bc23150cd45ddf618296
|
[
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null |
src/component/text_component.cpp
|
equal-games/equal
|
acaf0d456d7b996dd2a6bc23150cd45ddf618296
|
[
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2019 Equal Games
* 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 <equal/component/text_component.hpp>
#include <equal/component/transform_component.hpp>
#include <equal/core/game_object.hpp>
#include <equal/core/logger.hpp>
#include <equal/core/resource.hpp>
#include <equal/helper/error.hpp>
#include <equal/helper/string.hpp>
#ifdef EQ_SDL
#include <SDL2/SDL_ttf.h>
#endif
namespace eq {
TextComponent::TextComponent(Font *font) { m_font = font; }
TextComponent::TextComponent(const std::string &text, Font *font) {
m_text = str::utf8_to_wchar(text.c_str());
m_font = font;
}
TextComponent::~TextComponent() { delete m_font; }
uint32_t TextComponent::font_size() const { return m_font_size; }
void TextComponent::font_size(uint32_t font_size) {
if (m_font_size != font_size) {
m_font_size = font_size;
m_need_update = true;
}
}
Text::Overflow TextComponent::overflow_x() const { return m_overflow_x; }
void TextComponent::overflow_x(Text::Overflow overflow) {
if (m_overflow_x != overflow) {
m_overflow_x = overflow;
}
}
Text::Overflow TextComponent::overflow_y() const { return m_overflow_y; }
void TextComponent::overflow_y(Text::Overflow overflow) {
if (m_overflow_y != overflow) {
m_overflow_y = overflow;
}
}
const Position &TextComponent::offset() const { return m_offset; }
void TextComponent::offset(const Position &offset) {
if (m_offset != offset) {
m_offset = offset;
}
}
const Color &TextComponent::color() const { return m_color; }
void TextComponent::color(const Color &color) {
if (m_color != color) {
m_color = color;
}
}
const std::wstring &TextComponent::text() const { return m_text; }
void TextComponent::text(const std::wstring &text) {
if (m_text != text) {
m_text = text;
m_need_update = true;
}
}
void TextComponent::text(const std::string &text) { this->text(str::utf8_to_wchar(text.c_str())); }
bool TextComponent::masked() const { return m_masked; }
void TextComponent::masked(bool masked) {
if (m_masked != masked) {
m_masked = masked;
}
}
void TextComponent::alignment(const Text::Alignment &align) {
if (m_align != align) {
m_align = align;
}
}
void TextComponent::style(const Text::Style &style) {
if (m_style != style) {
m_style = style;
}
}
Font *TextComponent::font() const { return m_font; }
void TextComponent::font(Font *font) {
if (m_font != font) {
m_font = font;
m_need_update = true;
}
}
const BoundingBox &TextComponent::crop() const { return m_crop; }
void TextComponent::crop(const BoundingBox &crop) {
if (m_crop != crop) {
m_crop = crop;
m_need_update = true;
}
}
void TextComponent::fixed_update(const Timestep ×tep) {}
void TextComponent::update(const Timestep ×tep) {
if (m_need_update) {
m_need_update = false;
if (!m_text.empty()) {
m_target->visible(true);
TransformComponent *transform{m_target->get<TransformComponent>()};
#ifdef EQ_SDL
std::string text_value = str::wchar_to_utf8(m_text.c_str());
int w, h;
if (TTF_SizeText(static_cast<TTF_Font *>(m_font->data), text_value.c_str(), &w, &h) != 0) {
EQ_THROW("Can't draw game object: {}", TTF_GetError());
}
transform->size(Size{w, h});
#endif
} else {
m_target->visible(false);
}
}
}
} // namespace eq
| 25.136364
| 99
| 0.690778
|
equal-games
|
e64ca83cd4bd195736713ff544c43021e380e224
| 3,522
|
cpp
|
C++
|
src/qt/moc_UnivariateRunEditor.cpp
|
satra/murfi2
|
95d954a8735c107caae2ab4eec2926fafe420402
|
[
"Apache-2.0"
] | 7
|
2015-02-10T17:00:49.000Z
|
2021-07-27T22:09:43.000Z
|
src/qt/moc_UnivariateRunEditor.cpp
|
satra/murfi2
|
95d954a8735c107caae2ab4eec2926fafe420402
|
[
"Apache-2.0"
] | 11
|
2015-02-22T19:15:53.000Z
|
2021-08-04T17:26:18.000Z
|
src/qt/moc_UnivariateRunEditor.cpp
|
satra/murfi2
|
95d954a8735c107caae2ab4eec2926fafe420402
|
[
"Apache-2.0"
] | 8
|
2015-07-06T22:31:51.000Z
|
2019-04-22T21:22:07.000Z
|
/****************************************************************************
** Meta object code from reading C++ file 'UnivariateRunEditor.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.2.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "UnivariateRunEditor.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'UnivariateRunEditor.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.2.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_UnivariateRunEditor_t {
QByteArrayData data[4];
char stringdata[46];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
offsetof(qt_meta_stringdata_UnivariateRunEditor_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData) \
)
static const qt_meta_stringdata_UnivariateRunEditor_t qt_meta_stringdata_UnivariateRunEditor = {
{
QT_MOC_LITERAL(0, 0, 19),
QT_MOC_LITERAL(1, 20, 16),
QT_MOC_LITERAL(2, 37, 0),
QT_MOC_LITERAL(3, 38, 6)
},
"UnivariateRunEditor\0handleNextButton\0"
"\0finish\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_UnivariateRunEditor[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 24, 2, 0x0a,
3, 0, 25, 2, 0x0a,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void UnivariateRunEditor::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
UnivariateRunEditor *_t = static_cast<UnivariateRunEditor *>(_o);
switch (_id) {
case 0: _t->handleNextButton(); break;
case 1: _t->finish(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject UnivariateRunEditor::staticMetaObject = {
{ &QWizard::staticMetaObject, qt_meta_stringdata_UnivariateRunEditor.data,
qt_meta_data_UnivariateRunEditor, qt_static_metacall, 0, 0}
};
const QMetaObject *UnivariateRunEditor::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *UnivariateRunEditor::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_UnivariateRunEditor.stringdata))
return static_cast<void*>(const_cast< UnivariateRunEditor*>(this));
return QWizard::qt_metacast(_clname);
}
int UnivariateRunEditor::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWizard::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
| 30.626087
| 99
| 0.632595
|
satra
|
e64d514d029ead61d9be0d128d5db871d7ff7a1f
| 3,173
|
cpp
|
C++
|
tests/nnti/cpp-api/NntiOpVectorTest.cpp
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-01-25T21:21:07.000Z
|
2021-04-29T17:24:00.000Z
|
tests/nnti/cpp-api/NntiOpVectorTest.cpp
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 8
|
2018-10-09T14:35:30.000Z
|
2020-09-30T20:09:42.000Z
|
tests/nnti/cpp-api/NntiOpVectorTest.cpp
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-04-23T19:01:36.000Z
|
2021-05-11T07:44:55.000Z
|
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#include "nnti/nnti_pch.hpp"
#include <mpi.h>
#include "gtest/gtest.h"
#include "faodel-common/Common.hh"
#include "nnti/nntiConfig.h"
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <iostream>
#include <thread>
#include <vector>
#include "nnti/nnti_transport.hpp"
#include "nnti/nnti_op.hpp"
#include "nnti/nnti_wid.hpp"
#include "test_utils.hpp"
using namespace std;
using namespace faodel;
string default_config_string = R"EOF(
# default to using mpi, but allow override in config file pointed to by CONFIG
nnti.transport.name mpi
)EOF";
class test_op
: public nnti::core::nnti_op {
private:
test_op(void);
public:
test_op(
nnti::transports::transport *transport,
nnti::datatype::nnti_work_id *wid)
: nnti_op(
wid)
{
return;
}
};
class NntiOpVectorTest : public testing::Test {
protected:
Configuration config;
nnti::transports::transport *t=nullptr;
void SetUp () override {
config = Configuration(default_config_string);
config.AppendFromReferences();
test_setup(0,
NULL,
config,
"OpVectorTest",
t);
}
void TearDown () override {
NNTI_result_t nnti_rc = NNTI_OK;
bool init;
init = t->initialized();
EXPECT_TRUE(init);
if (init) {
nnti_rc = t->stop();
EXPECT_EQ(nnti_rc, NNTI_OK);
}
}
};
const int num_op=1024;
TEST_F(NntiOpVectorTest, start1) {
nnti::datatype::nnti_work_id wid(t);
std::vector<test_op*> mirror;
nnti::core::nnti_op_vector op_vector(1024);
mirror.reserve(1024);
for (int i = 0; i < num_op; ++i) {
test_op *op = new test_op(t, &wid);
op_vector.add(op);
mirror[i] = op;
if (i % 10 == 0) {
uint32_t victim_index = i/2;
nnti::core::nnti_op *victim_op = op_vector.remove(victim_index);
EXPECT_EQ(victim_op, mirror[victim_index]);
op = new test_op(t, &wid);
op_vector.add(op);
mirror[victim_index] = op;
EXPECT_EQ(op_vector.at(victim_index), mirror[victim_index]);
delete victim_op;
}
}
for (uint32_t i = 0; i < mirror.size(); ++i) {
EXPECT_EQ(op_vector.at(i), mirror[i]);
op_vector.remove(i);
delete mirror[i];
}
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
int mpi_rank,mpi_size;
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
EXPECT_EQ(1, mpi_size);
assert(1==mpi_size);
int rc = RUN_ALL_TESTS();
cout <<"Tester completed all tests.\n";
MPI_Barrier(MPI_COMM_WORLD);
bootstrap::Finish();
MPI_Finalize();
return (rc);
}
| 22.034722
| 78
| 0.607942
|
faodel
|
e6514457bc2b8dd014f85c0b00fe47f067f7155e
| 283
|
cpp
|
C++
|
tests/test3.cpp
|
chrisroman/llvm-pass-skeleton
|
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
|
[
"MIT"
] | 1
|
2020-10-26T02:45:22.000Z
|
2020-10-26T02:45:22.000Z
|
tests/test3.cpp
|
chrisroman/llvm-pass-skeleton
|
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
|
[
"MIT"
] | null | null | null |
tests/test3.cpp
|
chrisroman/llvm-pass-skeleton
|
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
|
[
"MIT"
] | null | null | null |
#include <stdlib.h> /* exit, EXIT_FAILURE */
#include "track_nullptr.h"
void deref_null(int argc) {
int *p = nullptr;
if (argc == 1) {
p = &argc;
}
*p = 42;
}
int main(int argc, char** argv) {
//escape(&nullp);
deref_null(argc);
return 0;
}
| 16.647059
| 48
| 0.537102
|
chrisroman
|
e654beaee6fadb0fdaad20ec16f713cbb088f20b
| 1,275
|
hpp
|
C++
|
android-31/android/icu/text/DateIntervalInfo.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-28/android/icu/text/DateIntervalInfo.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-30/android/icu/text/DateIntervalInfo.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#pragma once
#include "../../../JObject.hpp"
namespace android::icu::text
{
class DateIntervalInfo_PatternInfo;
}
namespace android::icu::util
{
class ULocale;
}
class JObject;
class JString;
namespace java::util
{
class Locale;
}
namespace android::icu::text
{
class DateIntervalInfo : public JObject
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit DateIntervalInfo(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
DateIntervalInfo(QJniObject obj);
// Constructors
DateIntervalInfo(android::icu::util::ULocale arg0);
DateIntervalInfo(java::util::Locale arg0);
// Methods
JObject clone() const;
android::icu::text::DateIntervalInfo cloneAsThawed() const;
jboolean equals(JObject arg0) const;
android::icu::text::DateIntervalInfo freeze() const;
jboolean getDefaultOrder() const;
JString getFallbackIntervalPattern() const;
android::icu::text::DateIntervalInfo_PatternInfo getIntervalPattern(JString arg0, jint arg1) const;
jint hashCode() const;
jboolean isFrozen() const;
void setFallbackIntervalPattern(JString arg0) const;
void setIntervalPattern(JString arg0, jint arg1, JString arg2) const;
};
} // namespace android::icu::text
| 25.5
| 157
| 0.737255
|
YJBeetle
|
e655ee06e0db284b536e2a0f8e9c737708efaf2e
| 850
|
cpp
|
C++
|
src/atom.cpp
|
chiang-yuan/csh4lmp
|
8a8dff5d2b65ce463e4d58dc52e35a6114b7e597
|
[
"MIT"
] | 9
|
2019-03-22T03:45:24.000Z
|
2021-02-18T04:19:12.000Z
|
src/atom.cpp
|
Chiang-Yuan/csh4lmp
|
8a8dff5d2b65ce463e4d58dc52e35a6114b7e597
|
[
"MIT"
] | null | null | null |
src/atom.cpp
|
Chiang-Yuan/csh4lmp
|
8a8dff5d2b65ce463e4d58dc52e35a6114b7e597
|
[
"MIT"
] | 1
|
2022-03-31T11:57:07.000Z
|
2022-03-31T11:57:07.000Z
|
#include "atom.h"
Atom::Atom()
{
delete_flag = false;
bondNum = 0;
bondID = std::vector<bigint>(MAX_BONDS_PER_ATOM);
bonds = std::vector<Bond*>(MAX_BONDS_PER_ATOM);
angleNum = 0;
}
Atom::~Atom()
{
}
bool operator==(const Atom& lhs, const Atom& rhs) {
return (lhs.id == rhs.id);
}
bool operator!=(const Atom & lhs, const Atom & rhs)
{
return !(lhs == rhs);
}
Atom & operator&=(Atom & lhs, const Atom & rhs)
{
lhs.id = rhs.id;
lhs.molecule = rhs.molecule;
lhs.type = rhs.type;
lhs.q = rhs.q;
lhs.x[0] = rhs.x[0]; lhs.x[1] = rhs.x[1]; lhs.x[2] = rhs.x[2];
lhs.n[0] = rhs.n[0]; lhs.n[1] = rhs.n[1]; lhs.n[2] = rhs.n[2];
strcpy(lhs.name, rhs.name);
lhs.delete_flag = rhs.delete_flag;
lhs.bondNum = rhs.bondNum;
lhs.bondID = rhs.bondID;
lhs.bonds = rhs.bonds;
lhs.angleNum = rhs.angleNum;
lhs.angles = rhs.angles;
return lhs;
}
| 19.318182
| 63
| 0.625882
|
chiang-yuan
|
e65cb69470313025359f0dd0053f56a558f24d34
| 6,099
|
cpp
|
C++
|
Engine/Core/Sources/Threading/ThreadPool.cpp
|
makdenis/YetAnotherProject
|
e43cc3ca2d4a13984f97f0949f88ab17fa6905d3
|
[
"MIT"
] | 1
|
2018-05-02T10:40:26.000Z
|
2018-05-02T10:40:26.000Z
|
Engine/Core/Sources/Threading/ThreadPool.cpp
|
makdenis/YetAnotherProject
|
e43cc3ca2d4a13984f97f0949f88ab17fa6905d3
|
[
"MIT"
] | 9
|
2018-03-26T10:22:07.000Z
|
2018-05-22T20:43:14.000Z
|
Engine/Core/Sources/Threading/ThreadPool.cpp
|
makdenis/YetAnotherProject
|
e43cc3ca2d4a13984f97f0949f88ab17fa6905d3
|
[
"MIT"
] | 6
|
2018-04-15T16:03:32.000Z
|
2018-05-21T22:02:49.000Z
|
#include "ThreadPool.hpp"
#include <assert.h>
#define LOCK(MUTEX) std::unique_lock<std::mutex> lock
/********************************************************************
* TaskBacket
********************************************************************/
TaskBacket::TaskBacket()
{
bComplitted = true;
}
TaskBacket::~TaskBacket()
{
}
bool TaskBacket::AddTask(IRunable* newTask)
{
if (!newTask) return false;
bComplitted = false;
{ LOCK(mutex_storedTasks);
storedTasks.emplace_back(newTask);
}
return true;
}
bool TaskBacket::MarkAsDone(IRunable* doneTask)
{
assert(doneTask);
{ LOCK(mutex_processingTasks);
processingTasks.erase(doneTask);
if (processingTasks.size()) return false;
if (mutex_storedTasks.try_lock())
{
bool bDone = !storedTasks.size();
mutex_storedTasks.unlock();
bComplitted = bDone;
return bDone;
}
else return false;
}
}
bool TaskBacket::IsCompleted()
{
return bComplitted;
}
IRunable* TaskBacket::GetTask()
{
IRunable* task;
{ mutex_storedTasks.lock();
if (!storedTasks.size())
{
mutex_storedTasks.unlock();
return nullptr;
}
task = storedTasks.front();
storedTasks.pop_front();
{ LOCK(mutex_processingTasks);
processingTasks.emplace(task);
mutex_storedTasks.unlock();
}
}
return task;
}
void TaskBacket::Wait()
{
while (!bComplitted)
{
std::this_thread::sleep_for(std::chrono::microseconds(300));
}
}
/********************************************************************
* ThreadPool
********************************************************************/
std::deque<IRunable*> ThreadPool::tasks = std::deque<IRunable*>();
std::deque<IRunable*> ThreadPool::tasks_exclusive = std::deque<IRunable*>();
std::deque<TaskBacket*> ThreadPool::backets = std::deque<TaskBacket*>();
std::unordered_set<Thread*> ThreadPool::threads = std::unordered_set<Thread*>();
std::unordered_set<Thread*> ThreadPool::threads_exclusive = std::unordered_set<Thread*>();
std::unordered_map<Thread*, UNIQUE(Thread)> ThreadPool::allThreads;
std::atomic<size_t> ThreadPool::maxThreadCount = 1;
std::atomic<bool> ThreadPool::bProcessBacket = false;
bool ThreadPool::AddTask(IRunable* task, bool bExlusiveThread)
{
if (!task) return false;
if (!bExlusiveThread)
{
{ LOCK(mutex_tasks);
tasks.emplace_back(task);
}
{ LOCK(mutex_threads);
if (NewThreadRequired(bExlusiveThread))
{
CreateThread(bExlusiveThread);
}
}
}
else
{
{ LOCK(mutex_tasks_exclusive);
tasks_exclusive.emplace_back(task);
}
{ LOCK(mutex_threads_exclusive);
if (NewThreadRequired(bExlusiveThread))
{
CreateThread(bExlusiveThread);
}
}
}
return true;
}
bool ThreadPool::AddTaskBacket(TaskBacket& backet)
{
if (backet.IsCompleted()) return true;
{ LOCK(mutex_backets);
backets.emplace_back(&backet);
}
AddTask(new BacketRunable(), false);
return true;
}
ThreadTask ThreadPool::GetRunTask(Thread* thread, IRunable* complittedTask)
{
if (!thread) return ThreadTask();
bool bExclusive = false;
ThreadTask result;
{ LOCK(mutex_threads_exclusive);
if (threads_exclusive.count(thread))
{
result = GetRunTask_exclusive(thread, complittedTask);
bExclusive = true;
}
}
if (!bExclusive)
{
if (bProcessBacket)
{
result = GetRunTask_backet(thread, complittedTask);
}
else
{
result = GetRunTask_common(thread, complittedTask);
}
}
if (complittedTask)
{
delete complittedTask;
}
if (result == ThreadTask::ShouldDie)
{
DeleteThread(bExclusive, thread);
}
return result;
}
ThreadTask ThreadPool::GetRunTask_common(Thread* thread, IRunable* complittedTask)
{
ThreadTask result = ThreadTask::NextLoop;
{ LOCK(mutex_tasks);
if (ShouldDie(thread))
{
result = ThreadTask::ShouldDie;
}
else if (tasks.size())
{ // get new task
result.task = tasks.front();
result.bDie = false;
tasks.pop_front();
// start process a backet
if (dynamic_cast<BacketRunable*>(result.task))
{
delete result.task;
bProcessBacket = true;
result = ThreadTask::NextLoop;
}
}
else
{
result = ThreadTask::NextLoop;
}
}
return result;
}
ThreadTask ThreadPool::GetRunTask_backet(Thread* thread, IRunable* complittedTask)
{
ThreadTask result = ThreadTask::NextLoop;
{ LOCK(mutex_backets);
bool bDone = false;
if (complittedTask)
{
bDone = backets.front()->MarkAsDone(complittedTask);
}
else
{
bDone = backets.front()->IsCompleted();
}
if (!bDone) // try to get a new task
{
IRunable* newTask = backets.front()->GetTask();
if (newTask)
{
result.task = newTask;
result.bDie = false;
}
else
{
result = ThreadTask::NextLoop;
}
}
if (bDone) // the lates task is done
{
bProcessBacket = false;
backets.pop_front();
result = ShouldDie(thread)
? ThreadTask::ShouldDie
: ThreadTask::NextLoop;
}
}
return result;
}
ThreadTask ThreadPool::GetRunTask_exclusive(Thread* thread, IRunable* complittedTask)
{
ThreadTask result = ThreadTask::NextLoop;
{ LOCK(mutex_tasks_exclusive);
if (tasks_exclusive.size())
{
result.task = tasks_exclusive.front();
result.bDie = false;
tasks_exclusive.pop_front();
return result;
}
}
{ LOCK(mutex_threads);
threads_exclusive.erase(thread);
threads.emplace(thread);
return result;
}
}
bool ThreadPool::ShouldDie(Thread* thread)
{
return threads.size() > maxThreadCount;
}
bool ThreadPool::NewThreadRequired(bool bExlusive)
{
if (!bExlusive)
{
return threads.size() < maxThreadCount;
}
else
{
return true;
}
}
void ThreadPool::CreateThread(bool bExlusive)
{
UNIQUE(Thread) newThread = Thread::Get();
Thread* thread_ptr = newThread.get();
allThreads[thread_ptr] = std::move(newThread);
if (!bExlusive)
{
threads.emplace(thread_ptr);
}
else
{
threads_exclusive.emplace(thread_ptr);
}
thread_ptr->Run();
}
void ThreadPool::DeleteThread(bool bExlusive, Thread* thread)
{
if (!bExlusive)
{
threads.erase(thread);
}
else
{
threads_exclusive.erase(thread);
}
allThreads.erase(thread);
}
| 17.99115
| 90
| 0.654697
|
makdenis
|
e65ce6a63ac15bef27e6c2c1e18df66fb0a96107
| 1,381
|
cpp
|
C++
|
Codeforces/1/B.cpp
|
Mindjolt2406/Competitive-Programming
|
d000d98bf7005ee4fb809bcea2f110e4c4793b80
|
[
"MIT"
] | 2
|
2018-12-11T14:37:24.000Z
|
2022-01-23T18:11:54.000Z
|
Codeforces/1/B.cpp
|
Mindjolt2406/Competitive-Programming
|
d000d98bf7005ee4fb809bcea2f110e4c4793b80
|
[
"MIT"
] | null | null | null |
Codeforces/1/B.cpp
|
Mindjolt2406/Competitive-Programming
|
d000d98bf7005ee4fb809bcea2f110e4c4793b80
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
#define mp make_pair
#define pu push_back
#define mt make_tuple
#define INF 1000000001
using namespace std;
int check(string s)
{
if(s[0]!='R') return 0;
int boo = 0;
for(int i=0;i<s.size();i++)
{
if(65<=s[i] && s[i]<=90 && boo == 1) return 1;
else if(s[i]-'0'<11) boo = 1;
}
return 0;
}
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
if(check(s))
{
// cout<<"here"<<endl;
int i = 1;
string k;
for(i=1;i<s.size() && s[i]!='C';i++)
{
k+=s[i];
}
// cout<<k<<endl;
if(s[i]=='C')i++;
string k1;
for(;i<s.size();i++)
{
k1+=s[i];
}
stringstream geek(k1);
long long int a = 0;
geek >> a;
int prod = 26;
string k2;
while(a)
{
int c = a%prod;
cout<<"c: "<<c<<endl;
k2 = (char)(c + 'A') + k2;
a/=prod;
}
cout<<k2<<k<<endl;
}
else
{
string k,k1;
for(int i=0;i<s.size();i++)
{
if(s[i]<65) k1+=s[i];
else k+=s[i];
}
long long int prod = 1;
long long int count = 0;
for(int i=k.size()-1;i>=0;i--)
{
count+=prod*(s[i]-'A'+1);
prod*=26;
// cout<<"count: "<<count<<endl;
}
cout<<"R"<<k1<<"C"<<count<<endl;
}
}
return 0;
}
| 17.481013
| 50
| 0.415641
|
Mindjolt2406
|
e65ddf9e93182443c1db22f317c886713ade7900
| 4,028
|
hpp
|
C++
|
include/jitana/analysis/call_graph.hpp
|
Xbeas/jitana
|
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
|
[
"0BSD"
] | 31
|
2017-04-21T03:25:46.000Z
|
2022-02-20T20:59:23.000Z
|
include/jitana/analysis/call_graph.hpp
|
Xbeas/jitana
|
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
|
[
"0BSD"
] | 3
|
2020-12-21T09:02:06.000Z
|
2021-03-16T10:37:38.000Z
|
include/jitana/analysis/call_graph.hpp
|
Xbeas/jitana
|
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
|
[
"0BSD"
] | 9
|
2017-06-06T19:30:43.000Z
|
2021-05-19T19:50:03.000Z
|
/*
* Copyright (c) 2015, 2016, Yutaka Tsutano
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef JITANA_CALL_GRAPH_HPP
#define JITANA_CALL_GRAPH_HPP
#include "jitana/jitana.hpp"
#include <algorithm>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/range/iterator_range.hpp>
namespace jitana {
struct method_call_edge_property {
bool virtual_call;
insn_vertex_descriptor caller_insn_vertex;
};
inline void print_graphviz_attr(std::ostream& os,
const method_call_edge_property& prop)
{
os << "color=red, label=";
os << (prop.virtual_call ? "virtual" : "direct");
os << ", taillabel=" << prop.caller_insn_vertex;
}
inline void add_call_graph_edges(virtual_machine& vm,
const method_vertex_descriptor& v)
{
using boost::type_erasure::any_cast;
auto& mg = vm.methods();
// Abort if we already have an outgoing call graph edge to avoid
// creating duplicates. For performacnce, we should have flags
// indicating if we have already computed the call graph for this edge.
for (const auto& me : boost::make_iterator_range(out_edges(v, mg))) {
if (any_cast<method_call_edge_property*>(&mg[me]) != nullptr) {
return;
}
}
auto ig = mg[v].insns;
// Iterate over the instruction graph vertices.
for (const auto& iv : boost::make_iterator_range(vertices(ig))) {
// Get the vertex property.
const auto& prop = ig[iv];
// Ignore if it is a non-DEX instruction.
if (is_pseudo(prop.insn)) {
continue;
}
// Determine the type of the instruction.
method_call_edge_property eprop;
const auto& insn_info = info(op(prop.insn));
if (insn_info.can_virtually_invoke()) {
eprop.virtual_call = true;
}
else if (insn_info.can_directly_invoke()) {
eprop.virtual_call = false;
}
else {
// Not an invoke instruction.
continue;
}
eprop.caller_insn_vertex = iv;
// Get the target method handle.
dex_method_hdl method_hdl;
if (insn_info.odex_only()) {
// Optimized: uses vtable. Unless we know the type of the target
// method's class, we cannot tell the method handle.
// auto off =
// any_cast<code::i_invoke_quick>(prop.insn).const_val;
continue;
}
else {
method_hdl = *const_val<dex_method_hdl>(prop.insn);
}
// Add an edge to the methood graph.
auto target_v = vm.find_method(method_hdl, false);
if (target_v) {
add_edge(v, *target_v, eprop, mg);
}
}
}
inline void add_call_graph_edges(virtual_machine& vm)
{
auto& mg = vm.methods();
std::for_each(vertices(mg).first, vertices(mg).second,
[&](const method_vertex_descriptor& v) {
add_call_graph_edges(vm, v);
});
}
}
#endif
| 34.724138
| 80
| 0.588878
|
Xbeas
|
e661ff980e7be9bfb2ab4ac0cca88b59be10469d
| 1,100
|
cpp
|
C++
|
Libraries/RobsJuceModules/romos/Framework/romos_ProcessingStatus.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 34
|
2017-04-19T18:26:02.000Z
|
2022-02-15T17:47:26.000Z
|
Libraries/RobsJuceModules/romos/Framework/romos_ProcessingStatus.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 307
|
2017-05-04T21:45:01.000Z
|
2022-02-03T00:59:01.000Z
|
Libraries/RobsJuceModules/romos/Framework/romos_ProcessingStatus.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 4
|
2017-09-05T17:04:31.000Z
|
2021-12-15T21:24:28.000Z
|
//#include "romos_ProcessingStatus.h"
//using namespace romos;
ProcessingStatus processingStatus; // definition of the global object
//-----------------------------------------------------------------------------------------------------------------------------------------
// construction/destruction:
ProcessingStatus::ProcessingStatus()
{
setSystemSampleRate(44100.0);
setTempo(120.0);
setBufferSize(66); // 66 yields best performance with IdentityChain performance test
}
ProcessingStatus::~ProcessingStatus()
{
}
//-----------------------------------------------------------------------------------------------------------------------------------------
// setup:
void ProcessingStatus::setSystemSampleRate(double newSampleRate)
{
systemSampleRate = newSampleRate;
systemSamplePeriod = 1.0 / systemSampleRate;
freqToOmegaFactor = (2.0*PI) / systemSampleRate;
}
void ProcessingStatus::setTempo(double newTempo)
{
tempo = newTempo;
}
void ProcessingStatus::setBufferSize(int newBufferSize)
{
if( newBufferSize <= maxBufferSize )
bufferSize = newBufferSize;
}
| 26.190476
| 139
| 0.565455
|
RobinSchmidt
|
e66291ea7314d2fbde3ac9368ba51effc802e746
| 636
|
cpp
|
C++
|
String/10_permutations.cpp
|
ritikrajdev/450DSA
|
a9efa8c8be781fd7b101407ac807a83b8a0929f4
|
[
"MIT"
] | null | null | null |
String/10_permutations.cpp
|
ritikrajdev/450DSA
|
a9efa8c8be781fd7b101407ac807a83b8a0929f4
|
[
"MIT"
] | null | null | null |
String/10_permutations.cpp
|
ritikrajdev/450DSA
|
a9efa8c8be781fd7b101407ac807a83b8a0929f4
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
class Solution {
void helper(string &S, int l, int r, vector<string> &vec) {
if (l == r) {
vec.push_back(S);
return;
}
for (int i = l; i <= r; i++) {
swap(S[i], S[l]);
helper(S, l + 1, r, vec);
swap(S[i], S[l]);
}
}
public:
vector<string> find_permutation(string S) {
std::sort(S.begin(), S.end());
vector<string> vec;
helper(S, 0, S.size() - 1, vec);
std::sort(vec.begin(), vec.end());
return vec;
}
};
| 21.2
| 63
| 0.463836
|
ritikrajdev
|
e662bb84a95721dbc93162a81e9bd8ec016474b3
| 1,627
|
hpp
|
C++
|
src/message_service.hpp
|
madmongo1/blog-october-2020
|
95968a7c6bc9ed8476f72d0ec107544b5ec26498
|
[
"BSL-1.0"
] | 1
|
2021-02-12T00:18:55.000Z
|
2021-02-12T00:18:55.000Z
|
src/message_service.hpp
|
madmongo1/blog-october-2020
|
95968a7c6bc9ed8476f72d0ec107544b5ec26498
|
[
"BSL-1.0"
] | 1
|
2020-12-21T09:53:31.000Z
|
2020-12-21T09:53:31.000Z
|
src/message_service.hpp
|
madmongo1/blog-october-2020
|
95968a7c6bc9ed8476f72d0ec107544b5ec26498
|
[
"BSL-1.0"
] | null | null | null |
//
// Created by rhodges on 09/11/2020.
//
#pragma once
#include "async_condition_variable.hpp"
#include "basic_distributor.hpp"
#include "config.hpp"
#include <memory>
struct message_service_impl
{
using executor_type = net::strand<net::io_context::executor_type>;
message_service_impl(net::io_context::executor_type const &exec);
net::awaitable<void>
run();
auto
connect(net::any_io_executor client_exec)
-> net::awaitable<basic_connection<std::string>>;
void
stop();
auto
get_executor() const -> executor_type const &
{
return exec_;
}
private:
void
listen_for_stop(std::function<void()> slot);
executor_type exec_;
error_code stop_reason_;
std::vector<std::function<void()>> stop_signals_;
async_condition_variable stop_condition_{get_executor()};
basic_distributor_impl<std::string> message_dist_;
};
struct message_service
{
using executor_type = net::io_context::executor_type;
message_service(executor_type const &exec);
message_service(message_service &&) noexcept = default;
message_service &
operator=(message_service &&) noexcept = default;
message_service(message_service const &) = delete;
message_service &
operator=(message_service const &)
= delete;
void
reset() noexcept;
~message_service();
auto
connect() -> net::awaitable<basic_connection<std::string>>;
auto
get_executor() const -> executor_type const &
{
return exec_;
}
private:
executor_type exec_;
std::shared_ptr<message_service_impl> impl_;
};
| 20.3375
| 70
| 0.684696
|
madmongo1
|
e6658c75e8f1c293df47c437c86993b0f061e079
| 1,600
|
cpp
|
C++
|
datasets/github_cpp_10/7/38.cpp
|
yijunyu/demo-fast
|
11c0c84081a3181494b9c469bda42a313c457ad2
|
[
"BSD-2-Clause"
] | 1
|
2019-05-03T19:27:45.000Z
|
2019-05-03T19:27:45.000Z
|
datasets/github_cpp_10/7/38.cpp
|
yijunyu/demo-vscode-fast
|
11c0c84081a3181494b9c469bda42a313c457ad2
|
[
"BSD-2-Clause"
] | null | null | null |
datasets/github_cpp_10/7/38.cpp
|
yijunyu/demo-vscode-fast
|
11c0c84081a3181494b9c469bda42a313c457ad2
|
[
"BSD-2-Clause"
] | null | null | null |
#include <iostream>
#include <string>
using namespace std;
template<class ItemType>
void merge(ItemType theArray[], int first, int mid, int last, ItemType tempArray[])
{
int first1 = first;
int last1 = mid;
int first2 = mid + 1;
int last2 = last;
int index = first1;
while ((first1 <= last1) && (first2 <= last2))
{
if (theArray[first1] <= theArray[first2])
{
tempArray[index] = theArray[first1];
first1++;
}
else
{
tempArray[index] = theArray[first2];
first2++;
}
index++;
}
while (first1 <= last1)
{
tempArray[index] = theArray[first1];
first1++;
index++;
}
while (first2 <= last2)
{
tempArray[index] = theArray[first2];
first2++;
index++;
}
for (index = first; index <= last; index++)
theArray[index] = tempArray[index];
}
template<class ItemType>
void mergeSort(ItemType theArray[], int first, int last, ItemType tempArray[])
{
if (first < last)
{
int mid = (first + last) / 2;
mergeSort(theArray, first, mid, tempArray);
mergeSort(theArray, mid + 1, last, tempArray);
merge(theArray, first, mid, last, tempArray);
}
}
template<typename ItemType>
void mergeSort(ItemType theArray[], int n)
{
ItemType* tempArray = new ItemType[n];
mergeSort(theArray, 0, n-1, tempArray);
delete [] tempArray;
}
| 17.777778
| 83
| 0.52
|
yijunyu
|
e667671ae23c8ce12de0895757d128bd9b81b96c
| 2,761
|
cpp
|
C++
|
AAMPJSController.cpp
|
rdkcmf/rdk-injectedbundle
|
8eded43baa7ae6d27670b8485c8de145f54b39ef
|
[
"Apache-2.0"
] | null | null | null |
AAMPJSController.cpp
|
rdkcmf/rdk-injectedbundle
|
8eded43baa7ae6d27670b8485c8de145f54b39ef
|
[
"Apache-2.0"
] | null | null | null |
AAMPJSController.cpp
|
rdkcmf/rdk-injectedbundle
|
8eded43baa7ae6d27670b8485c8de145f54b39ef
|
[
"Apache-2.0"
] | 2
|
2017-10-04T04:44:13.000Z
|
2018-08-16T20:45:04.000Z
|
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2017 RDK Management
*
* 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 <WebKit/WKBundlePage.h>
#include <WebKit/WKBundleFrame.h>
#include <WebKit/WKString.h>
#include <WebKit/WKNumber.h>
#include <WebKit/WKRetainPtr.h>
#include <WebKit/WKBundlePagePrivate.h>
#include "AAMPJSController.h"
#include "logger.h"
#include "utils.h"
#include <fstream>
#include <string>
#include <stdlib.h>
#define AAMP_UNUSED(x) (void) x
extern "C"
{
void aamp_LoadJSController(JSGlobalContextRef context);
void aamp_UnloadJSController(JSGlobalContextRef context);
}
namespace AAMPJSController
{
bool enableAAMP = false;
void initialize()
{
RDKLOG_TRACE("AAMPJSController::initialize()");
enableAAMP = false; //Set default value
//Check if AAMP is enabled in configuration
const char *status = getenv("ENABLE_AAMP");
if (status != NULL && strcasecmp(status, "TRUE") == 0)
{
RDKLOG_INFO("AAMPJSController::initialize() - AAMP enabled!");
enableAAMP = true;
}
}
void didCommitLoad(WKBundlePageRef page, WKBundleFrameRef frame)
{
RDKLOG_TRACE("AAMPJSController::didCommitLoad()");
if (WKBundlePageGetMainFrame(page) != frame)
{
return;
}
if (enableAAMP)
{
JSGlobalContextRef context = WKBundleFrameGetJavaScriptContext(frame);
aamp_LoadJSController(context);
}
}
void didStartProvisionalLoadForFrame(WKBundlePageRef page, WKBundleFrameRef frame)
{
RDKLOG_TRACE("AAMPJSController::didStartProvisionalLoadForFrame()");
WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(page);
if (mainFrame == frame && enableAAMP )
{
JSGlobalContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
RDKLOG_INFO("AAMPJSController::didStartProvisionalLoadForFrame(): Unloading JSController");
aamp_UnloadJSController(context);
}
}
bool didReceiveMessageToPage(WKStringRef messageName, WKTypeRef messageBody)
{
AAMP_UNUSED(messageName);
AAMP_UNUSED(messageBody);
RDKLOG_TRACE("AAMPJSController::didReceiveMessageToPage()");
return false;
}
} // namespace
| 27.888889
| 99
| 0.732343
|
rdkcmf
|
e667ecb9ae71a5f34cf7f886ad808bd62d96ccbb
| 5,179
|
hpp
|
C++
|
include/vecl/broadcast.hpp
|
ethereal-sheep/vecl
|
519e8e90a1cd2c424f0a666e24da2d2ad3ffdcaf
|
[
"MIT"
] | 1
|
2021-09-15T13:13:16.000Z
|
2021-09-15T13:13:16.000Z
|
include/vecl/broadcast.hpp
|
ethereal-sheep/vecl
|
519e8e90a1cd2c424f0a666e24da2d2ad3ffdcaf
|
[
"MIT"
] | 1
|
2022-01-03T09:52:35.000Z
|
2022-01-03T09:52:35.000Z
|
include/vecl/broadcast.hpp
|
ethereal-sheep/vecl
|
519e8e90a1cd2c424f0a666e24da2d2ad3ffdcaf
|
[
"MIT"
] | null | null | null |
#ifndef VECL_BROADCAST_H
#define VECL_BROADCAST_H
#include "config/config.h"
#include <memory>
#include <functional>
#include <vector>
#include <memory_resource>
namespace vecl
{
/**
* @brief A Broadcast is a smart event-handler that models a
* broadcast design pattern.
*
* The container allows functions to listen to the broadcast.
* The broadcast will invoke all functions that are listening
* to it when triggered.
*
* A token is given to the listener when they listen to the broadcast.
* It handles the lifetime of the listener within the container.
* When the token goes out of scope, the listener dies and
* will be automatically removed from the container.
*
* @tparam Callable Callable object type
*/
template<typename Callable>
class broadcast
{
public:
/** @brief type traits for container */
using callback = Callable;
using token = std::shared_ptr<callback>;
using allocator_type = std::pmr::polymorphic_allocator<std::byte>;
/**
* @note MEMBER FUNCTIONS
*/
/**
* @brief Default Constructor.
*
* @param mr Pointer to a pmr resource. Default gets the default
* global pmr resource via get_default_resource().
*/
explicit broadcast(
allocator_type mr = std::pmr::get_default_resource()
) : _listeners(mr)
{
}
/**
* @brief Default Copy Constructor. Uses same memory resource as
* other.
*/
broadcast(const broadcast& other) = default;
/**
* @brief Memory-Extended Copy Constructor. Uses provided
* memory_resource to allocate copied arrays from other.
*
* @param other Const-reference to other.
* @param mr Pointer to a pmr resource.
*/
broadcast(
const broadcast& other,
allocator_type mr
) : _listeners(other._listeners, mr)
{
}
/**
* @brief Default Move Constructor. Constructs container with
* the contents of other using move-semantics. After the move, other
* is guaranteed to be empty.
*/
broadcast(broadcast&& other) = default;
/**
* @brief Memory-Extended Move Constructor. If memory_resource used
* by other is not the same as memory_resource provided, the
* construction resolves to a Memory-Extended copy construction. In
* which case, other is not guranteed to be empty after the move.
*
* @param other Universal-reference to other.
* @param mr Pointer to a pmr resource.
*/
broadcast(
broadcast&& other,
allocator_type mr
) : _listeners(std::move(other._listeners), mr)
{
}
/**
* @brief Copy-Assignment Operator. Uses same memory resource as
* other. If the memory_resource of this is equal to that of other,
* the memory owned by this may be reused when possible.
*
* @param other Const-reference to other.
*/
broadcast& operator=(const broadcast& other) = default;
/**
* @brief Move-Assignment Operator. Assigns contents of other using
* move-semantics. After the move, other is guaranteed to be empty.
*
* @param other Universal-reference to other.
*/
broadcast& operator=(broadcast&& other) = default;
/**
* @return Copy of allocator_type object used by the container.
*/
VECL_NODISCARD allocator_type get_allocator() const VECL_NOEXCEPT
{
return _listeners.get_allocator();
}
/**
* @note CAPACITY
*/
/**
* @return Number of listeners.
*
* @warning Size is only an approximation as there may be dead listeners
* who have not been cleaned up.
*/
VECL_NODISCARD auto size() const VECL_NOEXCEPT
{
return _listeners.size();
}
/**
* @brief Checks if the container is empty.
*
* @warning Only an approximation as there may be dead listeners
* who have not been cleaned up.
*/
VECL_NODISCARD bool empty() const VECL_NOEXCEPT
{
return _listeners.empty();
}
/**
* @note MODIFIERS
*/
/**
* @brief Registers a function to listen to the broadcast.
*
* @param callable Callable object to be registered
*
* @return Listener token(shared_ptr). When the token goes out
* of scope, the listener is revoked.
*/
VECL_NODISCARD token listen(Callable&& callable)
{
token handle = std::make_shared<callback>(callable);
_listeners.push_back(handle);
return handle;
}
/**
* @brief Triggers a broadcast to all listeners.
*
* @tparam Args Variadic argument list
*
* @param args Variadic arguments to be passed to listeners.
*/
template<typename... Args>
void trigger(Args&&... args)
{
for (auto weak : _listeners)
{
if (auto callable = weak.lock())
(*callable)(std::forward<Args>(args)...);
}
_listeners.erase(
std::remove_if(
_listeners.begin(), _listeners.end(),
[](auto weak) { return weak.expired(); }
), _listeners.end());
}
/**
* @brief Swaps the contents of two broadcasts. The swap operation
* of two broadcasts with different memory_resource is undefined.
*/
friend void swap(broadcast& lhs, broadcast& rhs) VECL_NOEXCEPT
{
std::swap(lhs._subs, rhs._subs);
}
private:
using weak = std::weak_ptr<callback>;
using listeners = std::pmr::vector<weak>;
listeners _listeners;
};
}
#endif
| 24.088372
| 74
| 0.674068
|
ethereal-sheep
|
e66ccf5db157f828ccdc7aea66caca4da8442d63
| 320
|
hpp
|
C++
|
include/base64-cpp/detail/decode-common.hpp
|
contour-terminal/base64-cpp
|
885789cd7ec427cf63eef867f6c273eaa92b5d88
|
[
"Apache-2.0"
] | 2
|
2021-07-11T21:03:13.000Z
|
2021-07-23T23:47:29.000Z
|
include/base64-cpp/detail/decode-common.hpp
|
contour-terminal/base64-cpp
|
885789cd7ec427cf63eef867f6c273eaa92b5d88
|
[
"Apache-2.0"
] | 1
|
2021-08-03T05:51:53.000Z
|
2021-08-16T14:32:49.000Z
|
include/base64-cpp/detail/decode-common.hpp
|
contour-terminal/base64-cpp
|
885789cd7ec427cf63eef867f6c273eaa92b5d88
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <cstdint>
#include <cstdlib>
#include <string_view>
namespace base64::detail::decoder
{
auto static const inline alphabet = std::string_view{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"};
struct invalid_input final
{
size_t const offset;
uint8_t const byte;
};
}
| 16.842105
| 121
| 0.76875
|
contour-terminal
|
e66d0362b11a8ef129db894387de321567d9e3fc
| 6,918
|
cpp
|
C++
|
Anime4KCore/src/ACOpenCL.cpp
|
king350023/Anime4KCPP
|
659442101b884108c24811de3c669283d2d8b20e
|
[
"MIT"
] | null | null | null |
Anime4KCore/src/ACOpenCL.cpp
|
king350023/Anime4KCPP
|
659442101b884108c24811de3c669283d2d8b20e
|
[
"MIT"
] | null | null | null |
Anime4KCore/src/ACOpenCL.cpp
|
king350023/Anime4KCPP
|
659442101b884108c24811de3c669283d2d8b20e
|
[
"MIT"
] | null | null | null |
#define DLL
#include "ACOpenCL.hpp"
Anime4KCPP::OpenCL::GPUList::GPUList(
const int platforms,
std::vector<int> devices,
std::string message
) :platforms(platforms), devices(std::move(devices)), message(std::move(message)) {}
int Anime4KCPP::OpenCL::GPUList::operator[](int pID) const
{
return devices[pID];
}
std::string& Anime4KCPP::OpenCL::GPUList::operator()() noexcept
{
return message;
}
Anime4KCPP::OpenCL::GPUInfo::GPUInfo(const bool supported, std::string message) :
supported(supported), message(std::move(message)) {};
std::string& Anime4KCPP::OpenCL::GPUInfo::operator()() noexcept
{
return message;
}
Anime4KCPP::OpenCL::GPUInfo::operator bool() const noexcept
{
return supported;
}
Anime4KCPP::OpenCL::GPUList Anime4KCPP::OpenCL::listGPUs()
{
cl_int err = 0;
cl_uint platforms = 0;
cl_uint devices = 0;
cl_platform_id* platform = nullptr;
cl_device_id* device = nullptr;
size_t platformNameLength = 0;
size_t deviceNameLength = 0;
char* platformName = nullptr;
char* deviceName = nullptr;
std::ostringstream msg;
std::vector<int> devicesVector;
err = clGetPlatformIDs(0, nullptr, &platforms);
if (err != CL_SUCCESS || !platforms)
return GPUList(0, { 0 }, "No suppoted platform");
platform = new cl_platform_id[platforms];
err = clGetPlatformIDs(platforms, platform, nullptr);
if (err != CL_SUCCESS)
{
delete[] platform;
return GPUList(0, { 0 }, "inital platform error");
}
for (cl_uint i = 0; i < platforms; i++)
{
err = clGetPlatformInfo(platform[i], CL_PLATFORM_NAME, 0, nullptr, &platformNameLength);
if (err != CL_SUCCESS)
{
delete[] platform;
return GPUList(0, { 0 }, "Failed to get platform name length information");
}
platformName = new char[platformNameLength];
err = clGetPlatformInfo(platform[i], CL_PLATFORM_NAME, platformNameLength, platformName, nullptr);
if (err != CL_SUCCESS)
{
delete[] platformName;
delete[] platform;
return GPUList(0, { 0 }, "Failed to get platform name information");
}
msg << "Platform " << i << ": " << platformName << std::endl;
delete[] platformName;
err = clGetDeviceIDs(platform[i], CL_DEVICE_TYPE_GPU, 0, nullptr, &devices);
if (err != CL_SUCCESS || !devices)
{
if (platforms == 1)
{
delete[] platform;
return GPUList(0, { 0 }, "No supported GPU");
}
devicesVector.push_back(0);
msg << " No supported GPU in this platform" << std::endl;
continue;
}
devicesVector.push_back(devices);
device = new cl_device_id[devices];
err = clGetDeviceIDs(platform[i], CL_DEVICE_TYPE_GPU, devices, device, nullptr);
if (err != CL_SUCCESS)
{
delete[] device;
delete[] platform;
return GPUList(0, { 0 }, "inital GPU error");
}
for (cl_uint j = 0; j < devices; j++)
{
err = clGetDeviceInfo(device[j], CL_DEVICE_NAME, 0, nullptr, &deviceNameLength);
if (err != CL_SUCCESS)
{
delete[] device;
delete[] platform;
return GPUList(0, { 0 }, "Failed to get device name length information");
}
deviceName = new char[deviceNameLength];
err = clGetDeviceInfo(device[j], CL_DEVICE_NAME, deviceNameLength, deviceName, nullptr);
if (err != CL_SUCCESS)
{
delete[] deviceName;
delete[] device;
delete[] platform;
return GPUList(0, { 0 }, "Failed to get device name information");
}
msg << " Device " << j << ": " << deviceName << std::endl;
delete[] deviceName;
}
delete[] device;
}
delete[] platform;
return GPUList(platforms, devicesVector, msg.str());
}
Anime4KCPP::OpenCL::GPUInfo Anime4KCPP::OpenCL::checkGPUSupport(unsigned int pID, unsigned int dID)
{
cl_int err = 0;
cl_uint platforms = 0;
cl_uint devices = 0;
cl_platform_id firstPlatform = nullptr;
cl_device_id device = nullptr;
size_t platformNameLength = 0;
size_t deviceNameLength = 0;
char* platformName = nullptr;
char* deviceName = nullptr;
err = clGetPlatformIDs(0, nullptr, &platforms);
if (err != CL_SUCCESS || !platforms)
return GPUInfo(false, "No suppoted platform");
cl_platform_id* tmpPlatform = new cl_platform_id[platforms];
err = clGetPlatformIDs(platforms, tmpPlatform, nullptr);
if (err != CL_SUCCESS)
{
delete[] tmpPlatform;
return GPUInfo(false, "inital platform error");
}
if (pID >= 0 && pID < platforms)
firstPlatform = tmpPlatform[pID];
else
firstPlatform = tmpPlatform[0];
delete[] tmpPlatform;
err = clGetPlatformInfo(firstPlatform, CL_PLATFORM_NAME, 0, nullptr, &platformNameLength);
if (err != CL_SUCCESS)
return GPUInfo(false, "Failed to get platform name length information");
platformName = new char[platformNameLength];
err = clGetPlatformInfo(firstPlatform, CL_PLATFORM_NAME, platformNameLength, platformName, nullptr);
if (err != CL_SUCCESS)
{
delete[] platformName;
return GPUInfo(false, "Failed to get platform name information");
}
err = clGetDeviceIDs(firstPlatform, CL_DEVICE_TYPE_GPU, 0, nullptr, &devices);
if (err != CL_SUCCESS || !devices)
{
delete[] platformName;
return GPUInfo(false, "No supported GPU");
}
cl_device_id* tmpDevice = new cl_device_id[devices];
err = clGetDeviceIDs(firstPlatform, CL_DEVICE_TYPE_GPU, devices, tmpDevice, nullptr);
if (err != CL_SUCCESS)
{
delete[] platformName;
delete[] tmpDevice;
return GPUInfo(false, "No supported GPU");
}
if (dID >= 0 && dID < devices)
device = tmpDevice[dID];
else
device = tmpDevice[0];
delete[] tmpDevice;
err = clGetDeviceInfo(device, CL_DEVICE_NAME, 0, nullptr, &deviceNameLength);
if (err != CL_SUCCESS)
{
delete[] platformName;
return GPUInfo(false, "Failed to get device name length information");
}
deviceName = new char[deviceNameLength];
err = clGetDeviceInfo(device, CL_DEVICE_NAME, deviceNameLength, deviceName, nullptr);
if (err != CL_SUCCESS)
{
delete[] deviceName;
delete[] platformName;
return GPUInfo(false, "Failed to get device name information");
}
GPUInfo ret(true,
std::string("Platform: ") + platformName + "\n" + " Device: " + deviceName);
delete[] deviceName;
delete[] platformName;
return ret;
}
| 29.564103
| 106
| 0.60769
|
king350023
|
e66d8f43e0402f89403e33ec0325b45b1e0c90de
| 3,124
|
cpp
|
C++
|
volume_I/acm_1096.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
volume_I/acm_1096.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
volume_I/acm_1096.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
#include <cstdio>
char in [ 65536 ];
char const* o;
int a[ 1024 ];
int b[ 1024 ];
bool visit[1024] ;
int que [ 1024 ] ;
int dist[ 1024 ] ;
int prv [ 1024 ];
int n; // number of bus
int n_q;
int nxt[ 2048 ] ;
//int dst[ 2028 ] ;
int head[2048 ] ;
static int readInt()
{
int u = 0;
while(*o && *o <= 32)++o;
while(*o >= 48 && *o <= 57) u = (u << 3) + (u << 1) + (*o ++ - 48);
return u;
}
int readData()
{
o = in;
in[fread(in,1,sizeof(in)-4,stdin)] = 0;
//1. n
n = readInt();
for(int i = 1; i <= n; ++i)
{
a[i] = readInt();
b[i] = readInt();
}
n_q = readInt();
a[n+1] = readInt();
b[n+1] = readInt();
return 0;
}
int bfs()
{
for(int i = 0 ;i != 1024; ++i)
{
visit[i] = false;
prv[i] = 0;
dist[i] = 1024;
}
for(int i = 0; i != 2048; ++i) head[i] = 0;
for(int i= 1 ; i <=n;++i)
{
// i = 1 : p = 2 and 3
// i = 2 : p = 4 and 5 and etc.
//++p;
nxt[i] = head[a[i]];
head[a[i]] = i;
//dst[ p ] = i;
//++p;
//nxt[p] = head[b[i]];
//head[b[i]] = p;
}
int h = 0, t = 0;
que[t++] = n + 1;
visit[n+1] = true;
dist[n+1] = 0;
while( h < t )
{
int u = que[h++];
int au = a[u];
int bu = b[u];
for(int e = head[au]; e != 0; e = nxt[e])
{
int v = e ;
if (!visit[v])
{
visit[v] = true;
dist[v] = 1 + dist[u];
prv[v] = u;
que[t++] = v;
}
}
if (au != bu)
{
for(int e = head[bu]; e != 0; e = nxt[e])
{
int v = e;
if (!visit[v])
{
visit[v] = true;
dist[v] = 1 + dist[u];
prv[v] = u;
que[t++] = v;
}
}
}
}
int ans = 0;
int deep = 1024;
for(int i = 1; i <= n; ++i)
{
if (visit[i] && (n_q == a[i] || n_q == b[i]))
{
if ( deep > dist[ i ] )
{
ans = i;
deep = dist[i];
}
}
}
return ans;
}
int writeData(int ans)
{
if (ans == 0)
{
puts("IMPOSSIBLE");
return 0;
}
int h = 0;
int cur = ans;
char * w = in + 16384;
while(cur != n + 1)
{
++h; // number of changes
*--w = '\n';
int u = cur;
do *--w = u % 10 + '0'; while(u/=10);
cur = prv[cur];
}
//now number of changes
*--w = '\n';
do *--w = h % 10 + '0'; while(h/=10);
fwrite(w, 1, in + 16384 - w, stdout);
return 0;
}
int solve()
{
int ans;
readData();
ans = bfs();
writeData(ans);
return 0;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
solve();
return 0;
}
| 18.057803
| 71
| 0.338668
|
raidenluikang
|
e670f1dce1004823bd8f2e342c2e7b076495df78
| 5,123
|
cpp
|
C++
|
cpp/include/math/matrix.cpp
|
kyuridenamida/competitive-library
|
a2bea434c4591359c208b865d2d4dc25574df24d
|
[
"MIT"
] | 3
|
2017-04-09T10:12:31.000Z
|
2019-02-11T03:11:27.000Z
|
cpp/include/math/matrix.cpp
|
kyuridenamida/competitive-library
|
a2bea434c4591359c208b865d2d4dc25574df24d
|
[
"MIT"
] | null | null | null |
cpp/include/math/matrix.cpp
|
kyuridenamida/competitive-library
|
a2bea434c4591359c208b865d2d4dc25574df24d
|
[
"MIT"
] | 1
|
2019-11-29T06:11:10.000Z
|
2019-11-29T06:11:10.000Z
|
#pragma once
#include "../util.hpp"
template<typename T>
class Vec {
protected:
using iterator = typename vector<T>::iterator;
using const_iterator = typename vector<T>::const_iterator;
using reference = T&;
using const_reference = const T&;
vector<T> v;
template<typename Unop> Vec<T> unop_new(Unop op) const {
Vec<T> res(v.size());
transform(begin(v), end(v), res.begin(), op);
return res;
}
template<typename Binop> Vec<T>& binop(const Vec<T> &r, Binop op) {
transform(r.begin(), r.end(), v.begin(), v.begin(), op);
return *this;
}
template<typename Binop> Vec<T> binop_new(const Vec<T> &r, Binop op) const {
Vec<T> res(v.size());
transform(r.begin(), r.end(), v.begin(), res.begin(), op);
return res;
}
public:
Vec(int n) : v(n) {}
Vec(int n, const T &val) : v(n, val) {}
Vec(const vector<T> &w) : v(w) {}
int size() const noexcept { return v.size(); }
const_iterator begin() const noexcept { return v.begin(); }
const_iterator end() const noexcept { return v.end(); }
iterator begin() noexcept { return v.begin(); }
iterator end() noexcept { return v.end(); }
reference operator[] (int i) { return v[i]; }
const_reference operator[] (int i) const { return v[i]; }
Vec<T> operator-() const { return unop_new([](T val){ return -val; }); };
Vec<T> &operator+=(const Vec<T> &r) {
return binop(r, [](T x, T y) { return x + y; });
}
Vec<T> &operator-=(const Vec<T> &r) {
return binop(r, [](T x, T y) { return x - y; });
}
Vec<T> operator+(const Vec<T> &r) const {
return binop_new(r, [](T x, T y) { return x + y; });
}
Vec<T> operator-(const Vec<T> &r) const {
return binop_new(r, [](T x, T y) { return x - y; });
}
T dot(const Vec<T> &r) const {
return inner_product(v.begin(), v.end(), r.begin(), T(0));
}
T norm() const { return this->dot(v); }
void push_back(const T &r) { v.push_back(r); }
void concat(const Vec<T> &r) { v.insert(v.end(), r.begin(), r.end()); }
};
template<typename T>
class Matrix : public Vec<Vec<T>> {
public:
using Vec<Vec<T>>::Vec;
Matrix(int n, int m, const T &val) : Vec<Vec<T>>::Vec(n, Vec<T>(m, val)) {}
int Y() const { return this->size(); }
int X() const { return (*this)[0].size(); }
Matrix<T> transpose() const {
const int row = Y(), col = X();
Matrix res(col, row);
for (int j = 0; j < col; ++j) {
for (int i = 0; i < row; ++i) {
res[j][i] = (*this)[i][j];
}
}
return res;
}
Matrix<T> operator*(const Matrix<T> &r) const {
Matrix<T> tr = r.transpose();
const int row = Y(), col = tr.Y();
assert (X() == tr.X());
Matrix<T> res(row, col);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
res[i][j] = (*this)[i].dot(tr[j]);
}
}
return res;
}
Vec<T> operator*(const Vec<T> &r) const {
const int row = Y(), col = r.Y();
assert (r.size() == col);
Vec<T> res(row);
for (int i = 0; i < row; ++i) {
res[i] = (*this)[i].dot(r);
}
return res;
}
Matrix<T> &operator*=(const Matrix<T> &r) { return *this = *this * r; }
Matrix<T> operator^(ll n) const {
const int m = Y();
assert (m == X());
Matrix<T> A = *this, res(m, m, 0);
for (int i = 0; i < m; ++i) res[i][i] = 1;
while (n > 0) {
if (n % 2) res *= A;
A = A * A;
n /= 2;
}
return res;
}
void concat_right(const Vec<T> &r) {
const int n = Y();
assert (n == r.size());
for (int i = 0; i < n; ++i) {
(*this)[i].push_back(r[i]);
}
}
void concat_right(const Matrix<T> &r) {
const int n = Y();
assert (n == r.Y());
for (int i = 0; i < n; ++i) {
(*this)[i].concat(r[i]);
}
}
void concat_below(const Vec<T> &r) {
assert (Y() == 0 || X() == r.size());
this->push_back(r);
}
void concat_below(const Matrix<T> &r) {
assert (Y() == 0 || X() == r.X());
for (Vec<T> i: r) (*this).push_back(i);
}
int rank() const {
Matrix<T> A = *this;
if (Y() == 0) return 0;
const int n = Y(), m = X();
int r = 0;
for (int i = 0; r < n && i < m; ++i) {
int pivot = r;
for (int j = r+1; j < n; ++j) {
if (abs(A[j][i]) > abs(A[pivot][i])) pivot = j;
}
swap(A[pivot], A[r]);
if (is_zero(A[r][i])) continue;
for (int k = m-1; k >= i; --k) A[r][k] = A[r][k] / A[r][i];
for(int j = r+1; j < n; ++j) {
for(int k = m-1; k >= i; --k) {
A[j][k] -= A[r][k] * A[j][i];
}
}
++r;
}
return r;
}
T det() const {
const int n = Y();
if (n == 0) return 1;
assert (Y() == X());
Matrix<T> A = *this;
T D = 1;
for (int i = 0; i < n; ++i) {
int pivot = i;
for (int j = i+1; j < n; ++j) {
if (abs(A[j][i]) > abs(A[pivot][i])) pivot = j;
}
swap(A[pivot], A[i]);
D = D * A[i][i] * T(i != pivot ? -1 : 1);
if (is_zero(A[i][i])) break;
for(int j = i+1; j < n; ++j) {
for(int k = n-1; k >= i; --k) {
A[j][k] -= A[i][k] * A[j][i] / A[i][i];
}
}
}
return D;
}
};
| 28.943503
| 78
| 0.486824
|
kyuridenamida
|
e6747b18e969ed210e3bd2c2b55fee3281fa92c7
| 1,585
|
cpp
|
C++
|
gameuit-console-game-engine/Player.cpp
|
phuctm97/console-game-engine
|
b90f4bc50950d75491c82f18820a004e92fe38fe
|
[
"MIT"
] | null | null | null |
gameuit-console-game-engine/Player.cpp
|
phuctm97/console-game-engine
|
b90f4bc50950d75491c82f18820a004e92fe38fe
|
[
"MIT"
] | null | null | null |
gameuit-console-game-engine/Player.cpp
|
phuctm97/console-game-engine
|
b90f4bc50950d75491c82f18820a004e92fe38fe
|
[
"MIT"
] | 1
|
2021-05-23T06:14:25.000Z
|
2021-05-23T06:14:25.000Z
|
#include "Player.h"
#include "Game.h"
Player::Player()
{
_width = 5;
_height = 10;
Game::getInstance()->registerInputNotification( CC_CALLBACK_1(Player::processInput, this) );
}
Player::~Player() {}
void Player::moveUp()
{
int y = getPositionY();
y -= 1;
setPositionY( y );
}
void Player::moveDown()
{
int y = getPositionY();
y += 1;
setPositionY( y );
}
void Player::setPositionX( int x )
{
if ( x < 0 || x > Game::getInstance()->getWidth() - _width ) return;
GameObject::setPositionX( x );
}
void Player::setPositionY( int y )
{
if ( y < 0 || y > Game::getInstance()->getHeight() - _height ) return;
GameObject::setPositionY( y );
}
int Player::getWidth() const { return _width; }
void Player::setWidth( int width )
{
if ( _width == width ) return;
_width_old = _width;
_width = width;
_dirty = true;
}
int Player::getHeight() const { return _height; }
void Player::setHeight( int height )
{
if ( _height == height ) return;
_height_old = _height;
_height = height;
_dirty = true;
}
void Player::childUpdate() {}
void Player::childRender()
{
for ( int i = 0; i < _height_old; i++ ) {
Console::setCursor( _positionX_old, _positionY_old + i );
for ( int j = 0; j < _width_old; j++ ) {
std::cout << char( 0x20 );
}
}
for ( int i = 0; i < _height; i++ ) {
Console::setCursor( _positionX, _positionY + i );
for ( int j = 0; j < _width; j++ ) {
std::cout << char( 178 );
}
}
}
void Player::childReset()
{
GameObject::reset();
_width_old = _width;
_height_old = _height;
}
void Player::processInput( int pressedKey )
{
}
| 16.684211
| 93
| 0.624606
|
phuctm97
|
e677f38a25d5597728f261ea975db366e5d3c20e
| 2,125
|
cc
|
C++
|
MagneticField/Interpolation/src/binary_ofstream.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 852
|
2015-01-11T21:03:51.000Z
|
2022-03-25T21:14:00.000Z
|
MagneticField/Interpolation/src/binary_ofstream.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 30,371
|
2015-01-02T00:14:40.000Z
|
2022-03-31T23:26:05.000Z
|
MagneticField/Interpolation/src/binary_ofstream.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 3,240
|
2015-01-02T05:53:18.000Z
|
2022-03-31T17:24:21.000Z
|
#include "binary_ofstream.h"
#include <cstdio>
#include <iostream>
struct binary_ofstream_error {};
binary_ofstream::binary_ofstream(const char* name) : file_(nullptr) { init(name); }
binary_ofstream::binary_ofstream(const std::string& name) : file_(nullptr) { init(name.c_str()); }
void binary_ofstream::init(const char* name) {
file_ = fopen(name, "wb");
if (file_ == nullptr) {
std::cout << "file " << name << " cannot be opened for writing" << std::endl;
throw binary_ofstream_error();
}
}
binary_ofstream::~binary_ofstream() { close(); }
void binary_ofstream::close() {
if (file_ != nullptr)
fclose(file_);
file_ = nullptr;
}
binary_ofstream& binary_ofstream::operator<<(char n) {
fputc(n, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(unsigned char n) {
fputc(n, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(short n) {
fwrite(&n, sizeof(n), 1, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(unsigned short n) {
fwrite(&n, sizeof(n), 1, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(int n) {
fwrite(&n, sizeof(n), 1, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(unsigned int n) {
fwrite(&n, sizeof(n), 1, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(long n) {
fwrite(&n, sizeof(n), 1, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(unsigned long n) {
fwrite(&n, sizeof(n), 1, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(float n) {
fwrite(&n, sizeof(n), 1, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(double n) {
fwrite(&n, sizeof(n), 1, file_);
return *this;
}
binary_ofstream& binary_ofstream::operator<<(bool n) { return operator<<(static_cast<char>(n)); }
binary_ofstream& binary_ofstream::operator<<(const std::string& s) {
(*this)
<< (uint32_t)
s.size(); // Use uint32 for backward compatibilty of binary files that were generated on 32-bit machines.
fwrite(s.data(), 1, s.size(), file_);
return *this;
}
| 27.24359
| 119
| 0.680941
|
ckamtsikis
|
e678b7750515d5686bc61f1cc4b4cb2775da02aa
| 1,708
|
hpp
|
C++
|
src/snapplot/snapplot_mapview.hpp
|
linz/snap
|
1505880b282290fc28bbbe0c4d4f69088ad81de0
|
[
"BSD-3-Clause"
] | 7
|
2018-09-17T06:49:30.000Z
|
2020-10-10T19:12:31.000Z
|
src/snapplot/snapplot_mapview.hpp
|
linz/snap
|
1505880b282290fc28bbbe0c4d4f69088ad81de0
|
[
"BSD-3-Clause"
] | 81
|
2016-11-09T01:18:19.000Z
|
2022-03-31T04:34:12.000Z
|
src/snapplot/snapplot_mapview.hpp
|
linz/snap
|
1505880b282290fc28bbbe0c4d4f69088ad81de0
|
[
"BSD-3-Clause"
] | 5
|
2017-07-03T03:00:29.000Z
|
2022-01-25T07:05:08.000Z
|
#ifndef SNAPPLOT_MAPVIEW_HPP
#define SNAPPLOT_MAPVIEW_HPP
#include "snapplot_event.hpp"
#include "snapplot_dragger.hpp"
#include "wxmapwindow.hpp"
DECLARE_EVENT_TYPE( WX_MAPVIEW_DISPLAY_COORDS, -1 )
class SnapplotMapView : public wxMapWindow
{
public:
SnapplotMapView( wxWindow *parent );
~SnapplotMapView();
void ZoomToStation( int istn );
void ZoomToLine( int from, int to );
void LocateStation( int istn );
void LocateLine( int from, int to );
wxBitmap CreateImage();
void SetWeakLock( bool newWeakLock ) { weakLock = newWeakLock; }
bool WeakLock() { return weakLock; }
private:
void OnIdleEvent( wxIdleEvent &event );
void TestOnShowDetails( wxSnapplotEvent &event );
void OnMapWindowPosition( wxMapWindowEvent &event );
void OnClickEvent( wxMapWindowEvent &event );
void OnIdle( wxIdleEvent &event );
void OnPaint( wxPaintEvent &event );
void ShowInfo( const MapPoint &pt, bool zoom );
void SendShowStationEvent( int istn, bool zoom );
void SendShowLineEvent( int from, int to, bool zoom );
void SendShowTitleEvent();
void SetLocator( int from, int to );
void SetLocatorLocked( bool locked );
void PaintLocator();
void PaintLocator( wxDC &dc );
void ClearLocator();
int FindStation( const MapPoint &pt );
int pickTolerance;
bool positionChanged;
int locatorFrom;
int locatorTo;
bool locatorLocked; // If the from station is locked ...
bool weakLock; // If true, then clicking other than a station will release a lock
wxString coordString;
// Object used to manage dragging on the map
SnapplotMapDragger mapDragger;
DECLARE_EVENT_TABLE();
};
#endif
| 27.548387
| 85
| 0.70726
|
linz
|
e67e6a7eef68204b34ac5e6b2f6ebad8deca1b6d
| 7,262
|
cpp
|
C++
|
main.cpp
|
jiangzhuti/DMProxy
|
0a95e5173079eca6b61e7661b3f4d5d3a2ae08a6
|
[
"WTFPL"
] | null | null | null |
main.cpp
|
jiangzhuti/DMProxy
|
0a95e5173079eca6b61e7661b3f4d5d3a2ae08a6
|
[
"WTFPL"
] | null | null | null |
main.cpp
|
jiangzhuti/DMProxy
|
0a95e5173079eca6b61e7661b3f4d5d3a2ae08a6
|
[
"WTFPL"
] | null | null | null |
#include <map>
#include <set>
#include <sstream>
#include <memory>
#include <utility>
#include <tuple>
#include <boost/program_options.hpp>
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include "network/dmp_cs.hpp"
#include "platforms/platforms.hpp"
#include "utils/others.hpp"
#include "utils/rw_lock.hpp"
//use 'static' to prevent clang for generating -Wmissing-variable-declarations warnings
static int server_threads, client_threads;
static uint16_t server_port;
static std::string server_host;
static std::string uri;
static boost::asio::io_service server_io_service;
static boost::asio::io_service platform_io_service;
//STL Containers are thread-safe for concurrent read, so need a rw lock
//see https://stackoverflow.com/questions/7455982/is-stl-vector-concurrent-read-thread-safe
typedef std::map<std::string, platform_base_ptr_t> roomstr_platform_map;
static roomstr_platform_map rp_map;
static rw_mutex_t rp_rw_mtx;
namespace po = boost::program_options;
void on_platform_close(std::string roomstr)
{
wlock_t wlock(rp_rw_mtx);
rp_map.erase(roomstr);
}
void on_server_close(std::string roomstr, connection_hdl hdl)
{
wlock_t wlock(rp_rw_mtx);
if (rp_map.count(roomstr) == 0) {
return;
}
auto pbase = rp_map[roomstr];
pbase->erase_listener(hdl);
if (pbase->listeners_count() == 0) {
pbase->close();
rp_map.erase(roomstr);
}
}
void on_server_message(std::string old_roomstr, connection_hdl hdl, message_ptr msg)
{
if (msg->get_opcode() != opcode::TEXT) {
//ignored;
return;
}
std::error_code ec;
//payload format :: "platform-tag" + "_" + "roomid"
std::string roomstr = msg->get_payload();
boost::trim(roomstr);
auto pos = roomstr.find_first_of('_');
if (!(roomstr.length() > 3 && pos > 0 && pos < roomstr.length() - 1)) {
server.send(hdl, std::string("format error!"), opcode::TEXT, ec);
SERVER_CLOSE_AND_REPORT_WHEN_ERROR(ec, hdl);
return;
}
std::string tag = std::string(roomstr, 0, pos);
std::string roomid = std::string(roomstr, pos + 1);
platform_base_ptr_t pbase;
wlock_t rp_wlock(rp_rw_mtx);
if (old_roomstr == roomstr && rp_map.count(old_roomstr) != 0)
return;
auto s_conn = server.get_con_from_hdl(hdl);
s_conn->set_message_handler(std::bind(on_server_message,
roomstr,
std::placeholders::_1,
std::placeholders::_2));
if (rp_map.count(old_roomstr) != 0) {
auto old_pbase = rp_map[old_roomstr];
old_pbase->erase_listener(hdl);
if (old_pbase->listeners_count() == 0) {
old_pbase->close();
rp_map.erase(old_roomstr);
}
}
if (rp_map.count(roomstr) != 0) {
pbase = rp_map[roomstr];
if (!pbase->have_listener(hdl)) {
pbase->add_listener(hdl);
return;
}
} else {
pbase = platform_get_instance(tag, platform_io_service, roomid);
if (pbase == nullptr) {
server.send(hdl, std::string("platform ") + tag + std::string(" is not valid!"), opcode::TEXT, ec);
SERVER_CLOSE_AND_REPORT_WHEN_ERROR(ec, hdl);
return;
}
websocketpp::lib::error_code ec;
if (!pbase->is_room_valid()) {
server.send(hdl, std::string("roomid invalid!"), opcode::TEXT, ec);
SERVER_CLOSE_AND_REPORT_WHEN_ERROR(ec, hdl);
return;
}
}
auto conn_ptr = server.get_con_from_hdl(hdl);
conn_ptr->set_close_handler(std::bind(on_server_close, roomstr, std::placeholders::_1));
pbase->add_listener(hdl);
pbase->set_close_callback(on_platform_close);\
rp_map[roomstr] = pbase;
pbase->start();
}
int main(int argc, char *argv[])
{
po::options_description desc("Allowed Options:");
desc.add_options()
("help", "Produce help message")
("server-host", po::value<std::string>(&server_host)->default_value("localhost"), "Set the DMProxy server port, default to 9001")
("server-port", po::value<uint16_t>(&server_port)->default_value(9001), "Set the DMProxy server port, default to 9001")
("server-threads", po::value<int>(&server_threads)->default_value(3), "Set the number of the DMProxy server io_service threads, defalut to 3")
("client-threads", po::value<int>(&client_threads)->default_value(3), "Set the number of the DMProxy client io_service threads, defalut to 3");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 1;
}
platforms_init();
try {
server.clear_access_channels(websocketpp::log::alevel::all);
server.clear_error_channels(websocketpp::log::alevel::all);
server.init_asio(&server_io_service);
server.set_reuse_addr(true);
server.set_message_handler(std::bind(on_server_message, std::string(), std::placeholders::_1, std::placeholders::_2));
server.set_socket_init_handler([](connection_hdl, boost::asio::ip::tcp::socket & s)
{
boost::asio::ip::tcp::no_delay option(true);
s.set_option(option);
});
server.set_listen_backlog(8192);
server.listen(server_host, std::to_string(server_port));
server.start_accept();
client.clear_access_channels(websocketpp::log::alevel::all);
client.clear_error_channels(websocketpp::log::alevel::all);
client.set_user_agent("Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0");
client.init_asio(&platform_io_service);
boost::asio::io_service::work platform_work(platform_io_service);
typedef websocketpp::lib::shared_ptr<std::thread> thread_ptr;
std::vector<thread_ptr> s_ts, c_ts;
for (auto i = 0; i < server_threads; i++) {
s_ts.push_back(std::make_shared<std::thread>([&]()
{
server_io_service.run();
std::cout << "server thread returned\n";
}));
}
for (auto i = 0; i < client_threads; i++) {
c_ts.push_back(std::make_shared<std::thread>([&]()
{
platform_io_service.run();
std::cout << "client thread returned\n";
}));
}
for (auto i : s_ts) {
i->join();
}
for (auto i : c_ts) {
i->join();
}
} catch (websocketpp::exception const &e) {
std::cout << "Exception:" << e.what() <<std::endl;
}
return 0;
}
| 39.043011
| 155
| 0.576012
|
jiangzhuti
|
e680e9aa39e997fe9a04909728b929bce7da9ac2
| 7,386
|
cpp
|
C++
|
src/api/JavaIntegration.cpp
|
davidcorbin/mygcc-application
|
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
|
[
"MIT"
] | 2
|
2019-01-18T02:33:45.000Z
|
2019-02-01T23:44:05.000Z
|
src/api/JavaIntegration.cpp
|
davidcorbin/mygcc-application
|
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
|
[
"MIT"
] | null | null | null |
src/api/JavaIntegration.cpp
|
davidcorbin/mygcc-application
|
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
|
[
"MIT"
] | null | null | null |
/**
* Copyright 2018 <David Corbin, Mitchell Harvey>
*/
#include <include/api/JavaIntegration.hpp>
#include <include/FileNotFound.hpp>
#include <QDesktopServices>
#include <QUrl>
#include <QFileInfo>
#include <QTextStream>
#include <QDebug>
#include <QSettings>
#include <QApplication>
#include <string>
#include <algorithm>
#include <random>
#include <regex> // NOLINT
#define MYGCC_API_FILENAME "mygcc-api-jar-with-dependencies.jar"
#define VALID_JAVA_VER_REG "1.8|10"
#define JAVA_PATH_MAC "/Library/Internet Plug-Ins/JavaAppletPlugin." \
"plugin/Contents/Home/bin/java"
#define INSTALL_JAVA_SITE "https://facadeapp.cc/installjava8"
JavaIntegration::JavaIntegration() {
fm = new FileManager;
}
void JavaIntegration::startAPIThread() {
auto *initvect = getInitVect();
auto *enckey = getEncKey();
qputenv("initvect", initvect->c_str());
qputenv("enckey", enckey->c_str());
startAPIServerCmd();
}
void JavaIntegration::startAPIServerCmd() {
std::string jarPath = fm->getResourcePath(MYGCC_API_FILENAME);
auto *javaPath = findJava();
if (!javaPath->empty()) {
if (checkJavaVersion(javaPath)) {
qDebug() << "Valid Java version found at" << javaPath->c_str();
std::string fullStr = "\"" + *javaPath + "\" -cp \""
+ jarPath + "\" com.mygcc.api.Main";
qDebug() << "Starting API with command:" << fullStr.c_str();
javaProcess.start(fullStr.c_str());
} else {
qDebug() << "Invalid java version";
// Open site to show user how to install java
QDesktopServices::openUrl(QUrl(INSTALL_JAVA_SITE));
qApp->exit(1);
}
} else {
qDebug("%s", "Could not start java server");
// Open site to show user how to install java
QDesktopServices::openUrl(QUrl(INSTALL_JAVA_SITE));
qApp->exit(1);
}
}
int JavaIntegration::stopAPIServerCmd() {
javaProcess.close();
return 0;
}
int JavaIntegration::getAPIPort() {
return 8080;
}
std::string* JavaIntegration::findJava() {
// Use the standard path for finding java on macOS
#if defined(__APPLE__) || defined(__MACH__)
qDebug() << "Checking for java at known macOS path" << JAVA_PATH_MAC;
QFileInfo check_file(JAVA_PATH_MAC);
if (check_file.exists()) {
qDebug() << "Known macOS java path found";
return new std::string(JAVA_PATH_MAC);
} else {
qDebug() << "Known macOS java path NOT found";
return new std::string("");
}
#endif
// User registry keys for finding java on Windows
#if defined(_WIN32) || defined(_WIN64)
// 64 bit registry key
QSettings jreKey64("HKEY_LOCAL_MACHINE\\SOFTWARE" \
"\\JavaSoft\\Java Runtime Environment",
QSettings::Registry64Format);
// 32 bit registry key
QSettings jreKey32("HKEY_LOCAL_MACHINE\\Software\\WOW6432Node" \
"\\JavaSoft\\Java Runtime Environment",
QSettings::Registry32Format);
// If JAVA installed
if (jreKey32.allKeys().contains("CurrentVersion", Qt::CaseInsensitive) ||
jreKey64.allKeys().contains("CurrentVersion", Qt::CaseInsensitive)) {
QSettings *jreKey;
if (jreKey32.allKeys().contains("CurrentVersion", Qt::CaseInsensitive)) {
qDebug("32 bit Java FOUND");
jreKey = &jreKey32;
}
if (jreKey64.allKeys().contains("CurrentVersion", Qt::CaseInsensitive)) {
qDebug("64 bit JAVA FOUND");
jreKey = &jreKey64;
}
auto version = jreKey->value("CurrentVersion").toString();
qDebug() << "Latest java version identified:" <<
version.toStdString().c_str();
if (version.contains("1.8")) {
QSettings jreVerKey(jreKey->fileName() + "\\" + version,
QSettings::Registry64Format);
if (jreVerKey.childKeys().contains("JavaHome", Qt::CaseInsensitive)) {
auto javaHome = jreVerKey.value("JavaHome").toString();
qDebug() << "Java home identified:" << javaHome.toStdString().c_str();
return new std::string(javaHome.toStdString() + "\\bin\\java.exe");
} else {
qWarning("JavaHome key NOT FOUND");
}
} else {
qWarning("Java version '1.8' NOT FOUND");
}
} else {
qWarning("Java NOT FOUND in default install path");
}
return new std::string("");
#endif
#if defined(__unix) || defined(__unix__) || defined(__linux__)
// Check for java in $PATH
QProcess findJavaExe;
findJavaExe.start("java");
bool started = findJavaExe.waitForStarted();
QByteArray stdoutput;
do {
stdoutput += findJavaExe.readAllStandardOutput();
} while (!findJavaExe.waitForFinished(100) && findJavaExe.isOpen());
// If java executable in path
if (started) {
return new std::string("java");
} else {
return new std::string("");
}
#endif
}
bool JavaIntegration::checkJavaVersion(std::string *javaPath) {
auto *path = new std::string(javaPath->c_str());
QProcess javaInPath;
javaInPath.start(("\"" + *path + "\" -version").c_str());
javaInPath.waitForFinished();
QString out(javaInPath.readAllStandardError());
auto output = out.toStdString();
std::string line(output.begin(),
std::find(output.begin(), output.end(), '\n'));
qDebug("%s", line.c_str());
std::regex re(VALID_JAVA_VER_REG);
return std::regex_search(line, re);
}
std::string* JavaIntegration::getInitVect() {
try {
QString ivpath = QString::fromStdString(fm->getDataPath("initvect"));
qDebug() << "Initialization vector path: " << ivpath;
QFile file(ivpath);
if (file.open(QIODevice::ReadOnly)) {
QTextStream in(&file);
std::string line = in.readLine().toStdString();
file.close();
return new std::string(line.c_str());
}
} catch (FileNotFound &e) {
// Generate init vect
auto *initvect = reinterpret_cast<char *>(malloc(sizeof(char) * 17));
genRandomString(initvect);
QString datadir = QString::fromStdString(fm->getDataDir());
QFile file(datadir + "/initvect");
// Open file
if (file.open(QIODevice::ReadWrite)) {
QTextStream stream(&file);
stream << initvect << endl;
}
std::string stdinitvect(initvect);
return new std::string(stdinitvect.c_str());
}
return nullptr;
}
std::string* JavaIntegration::getEncKey() {
try {
QString ivpath = QString::fromStdString(fm->getDataPath("enckey"));
qDebug() << "Encryption key path: " << ivpath;
QFile file(ivpath);
if (file.open(QIODevice::ReadOnly)) {
QTextStream in(&file);
auto line = in.readLine().toStdString();
file.close();
return new std::string(line.c_str());
}
} catch (FileNotFound &e) {
// Generate encryption key
auto *initvect = reinterpret_cast<char *>(malloc(sizeof(char) * 17));
genRandomString(initvect);
QString datadir = QString::fromStdString(fm->getDataDir());
QFile file(datadir + "/enckey");
// Open file
if (file.open(QIODevice::ReadWrite)) {
QTextStream stream(&file);
stream << initvect << endl;
}
std::string stdenckey(initvect);
return new std::string(stdenckey.c_str());
}
return nullptr;
}
void JavaIntegration::genRandomString(char *s, int size) {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<> dist(1, 26);
static const char alphanum[] = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < size; ++i) {
s[i] = alphanum[static_cast<int>(dist(mt)) % (sizeof(alphanum) - 1)];
}
s[size] = 0;
}
| 30.647303
| 78
| 0.653804
|
davidcorbin
|
e697b4d120c2cb38fccd361679dd9388b4d1da22
| 1,435
|
cpp
|
C++
|
Range Queries/Pizzeria Queries.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | 2
|
2022-02-12T12:30:13.000Z
|
2022-02-12T13:59:20.000Z
|
Range Queries/Pizzeria Queries.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | 2
|
2022-02-12T11:09:41.000Z
|
2022-02-12T11:55:49.000Z
|
Range Queries/Pizzeria Queries.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int INF=2e9;
void buildTree(int v, int tl, int tr,vector<int>&st,vector<int>&a){
if (tl==tr){
st[v]=a[tl];
return;
}
int mid = (tl+tr)>>1;
buildTree(v*2,tl,mid,st,a);
buildTree(v*2+1,mid+1,tr,st,a);
st[v]=min(st[v*2],st[v*2+1]);
}
int get(int v, int l, int r, int tl, int tr,vector<int>&st){
if (l>r) return INF;
if (tl==l&&tr==r)return st[v];
int mid=(tl+tr)>>1;
return min(get(v*2,l,min(mid,r),tl,mid,st),get(v*2+1,max(l,mid+1),r,mid+1,tr,st));
}
void update(int v, int tl, int tr, int pos,vector<int>&st,vector<int>&a){
if (tl==tr){
st[v]=a[pos];
return;
}
int mid=(tl+tr)>>1;
if (pos<=mid) update(v*2,tl,mid,pos,st,a);
else update(v*2+1,mid+1,tr,pos,st,a);
st[v]=min(st[v*2],st[v*2+1]);
}
int main(){
ios::sync_with_stdio(false);cin.tie(NULL);
int n,q;
cin>>n>>q;
vector<int> a1(n),a2(n),a(n);
for(int i=0;i<n;++i){
cin>>a[i];
a1[i]=a[i]-i-1;
a2[i]=a[i]-n+i;
}
vector<int>st1(n*4),st2(n*4);
buildTree(1,0,n-1,st1,a1);
buildTree(1,0,n-1,st2,a2);
for (int i=0;i<q;++i){
int t,pos;cin>>t>>pos;--pos;
if (t==2){
int re1=get(1,0,pos,0,n-1,st1)-a1[pos];
int re2=get(1,pos,n-1,0,n-1,st2)-a2[pos];
cout<<min(re1,re2)+a[pos]<<'\n';
}
else {
int val;cin>>val;
a1[pos]+=val-a[pos];
a2[pos]+=val-a[pos];
a[pos]=val;
update(1,0,n-1,pos,st1,a1);
update(1,0,n-1,pos,st2,a2);
}
}
return 0;
}
| 22.076923
| 83
| 0.570035
|
DecSP
|
e697d9198534bd197f46f41fc1ff37d94f8132b4
| 6,871
|
cpp
|
C++
|
Gems/NvCloth/Code/Tests/UnitTestHelper.cpp
|
aaarsene/o3de
|
37e3b0226958974defd14dd6d808e8557dcd7345
|
[
"Apache-2.0",
"MIT"
] | 1
|
2021-09-13T00:01:12.000Z
|
2021-09-13T00:01:12.000Z
|
Gems/NvCloth/Code/Tests/UnitTestHelper.cpp
|
aaarsene/o3de
|
37e3b0226958974defd14dd6d808e8557dcd7345
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
Gems/NvCloth/Code/Tests/UnitTestHelper.cpp
|
aaarsene/o3de
|
37e3b0226958974defd14dd6d808e8557dcd7345
|
[
"Apache-2.0",
"MIT"
] | 1
|
2021-07-20T11:07:25.000Z
|
2021-07-20T11:07:25.000Z
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <UnitTestHelper.h>
#include <AzCore/Interface/Interface.h>
#include <TriangleInputHelper.h>
#include <NvCloth/IFabricCooker.h>
namespace UnitTest
{
void ExpectEq(const AZ::Vector3& azVec, const physx::PxVec3& pxVec, const float tolerance)
{
EXPECT_NEAR(azVec.GetX(), pxVec.x, tolerance);
EXPECT_NEAR(azVec.GetY(), pxVec.y, tolerance);
EXPECT_NEAR(azVec.GetZ(), pxVec.z, tolerance);
}
void ExpectEq(const AZ::Vector4& azVec, const physx::PxVec4& pxVec, const float tolerance)
{
EXPECT_NEAR(azVec.GetX(), pxVec.x, tolerance);
EXPECT_NEAR(azVec.GetY(), pxVec.y, tolerance);
EXPECT_NEAR(azVec.GetZ(), pxVec.z, tolerance);
EXPECT_NEAR(azVec.GetW(), pxVec.w, tolerance);
}
void ExpectEq(const AZ::Quaternion& azQuat, const physx::PxQuat& pxQuat, const float tolerance)
{
EXPECT_NEAR(azQuat.GetX(), pxQuat.x, tolerance);
EXPECT_NEAR(azQuat.GetY(), pxQuat.y, tolerance);
EXPECT_NEAR(azQuat.GetZ(), pxQuat.z, tolerance);
EXPECT_NEAR(azQuat.GetW(), pxQuat.w, tolerance);
}
void ExpectEq(const physx::PxVec4& pxVecA, const physx::PxVec4& pxVecB, const float tolerance)
{
EXPECT_NEAR(pxVecA.x, pxVecB.x, tolerance);
EXPECT_NEAR(pxVecA.y, pxVecB.y, tolerance);
EXPECT_NEAR(pxVecA.z, pxVecB.z, tolerance);
EXPECT_NEAR(pxVecA.w, pxVecB.w, tolerance);
}
void ExpectEq(const NvCloth::FabricCookedData::InternalCookedData& azCookedData, const nv::cloth::CookedData& nvCookedData, const float tolerance)
{
EXPECT_EQ(azCookedData.m_numParticles, nvCookedData.mNumParticles);
ExpectEq(azCookedData.m_phaseIndices, nvCookedData.mPhaseIndices);
ExpectEq(azCookedData.m_phaseTypes, nvCookedData.mPhaseTypes);
ExpectEq(azCookedData.m_sets, nvCookedData.mSets);
ExpectEq(azCookedData.m_restValues, nvCookedData.mRestvalues, tolerance);
ExpectEq(azCookedData.m_stiffnessValues, nvCookedData.mStiffnessValues, tolerance);
ExpectEq(azCookedData.m_indices, nvCookedData.mIndices);
ExpectEq(azCookedData.m_anchors, nvCookedData.mAnchors);
ExpectEq(azCookedData.m_tetherLengths, nvCookedData.mTetherLengths, tolerance);
ExpectEq(azCookedData.m_triangles, nvCookedData.mTriangles);
}
void ExpectEq(const NvCloth::FabricCookedData::InternalCookedData& azCookedDataA, const NvCloth::FabricCookedData::InternalCookedData& azCookedDataB, const float tolerance)
{
EXPECT_EQ(azCookedDataA.m_numParticles, azCookedDataB.m_numParticles);
EXPECT_EQ(azCookedDataA.m_phaseIndices, azCookedDataB.m_phaseIndices);
EXPECT_EQ(azCookedDataA.m_phaseTypes, azCookedDataB.m_phaseTypes);
EXPECT_EQ(azCookedDataA.m_sets, azCookedDataB.m_sets);
ExpectEq(azCookedDataA.m_restValues, azCookedDataB.m_restValues, tolerance);
ExpectEq(azCookedDataA.m_stiffnessValues, azCookedDataB.m_stiffnessValues, tolerance);
EXPECT_EQ(azCookedDataA.m_indices, azCookedDataB.m_indices);
EXPECT_EQ(azCookedDataA.m_anchors, azCookedDataB.m_anchors);
ExpectEq(azCookedDataA.m_tetherLengths, azCookedDataB.m_tetherLengths, tolerance);
EXPECT_EQ(azCookedDataA.m_triangles, azCookedDataB.m_triangles);
}
void ExpectEq(const NvCloth::FabricCookedData& fabricCookedDataA, const NvCloth::FabricCookedData& fabricCookedDataB, const float tolerance)
{
EXPECT_EQ(fabricCookedDataA.m_id, fabricCookedDataB.m_id);
EXPECT_THAT(fabricCookedDataA.m_particles, ::testing::Pointwise(ContainerIsCloseTolerance(tolerance), fabricCookedDataB.m_particles));
EXPECT_EQ(fabricCookedDataA.m_indices, fabricCookedDataB.m_indices);
EXPECT_THAT(fabricCookedDataA.m_gravity, IsCloseTolerance(fabricCookedDataB.m_gravity, tolerance));
EXPECT_EQ(fabricCookedDataA.m_useGeodesicTether, fabricCookedDataB.m_useGeodesicTether);
ExpectEq(fabricCookedDataA.m_internalData, fabricCookedDataB.m_internalData, tolerance);
}
void ExpectEq(const AZStd::vector<float>& azVectorA, const AZStd::vector<float> azVectorB, const float tolerance)
{
EXPECT_EQ(azVectorA.size(), azVectorB.size());
if (azVectorA.size() == azVectorB.size())
{
for (size_t i = 0; i < azVectorA.size(); ++i)
{
EXPECT_NEAR(azVectorA[i], azVectorB[i], tolerance);
}
}
}
void ExpectEq(const AZStd::vector<AZ::s32>& azVector, const nv::cloth::Range<const AZ::s32>& nvRange)
{
EXPECT_EQ(azVector.size(), nvRange.size());
if (azVector.size() == nvRange.size())
{
for (AZ::u32 i = 0; i < nvRange.size(); ++i)
{
EXPECT_EQ(azVector[i], nvRange[i]);
}
}
}
void ExpectEq(const AZStd::vector<AZ::u32>& azVector, const nv::cloth::Range<const AZ::u32>& nvRange)
{
EXPECT_EQ(azVector.size(), nvRange.size());
if (azVector.size() == nvRange.size())
{
for (AZ::u32 i = 0; i < nvRange.size(); ++i)
{
EXPECT_EQ(azVector[i], nvRange[i]);
}
}
}
void ExpectEq(const AZStd::vector<float>& azVector, const nv::cloth::Range<const float>& nvRange, const float tolerance)
{
EXPECT_EQ(azVector.size(), nvRange.size());
if (azVector.size() == nvRange.size())
{
for (AZ::u32 i = 0; i < nvRange.size(); ++i)
{
EXPECT_NEAR(azVector[i], nvRange[i], tolerance);
}
}
}
void ExpectEq(const AZStd::vector<AZ::Vector4>& azVector, const nv::cloth::Range<const physx::PxVec4>& nvRange, const float tolerance)
{
EXPECT_EQ(azVector.size(), nvRange.size());
if (azVector.size() == nvRange.size())
{
for (AZ::u32 i = 0; i < nvRange.size(); ++i)
{
ExpectEq(azVector[i], nvRange[i], tolerance);
}
}
}
NvCloth::FabricCookedData CreateTestFabricCookedData()
{
const float width = 1.0f;
const float height = 1.0f;
const AZ::u32 segmentsX = 5;
const AZ::u32 segmentsY = 5;
const TriangleInput planeXY = CreatePlane(width, height, segmentsX, segmentsY);
const AZStd::optional<const NvCloth::FabricCookedData> fabricCookedData =
AZ::Interface<NvCloth::IFabricCooker>::Get()->CookFabric(
planeXY.m_vertices, planeXY.m_indices);
EXPECT_TRUE(fabricCookedData.has_value());
return *fabricCookedData;
}
} // namespace UnitTest
| 41.896341
| 176
| 0.667006
|
aaarsene
|
e69af1c7058358166fb3546346080ab385e380b6
| 2,439
|
cpp
|
C++
|
flow/walker/serial_node_walker.cpp
|
aconstlink/snakeoil
|
3c6e02655e1134f8422f01073090efdde80fc109
|
[
"MIT"
] | 1
|
2017-08-11T19:12:24.000Z
|
2017-08-11T19:12:24.000Z
|
flow/walker/serial_node_walker.cpp
|
aconstlink/snakeoil
|
3c6e02655e1134f8422f01073090efdde80fc109
|
[
"MIT"
] | 11
|
2018-07-07T20:09:44.000Z
|
2020-02-16T22:45:09.000Z
|
flow/walker/serial_node_walker.cpp
|
aconstlink/snakeoil
|
3c6e02655e1134f8422f01073090efdde80fc109
|
[
"MIT"
] | null | null | null |
//------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#include "serial_node_walker.h"
using namespace so_flow ;
//**********************************************************************************************
serial_node_walker::serial_node_walker( void_t )
{}
//**********************************************************************************************
serial_node_walker::serial_node_walker( this_rref_t )
{}
//**********************************************************************************************
serial_node_walker::~serial_node_walker( void_t )
{}
//**********************************************************************************************
serial_node_walker::this_ptr_t serial_node_walker::create( so_memory::purpose_cref_t p )
{
return so_flow::memory::alloc( this_t(), p ) ;
}
//**********************************************************************************************
void_t serial_node_walker::destroy( this_ptr_t ptr )
{
so_flow::memory::dealloc( ptr ) ;
}
//**********************************************************************************************
void_t serial_node_walker::walk( so_flow::inode::nodes_rref_t init_nodes )
{
// trigger
{
so_flow::inode::nodes_t nodes = init_nodes ;
while(nodes.size() != 0)
{
so_flow::inode::nodes_t inner_nodes = std::move( nodes ) ;
for(so_flow::inode_ptr_t nptr : inner_nodes)
{
nptr->on_trigger( nodes ) ;
}
}
}
// update
{
so_flow::inode::nodes_t nodes = init_nodes ;
while(nodes.size() != 0)
{
so_flow::inode::nodes_t inner_nodes = std::move( nodes ) ;
for(so_flow::inode_ptr_t nptr : inner_nodes)
{
nptr->on_update( nodes ) ;
}
}
}
}
//**********************************************************************************************
void_t serial_node_walker::walk( so_flow::inode::nodes_cref_t init_nodes )
{
so_flow::inode::nodes_t nodes = init_nodes ;
this_t::walk( std::move(nodes) ) ;
}
//**********************************************************************************************
void_t serial_node_walker::destroy( void_t )
{
this_t::destroy( this ) ;
}
| 32.52
| 96
| 0.388684
|
aconstlink
|
e69bacf5f2c16dda5a156d178a56479e3dc46657
| 14,962
|
hpp
|
C++
|
dakota-6.3.0.Windows.x86/include/Teuchos_ArrayViewDecl.hpp
|
seakers/ExtUtils
|
b0186098063c39bd410d9decc2a765f24d631b25
|
[
"BSD-2-Clause"
] | null | null | null |
dakota-6.3.0.Windows.x86/include/Teuchos_ArrayViewDecl.hpp
|
seakers/ExtUtils
|
b0186098063c39bd410d9decc2a765f24d631b25
|
[
"BSD-2-Clause"
] | null | null | null |
dakota-6.3.0.Windows.x86/include/Teuchos_ArrayViewDecl.hpp
|
seakers/ExtUtils
|
b0186098063c39bd410d9decc2a765f24d631b25
|
[
"BSD-2-Clause"
] | 1
|
2022-03-18T14:13:14.000Z
|
2022-03-18T14:13:14.000Z
|
// @HEADER
// ***********************************************************************
//
// Teuchos: Common Tools Package
// Copyright (2004) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ***********************************************************************
// @HEADER
#ifndef TEUCHOS_ARRAY_VIEW_DECL_HPP
#define TEUCHOS_ARRAY_VIEW_DECL_HPP
#include "Teuchos_RCPNode.hpp"
#include "Teuchos_ENull.hpp"
#include "Teuchos_NullIteratorTraits.hpp"
#include "Teuchos_ConstTypeTraits.hpp"
namespace Teuchos {
template<class T> class ArrayRCP;
/** \brief Array view class.
*
* This class is designed to be used as a substitute for array arguments to
* functions. It aggregates a pointer to a contiguous array of data and the
* size of that array. In debug mode, it will perform runtime checks of all
* usage.
*
* The <tt>ArrayView</tt> class has the same shallow copy semantics of the #
* <tt>Ptr</tt> class. <tt>ArrayView</tt> is to <tt>ArrayRCP</tt> as
* <tt>Ptr</tt> is to <tt>RCP</tt>.
*
* \section Teuchos_ArrayView_DesignDiscussion_sec Design Discussion
*
* This class is setup to allow derived classes that can only be allocated on
* the stack.
*
* \ingroup teuchos_mem_mng_grp
*/
template<class T>
class ArrayView {
public:
/** \name std::vector typedefs */
//@{
/** \brief. */
typedef Teuchos_Ordinal Ordinal;
/** \brief . */
typedef Ordinal size_type;
/** \brief . */
typedef Ordinal difference_type;
/** \brief . */
typedef T value_type;
/** \brief . */
typedef T* pointer;
/** \brief . */
typedef const T* const_pointer;
/** \brief . */
typedef T& reference;
/** \brief . */
typedef const T& const_reference;
#ifdef HAVE_TEUCHOS_ARRAY_BOUNDSCHECK
/** \brief . */
typedef ArrayRCP<T> iterator;
/** \brief . */
typedef ArrayRCP<const T> const_iterator;
#else
/** \brief . */
typedef pointer iterator;
/** \brief . */
typedef const_pointer const_iterator;
#endif
//@}
//! @name Constructors/Destructors
//@{
/** \brief Initialize to NULL (implicitly or explicitly). */
ArrayView( ENull null_arg = null );
/** \brief Initialize view from raw memory.
*
* \param p [in] Pointer to array of typed memory of size <tt>size</tt>. If
* <tt>p==0</tt>, then <tt>*this</tt> is a null view. Note that the memory
* pointed to by <tt>p</tt> can not go away until this view object is
* destoryed!
*
* \param size [in] The size of the array that <tt>*this</tt> will represent
* pointer to by <tt>p</tt>. If <tt>p==0</tt> then <tt>size</tt> must be 0!
*
* Preconditions:<ul>
* <li>[<tt>p!=0</tt>] <tt>size > 0</tt>
* <li>[<tt>p==0</tt>] <tt>size == 0</tt>
* </ul>
*
* Postconditions:<ul>
* <li>???
* </ul>
*/
ArrayView( T* p, size_type size,
const ERCPNodeLookup rcpNodeLookup = RCP_ENABLE_NODE_LOOKUP );
/** \brief Initialize from another <tt>ArrayView<T></tt> object.
*
* After construction, <tt>this</tt> and <tt>array</tt> will reference the
* same array.
*
* This form of the copy constructor is required even though the
* below more general templated version is sufficient since some
* compilers will generate this function automatically which will
* give an incorrect implementation.
*
* Postconditions:<ul>
* <li>???
* </ul>
*/
ArrayView(const ArrayView<T>& array);
/** \brief Non-const view of an std::vector<T> .*/
ArrayView(
std::vector<typename ConstTypeTraits<T>::NonConstType>& vec
);
/** \brief Const view of an std::vector<T> .*/
ArrayView(
const std::vector<typename ConstTypeTraits<T>::NonConstType>& vec
);
/** \brief Shallow copy assignment operator. */
ArrayView<T>& operator=(const ArrayView<T>& array);
/** \brief Destroy the array view object.
*/
~ArrayView();
//@}
//! @name General query functions
//@{
/** \brief Returns true if the underlying pointer is null. */
bool is_null() const;
/** \brief The total number of items in the managed array. */
size_type size() const;
/** \brief Convert an ArrayView<T> to an <tt>std::string</tt> */
std::string toString() const;
//@}
//! @name Element Access Functions
//@{
/** \brief Return a raw pointer to beginning of array or NULL if unsized. */
inline T* getRawPtr() const;
/** \brief Random object access.
*
* <b>Preconditions:</b><ul>
* <li><tt>this->get() != NULL</tt>
* <li><tt>0 <= i && i < this->size()</tt>
* </ul>
*/
T& operator[](size_type i) const;
/** \brief Get the first element. */
T& front() const;
/** \brief Get the last element. */
T& back() const;
//@}
//! @name Views
//@{
/** \brief Return a view of a contiguous range of elements.
*
* <b>Preconditions:</b><ul>
* <li><tt>this->get() != NULL</tt>
* <li><tt>0 <= offset && offset + size <= this->size()</tt>
* </ul>
*
* <b>Postconditions:</b><ul>
* <li><tt>returnVal.size() == size</tt>
* </ul>
*
* NOTE: A <tt>size==0</tt> view of even a null ArrayView is allowed and
* returns a <tt>null</tt> view.
*/
ArrayView<T> view( size_type offset, size_type size ) const;
/** \brief Return a view of a contiguous range of elements (calls
* view(offset, size)).
*/
ArrayView<T> operator()( size_type offset, size_type size ) const;
/** \brief Return a *this (just for compatibility with Array and ArrayPtr)
*/
const ArrayView<T>& operator()() const;
/** \brief Return an ArrayView<const T> of an ArrayView<T> object.
*
* WARNING! If <tt>T</tt> is already const (e.g. <tt>const double</tt>)
* then do not try to instantiate this function since it will not compile!
*/
ArrayView<const T> getConst() const;
// 2009/06/30: rabartl: Disable Intel compiler warning #597 about the function
// below not ever being called. This is a bogus warning and if you comment
// out this function, the Teuchos unit tests for this class will not compile
// (see Trilinos bug 4457).
#ifdef __INTEL_COMPILER
# pragma warning(disable : 597)
#endif
/** \brief Impliict conversion from ArrayView<T> to ArrayView<const T>.
*
* WARNING! If <tt>T</tt> is already const (e.g. <tt>const double</tt>)
* then do not try to instantiate this function since it will not compile!
*/
operator ArrayView<const T>() const;
//@}
/** \name Assignment */
//@{
/** \brief Copy the data from one array view object to this array view
* object.
*
* <b>Preconditions:</b><ul>
* <li><tt>this->size() == array.size()</tt>
* </ul>
*
* WARNING! If <tt>T</tt> is a const type (e.g. <tt>const double</tt>) then
* do not try to instantiate this function since it will not compile!
*
* NOTE: This function is really like an operator=() function except that it
* is declared const. This is the correct behavior since a const ArrayView
* simply means that we can not change what *this points to. The type of
* the template argument always determines if the underlyihng data is const
* or not.
*/
void assign(const ArrayView<const T>& array) const;
//@}
//! @name Standard Container-Like Functions
//@{
/** \brief Return an iterator to beginning of the array of data.
*
* If <tt>HAVE_TEUCHOS_ARRAY_BOUNDSCHECK</tt> is defined then the iterator
* returned is an <tt>ArrayRCP<T></tt> object and all operations are
* checked at runtime. When <tt>HAVE_TEUCHOS_ARRAY_BOUNDSCHECK</tt> is not
* defined, the a raw pointer <tt>T*</tt> is returned for fast execution.
*
* <b>Postconditions:</b><ul>
* <li>[this->get()!=NULL</tt>] <tt>&*return == this->get()</tt>
* <li>[<tt>this->get()==NULL</tt>] <tt>return == (null or NULL)</tt>
* </ul>
*/
iterator begin() const;
/** \brief Return an iterator to past the end of the array of data.
*
* If <tt>HAVE_TEUCHOS_ARRAY_BOUNDSCHECK</tt> is defined then the iterator
* returned is an <tt>ArrayView<T></tt> object and all operations are
* checked at runtime. When <tt>HAVE_TEUCHOS_ARRAY_BOUNDSCHECK</tt> is not
* defined, the a raw pointer <tt>T*</tt> is returned for fast execution.
*
* <b>Postconditions:</b><ul>
* <li>[<tt>this->get()!=NULL</tt>] <tt>&*end == this->get()+(this->upperOffset()+1)</tt>
* <li>[<tt>this->get()==NULL</tt>] <tt>return == (null or NULL)</tt>
* </ul>
*/
iterator end() const;
//@}
//! @name Assertion Functions.
//@{
/** \brief Throws <tt>NullReferenceError</tt> if <tt>this->get()==NULL</tt>,
* otherwise returns reference to <tt>*this</tt>.
*/
const ArrayView<T>& assert_not_null() const;
/** \brief Throws <tt>NullReferenceError</tt> if <tt>this->get()==NULL</tt>
* or<tt>this->get()!=NULL</tt>, throws <tt>RangeError</tt> if <tt>(offset < 0 ||
* this->size() < offset+size</tt>, otherwise returns reference to <tt>*this</tt>
*/
const ArrayView<T>& assert_in_range( size_type offset, size_type size ) const;
//@}
#ifdef HAVE_TEUCHOS_ARRAY_BOUNDSCHECK
// I should make these private but templated friends are not very portable.
// Besides, if a client directly calls this it will not compile in an
// optimized build.
explicit ArrayView( const ArrayRCP<T> &arcp );
explicit ArrayView( T* p, size_type size, const ArrayRCP<T> &arcp );
#endif
private:
// ///////////////////////
// Private data members
T *ptr_;
int size_;
#ifdef HAVE_TEUCHOS_ARRAY_BOUNDSCHECK
ArrayRCP<T> arcp_;
#endif
void setUpIterators(const ERCPNodeLookup rcpNodeLookup = RCP_ENABLE_NODE_LOOKUP);
// ///////////////////////
// Private member functions
void debug_assert_not_null() const
{
#ifdef HAVE_TEUCHOS_ARRAY_BOUNDSCHECK
assert_not_null();
#endif
}
void debug_assert_in_range( size_type offset, size_type size_in ) const
{
(void)offset; (void)size_in;
#ifdef HAVE_TEUCHOS_ARRAY_BOUNDSCHECK
assert_in_range(offset, size_in);
#endif
}
void debug_assert_valid_ptr() const
{
#ifdef HAVE_TEUCHOS_ARRAY_BOUNDSCHECK
arcp_.access_private_node().assert_valid_ptr(*this);
#endif
}
public: // Bad bad bad
// This is a very bad breach of encapsulation but it exists to avoid
// problems with portability of tempalted friends
T* access_private_ptr() const
{ return ptr_; }
#ifdef HAVE_TEUCHOS_ARRAY_BOUNDSCHECK
ArrayRCP<T> access_private_arcp() const
{ return arcp_; }
#endif
};
/** \brief Construct a const or non-const view to const or non-const data.
*
* \relates ArrayView
*/
template<class T>
ArrayView<T> arrayView( T* p, typename ArrayView<T>::size_type size );
/** \brief Construct a non-const view of an std::vector.
*
* \relates ArrayView
*/
template<class T>
ArrayView<T> arrayViewFromVector( std::vector<T>& vec );
/** \brief Construct a const view of an std::vector.
*
* \relates ArrayView
*/
template<class T>
ArrayView<const T> arrayViewFromVector( const std::vector<T>& vec );
#ifndef __sun
// 2007/11/30: From some reason, the Sun C++ compile on sass9000 compains that
// a call to this function below is ambiguous. However, if you just comment
// the function out, then the code on g++ (3.4.6 at least) will not compile.
// Therefore, I have no choice but to put in a hacked ifdef for the sun.
/** \brief Get a new <tt>std::vector<T></tt> object out of an
* <tt>ArrayView<T></tt> object.
*
* Note that a copy of data is made!
*
* \relates ArrayView
*/
template<class T>
std::vector<T> createVector( const ArrayView<T> &av );
#endif // __sun
/** \brief Get a new <tt>std::vector<T></tt> object out of an
* <tt>ArrayView<const T></tt> object.
*
* Note that a copy of data is made!
*
* \relates ArrayView
*/
template<class T>
std::vector<T> createVector( const ArrayView<const T> &av );
/** \brief Returns true if <tt>av.is_null()==true</tt>.
*
* \relates ArrayView
*/
template<class T>
bool is_null( const ArrayView<T> &av );
/** \brief Returns true if <tt>av.get()!=NULL</tt>.
*
* \relates ArrayView
*/
template<class T>
bool nonnull( const ArrayView<T> &av );
/** \brief Output stream inserter.
*
* The implementation of this function just prints pointer addresses and
* therefore puts no restrictions on the data types involved.
*
* \relates ArrayView
*/
template<class T>
std::ostream& operator<<( std::ostream& out, const ArrayView<T>& av );
/** \brief Const cast of underlying <tt>ArrayView</tt> type from <tt>const T*</tt>
* to <tt>T*</tt>.
*
* The function will compile only if (<tt>const_cast<T2*>(p1.get());</tt>)
* compiles.
*
* \relates ArrayView
*/
template<class T2, class T1>
ArrayView<T2> av_const_cast(const ArrayView<T1>& p1);
/** \brief Reinterpret cast of underlying <tt>ArrayView</tt> type from
* <tt>T1*</tt> to <tt>T2*</tt>.
*
* The function will compile only if (<tt>reinterpret_cast<T2*>(p1.get());</tt>) compiles.
*
* <b>Warning!</b> Do not use this function unless you absolutely know what
* you are doing. Doing a reinterpret cast is always a tricking thing and
* must only be done by developers who are 100% comfortable with what they are
* doing.
*
* \relates ArrayView
*/
template<class T2, class T1>
ArrayView<T2> av_reinterpret_cast(const ArrayView<T1>& p1);
} // end namespace Teuchos
//
// Inline members
//
// ToDo: Fill in!
#endif // TEUCHOS_ARRAY_VIEW_DECL_HPP
| 28.283554
| 91
| 0.662478
|
seakers
|
e69c6bea04a01f6f89963ff6a688ded77cbf26d1
| 3,279
|
hpp
|
C++
|
Test/TestCommon/TestFunction.hpp
|
SpaceGameEngine/SpaceGameEngine
|
cc7bbadbc3ed9577d1d6c9b4470d2c4926ed5ef8
|
[
"Apache-2.0"
] | 3
|
2019-11-25T04:08:44.000Z
|
2020-08-13T09:53:43.000Z
|
Test/TestCommon/TestFunction.hpp
|
SpaceGameEngine/SpaceGameEngine
|
cc7bbadbc3ed9577d1d6c9b4470d2c4926ed5ef8
|
[
"Apache-2.0"
] | 3
|
2019-07-11T09:20:43.000Z
|
2021-01-17T10:21:22.000Z
|
Test/TestCommon/TestFunction.hpp
|
SpaceGameEngine/SpaceGameEngine
|
cc7bbadbc3ed9577d1d6c9b4470d2c4926ed5ef8
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2021 creatorlxd
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.
*/
#pragma once
#include "Function.hpp"
#include "gtest/gtest.h"
using namespace SpaceGameEngine;
void func_(int i)
{
}
void func_2(int i, int i2)
{
}
int func_3(int i, int i2)
{
return 0;
}
struct functor
{
int operator()()
{
return 1;
}
};
struct test_func_class
{
int test()
{
return 1;
}
int test2() const
{
return 2;
}
};
TEST(Function, IsCorrectFunctionTest)
{
ASSERT_TRUE((IsCorrectFunction<decltype(func_), void(int)>::Value));
ASSERT_FALSE((IsCorrectFunction<decltype(func_2), void(int)>::Value));
ASSERT_TRUE((IsCorrectFunction<decltype(func_2), void(int, int)>::Value));
ASSERT_FALSE((IsCorrectFunction<decltype(func_3), void(int, int)>::Value));
ASSERT_TRUE((IsCorrectFunction<decltype(func_3), int(int, int)>::Value));
ASSERT_TRUE((IsCorrectFunction<functor, int(void)>::Value));
ASSERT_FALSE((IsCorrectFunction<int, void()>::Value));
ASSERT_TRUE((IsCorrectFunction<decltype(&test_func_class::test), int(test_func_class*)>::Value));
ASSERT_TRUE((IsCorrectFunction<decltype(&test_func_class::test2), int(const test_func_class*)>::Value));
}
TEST(Function, IsFunctionTest)
{
Function<void()> func([]() {});
ASSERT_TRUE(Function<void()>::IsFunction<decltype(func)>::Value);
ASSERT_TRUE(!Function<void()>::IsFunction<int>::Value);
}
TEST(Function, ConstructionTest)
{
auto lambda = [](void) -> int { return 1; };
Function<int(void)> func(lambda);
ASSERT_TRUE((int (*)(void))lambda == (int (*)(void))func.Get<decltype(lambda)>());
ASSERT_TRUE(lambda() == func());
Function<int(void)> func2 = func;
ASSERT_TRUE((int (*)(void))func2.Get<decltype(lambda)>() ==
(int (*)(void))func.Get<decltype(lambda)>());
Function<int(void)> func3([]() -> int { return 2; });
func3 = func2;
ASSERT_TRUE(func3() == func2());
Function<void(int)> func5 = &func_; // use function pointer
ASSERT_TRUE(func5.Get<decltype(&func_)>() == &func_);
Function<int(test_func_class*)> func6 = &test_func_class::test;
test_func_class tc;
ASSERT_TRUE(func6(&tc) == tc.test());
Function<int(void)> func7 = functor();
ASSERT_TRUE(func7() == functor()()); // use functor
Function<int(int)> func8 = [](int i) { return i; };
ASSERT_TRUE(func8(1) == 1);
}
TEST(Function, MetaDataTest)
{
Function<void(int)> func(&func_);
ASSERT_TRUE(func.GetMetaData() == GetMetaData<decltype(&func_)>());
}
TEST(Function, ComparisionTest)
{
Function<void(int)> func(&func_);
Function<void(int)> func2 = func;
ASSERT_EQ(func, func2);
}
TEST(Function, CopyTest)
{
Function<void(int)> func(&func_);
Function<void(int), MemoryManagerAllocator> func2([](int) -> void {});
Function<void(int), StdAllocator> func3([](int) -> void {});
func2 = func;
func3 = func2;
ASSERT_EQ(func, func2);
ASSERT_EQ(func2, func3);
}
| 29.017699
| 105
| 0.705398
|
SpaceGameEngine
|
e69e9d7b12708f9aaa96c03cfcc653303225302b
| 16,151
|
hpp
|
C++
|
include/codegen/include/GlobalNamespace/LevelSelectionNavigationController.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/GlobalNamespace/LevelSelectionNavigationController.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/GlobalNamespace/LevelSelectionNavigationController.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: HMUI.NavigationController
#include "HMUI/NavigationController.hpp"
// Including type: StandardLevelDetailViewController/ContentType
#include "GlobalNamespace/StandardLevelDetailViewController.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: LoadingControl
class LoadingControl;
// Forward declaring type: LevelCollectionViewController
class LevelCollectionViewController;
// Forward declaring type: LevelPackDetailViewController
class LevelPackDetailViewController;
// Skipping declaration: StandardLevelDetailViewController because it is already included!
// Forward declaring type: AppStaticSettingsSO
class AppStaticSettingsSO;
// Forward declaring type: IBeatmapLevelPack
class IBeatmapLevelPack;
// Forward declaring type: IBeatmapLevel
class IBeatmapLevel;
// Forward declaring type: IDifficultyBeatmap
class IDifficultyBeatmap;
// Forward declaring type: IPreviewBeatmapLevel
class IPreviewBeatmapLevel;
// Forward declaring type: IAnnotatedBeatmapLevelCollection
class IAnnotatedBeatmapLevelCollection;
// Forward declaring type: IBeatmapLevelCollection
class IBeatmapLevelCollection;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: GameObject
class GameObject;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: LevelSelectionNavigationController
class LevelSelectionNavigationController : public HMUI::NavigationController {
public:
// Nested type: GlobalNamespace::LevelSelectionNavigationController::$$c__DisplayClass42_0
class $$c__DisplayClass42_0;
// private LoadingControl _loadingControl
// Offset: 0x90
GlobalNamespace::LoadingControl* loadingControl;
// private LevelCollectionViewController _levelCollectionViewController
// Offset: 0x98
GlobalNamespace::LevelCollectionViewController* levelCollectionViewController;
// private LevelPackDetailViewController _levelPackDetailViewController
// Offset: 0xA0
GlobalNamespace::LevelPackDetailViewController* levelPackDetailViewController;
// private StandardLevelDetailViewController _levelDetailViewController
// Offset: 0xA8
GlobalNamespace::StandardLevelDetailViewController* levelDetailViewController;
// private AppStaticSettingsSO _appStaticSettings
// Offset: 0xB0
GlobalNamespace::AppStaticSettingsSO* appStaticSettings;
// private System.Action`2<LevelSelectionNavigationController,StandardLevelDetailViewController/ContentType> didPresentDetailContentEvent
// Offset: 0xB8
System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::StandardLevelDetailViewController::ContentType>* didPresentDetailContentEvent;
// private System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> didSelectLevelPackEvent
// Offset: 0xC0
System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* didSelectLevelPackEvent;
// private System.Action`1<LevelSelectionNavigationController> didPressPlayButtonEvent
// Offset: 0xC8
System::Action_1<GlobalNamespace::LevelSelectionNavigationController*>* didPressPlayButtonEvent;
// private System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> didPressOpenPackButtonEvent
// Offset: 0xD0
System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* didPressOpenPackButtonEvent;
// private System.Action`2<LevelSelectionNavigationController,IBeatmapLevel> didPressPracticeButtonEvent
// Offset: 0xD8
System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevel*>* didPressPracticeButtonEvent;
// private System.Action`2<LevelSelectionNavigationController,IDifficultyBeatmap> didChangeDifficultyBeatmapEvent
// Offset: 0xE0
System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IDifficultyBeatmap*>* didChangeDifficultyBeatmapEvent;
// private System.Boolean _showPlayerStatsInDetailView
// Offset: 0xE8
bool showPlayerStatsInDetailView;
// private System.Boolean _showPracticeButtonInDetailView
// Offset: 0xE9
bool showPracticeButtonInDetailView;
// private IBeatmapLevelPack _levelPack
// Offset: 0xF0
GlobalNamespace::IBeatmapLevelPack* levelPack;
// private IPreviewBeatmapLevel _beatmapLevelToBeSelectedAfterPresent
// Offset: 0xF8
GlobalNamespace::IPreviewBeatmapLevel* beatmapLevelToBeSelectedAfterPresent;
// public System.Void add_didPresentDetailContentEvent(System.Action`2<LevelSelectionNavigationController,StandardLevelDetailViewController/ContentType> value)
// Offset: 0xBF6CE8
void add_didPresentDetailContentEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::StandardLevelDetailViewController::ContentType>* value);
// public System.Void remove_didPresentDetailContentEvent(System.Action`2<LevelSelectionNavigationController,StandardLevelDetailViewController/ContentType> value)
// Offset: 0xBF7438
void remove_didPresentDetailContentEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::StandardLevelDetailViewController::ContentType>* value);
// public System.Void add_didSelectLevelPackEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> value)
// Offset: 0xBF6AFC
void add_didSelectLevelPackEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* value);
// public System.Void remove_didSelectLevelPackEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> value)
// Offset: 0xBF724C
void remove_didSelectLevelPackEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* value);
// public System.Void add_didPressPlayButtonEvent(System.Action`1<LevelSelectionNavigationController> value)
// Offset: 0xBF6BA0
void add_didPressPlayButtonEvent(System::Action_1<GlobalNamespace::LevelSelectionNavigationController*>* value);
// public System.Void remove_didPressPlayButtonEvent(System.Action`1<LevelSelectionNavigationController> value)
// Offset: 0xBF72F0
void remove_didPressPlayButtonEvent(System::Action_1<GlobalNamespace::LevelSelectionNavigationController*>* value);
// public System.Void add_didPressOpenPackButtonEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> value)
// Offset: 0xBF6D8C
void add_didPressOpenPackButtonEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* value);
// public System.Void remove_didPressOpenPackButtonEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> value)
// Offset: 0xBF74DC
void remove_didPressOpenPackButtonEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* value);
// public System.Void add_didPressPracticeButtonEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevel> value)
// Offset: 0xBF6C44
void add_didPressPracticeButtonEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevel*>* value);
// public System.Void remove_didPressPracticeButtonEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevel> value)
// Offset: 0xBF7394
void remove_didPressPracticeButtonEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevel*>* value);
// public System.Void add_didChangeDifficultyBeatmapEvent(System.Action`2<LevelSelectionNavigationController,IDifficultyBeatmap> value)
// Offset: 0xBF6A58
void add_didChangeDifficultyBeatmapEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IDifficultyBeatmap*>* value);
// public System.Void remove_didChangeDifficultyBeatmapEvent(System.Action`2<LevelSelectionNavigationController,IDifficultyBeatmap> value)
// Offset: 0xBF71A8
void remove_didChangeDifficultyBeatmapEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IDifficultyBeatmap*>* value);
// public IDifficultyBeatmap get_selectedDifficultyBeatmap()
// Offset: 0xBF787C
GlobalNamespace::IDifficultyBeatmap* get_selectedDifficultyBeatmap();
// public System.Void SetData(IAnnotatedBeatmapLevelCollection annotatedBeatmapLevelCollection, System.Boolean showPackHeader, System.Boolean showPlayerStats, System.Boolean showPracticeButton, UnityEngine.GameObject noDataInfoPrefab)
// Offset: 0xBF7B40
void SetData(GlobalNamespace::IAnnotatedBeatmapLevelCollection* annotatedBeatmapLevelCollection, bool showPackHeader, bool showPlayerStats, bool showPracticeButton, UnityEngine::GameObject* noDataInfoPrefab);
// public System.Void SelectLevel(IPreviewBeatmapLevel beatmapLevel)
// Offset: 0xBF6E30
void SelectLevel(GlobalNamespace::IPreviewBeatmapLevel* beatmapLevel);
// private System.Void SetData(IBeatmapLevelPack levelPack, System.Boolean showPackHeader, System.Boolean showPlayerStats, System.Boolean showPracticeButton)
// Offset: 0xBF8654
void SetData(GlobalNamespace::IBeatmapLevelPack* levelPack, bool showPackHeader, bool showPlayerStats, bool showPracticeButton);
// private System.Void SetData(IBeatmapLevelCollection beatmapLevelCollection, System.Boolean showPlayerStats, System.Boolean showPracticeButton, UnityEngine.GameObject noDataInfoPrefab)
// Offset: 0xBF8874
void SetData(GlobalNamespace::IBeatmapLevelCollection* beatmapLevelCollection, bool showPlayerStats, bool showPracticeButton, UnityEngine::GameObject* noDataInfoPrefab);
// public System.Void ShowLoading()
// Offset: 0xBF78B0
void ShowLoading();
// private System.Void PresentViewControllersForPack()
// Offset: 0xBF8900
void PresentViewControllersForPack();
// private System.Void PresentViewControllersForLevelCollection()
// Offset: 0xBF8A78
void PresentViewControllersForLevelCollection();
// private System.Void HideLoading()
// Offset: 0xBF8B8C
void HideLoading();
// private System.Void HideDetailViewController()
// Offset: 0xBF8D78
void HideDetailViewController();
// private System.Void HandleLevelCollectionViewControllerDidSelectLevel(LevelCollectionViewController viewController, IPreviewBeatmapLevel level)
// Offset: 0xBF9388
void HandleLevelCollectionViewControllerDidSelectLevel(GlobalNamespace::LevelCollectionViewController* viewController, GlobalNamespace::IPreviewBeatmapLevel* level);
// private System.Void HandleLevelCollectionViewControllerDidSelectPack(LevelCollectionViewController viewController)
// Offset: 0xBF9434
void HandleLevelCollectionViewControllerDidSelectPack(GlobalNamespace::LevelCollectionViewController* viewController);
// private System.Void PresentDetailViewController(HMUI.ViewController viewController, System.Boolean immediately)
// Offset: 0xBF8BA4
void PresentDetailViewController(HMUI::ViewController* viewController, bool immediately);
// private System.Void HandleLevelDetailViewControllerDidPressPlayButton(StandardLevelDetailViewController viewController)
// Offset: 0xBF94CC
void HandleLevelDetailViewControllerDidPressPlayButton(GlobalNamespace::StandardLevelDetailViewController* viewController);
// private System.Void HandleLevelDetailViewControllerDidPressPracticeButton(StandardLevelDetailViewController viewController, IBeatmapLevel level)
// Offset: 0xBF9530
void HandleLevelDetailViewControllerDidPressPracticeButton(GlobalNamespace::StandardLevelDetailViewController* viewController, GlobalNamespace::IBeatmapLevel* level);
// private System.Void HandleLevelDetailViewControllerDidChangeDifficultyBeatmap(StandardLevelDetailViewController viewController, IDifficultyBeatmap beatmap)
// Offset: 0xBF95A8
void HandleLevelDetailViewControllerDidChangeDifficultyBeatmap(GlobalNamespace::StandardLevelDetailViewController* viewController, GlobalNamespace::IDifficultyBeatmap* beatmap);
// private System.Void HandleLevelDetailViewControllerDidPresentContent(StandardLevelDetailViewController viewController, StandardLevelDetailViewController/ContentType contentType)
// Offset: 0xBF9620
void HandleLevelDetailViewControllerDidPresentContent(GlobalNamespace::StandardLevelDetailViewController* viewController, GlobalNamespace::StandardLevelDetailViewController::ContentType contentType);
// private System.Void HandleLevelDetailViewControllerDidPressOpenLevelPackButton(StandardLevelDetailViewController viewController, IBeatmapLevelPack levelPack)
// Offset: 0xBF9698
void HandleLevelDetailViewControllerDidPressOpenLevelPackButton(GlobalNamespace::StandardLevelDetailViewController* viewController, GlobalNamespace::IBeatmapLevelPack* levelPack);
// private System.Void HandleLevelDetailViewControllerLevelFavoriteStatusDidChange(StandardLevelDetailViewController viewController, System.Boolean favoriteStatus)
// Offset: 0xBF9710
void HandleLevelDetailViewControllerLevelFavoriteStatusDidChange(GlobalNamespace::StandardLevelDetailViewController* viewController, bool favoriteStatus);
// public System.Void RefreshDetail()
// Offset: 0xBF8420
void RefreshDetail();
// protected override System.Void DidActivate(System.Boolean firstActivation, HMUI.ViewController/ActivationType activationType)
// Offset: 0xBF8DDC
// Implemented from: HMUI.ViewController
// Base method: System.Void ViewController::DidActivate(System.Boolean firstActivation, HMUI.ViewController/ActivationType activationType)
void DidActivate(bool firstActivation, HMUI::ViewController::ActivationType activationType);
// protected override System.Void DidDeactivate(HMUI.ViewController/DeactivationType deactivationType)
// Offset: 0xBF90C8
// Implemented from: HMUI.ViewController
// Base method: System.Void ViewController::DidDeactivate(HMUI.ViewController/DeactivationType deactivationType)
void DidDeactivate(HMUI::ViewController::DeactivationType deactivationType);
// public System.Void .ctor()
// Offset: 0xBF972C
// Implemented from: HMUI.NavigationController
// Base method: System.Void NavigationController::.ctor()
// Base method: System.Void ContainerViewController::.ctor()
// Base method: System.Void ViewController::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static LevelSelectionNavigationController* New_ctor();
}; // LevelSelectionNavigationController
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::LevelSelectionNavigationController*, "", "LevelSelectionNavigationController");
#pragma pack(pop)
| 68.147679
| 238
| 0.815925
|
Futuremappermydud
|
e69ff09b9fe3e439dfdf90160d2aa3aeeea5129e
| 3,967
|
hpp
|
C++
|
src/device_model/device.hpp
|
bburns/cppagent
|
c1891c631465ebc9b63a4b3c627727ca3da14ee8
|
[
"Apache-2.0"
] | null | null | null |
src/device_model/device.hpp
|
bburns/cppagent
|
c1891c631465ebc9b63a4b3c627727ca3da14ee8
|
[
"Apache-2.0"
] | null | null | null |
src/device_model/device.hpp
|
bburns/cppagent
|
c1891c631465ebc9b63a4b3c627727ca3da14ee8
|
[
"Apache-2.0"
] | null | null | null |
//
// Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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.
//
#pragma once
#include <map>
#include <unordered_map>
#include "component.hpp"
#include "data_item/data_item.hpp"
#include "utilities.hpp"
namespace mtconnect {
namespace source::adapter {
class Adapter;
}
namespace device_model {
class Device : public Component
{
public:
// Constructor that sets variables from an attribute map
Device(const std::string &name, entity::Properties &props);
~Device() override = default;
auto getptr() const { return std::dynamic_pointer_cast<Device>(Entity::getptr()); }
void initialize() override
{
Component::initialize();
buildDeviceMaps(getptr());
resolveReferences(getptr());
}
static entity::FactoryPtr getFactory();
static entity::FactoryPtr getRoot();
void setOptions(const ConfigOptions &options);
// Add/get items to/from the device name to data item mapping
void addDeviceDataItem(DataItemPtr dataItem);
DataItemPtr getDeviceDataItem(const std::string &name) const;
void addAdapter(source::adapter::Adapter *anAdapter) { m_adapters.emplace_back(anAdapter); }
ComponentPtr getComponentById(const std::string &aId) const
{
auto comp = m_componentsById.find(aId);
if (comp != m_componentsById.end())
return comp->second.lock();
else
return nullptr;
}
void addComponent(ComponentPtr aComponent)
{
m_componentsById.insert(make_pair(aComponent->getId(), aComponent));
}
DevicePtr getDevice() const override { return getptr(); }
// Return the mapping of Device to data items
const auto &getDeviceDataItems() const { return m_deviceDataItemsById; }
void addDataItem(DataItemPtr dataItem, entity::ErrorList &errors) override;
std::vector<source::adapter::Adapter *> m_adapters;
auto getMTConnectVersion() const { maybeGet<std::string>("mtconnectVersion"); }
// Cached data items
DataItemPtr getAvailability() const { return m_availability; }
DataItemPtr getAssetChanged() const { return m_assetChanged; }
DataItemPtr getAssetRemoved() const { return m_assetRemoved; }
void setPreserveUuid(bool v) { m_preserveUuid = v; }
bool preserveUuid() const { return m_preserveUuid; }
void registerDataItem(DataItemPtr di);
void registerComponent(ComponentPtr c) { m_componentsById[c->getId()] = c; }
protected:
void cachePointers(DataItemPtr dataItem);
protected:
bool m_preserveUuid {false};
DataItemPtr m_availability;
DataItemPtr m_assetChanged;
DataItemPtr m_assetRemoved;
// Mapping of device names to data items
std::unordered_map<std::string, std::weak_ptr<data_item::DataItem>> m_deviceDataItemsByName;
std::unordered_map<std::string, std::weak_ptr<data_item::DataItem>> m_deviceDataItemsById;
std::unordered_map<std::string, std::weak_ptr<data_item::DataItem>> m_deviceDataItemsBySource;
std::unordered_map<std::string, std::weak_ptr<Component>> m_componentsById;
};
using DevicePtr = std::shared_ptr<Device>;
} // namespace device_model
using DevicePtr = std::shared_ptr<device_model::Device>;
} // namespace mtconnect
| 34.798246
| 100
| 0.693471
|
bburns
|
e6a036880c3a3f663d89be8053627349388e1e82
| 2,439
|
cpp
|
C++
|
src/mesh/adjacent_table.cpp
|
ZJUCADGeoSim/hausdorff
|
df9fdf0294d7efd4ec694ec5135487344e509231
|
[
"MIT"
] | 13
|
2021-09-06T07:19:28.000Z
|
2022-03-29T15:48:21.000Z
|
src/mesh/adjacent_table.cpp
|
ZJUCADGeoSim/hausdorff
|
df9fdf0294d7efd4ec694ec5135487344e509231
|
[
"MIT"
] | null | null | null |
src/mesh/adjacent_table.cpp
|
ZJUCADGeoSim/hausdorff
|
df9fdf0294d7efd4ec694ec5135487344e509231
|
[
"MIT"
] | null | null | null |
/*
State Key Lab of CAD&CG Zhejiang Unv.
Author:
Yicun Zheng (3130104113@zju.edu.cn)
Haoran Sun (hrsun@zju.edu.cn)
Jin Huang (hj@cad.zju.edu.cn)
Copyright (c) 2004-2021 <Jin Huang>
All rights reserved.
Licensed under the MIT License.
*/
#include "adjacent_table.hpp"
using namespace zjucad::matrix;
bool get_neighbor_edge(const matrixst_t &prims, size_t p1, size_t p2, edge_t &e) {
size_t point_count = 0;
for (size_t vi = 0; vi < prims.size(1); ++vi) {
for (size_t vj = 0; vj < prims.size(1); ++vj) {
if (prims(vi, p1) == prims(vj, p2)) {
if (point_count == 0) {
e.first = prims(vi, p1);
} else if (point_count == 1) {
e.second = prims(vi, p1);
} else {
return false;
}
point_count++;
}
}
}
if (point_count != 2) {
return false;
} else {
return true;
}
}
void build_primitive_adjacent_table_from_mesh(const matrixd_t &v, const matrixst_t &prims, primitive_adjacent_table &table) {
// build vertex-primitives map
std::vector<std::vector<size_t>> vpmap(v.size(2));
for (size_t pi = 0; pi < prims.size(2); ++pi) {
for (size_t vi = 0; vi < prims.size(1); ++vi) {
vpmap[prims(vi, pi)].push_back(pi);
}
}
// iterate vertex to build primitive adjacent table
for (size_t i = 0; i < vpmap.size(); ++i) {
if (vpmap[i].size() <= 1)
continue;
for (size_t p1 = 0; p1 < vpmap[i].size(); ++p1) {
for (size_t p2 = p1 + 1; p2 < vpmap[i].size(); ++p2) {
edge_t e;
if (get_neighbor_edge(prims, vpmap[i][p1], vpmap[i][p2], e)) {
// std::cout << "prim " << prims(colon(), vpmap[i][p1]) << prims(colon(), vpmap[i][p2]) << std::endl;
// std::cout << "e: " << e.first << " " << e.second << std::endl;
table.table_.emplace(primitive_pair(vpmap[i][p1], vpmap[i][p2]), e);
}
}
}
}
// for(auto i = table.table_.begin(); i != table.table_.end(); ++i){
// std::cout << i->first.pair_.first << "-" << i->first.pair_.second << ": " << i->second.first << ", " << i->second.second << std::endl;
// }
// std::cout << "size: " << table.table_.size() << std::endl;
}
| 34.352113
| 145
| 0.497745
|
ZJUCADGeoSim
|
e6a4978f3667fb150541ef0fd3dd77dbb74beba1
| 1,601
|
cpp
|
C++
|
src/main.cpp
|
Benjins/simple-vm
|
ef31ea36ad698a47da81642c97d718d3415bd133
|
[
"CC-BY-4.0"
] | null | null | null |
src/main.cpp
|
Benjins/simple-vm
|
ef31ea36ad698a47da81642c97d718d3415bd133
|
[
"CC-BY-4.0"
] | null | null | null |
src/main.cpp
|
Benjins/simple-vm
|
ef31ea36ad698a47da81642c97d718d3415bd133
|
[
"CC-BY-4.0"
] | null | null | null |
#include "../header/VM.h"
#include "../header/Instruction.h"
#include "../header/Parser.h"
#include "../header/AST.h"
#include "../header/DLLFile.h"
#include <assert.h>
#include <iostream>
//#include <dlfcn.h>
using std::cout; using std::endl;
int main(int argc, char** argv){
#if TESTING
VM x;
bool allPass = true;
x.CompileAndLoadCode("examples/test2.svm");
x.SaveByteCode("examples/test2.svb");
x.LoadByteCode("examples/test2.svb");
allPass &= (x.Execute("main") == 5);
allPass &= (x.Execute("testOne") == 1);
allPass &= (x.Execute("testTwo") == 1);
allPass &= (x.Execute("testThree") == 0);
allPass &= (x.Execute("testFour") == 9);
cout << (allPass ? "allPass" : "some failed.") << endl;
return allPass ? 0 : 1;
#elif COMPILER //VM Compiler
if(argc < 2){
cout << "\nError: Must supply at least one input file.\n";
return -1;
}
char* fileNameC = argv[1];
string fileName = string(fileNameC);
vector<string> dllNames;
for(int i = 2; i < argc; i++){
char* dllNameC = argv[i];
string dllName = string(dllNameC);
dllNames.push_back(dllName);
}
VM x;
if(x.CompileAndLoadCode(fileName, &dllNames)){
x.SaveByteCode(fileName + ".svb");
x.LoadByteCode(fileName + ".svb");
x.Execute("main");
}
#else //VM runner
if(argc < 2){
cout << "\nError: Must supply at least one input file.\n";
return -1;
}
string fileName = string(argv[1]);
string functionName = (argc > 2) ? string(argv[2]) : "main";
VM x;
if(x.LoadByteCode(fileName)){
int retVal = x.Execute(functionName);
cout << "\nReturned: " << retVal << endl;
}
#endif
return 0;
}
| 21.065789
| 61
| 0.63273
|
Benjins
|
e6a94ff699f2a4401b126ee510999617cc827c1e
| 5,894
|
cpp
|
C++
|
Source/Motor2D/Wall.cpp
|
BarcinoLechiguino/Project_F
|
9e40c771f5ce6b821e3d380edd5d92fb129cdf53
|
[
"MIT"
] | 1
|
2020-04-28T16:09:51.000Z
|
2020-04-28T16:09:51.000Z
|
Source/Motor2D/Wall.cpp
|
Aitorlb7/Project_F
|
9e40c771f5ce6b821e3d380edd5d92fb129cdf53
|
[
"MIT"
] | 3
|
2020-03-03T09:57:49.000Z
|
2020-04-25T16:02:36.000Z
|
Source/Motor2D/Wall.cpp
|
BarcinoLechiguino/Project-RTS
|
9e40c771f5ce6b821e3d380edd5d92fb129cdf53
|
[
"MIT"
] | 1
|
2020-11-06T22:31:26.000Z
|
2020-11-06T22:31:26.000Z
|
#include "Application.h"
#include "Render.h"
#include "Textures.h"
#include "Audio.h"
#include "Map.h"
#include "Pathfinding.h"
#include "Player.h"
#include "GuiManager.h"
#include "GuiElement.h"
#include "GuiHealthbar.h"
#include "GuiCreationBar.h"
#include "FowManager.h"
#include "EntityManager.h"
#include "Wall.h"
Wall::Wall(int x, int y, ENTITY_TYPE type, int level) : Building(x, y, type, level)
{
InitEntity();
}
Wall::~Wall()
{
}
bool Wall::Awake(pugi::xml_node& config)
{
return true;
}
bool Wall::Start()
{
App->pathfinding->ChangeWalkability(tile_position, this, NON_WALKABLE);
return true;
}
bool Wall::PreUpdate()
{
return true;
}
bool Wall::Update(float dt, bool do_logic)
{
if (building_state == BUILDING_STATE::CONSTRUCTING)
{
ConstructBuilding();
}
// FOG OF WAR
is_visible = fow_entity->is_visible;
return true;
}
bool Wall::PostUpdate()
{
if (current_health <= 0)
{
App->entity_manager->DeleteEntity(this);
}
return true;
}
bool Wall::CleanUp()
{
App->pathfinding->ChangeWalkability(tile_position, this, WALKABLE); //The entity is cleared from the walkability map.
App->entity_manager->ChangeEntityMap(tile_position, this, true); //The entity is cleared from the entity_map.
entity_sprite = nullptr;
if (is_selected)
{
App->player->DeleteEntityFromBuffers(this);
}
App->gui_manager->DeleteGuiElement(healthbar);
App->fow_manager->DeleteFowEntity(fow_entity);
return true;
}
void Wall::Draw()
{
//App->render->Blit(entity_sprite, (int)pixel_position.x, (int)pixel_position.y - 20, &wall_rect); //Magic
if (construction_finished)
{
App->render->Blit(entity_sprite, (int)pixel_position.x + 2, (int)pixel_position.y + 2, NULL); //Magic
}
}
void Wall::LevelChanges()
{
switch (level)
{
case 1:
wall_rect = wall_rect_1;
break;
case 2:
wall_rect = wall_rect_2;
max_health = 750;
current_health = max_health;
//infantry_level++; // TALK ABOUT THIS
break;
default:
wall_rect = wall_rect_2;
break;
}
}
void Wall::ConstructBuilding()
{
if (!constructing_building)
{
creation_bar->is_visible = true;
creation_bar->SetNewCreationTime(construction_time);
fow_entity->provides_visibility = false;
constructing_building = true;
}
else
{
creation_bar->UpdateCreationBarValue();
for (int y = 0; y != tiles_occupied.y; ++y)
{
for (int x = 0; x != tiles_occupied.x; ++x)
{
int pos_y = tile_position.y + y;
int pos_x = tile_position.x + x;
iPoint draw_position = App->map->MapToWorld(pos_x, pos_y);
if (App->player->buildable_tile_tex != nullptr)
{
App->render->Blit(App->player->buildable_tile_tex, draw_position.x + 2, draw_position.y + 2, nullptr);
}
}
}
/*if (App->player->townhall_build_tex != nullptr)
{
SDL_SetTextureAlphaMod(App->player->wall_build_tex, (Uint8)(current_rate * 255.0f));
}*/
if (creation_bar->creation_finished)
{
fow_entity->provides_visibility = true;
building_state = BUILDING_STATE::IDLE;
construction_finished = true;
constructing_building = false;
}
}
}
void Wall::InitEntity()
{
// POSITION & SIZE
iPoint world_position = App->map->MapToWorld(tile_position.x, tile_position.y);
pixel_position.x = (float)world_position.x;
pixel_position.y = (float)world_position.y;
center_point = fPoint(pixel_position.x, pixel_position.y + App->map->data.tile_height);
tiles_occupied.x = 1;
tiles_occupied.y = 1;
// TEXTURE & SECTIONS
entity_sprite = App->entity_manager->GetWallTexture();
wall_rect_1 = { 0, 0, 106, 95 }; // NEED REVISION
wall_rect_2 = { 108, 0, 106, 95 };
wall_rect = wall_rect_1;
// FLAGS
is_selected = false;
// BUILDING CONSTRUCTION VARIABLES
construction_time = 5.0f;
// STATS
max_health = 500;
current_health = max_health;
// HEALTHBAR & CREATION BAR
if (App->entity_manager->CheckTileAvailability(tile_position, this))
{
AttachHealthbarToEntity();
AttachCreationBarToEntity();
}
// FOG OF WAR
is_visible = true;
is_neutral = false;
provides_visibility = true;
range_of_vision = 4;
fow_entity = App->fow_manager->CreateFowEntity(tile_position, is_neutral, provides_visibility);
//fow_entity->frontier = App->fow_manager->CreateRectangularFrontier(range_of_vision, range_of_vision, tile_position);
fow_entity->frontier = App->fow_manager->CreateCircularFrontier(range_of_vision, tile_position);
fow_entity->line_of_sight = App->fow_manager->GetLineOfSight(fow_entity->frontier);
}
void Wall::AttachHealthbarToEntity()
{
healthbar_position_offset.x = -30; //Magic
healthbar_position_offset.y = -6;
healthbar_background_rect = { 618, 1, MAX_BUILDING_HEALTHBAR_WIDTH, 9 };
healthbar_rect = { 618, 23, MAX_BUILDING_HEALTHBAR_WIDTH, 9 };
int healthbar_position_x = (int)pixel_position.x + healthbar_position_offset.x; // X and Y position of the healthbar's hitbox.
int healthbar_position_y = (int)pixel_position.y + healthbar_position_offset.y; // The healthbar's position is already calculated in GuiHealthbar.
healthbar = (GuiHealthbar*)App->gui_manager->CreateHealthbar(GUI_ELEMENT_TYPE::HEALTHBAR, healthbar_position_x, healthbar_position_y, true, &healthbar_rect, &healthbar_background_rect, this);
}
void Wall::AttachCreationBarToEntity()
{
creation_bar_position_offset.x = -30; // Magic
creation_bar_position_offset.y = 6;
creation_bar_background_rect = { 618, 1, MAX_CREATION_BAR_WIDTH, 9 };
creation_bar_rect = { 618, 23, MAX_CREATION_BAR_WIDTH, 9 };
int creation_bar_position_x = (int)pixel_position.x + creation_bar_position_offset.x;
int creation_bar_position_y = (int)pixel_position.y + creation_bar_position_offset.y;
creation_bar = (GuiCreationBar*)App->gui_manager->CreateCreationBar(GUI_ELEMENT_TYPE::CREATIONBAR, creation_bar_position_x, creation_bar_position_y, false
, &creation_bar_rect, &creation_bar_background_rect, this);
}
| 24.661088
| 192
| 0.725993
|
BarcinoLechiguino
|
e6aa28a55c657282a31df9acaf79c1edf228f159
| 3,171
|
cc
|
C++
|
charstream.cc
|
justinleona/capstone
|
4a525cad12fba07a43452776a0e289148f04a12d
|
[
"MIT"
] | 1
|
2021-06-26T05:32:43.000Z
|
2021-06-26T05:32:43.000Z
|
charstream.cc
|
justinleona/capstone
|
4a525cad12fba07a43452776a0e289148f04a12d
|
[
"MIT"
] | 2
|
2019-10-14T06:46:43.000Z
|
2019-10-18T04:34:20.000Z
|
charstream.cc
|
justinleona/capstone
|
4a525cad12fba07a43452776a0e289148f04a12d
|
[
"MIT"
] | null | null | null |
#include "charstream.h"
#include <iomanip>
#include "notimplemented.h"
using namespace std;
charbuf::charbuf(char* s, size_t n, size_t offset) : offset(offset) {
auto begin = s;
auto c = s;
auto end = s + n;
// set begin, current, and end states for reading
setg(begin, c, end);
setp(begin, end);
}
streampos charbuf::seekpos(streampos pos, ios_base::openmode which) {
const pos_type& rel = pos - pos_type(off_type(offset));
bool in = which & ios_base::openmode::_S_in;
cout << "seekpos(" << hex << pos << ", in=" << in << ")" << endl;
return seekoff(rel, ios_base::beg, which);
}
long repos(streamoff pos, char* begin, char* cur, char* end, ios_base::seekdir way) {
switch (way) {
case ios_base::beg:
return begin + pos - cur;
break;
case ios_base::cur:
return pos;
break;
case ios_base::end:
return end + pos - cur;
break;
default:
break;
}
return -1;
}
streampos charbuf::seekoff(streamoff pos, ios_base::seekdir way, ios_base::openmode which) {
bool in = which & ios_base::openmode::_S_in;
cout << "seekoff(" << hex << pos << "," << way << ", in=" << in << ")" << endl;
// no separate begin/end - single array in memory
char* begin = eback();
char* end = egptr();
long goff = repos(pos, begin, gptr(), end, way);
long poff = repos(pos, begin, pptr(), end, way);
char* cg = gptr() + goff;
char* cp = pptr() + poff;
// cout << "gptr=" << hex << (uint64_t)gptr() << " goffset=" << goff << endl;
bool set = false;
if (which & ios_base::in) {
if (begin <= cg && cg < end) {
gbump(goff);
set = true;
}
}
if (which & ios_base::out) {
if (begin <= cp && cp < end) {
pbump(poff);
set = true;
}
}
if (set) {
return gptr() - begin;
}
return -1;
}
// below are implemented so we know if we're using features we'd expect to provide but don't!
streambuf* charbuf::setbuf(char* s, streamsize n) {
// cerr << "setbuf not yet implemented" << endl;
throw not_implemented{"setbuf not yet implemented!"};
}
int charbuf::underflow() {
// cerr << "underflow not yet implemented" << endl;
throw not_implemented{"underflow not yet implemented!"};
}
int charbuf::pbackfail(int c) {
// cerr << "pbackfail not yet implemented" << endl;
throw not_implemented{"pbackfail not yet implemented!"};
}
int charbuf::overflow(int c) {
// cerr << "overflow not yet implemented" << endl;
throw not_implemented{"overflow not yet implemented!"};
}
charstream::charstream(char* s, size_t n, size_t offset) : istream(&b), ostream(&b), b(s, n, offset) {
rdbuf(&b);
}
charstream::charstream(uint8_t* s, size_t n, size_t offset) : charstream((char*)s, n, offset) {}
void dumpBytes(uint8_t bytes[], size_t size, uint64_t offset) {
cout << hex << setfill('0') << setw(8) << (unsigned int)offset << ": ";
for (uint64_t i = 0; i != size; ++i) {
if (i > 0 && i % 16 == 0)
cout << endl << hex << setfill('0') << setw(8) << (unsigned int)(i + offset) << ": ";
else if (i > 0 && i % 2 == 0)
cout << " ";
cout << hex << setfill('0') << setw(2) << (unsigned int)bytes[i];
}
cout << endl;
}
| 27.815789
| 102
| 0.595396
|
justinleona
|
e6afcc659277abe69decd9e30b055f3c75b1a6f6
| 4,007
|
cpp
|
C++
|
Essential Cpp/UserProfile.cpp
|
HuangJingGitHub/PracMakePert_C
|
94e570c55d9e391913ccd9c5c72026ab926809b2
|
[
"Apache-2.0"
] | 1
|
2019-10-17T03:13:29.000Z
|
2019-10-17T03:13:29.000Z
|
Essential Cpp/UserProfile.cpp
|
HuangJingGitHub/PracMakePert_C-Cpp
|
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
|
[
"Apache-2.0"
] | null | null | null |
Essential Cpp/UserProfile.cpp
|
HuangJingGitHub/PracMakePert_C-Cpp
|
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdlib>
#include <string>
#include <map>
#include <iostream>
using namespace std;
class UserProfile
{
public:
enum uLevel { Beginner, Intermediate, Advanced, Guru };
UserProfile(string login, uLevel = Beginner);
UserProfile();
bool operator==(const UserProfile&);
bool operator!=(const UserProfile &rhs);
string login() const { return _login;}
string user_name() const { return _user_name;}
int login_count() const { return _times_logged; }
int guess_count() const { return _guesses; }
int guess_correct() const {return _correct_guesses; }
double guess_average() const;
string level() const;
void reset_login(const string &val) { _login = val; }
void user_name(const string &val) { _user_name = val; }
void reset_level(const string&);
void reset_level(uLevel newLevel) { _user_level = newLevel; }
void reset_login_count(int val) { _times_logged = val; }
void reset_guess_count(int val) { _guesses = val; }
void reset_guess_correct(int val) { _correct_guesses = val; }
void bump_login_count(int cnt = 1) { _times_logged += cnt; }
void bump_guess_count(int cnt = 1) { _guesses += cnt; }
void bump_guess_correct(int cnt = 1) { _correct_guesses += cnt; }
private:
string _login;
string _user_name;
int _times_logged;
int _guesses;
int _correct_guesses;
uLevel _user_level;
static map<string, uLevel> _level_map;
static void init_level_map();
static string guest_login();
};
inline double UserProfile::guess_average() const
{
return _guesses ? double(_correct_guesses) / double(_guesses) * 100 : 0.0;
}
inline UserProfile::UserProfile(string login, uLevel level)
: _login(login), _user_level(level), _times_logged(1),
_guesses(0), _correct_guesses(0) {}
inline UserProfile::UserProfile()
:_login("guest"), _user_level(Beginner),
_times_logged(1), _guesses(0), _correct_guesses(0)
{
static int id = 0;
char buffer[16];
_itoa(id++, buffer, 10);
_login += buffer;
}
inline bool UserProfile::operator==(const UserProfile &rhs)
{
if (_login == rhs._login && _user_name == rhs._user_name)
return true;
return false;
}
inline bool UserProfile::operator!=(const UserProfile &rhs)
{
return !(*this == rhs);
}
inline string UserProfile::level() const
{
static string _level_table[] = {"Beginner", "Intermediate",
"Advanced", "Guru"};
return _level_table[_user_level]; // The way to return level is interesting
} // from enum to string, need transform...
ostream& operator<<(ostream &os, const UserProfile &rhs)
{
os << rhs.login() << ' '
<< rhs.level() << ' '
<< rhs.login_count() << ' '
<< rhs.guess_count() << ' '
<< rhs.guess_correct() << ' '
<< rhs.guess_average() << endl;
return os;
}
map<string, UserProfile::uLevel> UserProfile::_level_map;
void UserProfile::init_level_map()
{
_level_map["Beginner"] = Beginner;
_level_map["Intermediate"] = Intermediate;
_level_map["Advanced"] = Advanced;
_level_map["Guru"] = Guru;
}
inline void UserProfile::reset_level(const string &level)
{
map<string,uLevel>::iterator it;
if (_level_map.empty())
init_level_map();
_user_level = ((it = _level_map.find(level)) != _level_map.end())
? it->second : Beginner;
}
istream& operator>>(istream& is, UserProfile &rhs)
{
string login, level;
is >> login >> level;
int lcount, gcount, gcorrect;
is >> lcount >> gcount >> gcorrect;
rhs.reset_login(login);
rhs.reset_level(level);
rhs.reset_login_count(lcount);
rhs.reset_guess_count(gcount);
rhs.reset_guess_correct(gcorrect);
return is;
}
int main()
{
UserProfile anon;
cout << anon;
UserProfile anon_too;
cout << anon_too;
UserProfile anna("Annal", UserProfile::Guru);
cout << anna;
anna.bump_guess_count(27);
anna.bump_guess_correct(25);
anna.bump_login_count();
cout << anna;
cin >> anon;
cout << anon;
}
| 25.522293
| 79
| 0.664837
|
HuangJingGitHub
|
e6b2f4dcf87049372bc1672a82aeddf019ace903
| 4,286
|
cpp
|
C++
|
editor/gui/toolbar_dock.cpp
|
ChronicallySerious/Rootex
|
bf2a0997b6aa5be84dbfc0e7826c31ff693ca0f1
|
[
"MIT"
] | 166
|
2019-06-19T19:51:45.000Z
|
2022-03-24T13:03:29.000Z
|
editor/gui/toolbar_dock.cpp
|
rahil627/Rootex
|
44f827d469bddc7167b34dedf80d7a8b984fdf20
|
[
"MIT"
] | 312
|
2019-06-13T19:39:25.000Z
|
2022-03-02T18:37:22.000Z
|
editor/gui/toolbar_dock.cpp
|
rahil627/Rootex
|
44f827d469bddc7167b34dedf80d7a8b984fdf20
|
[
"MIT"
] | 23
|
2019-10-04T11:02:21.000Z
|
2021-12-24T16:34:52.000Z
|
#include "toolbar_dock.h"
#include "editor/editor_application.h"
#include "framework/scene_loader.h"
#include "framework/system.h"
#include "editor/editor_system.h"
#include "vendor/ImGUI/imgui.h"
#include "vendor/ImGUI/imgui_stdlib.h"
#include "vendor/ImGUI/imgui_impl_dx11.h"
#include "vendor/ImGUI/imgui_impl_win32.h"
Variant ToolbarDock::disablePlayInEditor(const Event* e)
{
m_InEditorPlaying = false;
EditorApplication::GetSingleton()->setGameMode(false);
if (!m_StartPlayingScene.empty())
{
SceneLoader::GetSingleton()->loadScene(m_StartPlayingScene, {});
m_StartPlayingScene.clear();
}
PRINT("Stopped Scene in Editor");
return true;
}
ToolbarDock::ToolbarDock()
{
m_Binder.bind(EditorEvents::EditorSceneIsClosing, this, &ToolbarDock::disablePlayInEditor);
m_Binder.bind(RootexEvents::QuitEditorWindow, this, &ToolbarDock::disablePlayInEditor);
m_FPSRecords.resize(m_FPSRecordsPoolSize, 0.0f);
}
void ToolbarDock::draw(float deltaMilliseconds)
{
ZoneScoped;
if (m_ToolbarDockSettings.m_IsActive)
{
if (ImGui::Begin("Toolbar"))
{
if (SceneLoader::GetSingleton()->getCurrentScene())
{
static int playModeSelected = 0;
static const char* playModes[3] = {
"Play Scene in Editor",
"Play Scene in Game",
"Play Game"
};
if (m_InEditorPlaying)
{
ImColor lightErrorColor = EditorSystem::GetSingleton()->getFatalColor();
lightErrorColor.Value.x *= 0.8f;
ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)lightErrorColor);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)(EditorSystem::GetSingleton()->getFatalColor()));
if (ImGui::Button("Stop " ICON_ROOTEX_WINDOW_CLOSE, { ImGui::GetContentRegionAvailWidth(), 40.0f }))
{
disablePlayInEditor(nullptr);
}
ImGui::PopStyleColor(2);
}
else
{
if (ImGui::Button("Play " ICON_ROOTEX_FORT_AWESOME, { ImGui::GetContentRegionAvailWidth(), 40.0f }))
{
switch (playModeSelected)
{
case 0:
m_InEditorPlaying = true;
m_StartPlayingScene = SceneLoader::GetSingleton()->getCurrentScene()->getScenePath();
EventManager::GetSingleton()->call(EditorEvents::EditorSaveAll);
EditorApplication::GetSingleton()->setGameMode(true);
SceneLoader::GetSingleton()->loadScene(m_StartPlayingScene, {});
PRINT("Loaded Scene in Editor");
break;
case 1:
m_InEditorPlaying = false;
EventManager::GetSingleton()->call(EditorEvents::EditorSaveAll);
OS::RunApplication("\"" + OS::GetGameExecutablePath() + "\" " + SceneLoader::GetSingleton()->getCurrentScene()->getScenePath());
PRINT("Launched Game process with Scene");
break;
case 2:
m_InEditorPlaying = false;
EventManager::GetSingleton()->call(EditorEvents::EditorSaveAll);
OS::RunApplication("\"" + OS::GetGameExecutablePath() + "\"");
PRINT("Launched Game process");
break;
default:
WARN("Unknown play mode found");
}
}
}
#ifdef TRACY_ENABLE
if (ImGui::Button("Start Tracy " ICON_ROOTEX_EXTERNAL_LINK " "))
{
OS::OpenFileInSystemEditor("rootex/vendor/Tracy/Tracy.exe");
}
ImGui::SameLine();
#endif // TRACY_ENABLE
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvailWidth());
if (ImGui::BeginCombo("##Play Mode", playModes[playModeSelected]))
{
for (int i = 0; i < sizeof(playModes) / sizeof(playModes[0]); i++)
{
if (ImGui::MenuItem(playModes[i]))
{
playModeSelected = i;
}
}
ImGui::EndCombo();
}
}
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvailWidth());
ImGui::SliderFloat("##Delta Multiplier", Application::GetSingleton()->getDeltaMultiplierPtr(), -2.0f, 2.0f, "");
if (ImGui::IsItemDeactivatedAfterEdit())
{
Application::GetSingleton()->resetDeltaMultiplier();
}
if (ImGui::TreeNodeEx("Editor"))
{
RootexFPSGraph("FPS", m_FPSRecords, EditorApplication::GetSingleton()->getAppFrameTimer().getLastFPS());
ImGui::TreePop();
}
for (auto& systems : System::GetSystems())
{
for (auto& system : systems)
{
if (ImGui::TreeNodeEx(system->getName().c_str()))
{
system->draw();
ImGui::TreePop();
}
}
}
}
ImGui::End();
}
}
| 29.558621
| 135
| 0.667755
|
ChronicallySerious
|
e6b3c330b8370ad9ccafef3cf97f0dd6b8b6cad9
| 7,737
|
cpp
|
C++
|
src/ndnSIM/NFD/daemon/table/name-tree-hashtable.cpp
|
NDNLink/NDN-Chord
|
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
|
[
"MIT"
] | 1
|
2021-09-07T04:12:15.000Z
|
2021-09-07T04:12:15.000Z
|
src/ndnSIM/NFD/daemon/table/name-tree-hashtable.cpp
|
NDNLink/NDN-Chord
|
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
|
[
"MIT"
] | null | null | null |
src/ndnSIM/NFD/daemon/table/name-tree-hashtable.cpp
|
NDNLink/NDN-Chord
|
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
|
[
"MIT"
] | 1
|
2020-07-15T06:21:03.000Z
|
2020-07-15T06:21:03.000Z
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2014-2017, Regents of the University of California,
* Arizona Board of Regents,
* Colorado State University,
* University Pierre & Marie Curie, Sorbonne University,
* Washington University in St. Louis,
* Beijing Institute of Technology,
* The University of Memphis.
*
* This file is part of NFD (Named Data Networking Forwarding Daemon).
* See AUTHORS.md for complete list of NFD authors and contributors.
*
* NFD 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.
*
* NFD 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
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*/
#include "name-tree-hashtable.hpp"
#include "core/logger.hpp"
#include "core/city-hash.hpp"
namespace nfd {
namespace name_tree {
NFD_LOG_INIT("NameTreeHashtable");
class Hash32
{
public:
static HashValue
compute(const void* buffer, size_t length)
{
return static_cast<HashValue>(CityHash32(reinterpret_cast<const char*>(buffer), length));
}
};
class Hash64
{
public:
static HashValue
compute(const void* buffer, size_t length)
{
return static_cast<HashValue>(CityHash64(reinterpret_cast<const char*>(buffer), length));
}
};
/** \brief a type with compute static method to compute hash value from a raw buffer
*/
using HashFunc = std::conditional<(sizeof(HashValue) > 4), Hash64, Hash32>::type;
HashValue
computeHash(const Name& name, size_t prefixLen)
{
name.wireEncode(); // ensure wire buffer exists
HashValue h = 0;
for (size_t i = 0, last = std::min(prefixLen, name.size()); i < last; ++i) {
const name::Component& comp = name[i];
h ^= HashFunc::compute(comp.wire(), comp.size());
}
return h;
}
HashSequence
computeHashes(const Name& name, size_t prefixLen)
{
name.wireEncode(); // ensure wire buffer exists
size_t last = std::min(prefixLen, name.size());
HashSequence seq;
seq.reserve(last + 1);
HashValue h = 0;
seq.push_back(h);
for (size_t i = 0; i < last; ++i) {
const name::Component& comp = name[i];
h ^= HashFunc::compute(comp.wire(), comp.size());
seq.push_back(h);
}
return seq;
}
Node::Node(HashValue h, const Name& name)
: hash(h)
, prev(nullptr)
, next(nullptr)
, entry(name, this)
{
}
Node::~Node()
{
BOOST_ASSERT(prev == nullptr);
BOOST_ASSERT(next == nullptr);
}
Node*
getNode(const Entry& entry)
{
return entry.m_node;
}
HashtableOptions::HashtableOptions(size_t size)
: initialSize(size)
, minSize(size)
{
}
Hashtable::Hashtable(const Options& options)
: m_options(options)
, m_size(0)
{
BOOST_ASSERT(m_options.minSize > 0);
BOOST_ASSERT(m_options.initialSize >= m_options.minSize);
BOOST_ASSERT(m_options.expandLoadFactor > 0.0);
BOOST_ASSERT(m_options.expandLoadFactor <= 1.0);
BOOST_ASSERT(m_options.expandFactor > 1.0);
BOOST_ASSERT(m_options.shrinkLoadFactor >= 0.0);
BOOST_ASSERT(m_options.shrinkLoadFactor < 1.0);
BOOST_ASSERT(m_options.shrinkFactor > 0.0);
BOOST_ASSERT(m_options.shrinkFactor < 1.0);
m_buckets.resize(options.initialSize);
this->computeThresholds();
}
Hashtable::~Hashtable()
{
for (size_t i = 0; i < m_buckets.size(); ++i) {
foreachNode(m_buckets[i], [] (Node* node) {
node->prev = node->next = nullptr;
delete node;
});
}
}
void
Hashtable::attach(size_t bucket, Node* node)
{
node->prev = nullptr;
node->next = m_buckets[bucket];
if (node->next != nullptr) {
BOOST_ASSERT(node->next->prev == nullptr);
node->next->prev = node;
}
m_buckets[bucket] = node;
}
void
Hashtable::detach(size_t bucket, Node* node)
{
if (node->prev != nullptr) {
BOOST_ASSERT(node->prev->next == node);
node->prev->next = node->next;
}
else {
BOOST_ASSERT(m_buckets[bucket] == node);
m_buckets[bucket] = node->next;
}
if (node->next != nullptr) {
BOOST_ASSERT(node->next->prev == node);
node->next->prev = node->prev;
}
node->prev = node->next = nullptr;
}
std::pair<const Node*, bool>
Hashtable::findOrInsert(const Name& name, size_t prefixLen, HashValue h, bool allowInsert)
{
size_t bucket = this->computeBucketIndex(h);
for (const Node* node = m_buckets[bucket]; node != nullptr; node = node->next) {
if (node->hash == h && name.compare(0, prefixLen, node->entry.getName()) == 0) {
NFD_LOG_TRACE("found " << name.getPrefix(prefixLen) << " hash=" << h << " bucket=" << bucket);
return {node, false};
}
}
if (!allowInsert) {
NFD_LOG_TRACE("not-found " << name.getPrefix(prefixLen) << " hash=" << h << " bucket=" << bucket);
return {nullptr, false};
}
Node* node = new Node(h, name.getPrefix(prefixLen));
this->attach(bucket, node);
NFD_LOG_TRACE("insert " << node->entry.getName() << " hash=" << h << " bucket=" << bucket);
++m_size;
if (m_size > m_expandThreshold) {
this->resize(static_cast<size_t>(m_options.expandFactor * this->getNBuckets()));
}
return {node, true};
}
const Node*
Hashtable::find(const Name& name, size_t prefixLen) const
{
HashValue h = computeHash(name, prefixLen);
return const_cast<Hashtable*>(this)->findOrInsert(name, prefixLen, h, false).first;
}
const Node*
Hashtable::find(const Name& name, size_t prefixLen, const HashSequence& hashes) const
{
BOOST_ASSERT(hashes.at(prefixLen) == computeHash(name, prefixLen));
return const_cast<Hashtable*>(this)->findOrInsert(name, prefixLen, hashes[prefixLen], false).first;
}
std::pair<const Node*, bool>
Hashtable::insert(const Name& name, size_t prefixLen, const HashSequence& hashes)
{
BOOST_ASSERT(hashes.at(prefixLen) == computeHash(name, prefixLen));
return this->findOrInsert(name, prefixLen, hashes[prefixLen], true);
}
void
Hashtable::erase(Node* node)
{
BOOST_ASSERT(node != nullptr);
BOOST_ASSERT(node->entry.getParent() == nullptr);
size_t bucket = this->computeBucketIndex(node->hash);
NFD_LOG_TRACE("erase " << node->entry.getName() << " hash=" << node->hash << " bucket=" << bucket);
this->detach(bucket, node);
delete node;
--m_size;
if (m_size < m_shrinkThreshold) {
size_t newNBuckets = std::max(m_options.minSize,
static_cast<size_t>(m_options.shrinkFactor * this->getNBuckets()));
this->resize(newNBuckets);
}
}
void
Hashtable::computeThresholds()
{
m_expandThreshold = static_cast<size_t>(m_options.expandLoadFactor * this->getNBuckets());
m_shrinkThreshold = static_cast<size_t>(m_options.shrinkLoadFactor * this->getNBuckets());
NFD_LOG_TRACE("thresholds expand=" << m_expandThreshold << " shrink=" << m_shrinkThreshold);
}
void
Hashtable::resize(size_t newNBuckets)
{
if (this->getNBuckets() == newNBuckets) {
return;
}
NFD_LOG_DEBUG("resize from=" << this->getNBuckets() << " to=" << newNBuckets);
std::vector<Node*> oldBuckets;
oldBuckets.swap(m_buckets);
m_buckets.resize(newNBuckets);
for (Node* head : oldBuckets) {
foreachNode(head, [this] (Node* node) {
size_t bucket = this->computeBucketIndex(node->hash);
this->attach(bucket, node);
});
}
this->computeThresholds();
}
} // namespace name_tree
} // namespace nfd
| 27.43617
| 102
| 0.670156
|
NDNLink
|
e6b4455ff486fd573f09a580df66b81d3d7a2207
| 30,694
|
cpp
|
C++
|
BlackVision/Tools/Triangulator/Source/PolylineValidator.cpp
|
black-vision-engine/bv-engine
|
85089d41bb22afeaa9de070646e12aa1777ecedf
|
[
"MIT"
] | 1
|
2022-01-28T11:43:47.000Z
|
2022-01-28T11:43:47.000Z
|
BlackVision/Tools/Triangulator/Source/PolylineValidator.cpp
|
black-vision-engine/bv-engine
|
85089d41bb22afeaa9de070646e12aa1777ecedf
|
[
"MIT"
] | null | null | null |
BlackVision/Tools/Triangulator/Source/PolylineValidator.cpp
|
black-vision-engine/bv-engine
|
85089d41bb22afeaa9de070646e12aa1777ecedf
|
[
"MIT"
] | null | null | null |
#include "PolylineValidator.h"
#include "glm.hpp"
#include <algorithm>
namespace triangulator {
const float epsilon = 0.00001f;
bool CompareEvent ( const Event & a, const Event & b );
bool CompareEdge ( p2t::Edge * leftEdge, p2t::Edge * rightEdge, double sweepY );
double FindX ( p2t::Edge * edge, double sweepY );
double EdgeDelta ( p2t::Edge * edge );
p2t::Edge * GetAboveEdge ( int pos, std::vector< p2t::Edge* >& sweepLine );
p2t::Edge * GetBelowEdge ( int pos, std::vector< p2t::Edge* >& sweepLine );
p2t::Point * GetIntesection ( p2t::Edge * edge1, p2t::Edge * edge2 );
bool operator< ( const p2t::Point & point1, const p2t::Point & point2 );
bool Equal ( const p2t::Point & point1, const p2t::Point & point2 );
bool IsIntersectionStart ( const p2t::Point * polylinePoint, const p2t::Point * nextPoint, const p2t::Point * intersectionPoint );
int FindFreeDividePoint ( std::vector< IntersectionData >& data );
int FindNextContourPart ( std::vector< IntersectionData >& data, Polyline & polyline, const p2t::Point * partEnd, int intersectionIdx );
bool IsSharedPointIntersection ( const Event& intersectEvent );
// ***********************
//
PolylineValidator::PolylineValidator ( const Polyline & polyline )
{
m_polyline.reserve( polyline.size() );
for( int i = 0; i < polyline.size(); ++i )
{
m_polyline.push_back( new p2t::Point( *polyline[ i ] ) );
}
Init();
}
// ***********************
//
PolylineValidator::PolylineValidator ( Polyline && polyline )
: m_polyline( std::move( polyline ) )
{
Init();
}
// ***********************
//
PolylineValidator::~PolylineValidator ()
{
ClearEdges();
for( auto & point : m_intersections )
{
delete point;
}
if( !m_polyline.empty() && m_resultPolylines.empty() )
{
for( auto & point : m_polyline )
{
delete point;
}
}
else
{
for( auto & polyline : m_resultPolylines )
{
for( auto point : polyline )
{
delete point;
}
}
}
}
// ***********************
//
void PolylineValidator::Init ()
{
InitEdges( m_polyline );
}
// ***********************
//
void PolylineValidator::InitEdges ( Polyline & polyline )
{
for( size_t i = 0; i < polyline.size(); i++ )
{
size_t j = i < polyline.size() - 1 ? i + 1 : 0;
//m_edgeList.push_back( new p2t::Edge( *polyline[ i ], *polyline[ j ] ) );
if( !Equal( *polyline[ i ], *polyline[ j ] ) )
{
m_edgeList.push_back( new p2t::Edge( *polyline[ i ], *polyline[ j ] ) );
}
else
{
if( j == 0 )
{
delete m_polyline[ i ];
delete m_edgeList[ i - 1 ];
m_polyline.erase( m_polyline.begin() + i );
m_edgeList.erase( m_edgeList.begin() + i - 1 );
m_edgeList.push_back( new p2t::Edge( *polyline[ i - 1 ], *polyline[ 0 ] ) );
}
else
{
delete m_polyline[ j ];
m_polyline.erase( m_polyline.begin() + j );
--i; // Next point ca be equal too.
}
}
}
}
// ***********************
//
void PolylineValidator::Sort ()
{
std::sort( m_polyline.begin(), m_polyline.end(), p2t::cmp );
}
// ***********************
//
PolylinesVec && PolylineValidator::StealDecomposedPolylines()
{
ClearEdges();
// Return source polylines, if no decomposition was needed.
if( m_resultPolylines.empty() && !m_polyline.empty() )
{
m_resultPolylines.push_back( std::move( m_polyline ) );
}
else
{
m_polyline.clear();
}
return std::move( m_resultPolylines );
}
// ***********************
//
IntersectionsVec && PolylineValidator::StealIntersections ()
{
ClearEdges();
return std::move( m_intersections );
}
// ***********************
//
void PolylineValidator::ClearEdges ()
{
for( auto & point : m_intersections )
point->edge_list.clear();
for( auto & point : m_polyline )
point->edge_list.clear();
for( auto & edge : m_edgeList )
delete edge;
m_edgeList.clear();
}
// ***********************
//
std::deque< Event > PolylineValidator::InitEventQueue ()
{
std::deque< Event > eventQueue;
// Fill event queue with all contours end points.
for( int i = 0; i < m_polyline.size(); i++ )
{
// Contours are closed. Last point from m_polyline is connected to first point in polyline.
int j = i < m_polyline.size() - 1 ? i + 1 : 0;
int topIdx; // Index of top point.
int bottomIdx; // Index of bottom point.
// Comparing points not pointers !!!
if( *m_polyline[ j ] < *m_polyline[ i ] )
{
// m_polyline[ i ] is top point
topIdx = i;
bottomIdx = j;
}
else
{
// m_polyline[ j ] is top point
topIdx = j;
bottomIdx = i;
}
// Note: Both points share the same edge from index i. (Check initialization in function PolylineValidator::InitEdges)
eventQueue.push_back( Event( EventType::StartPoint, m_polyline[ topIdx ], m_edgeList[ i ] ) );
eventQueue.push_back( Event( EventType::EndPoint, m_polyline[ bottomIdx ], m_edgeList[ i ] ) );
}
// Sort event queue - top left points first.
std::sort( eventQueue.begin(), eventQueue.end(), CompareEvent );
return eventQueue;
}
// ***********************
// @deprecated
void PolylineValidator::RepairRepeatPoints ()
{
for( int i = 0; i < m_polyline.size(); ++i )
{
int j = i < m_polyline.size() - 1 ? i + 1 : 0;
if( Equal( *m_polyline[ i ], *m_polyline[ j ] ) )
{
delete m_polyline[ j ];
m_polyline.erase( m_polyline.begin() + j );
--i; // Next point ca be equal too.
}
}
for( int i = 0; i < m_edgeList.size(); ++i )
{
if( Equal( *m_edgeList[ i ]->p, *m_edgeList[ i ]->q ) )
{
delete m_edgeList[ i ];
m_edgeList.erase( m_edgeList.begin() + i );
--i; // Next point ca be equal too.
}
}
}
// ***********************
// Checks if intersections are valid for further decomposition.
void PolylineValidator::ValidateIntersections ( const IntersectionsVec & intersect )
{
// FIXME: Two intersections shouldn't lie on the same edge.
for( auto inter1 = intersect.begin(); inter1 != intersect.end(); inter1++ )
{
for( auto inter2 = inter1 + 1; inter2 != intersect.end(); inter2++ )
{
if( inter1 == inter2 )
continue;
auto edge11 = ( *inter1 )->edge_list[ 0 ];
auto edge12 = ( *inter1 )->edge_list[ 1 ];
auto edge21 = ( *inter2 )->edge_list[ 0 ];
auto edge22 = ( *inter2 )->edge_list[ 1 ];
if( edge11 == edge21 ||
edge11 == edge22 ||
edge12 == edge21 ||
edge12 == edge22 )
throw std::runtime_error( "[PolylineValidator] One edge is intersected multpile times. Fix this in future versions." );
}
}
}
// ***********************
//
std::vector< IntersectionData > PolylineValidator::InitDividePoints ()
{
std::vector< IntersectionData > dividePoints;
dividePoints.reserve( 2 * m_intersections.size() ); // Each intersection gives 2 divide points.
// Divide polyline into ranges between intersection points.
for( int i = 0; i < m_polyline.size(); ++i )
{
int nextPoint = i + 1 < m_polyline.size() ? i + 1 : 0;
for( int j = 0; j < m_intersections.size(); j++ )
{
if( IsIntersectionStart( m_polyline[ i ], m_polyline[ nextPoint ], m_intersections[ j ] ) )
{
IntersectionData data;
data.IntersectionPoint = m_intersections[ j ];
data.Processed = false;
data.PolylineIdx = i;
dividePoints.push_back( data );
break;
}
}
}
return dividePoints;
}
// ***********************
// Implementation based on http://geomalgorithms.com/a09-_intersect-3.html
const IntersectionsVec & PolylineValidator::FindSelfIntersections ()
{
// Two points with same coordinates can't exist.
//RepairRepeatPoints();
std::deque< Event > eventQueue = InitEventQueue();
std::vector< p2t::Edge* > sweepLine;
std::vector< p2t::Point* > intersection;
while( !eventQueue.empty() )
{
auto event = eventQueue[ 0 ];
eventQueue.pop_front();
if( event.Type == EventType::StartPoint )
ProcessBeginPoint( event, eventQueue, sweepLine );
else if( event.Type == EventType::EndPoint )
ProcessEndPoint( event, eventQueue, sweepLine );
else
ProcessIntersectionPoint( event, eventQueue, sweepLine, intersection );
}
return m_intersections;
}
// ***********************
//
const PolylinesVec & PolylineValidator::DecomposeContour ()
{
PolylinesVec& polylines = m_resultPolylines;
if( m_intersections.empty() )
{
polylines.push_back( m_polyline );
return polylines;
}
ValidateIntersections( m_intersections );
// Number of intersection is maximal number of separate segments.
polylines.reserve( m_intersections.size() + 1 );
// Collect intersection points indicies.
std::vector< IntersectionData > dividePoints = InitDividePoints();
// Connect end of m_polyline with begining.
polylines.push_back( Polyline() );
for( int idx = dividePoints.back().PolylineIdx + 1; idx < m_polyline.size(); idx++ )
{
polylines[ 0 ].push_back( m_polyline[ idx ] );
}
for( int idx = 0; idx <= dividePoints.front().PolylineIdx; idx++ )
{
polylines[ 0 ].push_back( m_polyline[ idx ] );
}
dividePoints.back().Processed = true;
// Add intersection point
auto dividePoint = dividePoints[ 0 ].IntersectionPoint;
polylines[ 0 ].push_back( new p2t::Point( dividePoint->x, dividePoint->y ) );
// Connect ranges into contours.
int intersectIdx = FindNextContourPart( dividePoints, m_polyline, m_polyline[ dividePoints.front().PolylineIdx ], 0 );
int curPolyline = 0;
if( intersectIdx < 0 )
{
intersectIdx = FindFreeDividePoint( dividePoints );
curPolyline = 1;
polylines.push_back( Polyline() );
}
do
{
// Make single closed contour.
curPolyline = (int)polylines.size() - 1;
do
{
int beginIdx = dividePoints[ intersectIdx ].PolylineIdx + 1;
int endIdx = dividePoints[ intersectIdx + 1 ].PolylineIdx;
// Rewrite contour points to polyline.
for( int i = beginIdx; i <= endIdx; ++i )
{
polylines[ curPolyline ].push_back( m_polyline[ i ] );
}
// Add intersection point
auto dividePoint = dividePoints[ intersectIdx + 1 ].IntersectionPoint;
polylines[ curPolyline ].push_back( new p2t::Point( dividePoint->x, dividePoint->y ) );
// Set current points range as used.
dividePoints[ intersectIdx ].Processed = true;
// Find contour continuation.
intersectIdx = FindNextContourPart( dividePoints, m_polyline, m_polyline[ endIdx ], intersectIdx + 1 );
} while( intersectIdx != -1 );
//// We added have duplicate point on contour closing. Delete it.
//delete polylines[ curPolyline ].back();
//polylines[ curPolyline ].pop_back();
// Add place for new contour.
polylines.push_back( Polyline() );
// Find new segment. Returns -1 if all segments were used.
intersectIdx = FindFreeDividePoint( dividePoints );
} while( intersectIdx != -1 );
// We added to many polylines (check loop above).
polylines.pop_back();
return polylines;
}
// ***********************
//
void PolylineValidator::AddIntersectionEvent ( const Event & event, std::deque< Event > & eventQueue )
{
auto iter = std::upper_bound( eventQueue.begin(), eventQueue.end(), event, CompareEvent );
auto eventBefore = *iter;
// We must prevent adding duplicate intersection events.
if( eventBefore.Type == EventType::Intersection )
{
if( event.Point->x == eventBefore.Point->x &&
event.Point->y == eventBefore.Point->y )
return;
}
eventQueue.insert( iter, event );
}
// ***********************
//
void PolylineValidator::ProcessBeginPoint ( Event & event, std::deque< Event > & eventQueue, std::vector< p2t::Edge* >& sweepLine )
{
p2t::Edge * newEdge = event.Edge;
auto pos = AddToSweepLine( newEdge, sweepLine );
p2t::Edge * aboveEdge = GetAboveEdge( pos, sweepLine );
p2t::Edge * belowEdge = GetBelowEdge( pos, sweepLine );
p2t::Point * aboveIntersect = GetIntesection( newEdge, aboveEdge );
p2t::Point * belowIntersect = GetIntesection( newEdge, belowEdge );
if( aboveIntersect )
{
AddIntersectionEvent( Event( EventType::Intersection, aboveIntersect, nullptr ), eventQueue );
}
if( belowIntersect )
{
AddIntersectionEvent( Event( EventType::Intersection, belowIntersect, nullptr ), eventQueue );
}
}
// ***********************
//
void PolylineValidator::ProcessEndPoint ( Event & event, std::deque< Event > & eventQueue, std::vector< p2t::Edge* >& sweepLine )
{
p2t::Edge * curEdge = event.Edge;
auto pos = BruteFindInSweepLine( curEdge, sweepLine );
assert( pos >= 0 );
p2t::Edge * aboveEdge = GetAboveEdge( pos, sweepLine );
p2t::Edge * belowEdge = GetBelowEdge( pos, sweepLine );
DeleteFromSweepLine( curEdge, sweepLine );
auto intersection = GetIntesection( aboveEdge, belowEdge );
if( intersection )
{
// If intersection exist, it won't be added.
AddIntersectionEvent( Event( EventType::Intersection, intersection, nullptr ), eventQueue );
}
}
// ***********************
//
void PolylineValidator::ProcessIntersectionPoint ( Event & event, std::deque< Event > & eventQueue, std::vector< p2t::Edge* > & sweepLine, std::vector< p2t::Point* > & intersections )
{
// Segment start and end point are intersection, which we don't count in.
//if( !IsSharedPointIntersection( event ) )
m_intersections.push_back( event.Point );
assert( event.Point->edge_list.size() >= 2 );
auto edge1Idx = BruteFindInSweepLine( event.Point->edge_list[ 0 ], sweepLine );
auto edge2Idx = BruteFindInSweepLine( event.Point->edge_list[ 1 ], sweepLine );
assert( edge1Idx >= 0 );
assert( edge2Idx >= 0 );
p2t::Edge * aboveEdge = nullptr;
p2t::Edge * belowEdge = nullptr;
int aboveIdx;
int belowIdx;
if( edge1Idx > edge2Idx )
{
aboveEdge = sweepLine[ edge1Idx ]; aboveIdx = edge1Idx;
belowEdge = sweepLine[ edge2Idx ]; belowIdx = edge2Idx;
}
else
{
belowEdge = sweepLine[ edge1Idx ]; belowIdx = edge1Idx;
aboveEdge = sweepLine[ edge2Idx ]; aboveIdx = edge2Idx;
}
// Swap after reaching intersection point in event queue.
std::iter_swap( sweepLine.begin() + aboveIdx, sweepLine.begin() + belowIdx );
p2t::Edge * aboveAboveEdge = GetAboveEdge( aboveIdx, sweepLine );
p2t::Edge * belowBelowEdge = GetBelowEdge( belowIdx, sweepLine );
// Note: we swapped below with above. Now we compare new above edge with above above edge.
auto aboveIntersect = GetIntesection( belowEdge, aboveAboveEdge );
auto belowIntersect = GetIntesection( aboveEdge, belowBelowEdge );
if( aboveIntersect )
AddIntersectionEvent( Event( EventType::Intersection, aboveIntersect, nullptr ), eventQueue );
if( belowIntersect )
AddIntersectionEvent( Event( EventType::Intersection, belowIntersect, nullptr ), eventQueue );
}
// ***********************
//
p2t::Point * PolylineValidator::Intersect ( p2t::Edge * edge1, p2t::Edge * edge2 )
{
// http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
glm::vec2 edge1Begin = glm::vec2( edge1->p->x, edge1->p->y );
glm::vec2 edge1End = glm::vec2( edge1->q->x, edge1->q->y );
glm::vec2 edge2Begin = glm::vec2( edge2->p->x, edge2->p->y );
glm::vec2 edge2End = glm::vec2( edge2->q->x, edge2->q->y );
// Edge vectors
glm::vec2 edge1Vec = edge1End - edge1Begin;
glm::vec2 edge2Vec = edge2End - edge2Begin;
// Vector from begin points of edge1 and edge2
glm::vec2 edge12Vec = edge2Begin - edge1Begin;
auto edge12Cross = edge1Vec.x * edge2Vec.y - edge1Vec.y * edge2Vec.x; // r x s (check in link)
auto edge1Point2Cross = edge12Vec.x * edge1Vec.y - edge12Vec.y * edge1Vec.x; // (p - q) x r
auto edge2Point1Cross = edge12Vec.x * edge2Vec.y - edge12Vec.y * edge2Vec.x; // (p - q) x s
if( edge12Cross == 0 )
return nullptr;
float edge1Factor = edge2Point1Cross / edge12Cross;
float edge2Factor = edge1Point2Cross / edge12Cross;
// Note: We don't need intersection on begin and end point. Add some margin.
const float epsilon = 0.00005f;
if( edge1Factor >= 0.0f + epsilon && edge1Factor <= 1.0f - epsilon &&
edge2Factor >= 0.0f + epsilon && edge2Factor <= 1.0f - epsilon )
{
glm::vec2 intersectionPoint = edge1Begin + edge1Factor * edge1Vec;
p2t::Point * intersectPoint = new p2t::Point( intersectionPoint.x, intersectionPoint.y );
return intersectPoint;
}
return nullptr;
}
// ***********************
// @return Returns -1 if edge is not present in sweepLine
int PolylineValidator::FindInSweepLine ( p2t::Edge * searchedEdge, std::vector< p2t::Edge * > & sweepLine )
{
int resultIdx = 0;
auto sweepY = searchedEdge->p->y;
if( sweepLine.empty() )
return -1;
if( sweepLine.size() == 1 )
{
// !Compare( a, b ) && !Compare( b, a ) means that a, b are equal.
if( !CompareEdge( sweepLine[ 0 ], searchedEdge, sweepY ) && !CompareEdge( searchedEdge, sweepLine[ 0 ], sweepY ) )
return 0;
else
return -1;
}
// Binary search
size_t left = 0;
auto right = sweepLine.size();
auto span = right - left;
while( span > 1 )
{
span = span / 2;
auto pos = left + span;
auto edge = sweepLine[ pos ];
if( CompareEdge( edge, searchedEdge, sweepY ) )
{
right = pos;
}
else if( CompareEdge( searchedEdge, edge, sweepY ) )
{
left = pos;
}
else
{
return (int)pos;
}
}
auto edge = sweepLine[ left ];
if( !CompareEdge( edge, searchedEdge, sweepY ) && !CompareEdge( searchedEdge, edge, sweepY ) )
return (int)left;
else
return -1;
}
// ***********************
// This method iterates through edges and compares pointers. It doesn't use binary search, because
// sweepLine vector is ordered with function CompareEdge.
// Hopefully this function is more cache efficient and brute force won't be performance problem.
int PolylineValidator::BruteFindInSweepLine ( p2t::Edge * edge, std::vector< p2t::Edge * > & sweepLine )
{
for( int i = 0; i < sweepLine.size(); ++i )
{
if( edge == sweepLine[ i ] )
return i;
}
return -1;
}
// ***********************
//
int PolylineValidator::AddToSweepLine ( p2t::Edge* addEdge, std::vector< p2t::Edge* > & sweepLine )
{
auto sweepY = addEdge->q->y; // Take upper point y value.
if( sweepLine.size() == 0 )
{
sweepLine.push_back( addEdge );
return 0;
}
else if( sweepLine.size() == 1 )
{
if( CompareEdge( addEdge, sweepLine[ 0 ], sweepY ) )
{
sweepLine.insert( sweepLine.begin(), addEdge );
return 0;
}
else
{
sweepLine.push_back( addEdge );
return 1;
}
}
else
{
for( int i = 0 ; i < sweepLine.size(); ++i )
{
auto edge = sweepLine[ i ];
if( CompareEdge( addEdge, edge, sweepY ) )
{
sweepLine.insert( sweepLine.begin() + i, addEdge );
return i;
}
}
sweepLine.push_back( addEdge );
return (int)sweepLine.size() - 1;
//// Binary search
//size_t left = 0;
//auto right = sweepLine.size();
//auto span = right - left;
//while( span > 1 )
//{
// span = span / 2;
// auto pos = left + span;
// auto edge = sweepLine[ pos ];
// if( CompareEdge( addEdge, edge, sweepY ) )
// {
// right = pos;
// }
// else
// {
// left = pos;
// }
//}
//auto edge = sweepLine[ left ];
//if( CompareEdge( addEdge, edge, sweepY ) )
//{
// sweepLine.insert( sweepLine.begin() + left, addEdge );
// return (int)left;
//}
//else
//{
// if( left + 1 < sweepLine.size() )
// {
// sweepLine.insert( sweepLine.begin() + left + 1, addEdge );
// return int( left + 1 );
// }
// else
// {
// sweepLine.push_back( addEdge );
// return (int)sweepLine.size() - 1;
// }
//}
}
}
// ***********************
//
void PolylineValidator::DeleteFromSweepLine ( p2t::Edge * edge, std::vector< p2t::Edge * > & sweepLine )
{
auto pos = BruteFindInSweepLine( edge, sweepLine );
assert( pos >= 0 );
sweepLine.erase( sweepLine.begin() + pos );
}
// ***********************
//
bool CompareEvent ( const Event & a, const Event & b )
{
if( a.Point->y > b.Point->y )
{
return true;
}
else if( a.Point->y == b.Point->y )
{
// Make sure q is point with greater x value
if( a.Point->x < b.Point->x )
{
return true;
}
else if( a.Point->x == b.Point->x )
{
// Start point goes before end point.
if( a.Type == EventType::StartPoint && b.Type != EventType::StartPoint )
return true;
}
}
return false;
}
// ***********************
//
bool CompareEdge ( p2t::Edge * leftEdge, p2t::Edge * rightEdge, double sweepY )
{
auto leftX = FindX( leftEdge, sweepY );
auto rightX = FindX( rightEdge, sweepY );
if( leftX < rightX )
return true;
if( leftX == rightX )
{
// Probably we have two edges with beginning in the same point.
// Check which segment makes greater progress in x axis.
auto leftDelta = EdgeDelta( leftEdge );
auto rightDelta = EdgeDelta( rightEdge );
if( leftDelta < rightDelta )
return true;
}
return false;
}
// ***********************
// Finds X coordinate of edge in point Y.
double FindX ( p2t::Edge * edge, double sweepY )
{
p2t::Point* point1 = edge->p;
p2t::Point* point2 = edge->q;
// Dangerous situation. We can't order edges.
if( point1->y == point2->y )
return point1->x;
auto deltaX = point2->x - point1->x;
auto deltaY = point2->y - point1->y;
auto sweepPointDelta = sweepY - point1->y;
return point1->x + deltaX * ( sweepPointDelta / deltaY );
}
// ================================ //
//
double EdgeDelta ( p2t::Edge * edge )
{
p2t::Point* point1 = edge->p;
p2t::Point* point2 = edge->q;
auto deltaX = point1->x - point2->x;
auto deltaY = point2->y - point1->y;
return deltaX / deltaY;
}
// ***********************
//
p2t::Edge * GetAboveEdge ( int pos, std::vector< p2t::Edge * > & sweepLine )
{
// SweepLine is sorted so we can take element after and before pos if they exist.
if( pos >= 0 && pos < sweepLine.size() - 1 )
return sweepLine[ pos + 1 ];
return nullptr;
}
// ***********************
//
p2t::Edge * GetBelowEdge ( int pos, std::vector< p2t::Edge * > & sweepLine )
{
// SweepLine is sorted so we can take element after and before pos if they exist.
if( pos > 0 && pos < sweepLine.size() )
return sweepLine[ pos - 1 ];
return nullptr;
}
// ***********************
// Edges can be nullptr.
// Function adds two edges to point edge list.
p2t::Point * GetIntesection ( p2t::Edge * edge1, p2t::Edge * edge2 )
{
if( edge1 && edge2 )
{
auto point = PolylineValidator::Intersect( edge1, edge2 );
if( point )
{
point->edge_list.push_back( edge1 );
point->edge_list.push_back( edge2 );
return point;
}
}
return nullptr;
}
// ***********************
//
bool operator< ( const p2t::Point & a, const p2t::Point & b )
{
if( a.y < b.y )
{
return true;
}
else if( a.y == b.y )
{
// Make sure q is point with greater x value
if( a.x > b.x )
{
return true;
}
}
return false;
}
// ================================ //
//
bool Equal ( const p2t::Point & point1, const p2t::Point & point2 )
{
if( abs( point1.x - point2.x ) < epsilon && abs( point1.y - point2.y ) < epsilon )
return true;
return false;
}
// ***********************
//
bool IsIntersectionStart ( const p2t::Point * polylinePoint, const p2t::Point * nextPoint, const p2t::Point * intersectionPoint )
{
assert( intersectionPoint->edge_list.size() == 2 );
// Note: Make pointers comparision.
if( polylinePoint == intersectionPoint->edge_list[ 0 ]->p &&
nextPoint == intersectionPoint->edge_list[ 0 ]->q )
return true;
if( polylinePoint == intersectionPoint->edge_list[ 0 ]->q &&
nextPoint == intersectionPoint->edge_list[ 0 ]->p )
return true;
if( polylinePoint == intersectionPoint->edge_list[ 1 ]->p &&
nextPoint == intersectionPoint->edge_list[ 1 ]->q )
return true;
if( polylinePoint == intersectionPoint->edge_list[ 1 ]->q &&
nextPoint == intersectionPoint->edge_list[ 1 ]->p )
return true;
return false;
}
// ***********************
//
int FindFreeDividePoint ( std::vector< IntersectionData > & data )
{
for( int i = 0; i < data.size(); ++i )
{
if( !data[ i ].Processed )
return i;
}
return -1;
}
// ***********************
// http://geomalgorithms.com/a09-_intersect-3.html - decompose into Simple Pieces
int FindNextContourPart ( std::vector< IntersectionData > & data, Polyline & polyline, const p2t::Point * partEnd, int intersectionIdx )
{
auto & intersect = data[ intersectionIdx ];
auto point = intersect.IntersectionPoint;
// There are two occurances of one intersection point in data array. One we already met (intersectionIdx).
// We must find other.
for( int i = 0; i < data.size(); ++i )
{
if( !data[ i ].Processed && data[ i ].IntersectionPoint == point && intersectionIdx != i )
return i;
}
return -1;
//// q is upper point, p is lower point.
//// If edge goes from top to bottom, we choose top point from second edge.
//// Check link in comment to this function.
//if( point->edge_list[ 0 ]->p == partEnd )
//{
// nextPoint = point->edge_list[ 1 ]->p;
//}
//else if( point->edge_list[ 0 ]->q == partEnd )
//{
// nextPoint = point->edge_list[ 1 ]->q;
//}
//else if( point->edge_list[ 1 ]->p == partEnd )
//{
// nextPoint = point->edge_list[ 0 ]->p;
//}
//else if( point->edge_list[ 1 ]->q == partEnd )
//{
// nextPoint = point->edge_list[ 0 ]->p;
//}
//else
// assert( false );
//// Iterate all segments of contours to find proper continuation point.
//for( int i = 0; i < data.size(); ++i )
//{
// auto polylineIdx = data[ i ].PolylineIdx;
// if( !data[ i ].Processed && polyline[ polylineIdx ] == nextPoint )
// return i;
//}
//return -1;
}
// ***********************
//
bool IsSharedPointIntersection ( const Event& intersectEvent )
{
assert( intersectEvent.Type == EventType::Intersection );
if( intersectEvent.Point->edge_list[ 0 ]->p == intersectEvent.Point->edge_list[ 1 ]->p )
return true;
if( intersectEvent.Point->edge_list[ 0 ]->q == intersectEvent.Point->edge_list[ 1 ]->q )
return true;
if( intersectEvent.Point->edge_list[ 0 ]->p == intersectEvent.Point->edge_list[ 1 ]->q )
return true;
if( intersectEvent.Point->edge_list[ 1 ]->p == intersectEvent.Point->edge_list[ 0 ]->q )
return true;
return false;
}
} //triangulator
| 30.755511
| 206
| 0.530853
|
black-vision-engine
|
e6b49ac73d171bdfd88cd61f75bf9d7d7d1d4ba7
| 5,188
|
cpp
|
C++
|
config_manager.cpp
|
KA8KPN/keyer-ng
|
93f07dca6249574e19ee3331bd3c7240ddd5d4a5
|
[
"Apache-2.0"
] | 1
|
2022-02-22T05:46:49.000Z
|
2022-02-22T05:46:49.000Z
|
config_manager.cpp
|
KA8KPN/keyer-ng
|
93f07dca6249574e19ee3331bd3c7240ddd5d4a5
|
[
"Apache-2.0"
] | null | null | null |
config_manager.cpp
|
KA8KPN/keyer-ng
|
93f07dca6249574e19ee3331bd3c7240ddd5d4a5
|
[
"Apache-2.0"
] | null | null | null |
#include "config_manager.h"
#include "paddles.h"
#include "display.h"
#include "keying.h"
#include "memories.h"
#include "wpm.h"
#include <EEPROM.h>
#include <ctype.h>
config_manager system_config_manager;
#define MAGIC 0x5a0d
#define PADDLES_REVERSE_FLAG 0x01
#define SIDETONE_OFF_FLAG 0x02
#pragma pack(1)
typedef struct persistent_config {
uint16_t magic;
uint16_t size;
uint8_t configFlags;
uint8_t transmitter;
#ifdef FEATURE_MEMORIES
uint8_t memories[MEMORY_SIZE];
#endif // FEATURE_MEMORIES
#ifdef FEATURE_SPEED_CONTROL
int wpm_offset;
#endif // FEATURE_SPEED_CONTROL
uint16_t checksum;
} persistent_config_t;
#pragma pack()
void error_tone(void) {
tone(SIDETONE, 100);
delay(200);
noTone(SIDETONE);
}
static persistent_config_t s_persistentConfig;
// returns TRUE if the checksum has changed
static bool update_checksum(persistent_config_t *conf) {
uint16_t sum = 0;
for (size_t i=0; i<((sizeof(persistent_config_t)/2)-1); ++i) {
sum += ((uint16_t *)conf)[i];
}
if (~sum != conf->checksum) {
conf->checksum = ~sum;
return true;
}
return false;
}
// returns TRUE if the checksum is valid
static bool validate_checksum(persistent_config_t *conf) {
uint16_t sum = 0;
for (size_t i=0; i<(sizeof(persistent_config_t)/2); ++i) {
sum += ((uint16_t *)conf)[i];
}
return sum == ~0U;
}
static void write_eeprom(bool force) {
int max_address;
max_address = sizeof(persistent_config_t);
if (update_checksum(&s_persistentConfig) || force) {
// Write the memory, but only if that works
for (int i=0; i<max_address; ++i) {
if (EEPROM.read(i) != ((uint8_t *)&s_persistentConfig)[i]) {
EEPROM.write(i, ((uint8_t *)&s_persistentConfig)[i]);
}
}
}
}
config_manager::config_manager(void): m_paddlesMode(MODE_PADDLE_NORMAL), m_isInCommandMode(false), m_currentXmitter(1), m_processing(false) {
}
void config_manager::process_command(const char *command) {
if (!m_processing) {
switch(command[0]) {
case 'N':
m_paddlesMode = PADDLES_REVERSE();
if (PADDLES_REVERSE_FLAG & s_persistentConfig.configFlags) {
s_persistentConfig.configFlags &= ~PADDLES_REVERSE_FLAG;
}
else {
s_persistentConfig.configFlags |= PADDLES_REVERSE_FLAG;
}
command_mode(false);
break;
case 'O':
if (SIDETONE_OFF_FLAG & s_persistentConfig.configFlags) {
s_persistentConfig.configFlags &= ~SIDETONE_OFF_FLAG;
}
else {
s_persistentConfig.configFlags |= SIDETONE_OFF_FLAG;
}
TOGGLE_SIDETONE_ENABLE();
command_mode(false);
break;
case '0': case '1': case '2': case '3': case '4':
m_currentXmitter = command[0] - '0';
s_persistentConfig.transmitter = m_currentXmitter;
KEYING_SELECT_TRANSMITTER(m_currentXmitter);
command_mode(false);
break;
case 'P':
if (isdigit(command[1])) {
RECORD_MEMORY(atoi(command+1));
m_processing = true;
}
else {
error_tone();
}
break;
default:
error_tone();
break;
}
}
}
static void two_beeps(bool first_is_low, bool second_is_low) {
if (first_is_low) {
tone(SIDETONE, 600);
}
else {
tone(SIDETONE, 1200);
}
delay(100);
noTone(SIDETONE);
delay(50);
if (second_is_low) {
tone(SIDETONE, 600);
}
else {
tone(SIDETONE, 1200);
}
delay(100);
noTone(SIDETONE);
delay(50);
}
void config_manager::memory_start_tones(void) {
two_beeps(false, false);
}
void config_manager::memory_end_tones(void) {
two_beeps(true, true);
}
void config_manager::command_mode(bool is_in_command_mode) {
if (is_in_command_mode) {
two_beeps(true, false);
}
else {
if (m_isInCommandMode) {
two_beeps(false, true);
}
RECORD_MEMORY(0);
s_persistentConfig.wpm_offset = WPM_GET_OFFSET();
m_processing = false;
write_eeprom(false);
}
m_isInCommandMode = is_in_command_mode;
DISPLAY_MANAGER_PROG_MODE(m_isInCommandMode);
KEYING_COMMAND_MODE(m_isInCommandMode);
}
void config_manager_initialize(void) {
// Attempt to read the config from the EEPROM
int max_address;
max_address = sizeof(persistent_config_t);
for (int i=0; i<max_address; ++i) {
((uint8_t *)&s_persistentConfig)[i] = EEPROM.read(i);
}
// If the magic is right, the size is right, and the checksum is right, then I'm good, otherwise initialize
if ((MAGIC != s_persistentConfig.magic) ||
(s_persistentConfig.size != sizeof(s_persistentConfig)) ||
!validate_checksum(&s_persistentConfig)) {
memset(&s_persistentConfig, 0, sizeof(s_persistentConfig));
s_persistentConfig.magic = MAGIC;
s_persistentConfig.size = sizeof(s_persistentConfig);
s_persistentConfig.transmitter = 1;
write_eeprom(true);
}
//
MEMORIES_CONFIG(s_persistentConfig.memories);
if (s_persistentConfig.configFlags & PADDLES_REVERSE_FLAG) {
PADDLES_REVERSE();
}
if (s_persistentConfig.configFlags & SIDETONE_OFF_FLAG) {
TOGGLE_SIDETONE_ENABLE();
}
if (0 != s_persistentConfig.wpm_offset) {
WPM_SET_OFFSET(s_persistentConfig.wpm_offset);
}
KEYING_SELECT_TRANSMITTER(s_persistentConfig.transmitter);
}
| 23.581818
| 142
| 0.689476
|
KA8KPN
|
e6b4de51daf9e7e954e640ecb6fc2b84cfb19e6f
| 1,317
|
cpp
|
C++
|
src/memory.cpp
|
habs1337/hack-lib
|
4bd4c7182eba5e738d6d1a87daa1d4b37dfae798
|
[
"MIT"
] | null | null | null |
src/memory.cpp
|
habs1337/hack-lib
|
4bd4c7182eba5e738d6d1a87daa1d4b37dfae798
|
[
"MIT"
] | null | null | null |
src/memory.cpp
|
habs1337/hack-lib
|
4bd4c7182eba5e738d6d1a87daa1d4b37dfae798
|
[
"MIT"
] | null | null | null |
#include "../includes/includes.h"
namespace g_mini_crt::memory {
wchar_t get_bits(char x) {
return g_mini_crt::string::is_digit(x) ? (x - '0') : ((x - 'A') + 0xA);
}
BYTE get_byts(const char* x) {
return ((BYTE)(get_bits(x[0]) << 4 | get_bits(x[1])));
}
int mem_cmp(const void* str1, const void* str2, size_t count) {
const unsigned char* s1 = reinterpret_cast<const unsigned char*> (str1);
const unsigned char* s2 = reinterpret_cast<const unsigned char*> (str2);
while (count-- > 0) {
if (*s1++ != *s2++)
return s1[-1] < s2[-1] ? -1 : 1;
}
return 0;
}
void* mem_cpy(void* dest, const void* src, size_t len) {
char* d = reinterpret_cast<char*>(dest);
const char* s = reinterpret_cast<const char*>(src);;
while (len--)
*d++ = *s++;
return dest;
}
void* mem_move(void* dest, const void* src, size_t len) {
char* d = reinterpret_cast<char*>(dest);
const char* s = reinterpret_cast<const char*>(src);
if (d < s)
while (len--)
*d++ = *s++;
else {
const char* lasts = s + (len - 1);
char* lastd = d + (len - 1);
while (len--)
*lastd-- = *lasts--;
}
return dest;
}
void* mem_set(void* dest, int val, size_t len) {
unsigned char* ptr = reinterpret_cast<unsigned char*>(dest);
while (len-- > 0)
*ptr++ = val;
return dest;
}
}
| 21.95
| 74
| 0.589977
|
habs1337
|
e6b5a503196e184358448b40b89ad697bfa86120
| 6,648
|
cpp
|
C++
|
source/gameengine/GameLogic/SCA_GameActuator.cpp
|
linluofeng/upbge
|
50bc9bc923a41411461d662c0fddd58d1f0b3ab3
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1
|
2022-01-11T10:02:21.000Z
|
2022-01-11T10:02:21.000Z
|
source/gameengine/GameLogic/SCA_GameActuator.cpp
|
linluofeng/upbge
|
50bc9bc923a41411461d662c0fddd58d1f0b3ab3
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
source/gameengine/GameLogic/SCA_GameActuator.cpp
|
linluofeng/upbge
|
50bc9bc923a41411461d662c0fddd58d1f0b3ab3
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
/*
* global game stuff
*
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file gameengine/Ketsji/SCA_GameActuator.cpp
* \ingroup ketsji
*/
#include "SCA_GameActuator.h"
#include "CM_Message.h"
#include "KX_KetsjiEngine.h"
#include "KX_PythonInit.h" /* for config load/saving */
#include "RAS_ICanvas.h"
/* ------------------------------------------------------------------------- */
/* Native functions */
/* ------------------------------------------------------------------------- */
SCA_GameActuator::SCA_GameActuator(SCA_IObject *gameobj,
int mode,
const std::string &filename,
const std::string &loadinganimationname,
SCA_IScene *scene,
KX_KetsjiEngine *ketsjiengine)
: SCA_IActuator(gameobj, KX_ACT_GAME)
{
m_mode = mode;
m_filename = filename;
m_loadinganimationname = loadinganimationname;
m_scene = scene;
m_ketsjiengine = ketsjiengine;
} /* End of constructor */
SCA_GameActuator::~SCA_GameActuator()
{
// there's nothing to be done here, really....
} /* end of destructor */
CValue *SCA_GameActuator::GetReplica()
{
SCA_GameActuator *replica = new SCA_GameActuator(*this);
replica->ProcessReplica();
return replica;
}
bool SCA_GameActuator::Update()
{
// bool result = false; /*unused*/
bool bNegativeEvent = IsNegativeEvent();
RemoveAllEvents();
if (bNegativeEvent)
return false; // do nothing on negative events
switch (m_mode) {
case KX_GAME_LOAD:
case KX_GAME_START: {
if (m_ketsjiengine) {
std::string exitstring = "start other game";
m_ketsjiengine->RequestExit(KX_ExitRequest::START_OTHER_GAME);
m_ketsjiengine->SetNameNextGame(m_filename);
m_scene->AddDebugProperty((this)->GetParent(), exitstring);
}
break;
}
case KX_GAME_RESTART: {
if (m_ketsjiengine) {
std::string exitstring = "restarting game";
m_ketsjiengine->RequestExit(KX_ExitRequest::RESTART_GAME);
m_ketsjiengine->SetNameNextGame(m_filename);
m_scene->AddDebugProperty((this)->GetParent(), exitstring);
}
break;
}
case KX_GAME_QUIT: {
if (m_ketsjiengine) {
std::string exitstring = "quiting game";
m_ketsjiengine->RequestExit(KX_ExitRequest::QUIT_GAME);
m_scene->AddDebugProperty((this)->GetParent(), exitstring);
}
break;
}
case KX_GAME_SAVECFG: {
#ifdef WITH_PYTHON
if (m_ketsjiengine) {
saveGamePythonConfig();
}
break;
#endif // WITH_PYTHON
}
case KX_GAME_LOADCFG: {
#ifdef WITH_PYTHON
if (m_ketsjiengine) {
loadGamePythonConfig();
}
break;
#endif // WITH_PYTHON
}
case KX_GAME_SCREENSHOT: {
RAS_ICanvas *canvas = m_ketsjiengine->GetCanvas();
if (canvas) {
canvas->MakeScreenShot(m_filename);
}
else {
CM_LogicBrickError(this, "KX_GAME_SCREENSHOT Rasterizer not available");
}
break;
}
default:; /* do nothing? this is an internal error !!! */
}
return false;
}
#ifdef WITH_PYTHON
/* ------------------------------------------------------------------------- */
/* Python functions */
/* ------------------------------------------------------------------------- */
/* Integration hooks ------------------------------------------------------- */
PyTypeObject SCA_GameActuator::Type = {PyVarObject_HEAD_INIT(nullptr, 0) "SCA_GameActuator",
sizeof(PyObjectPlus_Proxy),
0,
py_base_dealloc,
0,
0,
0,
0,
py_base_repr,
0,
0,
0,
0,
0,
0,
0,
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
0,
0,
0,
0,
0,
0,
0,
Methods,
0,
0,
&SCA_IActuator::Type,
0,
0,
0,
0,
0,
0,
py_base_new};
PyMethodDef SCA_GameActuator::Methods[] = {
{nullptr, nullptr} // Sentinel
};
PyAttributeDef SCA_GameActuator::Attributes[] = {
KX_PYATTRIBUTE_STRING_RW("fileName", 0, 100, false, SCA_GameActuator, m_filename),
KX_PYATTRIBUTE_INT_RW(
"mode", KX_GAME_NODEF + 1, KX_GAME_MAX - 1, true, SCA_GameActuator, m_mode),
KX_PYATTRIBUTE_NULL // Sentinel
};
#endif // WITH_PYTHON
| 33.074627
| 92
| 0.469314
|
linluofeng
|
e6b7008f8d531dede9e7f9200cef8af462afd168
| 24,947
|
cpp
|
C++
|
libspace/plugins/standard/StandardLocationService.cpp
|
sirikata/sirikata
|
3a0d54a8c4778ad6e25ef031d461b2bc3e264860
|
[
"BSD-3-Clause"
] | 31
|
2015-01-28T17:01:10.000Z
|
2021-11-04T08:30:37.000Z
|
libspace/plugins/standard/StandardLocationService.cpp
|
sirikata/sirikata
|
3a0d54a8c4778ad6e25ef031d461b2bc3e264860
|
[
"BSD-3-Clause"
] | null | null | null |
libspace/plugins/standard/StandardLocationService.cpp
|
sirikata/sirikata
|
3a0d54a8c4778ad6e25ef031d461b2bc3e264860
|
[
"BSD-3-Clause"
] | 9
|
2015-08-02T18:39:49.000Z
|
2019-10-11T10:32:30.000Z
|
/* Sirikata
* StandardLocationService.cpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "StandardLocationService.hpp"
#include <sirikata/core/trace/Trace.hpp>
#include <sirikata/core/command/Commander.hpp>
#include "Protocol_Loc.pbj.hpp"
namespace Sirikata {
StandardLocationService::StandardLocationService(SpaceContext* ctx, LocationUpdatePolicy* update_policy)
: LocationService(ctx, update_policy)
{
}
bool StandardLocationService::contains(const UUID& uuid) const {
return (mLocations.find(uuid) != mLocations.end());
}
bool StandardLocationService::isLocal(const UUID& uuid) const {
LocationMap::const_iterator it = mLocations.find(uuid);
if (it == mLocations.end())
return false;
return it->second.local;
}
void StandardLocationService::service() {
mUpdatePolicy->service();
}
uint64 StandardLocationService::epoch(const UUID& uuid) {
LocationMap::iterator it = mLocations.find(uuid);
assert(it != mLocations.end());
LocationInfo locinfo = it->second;
return locinfo.props.maxSeqNo();
}
TimedMotionVector3f StandardLocationService::location(const UUID& uuid) {
LocationMap::iterator it = mLocations.find(uuid);
assert(it != mLocations.end());
LocationInfo locinfo = it->second;
return locinfo.props.location();
}
Vector3f StandardLocationService::currentPosition(const UUID& uuid) {
TimedMotionVector3f loc = location(uuid);
Vector3f returner = loc.extrapolate(mContext->simTime()).position();
return returner;
}
TimedMotionQuaternion StandardLocationService::orientation(const UUID& uuid) {
LocationMap::iterator it = mLocations.find(uuid);
assert(it != mLocations.end());
LocationInfo locinfo = it->second;
return locinfo.props.orientation();
}
Quaternion StandardLocationService::currentOrientation(const UUID& uuid) {
TimedMotionQuaternion orient = orientation(uuid);
return orient.extrapolate(mContext->simTime()).position();
}
AggregateBoundingInfo StandardLocationService::bounds(const UUID& uuid) {
LocationMap::iterator it = mLocations.find(uuid);
assert(it != mLocations.end());
LocationInfo locinfo = it->second;
return locinfo.props.bounds();
}
const String& StandardLocationService::mesh(const UUID& uuid) {
LocationMap::iterator it = mLocations.find(uuid);
assert(it != mLocations.end());
LocationInfo& locinfo = it->second;
locinfo.mesh_copied_str = locinfo.props.mesh().toString();
return locinfo.mesh_copied_str;
}
const String& StandardLocationService::physics(const UUID& uuid) {
LocationMap::iterator it = mLocations.find(uuid);
assert(it != mLocations.end());
LocationInfo& locinfo = it->second;
locinfo.physics_copied_str = locinfo.props.physics();
return locinfo.physics_copied_str;
}
const String& StandardLocationService::queryData(const UUID& uuid) {
LocationMap::iterator it = mLocations.find(uuid);
assert(it != mLocations.end());
LocationInfo& locinfo = it->second;
locinfo.query_data_copied_str = locinfo.props.queryData();
return locinfo.query_data_copied_str;
}
void StandardLocationService::addLocalObject(const UUID& uuid, const TimedMotionVector3f& loc, const TimedMotionQuaternion& orient, const AggregateBoundingInfo& bnds, const String& msh, const String& phy, const String& query_data) {
LocationMap::iterator it = mLocations.find(uuid);
// Add or update the information to the cache
if (it == mLocations.end()) {
mLocations[uuid] = LocationInfo();
it = mLocations.find(uuid);
} else {
// It was already in there as a replica, notify its removal
assert(it->second.local == false);
CONTEXT_SPACETRACE(serverObjectEvent, 0, mContext->id(), uuid, false, TimedMotionVector3f()); // FIXME remote server ID
notifyReplicaObjectRemoved(uuid);
}
LocationInfo& locinfo = it->second;
locinfo.props.reset();
locinfo.props.setLocation(loc, 0);
locinfo.props.setOrientation(orient, 0);
locinfo.props.setBounds(bnds, 0);
locinfo.props.setMesh(Transfer::URI(msh), 0);
locinfo.props.setPhysics(phy, 0);
locinfo.props.setQueryData(query_data, 0);
locinfo.local = true;
locinfo.aggregate = false;
// FIXME: we might want to verify that location(uuid) and bounds(uuid) are
// reasonable compared to the loc and bounds passed in
// Add to the list of local objects
CONTEXT_SPACETRACE(serverObjectEvent, mContext->id(), mContext->id(), uuid, true, loc);
notifyLocalObjectAdded(uuid, false, location(uuid), orientation(uuid), bounds(uuid), mesh(uuid), physics(uuid), query_data);
}
void StandardLocationService::removeLocalObject(const UUID& uuid, const std::tr1::function<void()>&completeCallback) {
// Remove from mLocations, but save the cached state
assert( mLocations.find(uuid) != mLocations.end() );
assert( mLocations[uuid].local == true );
assert( mLocations[uuid].aggregate == false );
mLocations.erase(uuid);
// Remove from the list of local objects
CONTEXT_SPACETRACE(serverObjectEvent, mContext->id(), mContext->id(), uuid, false, TimedMotionVector3f());
notifyLocalObjectRemoved(uuid, false, completeCallback);
// FIXME we might want to give a grace period where we generate a replica if one isn't already there,
// instead of immediately removing all traces of the object.
// However, this needs to be handled carefully, prefer updates from another server, and expire
// automatically.
}
void StandardLocationService::addLocalAggregateObject(const UUID& uuid, const TimedMotionVector3f& loc, const TimedMotionQuaternion& orient, const AggregateBoundingInfo& bnds, const String& msh, const String& phy, const String& query_data) {
// Aggregates get randomly assigned IDs -- if there's a conflict either we
// got a true conflict (incredibly unlikely) or somebody (prox/query
// handler) screwed up.
assert(mLocations.find(uuid) == mLocations.end());
mLocations[uuid] = LocationInfo();
LocationMap::iterator it = mLocations.find(uuid);
LocationInfo& locinfo = it->second;
locinfo.props.reset();
locinfo.props.setLocation(loc, 0);
locinfo.props.setOrientation(orient, 0);
locinfo.props.setBounds(bnds, 0);
locinfo.props.setMesh(Transfer::URI(msh), 0);
locinfo.props.setPhysics(phy, 0);
locinfo.props.setQueryData(query_data, 0);
locinfo.local = true;
locinfo.aggregate = true;
// Add to the list of local objects
notifyLocalObjectAdded(uuid, true, location(uuid), orientation(uuid), bounds(uuid), mesh(uuid), physics(uuid), "");
}
void StandardLocationService::removeLocalAggregateObject(const UUID& uuid, const std::tr1::function<void()>&completeCallback) {
// Remove from mLocations, but save the cached state
assert( mLocations.find(uuid) != mLocations.end() );
assert( mLocations[uuid].local == true );
assert( mLocations[uuid].aggregate == true );
mLocations.erase(uuid);
notifyLocalObjectRemoved(uuid, true, completeCallback);
}
void StandardLocationService::updateLocalAggregateLocation(const UUID& uuid, const TimedMotionVector3f& newval) {
LocationMap::iterator loc_it = mLocations.find(uuid);
assert(loc_it != mLocations.end());
assert(loc_it->second.aggregate == true);
loc_it->second.props.setLocation(newval, 0);
notifyLocalLocationUpdated( uuid, true, newval );
}
void StandardLocationService::updateLocalAggregateOrientation(const UUID& uuid, const TimedMotionQuaternion& newval) {
LocationMap::iterator loc_it = mLocations.find(uuid);
assert(loc_it != mLocations.end());
assert(loc_it->second.aggregate == true);
loc_it->second.props.setOrientation(newval, 0);
notifyLocalOrientationUpdated( uuid, true, newval );
}
void StandardLocationService::updateLocalAggregateBounds(const UUID& uuid, const AggregateBoundingInfo& newval) {
LocationMap::iterator loc_it = mLocations.find(uuid);
assert(loc_it != mLocations.end());
assert(loc_it->second.aggregate == true);
loc_it->second.props.setBounds(newval);
notifyLocalBoundsUpdated( uuid, true, newval );
}
void StandardLocationService::updateLocalAggregateMesh(const UUID& uuid, const String& newval) {
LocationMap::iterator loc_it = mLocations.find(uuid);
assert(loc_it != mLocations.end());
assert(loc_it->second.aggregate == true);
loc_it->second.props.setMesh(Transfer::URI(newval));
notifyLocalMeshUpdated( uuid, true, newval );
}
void StandardLocationService::updateLocalAggregatePhysics(const UUID& uuid, const String& newval) {
LocationMap::iterator loc_it = mLocations.find(uuid);
assert(loc_it != mLocations.end());
assert(loc_it->second.aggregate == true);
loc_it->second.props.setPhysics(newval, 0);
notifyLocalPhysicsUpdated( uuid, true, newval );
}
void StandardLocationService::updateLocalAggregateQueryData(const UUID& uuid, const String& newval) {
LocationMap::iterator loc_it = mLocations.find(uuid);
assert(loc_it != mLocations.end());
assert(loc_it->second.aggregate == true);
loc_it->second.props.setQueryData(newval);
notifyLocalQueryDataUpdated( uuid, true, newval );
}
void StandardLocationService::addReplicaObject(const Time& t, const UUID& uuid, bool agg, const TimedMotionVector3f& loc, const TimedMotionQuaternion& orient, const AggregateBoundingInfo& bnds, const String& msh, const String& phy, const String& query_data) {
// FIXME we should do checks on timestamps to decide which setting is "more" sane
LocationMap::iterator it = mLocations.find(uuid);
if (it != mLocations.end()) {
// It already exists. If its local, ignore the update. If its another replica, somethings out of sync, but perform the update anyway
LocationInfo& locinfo = it->second;
if (!locinfo.local) {
locinfo.props.reset();
locinfo.props.setLocation(loc, 0);
locinfo.props.setOrientation(orient, 0);
locinfo.props.setBounds(bnds, 0);
locinfo.props.setMesh(Transfer::URI(msh), 0);
locinfo.props.setPhysics(phy, 0);
locinfo.props.setQueryData(query_data, 0);
//local = false
// FIXME should we notify location and bounds updated info?
}
// else ignore
}
else {
// Its a new replica, just insert it
LocationInfo locinfo;
locinfo.props.reset();
locinfo.props.setLocation(loc, 0);
locinfo.props.setOrientation(orient, 0);
locinfo.props.setBounds(bnds, 0);
locinfo.props.setMesh(Transfer::URI(msh), 0);
locinfo.props.setPhysics(phy, 0);
locinfo.props.setQueryData(query_data, 0);
locinfo.local = false;
locinfo.aggregate = agg;
mLocations[uuid] = locinfo;
// We only run this notification when the object actually is new
CONTEXT_SPACETRACE(serverObjectEvent, 0, mContext->id(), uuid, true, loc); // FIXME add remote server ID
notifyReplicaObjectAdded(uuid, location(uuid), orientation(uuid), bounds(uuid), mesh(uuid), physics(uuid), query_data);
}
}
void StandardLocationService::removeReplicaObject(const Time& t, const UUID& uuid) {
// FIXME we should maintain some time information and check t against it to make sure this is sane
LocationMap::iterator it = mLocations.find(uuid);
if (it == mLocations.end())
return;
// If the object is marked as local, this is out of date information. Just ignore it.
LocationInfo& locinfo = it->second;
if (locinfo.local)
return;
// Otherwise, remove and notify
mLocations.erase(uuid);
CONTEXT_SPACETRACE(serverObjectEvent, 0, mContext->id(), uuid, false, TimedMotionVector3f()); // FIXME add remote server ID
notifyReplicaObjectRemoved(uuid);
}
void StandardLocationService::receiveMessage(Message* msg) {
assert(msg->dest_port() == SERVER_PORT_LOCATION);
Sirikata::Protocol::Loc::BulkLocationUpdate contents;
bool parsed = parsePBJMessage(&contents, msg->payload());
if (parsed) {
for(int32 idx = 0; idx < contents.update_size(); idx++) {
Sirikata::Protocol::Loc::LocationUpdate update = contents.update(idx);
notifyOnLocationUpdateFromServer(msg->source_server(), update);
// Its possible we'll get an out of date update. We only use this update
// if (a) we have this object marked as a replica object and (b) we don't
// have this object marked as a local object
if (!contains(update.object()) || isLocal(update.object()))
continue;
LocationMap::iterator loc_it = mLocations.find( update.object() );
// We can safely make this assertion right now because space server
// to space server loc and prox are on the same reliable channel. If
// this goes away then a) we can't make this assertion and b) we
// need an OrphanLocUpdateManager to save updates where this
// condition is false so they can be applied once the prox update
// arrives.
assert(loc_it != mLocations.end());
uint64 epoch = 0;
if (update.has_epoch())
epoch = update.epoch();
if (update.has_location()) {
TimedMotionVector3f newloc(
update.location().t(),
MotionVector3f( update.location().position(), update.location().velocity() )
);
loc_it->second.props.setLocation(newloc, epoch);
notifyReplicaLocationUpdated( update.object(), loc_it->second.props.location() );
CONTEXT_SPACETRACE(serverLoc, msg->source_server(), mContext->id(), update.object(), loc_it->second.props.location() );
}
if (update.has_orientation()) {
TimedMotionQuaternion neworient(
update.orientation().t(),
MotionQuaternion( update.orientation().position(), update.orientation().velocity() )
);
loc_it->second.props.setOrientation(neworient, epoch);
notifyReplicaOrientationUpdated( update.object(), loc_it->second.props.orientation() );
}
if (update.has_aggregate_bounds()) {
Vector3f center = update.aggregate_bounds().has_center_offset() ? update.aggregate_bounds().center_offset() : Vector3f(0,0,0);
float32 center_rad = update.aggregate_bounds().has_center_bounds_radius() ? update.aggregate_bounds().center_bounds_radius() : 0.f;
float32 max_object_size = update.aggregate_bounds().has_max_object_size() ? update.aggregate_bounds().max_object_size() : 0.f;
AggregateBoundingInfo newbounds(center, center_rad, max_object_size);
loc_it->second.props.setBounds(newbounds, epoch);
notifyReplicaBoundsUpdated( update.object(), loc_it->second.props.bounds() );
}
if (update.has_mesh()) {
String newmesh = update.mesh();
loc_it->second.props.setMesh(Transfer::URI(newmesh), epoch);
notifyReplicaMeshUpdated( update.object(), loc_it->second.props.mesh().toString() );
}
if (update.has_physics()) {
String newphy = update.physics();
loc_it->second.props.setPhysics(newphy, epoch);
notifyReplicaPhysicsUpdated( update.object(), loc_it->second.props.physics() );
}
if (update.has_query_data()) {
String newqd = update.query_data();
loc_it->second.props.setQueryData(newqd, epoch);
notifyReplicaQueryDataUpdated( update.object(), loc_it->second.props.queryData() );
}
}
}
delete msg;
}
bool StandardLocationService::locationUpdate(UUID source, void* buffer, uint32 length) {
Sirikata::Protocol::Loc::Container loc_container;
bool parse_success = loc_container.ParseFromString( String((char*) buffer, length) );
if (!parse_success) {
// Since we don't have framing on these, we can't really log this since
// some packets will require more than SST's 1000 byte default packet
// size and it would spam the console.
//LOG_INVALID_MESSAGE_BUFFER(standardloc, error, ((char*)buffer), length);
return false;
}
if (loc_container.has_update_request()) {
Sirikata::Protocol::Loc::LocationUpdateRequest request = loc_container.update_request();
if (isLocal(source)) {
LocationMap::iterator loc_it = mLocations.find( source );
assert(loc_it != mLocations.end());
uint64 epoch = 0;
if (request.has_epoch())
epoch = request.epoch();
if (request.has_location()) {
TimedMotionVector3f newloc(
request.location().t(),
MotionVector3f( request.location().position(), request.location().velocity() )
);
loc_it->second.props.setLocation(newloc, epoch);
notifyLocalLocationUpdated( source, loc_it->second.aggregate, loc_it->second.props.location() );
CONTEXT_SPACETRACE(serverLoc, mContext->id(), mContext->id(), source, loc_it->second.props.location() );
}
if (request.has_orientation()) {
TimedMotionQuaternion neworient(
request.orientation().t(),
MotionQuaternion( request.orientation().position(), request.orientation().velocity() )
);
loc_it->second.props.setOrientation(neworient, epoch);
notifyLocalOrientationUpdated( source, loc_it->second.aggregate, loc_it->second.props.orientation() );
}
if (request.has_bounds()) {
AggregateBoundingInfo newbounds(request.bounds());
loc_it->second.props.setBounds(newbounds, epoch);
notifyLocalBoundsUpdated( source, loc_it->second.aggregate, loc_it->second.props.bounds() );
}
if (request.has_mesh()) {
String newmesh = request.mesh();
loc_it->second.props.setMesh(Transfer::URI(newmesh), epoch);
notifyLocalMeshUpdated( source, loc_it->second.aggregate, loc_it->second.props.mesh().toString() );
}
if (request.has_physics()) {
String newphy = request.physics();
loc_it->second.props.setPhysics(newphy, epoch);
notifyLocalPhysicsUpdated( source, loc_it->second.aggregate, loc_it->second.props.physics() );
}
if (request.has_query_data()) {
String newqd = request.query_data();
loc_it->second.props.setQueryData(newqd, epoch);
notifyLocalQueryDataUpdated( source, loc_it->second.aggregate, loc_it->second.props.queryData() );
}
}
else {
// Warn about update to non-local object
}
}
return true;
}
// Command handlers
void StandardLocationService::commandProperties(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) {
Command::Result result = Command::EmptyResult();
result.put("name", "standard");
// FIXME we could track these as we add/remove objects so they'd be cheaper
// to compute
uint32 local_count = 0, aggregate_count = 0, local_aggregate_count = 0;
for(LocationMap::iterator it = mLocations.begin(); it != mLocations.end(); it++) {
if (it->second.local) local_count++;
if (it->second.aggregate) aggregate_count++;
if (it->second.local && it->second.aggregate) local_aggregate_count++;
}
result.put("objects.count", mLocations.size());
result.put("objects.local_count", local_count);
result.put("objects.aggregate_count", aggregate_count);
result.put("objects.local_aggregate_count", local_aggregate_count);
cmdr->result(cmdid, result);
}
void StandardLocationService::commandObjectProperties(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) {
Command::Result result = Command::EmptyResult();
String obj_string = cmd.getString("object", "");
if (obj_string.empty()) { // not specified
result.put("error", "Ill-formatted request: no object specified.");
cmdr->result(cmdid, result);
return;
}
UUID objid(obj_string, UUID::HumanReadable());
LocationMap::iterator it = mLocations.find(objid);
if (it == mLocations.end()) {
result.put("error", "Object not found.");
cmdr->result(cmdid, result);
return;
}
Time t = mContext->recentSimTime();
TimedMotionVector3f pos(t, it->second.props.location().extrapolate(t));
result.put("properties.location.position.x", pos.position().x);
result.put("properties.location.position.y", pos.position().y);
result.put("properties.location.position.z", pos.position().z);
result.put("properties.location.velocity.x", pos.velocity().x);
result.put("properties.location.velocity.y", pos.velocity().y);
result.put("properties.location.velocity.z", pos.velocity().z);
result.put("properties.location.time", pos.updateTime().raw());
TimedMotionQuaternion orient(t, it->second.props.orientation().extrapolate(t));
result.put("properties.orientation.position.x", orient.position().x);
result.put("properties.orientation.position.y", orient.position().y);
result.put("properties.orientation.position.z", orient.position().z);
result.put("properties.orientation.position.w", orient.position().w);
result.put("properties.orientation.velocity.x", orient.velocity().x);
result.put("properties.orientation.velocity.y", orient.velocity().y);
result.put("properties.orientation.velocity.z", orient.velocity().z);
result.put("properties.orientation.velocity.w", orient.velocity().w);
result.put("properties.orientation.time", orient.updateTime().raw());
// Present the bounds info in a way the consumer can easily draw a bounding
// sphere, especially for single objects
result.put("properties.bounds.center.x", it->second.props.bounds().centerOffset.x);
result.put("properties.bounds.center.y", it->second.props.bounds().centerOffset.y);
result.put("properties.bounds.center.z", it->second.props.bounds().centerOffset.z);
result.put("properties.bounds.radius", it->second.props.bounds().fullRadius());
// But also provide the other info so a correct view of
// aggregates. Technically we only need one of these since fullRadius is the
// sum of the two, but this is clearer.
result.put("properties.bounds.centerBoundsRadius", it->second.props.bounds().centerBoundsRadius);
result.put("properties.bounds.maxObjectRadius", it->second.props.bounds().maxObjectRadius);
result.put("properties.mesh", it->second.props.mesh().toString());
result.put("properties.physics", it->second.props.physics());
result.put("properties.local", it->second.local);
result.put("properties.aggregate", it->second.aggregate);
result.put("success", true);
cmdr->result(cmdid, result);
}
} // namespace Sirikata
| 44.153982
| 259
| 0.678839
|
sirikata
|
e6b96c963aaa6ff7916ac2f32554582f6b03240e
| 1,062
|
cpp
|
C++
|
cpp/tut/main.cpp
|
VeerabadraLokesh/miniature-guide
|
057e524ed8ffdac15cfaa9585800235234306225
|
[
"MIT"
] | null | null | null |
cpp/tut/main.cpp
|
VeerabadraLokesh/miniature-guide
|
057e524ed8ffdac15cfaa9585800235234306225
|
[
"MIT"
] | null | null | null |
cpp/tut/main.cpp
|
VeerabadraLokesh/miniature-guide
|
057e524ed8ffdac15cfaa9585800235234306225
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
// typedef int age;
int main() {
cout << "Hello world\n";
/* in comment */
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of long int : " << sizeof(long long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
typedef int age;
age my_age = 100;
cout << "my age: " << my_age << endl;
{
// enums
enum color { red, green, black=9, blue, gray } a, b; a = red; b = green;
color c = blue, d = black, e = gray;
cout << "color a: " << a << endl << "color b: " << b << endl << "color c: " << c << endl << "color d: " << d << endl << "color e: " << e << endl;
}
int a, b, c, d, e;
// return
return 0;
}
| 27.947368
| 153
| 0.496234
|
VeerabadraLokesh
|
e6b9929694ad270fa8eb8773d4405e37393a483b
| 307
|
cpp
|
C++
|
tapi-master/test/Inputs/CPP3/CPP3.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
tapi-master/test/Inputs/CPP3/CPP3.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
tapi-master/test/Inputs/CPP3/CPP3.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
#include "VTable.h"
// VTables
void test1::Simple::run() {}
void test2::Simple::run() {}
void test4::Sub::run() {}
void test5::Sub::run() {}
void test6::Sub::run() {}
void test11::Sub::run3() {}
template class test12::Simple<int>;
// Weak-Defined RTTI
__attribute__((visibility("hidden"))) test7::Sub a;
| 20.466667
| 51
| 0.651466
|
JunyiXie
|
e6c2d5cace421836c90ab3fdc38b5e709d856b51
| 76
|
cpp
|
C++
|
gtest_test/tests/testgtest2.cpp
|
darkenk/playground
|
ab1cf2585d27bdda65555bdd52aa7d7dafd9a430
|
[
"MIT"
] | null | null | null |
gtest_test/tests/testgtest2.cpp
|
darkenk/playground
|
ab1cf2585d27bdda65555bdd52aa7d7dafd9a430
|
[
"MIT"
] | null | null | null |
gtest_test/tests/testgtest2.cpp
|
darkenk/playground
|
ab1cf2585d27bdda65555bdd52aa7d7dafd9a430
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
TEST(SimpleTest2, Test1)
{
EXPECT_EQ(3, 2);
}
| 10.857143
| 24
| 0.644737
|
darkenk
|
e6c3773935366bf41cb30bfd9608e9495c028d0c
| 99
|
cc
|
C++
|
cpp/accelerated_c++/chapter08/my_max.cc
|
zhouzhiqi/book_and_code
|
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
|
[
"Apache-2.0"
] | null | null | null |
cpp/accelerated_c++/chapter08/my_max.cc
|
zhouzhiqi/book_and_code
|
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
|
[
"Apache-2.0"
] | null | null | null |
cpp/accelerated_c++/chapter08/my_max.cc
|
zhouzhiqi/book_and_code
|
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
|
[
"Apache-2.0"
] | null | null | null |
template <class T>
T max(const T& left, const T& right)
{
return left > right ? left : right;
}
| 14.142857
| 36
| 0.636364
|
zhouzhiqi
|
e6c70fea1a7bfd84c3ff6fd041fb3ef65e4992a2
| 28,735
|
cpp
|
C++
|
csl/cslbase/arith12.cpp
|
arthurcnorman/general
|
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
|
[
"BSD-2-Clause"
] | null | null | null |
csl/cslbase/arith12.cpp
|
arthurcnorman/general
|
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
|
[
"BSD-2-Clause"
] | null | null | null |
csl/cslbase/arith12.cpp
|
arthurcnorman/general
|
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
|
[
"BSD-2-Clause"
] | null | null | null |
// arith12.cpp Copyright (C) 1990-2020 Codemist
//
// Arithmetic functions... specials for Reduce (esp. factoriser)
//
//
/**************************************************************************
* Copyright (C) 2020, Codemist. A C Norman *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are *
* met: *
* *
* * Redistributions of source code must retain the relevant *
* copyright notice, this list of conditions and the following *
* disclaimer. *
* * Redistributions in binary form must reproduce the above *
* copyright notice, this list of conditions and the following *
* disclaimer in the documentation and/or other materials provided *
* with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* COPYRIGHT OWNERS 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. *
*************************************************************************/
// $Id: arith12.cpp 5390 2020-09-03 20:57:57Z arthurcnorman $
#include "headers.h"
#define FP_EVALUATE 1
LispObject Lfrexp(LispObject env, LispObject a)
{
#ifdef HAVE_SOFTFLOAT
if (is_long_float(a))
{ float128_t d;
int x;
f128M_frexp(reinterpret_cast<float128_t *>(long_float_addr(a)), &d,
&x);
return cons(fixnum_of_int(x), make_boxfloat128(d));
}
else
#endif // HAVE_SOFTFLOAT
if (is_single_float(a))
{ int x;
float d = std::frexp(single_float_val(a), &x);
return cons(fixnum_of_int(x), pack_single_float(d));
}
else if (is_short_float(a))
{ int x;
// I can afford to do the frexp on a double here.
double d = std::frexp(value_of_immediate_float(a), &x);
return cons(fixnum_of_int(x), pack_short_float(d));
}
else
{ int x;
double d = std::frexp(float_of_number(a), &x);
// I clearly once encountered a C library that failed on this edge case!
if (d == 1.0) d = 0.5, x++;
return cons(fixnum_of_int(x),make_boxfloat(d));
}
}
// N.B. that the modular arithmetic functions must cope with any small
// modulus that could fit in a fixnum.
LispObject Lmodular_difference(LispObject env, LispObject a,
LispObject b)
{ intptr_t r;
if (!modulus_is_large)
{ if (!is_fixnum(a)) return aerror1("modular-difference", a);
if (!is_fixnum(b)) return aerror1("modular-difference", b);
r = int_of_fixnum(a) - int_of_fixnum(b);
if (r < 0) r += current_modulus;
return onevalue(fixnum_of_int(r));
}
a = difference2(a, b);
return modulus(a, large_modulus);
}
LispObject Lmodular_minus(LispObject env, LispObject a)
{ if (!modulus_is_large)
{ if (!is_fixnum(a)) return aerror1("modular-minus", a);
if (a != fixnum_of_int(0))
{ intptr_t r = current_modulus - int_of_fixnum(a);
a = fixnum_of_int(r);
}
return onevalue(a);
}
a = negate(a);
return modulus(a, large_modulus);
}
LispObject Lmodular_number(LispObject env, LispObject a)
{ intptr_t r;
if (!modulus_is_large)
{ a = Cremainder(a, fixnum_of_int(current_modulus));
r = int_of_fixnum(a);
if (r < 0) r += current_modulus;
return onevalue(fixnum_of_int(r));
}
return modulus(a, large_modulus);
}
LispObject Lmodular_plus(LispObject env, LispObject a, LispObject b)
{ intptr_t r;
if (!modulus_is_large)
{ if (!is_fixnum(a)) return aerror1("modular-plus", a);
if (!is_fixnum(b)) return aerror1("modular-plus", b);
r = int_of_fixnum(a) + int_of_fixnum(b);
if (r >= current_modulus) r -= current_modulus;
return onevalue(fixnum_of_int(r));
}
a = plus2(a, b);
return modulus(a, large_modulus);
}
LispObject large_modular_reciprocal(LispObject n, bool safe)
{ LispObject a, b, x, y;
b = n;
x = fixnum_of_int(0);
y = fixnum_of_int(1);
if (b == fixnum_of_int(0))
{ if (safe) return onevalue(nil);
else return aerror1("modular-reciprocal", n);
}
b = modulus(b, large_modulus);
a = large_modulus;
while (b != fixnum_of_int(1))
{ LispObject w, t;
if (b == fixnum_of_int(0))
{ if (safe) return onevalue(nil);
else return aerror2("non-prime modulus in modular-reciprocal",
large_modulus, n);
}
push(x, y);
w = quot2(a, b);
pop(y, x);
t = b;
push(a, x, y, w, t);
b = times2(b, w);
pop(t, w, y, x, a);
push(x, y, w, t);
b = difference2(a, b);
pop(t, w, y, x);
a = t;
t = y;
push(a, b, x, t);
y = times2(y, w);
pop(t, x, b, a);
push(a, b, t);
y = difference2(x, y);
pop(t, b, a);
x = t;
}
y = modulus(y, large_modulus);
return onevalue(y);
}
LispObject Lmodular_reciprocal(LispObject, LispObject n)
{ intptr_t a, b, x, y;
if (modulus_is_large) return large_modular_reciprocal(n, false);
// If the modulus is "small" I can do all this using native integer
// arithmetic.
if (!is_fixnum(n)) return aerror1("modular-reciprocal", n);
a = current_modulus;
b = int_of_fixnum(n);
x = 0;
y = 1;
if (b == 0) return aerror1("modular-reciprocal", n);
if (b < 0) b = current_modulus - ((-b)%current_modulus);
while (b != 1)
{ intptr_t w, t;
if (b == 0)
return aerror2("non-prime modulus in modular-reciprocal",
fixnum_of_int(current_modulus), n);
w = a / b;
t = b;
b = a - b*w;
a = t;
t = y;
y = x - y*w;
x = t;
}
if (y < 0) y += current_modulus;
return onevalue(fixnum_of_int(y));
}
LispObject Lsafe_modular_reciprocal(LispObject env, LispObject n)
{ intptr_t a, b, x, y;
if (modulus_is_large) return large_modular_reciprocal(n, true);
if (!is_fixnum(n)) return aerror1("modular-reciprocal", n);
a = current_modulus;
b = int_of_fixnum(n);
x = 0;
y = 1;
if (b == 0) return onevalue(nil);
if (b < 0) b = current_modulus - ((-b)%current_modulus);
while (b != 1)
{ intptr_t w, t;
if (b == 0) return onevalue(nil);
w = a / b;
t = b;
b = a - b*w;
a = t;
t = y;
y = x - y*w;
x = t;
}
if (y < 0) y += current_modulus;
return onevalue(fixnum_of_int(y));
}
LispObject Lmodular_times(LispObject env, LispObject a, LispObject b)
{ uintptr_t cm;
intptr_t aa, bb;
if (!modulus_is_large)
{ if (!is_fixnum(a)) return aerror1("modular-times", a);
if (!is_fixnum(b)) return aerror1("modular-times", b);
cm = (uintptr_t)current_modulus;
aa = int_of_fixnum(a);
bb = int_of_fixnum(b);
// If I am on a 32-bit machine and the modulus is at worst 16 bits I can use
// 32-bit arithmetic to complete the job.
if (!SIXTY_FOUR_BIT && cm <= 0xffffU)
{ uint32_t r = ((uint32_t)aa * (uint32_t)bb) % (uint32_t)cm;
return onevalue(fixnum_of_int((intptr_t)r));
}
// On a 32 or 64-bit machine if the modulus is at worst 32 bits I can do
// a 64-bit (unsigned) multiplication and remainder step.
else if (cm <= 0xffffffffU)
{ uint64_t r = ((uint64_t)aa*(uint64_t)bb) % (uint64_t)cm;
// Because I am in a state where modulus_is_large is not set I know that the
// modulus fits in a fixnum, hence the result will. So even though all value
// that are of type uint64_t might not be valid as fixnums the one I have
// here will be.
return onevalue(fixnum_of_int((intptr_t)r));
}
// Now my modulus is over 32-bits...
// Using an int128_t bit type I can use it and the code is really neat!
// On some platforms this goes via C++ templates and operator overloading
// into a software implementation of 128-bit integer arithmetic!
else
{ int64_t r = static_cast<int64_t>(
(static_cast<int128_t>(aa) * static_cast<int128_t>(bb)) %
static_cast<int128_t>(cm));
return onevalue(fixnum_of_int((intptr_t)r));
}
}
a = times2(a, b);
return modulus(a, large_modulus);
}
LispObject Lmodular_quotient(LispObject env, LispObject a,
LispObject b)
{ push(a);
b = Lmodular_reciprocal(nil, b);
pop(a);
return Lmodular_times(nil, a, b);
}
LispObject large_modular_expt(LispObject a, int x)
{ LispObject r, p, w;
p = modulus(a, large_modulus);
while ((x & 1) == 0)
{ p = times2(p, p);
p = modulus(p, large_modulus);
x = x/2;
}
r = p;
while (x != 1)
{ push(r);
w = times2(p, p);
pop(r);
push(r);
p = modulus(w, large_modulus);
pop(r);
x = x/2;
if ((x & 1) != 0)
{ push(p);
w = times2(r, p);
pop(p);
push(p);
r = modulus(w, large_modulus);
pop(p);
}
}
return onevalue(r);
}
inline intptr_t muldivptr(uintptr_t a, uintptr_t b, uintptr_t c)
{ if (!SIXTY_FOUR_BIT || c <= 0xffffffffU)
return ((uint64_t)a*(uint64_t)b)%(uintptr_t)c;
else return (intptr_t)static_cast<int64_t>(
(uint128((uint64_t)a) * uint128((uint64_t)a)) % (uintptr_t)c);
}
LispObject Lmodular_expt(LispObject env, LispObject a, LispObject b)
{ intptr_t x, r, p;
x = int_of_fixnum(b);
if (x == 0) return onevalue(fixnum_of_int(1));
if (modulus_is_large) return large_modular_expt(a, x);
p = int_of_fixnum(a);
p = p % current_modulus; // In case somebody is being silly!
// I now want this to work for any modulus up to the size of the largest
// fixnum. That could be 60-bits in the newer world. The function
// muldivptr takes unsigned arguments but that should be OK because any
// valid modulus and any valid modular number will be positive.
while ((x & 1) == 0)
{ p = muldivptr((uintptr_t)p, (uintptr_t)p,
(uintptr_t)current_modulus);
x = x/2;
}
r = p;
while (x != 1)
{ p = muldivptr((uintptr_t)p, (uintptr_t)p,
(uintptr_t)current_modulus);
x = x/2;
if ((x & 1) != 0)
{ r = muldivptr((uintptr_t)r, (uintptr_t)p,
(uintptr_t)current_modulus);
}
}
return onevalue(fixnum_of_int(r));
}
// I can set any (positive) integer as a modulus here. I will treat it
// internally as "small" if it fits in a fixnum.
LispObject Lset_small_modulus(LispObject env, LispObject a)
{ LispObject old = modulus_is_large ? large_modulus :
fixnum_of_int(current_modulus);
if (a==nil) return onevalue(old);
else if (!is_fixnum(a))
{ if (!is_numbers(a) ||
!is_bignum(a) ||
minusp(a))
return aerror1("set-small-modulus", a);
modulus_is_large = 1;
current_modulus = 0; // should not be referenced.
large_modulus = a;
return old;
}
if ((intptr_t)a < 0 || a == fixnum_of_int(0))
return aerror1("set!-small!-modulus", a);
modulus_is_large = 0;
large_modulus = nil; // Should not be referenced.
current_modulus = int_of_fixnum(a);;
return onevalue(old);
}
LispObject Liadd1(LispObject, LispObject a)
{ if (!is_fixnum(a)) return aerror1("iadd1", a);
return onevalue(static_cast<LispObject>((intptr_t)a + 0x10));
}
LispObject Lidifference_2(LispObject, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("idifference", a, b);
return onevalue(static_cast<LispObject>((intptr_t)a -
(intptr_t)b + TAG_FIXNUM));
}
//
// xdifference is provided just for the support of the CASE operator. It
// subtracts its arguments but returns NIL if either argument is not
// an small integer or if the result overflows. Small is 28-bits in this
// context at present, which is maybe strange!
//
LispObject Lxdifference(LispObject env, LispObject a, LispObject b)
{ int32_t r;
if (!is_fixnum(a) || !is_fixnum(b)) return onevalue(nil);
r = int_of_fixnum(a) - int_of_fixnum(b);
if (r < -0x08000000 || r > 0x07ffffff) return onevalue(nil);
return onevalue(fixnum_of_int(r));
}
LispObject Ligreaterp_2(LispObject env, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("igreaterp", a, b);
return onevalue(Lispify_predicate(a > b));
}
LispObject Lilessp_2(LispObject env, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("ilessp", a, b);
return onevalue(Lispify_predicate(a < b));
}
LispObject Ligeq_2(LispObject env, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("igeq", a, b);
return onevalue(Lispify_predicate(a >= b));
}
LispObject Lileq_2(LispObject env, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("ileq", a, b);
return onevalue(Lispify_predicate(a <= b));
}
static LispObject Lilogand_0(LispObject)
{ return onevalue(fixnum_of_int(-1));
}
static LispObject Lilogor_0(LispObject)
{ return onevalue(fixnum_of_int(0));
}
static LispObject Lilogxor_0(LispObject)
{ return onevalue(fixnum_of_int(0));
}
static LispObject Lilogand_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
static LispObject Lilogor_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
static LispObject Lilogxor_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
static LispObject Lilogand_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("ilogand", a1, a2);
return onevalue(a1 & a2);
}
static LispObject Lilogor_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("ilogor", a1, a2);
return onevalue(a1 | a2);
}
static LispObject Lilogxor_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("ilogxor", a1, a2);
return onevalue((a1 ^ a2) + TAG_FIXNUM);
}
static LispObject Lilogand_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogand", a2, a2, a3);
return onevalue(a1 & a2 & a3);
}
static LispObject Lilogor_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogor", a2, a2, a3);
return onevalue(a1 | a2 | a3);
}
static LispObject Lilogxor_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogxor", a2, a2, a3);
return onevalue(a1 ^ a2 ^ a3);
}
static LispObject Lilogand_4up(LispObject env, LispObject a1,
LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogand", a2, a2, a3);
a1 = a1 & a2 & a3;
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("ilogand", a2);
a1 = a1 & a2;
}
return onevalue(a1);
}
static LispObject Lilogor_4up(LispObject env, LispObject a1,
LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogor", a2, a2, a3);
a1 = a1 | a2 | a3;
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("ilogor", a2);
a1 = a1 | a2;
}
return onevalue(a1);
}
static LispObject Lilogxor_4up(LispObject env, LispObject a1,
LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogxor", a2, a2, a3);
a1 = a1 ^ a2 ^ a3;
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("ilogxor", a2);
a1 = a1 ^ a2;
}
a1 = (a1 & ~static_cast<LispObject>(TAG_BITS)) | TAG_FIXNUM;
return onevalue(a1);
}
LispObject Limin_2(LispObject, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("imin", a, b);
return onevalue(a < b ? a : b);
}
LispObject Limax_2(LispObject, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("imax", a, b);
return onevalue(a > b ? a : b);
}
LispObject Liminus(LispObject, LispObject a)
{ if (!is_fixnum(a)) return aerror1("iminus", a);
return onevalue(static_cast<LispObject>(2*TAG_FIXNUM - (intptr_t)a));
}
LispObject Liminusp(LispObject env, LispObject a)
{ return onevalue(Lispify_predicate((intptr_t)a <
(intptr_t)fixnum_of_int(0)));
}
LispObject Liplus_0(LispObject)
{ return onevalue(fixnum_of_int(1));
}
LispObject Liplus_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
LispObject Liplus_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("iplus2", a1, a2);
return onevalue(static_cast<LispObject>((intptr_t)a1 +
(intptr_t)a2 - TAG_FIXNUM));
}
LispObject Liplus_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("iplus", a1, a2, a3);
return onevalue(static_cast<LispObject>((intptr_t)a1 +
(intptr_t)a2 - 2*TAG_FIXNUM +
(intptr_t)a3));
}
static LispObject Liplus_4up(LispObject, LispObject a1, LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("iplus", a1, a2, a3);
a1 = (intptr_t)a1 + (intptr_t)a2 - 2*TAG_FIXNUM + (intptr_t)a3;
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("iplus", a2);
a1 = a1 + (intptr_t)a2 - TAG_FIXNUM;
}
return onevalue(a1);
}
LispObject Liquotient_2(LispObject, LispObject a, LispObject b)
{ intptr_t aa, bb, c;
if (!is_fixnum(a) || !is_fixnum(b) ||
b == fixnum_of_int(0)) return aerror2("iquotient", a, b);
// C does not define the exact behaviour of /, % on -ve args
aa = int_of_fixnum(a);
bb = int_of_fixnum(b);
c = aa % bb;
if (aa < 0)
{ if (c > 0) c -= bb;
}
else if (c < 0) c += bb;
return onevalue(fixnum_of_int((aa-c)/bb));
}
LispObject Liremainder_2(LispObject, LispObject a, LispObject b)
{ intptr_t aa, bb, c;
if (!is_fixnum(a) || !is_fixnum(b) ||
b == fixnum_of_int(0)) return aerror2("iremainder", a, b);
// C does not define the exact behaviour of /, % on -ve args
aa = int_of_fixnum(a);
bb = int_of_fixnum(b);
c = aa % bb;
if (aa < 0)
{ if (c > 0) c -= bb;
}
else if (c < 0) c += bb;
return onevalue(fixnum_of_int(c));
}
LispObject Lirightshift(LispObject, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("irightshift", a, b);
return onevalue(fixnum_of_int(int_of_fixnum(a) >> int_of_fixnum(b)));
}
LispObject Lisub1(LispObject, LispObject a)
{ if (!is_fixnum(a)) return aerror1("isub1", a);
return onevalue(static_cast<LispObject>((intptr_t)a - 0x10));
}
LispObject Litimes_0(LispObject)
{ return onevalue(fixnum_of_int(1));
}
LispObject Litimes_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
LispObject Litimes_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("itimes2", a1, a2);
return onevalue(fixnum_of_int(int_of_fixnum(a1) * int_of_fixnum(a2)));
}
LispObject Litimes_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("itimes", a1, a2, a3);
return onevalue(fixnum_of_int(int_of_fixnum(a1) *
int_of_fixnum(a2) *
int_of_fixnum(a3)));
}
static LispObject Litimes_4up(LispObject env, LispObject a1,
LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("iplus", a1, a2, a3);
intptr_t r = int_of_fixnum(a1) * int_of_fixnum(a2) * int_of_fixnum(
a3);
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("itimes", a2);
r = r * int_of_fixnum(a2);
}
return onevalue(fixnum_of_int(r));
}
LispObject Lionep(LispObject env, LispObject a)
{ return onevalue(Lispify_predicate((intptr_t)a ==
(intptr_t)fixnum_of_int(1)));
}
LispObject Lizerop(LispObject env, LispObject a)
{ return onevalue(Lispify_predicate((intptr_t)a ==
(intptr_t)fixnum_of_int(0)));
}
#ifdef FP_EVALUATE
static double fp_args[32];
static double fp_stack[16];
// codes 0 to 31 just load up arguments
#define FP_RETURN 32
#define FP_PLUS 33
#define FP_DIFFERENCE 34
#define FP_TIMES 35
#define FP_QUOTIENT 36
#define FP_MINUS 37
#define FP_SQUARE 38
#define FP_CUBE 39
#define FP_SIN 40
#define FP_COS 41
#define FP_TAN 42
#define FP_EXP 43
#define FP_LOG 44
#define FP_SQRT 45
static LispObject Lfp_eval(LispObject env, LispObject code,
LispObject args)
//
// The object of this code is to support fast evaluation of numeric
// expressions. The first argument is a vector of byte opcodes, while
// the second arg is a list of floating point values whose value will (or
// at least may) be used. There are at most 32 values in this list.
//
{ int n = 0;
double w;
unsigned char *p;
if (!is_vector(code)) return aerror("fp-evaluate");
while (consp(args))
{ fp_args[n++] = float_of_number(car(args));
args = cdr(args);
}
n = 0;
p = reinterpret_cast<unsigned char *>(&ucelt(code, 0));
for (;;)
{ int op = *p++;
//
// Opcodes 0 to 31 just load up the corresponding input value.
//
if (op < 32)
{ fp_stack[n++] = fp_args[op];
continue;
}
switch (op)
{ default:
return aerror("Bad op in fp-evaluate");
case FP_RETURN:
args = make_boxfloat(fp_stack[0], TYPE_DOUBLE_FLOAT);
return onevalue(args);
case FP_PLUS:
n--;
fp_stack[n] += fp_stack[n-1];
continue;
case FP_DIFFERENCE:
n--;
fp_stack[n] -= fp_stack[n-1];
continue;
case FP_TIMES:
n--;
fp_stack[n] *= fp_stack[n-1];
continue;
case FP_QUOTIENT:
n--;
fp_stack[n] /= fp_stack[n-1];
continue;
case FP_MINUS:
fp_stack[n] = -fp_stack[n];
continue;
case FP_SQUARE:
fp_stack[n] *= fp_stack[n];
continue;
case FP_CUBE:
w = fp_stack[n];
w *= w;
fp_stack[n] *= w;
continue;
case FP_SIN:
fp_stack[n] = std::sin(fp_stack[n]);
continue;
case FP_COS:
fp_stack[n] = std::cos(fp_stack[n]);
continue;
case FP_TAN:
fp_stack[n] = std::tan(fp_stack[n]);
continue;
case FP_EXP:
fp_stack[n] = std::exp(fp_stack[n]);
continue;
case FP_LOG:
fp_stack[n] = std::log(fp_stack[n]);
continue;
case FP_SQRT:
fp_stack[n] = std::sqrt(fp_stack[n]);
continue;
}
}
}
#endif
setup_type const arith12_setup[] =
{ {"frexp", G0W1, Lfrexp, G2W1, G3W1, G4W1},
{"modular-difference", G0W2, G1W2, Lmodular_difference, G3W2, G4W2},
{"modular-minus", G0W1, Lmodular_minus, G2W1, G3W1, G4W1},
{"modular-number", G0W1, Lmodular_number, G2W1, G3W1, G4W1},
{"modular-plus", G0W2, G1W2, Lmodular_plus, G3W2, G4W2},
{"modular-quotient", G0W2, G1W2, Lmodular_quotient, G3W2, G4W2},
{"modular-reciprocal", G0W1, Lmodular_reciprocal, G2W1, G3W1, G4W1},
{"safe-modular-reciprocal", G0W1, Lsafe_modular_reciprocal, G2W1, G3W1, G4W1},
{"modular-times", G0W2, G1W2, Lmodular_times, G3W2, G4W2},
{"modular-expt", G0W2, G1W2, Lmodular_expt, G3W2, G4W2},
{"set-small-modulus", G0W1, Lset_small_modulus, G2W1, G3W1, G4W1},
{"iadd1", G0W1, Liadd1, G2W1, G3W1, G4W1},
{"idifference", G0W2, G1W2, Lidifference_2, G3W2, G4W2},
{"xdifference", G0W2, G1W2, Lxdifference, G3W2, G4W2},
{"igeq", G0W2, G1W2, Ligeq_2, G3W2, G4W2},
{"igreaterp", G0W2, G1W2, Ligreaterp_2, G3W2, G4W2},
{"ileq", G0W2, G1W2, Lileq_2, G3W2, G4W2},
{"ilessp", G0W2, G1W2, Lilessp_2, G3W2, G4W2},
{"ilogand", Lilogand_0, Lilogand_1, Lilogand_2, Lilogand_3, Lilogand_4up},
{"ilogor", Lilogor_0, Lilogor_1, Lilogor_2, Lilogor_3, Lilogor_4up},
{"ilogxor", Lilogxor_0, Lilogxor_1, Lilogxor_2, Lilogxor_3, Lilogxor_4up},
{"imax", G0W2, G1W2, Limax_2, G3W2, G4W2},
{"imin", G0W2, G1W2, Limin_2, G3W2, G4W2},
{"iminus", G0W1, Liminus, G2W1, G3W1, G4W1},
{"iminusp", G0W1, Liminusp, G2W1, G3W1, G4W1},
{"iplus", Liplus_0, Liplus_1, Liplus_2, Liplus_3, Liplus_4up},
{"iplus2", G0W2, G1W2, Liplus_2, G3W2, G4W2},
{"iquotient", G0W2, G1W2, Liquotient_2, G3W2, G4W2},
{"iremainder", G0W2, G1W2, Liremainder_2, G3W2, G4W2},
{"irightshift", G0W2, G1W2, Lirightshift, G3W2, G4W2},
{"isub1", G0W1, Lisub1, G2W1, G3W1, G4W1},
{"itimes", Litimes_0, Litimes_1, Litimes_2, Litimes_3, Litimes_4up},
{"itimes2", G0W2, G1W2, Litimes_2, G3W2, G4W2},
{"ionep", G0W1, Lionep, G2W1, G3W1, G4W1},
{"izerop", G0W1, Lizerop, G2W1, G3W1, G4W1},
#ifdef FP_EVALUATE
{"fp-evaluate", G0W2, G1W2, Lfp_eval, G3W2, G4W2},
#endif
{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}
};
// end of arith12.cpp
| 35.344403
| 94
| 0.569549
|
arthurcnorman
|
e6cc3d65cd87b32abc8cad03dd09a7494a88218b
| 3,121
|
cpp
|
C++
|
test/enum.cpp
|
leoetlino/c4core
|
cfd3060287aa1d8bf0f4de7c427d2fab0f816bd1
|
[
"MIT"
] | null | null | null |
test/enum.cpp
|
leoetlino/c4core
|
cfd3060287aa1d8bf0f4de7c427d2fab0f816bd1
|
[
"MIT"
] | null | null | null |
test/enum.cpp
|
leoetlino/c4core
|
cfd3060287aa1d8bf0f4de7c427d2fab0f816bd1
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <c4/enum.hpp>
#include <c4/test.hpp>
#include "./enum_common.hpp"
#include "c4/libtest/supprwarn_push.hpp"
TEST(eoffs, simple_enum)
{
using namespace c4;
EXPECT_EQ(eoffs_cls<MyEnum>(), 0);
EXPECT_EQ(eoffs_pfx<MyEnum>(), 0);
}
TEST(eoffs, scoped_enum)
{
using namespace c4;
EXPECT_EQ(eoffs_cls<MyEnumClass>(), strlen("MyEnumClass::"));
EXPECT_EQ(eoffs_pfx<MyEnumClass>(), 0);
}
TEST(eoffs, simple_bitmask)
{
using namespace c4;
EXPECT_EQ(eoffs_cls<MyBitmask>(), 0);
EXPECT_EQ(eoffs_pfx<MyBitmask>(), strlen("BM_"));
}
TEST(eoffs, scoped_bitmask)
{
using namespace c4;
EXPECT_EQ(eoffs_cls<MyBitmaskClass>(), strlen("MyBitmaskClass::"));
EXPECT_EQ(eoffs_pfx<MyBitmaskClass>(), strlen("MyBitmaskClass::BM_"));
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template<class Enum>
void test_esyms()
{
auto ss = c4::esyms<Enum>();
EXPECT_NE(ss.size(), 0);
EXPECT_FALSE(ss.empty());
for(auto s : ss)
{
EXPECT_STREQ(ss.find(s.name)->name, s.name);
EXPECT_STREQ(ss.find(s.value)->name, s.name);
EXPECT_EQ(ss.find(s.name)->value, s.value);
EXPECT_EQ(ss.find(s.value)->value, s.value);
}
}
TEST(esyms, simple_enum)
{
test_esyms<MyEnum>();
}
TEST(esyms, scoped_enum)
{
test_esyms<MyEnumClass>();
}
TEST(esyms, simple_bitmask)
{
test_esyms<MyBitmask>();
}
TEST(esyms, scoped_bitmask)
{
test_esyms<MyBitmaskClass>();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template<typename Enum>
void test_e2str()
{
using namespace c4;
using I = typename std::underlying_type<Enum>::type;
auto ss = esyms<Enum>();
EXPECT_NE(ss.size(), 0);
EXPECT_FALSE(ss.empty());
for(auto const& p : ss)
{
// test a round trip
EXPECT_EQ((I)str2e<Enum>(e2str(p.value)), (I)p.value);
// test the other way around
EXPECT_STREQ(e2str(str2e<Enum>(p.name)), p.name);
}
}
TEST(e2str, simple_enum)
{
test_e2str<MyEnum>();
}
TEST(e2str, scoped_enum)
{
test_e2str<MyEnumClass>();
EXPECT_EQ(c4::str2e<MyEnumClass>("MyEnumClass::FOO"), MyEnumClass::FOO);
EXPECT_EQ(c4::str2e<MyEnumClass>("FOO"), MyEnumClass::FOO);
}
TEST(e2str, simple_bitmask)
{
test_e2str<MyBitmask>();
EXPECT_EQ(c4::str2e<MyBitmask>("BM_FOO"), BM_FOO);
EXPECT_EQ(c4::str2e<MyBitmask>("FOO"), BM_FOO);
}
TEST(e2str, scoped_bitmask)
{
test_e2str<MyBitmaskClass>();
EXPECT_EQ(c4::str2e<MyBitmaskClass>("MyBitmaskClass::BM_FOO"), MyBitmaskClass::BM_FOO);
EXPECT_EQ(c4::str2e<MyBitmaskClass>("BM_FOO"), MyBitmaskClass::BM_FOO);
EXPECT_EQ(c4::str2e<MyBitmaskClass>("FOO"), MyBitmaskClass::BM_FOO);
}
#include "c4/libtest/supprwarn_pop.hpp"
| 24.193798
| 91
| 0.558475
|
leoetlino
|
e6ce22d78d8edf8283a150c8442b93af4b801a54
| 28,405
|
cpp
|
C++
|
reve/reve/lib/Assignment.cpp
|
mattulbrich/llreve
|
68cb958c1c02177fa0db1965a8afd879a97c2fc4
|
[
"BSD-3-Clause"
] | 20
|
2016-08-11T19:51:13.000Z
|
2021-09-02T13:10:58.000Z
|
reve/reve/lib/Assignment.cpp
|
mattulbrich/llreve
|
68cb958c1c02177fa0db1965a8afd879a97c2fc4
|
[
"BSD-3-Clause"
] | 9
|
2016-08-11T11:59:24.000Z
|
2021-07-16T09:44:28.000Z
|
reve/reve/lib/Assignment.cpp
|
mattulbrich/llreve
|
68cb958c1c02177fa0db1965a8afd879a97c2fc4
|
[
"BSD-3-Clause"
] | 7
|
2017-08-19T14:42:27.000Z
|
2020-05-20T16:14:13.000Z
|
/*
* This file is part of
* llreve - Automatic regression verification for LLVM programs
*
* Copyright (C) 2016 Karlsruhe Institute of Technology
*
* The system is published under a BSD license.
* See LICENSE (distributed with this file) for details.
*/
#include "Assignment.h"
#include "Helper.h"
#include "Opts.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
using llvm::CmpInst;
using llvm::Instruction;
using std::make_unique;
using std::string;
using std::unique_ptr;
using std::vector;
using namespace smt;
using namespace llreve::opts;
/// Convert a basic block to a list of assignments
vector<DefOrCallInfo> blockAssignments(const llvm::BasicBlock &BB,
const llvm::BasicBlock *prevBb,
bool onlyPhis, Program prog) {
const int progIndex = programIndex(prog);
vector<DefOrCallInfo> definitions;
definitions.reserve(BB.size());
assert(BB.size() >= 1); // There should be at least a terminator instruction
bool ignorePhis = prevBb == nullptr;
AssignmentVec phiAssgns;
for (auto instr = BB.begin(), e = std::prev(BB.end(), 1); instr != e;
++instr) {
// Ignore phi nodes if we are in a loop as they're bound in a
// forall quantifier
if (!ignorePhis && llvm::isa<llvm::PHINode>(instr)) {
auto assignments = instrAssignment(*instr, prevBb, prog);
for (auto &assignment : assignments) {
phiAssgns.insert(phiAssgns.end(), assignment->assgns.begin(),
assignment->assgns.end());
}
}
if (!llvm::isa<llvm::PHINode>(instr)) {
definitions.emplace_back(
std::make_unique<AssignmentGroup>(std::move(phiAssgns)));
phiAssgns.clear();
}
if (!onlyPhis && !llvm::isa<llvm::PHINode>(instr)) {
if (const auto CallInst = llvm::dyn_cast<llvm::CallInst>(instr)) {
const auto fun = CallInst->getCalledFunction();
if (!fun) {
logErrorData("Call to undeclared function\n", *CallInst);
exit(1);
}
if (fun->getIntrinsicID() == llvm::Intrinsic::memcpy) {
vector<DefOrCallInfo> defs =
memcpyIntrinsic(CallInst, prog);
for (auto &def : defs) {
definitions.emplace_back(std::move(def));
}
} else {
if (SMTGenerationOpts::getInstance().Heap ==
HeapOpt::Enabled) {
definitions.emplace_back(makeAssignment(
heapName(progIndex),
memoryVariable(heapName(progIndex))));
}
definitions.emplace_back(
toCallInfo(CallInst->getName(), prog, *CallInst));
if (SMTGenerationOpts::getInstance().Heap ==
HeapOpt::Enabled) {
definitions.emplace_back(makeAssignment(
heapName(progIndex),
memoryVariable(heapResultName(prog))));
}
if (SMTGenerationOpts::getInstance().Stack ==
StackOpt::Enabled) {
definitions.emplace_back(makeAssignment(
stackName(progIndex),
memoryVariable(stackResultName(prog))));
}
}
} else {
auto assignments = instrAssignment(*instr, prevBb, prog);
for (auto &assignment : assignments) {
definitions.push_back(std::move(assignment));
}
}
}
}
if (!phiAssgns.empty()) {
definitions.emplace_back(
std::make_unique<AssignmentGroup>(std::move(phiAssgns)));
}
if (const auto retInst =
llvm::dyn_cast<llvm::ReturnInst>(BB.getTerminator())) {
// TODO (moritz): use a more clever approach for void functions
unique_ptr<SMTExpr> retName =
std::make_unique<ConstantInt>(llvm::APInt(64, 0));
if (retInst->getReturnValue() != nullptr) {
retName =
instrNameOrVal(retInst->getReturnValue(), retInst->getType());
}
definitions.push_back(DefOrCallInfo(
makeAssignment(resultName(prog), std::move(retName))));
if (SMTGenerationOpts::getInstance().Heap == HeapOpt::Enabled) {
definitions.push_back(DefOrCallInfo(makeAssignment(
heapResultName(prog), memoryVariable(heapName(progIndex)))));
}
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled) {
definitions.push_back(DefOrCallInfo(makeAssignment(
stackResultName(prog), memoryVariable(stackName(progIndex)))));
}
}
return definitions;
}
/// Convert a single instruction to an assignment
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1>
instrAssignment(const llvm::Instruction &Instr, const llvm::BasicBlock *prevBb,
Program prog) {
const int progIndex = programIndex(prog);
if (const auto BinOp = llvm::dyn_cast<llvm::BinaryOperator>(&Instr)) {
if (BinOp->getType()->isFloatingPointTy()) {
auto op = std::make_unique<BinaryFPOperator>(
binaryFPOpcode(BinOp->getOpcode()), llvmType(BinOp->getType()),
instrNameOrVal(BinOp->getOperand(0)),
instrNameOrVal(BinOp->getOperand(1)));
return vecSingleton(
makeAssignment(BinOp->getName(), std::move(op)));
}
if (SMTGenerationOpts::getInstance().ByteHeap ==
ByteHeapOpt::Disabled &&
BinOp->getOpcode() == Instruction::SDiv) {
// This is a heuristic to remove divisions by 4 of pointer
// subtractions
// Since we treat every int as a single value, we expect the
// division to return the number of elements and not the number
// of
// bytes
if (const auto instr =
llvm::dyn_cast<llvm::Instruction>(BinOp->getOperand(0))) {
if (const auto ConstInt = llvm::dyn_cast<llvm::ConstantInt>(
BinOp->getOperand(1))) {
if (ConstInt->getSExtValue() == 4 && isPtrDiff(*instr)) {
return vecSingleton(makeAssignment(
BinOp->getName(),
instrNameOrVal(BinOp->getOperand(0))));
} else {
logWarning("Division of pointer difference by " +
std::to_string(ConstInt->getSExtValue()) +
"\n");
}
}
}
}
if (!SMTGenerationOpts::getInstance().BitVect &&
(BinOp->getOpcode() == Instruction::Or ||
BinOp->getOpcode() == Instruction::And ||
BinOp->getOpcode() == Instruction::Xor)) {
if (!(BinOp->getOperand(0)->getType()->isIntegerTy(1) &&
BinOp->getOperand(1)->getType()->isIntegerTy(1))) {
logWarningData(
"Bitwise operators of bitwidth > 1 is not supported\n",
*BinOp);
}
}
return vecSingleton(makeAssignment(
BinOp->getName(), combineOp(*BinOp, opName(*BinOp),
instrNameOrVal(BinOp->getOperand(0)),
instrNameOrVal(BinOp->getOperand(1)))));
}
if (const auto cmpInst = llvm::dyn_cast<llvm::CmpInst>(&Instr)) {
SMTRef cmp = makeOp(
predicateName(cmpInst->getPredicate()),
predicateFun(*cmpInst, instrNameOrVal(cmpInst->getOperand(0))),
predicateFun(*cmpInst, instrNameOrVal(cmpInst->getOperand(1))));
return vecSingleton(makeAssignment(cmpInst->getName(), std::move(cmp)));
}
if (const auto phiInst = llvm::dyn_cast<llvm::PHINode>(&Instr)) {
const auto val = phiInst->getIncomingValueForBlock(prevBb);
assert(val);
auto assgn = makeAssignment(phiInst->getName(), instrNameOrVal(val));
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled &&
phiInst->getType()->isPointerTy()) {
auto locAssgn = makeAssignment(
string(phiInst->getName()) + "_OnStack", instrLocation(val));
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1> result;
result.push_back(std::move(assgn));
result.push_back(std::move(locAssgn));
return result;
} else {
return vecSingleton(std::move(assgn));
}
}
if (const auto selectInst = llvm::dyn_cast<llvm::SelectInst>(&Instr)) {
const auto cond = selectInst->getCondition();
const auto trueVal = selectInst->getTrueValue();
const auto falseVal = selectInst->getFalseValue();
const vector<SharedSMTRef> args = {instrNameOrVal(cond),
instrNameOrVal(trueVal),
instrNameOrVal(falseVal)};
auto assgn = makeAssignment(selectInst->getName(),
std::make_unique<Op>("ite", args));
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled &&
trueVal->getType()->isPointerTy()) {
assert(falseVal->getType()->isPointerTy());
auto location =
makeOp("ite", instrNameOrVal(cond), instrLocation(trueVal),
instrLocation(falseVal));
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1> result;
result.push_back(std::move(assgn));
result.push_back(
makeAssignment(string(selectInst->getName()) + "_OnStack",
std::move(location)));
return result;
} else {
return vecSingleton(std::move(assgn));
}
}
if (const auto ptrToIntInst = llvm::dyn_cast<llvm::PtrToIntInst>(&Instr)) {
return vecSingleton(
makeAssignment(ptrToIntInst->getName(),
instrNameOrVal(ptrToIntInst->getPointerOperand(),
ptrToIntInst->getType())));
}
if (const auto getElementPtrInst =
llvm::dyn_cast<llvm::GetElementPtrInst>(&Instr)) {
auto assgn = makeAssignment(getElementPtrInst->getName(),
resolveGEP(*getElementPtrInst));
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled) {
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1> result;
result.push_back(std::move(assgn));
result.push_back(makeAssignment(
string(getElementPtrInst->getName()) + "_OnStack",
instrLocation(getElementPtrInst->getPointerOperand())));
return result;
} else {
return vecSingleton(std::move(assgn));
}
}
if (const auto loadInst = llvm::dyn_cast<llvm::LoadInst>(&Instr)) {
SharedSMTRef pointer = instrNameOrVal(loadInst->getOperand(0));
if (SMTGenerationOpts::getInstance().BitVect) {
// We load single bytes
unsigned bytes = loadInst->getType()->getIntegerBitWidth() / 8;
auto load =
makeOp("select", memoryVariable(heapName(progIndex)), pointer);
for (unsigned i = 1; i < bytes; ++i) {
load =
makeOp("concat", std::move(load),
makeOp("select", memoryVariable(heapName(progIndex)),
makeOp("bvadd", pointer,
std::make_unique<ConstantInt>(
llvm::APInt(64, i)))));
}
return vecSingleton(
makeAssignment(loadInst->getName(), std::move(load)));
} else {
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled) {
SMTRef load =
makeOp("select_", memoryVariable(heapName(progIndex)),
memoryVariable(stackName(progIndex)), pointer,
instrLocation(loadInst->getPointerOperand()));
return vecSingleton(
makeAssignment(loadInst->getName(), std::move(load)));
} else {
SMTRef load = makeOp(
"select", memoryVariable(heapName(progIndex)), pointer);
return vecSingleton(
makeAssignment(loadInst->getName(), std::move(load)));
}
}
}
if (const auto storeInst = llvm::dyn_cast<llvm::StoreInst>(&Instr)) {
string heap = heapName(progIndex);
SharedSMTRef pointer = instrNameOrVal(storeInst->getPointerOperand());
SharedSMTRef val = instrNameOrVal(storeInst->getValueOperand());
if (SMTGenerationOpts::getInstance().BitVect) {
int bytes =
storeInst->getValueOperand()->getType()->getIntegerBitWidth() /
8;
auto newHeap = memoryVariable(heap);
for (int i = 0; i < bytes; ++i) {
SharedSMTRef offset =
makeOp("bvadd", pointer,
std::make_unique<ConstantInt>(llvm::APInt(64, i)));
SharedSMTRef elem = makeOp(
"(_ extract " + std::to_string(8 * (bytes - i - 1) + 7) +
" " + std::to_string(8 * (bytes - i - 1)) + ")",
val);
std::vector<SharedSMTRef> args = {std::move(newHeap), offset,
elem};
newHeap = make_unique<Op>("store", std::move(args));
}
return vecSingleton(
makeAssignment(heapName(progIndex), std::move(newHeap)));
} else {
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled) {
const std::vector<SharedSMTRef> args = {
memoryVariable(heap), memoryVariable(stackName(progIndex)),
pointer, instrLocation(storeInst->getPointerOperand()),
val};
auto store = make_unique<Op>("store_", args);
return vecSingleton(
makeAssignment(heapName(progIndex), std::move(store)));
} else {
const std::vector<SharedSMTRef> args = {memoryVariable(heap),
pointer, val};
auto store = make_unique<Op>("store", args);
return vecSingleton(
makeAssignment(heapName(progIndex), std::move(store)));
}
}
}
if (const auto bitCast = llvm::dyn_cast<llvm::CastInst>(&Instr)) {
auto cast = std::make_unique<TypeCast>(
bitCast->getOpcode(), llvmType(bitCast->getSrcTy()),
llvmType(bitCast->getDestTy()),
instrNameOrVal(bitCast->getOperand(0)));
return vecSingleton(
makeAssignment(bitCast->getName(), std::move(cast)));
}
if (const auto allocaInst = llvm::dyn_cast<llvm::AllocaInst>(&Instr)) {
unsigned allocatedSize =
typeSize(allocaInst->getAllocatedType(),
allocaInst->getModule()->getDataLayout());
std::string sp = stackPointerName(progIndex);
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1> result;
result.push_back(
makeAssignment(sp, makeOp("-", sp,
std::make_unique<ConstantInt>(
llvm::APInt(64, allocatedSize)))));
result.push_back(
makeAssignment(allocaInst->getName(),
make_unique<TypedVariable>(sp, pointerType())));
result.push_back(
makeAssignment(string(allocaInst->getName()) + "_OnStack",
make_unique<ConstantBool>(true)));
return result;
}
if (const auto fcmpInst = llvm::dyn_cast<llvm::FCmpInst>(&Instr)) {
auto cmp = std::make_unique<FPCmp>(
fpPredicate(fcmpInst->getPredicate()),
llvmType(fcmpInst->getOperand(0)->getType()),
instrNameOrVal(fcmpInst->getOperand(0)),
instrNameOrVal(fcmpInst->getOperand(1)));
return vecSingleton(
makeAssignment(fcmpInst->getName(), std::move(cmp)));
}
logErrorData("Couldn’t convert instruction to def\n", Instr);
return vecSingleton(
makeAssignment("UNKNOWN INSTRUCTION", stringExpr("UNKNOWN ARGS")));
}
/// Convert an LLVM predicate to an SMT predicate
string predicateName(llvm::CmpInst::Predicate pred) {
if (SMTGenerationOpts::getInstance().BitVect) {
switch (pred) {
case CmpInst::ICMP_SLT:
return "bvslt";
case CmpInst::ICMP_ULT:
return "bvult";
case CmpInst::ICMP_SLE:
return "bvsle";
case CmpInst::ICMP_ULE:
return "bvule";
case CmpInst::ICMP_EQ:
return "=";
case CmpInst::ICMP_SGE:
return "bvsge";
case CmpInst::ICMP_UGE:
return "bvuge";
case CmpInst::ICMP_SGT:
return "bvsgt";
case CmpInst::ICMP_UGT:
return "bvugt";
case CmpInst::ICMP_NE:
return "distinct";
default:
return "unsupported predicate";
}
} else {
switch (pred) {
case CmpInst::ICMP_SLT:
case CmpInst::ICMP_ULT:
return "<";
case CmpInst::ICMP_SLE:
case CmpInst::ICMP_ULE:
return "<=";
case CmpInst::ICMP_EQ:
return "=";
case CmpInst::ICMP_SGE:
case CmpInst::ICMP_UGE:
return ">=";
case CmpInst::ICMP_SGT:
case CmpInst::ICMP_UGT:
return ">";
case CmpInst::ICMP_NE:
return "distinct";
default:
return "unsupported predicate";
}
}
}
FPCmp::Predicate fpPredicate(llvm::CmpInst::Predicate pred) {
switch (pred) {
case CmpInst::FCMP_FALSE:
return FPCmp::Predicate::False;
case CmpInst::FCMP_OEQ:
return FPCmp::Predicate::OEQ;
case CmpInst::FCMP_OGT:
return FPCmp::Predicate::OGT;
case CmpInst::FCMP_OGE:
return FPCmp::Predicate::OGE;
case CmpInst::FCMP_OLT:
return FPCmp::Predicate::OLT;
case CmpInst::FCMP_OLE:
return FPCmp::Predicate::OLE;
case CmpInst::FCMP_ONE:
return FPCmp::Predicate::ONE;
case CmpInst::FCMP_ORD:
return FPCmp::Predicate::ORD;
case CmpInst::FCMP_UNO:
return FPCmp::Predicate::UNO;
case CmpInst::FCMP_UEQ:
return FPCmp::Predicate::UEQ;
case CmpInst::FCMP_UGT:
return FPCmp::Predicate::UGT;
case CmpInst::FCMP_UGE:
return FPCmp::Predicate::UGE;
case CmpInst::FCMP_ULT:
return FPCmp::Predicate::ULT;
case CmpInst::FCMP_ULE:
return FPCmp::Predicate::ULE;
case CmpInst::FCMP_UNE:
return FPCmp::Predicate::UNE;
case CmpInst::FCMP_TRUE:
return FPCmp::Predicate::True;
default:
logError("No floating point predicate\n");
exit(1);
}
}
BinaryFPOperator::Opcode binaryFPOpcode(llvm::Instruction::BinaryOps op) {
switch (op) {
case Instruction::FAdd:
return BinaryFPOperator::Opcode::FAdd;
case Instruction::FSub:
return BinaryFPOperator::Opcode::FSub;
case Instruction::FMul:
return BinaryFPOperator::Opcode::FMul;
case Instruction::FDiv:
return BinaryFPOperator::Opcode::FDiv;
case Instruction::FRem:
return BinaryFPOperator::Opcode::FRem;
default:
logError("Not a floating point binary operator\n");
exit(1);
}
}
/// A function that is abblied to the arguments of a predicate
SMTRef predicateFun(const llvm::CmpInst &cmp, SMTRef expr) {
if (!SMTGenerationOpts::getInstance().BitVect && cmp.isUnsigned() &&
!SMTGenerationOpts::getInstance().EverythingSigned) {
return makeOp("abs", std::move(expr));
}
return expr;
}
/// Convert an LLVM op to an SMT op
string opName(const llvm::BinaryOperator &Op) {
if (SMTGenerationOpts::getInstance().BitVect) {
switch (Op.getOpcode()) {
case Instruction::Add:
return "bvadd";
case Instruction::Sub:
return "bvsub";
case Instruction::Mul:
return "bvmul";
case Instruction::SDiv:
return "bvsdiv";
case Instruction::UDiv:
return "bvudiv";
case Instruction::SRem:
return "bvsrem";
case Instruction::URem:
return "bvurem";
case Instruction::Or:
return "bvor";
case Instruction::And:
return "bvand";
case Instruction::Xor:
return "bvxor";
case Instruction::AShr:
return "bvashr";
case Instruction::LShr:
return "bvlshr";
case Instruction::Shl:
return "bvshl";
default:
logError("Unknown opcode: " + std::string(Op.getOpcodeName()) +
"\n");
return Op.getOpcodeName();
}
} else {
switch (Op.getOpcode()) {
case Instruction::Add:
return "+";
case Instruction::Sub:
return "-";
case Instruction::Mul:
return "*";
case Instruction::SDiv:
return "div";
case Instruction::UDiv:
return "div";
case Instruction::SRem:
return "mod";
case Instruction::URem:
return "mod";
case Instruction::Or:
return "or";
case Instruction::And:
return "and";
case Instruction::Xor:
return "xor";
case Instruction::AShr:
case Instruction::LShr:
return "div";
case Instruction::Shl:
return "*";
default:
logError("Unknown opcode: " + std::string(Op.getOpcodeName()) +
"\n");
return Op.getOpcodeName();
}
}
}
SMTRef combineOp(const llvm::BinaryOperator &Op, std::string opName,
SMTRef firstArg, SMTRef secondArg) {
if (!SMTGenerationOpts::getInstance().BitVect &&
(Op.getOpcode() == Instruction::AShr ||
Op.getOpcode() == Instruction::LShr ||
Op.getOpcode() == Instruction::Shl)) {
// We can only do that if there is a constant on the right side
if (const auto constInt =
llvm::dyn_cast<llvm::ConstantInt>(Op.getOperand(1))) {
// rounding conversion to guard for floating point errors
uint64_t divisor =
static_cast<uint64_t>(pow(2, constInt->getZExtValue()) + 0.5);
return makeOp(
std::move(opName), std::move(firstArg),
std::make_unique<ConstantInt>(llvm::APInt(64, divisor)));
} else {
logErrorData("Only shifts by a constant are supported\n", Op);
}
}
return makeOp(std::move(opName), std::move(firstArg), std::move(secondArg));
}
vector<DefOrCallInfo> memcpyIntrinsic(const llvm::CallInst *callInst,
Program prog) {
vector<DefOrCallInfo> definitions;
const auto castInst0 =
llvm::dyn_cast<llvm::CastInst>(callInst->getArgOperand(0));
const auto castInst1 =
llvm::dyn_cast<llvm::CastInst>(callInst->getArgOperand(1));
if (castInst0 && castInst1) {
const auto ty0 =
llvm::dyn_cast<llvm::PointerType>(castInst0->getSrcTy());
const auto ty1 =
llvm::dyn_cast<llvm::PointerType>(castInst1->getSrcTy());
const auto StructTy0 =
llvm::dyn_cast<llvm::StructType>(ty0->getElementType());
const auto StructTy1 =
llvm::dyn_cast<llvm::StructType>(ty1->getElementType());
if (StructTy0 && StructTy1) {
assert(StructTy0->isLayoutIdentical(StructTy1));
SharedSMTRef basePointerDest =
instrNameOrVal(callInst->getArgOperand(0));
SharedSMTRef basePointerSrc =
instrNameOrVal(callInst->getArgOperand(1));
string heapNameSelect = heapName(prog);
string heapNameStore = heapName(prog);
int i = 0;
for (const auto elTy : StructTy0->elements()) {
SharedSMTRef heapSelect = memoryVariable(heapNameSelect);
SharedSMTRef heapStore = memoryVariable(heapNameStore);
for (int j = 0;
j < typeSize(elTy, callInst->getModule()->getDataLayout());
++j) {
SMTRef select = makeOp("select", heapSelect,
makeOp("+", basePointerSrc,
std::make_unique<ConstantInt>(
llvm::APInt(64, i))));
const vector<SharedSMTRef> args = {
heapStore,
makeOp(
"+", basePointerDest,
std::make_unique<ConstantInt>(llvm::APInt(64, i))),
std::move(select)};
definitions.push_back(makeAssignment(
heapNameStore, make_unique<Op>("store", args)));
++i;
}
}
} else {
logError("currently only memcpy of structs is "
"supported\n");
exit(1);
}
} else {
logError("currently only memcpy of "
"bitcasted pointers is supported\n");
exit(1);
}
return definitions;
}
unique_ptr<CallInfo> toCallInfo(string assignedTo, Program prog,
const llvm::CallInst &callInst) {
vector<SharedSMTRef> args;
if (assignedTo.empty()) {
assignedTo = "res" + std::to_string(programIndex(prog));
}
uint32_t i = 0;
unsigned suppliedArgs = 0;
const auto &funTy = *callInst.getFunctionType();
const llvm::Function &fun = *callInst.getCalledFunction();
for (auto &arg : callInst.arg_operands()) {
args.push_back(instrNameOrVal(arg, funTy.getParamType(i)));
++suppliedArgs;
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled &&
arg->getType()->isPointerTy()) {
args.push_back(instrLocation(arg));
}
++i;
}
unsigned varargs = suppliedArgs - funTy.getNumParams();
return std::make_unique<CallInfo>(assignedTo, fun.getName(), args, varargs,
fun);
}
bool isPtrDiff(const llvm::Instruction &instr) {
if (const auto binOp = llvm::dyn_cast<llvm::BinaryOperator>(&instr)) {
return binOp->getOpcode() == Instruction::Sub &&
llvm::isa<llvm::PtrToIntInst>(binOp->getOperand(0)) &&
llvm::isa<llvm::PtrToIntInst>(binOp->getOperand(1));
}
return false;
}
auto coupledCalls(const CallInfo &call1, const CallInfo &call2) -> bool {
const auto &coupledFunctions =
SMTGenerationOpts::getInstance().CoupledFunctions;
bool coupledNames = false;
// The const cast here is safe because we are only comparing pointers
coupledNames =
coupledFunctions.find({const_cast<llvm::Function *>(&call1.fun),
const_cast<llvm::Function *>(&call2.fun)}) !=
coupledFunctions.end();
if (!hasFixedAbstraction(call1.fun) || !hasFixedAbstraction(call2.fun)) {
return coupledNames;
}
return coupledNames && call1.fun.getFunctionType()->getNumParams() ==
call2.fun.getFunctionType()->getNumParams();
}
| 41.58858
| 80
| 0.545256
|
mattulbrich
|
e6cf7c3755d1e7d3178d1b78820773d997e35d41
| 470
|
hpp
|
C++
|
global_kinematic_model/include/kinematic.hpp
|
Horki/CarND-MPC-Quizzes
|
236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69
|
[
"MIT"
] | null | null | null |
global_kinematic_model/include/kinematic.hpp
|
Horki/CarND-MPC-Quizzes
|
236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69
|
[
"MIT"
] | null | null | null |
global_kinematic_model/include/kinematic.hpp
|
Horki/CarND-MPC-Quizzes
|
236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69
|
[
"MIT"
] | null | null | null |
#ifndef KINEMATIC_H_
#define KINEMATIC_H_
#include <Eigen/Core>
#include <cmath>
using Eigen::VectorXd;
constexpr double Lf = 2;
//
// Helper functions
//
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180.0; }
double rad2deg(double x) { return x * 180.0 / pi(); }
// Return the next state.
VectorXd globalKinematic(const VectorXd & state,
const VectorXd & actuators, double dt);
#endif
| 20.434783
| 64
| 0.642553
|
Horki
|
e6d12ea3f53d333c65b074f699c0a1393446eabd
| 1,121
|
hpp
|
C++
|
include/disccord/models/invite_metadata.hpp
|
FiniteReality/disccord
|
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
|
[
"MIT"
] | 44
|
2016-09-19T15:28:25.000Z
|
2018-08-09T13:17:40.000Z
|
include/disccord/models/invite_metadata.hpp
|
FiniteReality/disccord
|
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
|
[
"MIT"
] | 44
|
2016-11-03T17:27:30.000Z
|
2017-12-10T16:17:31.000Z
|
include/disccord/models/invite_metadata.hpp
|
FiniteReality/disccord
|
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
|
[
"MIT"
] | 13
|
2016-11-01T00:17:20.000Z
|
2018-08-03T19:51:16.000Z
|
#ifndef _invite_metadata_hpp_
#define _invite_metadata_hpp_
#include <disccord/models/entity.hpp>
#include <disccord/models/user.hpp>
namespace disccord
{
namespace models
{
class invite_metadata : public model
{
public:
invite_metadata();
virtual ~invite_metadata();
virtual void decode(web::json::value json) override;
util::optional<user> get_inviter();
std::string get_created_at();
uint32_t get_uses();
uint32_t get_max_uses();
uint32_t get_max_age();
bool get_temporary();
bool get_revoked();
protected:
virtual void encode_to(
std::unordered_map<std::string, web::json::value> &info
) override;
private:
util::optional<user> inviter;
std::string created_at;
uint32_t uses, max_uses, max_age;
bool temporary, revoked;
};
}
}
#endif /* _invite_metadata_hpp_ */
| 26.690476
| 75
| 0.531668
|
FiniteReality
|
e6d47cd0d1594ea1ed44564eb7577a032c12856e
| 2,069
|
cc
|
C++
|
flare/base/buffer/zero_copy_stream_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 868
|
2021-05-28T04:00:22.000Z
|
2022-03-31T08:57:14.000Z
|
flare/base/buffer/zero_copy_stream_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 33
|
2021-05-28T08:44:47.000Z
|
2021-09-26T13:09:21.000Z
|
flare/base/buffer/zero_copy_stream_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 122
|
2021-05-28T08:22:23.000Z
|
2022-03-29T09:52:09.000Z
|
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "flare/base/buffer/zero_copy_stream.h"
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "google/protobuf/util/message_differencer.h"
#include "flare/testing/message.pb.h"
namespace flare {
TEST(ZeroCopyStream, SerializeAndDeserialize) {
testing::ComplexMessage src;
src.set_integer(556);
src.set_enumeration(testing::ENUM_0);
src.set_str("short str");
src.mutable_one()->set_str("a missing string" + std::string(16777216, 'a'));
NoncontiguousBufferBuilder nbb;
NoncontiguousBufferOutputStream zbos(&nbb);
CHECK(src.SerializeToZeroCopyStream(&zbos));
zbos.Flush();
auto serialized = nbb.DestructiveGet();
NoncontiguousBuffer cp1 = CreateBufferSlow(FlattenSlow(serialized));
NoncontiguousBuffer cp2 = serialized;
// Same size as serialized to string.
ASSERT_EQ(src.SerializeAsString().size(), serialized.ByteSize());
NoncontiguousBuffer splited;
splited.Append(serialized.Cut(1));
splited.Append(serialized.Cut(2));
splited.Append(serialized.Cut(3));
splited.Append(serialized.Cut(4));
splited.Append(std::move(serialized));
for (auto&& e : {&cp1, &cp2, &splited}) {
// Parseable.
NoncontiguousBufferInputStream nbis(e);
testing::ComplexMessage dest;
ASSERT_TRUE(dest.ParseFromZeroCopyStream(&nbis));
// Same as the original one.
ASSERT_TRUE(google::protobuf::util::MessageDifferencer::Equals(src, dest));
}
}
} // namespace flare
| 32.328125
| 80
| 0.740938
|
AriCheng
|
e6d4a327d3d13fc6a4257f7e90bb4aa25e33cd21
| 1,707
|
cpp
|
C++
|
scss/class/class3.cpp
|
chth2116/Faux-Compania
|
c8bc0e06ee5c67c59334195817b831481b9125ee
|
[
"MIT"
] | null | null | null |
scss/class/class3.cpp
|
chth2116/Faux-Compania
|
c8bc0e06ee5c67c59334195817b831481b9125ee
|
[
"MIT"
] | null | null | null |
scss/class/class3.cpp
|
chth2116/Faux-Compania
|
c8bc0e06ee5c67c59334195817b831481b9125ee
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
void passByValue(int a){
a++;
}
void passByPointer(int *ptr){
//this will give same address as that stored in b (ptr and b are pointing to the same location)
cout << "address stored in ptr " << ptr << endl;
*ptr = *ptr + 1; // this is the same as: (*ptr)++
}
int main(){
int a = 5;
//pointer and address it points to have to be the same type
int *b = &a;
//b gives address, *b gets the value stored at b which is the address of a
//* has two meanings
//use it to declare pointers
//use it to dereference the pointers
//dereference - go to address stored in pointer and get the value at that address
//cout << &b<< ", " << b<< ", " << *b << endl;
//*b gets updated as a gets updated because the address of a has not changed
a = 10;
int c = 20;
b = &c; //change the address stored in b to address of c
//cout << *b << endl;
int arrayA[5];
cout << arrayA << endl; //name of array gives us address of first element in arrayA
//Functions
passByValue(a);//the changes made to a in the function are local to that Functions
// pass by value basically made a copy of a and stored it at a new address unique to the function
//cout << a << endl;
//address' are unlike variables in that they are universal. If we change something at in address in one Functions
//that variable at that address changes for all other Functions
//in this case, we send the address of b to the function and the function changes the value at that address by adding one
//we then check b and get 21 which is the value of *b+1;
cout << "address stored in b " << b << endl;
passByPointer(b);
cout << *b << endl;
}
| 32.826923
| 123
| 0.66198
|
chth2116
|
e6d57b6a961401076c6636a468fb3e6a4108a0af
| 4,065
|
cpp
|
C++
|
common/terrain.cpp
|
yang-han/EnjoyYourRoad
|
c2a5926717ac1fbf6eaae8f89f451a601c5b1186
|
[
"MIT"
] | 1
|
2018-10-30T06:38:55.000Z
|
2018-10-30T06:38:55.000Z
|
common/terrain.cpp
|
sleeepyy/EnjoyYourRoad
|
c2a5926717ac1fbf6eaae8f89f451a601c5b1186
|
[
"MIT"
] | null | null | null |
common/terrain.cpp
|
sleeepyy/EnjoyYourRoad
|
c2a5926717ac1fbf6eaae8f89f451a601c5b1186
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "terrain.hpp"
#define PI 3.14159265
std::vector<glm::vec3> terrain;
int length;
int width;
//Set terrain height here
float height ( float x, float z ){
if ( x > 60 && x < 70 && z<5 && z>-5 ){
return 1.2f*( x - 60 );
}
else if ( x >= 70 && x < 80 && z<5 && z>-5 ){
return 0.8f*( 80 - x );
}
if ( z<50 && z>-50 ){
if ( ( -0.004*z*z + 10.0 )*cos ( ( x ) / 10.0 / PI ) > 0.0 )
return (float)( -0.004f*z*z + 10.0 )*cos ( ( x ) / 10.0 / PI );
else{
return 0;
}
}
else
return 0;
}
bool generateTerrain (
int l, int w,
std::vector<glm::vec3> & out_vertices,
std::vector<glm::vec2> & out_uvs,
std::vector<glm::vec3> & out_normals
){
length = l;
width = w;
std::vector<unsigned int> vertexIndices, uvIndices, normalIndices;
std::vector<glm::vec2> temp_uvs;
std::vector<glm::vec3> temp_normals;
glm::vec3 vertex;
glm::vec2 uv;
glm::vec3 normal;
for ( int i = 0; i < l + 1; i++ ){
for ( int j = 0; j < w + 1; j++ ){
vertex.x = i - l / 2;
vertex.z = j - w / 2;
vertex.y = height ( vertex.x, vertex.z );
uv.x = (float) i / (float) l;
uv.y = (float) j / (float) w;
normal.x = 0;
normal.z = 0;
normal.y = 1;
terrain.push_back ( vertex );
temp_uvs.push_back ( uv );
temp_normals.push_back ( normal );
}
}
for ( int a = 0; a < l; a++ ){
for ( int b = 0; b < w; b++ ){
unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
vertexIndex[0] = uvIndex[0] = normalIndex[0] = a*l + b;
vertexIndex[1] = uvIndex[1] = normalIndex[1] = ( a + 1 )*l + b;
vertexIndex[2] = uvIndex[2] = normalIndex[2] = a*l + b + 1;
vertexIndices.push_back ( vertexIndex[0] );
vertexIndices.push_back ( vertexIndex[1] );
vertexIndices.push_back ( vertexIndex[2] );
uvIndices.push_back ( uvIndex[0] );
uvIndices.push_back ( uvIndex[1] );
uvIndices.push_back ( uvIndex[2] );
normalIndices.push_back ( normalIndex[0] );
normalIndices.push_back ( normalIndex[1] );
normalIndices.push_back ( normalIndex[2] );
vertexIndex[0] = uvIndex[0] = normalIndex[0] = a*l + b + 1;
vertexIndex[1] = uvIndex[1] = normalIndex[1] = ( a + 1 )*l + b;
vertexIndex[2] = uvIndex[2] = normalIndex[2] = ( a + 1 )*l + b + 1;
vertexIndices.push_back ( vertexIndex[0] );
vertexIndices.push_back ( vertexIndex[1] );
vertexIndices.push_back ( vertexIndex[2] );
uvIndices.push_back ( uvIndex[0] );
uvIndices.push_back ( uvIndex[1] );
uvIndices.push_back ( uvIndex[2] );
normalIndices.push_back ( normalIndex[0] );
normalIndices.push_back ( normalIndex[1] );
normalIndices.push_back ( normalIndex[2] );
}
}
for ( int i = 0; i < vertexIndices.size ( ); i++ ){
unsigned int vertexIndex = vertexIndices[i];
unsigned int uvIndex = uvIndices[i];
unsigned int normalIndex = normalIndices[i];
vertex = terrain[vertexIndex];
uv = temp_uvs[uvIndex];
normal = temp_normals[normalIndex];
out_vertices.push_back ( vertex );
out_uvs.push_back ( uv );
out_normals.push_back ( normal );
}
return true;
}
float getHeight ( float x, float z ){
if ( x<-length || x>length || z<-width || z>width )
return 0;
float a, b, c, d;
float da, db, dc, dd;
float dt;/*
a = terrain[( (int) x + length / 2 )*( width + 1 ) + (int) z + width / 2].y;
b = terrain[( (int) x + 1 + length / 2 )*( width + 1 ) + (int) z + width / 2].y;
c = terrain[( (int) x + length / 2 )*( width + 1 ) + (int) z + 1 + width / 2].y;
d = terrain[( (int) x + 1 + length / 2 )*( width + 1 ) + (int) z + 1 + width / 2].y;*/
da = ( x - (int) x )*( x - (int) x ) + ( z - (int) z )*( z - (int) z );
db = ( x - (int) x + 1 )*( x - (int) x + 1 ) + ( z - (int) z )*( z - (int) z );
dc = ( x - (int) x )*( x - (int) x ) + ( z - (int) z + 1 )*( z - (int) z + 1 );
dd = ( x - (int) x + 1 )*( x - (int) x + 1 ) + ( z - (int) z + 1 )*( z - (int) z + 1 );
dt = da + db + dc + dd;
return height ( x, z );//a*da / dt + b*db / dt + c*dc / dt + d*dd / dt;
}
| 34.159664
| 91
| 0.546125
|
yang-han
|
5c798c111fb83e1cefd54d1eff981c94f1ffdad7
| 4,499
|
cc
|
C++
|
moui/core/android/device_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 59
|
2015-01-23T01:02:50.000Z
|
2021-11-26T00:01:45.000Z
|
moui/core/android/device_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 2
|
2017-05-26T15:26:24.000Z
|
2020-09-25T03:54:01.000Z
|
moui/core/android/device_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 7
|
2015-09-25T08:09:20.000Z
|
2019-11-24T15:24:28.000Z
|
// Copyright (c) 2014 Ollix. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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.
//
// ---
// Author: olliwang@ollix.com (Olli Wang)
#include "moui/core/device.h"
#include <map>
#include "jni.h" // NOLINT
#include "moui/core/application.h"
namespace {
// The screen scale factor of the current device.
float screen_scale_factor = 0;
// The smallest screen dp that should consider as a tablet. This value can
// be changed through the SetSmallestScreenWidthDpForTablet() method.
float tablet_smallest_screen_width_dp = 600;
std::map<JNIEnv*, jobject> global_devices;
// Returns the instance of the com.ollix.moui.Device class on the Java side.
jobject GetJavaDevice(JNIEnv* env) {
auto match = global_devices.find(env);
if (match != global_devices.end()) {
return match->second;
}
jclass device_class = env->FindClass("com/ollix/moui/Device");
jmethodID constructor = env->GetMethodID(device_class, "<init>",
"(Landroid/content/Context;)V");
jobject device_obj = env->NewObject(device_class, constructor,
moui::Application::GetMainActivity());
jobject global_device = env->NewGlobalRef(device_obj);
env->DeleteLocalRef(device_class);
env->DeleteLocalRef(device_obj);
global_devices[env] = global_device;
return global_device;
}
} // namespace
namespace moui {
void Device::Init() {
GetScreenScaleFactor();
}
Device::BatteryState Device::GetBatteryState() {
JNIEnv* env = moui::Application::GetJNIEnv();
jobject device = GetJavaDevice(env);
jclass device_class = env->GetObjectClass(device);
jmethodID java_method = env->GetMethodID(
device_class, "getBatteryState", "()I");
env->DeleteLocalRef(device_class);
const int kResult = env->CallIntMethod(device, java_method);
// BatteryManager.BATTERY_STATUS_CHARGING
if (kResult == 2)
return BatteryState::kCharging;
// BatteryManager.BATTERY_STATUS_DISCHARGING
if (kResult == 3)
return BatteryState::kUnplugged;
// BatteryManager.BATTERY_STATUS_NOT_CHARGING
if (kResult == 4)
return BatteryState::kNotCharging;
// BatteryManager.BATTERY_STATUS_FULL
if (kResult == 5)
return BatteryState::kFull;
return BatteryState::kUnknown;
}
// Calls com.ollix.moui.Device.getSmallestScreenWidthDp() on the Java side.
Device::Category Device::GetCategory() {
static float smallest_screen_width_dp = 0;
if (smallest_screen_width_dp >= tablet_smallest_screen_width_dp) {
return Category::kTablet;
} else if (smallest_screen_width_dp > 0) {
return Category::kPhone;
}
// Determines the smallest_screen_width_dp for the first time calling this
// method.
JNIEnv* env = moui::Application::GetJNIEnv();
jobject device = GetJavaDevice(env);
jclass device_class = env->GetObjectClass(device);
jmethodID java_method = env->GetMethodID(
device_class, "getSmallestScreenWidthDp", "()F");
env->DeleteLocalRef(device_class);
smallest_screen_width_dp = env->CallFloatMethod(device, java_method);
return GetCategory();
}
// Calls com.ollix.moui.Device.getScreenScaleFactor() on the Java side.
float Device::GetScreenScaleFactor() {
if (screen_scale_factor > 0)
return screen_scale_factor;
JNIEnv* env = moui::Application::GetJNIEnv();
jobject device = GetJavaDevice(env);
jclass device_class = env->GetObjectClass(device);
jmethodID java_method = env->GetMethodID(
device_class, "getScreenScaleFactor", "()F");
env->DeleteLocalRef(device_class);
screen_scale_factor = env->CallFloatMethod(device, java_method);
return screen_scale_factor;
}
void Device::Reset() {
for (auto& pair : global_devices) {
JNIEnv* env = Application::GetJNIEnv();
jobject global_device = pair.second;
env->DeleteGlobalRef(global_device);
}
global_devices.clear();
}
void Device::SetSmallestScreenWidthDpForTablet(float screen_width_dp) {
tablet_smallest_screen_width_dp = screen_width_dp;
}
} // namespace moui
| 33.325926
| 76
| 0.728829
|
ollix
|
5c7d39a14fee99e4e5118aa6274302513e7e3236
| 29,733
|
hh
|
C++
|
dune/ax1/acme2/common/acme2_setup.hh
|
pederpansen/dune-ax1
|
152153824d95755a55bdd4fba80686863e928196
|
[
"BSD-3-Clause"
] | null | null | null |
dune/ax1/acme2/common/acme2_setup.hh
|
pederpansen/dune-ax1
|
152153824d95755a55bdd4fba80686863e928196
|
[
"BSD-3-Clause"
] | null | null | null |
dune/ax1/acme2/common/acme2_setup.hh
|
pederpansen/dune-ax1
|
152153824d95755a55bdd4fba80686863e928196
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef DUNE_AX1_ACME2_SETUP_HH
#define DUNE_AX1_ACME2_SETUP_HH
#include <dune/common/array.hh>
#include <dune/pdelab/backend/istlvectorbackend.hh>
//#include<dune/pdelab/finiteelementmap/q12dfem.hh>
//#include<dune/pdelab/finiteelementmap/q22dfem.hh>
#include <dune/pdelab/common/clock.hh>
#include <dune/pdelab/finiteelementmap/q1fem.hh>
#include <dune/pdelab/finiteelementmap/conformingconstraints.hh>
#include <dune/pdelab/function/selectcomponent.hh>
#include <dune/pdelab/gridoperator/gridoperator.hh>
#include <dune/pdelab/gridoperator/onestep.hh>
#include <dune/pdelab/backend/seqistlsolverbackend.hh>
#include <dune/pdelab/stationary/linearproblem.hh>
#include <dune/ax1/common/ax1_newton.hh>
#include <dune/ax1/common/ax1_linearproblem.hh>
#include <dune/ax1/common/ax1_discretegridfunction.hh>
#include <dune/ax1/common/ax1_simulationdata.hh>
#include <dune/ax1/common/ax1_simulationstate.hh>
#include <dune/ax1/common/chargedensitygridfunction.hh>
#include <dune/ax1/common/ionicstrengthgridfunction.hh>
#include <dune/ax1/common/membranefluxgridfunction.hh>
#include <dune/ax1/common/poisson_boltzmann_concentrationgridfunction.hh>
#include <dune/ax1/common/poisson_boltzmann_rhs_gridfunction.hh>
#include <dune/ax1/common/output.hh>
#include <dune/ax1/common/vectordiscretegridfunctiongradient.hh>
#include <dune/ax1/acme2/common/acme2_boundary.hh>
#include <dune/ax1/acme2/common/acme2_initial.hh>
#include <dune/ax1/acme2/common/acme2_output.hh>
#include <dune/ax1/acme2/common/acme2_solutionvectors.hh>
#include <dune/ax1/acme2/common/nernst_planck_parameters.hh>
#include <dune/ax1/acme2/common/poisson_parameters.hh>
#include <dune/ax1/acme2/common/poisson_boltzmann_parameters.hh>
#include <dune/ax1/acme2/common/acme2_simulation.hh>
#include <dune/ax1/acme2/operator/convectiondiffusionfem.hh>
#include <dune/ax1/acme2/operator/poisson_boltzmann_operator.hh>
#include <dune/ax1/acme2/operator/acme2_operator_fully_coupled.hh>
#include <dune/ax1/acme2/operator/acme2_toperator.hh>
template<class Grid, class GV, class PHYSICS, class SubGV>
class Acme2Setup
{
public:
//! Traits class providing function spaces and related data types for the acme2 use case
template<int NUMBER_OF_SPECIES>
struct Acme2Traits
{
typedef Acme2Setup<Grid,GV,PHYSICS,SubGV> SETUP;
typedef PHYSICS Physics;
typedef GV GridView;
typedef Grid GridType;
typedef typename GV::Grid::ctype Coord;
typedef double Real;
typedef SubGV SubGridView;
typedef typename SubGV::Grid SubGridType;
#if USE_PARALLEL==1
typedef Dune::PDELab::NonoverlappingConformingDirichletConstraints CONSTRAINTS;
#else
typedef Dune::PDELab::ConformingDirichletConstraints CONSTRAINTS;
#endif
typedef Dune::PDELab::ISTLVectorBackend<AX1_BLOCKSIZE> VBE;
typedef Dune::PDELab::Q1LocalFiniteElementMap<Coord,Real,GV::dimension> FEM_CON;
typedef Dune::PDELab::Q1LocalFiniteElementMap<Coord,Real,GV::dimension> FEM_POT;
//typedef Dune::PDELab::Pk1dLocalFiniteElementMap<Coord,Real> FEM_CON;
//typedef Dune::PDELab::Pk1dLocalFiniteElementMap<Coord,Real> FEM_POT;
// Nernst-Planck GFS (on electrolyte subdomain)
typedef Dune::PDELab::GridFunctionSpaceLexicographicMapper LexicographicOrdering;
typedef Dune::PDELab::GridFunctionSpaceComponentBlockwiseMapper<1,1,1> PowerGFSOrdering;
typedef Dune::PDELab::GridFunctionSpace<SubGV,FEM_CON,CONSTRAINTS,VBE> GFS_SINGLE_CON;
typedef Dune::PDELab::PowerGridFunctionSpace<
GFS_SINGLE_CON, NUMBER_OF_SPECIES, PowerGFSOrdering> GFS_CON;
// Poisson GFS (on electrolyte or membrane subdomain)
typedef Dune::PDELab::GridFunctionSpace<GV,FEM_POT,CONSTRAINTS,VBE> GFS_POT;
// Composite GFS for electrolyte
//typedef Dune::PDELab::GridFunctionSpaceLexicographicMapper CompositeGFSOrdering;
// This has no effect when using dune-multidomain => ordering always lexicographic!
typedef Dune::PDELab::GridFunctionSpaceComponentBlockwiseMapper<3,1> CompositeBlockedOrdering;
// Multidomain GFS
typedef Dune::PDELab::MultiDomain::MultiDomainGridFunctionSpace<GridType,VBE,GFS_CON,GFS_POT> MultiGFS;
// Extract SubGFS for use in gridfunctions; use these after creating MultiGFS!
typedef typename Dune::PDELab::GridFunctionSubSpace<MultiGFS,0> GFS_CON_SUB;
typedef typename Dune::PDELab::GridFunctionSubSpace<MultiGFS,1> GFS_POT_SUB;
// Extract solution vector type
//typedef typename Dune::PDELab::BackendVectorSelector<GFS_CON,Real>::Type U_CON;
//typedef typename Dune::PDELab::BackendVectorSelector<GFS_POT,Real>::Type U_POT;
typedef typename Dune::PDELab::BackendVectorSelector<MultiGFS,Real>::Type U;
// Various gridfunctions
typedef Dune::PDELab::VectorDiscreteGridFunction <GFS_CON_SUB,U> DGF_CON_SUB;
typedef Dune::PDELab::VectorDiscreteGridFunctionGradient <GFS_CON_SUB,U> DGF_CON_GRAD_SUB;
typedef Ax1MultiDomainGridFunctionExtension<GV, DGF_CON_SUB, PHYSICS> DGF_CON;
typedef Ax1MultiDomainGridFunctionExtension<GV, DGF_CON_GRAD_SUB, PHYSICS> DGF_CON_GRAD;
typedef Dune::PDELab::DiscreteGridFunction<GFS_POT_SUB,U> DGF_POT;
typedef Dune::PDELab::DiscreteGridFunctionGradient<GFS_POT_SUB,U> DGF_POT_GRAD;
typedef ChargeDensityGridFunction<DGF_CON, PHYSICS> GF_CD;
typedef IonicStrengthGridFunction<DGF_CON, PHYSICS> GF_IS;
typedef MembraneFluxGridFunction<DGF_CON,DGF_POT,PHYSICS> GF_MEMB_FLUX;
// Grid functions for initial values (subdomains)
typedef typename PHYSICS::Traits::INITIAL_CON INITIAL_GF_CON;
typedef InitialCon<GV,Real,NUMBER_OF_SPECIES,PHYSICS,INITIAL_GF_CON> INITIAL_CON;
typedef typename PHYSICS::Traits::INITIAL_POT INITIAL_GF_POT;
typedef InitialPot<GV,Real,PHYSICS,GF_CD,INITIAL_GF_POT> INITIAL_POT;
typedef Dune::PDELab::CompositeGridFunction<INITIAL_CON,INITIAL_POT> INITIAL_ELEC;
// Helper grid function to calculate equilibirum concentrations from stationary Poisson-Boltzmann potential
//typedef PoissonBoltzmannRHSGridFunction<DGF_POT, INITIAL_CON, PHYSICS> GF_PB_RHS;
//typedef PoissonBoltzmannConcentrationGridFunction<INITIAL_CON, DGF_POT, SubGV, PHYSICS> GF_PB_CON;
// Boundary values
typedef typename PHYSICS::Traits::NERNST_PLANCK_BOUNDARY BOUNDARY_CON;
typedef typename PHYSICS::Traits::POISSON_BOUNDARY BOUNDARY_POT;
// Parameter classes
typedef NernstPlanckParameters<GV,Real,PHYSICS,BOUNDARY_CON,GF_MEMB_FLUX> PARAMETERS_CON;
typedef PoissonParameters<GV,Real,PHYSICS,BOUNDARY_POT> PARAMETERS_POT;
};
// Choose domain and range field type
typedef GV GridView;
typedef typename GV::Grid GridType;
typedef typename GV::Grid::ctype Coord;
typedef double Real;
typedef typename GV::template Codim<0>::Iterator ElementIterator;
typedef Dune::SingleCodimSingleGeomTypeMapper<GV, 0> ElementMapper;
// SubGrid stuff
typedef typename SubGV::Grid SubGrid;
typedef Acme2Traits<NUMBER_OF_SPECIES> Traits;
static const bool writeIfNotConverged = true;
Acme2Setup(Grid& grid_, GV& gv_, PHYSICS& physics_,
SubGV& elecGV_, SubGV& membGV_)
: grid(grid_),
gv(gv_),
physics(physics_),
elecGV(elecGV_),
membGV(membGV_)
{}
void setup (double dtstart, double tend)
{
Real time = 0.0;
Real dt = dtstart;
const Acme2Parameters& params = physics.getParams();
Real tEquilibrium = physics.getParams().tEquilibrium();
if(tEquilibrium > time)
{
dt = physics.getParams().dtEquilibrium();
debug_info << "== Starting with initial dt = " << dt << " until tEquilibirum " << tEquilibrium
<< " ==" << std::endl;
}
const int dim = GV::dimension;
const int degreePot = 1, degreeCon = 1;
// Finite element map for CG
typename Traits::FEM_CON femCon;
typename Traits::FEM_POT femPot;
// =================== GFS SETUP ================================================================
// Single-component GFS for one ion species
typename Traits::GFS_SINGLE_CON gfsSingleCon(elecGV,femCon);
// Power grid function space for all ion species
typename Traits::GFS_CON gfsCon(gfsSingleCon);
// Full GFS for potential on electrolyte and membrane subdomain
typename Traits::GFS_POT gfsPot(gv,femPot);
// Multidomain GFS
//typename Traits::MultiGFS multigfs(grid,gfsCon,gfsPot);
typename Traits::MultiGFS multigfs(grid,gfsCon,gfsPot);
// SubGridFunctionSpaces for use in gridfunctions
typename Traits::GFS_CON_SUB gfsConSub(multigfs);
typename Traits::GFS_POT_SUB gfsPotSub(multigfs);
// ==============================================================================================
// =========== Define solution vectors ==========================================================
// Coefficient vectors on subdomains
//typename Traits::U_CON uoldCon(gfsCon,0.0);
//typename Traits::U_CON unewCon(gfsCon,0.0);
//debug_jochen << "U_CON.N(): " << unewCon.N() << std::endl;
//debug_jochen << "U_CON.flatsize(): " << unewCon.flatsize() << std::endl;
//typename Traits::U_POT uoldPot(gfsPot,0.0);
//typename Traits::U_POT unewPot(gfsPot,0.0);
//debug_jochen << "U_POT.N(): " << unewPot.N() << std::endl;
//debug_jochen << "U_POT.flatsize(): " << unewPot.flatsize() << std::endl;
typename Traits::U uold(multigfs,0.0);
typename Traits::U unew = uold;
debug_jochen << "U.N(): " << unew.N() << std::endl;
debug_jochen << "U.flatsize(): " << unew.flatsize() << std::endl;
debug_jochen << "con/pot GFS size: " << gfsConSub.size() << " / " << gfsPotSub.size() << std::endl;
// Now let's put 'em all into one structure!
//Acme2SolutionVectors<Traits> solutionVectors(uold, unew, uoldCon, unewCon, uoldPot, unewPot);
Acme2SolutionVectors<Traits> solutionVectors(uold, unew);
// ==============================================================================================
// ====== Create grid functions and interpolate initial values onto coefficient vectors =========
// Initial concentrations
typename Traits::INITIAL_GF_CON initialGFCon(gv,physics.getParams());
// Generic wrapper class for initial grid function
typename Traits::INITIAL_CON initialCon(gv,physics,initialGFCon);
initialCon.setTime(time);
typename Traits::DGF_CON_SUB dgfConElec(gfsConSub,unew);
typename Traits::DGF_CON_SUB dgfOldConElec(gfsConSub,uold);
typename Traits::DGF_CON_GRAD_SUB dgfGradConElec(gfsConSub, unew);
typename Traits::DGF_CON dgfCon(gv, dgfConElec, physics);
typename Traits::DGF_CON dgfOldCon(gv, dgfOldConElec, physics);
typename Traits::DGF_CON_GRAD dgfGradCon(gv, dgfGradConElec, physics);
typename Traits::GF_CD gfChargeDensity(dgfCon, dgfOldCon, physics);
typename Traits::GF_IS gfIonicStrength(dgfCon, physics);
// Initial potential
typename Traits::INITIAL_GF_POT initialGFPot(gv,physics.getParams());
typename Traits::INITIAL_POT initialPot(gv,physics,gfChargeDensity,initialGFPot,2*degreePot);
initialPot.setTime(time);
typename Traits::DGF_POT dgfPot(gfsPotSub, unew);
typename Traits::DGF_POT dgfOldPot(gfsPotSub, uold);
typename Traits::DGF_POT_GRAD dgfGradPot(gfsPotSub, unew);
// Flag 'true' for updating channel states in each time step
typename Traits::GF_MEMB_FLUX gfMembFlux(dgfOldCon, dgfOldPot, physics, true, tEquilibrium);
// Composite initial grid function for the electrolyte subdomain
typename Traits::INITIAL_ELEC initialElec(initialCon,initialPot);
// Define and instantiate output class
//typedef Acme2Output<Traits,GV,SubGV,typename Traits::GFS_CON,
// typename Traits::GFS_POT,typename Traits::U_CON,typename Traits::U_POT,PHYSICS> ACME2_OUTPUT;
typedef Acme2Output<Traits> ACME2_OUTPUT;
ACME2_OUTPUT acme2Output(gv,elecGV,membGV,multigfs,gfsConSub,gfsPotSub,solutionVectors,
gfMembFlux,physics,2*degreePot,2*degreeCon);
// ==============================================================================================
// ========== Define Parameter classes containing the model problem =============================
typename Traits::BOUNDARY_CON boundaryCon(physics.getParams(), initialGFCon);
typename Traits::PARAMETERS_CON parametersCon(gv,physics,boundaryCon,gfMembFlux,tEquilibrium);
typename Traits::BOUNDARY_POT boundaryPot(physics.getParams(), initialGFPot);
typename Traits::PARAMETERS_POT parametersPot(physics,boundaryPot);
// ==============================================================================================
// ============== BOUNDARY CONDITION TYPES ======================================================
typedef BCTypeSingleCon<typename Traits::PARAMETERS_CON,PHYSICS> BCType_SINGLE_CON;
typedef Dune::PDELab::PowerConstraintsParameters<BCType_SINGLE_CON,NUMBER_OF_SPECIES> BCType_CON;
typedef BCTypePot<typename Traits::PARAMETERS_POT,PHYSICS> BCType_POT;
typedef Dune::PDELab::CompositeConstraintsParameters<BCType_CON, BCType_POT> BCType_ELEC;
// Create NUMBER_OF_SPECIES boundary condition type classes
BCType_CON bctypeCon;
for(int i=0; i<NUMBER_OF_SPECIES; ++i)
{
BCType_SINGLE_CON* bctypeSingleCon = new BCType_SINGLE_CON(gv,parametersCon,physics,i);
bctypeCon.setChild(i,*bctypeSingleCon);
}
BCType_POT bctypePot(gv,parametersPot,physics);
BCType_ELEC bctypeElec(bctypeCon, bctypePot);
// ==============================================================================================
// ============== Define local operators ========================================================
// ##### Spatial part #####
// ### Standard FEM (CG) fully-coupled Poisson-Nernst-Planck local operator on electrolyte subdomain
typedef Acme2OperatorFullyCoupled<typename Traits::PARAMETERS_CON, typename Traits::PARAMETERS_POT,
typename Traits::FEM_CON, typename Traits::FEM_POT> LOP_ELEC;
LOP_ELEC lopElec(parametersCon, parametersPot);
// ### Standard FEM (CG) Poisson local operator on membrane subdomain
typedef Dune::PDELab::ConvectionDiffusionFEM<typename Traits::PARAMETERS_POT,typename Traits::FEM_POT> LOP_MEMB;
LOP_MEMB lopMemb(parametersPot);
// ##### Temporal part #####
typedef NernstPlanckTimeLocalOperator<PHYSICS> TLOP_ELEC;
TLOP_ELEC tlop(physics);
// ==============================================================================================
// =========== dune-multidomain setup stuff =====================================================
typedef Dune::PDELab::MultiDomain::SubDomainEqualityCondition<Grid> EC;
typedef Dune::PDELab::MultiDomain::SubDomainSupersetCondition<Grid> SC;
EC conditionElec(0); //only on subdomain 0
EC conditionMemb(1); //only on subdomain 1
SC conditionAll; //on all subdomains
// Empty constraints for subproblems
typename Traits::CONSTRAINTS constraints;
typedef Dune::PDELab::MultiDomain::TypeBasedSubProblem<typename Traits::MultiGFS,typename Traits::MultiGFS,
LOP_ELEC,EC,typename Traits::GFS_CON,typename Traits::GFS_POT> ElecSubProblem;
ElecSubProblem elecSubProblem(lopElec,conditionElec);
typedef Dune::PDELab::MultiDomain::TypeBasedSubProblem<typename Traits::MultiGFS,typename Traits::MultiGFS,
LOP_MEMB,EC,typename Traits::GFS_POT> MembSubProblem;
MembSubProblem membSubProblem(lopMemb,conditionMemb);
typedef Dune::PDELab::MultiDomain::SubProblem<typename Traits::MultiGFS,typename Traits::MultiGFS,
TLOP_ELEC,EC,0> TimeSubProblem;
TimeSubProblem timeSubProblem(tlop,conditionElec);
// ==============================================================================================
// =================== BOUNDARY CONDITIONS ======================================================
//typedef Traits::MultiGFS::ConstraintsContainer<Real>::Type CC;
typedef typename Traits::MultiGFS::template ConstraintsContainer<Real>::Type CC;
CC cc;
auto md_constraints = Dune::PDELab::MultiDomain::template constraints<Real>(multigfs,
Dune::PDELab::MultiDomain::constrainSubProblem(elecSubProblem, bctypeElec),
Dune::PDELab::MultiDomain::constrainSubProblem(membSubProblem, bctypePot));
md_constraints.assemble(cc);
std::cout << multigfs.size() << " DOF, " << cc.size() << " restricted" << std::endl;
// The following boundary value classes are not used, as they are assumed to be fulfilled by the
// initial conditions are not allowed to change over time!
// ###### Dirichlet values ########
typedef DirichletValuesSingleCon<typename Traits::PARAMETERS_CON> DirichletValuesSingleCon;
// Create NUMBER_OF_SPECIES Dirichlet value classes
typedef Dune::PDELab::PowerGridFunction<DirichletValuesSingleCon,NUMBER_OF_SPECIES> DirichletValuesCon;
DirichletValuesCon dirichletValuesCon;
for(int i=0; i<NUMBER_OF_SPECIES; ++i)
{
DirichletValuesSingleCon* dirichletValuesSingleCon
= new DirichletValuesSingleCon(gv,parametersCon,i);
dirichletValuesCon.setChild(i,*dirichletValuesSingleCon);
}
typedef Dune::PDELab::ConvectionDiffusionDirichletExtensionAdapter
<typename Traits::PARAMETERS_POT> DirichletValuesPot;
DirichletValuesPot dirichletValuesPot(gv,parametersPot);
// Is this necessary? Initial conditions should fulfill the boundary conditions anyways,
// otherwise we have an ill-posed problem!
//Dune::PDELab::interpolate(dirichletValuesCon_Inside,subGfsCon_Inside,unewCon_Inside);
//Dune::PDELab::copy_nonconstrained_dofs(ccCon_Inside,uoldCon_Inside,unewCon_Inside);
//Dune::PDELab::interpolate(dirichletValuesPot,gfsPot,uPot);
//Output::printSingleCoefficientVector(uPot, "uPot t=0");
// ==============================================================================================
// ============== Make grid operator ============================================================
typedef typename Traits::VBE::MatrixBackend MBE;
//typedef Dune::PDELab::GridOperator<GFS_POT,GFS_POT,STATIONARY_LOP_POT,MBE,Real,Real,Real,CC_POT,CC_POT>
// STATIONARY_GO_POT;
//STATIONARY_GO_POT stationaryGoPot(gfsPot,ccPot,gfsPot,ccPot,stationaryLopPot);
typedef Dune::PDELab::MultiDomain::GridOperator<typename Traits::MultiGFS,typename Traits::MultiGFS,
MBE,Real,Real,Real,CC,CC,ElecSubProblem,MembSubProblem> GO0;
typedef Dune::PDELab::MultiDomain::GridOperator<typename Traits::MultiGFS,typename Traits::MultiGFS,
MBE,Real,Real,Real,CC,CC,TimeSubProblem> GO1;
typedef Dune::PDELab::OneStepGridOperator<GO0,GO1> IGO;
GO0 go0(multigfs,multigfs,cc,cc,elecSubProblem,membSubProblem);
GO1 go1(multigfs,multigfs,cc,cc,timeSubProblem);
IGO igo(go0,go1);
// Here, initial values coming from the both subdomain initial GFs are written to uold
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,uold,initialElec,elecSubProblem);
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,uold,initialPot,membSubProblem);
unew = uold;
// ==============================================================================================
// ========== Select a linear solver backend ====================================================
#if USE_PARALLEL==1
//typedef Dune::PDELab::ISTLBackend_NOVLP_CG_NOPREC<typename Traits::MultiGFS> LS;
typedef Dune::PDELab::ISTLBackend_NOVLP_BCGS_SSORk<IGO> LS;
LS ls(multigfs);
#else
// funktionieren bei: PowerGFS lexicographic / PowerGFS blockwise<1,1,1> ?
//typedef Dune::PDELab::ISTLBackend_SEQ_LOOP_Jac LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_ILU0 LS; // nö / nö
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_ILUn LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_SSOR LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_Jac LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_AMG_SSOR<IGO> LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_MINRES_SSOR LS; // nö / nö
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_Jac LS; // nö / nö
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_SSOR LS; // nö / nö
// !!! Watch them constructor parameters !!!
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_ILU0 LS; //nö / ja
//LS ls(5000,5);
typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_ILUn LS; // hardly / ja
LS ls(1,1.0,5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_AMG_SSOR<IGO,true> LS; // nö / ja
//LS ls(5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_AMG_SOR<IGO,true> LS; // ? / ja
//LS ls(5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_LS_AMG_SSOR<IGO> LS; // nö / ja
//LS ls(5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_LS_AMG_SOR<IGO> LS; //nö / ja
//LS ls(5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_SuperLU LS;
//LS ls(5); // verbose = 1
debug_info << "Using linear solver " << Tools::getTypeName(ls) << std::endl;
//typedef typename FAKE_IGO::Traits::Jacobian M;
//typename M::BaseT MatrixType ;
//typedef typename FAKE_IGO::Traits::Domain FAKE_V;
//typedef typename IGO::Traits::Domain REAL_V;
//REAL_V v1(unew);
//FAKE_V v2(unew);
//debug_jochen << "M: " << Tools::getTypeName(bla) << std::endl;
//debug_jochen << "V: " << Tools::getTypeName(v1) << std::endl;
//debug_jochen << "V: " << Tools::getTypeName(v2) << std::endl;
//debug_jochen << "VectorType: " << Tools::getTypeName(v2) << std::endl;
#endif
#if 1
// ==============================================================================================
// ========= Solver for nonlinear problem per stage ==========================================
typedef Ax1Newton<ACME2_OUTPUT,IGO,LS,typename Traits::U> PDESOLVER;
PDESOLVER pdesolver(acme2Output,igo,ls,"octave/acme2");
pdesolver.setReassembleThreshold(0.0);
pdesolver.setVerbosityLevel(5); // 2
pdesolver.setReduction(params.getReduction()); // 1e-10
pdesolver.setAbsoluteLimit(params.getAbsLimit()); // 1e-10
pdesolver.setMinLinearReduction(1e-5); // has no effect when using direct solver like SuperLU
pdesolver.setMaxIterations(50);
pdesolver.setLineSearchStrategy(PDESOLVER::hackbuschReuskenAcceptBest);
pdesolver.setLineSearchMaxIterations(50); // 10
pdesolver.setPrintMatrix(params.doPrintMatrix());
pdesolver.setPrintRhs(params.doPrintRhs());
pdesolver.setRowPreconditioner(params.useRowNormPreconditioner());
pdesolver.setReorderMatrix(params.doReorderMatrix());
// ==============================================================================================
// ========== time-stepper ======================================================================
//Dune::PDELab::Alexander3Parameter<Real> timeStepper;
//Dune::PDELab::Alexander3Parameter<Real> timeStepper;
Dune::PDELab::ImplicitEulerParameter<Real> timeStepper;
//Dune::PDELab::ExplicitEulerParameter<Real> timeStepper;
//Dune::PDELab::RK4Parameter<Real> timeStepper;
//Dune::PDELab::HeunParameter<Real> timeStepper;
typedef Dune::PDELab::OneStepMethod<Real,IGO,PDESOLVER,typename Traits::U,typename Traits::U> SOLVER;
SOLVER solver(timeStepper,igo,pdesolver);
solver.setVerbosityLevel(0); // 2
// In case we need access to the pdesolver later on
const PDESOLVER& pdesolverRef = solver.getPDESolver();
// ==============================================================================================
// ========== Load saved state ======================================================================
if(physics.getParams().doLoadState())
{
//solutionVectors.printHostGridVectors();
std::string loadFilename = physics.getParams().getLoadFilename();
acme2Output.loadState(time,dt,loadFilename);
debug_info << "======================================================================================"
<< std::endl;
debug_info << "Loaded simulation state from file " << loadFilename << std::endl;
debug_info << "======================================================================================"
<< std::endl;
// Enforcing boundary conditions is removed; use the loaded values and leave them untouched!
/*
// Set Dirichlet boundary values from the saved data just loaded
Real xReference = params.xMin() + 0.5 * (params.xMax() - params.xMin());
Real yReference = params.yMin() + 0.5 * (params.yMax() - params.yMin());
std::vector<Real> boundaryValues = physics.getBoundaryValues(dgfPot, xReference, yReference);
initialGFPot.setPotValues(boundaryValues);
debug_jochen << "Boundary values: ";
Output::printVector(boundaryValues);
// Enforce boundary conditions
typename Traits::U uold_save = uold;
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,uold,initialElec,elecSubProblem);
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,uold,initialPot,membSubProblem);
Dune::PDELab::copy_nonconstrained_dofs(cc,uold_save,uold);
typename Traits::U unew_save = unew;
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,unew,initialElec,elecSubProblem);
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,unew,initialPot,membSubProblem);
Dune::PDELab::copy_nonconstrained_dofs(cc,unew_save,unew);
*/
if(not params.doContinueSimulation())
{
time = 0.0;
} else {
if(tend < time)
DUNE_THROW(Dune::Exception, "Start time (" << time << ") > end time (" << tend << ")!");
}
dt = dtstart;
if(tEquilibrium > time)
{
dt = physics.getParams().dtEquilibrium();
debug_info << "== Starting with initial dt = " << dt << " until tEquilibirum " << tEquilibrium
<< " ==" << std::endl;
}
//solutionVectors.printHostGridVectors();
}
// ==============================================================================================
// ========== Initial output ====================================================================
//Tools::compositeToChildCoefficientVector(multigfs, unew, unewCon, 0);
//uoldCon = unewCon;
//Tools::compositeToChildCoefficientVector(multigfs, unew, unewPot, 1);
//uoldPot = unewPot;
//Output::printSingleCoefficientVector(unewCon, "uCon");
//Output::printSingleCoefficientVector(unewPot, "uPot");
//Output::printSingleCoefficientVector(unew, "u");
double debyeLength, h_x, h_y;
physics.getDebyeLength(gfIonicStrength, debyeLength, h_x, h_y);
debug_info << std::endl;
debug_info << "@@@@@@@ minimum Debye length / length scale " << debyeLength / physics.getLengthScale()
<< std::endl;
debug_info << "@@@@@@@ h_x = " << h_x << ", h_y = " << h_y << std::endl;
if(h_x >= (debyeLength/physics.getLengthScale()) || h_y >= (debyeLength/physics.getLengthScale()))
{
debug_warn << "WARNING: Grid does not resolve Debye length [h_x = "
<< h_x << ", h_y = " << h_y << "]!" << std::endl;
}
debug_verb << "" << std::endl;
debug_jochen << "Diffusion length for this initial dt: "
<< 2*std::sqrt(physics.getDiffCoeff(Na, 0) * dt)
<< std::endl;
// ==============================================================================================
// ========== Run simulation ====================================================================
Acme2Simulation<Traits,ACME2_OUTPUT>::run(time, dt, dtstart, tend, tEquilibrium,
physics, gv, membGV,
solver,
parametersCon,
multigfs,
uold, unew,
//uoldCon, unewCon, uoldPot, unewPot,
gfMembFlux, dgfCon, dgfPot, dgfGradPot,
acme2Output, solutionVectors);
// ==============================================================================================
// ======= Save simulation state ================================================================
if(physics.getParams().doSaveState())
{
std::string saveFilename = physics.getParams().getSaveFilename();
acme2Output.saveState(time,dt,saveFilename);
debug_info << "=============================================================" << std::endl;
debug_info << "Saved simulation state to file " << saveFilename << std::endl;
debug_info << "=============================================================" << std::endl;
}
// ==============================================================================================
debug_info << "Total Acme2Output time: " << acme2Output.getTotalOutputTime() << "s" << std::endl;
#endif
}
private:
Grid& grid;
GV& gv;
PHYSICS& physics;
SubGV& elecGV;
SubGV& membGV;
};
#endif /* DUNE_AX1_ACME2_SETUP_HH */
| 48.82266
| 118
| 0.633908
|
pederpansen
|
5c82413d5761ffbcb270d723db59c0aae19fb02d
| 1,573
|
cpp
|
C++
|
tests/statement_serializator_tests/arithmetic_operators.cpp
|
tstrutz/sqlite_orm
|
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
|
[
"BSD-3-Clause"
] | 1,566
|
2016-12-20T15:31:04.000Z
|
2022-03-31T18:17:34.000Z
|
tests/statement_serializator_tests/arithmetic_operators.cpp
|
tstrutz/sqlite_orm
|
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
|
[
"BSD-3-Clause"
] | 620
|
2017-01-06T13:53:35.000Z
|
2022-03-31T12:05:50.000Z
|
tests/statement_serializator_tests/arithmetic_operators.cpp
|
tstrutz/sqlite_orm
|
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
|
[
"BSD-3-Clause"
] | 274
|
2017-01-07T05:34:24.000Z
|
2022-03-27T18:22:47.000Z
|
#include <sqlite_orm/sqlite_orm.h>
#include <catch2/catch.hpp>
using namespace sqlite_orm;
TEST_CASE("statement_serializator arithmetic operators") {
internal::serializator_context_base context;
SECTION("add") {
std::string value;
SECTION("func") {
value = serialize(add(3, 5), context);
}
SECTION("operator") {
value = serialize(c(3) + 5, context);
}
REQUIRE(value == "(3 + 5)");
}
SECTION("sub") {
std::string value;
SECTION("func") {
value = serialize(sub(5, -9), context);
}
SECTION("operator") {
value = serialize(c(5) - -9, context);
}
REQUIRE(value == "(5 - -9)");
}
SECTION("mul") {
std::string value;
SECTION("func") {
value = serialize(mul(10, 0.5), context);
}
SECTION("operator") {
value = serialize(c(10) * 0.5, context);
}
REQUIRE(value == "(10 * 0.5)");
}
SECTION("div") {
std::string value;
SECTION("func") {
value = serialize(sqlite_orm::div(10, 2), context);
}
SECTION("operator") {
value = serialize(c(10) / 2, context);
}
REQUIRE(value == "(10 / 2)");
}
SECTION("mod") {
std::string value;
SECTION("func") {
value = serialize(mod(20, 3), context);
}
SECTION("operator") {
value = serialize(c(20) % 3, context);
}
REQUIRE(value == "(20 % 3)");
}
}
| 26.661017
| 63
| 0.479975
|
tstrutz
|
5c84be2240a447f3a324bf46e131da0f9d3bbce4
| 263
|
cpp
|
C++
|
Code full house/buoi19 nguyen dinh trung duc/bai1146A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
Code full house/buoi19 nguyen dinh trung duc/bai1146A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
Code full house/buoi19 nguyen dinh trung duc/bai1146A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
/*bai 1146A*/
#include<stdio.h>
#include<string.h>
int main(){
char c[100];
scanf("%s",c);
int i,cnt=0;
int len=strlen(c);
for(i=0; i<len;i++){
if((c[i]-'a')==0) cnt++;
}
if(cnt>(len/2)){
printf("%d",len);
return 0;
}
else printf("%d",2*cnt-1);
}
| 13.842105
| 27
| 0.528517
|
ducyb2001
|
5c867d124d49f0d0a622157b48250bf937968b74
| 5,186
|
cc
|
C++
|
tools/graft/graft.cc
|
fcharlie/git-analyze-sync
|
1c974ac4b6f695c01ee666aff60d7817f6c0acaf
|
[
"MIT"
] | 1
|
2021-02-18T06:12:13.000Z
|
2021-02-18T06:12:13.000Z
|
tools/graft/graft.cc
|
fcharlie/git-analyze-sync
|
1c974ac4b6f695c01ee666aff60d7817f6c0acaf
|
[
"MIT"
] | 1
|
2021-08-28T14:08:30.000Z
|
2021-08-28T14:09:32.000Z
|
tools/graft/graft.cc
|
fcharlie/git-analyze-sync
|
1c974ac4b6f695c01ee666aff60d7817f6c0acaf
|
[
"MIT"
] | 1
|
2021-08-28T14:00:29.000Z
|
2021-08-28T14:00:29.000Z
|
/// THIS IS GRAFT COMMAND
#include <cstdio>
#include <cstdlib>
#include <string>
#include <string_view>
#include <argv.hpp>
#include <git.hpp>
#include <optional>
#include <console.hpp>
#include <os.hpp>
struct graft_info_t {
std::string gitdir{"."};
std::string branch;
std::string commitid;
std::string message;
};
void PrintUsage() {
const char *ua = R"(OVERVIEW: git-graft
Usage: git-graft [options] <input>
OPTIONS:
-h [--help] print git-graft usage information and exit
-b [--branch] new branch name.
-d [--git-dir] repository path.
-m [--message] commit message
Example:
git-graft commit-id -m "message"
)";
printf("%s", ua);
}
bool parse_argv(int argc, char **argv, graft_info_t &gf) {
av::ParseArgv pv(argc, argv);
pv.Add("help", av::no_argument, 'h')
.Add("git-dir", av::required_argument, 'd')
.Add("message", av::required_argument, 'm')
.Add("branch", av::required_argument, 'b');
av::error_code ec;
auto result = pv.Execute(
[&](int ch, const char *optarg, const char *raw) {
switch (ch) {
case 'h':
PrintUsage();
exit(0);
break;
case 'b':
gf.branch = optarg;
break;
case 'm':
gf.message = optarg;
break;
case 'd':
gf.gitdir = optarg;
break;
default:
printf("Error Argument: %s\n", raw != nullptr ? raw : "unknown");
return false;
}
return true;
},
ec);
if (!result && ec.ec != av::SkipParse) {
aze::FPrintF(stderr, "ParseArgv: %s\n", ec.message);
return false;
}
if (pv.UnresolvedArgs().size() < 1) {
PrintUsage();
return false;
}
gf.commitid = pv.UnresolvedArgs()[0];
return true;
}
class SignatureSaver {
public:
SignatureSaver() = default;
SignatureSaver(const SignatureSaver &) = delete;
SignatureSaver &operator=(const SignatureSaver &) = delete;
void InitializeEnv() {
name = os::GetEnv("GIT_COMMITTER_NAME");
email = os::GetEnv("GIT_COMMITTER_EMAIL");
aname = os::GetEnv("GIT_AUTHOR_NAME");
aemail = os::GetEnv("GIT_AUTHOR_NAME");
}
void UpdateCommiter(git_signature *sig, const git_signature *old) {
sig->email = email.empty() ? old->email : email.data();
sig->name = name.empty() ? old->name : name.data();
sig->when = old->when;
}
void UpdateAuthor(git_signature *sig, const git_signature *old) {
sig->email = aemail.empty() ? old->email : aemail.data();
sig->name = aname.empty() ? old->name : aname.data();
sig->when = old->when;
}
private:
std::string name;
std::string email;
std::string aname;
std::string aemail;
};
void dump_error() {
auto ec = giterr_last();
if (ec != nullptr) {
aze::FPrintF(stderr, "%s\n", ec->message);
}
}
std::optional<std::string> make_refname(git::repository &r,
std::string_view sv) {
if (!sv.empty()) {
return std::make_optional(absl::StrCat("refs/heads/", sv));
}
auto ref = r.get_reference("HEAD");
if (!ref) {
return std::nullopt;
}
auto dr = ref->symbolic_target();
if (!dr) {
return std::nullopt;
}
auto p = git_reference_name(dr->p());
if (p != nullptr) {
return std::make_optional(p);
}
return std::nullopt;
}
bool graft_commit(const graft_info_t &gf) {
git::error_code ec;
auto repo = git::repository::make_repository_ex(gf.gitdir, ec);
if (!repo) {
aze::FPrintF(stderr, "Error: %s\n", ec.message);
return false;
}
auto commit = repo->get_commit(gf.commitid);
if (!commit) {
aze::FPrintF(stderr, "open commit: %s ", gf.commitid);
dump_error();
return false;
}
auto refname = make_refname(*repo, gf.branch);
if (!refname) {
aze::FPrintF(stderr, "unable lookup branch name\n");
return false;
}
auto parent = repo->get_reference_commit(*refname);
if (!parent) {
aze::FPrintF(stderr, "open par commit: %s ", gf.branch);
dump_error();
return false;
}
///
git_tree *tree = nullptr;
if (git_commit_tree(&tree, commit->p()) != 0) {
dump_error();
return false;
}
git_signature author, committer;
SignatureSaver saver;
saver.InitializeEnv();
saver.UpdateAuthor(&author, git_commit_author(commit->p()));
saver.UpdateCommiter(&committer, git_commit_committer(commit->p()));
std::string msg =
gf.message.empty() ? git_commit_message(commit->p()) : gf.message;
const git_commit *parents[] = {parent->p(), commit->p()};
aze::FPrintF(stderr, "New commit, message: '%s'\n", msg);
git_oid oid;
if (git_commit_create(&oid, repo->p(), refname->c_str(), &author, &committer,
nullptr, msg.c_str(), tree, 2, parents) != 0) {
dump_error();
git_tree_free(tree);
return false;
}
fprintf(stderr, "New commit id: %s\n", git_oid_tostr_s(&oid));
git_tree_free(tree);
return true;
}
int cmd_main(int argc, char **argv) {
git::global_initializer_t gi;
graft_info_t gf;
if (!parse_argv(argc, argv, gf)) {
return 1;
}
if (!graft_commit(gf)) {
return 1;
}
return 0;
}
| 26.324873
| 79
| 0.599306
|
fcharlie
|
5c882414a57083cd60b3f99239924d5285baf426
| 1,315
|
cpp
|
C++
|
monitor.cpp
|
n7jti/Freezer-Monitor-AWS-SNS
|
3eeb19135582839ae84943cfd0310a6b22a11853
|
[
"MIT"
] | null | null | null |
monitor.cpp
|
n7jti/Freezer-Monitor-AWS-SNS
|
3eeb19135582839ae84943cfd0310a6b22a11853
|
[
"MIT"
] | null | null | null |
monitor.cpp
|
n7jti/Freezer-Monitor-AWS-SNS
|
3eeb19135582839ae84943cfd0310a6b22a11853
|
[
"MIT"
] | null | null | null |
// monitor.cpp
#include <arduino.h>
#include "monitor.h"
Monitor::Monitor(Trigger *trigger, unsigned int timeout)
: _trigger(trigger)
, _timeout(timeout)
, _state(MONITOR_GREEN)
, _stateStartMs(millis())
{
}
bool Monitor::begin()
{
return _trigger->begin();
}
MONITOR_STATE Monitor::getState()
{
return _state;
}
unsigned int Monitor::getStateElapsedMs()
{
return millis() - _stateStartMs;
}
MONITOR_STATE Monitor::run()
{
unsigned int now = millis();
unsigned int elapsed = now - _stateStartMs;
bool triggered = _trigger->isTriggered();
switch(_state)
{
case MONITOR_RED:
if (triggered == false)
{
_stateStartMs = now;
_state = MONITOR_GREEN;
}
break;
case MONITOR_YELLOW:
if (triggered == false)
{
_stateStartMs = now;
_state = MONITOR_GREEN;
}
else if (elapsed > _timeout)
{
_state = MONITOR_RED;
}
break;
case MONITOR_GREEN:
if (triggered == true)
{
_stateStartMs = now;
_state = MONITOR_YELLOW;
}
break;
}
return _state;
}
int Monitor::getStatus(char* buffer, int length)
{
return _trigger->getStatus(buffer, length);
}
| 18.785714
| 57
| 0.571103
|
n7jti
|
5c8f9c5ab8dcad47af31d168f5086a6febef5480
| 633
|
cpp
|
C++
|
leetcode/844. Backspace String Compare/s1.cpp
|
contacttoakhil/LeetCode-1
|
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
|
[
"Fair"
] | 1
|
2021-02-09T11:38:51.000Z
|
2021-02-09T11:38:51.000Z
|
leetcode/844. Backspace String Compare/s1.cpp
|
contacttoakhil/LeetCode-1
|
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
|
[
"Fair"
] | null | null | null |
leetcode/844. Backspace String Compare/s1.cpp
|
contacttoakhil/LeetCode-1
|
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
|
[
"Fair"
] | null | null | null |
// OJ: https://leetcode.com/problems/backspace-string-compare/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
private:
int normalize(string &S) {
int length = 0;
for (char c : S) {
if (c == '#') {
if (length) --length;
} else S[length++] = c;
}
return length;
}
public:
bool backspaceCompare(string S, string T) {
int s = normalize(S), t = normalize(T);
if (s != t) return false;
for (int i = 0; i < s; ++i) {
if (S[i] != T[i]) return false;
}
return true;
}
};
| 25.32
| 62
| 0.478673
|
contacttoakhil
|
5c92736f323d3d4510783548178754bf6da786a1
| 354
|
cpp
|
C++
|
src/common/Client.cpp
|
jiridanek/cli-cpp
|
0e79a8a6c7f16849e741c73ce74e90e79f82bff3
|
[
"Apache-2.0"
] | 1
|
2020-10-13T08:17:20.000Z
|
2020-10-13T08:17:20.000Z
|
src/common/Client.cpp
|
rh-messaging/cli-cpp
|
73803c7a72fb976ec6e32292115c2a61e7642d8d
|
[
"Apache-2.0"
] | 18
|
2020-04-05T10:02:09.000Z
|
2021-11-03T12:04:39.000Z
|
src/common/Client.cpp
|
jiridanek/cli-cpp
|
0e79a8a6c7f16849e741c73ce74e90e79f82bff3
|
[
"Apache-2.0"
] | 2
|
2018-08-10T08:53:33.000Z
|
2020-04-05T11:38:04.000Z
|
/*
* Client.cpp
*
* Created on: Apr 28, 2015
* Author: opiske
*/
#include "Client.h"
using namespace dtests::common;
using namespace dtests::common::log;
Logger Client::logger = LoggerWrapper::getLogger();
Client::Client()
{
// TODO Auto-generated constructor stub
}
Client::~Client()
{
// TODO Auto-generated destructor stub
}
| 13.615385
| 51
| 0.663842
|
jiridanek
|
5c9346e219ecf37ed5bee4f71d4d5f7e0d45ec47
| 642
|
cpp
|
C++
|
test/blob.cpp
|
detunized/lastpass-cpp
|
d938cb142abee6c6f19b5f35a70da802d8a41ffa
|
[
"MIT"
] | 5
|
2015-12-11T14:49:59.000Z
|
2019-10-10T17:02:18.000Z
|
test/blob.cpp
|
detunized/lastpass-cpp
|
d938cb142abee6c6f19b5f35a70da802d8a41ffa
|
[
"MIT"
] | null | null | null |
test/blob.cpp
|
detunized/lastpass-cpp
|
d938cb142abee6c6f19b5f35a70da802d8a41ffa
|
[
"MIT"
] | null | null | null |
// Copyright (C) 2014 Dmitry Yakimenko (detunized@gmail.com).
// Licensed under the terms of the MIT license. See LICENCE for details.
#include "test.h"
namespace
{
using namespace lastpass;
using namespace test;
auto const BLOB_BYTES = "\x4c\x50\x41\x56\x00\x00\x00\x03\x31\x31\x38"_s;
int const KEY_ITERATION_COUNT = 5000;
Blob blob()
{
return {BLOB_BYTES, KEY_ITERATION_COUNT};
}
BOOST_AUTO_TEST_CASE(blob_bytes_returns_set_value)
{
BOOST_CHECK(blob().bytes() == BLOB_BYTES);
}
BOOST_AUTO_TEST_CASE(blob_key_iteration_count_returns_set_value)
{
BOOST_CHECK_EQUAL(blob().key_iteration_count(), KEY_ITERATION_COUNT);
}
}
| 20.709677
| 73
| 0.76324
|
detunized
|
5c97bbc3bf52ba514bb696920cb6b0b0f6d832af
| 4,904
|
hpp
|
C++
|
include/argot/case/detail/as_constant.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | 49
|
2018-05-09T23:17:45.000Z
|
2021-07-21T10:05:19.000Z
|
include/argot/case/detail/as_constant.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | null | null | null |
include/argot/case/detail/as_constant.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | 2
|
2019-08-04T03:51:36.000Z
|
2020-12-28T06:53:29.000Z
|
/*==============================================================================
Copyright (c) 2017, 2018 Matt Calabrese
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef ARGOT_CASE_DETAIL_AS_CONSTANT_HPP_
#define ARGOT_CASE_DETAIL_AS_CONSTANT_HPP_
#include <argot/case/detail/cast_value_list_elements.hpp>
#include <argot/concepts/argument_receiver.hpp> // of
#include <argot/concepts/case_labels.hpp>
#include <argot/concepts/persistent_switch_body_case.hpp>
#include <argot/concepts/switch_body.hpp>
#include <argot/concepts/switch_body_case.hpp>
#include <argot/concepts/true.hpp>
#include <argot/detail/constant.hpp>
#include <argot/detail/unreachable.hpp>
#include <argot/detail/forward.hpp>
#include <argot/gen/access_raw_concept_map.hpp>
#include <argot/gen/concept_assert.hpp>
#include <argot/gen/requires.hpp>
#include <argot/receiver_traits/argument_list_kinds.hpp>
#include <argot/receiver_traits/argument_types.hpp>
#include <argot/receiver_traits/receive.hpp>
#include <argot/value_list.hpp>
#include <argot/value_zipper.hpp>
namespace argot {
namespace case_detail {
template< class Cases >
struct as_constant_t {};
template< class Values >
struct values_to_integral_constant_argument_list_kinds;
template< auto... Values >
struct values_to_integral_constant_argument_list_kinds
< value_list_t< Values... > >
{
using type
= receiver_traits::argument_list_kinds_t
< receiver_traits::argument_types_t
< call_detail::constant< Values >&& >...
>;
};
template< class Values >
using values_to_integral_constant_argument_list_kinds_t
= typename values_to_integral_constant_argument_list_kinds< Values >::type;
} // namespace argot(::case_detail)
template< class Cases >
struct make_concept_map< SwitchBody< case_detail::as_constant_t< Cases > > >
{
// TODO(mattcalabrese) Don't access raw
using case_values_t
= typename access_raw_concept_map< CaseLabels< Cases > >::case_values_t;
template< template< auto... > class Template >
using expand_case_values_t
= typename access_raw_concept_map< CaseLabels< Cases > >
::template expand_case_values_t< Template >;
};
// TODO(mattcalabrese) Constrain
template< class Cases, auto Value >
struct make_concept_map
< SwitchBodyCase< case_detail::as_constant_t< Cases >, Value >
, ARGOT_REQUIRES
( True
< value_zipper_contains_v
< case_detail::cast_value_list_elements_t
< decltype( Value )
, typename access_raw_concept_map< CaseLabels< Cases > >::case_values_t
>
, Value
>
>
)
<>
>
{
private:
using typed_value_list
= case_detail::cast_value_list_elements_t
< decltype( Value )
, typename access_raw_concept_map< CaseLabels< Cases > >::case_values_t
>;
using partition = value_zipper_find_t< typed_value_list, Value >;
public:
using leading_argument_list_kinds_t
= case_detail::values_to_integral_constant_argument_list_kinds_t
< typename partition::leading_t >;
using trailing_argument_list_kinds_t
= case_detail::values_to_integral_constant_argument_list_kinds_t
< typename partition::trailing_t >;
// TODO(mattcalabrese) Constrain
template< class Receiver >
static constexpr decltype( auto ) provide_isolated_case
( case_detail::as_constant_t< Cases > self, Receiver&& rec )
{
return receiver_traits::receive
( ARGOT_FORWARD( Receiver )( rec )
, std::integral_constant< detail_argot::remove_cvref_t< decltype( Value ) >, Value >()
);
}
};
// TODO(mattcalabrese) Constrain
template< class Cases, auto Value >
struct make_concept_map
< PersistentSwitchBodyCase< case_detail::as_constant_t< Cases >, Value > >
{
private:
using typed_value_list
= case_detail::cast_value_list_elements_t
< decltype( Value )
, typename access_raw_concept_map< CaseLabels< Cases > >::case_values_t
>;
using partition = value_zipper_find_t< typed_value_list, Value >;
public:
using leading_argument_list_kinds_t
= case_detail::values_to_integral_constant_argument_list_kinds_t
< typename partition::leading_t >;
using trailing_argument_list_kinds_t
= case_detail::values_to_integral_constant_argument_list_kinds_t
< typename partition::trailing_t >;
// TODO(mattcalabrese) Constrain
template< class Receiver >
static constexpr decltype( auto ) provide_isolated_case
( case_detail::as_constant_t< Cases > self, Receiver&& rec )
{
// TODO(mattcalabrese) Use constant
return receiver_traits::receive
( ARGOT_FORWARD( Receiver )( rec )
, std::integral_constant< detail_argot::remove_cvref_t< decltype( Value ) >, Value >()
);
}
};
} // namespace argot
#endif // ARGOT_CASE_DETAIL_AS_CONSTANT_HPP_
| 31.844156
| 90
| 0.727977
|
mattcalabrese
|
5c9a2e881e4074428205f84ee26402159f5a20a7
| 5,794
|
hpp
|
C++
|
INCLUDE/Vcl/dblocal.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | 1
|
2022-01-13T01:03:55.000Z
|
2022-01-13T01:03:55.000Z
|
INCLUDE/Vcl/dblocal.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null |
INCLUDE/Vcl/dblocal.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null |
// Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'DBLocal.pas' rev: 6.00
#ifndef DBLocalHPP
#define DBLocalHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <Provider.hpp> // Pascal unit
#include <DBClient.hpp> // Pascal unit
#include <SqlTimSt.hpp> // Pascal unit
#include <Midas.hpp> // Pascal unit
#include <DBCommon.hpp> // Pascal unit
#include <DB.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <Variants.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Dblocal
{
//-- type declarations -------------------------------------------------------
#pragma option push -b-
enum TSqlDBType { typeDBX, typeBDE, typeADO, typeIBX };
#pragma option pop
class DELPHICLASS TCustomCachedDataSet;
class PASCALIMPLEMENTATION TCustomCachedDataSet : public Dbclient::TCustomClientDataSet
{
typedef Dbclient::TCustomClientDataSet inherited;
private:
Provider::TDataSetProvider* FProvider;
TSqlDBType FSqlDBType;
Provider::TBeforeUpdateRecordEvent __fastcall GetBeforeUpdateRecord();
void __fastcall SetBeforeUpdateRecord(Provider::TBeforeUpdateRecordEvent Value);
Provider::TAfterUpdateRecordEvent __fastcall GetAfterUpdateRecord();
void __fastcall SetAfterUpdateRecord(Provider::TAfterUpdateRecordEvent Value);
Provider::TGetTableNameEvent __fastcall GetOnGetTableName();
void __fastcall SetOnGetTableName(Provider::TGetTableNameEvent Value);
Provider::TProviderDataEvent __fastcall GetOnUpdateData();
void __fastcall SetOnUpdateData(Provider::TProviderDataEvent Value);
Provider::TResolverErrorEvent __fastcall GetOnUpdateError();
void __fastcall SetOnUpdateError(Provider::TResolverErrorEvent Value);
protected:
virtual void __fastcall CloseCursor(void);
virtual AnsiString __fastcall GetCommandText();
Provider::TProviderOptions __fastcall GetOptions(void);
Db::TUpdateMode __fastcall GetUpdateMode(void);
virtual void __fastcall SetActive(bool Value);
virtual void __fastcall SetAggregates(Dbclient::TAggregates* Value);
virtual void __fastcall SetCommandText(AnsiString Value);
void __fastcall SetOptions(Provider::TProviderOptions Value);
void __fastcall SetUpdateMode(Db::TUpdateMode Value);
__property Provider::TDataSetProvider* Provider = {read=FProvider, write=FProvider};
__property TSqlDBType SqlDBType = {read=FSqlDBType, write=FSqlDBType, nodefault};
public:
__fastcall virtual TCustomCachedDataSet(Classes::TComponent* AOwner);
__fastcall virtual ~TCustomCachedDataSet(void);
HIDESBASE void __fastcall LoadFromFile(const AnsiString AFileName = "");
__published:
__property Active = {default=0};
__property CommandText ;
__property Aggregates ;
__property AggregatesActive = {default=0};
__property AutoCalcFields = {default=1};
__property Constraints = {stored=ConstraintsStored};
__property DisableStringTrim = {default=0};
__property FetchOnDemand = {default=1};
__property FieldDefs ;
__property FileName ;
__property Filter ;
__property Filtered = {default=0};
__property FilterOptions = {default=0};
__property IndexDefs ;
__property IndexFieldNames ;
__property IndexName ;
__property MasterFields ;
__property MasterSource ;
__property Provider::TProviderOptions Options = {read=GetOptions, write=SetOptions, default=0};
__property ObjectView = {default=1};
__property PacketRecords = {default=-1};
__property Params ;
__property ReadOnly = {default=0};
__property Db::TUpdateMode UpdateMode = {read=GetUpdateMode, write=SetUpdateMode, default=0};
__property BeforeOpen ;
__property AfterOpen ;
__property BeforeClose ;
__property AfterClose ;
__property BeforeInsert ;
__property AfterInsert ;
__property BeforeEdit ;
__property AfterEdit ;
__property BeforePost ;
__property AfterPost ;
__property BeforeCancel ;
__property AfterCancel ;
__property BeforeDelete ;
__property AfterDelete ;
__property BeforeScroll ;
__property AfterScroll ;
__property BeforeRefresh ;
__property AfterRefresh ;
__property OnCalcFields ;
__property OnDeleteError ;
__property OnEditError ;
__property OnFilterRecord ;
__property OnNewRecord ;
__property OnPostError ;
__property OnReconcileError ;
__property BeforeApplyUpdates ;
__property AfterApplyUpdates ;
__property BeforeGetRecords ;
__property AfterGetRecords ;
__property BeforeRowRequest ;
__property AfterRowRequest ;
__property BeforeExecute ;
__property AfterExecute ;
__property BeforeGetParams ;
__property AfterGetParams ;
__property Provider::TBeforeUpdateRecordEvent BeforeUpdateRecord = {read=GetBeforeUpdateRecord, write=SetBeforeUpdateRecord};
__property Provider::TAfterUpdateRecordEvent AfterUpdateRecord = {read=GetAfterUpdateRecord, write=SetAfterUpdateRecord};
__property Provider::TGetTableNameEvent OnGetTableName = {read=GetOnGetTableName, write=SetOnGetTableName};
__property Provider::TProviderDataEvent OnUpdateData = {read=GetOnUpdateData, write=SetOnUpdateData};
__property Provider::TResolverErrorEvent OnUpdateError = {read=GetOnUpdateError, write=SetOnUpdateError};
};
//-- var, const, procedure ---------------------------------------------------
} /* namespace Dblocal */
using namespace Dblocal;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // DBLocal
| 38.626667
| 127
| 0.746634
|
earthsiege2
|
5ca31c5a46250b493e1cee0dddb8f66a9f62e8c5
| 6,713
|
cxx
|
C++
|
Testing/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilterTest.cxx
|
kiranhs/ITKv4FEM-Kiran
|
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
|
[
"BSD-3-Clause"
] | 1
|
2018-04-15T13:32:43.000Z
|
2018-04-15T13:32:43.000Z
|
Testing/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilterTest.cxx
|
kiranhs/ITKv4FEM-Kiran
|
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
|
[
"BSD-3-Clause"
] | null | null | null |
Testing/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilterTest.cxx
|
kiranhs/ITKv4FEM-Kiran
|
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
|
[
"BSD-3-Clause"
] | null | null | null |
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkDiffusionTensor3DReconstructionImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkDiffusionTensor3DReconstructionImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include <iostream>
int itkDiffusionTensor3DReconstructionImageFilterTest(int, char*[])
{
typedef short int ReferencePixelType;
typedef short int GradientPixelType;
typedef double TensorPrecisionType;
typedef itk::DiffusionTensor3DReconstructionImageFilter<
ReferencePixelType, GradientPixelType, TensorPrecisionType >
TensorReconstructionImageFilterType;
typedef TensorReconstructionImageFilterType::GradientImageType GradientImageType;
TensorReconstructionImageFilterType::Pointer tensorReconstructionFilter =
TensorReconstructionImageFilterType::New();
// Create a reference image
//
typedef TensorReconstructionImageFilterType::ReferenceImageType ReferenceImageType;
ReferenceImageType::Pointer referenceImage = ReferenceImageType::New();
typedef ReferenceImageType::RegionType ReferenceRegionType;
typedef ReferenceRegionType::IndexType ReferenceIndexType;
typedef ReferenceRegionType::SizeType ReferenceSizeType;
ReferenceSizeType sizeReferenceImage = {{ 4, 4, 4 }};
ReferenceIndexType indexReferenceImage = {{ 0, 0, 0 }};
ReferenceRegionType regionReferenceImage;
regionReferenceImage.SetSize( sizeReferenceImage );
regionReferenceImage.SetIndex( indexReferenceImage);
referenceImage->SetRegions( regionReferenceImage );
referenceImage->Allocate();
referenceImage->FillBuffer( 100 );
const unsigned int numberOfGradientImages = 6;
// Assign gradient directions
//
double gradientDirections[6][3] =
{
{-1.000000, 0.000000 , 0.000000},
{-0.166000, 0.986000 , 0.000000},
{0.110000 , 0.664000 , 0.740000},
{-0.901000, -0.419000 , -0.110000},
{0.169000 , -0.601000 , 0.781000},
{0.815000 , -0.386000 , 0.433000}
};
// Create gradient images
//
typedef GradientImageType::Pointer GradientImagePointer;
typedef TensorReconstructionImageFilterType::GradientImageType GradientImageType;
typedef GradientImageType::RegionType GradientRegionType;
typedef GradientRegionType::IndexType GradientIndexType;
typedef GradientRegionType::SizeType GradientSizeType;
typedef ReferenceRegionType::IndexType ReferenceIndexType;
for( unsigned int i=0; i < numberOfGradientImages; i++ )
{
GradientImageType::Pointer gradientImage = GradientImageType::New();
GradientSizeType sizeGradientImage = {{ 4, 4, 4 }};
GradientIndexType indexGradientImage = {{ 0, 0, 0 }};
GradientRegionType regionGradientImage;
regionGradientImage.SetSize( sizeGradientImage );
regionGradientImage.SetIndex( indexGradientImage);
gradientImage->SetRegions( regionGradientImage );
gradientImage->Allocate();
itk::ImageRegionIteratorWithIndex< GradientImageType > git(
gradientImage, regionGradientImage );
git.GoToBegin();
while( !git.IsAtEnd() )
{
GradientPixelType fancyGradientValue =
static_cast< short int >((i+1) * (i+1) * (i+1));
git.Set( fancyGradientValue );
++git;
}
TensorReconstructionImageFilterType::GradientDirectionType gradientDirection;
gradientDirection[0] = gradientDirections[i][0];
gradientDirection[1] = gradientDirections[i][1];
gradientDirection[2] = gradientDirections[i][2];
tensorReconstructionFilter->AddGradientImage( gradientDirection, gradientImage );
std::cout << "Gradient directions: " << gradientDirection << std::endl;
}
tensorReconstructionFilter->SetReferenceImage( referenceImage );
// TODO: remove this when netlib is made thread safe
tensorReconstructionFilter->SetNumberOfThreads( 1 );
// Also see if vnl_svd is thread safe now...
std::cout << std::endl << "This filter is using " <<
tensorReconstructionFilter->GetNumberOfThreads() << " threads " << std::endl;
tensorReconstructionFilter->Update();
typedef TensorReconstructionImageFilterType::TensorImageType TensorImageType;
TensorImageType::Pointer tensorImage = tensorReconstructionFilter->GetOutput();
typedef TensorImageType::IndexType TensorImageIndexType;
TensorImageIndexType tensorImageIndex = {{3,3,3}};
GradientIndexType gradientImageIndex = {{3,3,3}};
ReferenceIndexType referenceImageIndex = {{3,3,3}};
std::cout << std::endl << "Pixels at index: " << tensorImageIndex << std::endl;
std::cout << "Reference pixel "
<< referenceImage->GetPixel( referenceImageIndex ) << std::endl;
for( unsigned int i=0; i < numberOfGradientImages; i++ )
{
std::cout << "Gradient image " << i << " pixel : "
<< static_cast< GradientImageType * >( const_cast< GradientImageType * >(
tensorReconstructionFilter->GetInput(i+1)))->GetPixel(gradientImageIndex)
<< std::endl;
}
double expectedResult[3][3] =
{
{4.60517, -2.6698, -8.4079},
{-2.6698, 1.56783, 0.900034},
{-8.4079, 0.900034, 2.62504}
};
std::cout << std::endl << "Reconstructed tensor : " << std::endl;
bool passed = true;
double precision = 0.0001;
for( unsigned int i = 0; i<3; i++ )
{
std::cout << "\t";
for( unsigned int j = 0; j<3; j++ )
{
std::cout << tensorImage->GetPixel(tensorImageIndex)(i,j) << " ";
if( (vnl_math_abs(tensorImage->GetPixel(tensorImageIndex)(i,j) - expectedResult[i][j])) > precision )
{
passed = false;
}
}
std::cout << std::endl;
}
if( !passed )
{
std::cout << "[FAILED]" << std::endl;
std::cout << "Expected tensor : " << std::endl;
for( unsigned int i = 0; i<3; i++ )
{
std::cout << "\t";
for( unsigned int j = 0; j<3; j++ )
{
std::cout << expectedResult[i][j] << " ";
}
std::cout << std::endl;
}
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
return EXIT_SUCCESS;
}
| 37.294444
| 107
| 0.669
|
kiranhs
|
5ca36a3257ea70050ddcc68b9a46f3ad7cd8660b
| 479
|
cpp
|
C++
|
MonoNative.Tests/mscorlib/System/mscorlib_System_IDisposable_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 7
|
2015-03-10T03:36:16.000Z
|
2021-11-05T01:16:58.000Z
|
MonoNative.Tests/mscorlib/System/mscorlib_System_IDisposable_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 1
|
2020-06-23T10:02:33.000Z
|
2020-06-24T02:05:47.000Z
|
MonoNative.Tests/mscorlib/System/mscorlib_System_IDisposable_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | null | null | null |
// Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System
// Name: IDisposable
// C++ Typed Name: mscorlib::System::IDisposable
#include <gtest/gtest.h>
#include <mscorlib/System/mscorlib_System_IDisposable.h>
namespace mscorlib
{
namespace System
{
//Public Methods Tests
// Method Dispose
// Signature:
TEST(mscorlib_System_IDisposable_Fixture,Dispose_Test)
{
}
}
}
| 15.451613
| 88
| 0.716075
|
brunolauze
|
5ca6e5bcac7c9d5625a7186af86632f2520fbd60
| 498
|
hpp
|
C++
|
src/entt/container/fwd.hpp
|
pgruenbacher/entt
|
2f06d1ce3c99c49ef61d7bc2080a16cdaa08e3ef
|
[
"MIT"
] | 6,792
|
2017-03-27T19:05:19.000Z
|
2022-03-31T20:21:26.000Z
|
src/entt/container/fwd.hpp
|
pgruenbacher/entt
|
2f06d1ce3c99c49ef61d7bc2080a16cdaa08e3ef
|
[
"MIT"
] | 764
|
2017-05-22T18:48:53.000Z
|
2022-03-31T22:04:27.000Z
|
src/entt/container/fwd.hpp
|
pgruenbacher/entt
|
2f06d1ce3c99c49ef61d7bc2080a16cdaa08e3ef
|
[
"MIT"
] | 811
|
2017-03-27T19:52:48.000Z
|
2022-03-30T11:32:57.000Z
|
#ifndef ENTT_CONTAINER_FWD_HPP
#define ENTT_CONTAINER_FWD_HPP
#include <functional>
#include <memory>
namespace entt {
template<
typename Key, typename Type,
typename = std::hash<Key>,
typename = std::equal_to<Key>,
typename = std::allocator<std::pair<const Key, Type>>>
class dense_hash_map;
template<
typename Type,
typename = std::hash<Type>,
typename = std::equal_to<Type>,
typename = std::allocator<Type>>
class dense_hash_set;
} // namespace entt
#endif
| 19.153846
| 58
| 0.704819
|
pgruenbacher
|
5ca741fad11fb3d8ee2d4f66b22341592e24067b
| 15,004
|
cc
|
C++
|
test/src/derived_unit_tests/inductance_tests.cc
|
sthagen/cpp-si-units
|
a0332b0deab26f31955fc2a8f8ba48af2515ab14
|
[
"MIT"
] | 366
|
2019-02-09T10:10:25.000Z
|
2022-03-31T13:53:35.000Z
|
test/src/derived_unit_tests/inductance_tests.cc
|
sthagen/cpp-si-units
|
a0332b0deab26f31955fc2a8f8ba48af2515ab14
|
[
"MIT"
] | 22
|
2019-03-01T12:04:23.000Z
|
2022-02-14T06:19:43.000Z
|
test/src/derived_unit_tests/inductance_tests.cc
|
sthagen/cpp-si-units
|
a0332b0deab26f31955fc2a8f8ba48af2515ab14
|
[
"MIT"
] | 27
|
2019-03-01T07:53:38.000Z
|
2022-03-17T21:53:05.000Z
|
#include <catch2/catch.hpp>
#include <SI/electric_current.h>
#include <SI/inductance.h>
#include <SI/magnetic_flux.h>
#include <SI/stream.h>
#include <sstream>
using namespace SI::literals;
TEST_CASE("GIVEN a value WHEN constructed with literal _aH THEN result is a "
"inductance type AND ratio 1 to 10^15") {
constexpr auto one = 1_aH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::atto>>::value);
constexpr auto one_f = 1.0_aH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::atto>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _fH THEN result is a "
"inductance type AND ratio 1 to 10^15") {
constexpr auto one = 1_fH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::femto>>::value);
constexpr auto one_f = 1.0_fH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::femto>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _pH THEN result is a "
"inductance type AND ratio 1 to 10^12") {
constexpr auto one = 1_pH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::pico>>::value);
constexpr auto one_f = 1.0_pH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::pico>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _nH THEN result is a "
"inductance type AND ratio 1 to 10^9") {
constexpr auto one = 1_nH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::nano>>::value);
constexpr auto one_f = 1.0_nH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::nano>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _uH THEN result is a "
"inductance type AND ratio 1 to 10^6") {
constexpr auto one = 1_uH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::micro>>::value);
constexpr auto one_f = 1.0_uH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::micro>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _mH THEN result is a "
"inductance type AND ratio 1 to 1000") {
constexpr auto one = 1_mH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::milli>>::value);
constexpr auto one_f = 1.0_mH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::milli>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _H THEN result is a "
"inductance type AND ratio 1 to 1") {
constexpr auto one = 1_H;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::ratio<1>>>::value);
constexpr auto one_f = 1.0_H;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::ratio<1>>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _kH THEN result is a "
"inductance type AND ratio 1000 to 1") {
constexpr auto one = 1_kH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::kilo>>::value);
constexpr auto one_f = 1.0_kH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::kilo>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _MH THEN result is a "
"inductance type AND ratio 10^6 to 1") {
constexpr auto one = 1_MH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::mega>>::value);
constexpr auto one_f = 1.0_MH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::mega>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _GH THEN result is a "
"inductance type AND ratio 10^9 to 1") {
constexpr auto one = 1_GH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::giga>>::value);
constexpr auto one_f = 1.0_GH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::giga>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _TH THEN result is a "
"inductance type AND ratio 10^12 to 1") {
constexpr auto one = 1_TH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::tera>>::value);
constexpr auto one_f = 1.0_TH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::tera>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _PH THEN result is a "
"inductance type AND ratio 10^15 to 1") {
constexpr auto one = 1_PH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::peta>>::value);
constexpr auto one_f = 1.0_PH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::peta>>::value);
}
TEST_CASE("GIVEN a value WHEN constructed with literal _EH THEN result is a "
"inductance type AND ratio 10^18 to 1") {
constexpr auto one = 1_EH;
STATIC_REQUIRE(
std::is_same<decltype(one),
const SI::inductance_t<int64_t, std::exa>>::value);
constexpr auto one_f = 1.0_EH;
STATIC_REQUIRE(
std::is_same<decltype(one_f),
const SI::inductance_t<long double, std::exa>>::value);
}
TEMPLATE_TEST_CASE("GIVEN a magnetic_flux value WHEN divided by an "
"electric_current value THEN "
"result is a inductance value",
"[inductance][operator/]", int64_t, long double) {
constexpr SI::magnetic_flux_t<TestType, std::ratio<1>> magnetic_flux{1};
constexpr SI::electric_current_t<TestType, std::ratio<1>> electric_current{1};
constexpr auto result = magnetic_flux / electric_current;
STATIC_REQUIRE(
std::is_same<decltype(result),
const SI::inductance_t<TestType, std::ratio<1>>>::value);
}
TEMPLATE_TEST_CASE("GIVEN a inductance value WHEN multiplied by an "
"electric_current value "
"THEN result is a magnetic_flux value",
"[inductance][operator*]", int64_t, long double) {
constexpr SI::inductance_t<TestType, std::ratio<1>> inductance{1};
constexpr SI::electric_current_t<TestType, std::ratio<1>> electric_current{1};
constexpr auto result = inductance * electric_current;
constexpr auto result_commutative = electric_current * inductance;
STATIC_REQUIRE(
std::is_same<decltype(result), decltype(result_commutative)>::value);
STATIC_REQUIRE(
std::is_same<decltype(result),
const SI::magnetic_flux_t<TestType, std::ratio<1>>>::value);
}
TEMPLATE_TEST_CASE("GIVEN a magnetic_flux value WHEN divided by a "
"inductance value THEN "
"result is an electric_current value",
"[magnetic_flux][operator/]", int64_t, long double) {
constexpr SI::magnetic_flux_t<TestType, std::ratio<1>> magnetic_flux{1};
constexpr SI::inductance_t<TestType, std::ratio<1>> inductance{1};
constexpr auto result = magnetic_flux / inductance;
STATIC_REQUIRE(std::is_same<
decltype(result),
const SI::electric_current_t<TestType, std::ratio<1>>>::value);
}
TEST_CASE("GIVEN a 1 atto Henry WHEN passed to a streaming operator THEN "
"result is '1aH'") {
constexpr auto value = 1_aH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1aH");
}
TEST_CASE("GIVEN a 1 femto Henry WHEN passed to a streaming operator THEN "
"result is '1fH'") {
constexpr auto value = 1_fH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1fH");
}
TEST_CASE("GIVEN a 1 pico Henry WHEN passed to a streaming operator THEN "
"result is '1pH'") {
constexpr auto value = 1_pH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1pH");
}
TEST_CASE("GIVEN a 1 nano Henry WHEN passed to a streaming operator THEN "
"result is '1pH'") {
constexpr auto value = 1_nH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1nH");
}
TEST_CASE("GIVEN a 1 micro Henry WHEN passed to a streaming operator THEN "
"result is '1uH'") {
constexpr auto value = 1_uH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1uH");
}
TEST_CASE("GIVEN a 1 milli Henry WHEN passed to a streaming operator THEN "
"result is '1mH'") {
constexpr auto value = 1_mH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1mH");
}
TEST_CASE("GIVEN a 1 Henry WHEN passed to a streaming operator THEN result is "
"'1H'") {
constexpr auto value = 1_H;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1H");
}
TEST_CASE("GIVEN a 1 kilo Henry WHEN passed to a streaming operator THEN "
"result is '1kH'") {
constexpr auto value = 1_kH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1kH");
}
TEST_CASE("GIVEN a 1 mega Henry WHEN passed to a streaming operator THEN "
"result is '1MH'") {
constexpr auto value = 1_MH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1MH");
}
TEST_CASE("GIVEN a 1 giga Henry WHEN passed to a streaming operator THEN "
"result is '1GH'") {
constexpr auto value = 1_GH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1GH");
}
TEST_CASE("GIVEN a 1 tera Henry WHEN passed to a streaming operator THEN "
"result is '1TH'") {
constexpr auto value = 1_TH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1TH");
}
TEST_CASE("GIVEN a 1 exa Henry WHEN passed to a streaming operator THEN "
"result is '1EH'") {
constexpr auto value = 1_EH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1EH");
}
TEST_CASE("GIVEN a 1 peta Henry WHEN passed to a streaming operator THEN "
"result is '1PH'") {
constexpr auto value = 1_PH;
std::stringstream ss;
ss << value;
REQUIRE(ss.str() == SI::to_string(value));
REQUIRE(ss.str() == "1PH");
}
TEST_CASE("GIVEN a string of '1aH' WHEN streamed into atto_henry_t THEN result "
"is a value of 1 atto_henry_t AND stream is good") {
std::stringstream ss;
ss << "1aH";
SI::atto_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_aH);
}
TEST_CASE(
"GIVEN a string of '1fH' WHEN streamed into femto_henry_t THEN result "
"is a value of 1 femto_henry_t AND stream is good") {
std::stringstream ss;
ss << "1fH";
SI::femto_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_fH);
}
TEST_CASE("GIVEN a string of '1pH' WHEN streamed into pico_henry_t THEN result "
"is a value of 1 pico_henry_t AND stream is good") {
std::stringstream ss;
ss << "1pH";
SI::pico_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_pH);
}
TEST_CASE("GIVEN a string of '1nH' WHEN streamed into nano_henry_t THEN result "
"is a value of 1 nano_henry_t AND stream is good") {
std::stringstream ss;
ss << "1nH";
SI::nano_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_nH);
}
TEST_CASE(
"GIVEN a string of '1uH' WHEN streamed into micro_henry_t THEN result "
"is a value of 1 micro_henry_t AND stream is good") {
std::stringstream ss;
ss << "1uH";
SI::micro_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_uH);
}
TEST_CASE(
"GIVEN a string of '1mH' WHEN streamed into milli_henry_t THEN result "
"is a value of 1 milli_henry_t AND stream is good") {
std::stringstream ss;
ss << "1mH";
SI::milli_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_mH);
}
TEST_CASE("GIVEN a string of '1H' WHEN streamed into henry_t THEN result "
"is a value of 1 henry_t AND stream is good") {
std::stringstream ss;
ss << "1H";
SI::henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_H);
}
TEST_CASE("GIVEN a string of '1kH' WHEN streamed into kilo_henry_t THEN result "
"is a value of 1 kilo_henry_t AND stream is good") {
std::stringstream ss;
ss << "1kH";
SI::kilo_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_kH);
}
TEST_CASE("GIVEN a string of '1MH' WHEN streamed into mega_henry_t THEN result "
"is a value of 1 mega_henry_t AND stream is good") {
std::stringstream ss;
ss << "1MH";
SI::mega_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_MH);
}
TEST_CASE("GIVEN a string of '1GH' WHEN streamed into giga_henry_t THEN result "
"is a value of 1 giga_henry_t AND stream is good") {
std::stringstream ss;
ss << "1GH";
SI::giga_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_GH);
}
TEST_CASE("GIVEN a string of '1TH' WHEN streamed into tera_henry_t THEN result "
"is a value of 1 tera_henry_t AND stream is good") {
std::stringstream ss;
ss << "1TH";
SI::tera_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_TH);
}
TEST_CASE("GIVEN a string of '1PH' WHEN streamed into peta_henry_t THEN result "
"is a value of 1 peta_henry_t AND stream is good") {
std::stringstream ss;
ss << "1PH";
SI::peta_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_PH);
}
TEST_CASE("GIVEN a string of '1EH' WHEN streamed into exa_henry_t THEN result "
"is a value of 1 exa_henry_t AND stream is good") {
std::stringstream ss;
ss << "1EH";
SI::exa_henry_t<int64_t> value{0};
ss >> value;
REQUIRE(!ss.fail());
REQUIRE(value == 1_EH);
}
| 31.72093
| 80
| 0.640229
|
sthagen
|
5ca9418b9d86fad740b69a9d12e1020a3f255d4a
| 8,042
|
cpp
|
C++
|
src/util/navigator.cpp
|
Caprica666/vixen
|
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
|
[
"BSD-2-Clause"
] | 1
|
2019-02-13T15:39:56.000Z
|
2019-02-13T15:39:56.000Z
|
src/util/navigator.cpp
|
Caprica666/vixen
|
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
|
[
"BSD-2-Clause"
] | null | null | null |
src/util/navigator.cpp
|
Caprica666/vixen
|
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
|
[
"BSD-2-Clause"
] | 2
|
2017-11-09T12:06:41.000Z
|
2019-02-13T15:40:02.000Z
|
#include "vixen.h"
#include "vxutil.h"
namespace Vixen {
VX_IMPLEMENT_CLASSID(Navigator, MouseEngine, VX_Navigator);
VX_IMPLEMENT_CLASSID(NavRecorder, Engine, VX_NavRecorder);
Navigator::Navigator() : MouseEngine()
{
m_kForward = m_kBack = m_kLeft = m_kRight = m_kCtrl = m_kUp = m_kDown = false;
m_TurnSpeed = 0.05f;
m_LastEvent = 0;
m_Buttons = MouseEvent::LEFT;
}
#define KTD_Forward 0x26 // forward arrow
#define KTD_Back 0x28 // back arrow
#define KTD_Left 0x25 // left arrow
#define KTD_Right 0x27 // right arrow
#define KTD_Up 0x41 // A
#define KTD_Down 0x5a // Z
#define KTD_Ctrl 0x11 // control key
void Navigator::SetButtons(int mask)
{
m_Buttons = mask;
}
void Navigator::SetTurnSpeed(float s)
{
m_TurnSpeed = s;
}
bool Navigator::OnEvent(Event* event)
{
KeyEvent* ke;
NavInputEvent* ne;
switch (event->Code)
{
case Event::KEY:
ke = (KeyEvent*) event;
m_LastEvent = 0;
return OnKey(ke->KeyCode, ke->KeyFlags, 1);
case Event::NAVINPUT:
ne = (NavInputEvent*) event;
MouseFlags = ne->Buttons;
m_LastEvent = Event::NAVINPUT;
MousePos.x = ne->Pos.x;
MousePos.y = ne->Pos.y;
return true;
}
return MouseEngine::OnEvent(event);
}
void Navigator::OnMouse(const Vec2& pos, uint32 flags)
{
Scene* scene = GetMainScene();
if (!scene)
return;
Box2 sViewBox = scene->GetViewport();
float fWidth2 = sViewBox.Width() / 2.0f;
float fHeight2 = sViewBox.Height() / 2.0f;
m_LastEvent = flags ? Event::NAVINPUT : 0;
MouseFlags = flags;
MousePos.x = (pos.x - fWidth2) / fWidth2;
MousePos.y = -(pos.y - fHeight2) / fHeight2;
}
bool Navigator::OnKey(int32 key, int32 flags, int32 repeat)
{
flags &= 0xc000;
key &= ~(0x100);
switch (flags)
{
//--- key down ---
case 0x0000:
switch (key)
{
case KTD_Forward: m_kForward = true; break;
case KTD_Back: m_kBack = true; break;
case KTD_Left: m_kLeft = true; break;
case KTD_Right: m_kRight = true; break;
case KTD_Ctrl: m_kCtrl = true; break;
case KTD_Up: m_kUp = true; break;
case KTD_Down: m_kDown = true; break;
}
break;
case 0xc000:
case 0x8000:
//--- key up ---
switch (key)
{
case KTD_Forward: m_kForward = false; break;
case KTD_Back: m_kBack = false; break;
case KTD_Left: m_kLeft = false; break;
case KTD_Right: m_kRight = false; break;
case KTD_Ctrl: m_kCtrl = false; break;
case KTD_Up: m_kUp = false; break;
case KTD_Down: m_kDown = false; break;
}
break;
}
m_LastEvent = Event::KEY;
return true;
}
void Navigator::OnNavInput(NavInputEvent* e)
{
if (e->Buttons == 0)
return;
NavigateEvent* event = new NavigateEvent;
event->Time = e->Time;
event->Flags = 0;
event->Sender = this;
switch (e->Buttons & m_Buttons)
{
case MouseEvent::LEFT: // Left button: forward-backward, turn around Y
event->Pos.z = -e->Pos.y * m_Speed;
event->Rot.Set(Model::YAXIS, -e->Pos.x * m_TurnSpeed);
event->Flags |= NavigateEvent::LOCAL_POS | NavigateEvent::ROTATION | NavigateEvent::YROTATION;
break;
case MouseEvent::RIGHT: // Right button: rot left-right, look up-down
if (fabs(e->Pos.x) > fabs(e->Pos.y))
{
event->Rot.Set(Model::YAXIS, -e->Pos.x * m_TurnSpeed);
event->Flags |= NavigateEvent::ROTATION;
}
else
{
event->Look.Set(Model::XAXIS, e->Pos.y * m_TurnSpeed);
event->Flags |= NavigateEvent::LOOK;
}
break;
case MouseEvent::LEFT | MouseEvent::RIGHT: // Both buttons: up-down only
event->Pos.y = e->Pos.y * m_Speed;
event->Flags |= NavigateEvent::LOCAL_POS;
break;
}
MouseFlags = e->Buttons;
LogEvent(event);
}
/*
* If we have a valid event and should be logging events,
* log the navigate event here
*/
void Navigator::LogEvent(NavigateEvent *event)
{
event->Sender = this;
if (IsSet(SharedObj::DOEVENTS))
event->Log();
}
#define MAX_dt 1.0f
bool Navigator::Eval(float t)
{
static float last_t = 0.0;
float dt;
//--- find dt - clamp it if it gets too big - catch some other conditions
if (t == 0.0f || last_t > t)
{
last_t = t;
return false;
}
dt = t - last_t;
last_t = t;
if (dt > MAX_dt) dt = MAX_dt;
if (m_LastEvent == Event::NAVINPUT)
{
NavInputEvent* e = new NavInputEvent;
dt *= 128.0f;
e->Pos.x = MousePos.x * dt;
e->Pos.y = MousePos.y * dt;
e->Buttons = MouseFlags;
OnNavInput(e);
return true;
}
if (m_LastEvent != Event::KEY)
return false;
NavigateEvent *ne = new NavigateEvent;
if (m_kCtrl)
{
dt *= 64.0f;
//--- turning and looking ---
if (m_kForward || m_kBack)
{
if (! m_kBack)
{
//--- look down ---
Quat look(Model::XAXIS, dt * m_TurnSpeed);
ne->Look = look;
ne->Flags |= NavigateEvent::LOOK;
}
else if (! m_kForward)
{
//--- look up ---
Quat look(Model::XAXIS, -dt * m_TurnSpeed);
ne->Look = look;
ne->Flags |= NavigateEvent::LOOK;
}
}
if (m_kLeft || m_kRight)
{
if (! m_kRight)
{
//--- turn left ---
Quat turn(Model::XAXIS, dt * m_TurnSpeed);
ne->Rot = turn;
ne->Flags |= NavigateEvent::ROTATION;
}
else if (! m_kLeft)
{
//--- turn right ---
Quat turn(Model::XAXIS, -dt * m_TurnSpeed);
ne->Rot = turn;
ne->Flags |= NavigateEvent::ROTATION;
}
}
}
else
{
dt *= 128.0f;
//--- moving ---
if (m_kForward || m_kBack)
{
if (! m_kBack)
{
//--- move forward ---
ne->Pos.z = -dt * m_Speed;
ne->Flags |= NavigateEvent::LOCAL_POS;
}
else if (! m_kForward)
{
//--- move back ---
ne->Pos.z = dt * m_Speed;
ne->Flags |= NavigateEvent::LOCAL_POS;
}
}
if (m_kLeft || m_kRight)
{
if (! m_kRight)
{
//--- slide left ---
ne->Pos.x = -dt * m_Speed;
ne->Flags |= NavigateEvent::LOCAL_POS;
}
else if (! m_kLeft)
{
//--- slide right ---
ne->Pos.x = dt * m_Speed;
ne->Flags |= NavigateEvent::LOCAL_POS;
}
}
if (m_kUp || m_kDown)
{
if (! m_kDown)
{
//--- move up ---
ne->Pos.y = dt * m_Speed;
ne->Flags |= NavigateEvent::LOCAL_POS;
}
else if (! m_kUp)
{
//--- move down ---
ne->Pos.y = -dt * m_Speed;
ne->Flags |= NavigateEvent::LOCAL_POS;
}
}
}
LogEvent(ne);
return true;
}
/*!
* @fn bool NavRecorder::OnEvent(Event* e)
*
* Records navigation events (type Event::NAVIGATE) to the output stream.
* All other events are ignored. This object is the sender of the
* events and their time is relative to the first event recorded.
* This engine will not record unless it is running.
*
* @see SharedObj::OnEvent
*/
bool NavRecorder::OnEvent(Event* e)
{
NavigateEvent RecordEvent;
Messenger* mess = m_Stream;
NavigateEvent* event;
if (e->Code != Event::NAVIGATE)
return false;
event = (NavigateEvent*) e;
if (!IsRunning() || (mess == NULL)) // engine not running?
return true;
if (m_RecordTime == 0.0f) // first time thru?
{ // describe initial conditions
Model* target = (Model*)GetTarget();
if (target) // initial position, orientation
{
RecordEvent.Pos = target->GetCenter();
RecordEvent.Rot = target->GetRotation();
}
else // no target
{
RecordEvent.Pos.Set(0,0,0);
RecordEvent.Rot.Set(Vec3(0,0,0),1);
}
RecordEvent.Time = 0; // time since previous event
RecordEvent.Sender = this;
RecordEvent.Flags = NavigateEvent::ABSOLUTE | NavigateEvent::POSITION | NavigateEvent::ROTATION;
*mess << RecordEvent; // log to event stream
*mess << int32(Messenger::VIXEN_End);
return true;
}
RecordEvent = *event; // event to record
RecordEvent.Sender = this;
RecordEvent.Time = event->Time - m_RecordTime;
m_RecordTime = event->Time; // save new event time
*mess << RecordEvent; // log to event stream
*mess << int32(Messenger::VIXEN_End);
return true;
}
bool NavRecorder::OnStart()
{
m_RecordTime = 0;
GetMessenger()->Observe(this, Event::NAVIGATE, NULL);
return true;
}
bool NavRecorder::OnStop()
{
GetMessenger()->Ignore(this, Event::NAVIGATE, NULL);
return true;
}
} // end Vixen
| 22.653521
| 98
| 0.624098
|
Caprica666
|
5caeeae20745c281ad0900ab77352ccee7b88938
| 900
|
hpp
|
C++
|
src/compiler/ir_passes/construct_cssa.hpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | 10
|
2020-01-23T20:41:19.000Z
|
2021-12-28T20:24:44.000Z
|
src/compiler/ir_passes/construct_cssa.hpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | 22
|
2021-03-25T16:22:08.000Z
|
2022-03-17T12:50:38.000Z
|
src/compiler/ir_passes/construct_cssa.hpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | null | null | null |
#ifndef TIRO_COMPILER_IR_PASSES_CONSTRUCT_CSSA_HPP
#define TIRO_COMPILER_IR_PASSES_CONSTRUCT_CSSA_HPP
#include "compiler/ir/fwd.hpp"
namespace tiro::ir {
/// Ensures that the function is in CSSA form (no phi function arguments
/// with interfering lifetime).
///
/// Returns true if the cfg was modified.
///
/// References:
///
/// Sreedhar, Vugranam C., Roy Dz-Ching Ju, David M. Gillies and Vatsa Santhanam.
/// Translating Out of Static Single Assignment Form.
/// 1999
///
/// Pereira, Fernando Magno Quintão.
/// The Designing and Implementation of A SSA - based register allocator
/// 2007
// TODO: This is currently very wasteful with new variables. Should be optimized more
// by implementing the missing parts of the above papers.
bool construct_cssa(Function& func);
} // namespace tiro::ir
#endif // TIRO_COMPILER_IR_PASSES_CONSTRUCT_CSSA_HPP
| 31.034483
| 85
| 0.723333
|
mbeckem
|
5cb2afe04a1385e3bf48002caed61488d8e6606a
| 1,556
|
cc
|
C++
|
tensorflow/security/fuzzing/stringprintf_fuzz.cc
|
yage99/tensorflow
|
c7fa71b32a3635eb25596ae80d007b41007769c4
|
[
"Apache-2.0"
] | 4
|
2020-06-28T08:25:36.000Z
|
2021-08-12T12:41:34.000Z
|
tensorflow/security/fuzzing/stringprintf_fuzz.cc
|
yage99/tensorflow
|
c7fa71b32a3635eb25596ae80d007b41007769c4
|
[
"Apache-2.0"
] | 5
|
2020-07-17T17:36:44.000Z
|
2020-08-05T20:18:02.000Z
|
tensorflow/security/fuzzing/stringprintf_fuzz.cc
|
yage99/tensorflow
|
c7fa71b32a3635eb25596ae80d007b41007769c4
|
[
"Apache-2.0"
] | 4
|
2019-11-28T12:18:07.000Z
|
2021-08-01T16:12:17.000Z
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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 <fuzzer/FuzzedDataProvider.h>
#include <cstdint>
#include <cstdlib>
#include "tensorflow/core/platform/stringprintf.h"
// This is a fuzzer for tensorflow::strings::Printf
namespace {
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
FuzzedDataProvider fuzzed_data(data, size);
const char split = fuzzed_data.ConsumeIntegral<char>();
const char split_a = split & 0x07;
const char split_b = (split >> 3) & 0x07;
const std::string sa_string = fuzzed_data.ConsumeBytesAsString(split_a);
const std::string sb_string = fuzzed_data.ConsumeBytesAsString(split_b);
const std::string sc_string = fuzzed_data.ConsumeRemainingBytesAsString();
const char *sa = sa_string.c_str();
const char *sb = sb_string.c_str();
const char *sc = sc_string.c_str();
tensorflow::strings::Printf("%s %s %s", sa, sb, sc);
return 0;
}
} // namespace
| 33.826087
| 80
| 0.715938
|
yage99
|
5cb3d4ae03cc8637ad4683e5135e03d5df085949
| 6,129
|
cpp
|
C++
|
libraries/u3shell/relative_branching.cpp
|
nd-nuclear-theory/spncci
|
18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4
|
[
"MIT"
] | 1
|
2021-10-17T22:58:31.000Z
|
2021-10-17T22:58:31.000Z
|
libraries/u3shell/relative_branching.cpp
|
nd-nuclear-theory/spncci
|
18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4
|
[
"MIT"
] | 1
|
2021-02-16T03:16:31.000Z
|
2021-02-16T19:46:18.000Z
|
libraries/u3shell/relative_branching.cpp
|
nd-nuclear-theory/spncci
|
18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4
|
[
"MIT"
] | 2
|
2019-04-27T17:26:59.000Z
|
2021-04-28T17:04:07.000Z
|
/****************************************************************
relative_branching.cpp
****************************************************************/
#include "u3shell/relative_branching.h"
#include "am/wigner_gsl.h"
#include "cppformat/format.h"
extern double zero_threshold;
namespace u3shell
{
void BranchRelativeNLST(
const u3shell::RelativeRMEsU3ST& interaction_u3st,
std::unordered_map<u3shell::RelativeStateSectorNLST,double,boost::hash<u3shell::RelativeStateSectorNLST>>& rmes_nlst
)
{
std::cout<<"branching "<<std::endl;
u3::WCoefCache w_cache;
for(auto it=interaction_u3st.begin(); it!=interaction_u3st.end(); ++it)
{
// extract lables
u3shell::RelativeUnitTensorLabelsU3ST tensor;
int kappa0, L0, N, Np;
HalfInt S0, T0, Sp,Tp,S,T;
u3::SU3 x0;
std::tie(tensor,kappa0,L0)=it->first;
std::tie(x0,S0,T0,Np,Sp,Tp,N,S,T)=tensor.FlatKey();
double rme=it->second;
// branch to L and sum over SU(3) labels
MultiplicityTagged<int>::vector L0_branch=BranchingSO3(x0);
for(int Lp=Np%2; Lp<=Np; Lp+=2)
for(int L=N%2; L<=N; L+=2)
{
if(not am::AllowedTriangle(Lp,L0,L))
continue;
int n((N-L)/2);
int np((Np-Lp)/2);
u3shell::RelativeStateLabelsNLST bra_nlst(Np,Lp,Sp,Tp);
u3shell::RelativeStateLabelsNLST ket_nlst(N,L,S,T);
u3shell::RelativeStateSectorNLST sector(L0,S0,T0,bra_nlst,ket_nlst);
// double coef=u3::WCached(w_cache,u3::SU3(N,0), 1,L, x0, kappa0, L0, u3::SU3(Np,0),1,Lp,1);
rmes_nlst[sector]+=parity(n+np)*u3::WCached(w_cache,u3::SU3(N,0), 1,L, x0, kappa0, L0, u3::SU3(Np,0),1,Lp,1)*rme;
// std::cout<<fmt::format("{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} ",Np,Lp,Sp,Tp,N,L,S,T, x0, kappa0,L0,S0,T0, )
}
}
}
void BranchRelativeNLSJT(
const basis::OperatorLabelsJT& operator_labels,
int Nmax, int Jmax,
const basis::RelativeSpaceLSJT& relative_space_lsjt,
const std::unordered_map<u3shell::RelativeStateSectorNLST,double,boost::hash<u3shell::RelativeStateSectorNLST>>& rmes_nlst,
std::array<basis::RelativeSectorsLSJT,3>& isospin_component_sectors_lsjt,
std::array<basis::MatrixVector,3>& isospin_component_blocks_lsjt
)
{ // setting up J sectors
basis::ConstructZeroOperatorRelativeLSJT(
operator_labels,relative_space_lsjt,
isospin_component_sectors_lsjt,isospin_component_blocks_lsjt
);
// branch to J and populate lsjt blocks
for(auto it=rmes_nlst.begin(); it!=rmes_nlst.end(); ++it)
{
// extract labels
int L0,L,Lp,N,Np;
HalfInt S0,T0,Sp,Tp,S,T;
u3shell::RelativeStateLabelsNLST bra_nlst, ket_nlst;
std::tie(L0,S0,T0,bra_nlst,ket_nlst)=it->first;
std::tie(N,L,S,T)=ket_nlst;
std::tie(Np,Lp,Sp,Tp)=bra_nlst;
HalfInt J0=operator_labels.J0;
double rme=it->second;
// Check if N valid for given Nmax truncation
if( N>Nmax || Np>Nmax )
continue;
// Check angular momentum coupling
if(not am::AllowedTriangle(L0,S0,J0))
continue;
// Get index for block vector
int T00(T0);
// Get indices for matrix element in block
int np((Np-Lp)/2);
int n((N-L)/2);
// For Jp and J, populate corresponding block
for(HalfInt Jp=abs(Lp-Sp); Jp<=Lp+Sp; ++Jp)
for(HalfInt J=abs(L-S); J<=L+S; ++J)
{
if(J>Jmax || Jp >Jmax)
continue;
if(not am::AllowedTriangle(J,J0,Jp))
continue;
int subspace_index_bra = relative_space_lsjt.LookUpSubspaceIndex(
basis::RelativeSubspaceLSJTLabels(Lp,Sp,Jp,Tp,Lp%2)
);
int subspace_index_ket = relative_space_lsjt.LookUpSubspaceIndex(
basis::RelativeSubspaceLSJTLabels(L,S,J,T,L%2)
);
// only store canonical ordered subspaces because others obtained by symmetry
if(subspace_index_bra>subspace_index_ket)
continue;
// only store upper triangle of diagonal sectors
if((subspace_index_bra==subspace_index_ket)&&(np>n))
continue;
// Look up block index for block vector
int sector_index = isospin_component_sectors_lsjt[T00].LookUpSectorIndex(subspace_index_bra,subspace_index_ket);
auto& block=isospin_component_blocks_lsjt[T00][sector_index];
block(np,n)+=am::Unitary9J(L,S,J, L0,S0,J0, Lp,Sp,Jp)*rme;
}
}
}
void BranchRelativeRMEs(const basis::OperatorLabelsJT& operator_labels,int Nmax, int Jmax,
const u3shell::RelativeRMEsU3ST& interaction_u3st,
const basis::RelativeSpaceLSJT& relative_space_lsjt,
std::array<basis::RelativeSectorsLSJT,3>& isospin_component_sectors_lsjt,
std::array<basis::MatrixVector,3>& isospin_component_blocks_lsjt
)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// branching interaction
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::cout<<"branching LST"<<std::endl;
std::unordered_map<u3shell::RelativeStateSectorNLST,double,boost::hash<u3shell::RelativeStateSectorNLST>> rmes_nlst;
u3shell::BranchRelativeNLST( interaction_u3st,rmes_nlst);
// Generatesectors for each T0
for (int T0=operator_labels.T0_min; T0<=operator_labels.T0_max; ++T0)
isospin_component_sectors_lsjt[T0]= basis::RelativeSectorsLSJT(relative_space_lsjt,operator_labels.J0,T0,operator_labels.g0);
std::cout<<"branching LSJT "<<std::endl;
BranchRelativeNLSJT(operator_labels, Nmax, Jmax,relative_space_lsjt,rmes_nlst,
isospin_component_sectors_lsjt,isospin_component_blocks_lsjt
);
}
} // end namespace
| 37.601227
| 135
| 0.589329
|
nd-nuclear-theory
|
5cb429be3b171e7be46b1642a3a7b3584e8828c7
| 398
|
cpp
|
C++
|
sourceCode/template/sceneObjects/dummy.cpp
|
mdecourse/CoppeliaSimLib
|
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
|
[
"RSA-MD"
] | null | null | null |
sourceCode/template/sceneObjects/dummy.cpp
|
mdecourse/CoppeliaSimLib
|
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
|
[
"RSA-MD"
] | null | null | null |
sourceCode/template/sceneObjects/dummy.cpp
|
mdecourse/CoppeliaSimLib
|
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
|
[
"RSA-MD"
] | null | null | null |
#include "dummy.h"
#include "app.h"
int CDummy::cnt=0;
CDummy::CDummy()
{
cnt++;
std::string tmp("dummy created (total: ");
tmp+=std::to_string(cnt)+")";
simAddLog("Sync",sim_verbosity_debug,tmp.c_str());
}
CDummy::~CDummy()
{
cnt--;
std::string tmp("dummy destroyed (total: ");
tmp+=std::to_string(cnt)+")";
simAddLog("Sync",sim_verbosity_debug,tmp.c_str());
}
| 18.090909
| 54
| 0.610553
|
mdecourse
|
5cb857f907b589bbfea31f9fc79c3dbc46b0dcfd
| 1,006
|
hpp
|
C++
|
src/XmlNya.hpp
|
Akela1101/nya_qt
|
a305158af3a764b6856d977f4d95fa2c5649793c
|
[
"MIT"
] | null | null | null |
src/XmlNya.hpp
|
Akela1101/nya_qt
|
a305158af3a764b6856d977f4d95fa2c5649793c
|
[
"MIT"
] | null | null | null |
src/XmlNya.hpp
|
Akela1101/nya_qt
|
a305158af3a764b6856d977f4d95fa2c5649793c
|
[
"MIT"
] | null | null | null |
#ifndef XMLNYA_H
#define XMLNYA_H
/*
Usage:
while( ss.ReadNextChild() )
{
QStringRef s = ss.name();
if( s == "a1" ) a1 = ss.ReadElement().toLatin1();
else if( s == "a2" ) a2 = ss.ReadElement().toDouble();
// ...
else ss.SkipElement();
}
*/
#include <QXmlStreamReader>
#include <QHash>
typedef QXmlStreamReader::TokenType XmlType;
typedef QHash<QString, QString> AttrsType;
namespace nya
{
class XmlReader : public QXmlStreamReader
{
public:
static QString ToFormatted(char* data);
static QString ToHumanReadable(char* data);
using QXmlStreamReader::QXmlStreamReader;
bool ReadNextChild()
{
auto tt = readNext();
if (tt == TokenType::Characters) tt = readNext(); // skip '\n' and other trash
return tt == TokenType::StartElement;
}
inline QString ReadElement() { return readElementText(QXmlStreamReader::IncludeChildElements); }
inline void SkipElement() { readElementText(QXmlStreamReader::IncludeChildElements); }
AttrsType GetAttributes();
};
}
#endif // XMLNYA_H
| 21.404255
| 97
| 0.709742
|
Akela1101
|
5cb91695732aa84f8905c95a4ece0afaff29221b
| 10,181
|
cxx
|
C++
|
smtk/task/testing/cxx/TestTaskJSON.cxx
|
jcfr/SMTK
|
0069ea37f8f71a440b8f10a157b84a56ca004551
|
[
"BSD-3-Clause-Clear"
] | 40
|
2015-02-21T19:55:54.000Z
|
2022-01-06T13:13:05.000Z
|
smtk/task/testing/cxx/TestTaskJSON.cxx
|
jcfr/SMTK
|
0069ea37f8f71a440b8f10a157b84a56ca004551
|
[
"BSD-3-Clause-Clear"
] | 127
|
2015-01-15T20:55:45.000Z
|
2021-08-19T17:34:15.000Z
|
smtk/task/testing/cxx/TestTaskJSON.cxx
|
jcfr/SMTK
|
0069ea37f8f71a440b8f10a157b84a56ca004551
|
[
"BSD-3-Clause-Clear"
] | 27
|
2015-03-04T14:17:51.000Z
|
2021-12-23T01:05:42.000Z
|
//=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/ComponentItem.h"
#include "smtk/attribute/Definition.h"
#include "smtk/attribute/ReferenceItem.h"
#include "smtk/attribute/ReferenceItemDefinition.h"
#include "smtk/attribute/Registrar.h"
#include "smtk/attribute/Resource.h"
#include "smtk/attribute/operators/Signal.h"
#include "smtk/common/Managers.h"
#include "smtk/model/Registrar.h"
#include "smtk/model/Resource.h"
#include "smtk/model/Volume.h"
#include "smtk/operation/Manager.h"
#include "smtk/operation/Registrar.h"
#include "smtk/plugin/Registry.h"
#include "smtk/resource/Manager.h"
#include "smtk/resource/Registrar.h"
#include "smtk/task/FillOutAttributes.h"
#include "smtk/task/GatherResources.h"
#include "smtk/task/Instances.h"
#include "smtk/task/Manager.h"
#include "smtk/task/Registrar.h"
#include "smtk/task/Task.h"
// #include "smtk/task/GatherResources.h"
#include "smtk/task/json/jsonManager.h"
#include "smtk/task/json/jsonTask.h"
#include "smtk/common/testing/cxx/helpers.h"
namespace test_task
{
using namespace smtk::task;
} // namespace test_task
namespace
{
void printTaskStates(smtk::task::Manager::Ptr taskManager)
{
taskManager->taskInstances().visit([](const std::shared_ptr<smtk::task::Task>& task) {
std::cout << task->title() << ": " << smtk::task::stateName(task->state()) << "\n";
return smtk::common::Visit::Continue;
});
}
} // anonymous namespace
int TestTaskJSON(int, char*[])
{
using smtk::task::State;
using smtk::task::Task;
using smtk::task::WorkflowEvent;
// Create managers
auto managers = smtk::common::Managers::create();
auto attributeRegistry = smtk::plugin::addToManagers<smtk::attribute::Registrar>(managers);
auto resourceRegistry = smtk::plugin::addToManagers<smtk::resource::Registrar>(managers);
auto operationRegistry = smtk::plugin::addToManagers<smtk::operation::Registrar>(managers);
auto taskRegistry = smtk::plugin::addToManagers<smtk::task::Registrar>(managers);
auto resourceManager = managers->get<smtk::resource::Manager::Ptr>();
auto operationManager = managers->get<smtk::operation::Manager::Ptr>();
auto taskManager = managers->get<smtk::task::Manager::Ptr>();
auto attributeResourceRegistry =
smtk::plugin::addToManagers<smtk::attribute::Registrar>(resourceManager);
auto attributeOperationRegistry =
smtk::plugin::addToManagers<smtk::attribute::Registrar>(operationManager);
auto modelRegistry = smtk::plugin::addToManagers<smtk::model::Registrar>(resourceManager);
auto taskTaskRegistry = smtk::plugin::addToManagers<smtk::task::Registrar>(taskManager);
smtk::task::Instances::WorkflowObserver wfObserver =
[&](const std::set<Task*>& workflows, WorkflowEvent event, Task* subject) {
std::cout << "-- Workflow event " << static_cast<int>(event) << " subject: " << subject
<< " workflows:\n";
for (const auto& wftask : workflows)
{
std::cout << "-- head task " << wftask->title() << "\n";
}
std::cout << "--\n";
};
auto workflowObserver = taskManager->taskInstances().workflowObservers().insert(wfObserver);
auto attrib = resourceManager->create<smtk::attribute::Resource>();
auto model = resourceManager->create<smtk::model::Resource>();
attrib->setName("simulation");
model->setName("geometry");
attrib->properties().get<std::string>()["project_role"] = "simulation attribute";
model->properties().get<std::string>()["project_role"] = "model geometry";
auto attribUUIDStr = attrib->id().toString();
auto modelUUIDStr = model->id().toString();
std::string configString = R"({
"tasks": [
{
"id": 1,
"type": "smtk::task::GatherResources",
"title": "Load a model and attribute",
"style": [ "foo", "bar", "baz" ],
"state": "completed",
"auto-configure": true,
"resources": [
{
"role": "model geometry",
"type": "smtk::model::Resource",
"max": 2
},
{
"role": "simulation attribute",
"type": "smtk::attribute::Resource"
}
]
},
{
"id": 2,
"type": "smtk::task::FillOutAttributes",
"title": "Mark up model",
"state": "incomplete",
"dependencies": [ 1 ],
"attribute-sets": [
{
"role": "simulation attribute",
"definitions": [
"Material",
"BoundaryCondition"
]
}
]
}
],
"//": [
"For each dependency, we can store configuration information",
"for the object used to adapt one task's output into",
"configuration information for its dependent task. If no",
"configuration is present for a dependency, we use the",
"'Ignore' adaptor as a default – which never modifies the",
"depedent task's configuration."
],
"adaptors": [
{
"id": 1,
"type": "smtk::task::adaptor::ResourceAndRole",
"from": 1,
"to": 2
}
],
"styles": {
"foo": { },
"bar": { },
"baz": { }
}
}
)";
auto config = nlohmann::json::parse(configString);
std::cout << config.dump(2) << "\n";
taskManager->taskInstances().pauseWorkflowNotifications(true);
bool ok = smtk::task::json::jsonManager::deserialize(managers, config);
taskManager->taskInstances().pauseWorkflowNotifications(false);
test(ok, "Failed to parse configuration.");
test(taskManager->taskInstances().size() == 2, "Expected to deserialize 2 tasks.");
smtk::task::GatherResources::Ptr gatherResources;
smtk::task::FillOutAttributes::Ptr fillOutAttributes;
taskManager->taskInstances().visit(
[&gatherResources, &fillOutAttributes](const smtk::task::Task::Ptr& task) {
if (!gatherResources)
{
gatherResources = std::dynamic_pointer_cast<smtk::task::GatherResources>(task);
}
if (!fillOutAttributes)
{
fillOutAttributes = std::dynamic_pointer_cast<smtk::task::FillOutAttributes>(task);
}
return smtk::common::Visit::Continue;
});
// Test that styles are properly deserialized.
test(fillOutAttributes->style().empty(), "Expected no style for fillOutAttributes.");
test(gatherResources->style().size() == 3, "Expected 3 style class-names for gatherResources.");
// Add components and signal to test FillOutAttributes.
// First, the FillOutAttributes task is irrelevant
printTaskStates(taskManager);
gatherResources->markCompleted(true);
printTaskStates(taskManager);
auto volume1 = model->addVolume();
auto volume2 = model->addVolume();
auto def = attrib->createDefinition("Material");
auto assoc = def->createLocalAssociationRule();
assoc->setAcceptsEntries("smtk::model::Resource", "volume", true);
assoc->setNumberOfRequiredValues(1);
assoc->setIsExtensible(true);
auto material1 = attrib->createAttribute("CarbonFiber", "Material");
// Signal the change
auto signal = operationManager->create<smtk::attribute::Signal>();
signal->parameters()->findComponent("created")->appendValue(material1);
auto result = signal->operate();
std::cout << "Signaled after adding a material\n";
// Now, the FillOutAttributes task is incomplete
printTaskStates(taskManager);
material1->associate(volume1.component());
signal->parameters()->findComponent("created")->setNumberOfValues(0);
signal->parameters()->findComponent("modified")->appendValue(material1);
result = signal->operate();
std::cout << "Signaled after associating to the material\n";
// Finally, the FillOutAttributes task is completable
printTaskStates(taskManager);
std::string configString2;
{
// Round trip it.
nlohmann::json config2;
ok = smtk::task::json::jsonManager::serialize(managers, config2);
test(ok, "Failed to serialize task manager.");
configString2 = config2.dump(2);
std::cout << configString2 << "\n";
}
{
// TODO: Round trip a second time so we should be guaranteed to have
// two machine-(not-hand-)generated strings to compare.
auto managers2 = smtk::common::Managers::create();
managers2->insert(resourceManager);
managers2->insert(operationManager);
auto taskManager2 = smtk::task::Manager::create();
smtk::task::Registrar::registerTo(taskManager2);
managers2->insert(taskManager2);
auto config3 = nlohmann::json::parse(configString2);
ok = smtk::task::json::jsonManager::deserialize(managers2, config3);
test(ok, "Failed to parse second configuration.");
test(taskManager2->taskInstances().size() == 2, "Expected to deserialize 2 tasks.");
// Test that styles are properly round-tripped.
smtk::task::GatherResources::Ptr gatherResources2;
smtk::task::FillOutAttributes::Ptr fillOutAttributes2;
taskManager->taskInstances().visit(
[&gatherResources2, &fillOutAttributes2](const smtk::task::Task::Ptr& task) {
if (!gatherResources2)
{
gatherResources2 = std::dynamic_pointer_cast<smtk::task::GatherResources>(task);
}
if (!fillOutAttributes2)
{
fillOutAttributes2 = std::dynamic_pointer_cast<smtk::task::FillOutAttributes>(task);
}
return smtk::common::Visit::Continue;
});
test(fillOutAttributes2->style().empty(), "Expected no style for fillOutAttributes2.");
test(
gatherResources2->style().size() == 3, "Expected 3 style class-names for gatherResources2.");
nlohmann::json config4;
ok = smtk::task::json::jsonManager::serialize(managers2, config4);
test(ok, "Failed to serialize second manager.");
std::string configString3 = config4.dump(2);
std::cout << "----\n" << configString3 << "\n";
// test(configString2 == configString3, "Failed to match strings.");
}
return 0;
}
| 36.622302
| 99
| 0.663982
|
jcfr
|
5cba5821036a75b51b930ef28ed3d58167ff16a5
| 3,802
|
cpp
|
C++
|
volume_II/acm_1103.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
volume_II/acm_1103.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
volume_II/acm_1103.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
/* acm.timus.ru 1103. Pencils and Circles
*
* Strategy:
* Pick two points on the convex hull of the point set. If we form a circle with some other point,
* the largest such circle will encompass all points, the second largest will encompass all points
* except for one, etc. The angle formed by the two static points and the third that we pick will
* be inversely proportional to the radius of the circle that they form (the specific location of
* the third point on the circle does not affect the angle), so we find the median biggest angle
* out of all angles that we can form accordingly, and use the points constituting that circle as
* the answer.
*
* Performance:
* O(n), runs the test suite in 0.001s using 448KB memory.
*/
#include <cstdio>
#include <cmath>
#include <algorithm>
struct point
{
int x;
int y;
};
typedef point vector;
vector operator - (point a, point b)
{
vector result = {a.x - b.x, a.y - b.y };
return result;
}
point operator + (point a, vector v)
{
point result = {a.x + v.x, a.y + v.y };
return result;
}
point operator * (point a, int k)
{
point result = {a.x * k, a.y * k };
return result;
}
long long operator * (vector a, vector b)
{
return a.x * 1ll * b.x + a.y * 1ll * b.y;
}
long long operator ^ (vector a, vector b)
{
return a.x * 1ll * b.y - a.y * 1ll * b.x;
}
struct cmp_point
{
bool operator()(point a, point b)const
{
return ( a.x < b.x ) || ( a.x == b.x && a.y < b.y ) ;
}
};
double dist(vector v)
{
return sqrt( v * v + 0.0);
}
struct scanner
{
char const* o;
char in[131072];
void init()
{
o = in;
in[fread(in,1,sizeof(in),stdin)] = 0;
}
int readInt()
{
unsigned u = 0, s = 0;
while(*o && *o <= 32)++o;
if (*o == '-') s= ~0u, ++o; else if (*o == '+')++o;
while(*o>='0') u = (u << 3) + (u << 1) + (*o++ - '0');
return (u ^ s) + !!s;
}
} sc ;
int n;
point p[ 5000 + 8 ];
struct angle
{
double cos_;
int i;
}angles[5000 + 8];
struct cmp_angle
{
// angle > 0 angle < 180
// cos(angle) = -1 .. +1
//
bool operator ()(angle a, angle b)const{ return a.cos_ > b.cos_ ; }
};
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
//I. readData.
// ---------------------------------------------------------------
sc.init();
n = sc.readInt();
for(int i= 0; i != n; ++i)
{
p[i].x = sc.readInt();
p[i].y = sc.readInt();
}
// -----------------------------------------------------------------
// II. find first point: minimum element.
// swap minimum with first point
{
point * pm = std::min_element(p, p + n, cmp_point());
std::swap( *pm, p[ 0 ] ) ;
}
point pa = p[ 0 ];
for(int i = 0; i < n ;++i)
p[ i ] = p[ i ] - pa;
// III. find second point: most right point than pa.
for(int i = 2; i < n; ++i)
{
if ( ( p[ i ] ^ p[ 1 ] ) >= 0 )
std::swap( p[ i ], p[ 1 ] );
}
point pb = p[ 1 ] ;
for(int i = 0; i < n - 2; ++i)
{
angles[i].i = 2 + i;
vector v = p[ i + 2 ];
vector u = p[ i + 2 ] - pb;
angles[i].cos_ = ( v * u ) / dist( u ) / dist( v );
}
std::nth_element(angles, angles + ( n - 2 ) / 2, angles + (n-2), cmp_angle() );
point pc = p[ angles[( n - 2 ) / 2 ].i ] ;
{
point ra = pa;
point rb = pb + pa;
point rc = pc + pa;
printf("%d %d\n", ra.x, ra.y ) ;
printf("%d %d\n", rb.x, rb.y ) ;
printf("%d %d\n", rc.x, rc.y ) ;
}
}
| 21.480226
| 98
| 0.477117
|
raidenluikang
|
5cc12a461f6665742765d93cfcce70a8df291a5f
| 17,569
|
hpp
|
C++
|
delaunay.hpp
|
GoldFeniks/delaunay
|
a96621d28a57bd6c73fbecf0ae5347714a3ed07e
|
[
"MIT"
] | null | null | null |
delaunay.hpp
|
GoldFeniks/delaunay
|
a96621d28a57bd6c73fbecf0ae5347714a3ed07e
|
[
"MIT"
] | 1
|
2021-01-31T11:20:44.000Z
|
2021-02-01T00:16:53.000Z
|
delaunay.hpp
|
GoldFeniks/delaunay
|
a96621d28a57bd6c73fbecf0ae5347714a3ed07e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <list>
#include <tuple>
#include <cmath>
#include <limits>
#include <vector>
#include <cstddef>
#include <utility>
#include <algorithm>
template<typename T>
class delaunay_triangulation {
private:
class edge;
class point;
class triangle;
template<typename V>
class data_value_wrapper;
public:
delaunay_triangulation() : _first_triangle(&_triangles, 0) {}
template<typename VX, typename VY>
delaunay_triangulation(const VX& x, const VY& y) : _first_triangle(&_triangles, 0) {
if (x.size() < 3)
throw std::runtime_error("At least 3 points are required for triangulation");
if (x.size() != y.size())
throw std::runtime_error("The number of x and y coordinates must match");
_points.reserve(x.size());
for (size_t i = 0; i < x.size(); ++i)
_points.emplace_back(x[i], y[i]);
triangulate();
}
delaunay_triangulation(const delaunay_triangulation& other) : _first_triangle(&_triangles, 0) {
*this = other;
}
delaunay_triangulation(delaunay_triangulation&& other) : _first_triangle(&_triangles, 0) {
*this = std::move(other);
}
auto& operator=(const delaunay_triangulation& other) {
_edges = other._edges;
_points = other._points;
_triangles = other._triangles;
_reassign_data();
return *this;
}
auto& operator=(delaunay_triangulation&& other) noexcept {
_edges = std::move(other._edges);
_points = std::move(other._points);
_triangles = std::move(other._triangles);
_reassign_data();
return *this;
}
const auto& edges() const {
return _edges;
}
const auto& points() const {
return _points;
}
const auto& triangles() const {
return _triangles;
}
const auto find_triangle(const T& x, const T& y) const {
return find_triangle({x, y});
}
const auto find_triangle(const point& p) const {
return find_triangle(_first_triangle, p);
}
const auto find_triangle(const data_value_wrapper<triangle>& t, const T& x, const T& y) const {
return find_triangle(t, {x, y});
}
const auto find_triangle(const data_value_wrapper<triangle>& t, const point& p) const {
return _find_triangle(t, p);
}
private:
const data_value_wrapper<triangle> _first_triangle;
std::vector<edge> _edges;
std::vector<point> _points;
std::vector<triangle> _triangles;
void _reassign_data() {
for (auto& it : _edges) {
it.a._data = &_points;
it.b._data = &_points;
it.t1._data = &_triangles;
if (it.t2.is_valid())
it.t2._data = &_triangles;
}
for (auto& it : _triangles) {
it.a._data = &_edges;
it.b._data = &_edges;
it.c._data = &_edges;
}
}
static constexpr auto eps = T(1e-8);
template<typename V>
class data_value_wrapper {
public:
data_value_wrapper() = default;
data_value_wrapper(std::vector<V>* data, const int64_t index) : _data(data), _index(index) {}
bool operator==(const data_value_wrapper<V>& other) const {
return _index == other._index;
}
bool operator!=(const data_value_wrapper<V>& other) const {
return !(*this == other);
}
bool is_valid() const {
return _data != nullptr;
}
const auto& get() const {
return (*_data)[_index];
}
auto& get() {
return (*_data)[_index];
}
const auto& index() const {
return _index;
}
private:
int64_t _index = -1;
std::vector<V>* _data = nullptr;
friend class delaunay_triangulation;
};
struct point {
T x, y;
point() = default;
point(T x, T y) : x(std::move(x)), y(std::move(y)) {}
};
struct edge {
data_value_wrapper<point> a, b;
data_value_wrapper<triangle> t1, t2;
edge(data_value_wrapper<point> a, data_value_wrapper<point> b) : a(std::move(a)), b(std::move(b)) {}
void flip() {
std::swap(a, b);
}
};
class triangle {
public:
data_value_wrapper<edge> a, b, c;
triangle(data_value_wrapper<edge> a, data_value_wrapper<edge> b, data_value_wrapper<edge> c) :
a(std::move(a)), b(std::move(b)), c(std::move(c)) {}
void rearrange(const data_value_wrapper<edge>& e) {
if (e == b)
std::swap(a, b);
else if (e == c)
std::swap(a, c);
_flip_edges(e.get().b, b, c);
}
auto barycentric_coordinates(const point& p) const {
const auto& [a, b, c] = get_points();
const auto v0x = a.x - c.x;
const auto v0y = a.y - c.y;
const auto v1x = b.x - c.x;
const auto v1y = b.y - c.y;
const auto v2x = p.x - c.x;
const auto v2y = p.y - c.y;
const auto den = T(1) / (v1y * v0x - v1x * v0y);
const auto v = (v1y * v2x - v1x * v2y) * den;
const auto w = (v0x * v2y - v0y * v2x) * den;
return std::make_tuple(v, w, T(1) - v - w);
}
auto points() const {
const auto& p0 = a.get().a;
const auto& p1 = a.get().b;
const auto& p2 = b.get().a;
if (p0 != p2 && p1 != p2)
return std::tie(p0, p1, p2);
return std::tie(p0, p1, b.get().b);
}
auto get_points() const {
const auto& [a, b, c] = points();
return std::tie(a.get(), b.get(), c.get());
}
bool contains_point(const point& p) const {
const auto& [a, b, c] = get_points();
const auto d1 = _sign(p, a, b);
const auto d2 = _sign(p, b, c);
const auto d3 = _sign(p, c, a);
const auto neg = (d1 < -eps) || (d2 < -eps) || (d3 < -eps);
const auto pos = (d1 > eps) || (d2 > eps) || (d3 > eps);
return !(neg && pos);
}
private:
static void _flip_edges(const data_value_wrapper<point>& p, data_value_wrapper<edge>& a, data_value_wrapper<edge>& b) {
auto& ag = a.get();
auto& bg = b.get();
if (p == ag.b)
ag.flip();
else if (p == bg.a)
std::swap(a, b);
else if (p == bg.b) {
bg.flip();
std::swap(a, b);
}
if (a.get().b != b.get().a)
b.get().flip();
}
static auto _sign(const point& a, const point& b, const point& c) {
return (a.x - c.x) * (b.y - c.y) - (b.x - c.x) * (a.y - c.y);
}
};
void triangulate() {
const auto p0 = data_value_wrapper(&_points, 0);
const auto& p0g = p0.get();
std::vector<std::pair<T, data_value_wrapper<point>>> points;
points.reserve(_points.size() - 1);
for (size_t i = 0; i < _points.size() - 1; ++i)
points.emplace_back(_norm(p0g, _points[i + 1]), data_value_wrapper(&_points, i + 1));
std::sort(points.begin(), points.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
auto p1 = points[0].second;
const auto& p1g = p1.get();
auto p2 = points[1].second;
size_t di = 1;
auto [r, c] = _circle_center(p0g, p1g, p2.get());
for (size_t i = 2; i < points.size(); ++i) {
const auto [cr, cc] = _circle_center(p0g, p1g, points[i].second.get());
if (cr < r) {
r = cr;
c = cc;
p2 = points[i].second;
di = i;
}
}
points.erase(points.begin() + di);
if (_is_clockwise(p0g, p1g, p2.get()))
std::swap(p1, p2);
for (size_t i = 1; i < points.size(); ++i)
points[i].first = _norm(c, points[i].second.get());
std::sort(points.begin() + 1, points.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
auto e0 = _add_edge(p0, p1);
auto e1 = _add_edge(p1, p2);
auto e2 = _add_edge(p2, p0);
_add_triangle(e0, e1, e2);
std::list<data_value_wrapper<edge>> hull;
hull.push_back(e0);
hull.push_back(e1);
hull.push_back(e2);
for (size_t i = 1; i < points.size(); ++i) {
const auto& p = points[i].second;
auto& e = hull.front();
const auto buff = !_is_clockwise(e.get().a.get(), e.get().b.get(), p.get());
auto a = _find_first(++hull.begin(), p.get(), buff);
auto b = _find_first(hull.rbegin(), p.get(), buff).base();
if (!buff) {
if (b == hull.end()) {
auto t = _add_triangle(hull.front(), p);
e0 = t.get().a;
e1 = t.get().b;
_add_triangles(e1, ++hull.begin(), a);
} else {
auto t = _add_triangle(*b, p);
e0 = t.get().a;
e1 = t.get().b;
auto d = b;
_add_triangles(e1, ++d, hull.end());
_add_triangles(e1, hull.begin(), a);
hull.erase(b, hull.end());
}
a = hull.erase(hull.begin(), a);
} else {
auto t = _add_triangle(*a, p);
e0 = t.get().a;
e1 = t.get().b;
auto d = a;
_add_triangles(e1, ++d, b);
a = hull.erase(a, b);
}
hull.insert(a, {e0, e1});
}
_flip_triangles();
}
static auto _norm(const point& a, const point& b) {
return std::pow(a.x - b.x, 2) + std::pow(a.y - b.y, 2);
}
static auto _circle_center(const point& a, const point& b, const point& c) {
const auto& [x0, y0] = a;
const auto& [x1, y1] = b;
const auto& [x2, y2] = c;
if (std::abs((y0 - y1) * (x0 - x2) - (y0 - y2) * (x0 - x1)) < eps)
return std::make_tuple(std::numeric_limits<T>::infinity(), point(0, 0));
const auto y01 = y0 - y1;
const auto y02 = y0 - y2;
const auto y12 = y1 - y2;
const auto sx0 = std::pow(x0, 2);
const auto sx1 = std::pow(x1, 2);
const auto sx2 = std::pow(x2, 2);
const auto sy0 = std::pow(y0, 2);
const auto sy1 = std::pow(y1, 2);
const auto sy2 = std::pow(y2, 2);
const auto x = (sx2 * -y01 + sx1 * y02 - (sx0 + y01 * y02) * y12) / (T(2) * (x2 * -y01 + x1 * y02 + x0 * -y12));
const auto y = (-sx1 * x2 + sx0 * (x2 - x1) + x2 * y01 * (y0 + y1) + x0 * (sx1 - sx2 + sy1 - sy2) + x1 * (sx2 - sy0 + sy2)) /
(T(2) * (x2 * y01 + x0 * y12 + x1 * -y02));
const auto p = point(x, y);
return std::make_tuple(_norm(a, p), p);
}
static auto _is_clockwise(const point& a, const point& b, const point& c) {
const auto& [x0, y0] = a;
const auto& [x1, y1] = b;
const auto& [x2, y2] = c;
return x0 * (y1 - y2) + x1 * (y2 - y0) + x2 * (y0 - y1) < -eps;
}
auto _add_edge(const data_value_wrapper<point>& a, const data_value_wrapper<point>& b) {
_edges.emplace_back(a, b);
return data_value_wrapper(&_edges, _edges.size() - 1);
}
auto _add_triangle(data_value_wrapper<edge>& a, data_value_wrapper<edge>& b, data_value_wrapper<edge>& c) {
_triangles.emplace_back(a, b, c);
auto res = data_value_wrapper(&_triangles, _triangles.size() - 1);
a.get().t1 = res;
b.get().t1 = res;
c.get().t1 = res;
return res;
}
auto _add_triangle(data_value_wrapper<edge>& c, const data_value_wrapper<point>& p) {
auto a = _add_edge(c.get().a, p);
auto b = _add_edge(p, c.get().b);
c.get().flip();
_triangles.emplace_back(a, b, c);
auto res = data_value_wrapper(&_triangles, _triangles.size() - 1);
a.get().t1 = res;
b.get().t1 = res;
c.get().t2 = res;
return res;
}
auto _add_triangle(data_value_wrapper<edge>& a, data_value_wrapper<edge>& c) {
auto b = _add_edge(a.get().a, c.get().b);
c.get().flip();
_triangles.emplace_back(a, b, c);
auto res = data_value_wrapper(&_triangles, _triangles.size() - 1);
a.get().t2 = res;
b.get().t1 = res;
c.get().t2 = res;
return res;
}
template<typename It>
static auto _find_first(It it, const point& p, const bool val) {
while (true) {
const auto& e = it->get();
if (_is_clockwise(e.a.get(), e.b.get(), p) == val)
break;
++it;
}
return it;
}
template<typename It>
void _add_triangles(data_value_wrapper<edge>& e, It it, const It end) {
while (it != end) {
auto t = _add_triangle(e, *it);
e = t.get().b;
++it;
}
}
auto _flip_triangles() {
std::vector<data_value_wrapper<edge>> edges;
edges.reserve(_edges.size());
for (size_t i = 0; i < _edges.size(); ++i)
if (_edges[i].t2.is_valid())
edges.emplace_back(data_value_wrapper(&_edges, i));
bool do_flip = true;
while (do_flip) {
do_flip = false;
for (auto& it : edges)
do_flip |= _flip_triangles_over_edge(it);
}
}
static bool _flip_triangles_over_edge(data_value_wrapper<edge>& e) {
auto& eg = e.get();
auto& t1 = eg.t1.get();
auto& t2 = eg.t2.get();
t1.rearrange(e);
t2.rearrange(e);
if (_should_flip(t1.b.get().b, eg.b, eg.a, t2.b.get().b)) {
e.get().a = t2.b.get().b;
e.get().b = t1.b.get().b;
std::swap(t1.b, t2.c);
_reassign_triangle(t1.b, eg.t2, eg.t1);
_reassign_triangle(t2.c, eg.t1, eg.t2);
return true;
}
return false;
}
static void _reassign_triangle(data_value_wrapper<edge>& e, data_value_wrapper<triangle>& t1, data_value_wrapper<triangle>& t2) {
if (e.get().t1 == t1)
e.get().t1 = t2;
else
e.get().t2 = t2;
}
static bool _should_flip(const data_value_wrapper<point>& a, const data_value_wrapper<point>& b,
const data_value_wrapper<point>& c, const data_value_wrapper<point>& d) {
const auto& [xa, ya] = a.get();
const auto& [xb, yb] = b.get();
const auto& [xc, yc] = c.get();
const auto& [xd, yd] = d.get();
const auto xba = xb - xa;
const auto yba = yb - ya;
const auto xca = xc - xa;
const auto yca = yc - ya;
const auto xbd = xb - xd;
const auto ybd = yb - yd;
const auto xcd = xc - xd;
const auto ycd = yc - yd;
const auto cosa = xba * xca + yba * yca;
const auto cosb = xbd * xcd + ybd * ycd;
if (cosa < -eps && cosb < -eps)
return true;
if (cosa > eps && cosb > eps)
return false;
const auto sina = std::abs(xba * yca - yba * xca);
const auto sinb = std::abs(xbd * ycd - ybd * xcd);
if (cosa * sinb + sina * cosb < -eps)
return true;
return false;
}
static auto _find_triangle(const data_value_wrapper<triangle>& wt, const point& p) {
const auto& t = wt.get();
if (t.contains_point(p))
return wt;
const auto& rp = t.a.get().a;
point cp;
if (rp == t.b.get().a || rp == t.b.get().b)
cp = _half_way_point(rp.get(), t.c.get());
else
cp = _half_way_point(rp.get(), t.b.get());
if (_does_intersect(cp, p, t.a.get()))
return _find_triangle(t.a.get(), wt, p);
if (_does_intersect(cp, p, t.b.get()))
return _find_triangle(t.b.get(), wt, p);
return _find_triangle(t.c.get(), wt, p);
}
static auto _find_triangle(const edge& e, const data_value_wrapper<triangle>& wt, const point& p) {
if (e.t2.is_valid()) {
if (wt == e.t1)
return _find_triangle(e.t2, p);
return _find_triangle(e.t1, p);
}
return wt;
}
static auto _half_way_point(const point& p, const edge& e) {
const auto& a = e.a.get();
const auto& b = e.b.get();
const auto x = (b.x + a.x) / T(2);
const auto y = (b.y + a.y) / T(2);
return point((x + p.x) / T(2), (y + p.y) / T(2));
}
static bool _does_intersect(const point& a, const point& b, const edge& ed) {
const auto& [ax, ay] = a;
const auto& [bx, by] = b;
const auto& [cx, cy] = ed.a.get();
const auto& [dx, dy] = ed.b.get();
const auto e = _det(bx - ax, by - ay, dx - cx, dy - cy);
if (std::abs(e) < eps)
return false;
const auto f = _det(dy - cy, dx - cx, cy - ay, cx - ax) / e;
const auto g = _det(by - ay, bx - ax, cy - ay, cx - ax) / e;
return f > -eps && f < T(1) + eps && g > -eps && g < T(1) + eps;
}
static auto _det(const T& a, const T& b, const T& c, const T& d) {
return a * d - b * c;
}
};
| 31.655856
| 133
| 0.499516
|
GoldFeniks
|
5cc1cf304df5d0e0ab2a5b795ba88053dd55eb2e
| 881
|
cpp
|
C++
|
src/Renderer/FE_GPU_Info.cpp
|
antsouchlos/OxygenEngine
|
11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48
|
[
"MIT"
] | null | null | null |
src/Renderer/FE_GPU_Info.cpp
|
antsouchlos/OxygenEngine
|
11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48
|
[
"MIT"
] | null | null | null |
src/Renderer/FE_GPU_Info.cpp
|
antsouchlos/OxygenEngine
|
11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48
|
[
"MIT"
] | null | null | null |
#include "FE_GPU_Info.h"
FE_GPU_Info::FE_GPU_Info()
{
//ctor
}
FE_GPU_Info::~FE_GPU_Info()
{
//dtor
}
// find GPU objects by name easily
size_t FE_GPU_Info::findVBO(string a_name){
//cout << vbos.size() << endl;
for(size_t x =0; x < vbos.size(); x++)
if(vbos[x].name == a_name){
return x;
}
return vbos.size();
}
size_t FE_GPU_Info::findVAO(string a_name){
for(size_t x =0; x < vaos.size(); x++)
if(vaos[x].name == a_name){
return x;
}
return vaos.size();
}
size_t FE_GPU_Info::findProgram(string a_name){
for(size_t x =0; x < programs.size(); x++)
if(programs[x].name == a_name){
return x;
}
return programs.size();
}
size_t FE_GPU_Info::findUniform(string a_name){
for(size_t x =0; x < ubos.size(); x++)
if(ubos[x].name == a_name){
return x;
}
return ubos.size();
}
| 19.577778
| 47
| 0.582293
|
antsouchlos
|
5cc5db16ce60312d7f6ae4895481330439fce15c
| 6,643
|
hpp
|
C++
|
nn_runtime/nnrt/permute_vector.hpp
|
phytec-mirrors/nn-imx
|
58525bf968e8d90004f6d782ad37cea28991a439
|
[
"MIT"
] | null | null | null |
nn_runtime/nnrt/permute_vector.hpp
|
phytec-mirrors/nn-imx
|
58525bf968e8d90004f6d782ad37cea28991a439
|
[
"MIT"
] | null | null | null |
nn_runtime/nnrt/permute_vector.hpp
|
phytec-mirrors/nn-imx
|
58525bf968e8d90004f6d782ad37cea28991a439
|
[
"MIT"
] | null | null | null |
/****************************************************************************
*
* Copyright (c) 2020 Vivante Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef __PERMUTE_VECTOR__
#define __PERMUTE_VECTOR__
#include <array>
#include <vector>
#include <cassert>
#include "types.hpp"
namespace nnrt {
namespace layout_inference {
class IPermuteVector;
using IPermuteVectorPtr = std::shared_ptr<IPermuteVector>;
class IPermuteVector {
public:
virtual ~IPermuteVector() = default;
virtual uint32_t rank() const = 0;
virtual const uint32_t& at(const uint32_t) const = 0;
virtual uint32_t& at(const uint32_t) = 0;
/**
* @brief get reverse permute vector
*
* PermuteVector + PermuteVector.reverse() = {0, 1, 2...R}
*
* Data layout = NHWC, current Permute = 0, 3, 1, 2, output layout = NCHW
* its reverse layout is 0, 2, 3, 1
*
* @return PermuteVector<R> reverse permute vector have same rank as current permute
*/
virtual IPermuteVectorPtr reverse() = 0;
virtual std::string asText() const = 0;
/**
* @brief apply addtional permute parameter
*
* @detail
* assume data stored as NHWC, this->param_ = {0, 3, 1, 2}
* if apply current permute vector, data stored as NCHW
* other->param_ = {0, 2, 1, 3}
* if apply the addtion permute, data stored as NHCW, current permute paramter become {0, 1,
* 3, 2}
*
* @param other addtional permute vector
* @return PermuteVector result = data.apply_this_permute().apply_other_permute()
*/
virtual IPermuteVectorPtr add(const IPermuteVectorPtr& other) const = 0;
virtual void reinitialize() = 0;
virtual bool isAligned() const = 0 ;
virtual std::vector<uint32_t> asStdVec() const = 0;
};
template <uint32_t R>
class PermuteVector : public IPermuteVector {
public:
static constexpr uint32_t MAX_RANK = 10;
PermuteVector() {
for (uint32_t i = 0; i < R; ++i) {
param_[i] = i;
}
}
// Copy Constructor
PermuteVector(const PermuteVector& other): param_(other.param_) {
}
// Move Constructor
PermuteVector(PermuteVector&& other): param_(std::move(other.param_)) {
}
// Initialize list
PermuteVector(std::initializer_list<uint32_t> init_list) {
std::vector<uint32_t> vec(init_list);
assert(vec.size() == R);
for(uint32_t i = 0; i < R; ++i) {
param_[i] = vec[i];
}
}
template <uint32_t S>
explicit PermuteVector(const PermuteVector<S>& smaller) {
// With this: you can construct a PermuteVector with larger Rank from a smaller rank permute
static_assert(S < R, "Cut Permute Vector is not allowed");
for (auto i = 0; i < R; ++i) {
param_[i] = i < S ? smaller[i] : i;
}
}
virtual const uint32_t& at(uint32_t idx) const override { return param_[idx]; }
virtual uint32_t& at(uint32_t idx) override { return param_[idx]; }
virtual uint32_t rank() const override { return R; }
virtual bool isAligned() const override {
uint32_t i = 0;
for (; i < R; ++i) {
if (i != param_[i]) break;
}
return i == R;
}
IPermuteVectorPtr reverse() override {
IPermuteVectorPtr r = std::make_shared<PermuteVector<R>>();
for (uint32_t i = 0; i < R; ++i) {
r->at(param_[i]) = i;
}
return r;
}
void reinitialize() override {
for (uint32_t i = 0; i < R; ++i) {
param_[i] = i;
}
}
virtual IPermuteVectorPtr add(const IPermuteVectorPtr& other) const override {
IPermuteVectorPtr r = std::make_shared<PermuteVector<R>>();
for (uint32_t i = 0; i < other->rank(); ++i){
r->at(i) = param_[other->at(i)];
}
return r;
}
virtual std::string asText() const override {
std::string str(R + 1, '\0');
for (uint32_t i = 0; i < R; i++) {
str[i] = (char(param_[i]));
}
// str[R] = '\0';
return str;
}
virtual std::vector<uint32_t> asStdVec() const override {
std::vector<uint32_t> data(R);
for (uint32_t i(0); i < R; ++i) {
data[i] = param_[i];
}
// return std::move(data);
return data;
}
private:
std::array<uint32_t, R> param_;
};
using PermuteVector1 = PermuteVector<1>;
/**
* @brief
*
* @param rankVal
* @return IPermuteVectorPtr
*/
inline IPermuteVectorPtr make_shared(uint32_t rankVal) {
switch (rankVal) {
// 0: represent scalar
case 0:
case 1:
return std::make_shared<PermuteVector<1>>();
case 2:
return std::make_shared<PermuteVector<2>>();
case 3:
return std::make_shared<PermuteVector<3>>();
case 4:
return std::make_shared<PermuteVector<4>>();
case 5:
return std::make_shared<PermuteVector<5>>();
case 6:
return std::make_shared<PermuteVector<6>>();
case 7:
return std::make_shared<PermuteVector<7>>();
case 8:
return std::make_shared<PermuteVector<8>>();
case 9:
return std::make_shared<PermuteVector<9>>();
case 10:
return std::make_shared<PermuteVector<10>>();
default:
assert("Not supported rankVal");
return nullptr;
}
}
}
}
#endif
| 30.195455
| 100
| 0.592353
|
phytec-mirrors
|
5cc7322147dd8620e402bf38cd61f60b86f22026
| 7,022
|
cpp
|
C++
|
Lib/src/PropertyExtractor/Greens.cpp
|
undisputed-seraphim/TBTK
|
45a0875a11da951f900b6fd5e0773ccdf8462915
|
[
"Apache-2.0"
] | 96
|
2016-04-21T16:46:56.000Z
|
2022-01-15T21:40:25.000Z
|
Lib/src/PropertyExtractor/Greens.cpp
|
undisputed-seraphim/TBTK
|
45a0875a11da951f900b6fd5e0773ccdf8462915
|
[
"Apache-2.0"
] | 4
|
2016-10-19T16:56:20.000Z
|
2020-04-14T01:31:40.000Z
|
Lib/src/PropertyExtractor/Greens.cpp
|
undisputed-seraphim/TBTK
|
45a0875a11da951f900b6fd5e0773ccdf8462915
|
[
"Apache-2.0"
] | 19
|
2016-10-19T14:21:58.000Z
|
2021-04-15T13:52:09.000Z
|
/* Copyright 2018 Kristofer Björnson
*
* 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.
*/
/** @file Greens.cpp
*
* @author Kristofer Björnson
*/
#include "TBTK/PropertyExtractor/Greens.h"
#include "TBTK/PropertyExtractor/PatternValidator.h"
#include "TBTK/Functions.h"
#include "TBTK/Streams.h"
#include "TBTK/TBTKMacros.h"
#include <set>
using namespace std;
namespace TBTK{
namespace PropertyExtractor{
Greens::Greens(){
}
Greens::~Greens(){
}
void Greens::setEnergyWindow(
double lowerBound,
double upperBound,
int energyResolution
){
TBTKExit(
"PropertyExtractor::Greens::setEnergyWindow()",
"This function is not supported by this PropertyExtractor.",
"The energy window is instead determined by the Green's"
<< " function that is used by the corresponding solver. Use"
<< " Solver::Greens::setGreensFunction() to set this Green's"
<< " function."
);
}
Property::Density Greens::calculateDensity(
Index pattern,
Index ranges
){
ensureCompliantRanges(pattern, ranges);
vector<int> loopRanges = getLoopRanges(pattern, ranges);
Property::Density density(loopRanges);
Information information;
calculate(
calculateDensityCallback,
density,
pattern,
ranges,
0,
1,
information
);
return density;
}
Property::Density Greens::calculateDensity(
vector<Index> patterns
){
PatternValidator::validateDensityPatterns(patterns);
const Solver::Greens &solver = getSolver();
IndexTree allIndices = generateIndexTree(
patterns,
solver.getModel().getHoppingAmplitudeSet(),
false,
false
);
IndexTree memoryLayout = generateIndexTree(
patterns,
solver.getModel().getHoppingAmplitudeSet(),
true,
true
);
Property::Density density(memoryLayout);
Information information;
calculate(
calculateDensityCallback,
allIndices,
memoryLayout,
density,
information
);
return density;
}
Property::LDOS Greens::calculateLDOS(
vector<Index> patterns
){
PatternValidator::validateLDOSPatterns(patterns);
const Solver::Greens &solver = getSolver();
IndexTree allIndices = generateIndexTree(
patterns,
solver.getModel().getHoppingAmplitudeSet(),
false,
true
);
IndexTree memoryLayout = generateIndexTree(
patterns,
solver.getModel().getHoppingAmplitudeSet(),
true,
true
);
Property::LDOS ldos(
memoryLayout,
Range(
solver.getGreensFunction().getLowerBound(),
solver.getGreensFunction().getUpperBound(),
solver.getGreensFunction().getResolution()
)
);
Information information;
calculate(
calculateLDOSCallback,
allIndices,
memoryLayout,
ldos,
information
);
return ldos;
}
void Greens::calculateDensityCallback(
PropertyExtractor *cb_this,
Property::Property &property,
const Index &index,
int offset,
Information &information
){
Greens *propertyExtractor = (Greens*)cb_this;
const Solver::Greens &solver = propertyExtractor->getSolver();
Property::Density &density = (Property::Density&)property;
vector<double> &data = density.getDataRW();
const Property::GreensFunction &greensFunction
= solver.getGreensFunction();
const Model &model = solver.getModel();
switch(greensFunction.getType()){
case Property::GreensFunction::Type::Retarded:
{
double lowerBound = greensFunction.getLowerBound();
double upperBound = greensFunction.getUpperBound();
int energyResolution = greensFunction.getResolution();
const double dE = (upperBound - lowerBound)/energyResolution;
for(int e = 0; e < energyResolution; e++){
double E = lowerBound + e*dE;
double weight = getThermodynamicEquilibriumOccupation(
E,
model
);
data[offset] += -weight*imag(
greensFunction({index, index}, e)
)/M_PI*dE;
}
break;
}
case Property::GreensFunction::Type::Advanced:
case Property::GreensFunction::Type::NonPrincipal:
{
double lowerBound = greensFunction.getLowerBound();
double upperBound = greensFunction.getUpperBound();
int energyResolution = greensFunction.getResolution();
const double dE = (upperBound - lowerBound)/energyResolution;
for(int e = 0; e < energyResolution; e++){
double E = lowerBound + e*dE;
double weight = getThermodynamicEquilibriumOccupation(
E,
model
);
data[offset] += weight*imag(
greensFunction({index, index}, e)
)/M_PI*dE;
}
break;
}
case Property::GreensFunction::Type::Matsubara:
{
for(
unsigned int e = 0;
e < greensFunction.getNumMatsubaraEnergies();
e++
){
data[offset] += real(greensFunction({index, index}, e));
}
data[offset]
*= greensFunction.getFundamentalMatsubaraEnergy()/M_PI;
data[offset] += 1/2.;
break;
}
default:
TBTKExit(
"PropertyExtractor::Greens::calculateDensityCallback()",
"Only calculation of the Density from the Retarded,"
<< " Advanced, and NonPrincipal Green's function"
<< " is supported yet.",
""
);
}
}
void Greens::calculateLDOSCallback(
PropertyExtractor *cb_this,
Property::Property &property,
const Index &index,
int offset,
Information &information
){
Greens *propertyExtractor = (Greens*)cb_this;
const Solver::Greens &solver = propertyExtractor->getSolver();
Property::LDOS &ldos = (Property::LDOS&)property;
vector<double> &data = ldos.getDataRW();
const Property::GreensFunction &greensFunction
= solver.getGreensFunction();
switch(greensFunction.getType()){
case Property::GreensFunction::Type::Retarded:
{
double lowerBound = greensFunction.getLowerBound();
double upperBound = greensFunction.getUpperBound();
int energyResolution = greensFunction.getResolution();
const double dE = (upperBound - lowerBound)/energyResolution;
for(int n = 0; n < energyResolution; n++){
data[offset + n] -= imag(
greensFunction({index, index}, n)
)/M_PI*dE;
}
break;
}
case Property::GreensFunction::Type::Advanced:
case Property::GreensFunction::Type::NonPrincipal:
{
double lowerBound = greensFunction.getLowerBound();
double upperBound = greensFunction.getUpperBound();
int energyResolution = greensFunction.getResolution();
const double dE = (upperBound - lowerBound)/energyResolution;
for(int n = 0; n < energyResolution; n++){
data[offset + n] += imag(
greensFunction({index, index}, n)
)/M_PI*dE;
}
break;
}
default:
TBTKExit(
"PropertyExtractor::Greens::calculateDensityCallback()",
"Only calculation of the Density from the Retarded,"
<< " Advanced, and NonPrincipal Green's function"
<< " is supported yet.",
""
);
}
}
}; //End of namespace PropertyExtractor
}; //End of namespace TBTK
| 23.174917
| 75
| 0.722159
|
undisputed-seraphim
|
5ccc2ae6acfeabfdc89ea685ee02dff9a26be907
| 2,459
|
cpp
|
C++
|
taco-oopsla2017/src/io/tns_file_format.cpp
|
peterahrens/FillEstimationIPDPS2017
|
857b6ee8866a2950aa5721d575d2d7d0797c4302
|
[
"BSD-3-Clause"
] | null | null | null |
taco-oopsla2017/src/io/tns_file_format.cpp
|
peterahrens/FillEstimationIPDPS2017
|
857b6ee8866a2950aa5721d575d2d7d0797c4302
|
[
"BSD-3-Clause"
] | null | null | null |
taco-oopsla2017/src/io/tns_file_format.cpp
|
peterahrens/FillEstimationIPDPS2017
|
857b6ee8866a2950aa5721d575d2d7d0797c4302
|
[
"BSD-3-Clause"
] | null | null | null |
#include "taco/io/tns_file_format.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cmath>
#include <limits.h>
#include "taco/tensor.h"
#include "taco/format.h"
#include "taco/error.h"
#include "taco/util/strings.h"
using namespace std;
namespace taco {
namespace io {
namespace tns {
TensorBase read(std::string filename, const Format& format, bool pack) {
std::ifstream file;
file.open(filename);
taco_uassert(file.is_open()) << "Error opening file: " << filename;
TensorBase tensor = read(file, format, pack);
file.close();
return tensor;
}
TensorBase read(std::istream& stream, const Format& format, bool pack) {
std::vector<int> coordinates;
std::vector<double> values;
std::string line;
if (!std::getline(stream, line)) {
return TensorBase();
}
// Infer tensor order from the first coordinate
vector<string> toks = util::split(line, " ");
size_t order = toks.size()-1;
std::vector<int> dimensions(order);
std::vector<int> coordinate(order);
// Load data
do {
char* linePtr = (char*)line.data();
for (size_t i = 0; i < order; i++) {
long idx = strtol(linePtr, &linePtr, 10);
taco_uassert(idx <= INT_MAX)<<"Coordinate in file is larger than INT_MAX";
coordinate[i] = (int)idx - 1;
dimensions[i] = std::max(dimensions[i], (int)idx);
}
coordinates.insert(coordinates.end(), coordinate.begin(), coordinate.end());
double val = strtod(linePtr, &linePtr);
values.push_back(val);
} while (std::getline(stream, line));
// Create tensor
const size_t nnz = values.size();
TensorBase tensor(type<double>(), dimensions, format);
tensor.reserve(nnz);
// Insert coordinates (TODO add and use bulk insertion)
for (size_t i = 0; i < nnz; i++) {
for (size_t j = 0; j < order; j++) {
coordinate[j] = coordinates[i*order + j];
}
tensor.insert(coordinate, values[i]);
}
if (pack) {
tensor.pack();
}
return tensor;
}
void write(std::string filename, const TensorBase& tensor) {
std::ofstream file;
file.open(filename);
taco_uassert(file.is_open()) << "Error opening file: " << filename;
write(file, tensor);
file.close();
}
void write(std::ostream& stream, const TensorBase& tensor) {
for (auto& value : iterate<double>(tensor)) {
for (int coord : value.first) {
stream << coord+1 << " ";
}
stream << value.second << endl;
}
}
}}}
| 24.838384
| 80
| 0.647824
|
peterahrens
|
5ccee7478fd0e8a053cba7962f9c04078dc9395c
| 760
|
cpp
|
C++
|
TypesetWidget/commanddeletetext.cpp
|
Math-Collection/YAWYSIWYGEE-Qt-Equation-Editor-Widget
|
c4e177bff5edff8122ec73a7ed8f325b42fc74b4
|
[
"MIT"
] | 2
|
2020-03-28T15:35:08.000Z
|
2021-01-10T06:50:05.000Z
|
TypesetWidget/commanddeletetext.cpp
|
Qt-Widgets/YAWYSIWYGEE-Qt-Equation-Editor-Widget
|
040383a8db795bb863c451caf4022018181afaf1
|
[
"MIT"
] | null | null | null |
TypesetWidget/commanddeletetext.cpp
|
Qt-Widgets/YAWYSIWYGEE-Qt-Equation-Editor-Widget
|
040383a8db795bb863c451caf4022018181afaf1
|
[
"MIT"
] | null | null | null |
#include "commanddeletetext.h"
#include "cursor.h"
namespace Typeset{
CommandDeleteText::CommandDeleteText(Cursor& cursor, Text* t, QTextCursor cL, QTextCursor cR)
: cursor(cursor),
t(t) {
pL = cL.position();
pR = cR.position();
c = cL;
c.setPosition(cR.position(), QTextCursor::KeepAnchor);
str = c.selectedText();
c = cL;
}
void CommandDeleteText::redo(){
c.setPosition(pL);
c.setPosition(c.position() + str.length(), QTextCursor::KeepAnchor);
c.removeSelectedText();
t->updateToTop();
cursor.setPosition(*t, c);
}
void CommandDeleteText::undo(){
c.setPosition(pL);
c.insertText(str);
t->updateToTop();
cursor.setPosition(*t, c);
c.setPosition(c.position() - str.length());
}
}
| 21.714286
| 93
| 0.643421
|
Math-Collection
|
5cd323e2d31d861165bfadfdce0e6c41f0e91ca8
| 4,970
|
tcc
|
C++
|
flens/blas/level1/raxpy.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 98
|
2015-01-26T20:31:37.000Z
|
2021-09-09T15:51:37.000Z
|
flens/blas/level1/raxpy.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 16
|
2015-01-21T07:43:45.000Z
|
2021-12-06T12:08:36.000Z
|
flens/blas/level1/raxpy.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 31
|
2015-01-05T08:06:45.000Z
|
2022-01-26T20:12:00.000Z
|
/*
* Copyright (c) 2012, Michael Lehn
*
* 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 FLENS development group nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FLENS_BLAS_LEVEL1_RAXPY_TCC
#define FLENS_BLAS_LEVEL1_RAXPY_TCC 1
#include <cxxblas/cxxblas.h>
#include <flens/auxiliary/auxiliary.h>
#include <flens/blas/closures/closures.h>
#include <flens/blas/level1/level1.h>
#include <flens/typedefs.h>
#ifdef FLENS_DEBUG_CLOSURES
# include <flens/blas/blaslogon.h>
#else
# include <flens/blas/blaslogoff.h>
#endif
namespace flens { namespace blas {
//-- raxpy
template <typename ALPHA, typename VX, typename VY>
typename RestrictTo<IsDenseVector<VX>::value
&& IsDenseVector<VY>::value,
void>::Type
raxpy(const ALPHA &alpha, const VX &x, VY &&y)
{
FLENS_BLASLOG_SETTAG("--> ");
FLENS_BLASLOG_BEGIN_RAXPY(alpha, x, y);
if (y.length()==0) {
//
// So we allow y += 1/alpha*x for an empty vector y
//
typedef typename RemoveRef<VY>::Type VectorY;
typedef typename VectorY::ElementType T;
const T Zero(0);
y.resize(x, Zero);
}
ASSERT(y.length()==x.length());
# ifdef HAVE_CXXBLAS_RAXPY
cxxblas::raxpy(x.length(), alpha,
x.data(), x.stride(),
y.data(), y.stride());
# else
ASSERT(0);
# endif
FLENS_BLASLOG_END;
FLENS_BLASLOG_UNSETTAG;
}
//-- geraxpy
//
// B += A/alpha
//
template <typename ALPHA, typename MA, typename MB>
typename RestrictTo<IsGeMatrix<MA>::value
&& IsGeMatrix<MB>::value,
void>::Type
raxpy(Transpose trans, const ALPHA &alpha, const MA &A, MB &&B)
{
typedef typename RemoveRef<MB>::Type MatrixB;
if (B.numRows()==0 || B.numCols()==0) {
//
// So we allow B += 1/alpha*A for an empty matrix B
//
typedef typename MatrixB::ElementType T;
const T Zero(0);
if ((trans==NoTrans) || (trans==Conj)) {
B.resize(A.numRows(), A.numCols(), Zero);
} else {
B.resize(A.numCols(), A.numRows(), Zero);
}
}
# ifndef NDEBUG
if ((trans==NoTrans) || (trans==Conj)) {
ASSERT((A.numRows()==B.numRows()) && (A.numCols()==B.numCols()));
} else {
ASSERT((A.numRows()==B.numCols()) && (A.numCols()==B.numRows()));
}
# endif
trans = (A.order()==B.order())
? Transpose(trans ^ NoTrans)
: Transpose(trans ^ Trans);
# ifndef FLENS_DEBUG_CLOSURES
# ifndef NDEBUG
if (trans==Trans || trans==ConjTrans) {
ASSERT(!DEBUGCLOSURE::identical(A, B));
}
# endif
# else
typedef typename RemoveRef<MA>::Type MatrixA;
//
// If A and B are identical a temporary is needed if we want to use axpy
// for B += A^T/alpha or B+= A^H/alpha
//
if ((trans==Trans || trans==ConjTrans) && DEBUGCLOSURE::identical(A, B)) {
typename Result<MatrixA>::Type A_ = A;
FLENS_BLASLOG_TMP_ADD(A_);
axpy(trans, alpha, A_, B);
FLENS_BLASLOG_TMP_REMOVE(A_, A);
return;
}
# endif
FLENS_BLASLOG_SETTAG("--> ");
FLENS_BLASLOG_BEGIN_MRAXPY(trans, alpha, A, B);
# ifdef HAVE_CXXBLAS_GERAXPY
geraxpy(B.order(), trans, B.numRows(), B.numCols(), alpha,
A.data(), A.leadingDimension(),
B.data(), B.leadingDimension());
# else
ASSERT(0);
# endif
FLENS_BLASLOG_END;
FLENS_BLASLOG_UNSETTAG;
}
} } // namespace blas, flens
#endif // FLENS_BLAS_LEVEL1_RAXPY_TCC
| 30.121212
| 78
| 0.645272
|
stip
|
5cd3570a357b9a4becdc314a42657c5218f9cf78
| 309
|
cpp
|
C++
|
examples/qcor_demos/pnnl_tutorials/1_kernels/ccnot_qfast.cpp
|
vetter/qcor
|
6f86835737277a26071593bb10dd8627c29d74a3
|
[
"BSD-3-Clause"
] | 59
|
2019-08-22T18:40:38.000Z
|
2022-03-09T04:12:42.000Z
|
examples/qcor_demos/pnnl_tutorials/1_kernels/ccnot_qfast.cpp
|
vetter/qcor
|
6f86835737277a26071593bb10dd8627c29d74a3
|
[
"BSD-3-Clause"
] | 137
|
2019-09-13T15:50:18.000Z
|
2021-12-06T14:19:46.000Z
|
examples/qcor_demos/pnnl_tutorials/1_kernels/ccnot_qfast.cpp
|
vetter/qcor
|
6f86835737277a26071593bb10dd8627c29d74a3
|
[
"BSD-3-Clause"
] | 26
|
2019-07-08T17:30:35.000Z
|
2021-12-03T16:24:12.000Z
|
__qpu__ void ccnot(qreg q) {
decompose {
UnitaryMatrix ccnot_mat = UnitaryMatrix::Identity(8, 8);
ccnot_mat(6, 6) = 0.0;
ccnot_mat(7, 7) = 0.0;
ccnot_mat(6, 7) = 1.0;
ccnot_mat(7, 6) = 1.0;
}
(q, QFAST);
}
int main() {
auto q = qalloc(3);
ccnot::print_kernel(q);
return 0;
}
| 17.166667
| 60
| 0.572816
|
vetter
|
5cd48f36f264bf9e2c1f1cfbe788d0b70faf89f6
| 267
|
cc
|
C++
|
benchmarks/0000.10m_size_t/strings/size_t/fmtformat_int.cc
|
EwoutH/fast_io
|
1393ef01b82dffa87f3008ec0898431865870a1f
|
[
"MIT"
] | 2
|
2020-07-20T06:07:20.000Z
|
2020-10-21T08:53:49.000Z
|
benchmarks/0000.10m_size_t/strings/size_t/fmtformat_int.cc
|
EwoutH/fast_io
|
1393ef01b82dffa87f3008ec0898431865870a1f
|
[
"MIT"
] | null | null | null |
benchmarks/0000.10m_size_t/strings/size_t/fmtformat_int.cc
|
EwoutH/fast_io
|
1393ef01b82dffa87f3008ec0898431865870a1f
|
[
"MIT"
] | null | null | null |
#include"../../../timer.h"
#include<fmt/format.h>
int main()
{
constexpr std::size_t N(200000000);
std::size_t value{};
{
fast_io::timer t("fmt::format_int");
for(std::size_t i{};i!=N;++i)
value+=fmt::format_int(i).str().size();
}
println("value:",value);
}
| 19.071429
| 41
| 0.614232
|
EwoutH
|
5cd51a933cc3bfa003384ad5feff282e29ac0ede
| 7,362
|
cpp
|
C++
|
multimedia/directx/dplay/dplay8/sp/wsock/locals.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
multimedia/directx/dplay/dplay8/sp/wsock/locals.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
multimedia/directx/dplay/dplay8/sp/wsock/locals.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
/*==========================================================================
*
* Copyright (C) 1998-2002 Microsoft Corporation. All Rights Reserved.
*
* File: Locals.cpp
* Content: Global variables for the DNWsock service provider
*
*
* History:
* Date By Reason
* ==== == ======
* 11/25/98 jtk Created
***************************************************************************/
#include "dnwsocki.h"
//**********************************************************************
// Constant definitions
//**********************************************************************
//**********************************************************************
// Macro definitions
//**********************************************************************
//**********************************************************************
// Structure definitions
//**********************************************************************
//**********************************************************************
// Variable definitions
//**********************************************************************
#if ((! defined(WINCE)) && (! defined(_XBOX)))
//
// DLL instance
//
HINSTANCE g_hDLLInstance = NULL;
#endif // ! WINCE and ! _XBOX
#ifdef _XBOX
BOOL g_fStartedXNet = FALSE;
#endif // _XBOX
#ifndef DPNBUILD_LIBINTERFACE
//
// count of outstanding COM interfaces
//
volatile LONG g_lOutstandingInterfaceCount = 0;
#endif // ! DPNBUILD_LIBINTERFACE
#ifndef DPNBUILD_ONLYONETHREAD
//
// thread count
//
LONG g_iThreadCount = 0;
#endif // ! DPNBUILD_ONLYONETHREAD
#ifndef DPNBUILD_NOREGISTRY
#if ((! defined(DPNBUILD_NOWINSOCK2)) && (! defined(DPNBUILD_ONLYWINSOCK2)))
DWORD g_dwWinsockVersion = 0;
#endif // ! DPNBUILD_NOWINSOCK2 and ! DPNBUILD_ONLYWINSOCK2
#endif // ! DPNBUILD_NOREGISTRY
//
// Winsock receive buffer size
//
BOOL g_fWinsockReceiveBufferSizeOverridden = FALSE;
INT g_iWinsockReceiveBufferSize = 0;
#ifndef DPNBUILD_NONATHELP
//
// global NAT/firewall traversal information
//
#ifndef DPNBUILD_NOREGISTRY
BOOL g_fDisableDPNHGatewaySupport = FALSE;
BOOL g_fDisableDPNHFirewallSupport = FALSE;
DWORD g_dwDefaultTraversalMode = DPNA_TRAVERSALMODE_PORTREQUIRED;
#endif // ! DPNBUILD_NOREGISTRY
IDirectPlayNATHelp ** g_papNATHelpObjects = NULL;
#ifndef DPNBUILD_NOLOCALNAT
BOOL g_fLocalNATDetectedAtStartup = FALSE;
#endif // ! DPNBUILD_NOLOCALNAT
#endif // ! DPNBUILD_NONATHELP
#ifndef DPNBUILD_NOREGISTRY
#if ((defined(WINNT)) && (! defined(DPNBUILD_NOMULTICAST)))
BOOL g_fDisableMadcapSupport = FALSE;
MCAST_CLIENT_UID g_mcClientUid;
#endif // WINNT and not DPNBUILD_NOMULTICAST
//
// ignore enums performance option
//
BOOL g_fIgnoreEnums = FALSE;
//
// disconnect upon reception of ICMP port not reachable option
//
BOOL g_fDisconnectOnICMP = FALSE;
#ifndef DPNBUILD_NOIPV6
//
// IPv4 only/IPv6 only/hybrid setting
//
int g_iIPAddressFamily = PF_INET;
#endif // ! DPNBUILD_NOIPV6
//
// IP banning globals
//
CHashTable * g_pHashBannedIPv4Addresses = NULL;
DWORD g_dwBannedIPv4Masks = 0;
//
// proxy support options
//
#ifndef DPNBUILD_NOWINSOCK2
BOOL g_fDontAutoDetectProxyLSP = FALSE;
#endif // ! DPNBUILD_NOWINSOCK2
BOOL g_fTreatAllResponsesAsProxied = FALSE;
//
// settings for overriding MTU
//
DWORD g_dwMaxUserDataSize = DEFAULT_MAX_USER_DATA_SIZE;
DWORD g_dwMaxEnumDataSize = DEFAULT_MAX_ENUM_DATA_SIZE;
//
// default port range
//
WORD g_wBaseDPlayPort = BASE_DPLAY8_PORT;
WORD g_wMaxDPlayPort = MAX_DPLAY8_PORT;
#endif // ! DPNBUILD_NOREGISTRY
//
// ID of most recent endpoint generated
//
DWORD g_dwCurrentEndpointID = 0;
#ifdef DBG
//
// Bilink for tracking DPNWSock critical sections
//
CBilink g_blDPNWSockCritSecsHeld;
#endif // DBG
#ifdef DPNBUILD_WINSOCKSTATISTICS
//
// Winsock debugging/tuning stats
//
DWORD g_dwWinsockStatNumSends = 0;
DWORD g_dwWinsockStatSendCallTime = 0;
#endif // DPNBUILD_WINSOCKSTATISTICS
#ifndef DPNBUILD_NOREGISTRY
//
// registry strings
//
const WCHAR g_RegistryBase[] = L"SOFTWARE\\Microsoft\\DirectPlay8";
const WCHAR g_RegistryKeyReceiveBufferSize[] = L"WinsockReceiveBufferSize";
#ifndef DPNBUILD_ONLYONETHREAD
const WCHAR g_RegistryKeyThreadCount[] = L"ThreadCount";
#endif // ! DPNBUILD_ONLYONETHREAD
#if ((! defined(DPNBUILD_NOWINSOCK2)) && (! defined(DPNBUILD_ONLYWINSOCK2)))
const WCHAR g_RegistryKeyWinsockVersion[] = L"WinsockVersion";
#endif // ! DPNBUILD_NOWINSOCK2 and ! DPNBUILD_ONLYWINSOCK2
#ifndef DPNBUILD_NONATHELP
const WCHAR g_RegistryKeyDisableDPNHGatewaySupport[] = L"DisableDPNHGatewaySupport";
const WCHAR g_RegistryKeyDisableDPNHFirewallSupport[] = L"DisableDPNHFirewallSupport";
const WCHAR g_RegistryKeyTraversalModeSettings[] = L"TraversalModeSettings";
const WCHAR g_RegistryKeyDefaultTraversalMode[] = L"DefaultTraversalMode";
#endif // !DPNBUILD_NONATHELP
const WCHAR g_RegistryKeyAppsToIgnoreEnums[] = L"AppsToIgnoreEnums";
const WCHAR g_RegistryKeyAppsToDisconnectOnICMP[] = L"AppsToDisconnectOnICMP";
#ifndef DPNBUILD_NOIPV6
const WCHAR g_RegistryKeyIPAddressFamilySettings[] = L"IPAddressFamilySettings";
const WCHAR g_RegistryKeyDefaultIPAddressFamily[]= L"DefaultIPAddressFamily";
#endif // ! DPNBUILD_NOIPV6
#ifndef DPNBUILD_NOWINSOCK2
const WCHAR g_RegistryKeyDontAutoDetectProxyLSP[] = L"DontAutoDetectProxyLSP";
#endif // ! DPNBUILD_NOWINSOCK2
const WCHAR g_RegistryKeyTreatAllResponsesAsProxied[] = L"TreatAllResponsesAsProxied";
#if ((defined(WINNT)) && (! defined(DPNBUILD_NOMULTICAST)))
const WCHAR g_RegistryKeyDisableMadcapSupport[] = L"DisableMadcapSupport";
#endif // WINNT and not DPNBUILD_NOMULTICAST
const WCHAR g_RegistryKeyBannedIPv4Addresses[] = L"BannedIPv4Addresses";
const WCHAR g_RegistryKeyMaxUserDataSize[] = L"MaxUserDataSize";
const WCHAR g_RegistryKeyMaxEnumDataSize[] = L"MaxEnumDataSize";
const WCHAR g_RegistryKeyBaseDPlayPort[] = L"BaseDPlayPort";
const WCHAR g_RegistryKeyMaxDPlayPort[] = L"MaxDPlayPort";
#endif // ! DPNBUILD_NOREGISTRY
//
// GUIDs for munging device and scope IDs
//
// {4CE725F4-7B00-4397-BA6F-11F965BC4299}
GUID g_IPSPEncryptionGuid = { 0x4ce725f4, 0x7b00, 0x4397, { 0xba, 0x6f, 0x11, 0xf9, 0x65, 0xbc, 0x42, 0x99 } };
#ifndef DPNBUILD_NOIPX
// {CA734945-3FC1-42ea-BF49-84AFCD4764AA}
GUID g_IPXSPEncryptionGuid = { 0xca734945, 0x3fc1, 0x42ea, { 0xbf, 0x49, 0x84, 0xaf, 0xcd, 0x47, 0x64, 0xaa } };
#endif // ! DPNBUILD_NOIPX
#ifndef DPNBUILD_NOIPV6
//
// IPv6 link-local multicast address for enumerating DirectPlay sessions
//
#pragma TODO(vanceo, "\"Standardize\" enum multicast address?")
const IN6_ADDR c_in6addrEnumMulticast = {0xff,0x02,0,0,0,0,0,0,0,0,0,0,0,0,0x01,0x30};
#endif // ! DPNBUILD_NOIPV6
//**********************************************************************
// Function prototypes
//**********************************************************************
//**********************************************************************
// Function definitions
//**********************************************************************
| 30.04898
| 113
| 0.625917
|
npocmaka
|
5cd67a6323c938d13e7ca548f26524eb93c5ca2a
| 1,146
|
cpp
|
C++
|
deps/mozjs/js/src/v8api/test/test_handle.cpp
|
zpao/spidernode
|
843d5b5e9be55ce447fd03127aeeb2c7728ae168
|
[
"MIT"
] | 48
|
2015-01-09T20:39:35.000Z
|
2021-12-21T21:17:52.000Z
|
deps/mozjs/js/src/v8api/test/test_handle.cpp
|
ninja1002/spidernode
|
ada8fc559bd2c047a6e52c78af9d27ab273c87d5
|
[
"MIT"
] | 2
|
2016-02-05T10:27:37.000Z
|
2019-01-22T16:22:51.000Z
|
deps/mozjs/js/src/v8api/test/test_handle.cpp
|
ninja1002/spidernode
|
ada8fc559bd2c047a6e52c78af9d27ab273c87d5
|
[
"MIT"
] | 8
|
2015-01-12T17:14:36.000Z
|
2018-09-15T14:10:27.000Z
|
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
#include "v8api_test_harness.h"
////////////////////////////////////////////////////////////////////////////////
//// Tests
void
test_ArrayConversion()
{
HandleScope handle_scope;
Persistent<Context> context = Context::New();
Context::Scope context_scope(context);
Local<String> s = String::New("hey");
Local<String> uncaught_exception_symbol_l = Local<String>::New(s);
Local<Value> argv[1] = { uncaught_exception_symbol_l };
context.Dispose();
}
void
test_HandleScope() {
HandleScope outer;
Local<Value> v;
{
HandleScope inner;
v = inner.Close(String::New("hey"));
}
do_check_true(!v.IsEmpty());
Local<String> s = v->ToString();
do_check_true(!s.IsEmpty());
do_check_true(s->Equals(v));
}
////////////////////////////////////////////////////////////////////////////////
//// Test Harness
Test gTests[] = {
TEST(test_ArrayConversion),
TEST(test_HandleScope),
};
const char* file = __FILE__;
#define TEST_NAME "Handle Classes"
#define TEST_FILE file
#include "v8api_test_harness_tail.h"
| 23.387755
| 80
| 0.602967
|
zpao
|
5cd7b02652bcf3eb19abc275c3682832010e23a3
| 398
|
cpp
|
C++
|
src/algos/connection.cpp
|
mhough/braingl
|
53e2078adc10731ee62feec11dcb767c4c6c0d35
|
[
"MIT"
] | 5
|
2016-03-17T07:02:11.000Z
|
2021-12-12T14:43:58.000Z
|
src/algos/connection.cpp
|
mhough/braingl
|
53e2078adc10731ee62feec11dcb767c4c6c0d35
|
[
"MIT"
] | null | null | null |
src/algos/connection.cpp
|
mhough/braingl
|
53e2078adc10731ee62feec11dcb767c4c6c0d35
|
[
"MIT"
] | 3
|
2015-10-29T15:21:01.000Z
|
2020-11-25T09:41:21.000Z
|
/*
* connection.cpp
*
* Created on: Apr 30, 2013
* Author: boettgerj
*/
#include "connection.h"
#include "qmath.h"
Connection::Connection( QVector3D fn, QVector3D diff, float v ) :
fn( fn ),
diff( diff ),
v( v )
{
QVector3D diffn = diff.normalized();
r=qAbs(diffn.x());
g=qAbs(diffn.y());
b=qAbs(diffn.z());
}
Connection::~Connection()
{
}
| 13.724138
| 65
| 0.557789
|
mhough
|
5ce1cf2c85f5c6504197bfe1a1e24e94ee48e855
| 4,033
|
cpp
|
C++
|
source/IrrOdeTestBed/tests/CTestCar.cpp
|
inniyah/irrode
|
0ecb125933ef828995e4fd557410acf703bea0e2
|
[
"bzip2-1.0.6"
] | 1
|
2018-01-17T22:57:55.000Z
|
2018-01-17T22:57:55.000Z
|
source/IrrOdeTestBed/tests/CTestCar.cpp
|
inniyah/irrode
|
0ecb125933ef828995e4fd557410acf703bea0e2
|
[
"bzip2-1.0.6"
] | null | null | null |
source/IrrOdeTestBed/tests/CTestCar.cpp
|
inniyah/irrode
|
0ecb125933ef828995e4fd557410acf703bea0e2
|
[
"bzip2-1.0.6"
] | null | null | null |
#include <tests/CTestCar.h>
CTestCar::CTestCar(irr::IrrlichtDevice *pDevice, IRunner *pRunner) : IState(pDevice, pRunner) {
m_sName=L"Car Test";
m_sDescr=L"Test with user controlled car";
}
void CTestCar::activate() {
m_pSmgr->loadScene(DATADIR "/scenes/Testbed_car.xml");
m_pCam=m_pSmgr->addCameraSceneNode();
m_pObject=reinterpret_cast<irr::ode::CIrrOdeBody *>(m_pSmgr->getSceneNodeFromName("car"));
m_pEngine[0]=reinterpret_cast<irr::ode::CIrrOdeMotor *>(m_pSmgr->getSceneNodeFromName("sc_motor1"));
m_pEngine[1]=reinterpret_cast<irr::ode::CIrrOdeMotor *>(m_pSmgr->getSceneNodeFromName("sc_motor2"));
m_pSteer[0]=reinterpret_cast<irr::ode::CIrrOdeServo *>(m_pSmgr->getSceneNodeFromName("sc_servo1"));
m_pSteer[1]=reinterpret_cast<irr::ode::CIrrOdeServo *>(m_pSmgr->getSceneNodeFromName("sc_servo2"));
m_pInfo=m_pGui->addStaticText(L"Hello World",irr::core::rect<irr::s32>(10,10,210,160),true,true,NULL,-1,true);
printf("\nOde Test Car's objects:\n\tbody: %i\n\tmotors: %i, %i\n\tservos: %i, %i\n\n",
(int)m_pObject,(int)m_pEngine[0],(int)m_pEngine[1],(int)m_pSteer[0],(int)m_pSteer[1]);
//init the ODE
m_pOdeMngr->initODE();
m_pOdeMngr->initPhysics();
m_pOdeMngr->getQueue()->addEventListener(this);
printf("Ready.\n");
m_pRunner->setEventReceiver(this);
}
void CTestCar::deactivate() {
m_pGui->clear();
m_pSmgr->clear();
m_pOdeMngr->closeODE();
m_pOdeMngr->getQueue()->removeEventListener(this);
m_pRunner->setEventReceiver(NULL);
}
irr::s32 CTestCar::update() {
irr::s32 iRet=0;
//step the simulation
m_pOdeMngr->step();
if (m_pObject!=NULL && m_pCam!=NULL) {
irr::core::vector3df vPos=m_pObject->getPosition(),
vRot=m_pObject->getRotation(),
vCam=vPos+vRot.rotationToDirection(irr::core::vector3df(12.5f,6.0f,0.0f)),
vUp =m_pObject->getRotation().rotationToDirection(irr::core::vector3df(0.0f,1.0f,0.0f));
m_pCam->setPosition(vCam);
m_pCam->setUpVector(vUp);
m_pCam->setTarget(vPos+3.0f*vUp);
}
return iRet;
}
bool CTestCar::OnEvent(const irr::SEvent &event) {
bool bRet=false;
if (event.EventType==irr::EET_KEY_INPUT_EVENT) {
if (event.KeyInput.PressedDown) {
switch (event.KeyInput.Key) {
case irr::KEY_UP : m_pEngine[0]->setVelocity(-25.0f); m_pEngine[1]->setVelocity(-25.0f); break;
case irr::KEY_DOWN: m_pEngine[0]->setVelocity( 25.0f); m_pEngine[1]->setVelocity( 25.0f); break;
case irr::KEY_LEFT : m_pSteer[0]->setServoPos( 25.0f); m_pSteer[1]->setServoPos( 25.0f); break;
case irr::KEY_RIGHT: m_pSteer[0]->setServoPos(-25.0f); m_pSteer[1]->setServoPos(-25.0f); break;
default: break;
}
}
else {
switch (event.KeyInput.Key) {
case irr::KEY_UP:
case irr::KEY_DOWN:
m_pEngine[0]->setVelocity(0.0f);
m_pEngine[1]->setVelocity(0.0f);
break;
case irr::KEY_LEFT:
case irr::KEY_RIGHT:
m_pSteer[0]->setServoPos(0.0f);
m_pSteer[1]->setServoPos(0.0f);
break;
default: break;
}
}
}
return bRet;
}
bool CTestCar::onEvent(irr::ode::IIrrOdeEvent *pEvent) {
if (pEvent->getType()==irr::ode::eIrrOdeEventStep) {
irr::core::vector3df vPos=m_pObject->getPosition(),
vRot=m_pObject->getRotation(),
vVel=m_pObject->getLinearVelocity();
irr::f32 fVel=(vRot.rotationToDirection(irr::core::vector3df(-1.0f,0.0f,0.0f))).dotProduct(vVel);
wchar_t s[0xFF];
swprintf(s,0xFF,L"Position: %.2f, %.2f, %.2f\nVelocity: %.2f, %.2f, %.2f\nForeward Velocity: %.2f",
vPos.X,vPos.Y,vPos.Z,vVel.X,vVel.Y,vVel.Z,fVel);
m_pInfo->setText(s);
}
return false;
}
bool CTestCar::handlesEvent(irr::ode::IIrrOdeEvent *pEvent) {
return pEvent->getType()==irr::ode::eIrrOdeEventStep;
}
| 33.890756
| 114
| 0.629804
|
inniyah
|
5ce80c86538d991c55a3fe4c1c3693a440ac9c49
| 405
|
hpp
|
C++
|
src/games/chess.hpp
|
RememberOfLife/mirabel
|
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
|
[
"MIT"
] | 2
|
2022-03-29T08:39:24.000Z
|
2022-03-30T09:22:18.000Z
|
src/games/chess.hpp
|
RememberOfLife/mirabel
|
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
|
[
"MIT"
] | null | null | null |
src/games/chess.hpp
|
RememberOfLife/mirabel
|
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
|
[
"MIT"
] | null | null | null |
#pragma once
#include "surena/game.h"
#include "games/game_catalogue.hpp"
namespace Games {
class Chess : public BaseGameVariant {
public:
Chess();
~Chess();
game* new_game() override;
void draw_options() override;
void draw_state_editor(game* abstract_game) override;
const char* description() override;
};
}
| 18.409091
| 65
| 0.582716
|
RememberOfLife
|