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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5236d919c073af46b8f557d57a7cdd132bdcb307 | 2,833 | cpp | C++ | Code Library Of Others/sgtlaugh/Mincost Maxflow (Dijkstra + Potentials).cpp | BIJOY-SUST/ACM---ICPC | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | 6 | 2018-10-15T18:45:05.000Z | 2022-03-29T04:30:10.000Z | Code Library Of Others/sgtlaugh/Mincost Maxflow (Dijkstra + Potentials).cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | Code Library Of Others/sgtlaugh/Mincost Maxflow (Dijkstra + Potentials).cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | 4 | 2018-01-07T06:20:07.000Z | 2019-08-21T15:45:59.000Z | #include <stdio.h>
#include <bits/stdtr1c++.h>
#define MAX 200010 /// 2 * max(nodes, edges)
#define clr(ar) memset(ar, 0, sizeof(ar))
#define read() freopen("lol.txt", "r", stdin)
#define dbg(x) cout << #x << " = " << x << endl
#define ran(a, b) ((((rand() << 15) ^ rand()) % ((b) - (a) + 1)) + (a))
using namespace std;
/// Min-cost Max-flow using dijkstra with potentials
/// 0 Based indexed for directed weighted graphs (for undirected graphs, just add two directed edges)
/// Runs in around 2 seconds when n <= 200 and m = n * (n - 1) / 2
/// Runs well for sparse graphs though, e.g, m <= 10 * n
/// Costs must be non-negative
namespace mcmf{
const long long INF = 1LL << 60;
long long potential[MAX], dis[MAX], cap[MAX], cost[MAX];
int n, m, s, t, to[MAX], from[MAX], last[MAX], next[MAX], adj[MAX];
struct compare{
inline bool operator()(int a, int b){
if (dis[a] == dis[b]) return (a < b);
return (dis[a] < dis[b]);
}
};
set<int, compare> S;
void init(int nodes, int source, int sink){
m = 0, n = nodes;
s = source, t = sink;
for (int i = 0; i <= n; i++) potential[i] = 0, last[i] = -1;
}
void addEdge(int u, int v, long long c, long long w){
from[m] = u, adj[m] = v, cap[m] = c, cost[m] = w, next[m] = last[u], last[u] = m++;
from[m] = v, adj[m] = u, cap[m] = 0, cost[m] = -w, next[m] = last[v], last[v] = m++;
}
pair<long long, long long> solve(){
int i, j, e, u, v;
long long w, aug = 0, mincost = 0, maxflow = 0;
while (1){
S.clear();
for (i = 0; i < n; i++) dis[i] = INF;
dis[s] = 0, S.insert(s);
while (!S.empty()){
u = *(S.begin());
if (u == t) break;
S.erase(S.begin());
for (e = last[u]; e != -1; e = next[e]){
if (cap[e] != 0){
v = adj[e];
w = dis[u] + potential[u] + cost[e] - potential[v];
if (dis[v] > w){
S.erase(v);
dis[v] = w, to[v] = e;
S.insert(v);
}
}
}
}
if (dis[t] >= (INF >> 1)) break;
aug = cap[to[t]];
for (i = t; i != s; i = from[to[i]]) aug = min(aug, cap[to[i]]);
for (i = t; i != s; i = from[to[i]]){
cap[to[i]] -= aug;
cap[to[i] ^ 1] += aug;
mincost += (cost[to[i]] * aug);
}
for (i = 0; i <= n; i++) potential[i] = min(potential[i] + dis[i], INF);
maxflow += aug;
}
return make_pair(mincost, maxflow);
}
}
int main(){
}
| 31.831461 | 101 | 0.424991 | BIJOY-SUST |
523c82d598610ed85e251d90b8fb16f630693245 | 2,695 | cpp | C++ | Utilities/Poco/Util/src/ConfigurationView.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/Poco/Util/src/ConfigurationView.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/Poco/Util/src/ConfigurationView.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | //
// ConfigurationView.cpp
//
// $Id$
//
// Library: Util
// Package: Configuration
// Module: ConfigurationView
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/ConfigurationView.h"
namespace Poco {
namespace Util {
ConfigurationView::ConfigurationView(const std::string& prefix, AbstractConfiguration* pConfig):
_prefix(prefix),
_pConfig(pConfig)
{
poco_check_ptr (pConfig);
_pConfig->duplicate();
}
ConfigurationView::~ConfigurationView()
{
_pConfig->release();
}
bool ConfigurationView::getRaw(const std::string& key, std::string& value) const
{
std::string translatedKey = translateKey(key);
return _pConfig->getRaw(translatedKey, value) || _pConfig->getRaw(key, value);
}
void ConfigurationView::setRaw(const std::string& key, const std::string& value)
{
std::string translatedKey = translateKey(key);
_pConfig->setRaw(translatedKey, value);
}
void ConfigurationView::enumerate(const std::string& key, Keys& range) const
{
std::string translatedKey = translateKey(key);
_pConfig->enumerate(translatedKey, range);
}
std::string ConfigurationView::translateKey(const std::string& key) const
{
std::string result = _prefix;
if (!result.empty() && !key.empty()) result += '.';
result += key;
return result;
}
} } // namespace Poco::Util
| 29.615385 | 96 | 0.748052 | nocnokneo |
523f0000c9d1dc3d2d02ba758a52dbd04330f56c | 1,842 | cpp | C++ | cpp/speech/text_to_speech/source/text_to_speech.cpp | ortelio/rapp_beginner_tutorials | 5f770c15bef9906b667dd6a7cb0b12eeccfb37bb | [
"Apache-2.0"
] | null | null | null | cpp/speech/text_to_speech/source/text_to_speech.cpp | ortelio/rapp_beginner_tutorials | 5f770c15bef9906b667dd6a7cb0b12eeccfb37bb | [
"Apache-2.0"
] | null | null | null | cpp/speech/text_to_speech/source/text_to_speech.cpp | ortelio/rapp_beginner_tutorials | 5f770c15bef9906b667dd6a7cb0b12eeccfb37bb | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2015 RAPP
*
* 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 <rapp/cloud/service_controller.hpp>
#include <rapp/cloud/text_to_speech.hpp>
/*
* \brief Example to recognise words from an audio file with Google
*/
int main()
{
/*
* Construct the platform info setting the hostname/IP, port and authentication token
* Then proceed to create a cloud controller.
* We'll use this object to create cloud calls to the platform.
*/
rapp::cloud::platform info = {"rapp.ee.auth.gr", "9001", "rapp_token"};
rapp::cloud::service_controller ctrl(info);
/*
* Construct a lambda, std::function or bind your own functor.
* In this example we'll pass an inline lambda as the callback.
* All it does is receive a rapp::object::audio and we save it
*/
auto callback = [&](rapp::object::audio audio) {
if (audio.save("audio.wav")) {
std::cout << "File saved" << std::endl;
}
else {
std::cout << "Error: file not save\r\n";
}
};
/*
* We make a call to text_to_speech. We pass words or a sentence
* and it becomes an audio.
* For more information \see rapp::cloud::text_to_speech
*/
ctrl.make_call<rapp::cloud::text_to_speech>("hello world", "en", callback);
return 0;
}
| 34.754717 | 89 | 0.660152 | ortelio |
5240981bf238356625fd7f055df893fd7614289e | 8,415 | hpp | C++ | src/computationalMesh/meshReading/meshReading.hpp | tomrobin-teschner/AIM | 2090cc6be1facee60f1aa9bee924f44d700b5533 | [
"MIT"
] | null | null | null | src/computationalMesh/meshReading/meshReading.hpp | tomrobin-teschner/AIM | 2090cc6be1facee60f1aa9bee924f44d700b5533 | [
"MIT"
] | null | null | null | src/computationalMesh/meshReading/meshReading.hpp | tomrobin-teschner/AIM | 2090cc6be1facee60f1aa9bee924f44d700b5533 | [
"MIT"
] | null | null | null | // This file is part of Artificial-based Incompressibile Methods (AIM), a CFD solver for exact projection
// methods based on hybrid Artificial compressibility and Pressure Projection methods.
// (c) by Tom-Robin Teschner 2021. This file is distribuited under the MIT license.
#pragma once
// c++ include headers
#include <filesystem>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
// third-party include headers
#include "cgnslib.h"
// AIM include headers
#include "src/types/types.hpp"
// concept definition
namespace AIM {
namespace Mesh {
/**
* \class MeshReader
* \brief This class processes a CGNS file from which the mesh properties are read
* \ingroup mesh
*
* This class provides a wrapper around the cgns file format and reads mesh data from these files. The constructor takes
* two arguments, the first being the location of the mesh and the second the dimensionality of the mesh. Then, the user
* can load different aspects from the file. No data is stored in this class and it is the responsibility of the calling
* method to store the data after calling it (i.e. there are no getter or setter methods implemented). The example below
* shows how this class may be used.
*
* \code
* // 2D mesh file
* auto meshReader = AIM::Mesh::MeshReader{std::filesystem::path("path/to/file.cgns"), AIM::Enum::Dimension::Two};
* // 3D mesh file
* auto meshReader = AIM::Mesh::MeshReader{std::filesystem::path("path/to/file.cgns"), AIM::Enum::Dimension::Three};
* ...
* // read coordinates
* auto x = meshReader.readCoordinate<AIM::Enum::Coordinate::X>();
* auto y = meshReader.readCoordinate<AIM::Enum::Coordinate::Y>();
* auto z = meshReader.readCoordinate<AIM::Enum::Coordinate::Z>();
* ...
* // read connectivity table
* auto connectivityTable = meshReader.readConnectivityTable();
* ...
* // read boundary conditions
* auto bc = meshReader.readBoundaryConditions();
* ...
* // read boundary condition connectivity array
* auto bcc = meshReader.readBoundaryConditionConnectivity();
* \endcode
*
* The coordinate arrays require a template index parameter to identify which coordinate to read (i.e x = 0, y = 1, and
* z = 2). This can be circumvented by using a built-in enum to aid documentation, i.e. AIM::Enum::Coordinate::X,
* AIM::Enum::Coordinate::Y or AIM::Enum::Coordinate::Z. It is a one dimensional array of type std::vector<FloatType>
* where FloatType is typically a wrapper around double, but can be set to float in the src/types/types.hpp file.
*
* \code
* // loop over coordinates
* auto x = meshReader.readCoordinate<AIM::Enum::Coordinate::X>();
* for (const auto &c : x)
* std::cout << "coordinate x: " << c << std::endl;
*
* // loop using classical for loop
* for (int i = 0; i < x.size(); ++i)
* std::cout << "coordinate x[" << i << "]: " << x[i] << std::endl;
* \endcode
*
* The connectivity table is a 2D vector with the first index being the number of cells in the mesh and the second index
* being the number of vertices for the current cell type. For example, if we have a mesh with two elements, one tri and
* one quad element, we may have the following structure:
*
* \code
* auto connectivityTable = meshReader.readConnectivityTable();
*
* // first element is a tri element with 3 vertices
* assert(connectivityTable[0].size() == 3);
*
* // second element is a quad element with 4 vertices
* assert(connectivityTable[1].size() == 4);
*
* auto cell_0_vertex_0 = connectivityTable[0][0];
* auto cell_0_vertex_1 = connectivityTable[0][1];
* auto cell_0_vertex_2 = connectivityTable[0][2];
*
* auto cell_1_vertex_0 = connectivityTable[1][0];
* auto cell_1_vertex_1 = connectivityTable[1][1];
* auto cell_1_vertex_2 = connectivityTable[1][2];
* auto cell_1_vertex_3 = connectivityTable[1][3];
* \endcode
*
* The boundary conditions are read into two different arrays. The first will provide information about the type
* and boundary name and is stored in a std::vector<std::pair<int, std::string>>. The first index of the pair is an int
* whose boundary condition can be queried using the build in enums. The second argument is the name of the boundary
* condition assigned at the meshing stage. Example usage:
*
* \code
* auto bc = meshReader.readBoundaryConditions();
*
* for (const auto &boundary : bc) {
* if (boundary.first == AIM::Enum::BoundaryCondition::Wall)
* std::cout << "Wall BC with name: " << boundary.second;
* ...
* // other available types are:
* auto inletBC = AIM::Enum::BoundaryCondition::Inlet;
* auto outletBC = AIM::Enum::BoundaryCondition::Outlet;
* auto symmetryBC = AIM::Enum::BoundaryCondition::Symmetry;
*
* // see src/types/enums.hpp for a full list of supported boundary conditions
* }
* \endcode
*
* The second part of the boundary condition readings provide the elements that are connected to each boundary condition
* read above. For each boundary condition, we have a std::vector that provides us with the element indices attached to
* that boundary condition. Example usage:
*
* \code
* auto bc = meshReader.readBoundaryConditions();
* auto bcc = meshReader.readBoundaryConditionConnectivity();
*
* assert(bc.size() == bcc.size() && "Boundary condition info and connectivity must have the same size");
*
* for (int i = 0; i < bcc.size(); ++i) {
* std::cout << "Elements connected to " << bc[i].second << " are: ";
* for (const auto& e : bcc[i])
* std::cout << e << " ";
* std::cout << std::endl;
* }
* \endcode
*/
class MeshReader {
/// \name Custom types used in this class
/// @{
public:
using CoordinateType = typename std::vector<AIM::Types::FloatType>;
using ConnectivityTableType = typename std::vector<std::vector<AIM::Types::UInt>>;
using BoundaryConditionType = typename std::vector<std::pair<int, std::string>>;
using BoundaryConditionConnectivityType = typename std::vector<std::vector<AIM::Types::CGNSInt>>;
/// @}
/// \name Constructors and destructors
/// @{
public:
MeshReader(short int dimensions);
~MeshReader();
/// @}
/// \name API interface that exposes behaviour to the caller
/// @{
public:
template <int Index>
auto readCoordinate() -> CoordinateType;
auto readConnectivityTable() -> ConnectivityTableType;
auto readBoundaryConditions() -> BoundaryConditionType;
auto readBoundaryConditionConnectivity() -> BoundaryConditionConnectivityType;
/// @}
/// \name Getters and setters
/// @{
public:
auto getDimensions() const -> short int { return dimensions_; }
/// @}
/// \name Overloaded operators
/// @{
/// @}
/// \name Private or protected implementation details, not exposed to the caller
/// @{
private:
auto readParameters() -> void;
auto getNumberOfBases() -> AIM::Types::UInt;
auto getNumberOfZones() -> AIM::Types::UInt;
auto getNumberOfVertices() -> AIM::Types::UInt;
auto getNumberOfCells() -> AIM::Types::UInt;
auto getNumberOfSections() -> AIM::Types::UInt;
auto getNumberOfBoundaryConditions() -> AIM::Types::UInt;
auto getNumberOfFamilies() -> AIM::Types::UInt;
auto getCellType(AIM::Types::UInt section) -> CGNS_ENUMT(ElementType_t);
auto addCurrentCellTypeToConnectivityTable(
AIM::Types::UInt section, AIM::Types::UInt numberOfVerticesPerCell, ConnectivityTableType& connectivity) -> void;
auto getNumberOfConnectivitiesForCellType(AIM::Types::UInt section, AIM::Types::UInt numVerticesPerCell)
-> AIM::Types::UInt;
auto writeConnectivityTable(AIM::Types::UInt section, AIM::Types::UInt elementSize,
AIM::Types::UInt numberOfVerticesPerCell, ConnectivityTableType& connectivity) -> void;
auto getCurrentBoundaryType(AIM::Types::UInt boundary)
-> std::tuple<CGNS_ENUMT(BCType_t), std::string, AIM::Types::UInt>;
auto getCurrentFamilyType(AIM::Types::UInt boundary) -> CGNS_ENUMT(BCType_t);
auto writeBoundaryConnectivityIntoArray(AIM::Types::UInt boundary, BoundaryConditionConnectivityType& bcc) -> void;
/// @}
/// \name Encapsulated data (private or protected variables)
/// @{
private:
const short int dimensions_{0};
std::filesystem::path meshFile_{""};
int fileIndex_{0};
AIM::Types::UInt numberOfVertices_{0};
AIM::Types::UInt numberOfCells_{0};
AIM::Types::UInt numberOfBCs_{0};
AIM::Types::UInt numberOfFamilies_{0};
/// @}
};
} // namespace Mesh
} // end namespace AIM
#include "meshReading.tpp" | 39.507042 | 120 | 0.706239 | tomrobin-teschner |
5243eb71583b16949d662fa38df0917d621d6c3a | 1,413 | cpp | C++ | experiments/nrf24receiver/src/main.cpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | 4 | 2016-12-10T13:20:52.000Z | 2019-10-25T19:47:44.000Z | experiments/nrf24receiver/src/main.cpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | null | null | null | experiments/nrf24receiver/src/main.cpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | 1 | 2019-05-03T17:31:38.000Z | 2019-05-03T17:31:38.000Z | #include <Arduino.h>
#include <SPI.h>
#include <power.h>
#include "RF24.h"
#include <printf.h>
#define NRF_CE 9 // Chip Enbale pin for NRF radio
#define NRF_CSN 10 // SPI Chip Select for NFR radio
void initializeNrfRadio();
RF24 nrf(NRF_CE, NRF_CSN);
uint8_t address[6] = "1Node";
uint8_t rcvbuf[40];
unsigned long prev;
void setup() {
Serial.begin(115200);
printf_begin();
initializeNrfRadio();
nrf.startListening();
}
void loop() {
if (nrf.available()) {
uint8_t len;
while (nrf.available())
{
// Fetch the payload, and see if this was the last one.
len = nrf.getDynamicPayloadSize();
nrf.read(rcvbuf, len);
if(len > 4) {
break;
}
unsigned long cur = *(unsigned long*)rcvbuf;
// Spew it
printf("Got payload size=%i value=%ld\n", len, cur);
if(cur - prev > 1) {
printf("Missed packet! %ld\n", cur);
}
prev = cur;
nrf.writeAckPayload(1, &prev, sizeof(prev));
}
}
}
void initializeNrfRadio() {
nrf.begin();
nrf.setPALevel(RF24_PA_MAX);
nrf.setDataRate(RF24_2MBPS);
nrf.setPayloadSize(32);
nrf.enableDynamicPayloads();
nrf.enableAckPayload();
nrf.openReadingPipe(1, address);
// Use auto ACKs to avoid sleeping between radio transmissions
nrf.setAutoAck(true);
nrf.setRetries(5, 15); // Retry every 1ms for maximum of 3ms + send times (~1ms)
}
| 21.089552 | 83 | 0.62845 | chacal |
524402f2959773a724d40a8cdf1f45393030bac8 | 5,073 | cpp | C++ | lib/src/cyber/parse.cpp | yuri-sevatz/cyberpunk-cpp | b0c9a95c012660bfd21c24ac3a69287330d3b3bd | [
"BSD-2-Clause"
] | 5 | 2021-06-12T10:29:58.000Z | 2022-03-03T13:21:57.000Z | lib/src/cyber/parse.cpp | yuri-sevatz/cyber_breach | b0c9a95c012660bfd21c24ac3a69287330d3b3bd | [
"BSD-2-Clause"
] | null | null | null | lib/src/cyber/parse.cpp | yuri-sevatz/cyber_breach | b0c9a95c012660bfd21c24ac3a69287330d3b3bd | [
"BSD-2-Clause"
] | 1 | 2021-02-21T09:45:37.000Z | 2021-02-21T09:45:37.000Z | #ifdef _WIN32
#include <io.h>
#endif
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <boost/algorithm/hex.hpp>
#include <opencv2/text/ocr.hpp>
#include <cyber/layout.hpp>
#include <cyber/parse.hpp>
namespace {
matrix_type parse_matrix(cv::text::OCRTesseract & ocr, cv::Mat image, matrix_length_type matrix_length) {
matrix_type matrix(boost::extents[matrix_length][matrix_length]);
// The position of the matrix left border
const cv::Point matrix_cell_begin(
matrix_border_topcenter.x - (matrix_cell_size.width / 2) * matrix_length + 2,
matrix_border_topcenter.y + matrix_margin_topleft.height
);
// The vector between the first cell and the ith + 1 cell
const cv::Size matrix_cell_step(
matrix_cell_size.width + matrix_cell_padding.width,
matrix_cell_size.height + matrix_cell_padding.height
);
for (int row = 0; row != matrix_length; ++row) {
for(int col = 0; col != matrix_length; ++col) {
const cv::Rect cell_rect = cv::Rect(
matrix_cell_begin.x + col * matrix_cell_step.width,
matrix_cell_begin.y + row * matrix_cell_step.height,
matrix_cell_size.width,
matrix_cell_size.height
);
const cv::Mat cell = image(cell_rect);
cv::Mat bitwise_not;
cv::bitwise_not(cell, bitwise_not);
std::string output_text;
ocr.run(bitwise_not, output_text);
output_text.erase(std::remove_if(output_text.begin(), output_text.end(), [](char x){return std::isspace(x);}), output_text.end());
if (output_text.size() % 2 == 0) {
std::string bytes = boost::algorithm::unhex(output_text);
if (bytes.size() == 1) {
matrix[row][col] = static_cast<byte_type>(bytes.front());
}
}
}
}
return matrix;
}
sequences_type parse_sequences(cv::text::OCRTesseract & ocr, cv::Mat image, matrix_length_type matrix_length, sequence_lengths_type sequence_lengths) {
sequences_type sequences(sequence_lengths.size());
// The position of the matrix right border
const int matrix_border_right = matrix_margin_bottomright.width + matrix_border_topcenter.x + (matrix_length * matrix_cell_size.width) / 2;
// The position of the sequences left border
const int sequences_border_left = matrix_border_right + sequences_border_matrix_left_offset;
// The coordinate of the first cell
const cv::Point sequence_cell_begin(
sequences_border_left + sequences_margin_topleft.width,
sequences_border_top + sequences_margin_topleft.height
);
// The vector between the first cell and the ith + 1 cell
const cv::Size sequence_cell_step(
sequence_cell_size.width + sequence_cell_padding.width,
sequence_cell_size.height + sequence_cell_padding.height
);
// For each known cell in the row
for (int row = 0; row != sequence_lengths.size(); ++row) {
sequences[row].resize(sequence_lengths[row]);
for(int col = 0; col != sequence_lengths[row]; ++col) {
const cv::Rect cell_rect(
sequence_cell_begin.x + col * sequence_cell_step.width,
sequence_cell_begin.y + row * sequence_cell_step.height,
sequence_cell_size.width,
sequence_cell_size.height
);
const cv::Mat cell = image(cell_rect);
cv::Mat bitwise_not;
cv::bitwise_not(cell, bitwise_not);
cv::Mat grayscale;
cv::cvtColor(bitwise_not, grayscale, cv::COLOR_BGR2GRAY);
cv::Mat enhance;
cv::adaptiveThreshold(grayscale, enhance, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY, 3, 10);
std::string output_text;
ocr.run(enhance, output_text);
output_text.erase(std::remove_if(output_text.begin(), output_text.end(), [](char x){return std::isspace(x);}), output_text.end());
if (output_text.size() % 2 == 0) {
std::string bytes = boost::algorithm::unhex(output_text);
if (bytes.size() == 1) {
sequences[row][col] = static_cast<byte_type>(bytes.front());
}
}
}
}
return sequences;
}
} // namespace
parsed_type parse(cv::Mat image, matrix_length_type matrix_length, sequence_lengths_type sequence_lengths) {
const int old = ::dup(2);
FILE * file;
#ifdef _WIN32
::fopen_s(&file, "nul", "w");
#else
file = ::fopen("/dev/null", "w");
#endif
::dup2(::fileno(file), 2);
auto ocr = cv::text::OCRTesseract::create(NULL, "Latin", "0123456789ABCDEF", cv::text::OEM_DEFAULT, cv::text::PSM_SINGLE_BLOCK);
const parsed_type result {
parse_matrix(*ocr, image, matrix_length),
parse_sequences(*ocr, image, matrix_length, sequence_lengths)
};
ocr.reset();
::fflush(stderr);
::fclose(file);
::dup2(old, 2);
return result;
}
| 34.277027 | 151 | 0.631382 | yuri-sevatz |
5248a9267eb09f75ad898a6faead5b4f3934d5f8 | 666 | cpp | C++ | ch02/build_in_types.cpp | imshenzhuo/CppPrimer | 87c74c0a36223e86571c2aedd9da428c06b04f4d | [
"CC0-1.0"
] | 3 | 2019-09-21T13:03:57.000Z | 2020-04-05T02:42:53.000Z | ch02/build_in_types.cpp | imshenzhuo/CppPrimer | 87c74c0a36223e86571c2aedd9da428c06b04f4d | [
"CC0-1.0"
] | null | null | null | ch02/build_in_types.cpp | imshenzhuo/CppPrimer | 87c74c0a36223e86571c2aedd9da428c06b04f4d | [
"CC0-1.0"
] | null | null | null | /*************************************************************************
> File Name: build_in_types.cpp
> Author: ma6174
> Mail: ma6174@163.com
> Created Time: 2019年08月26日 星期一 09时54分25秒
************************************************************************/
#include<iostream>
using namespace std;
int main()
{
cout<<sizeof(bool)<<endl;
cout<<sizeof(char)<<endl;
cout<<sizeof(signed char)<<endl;
cout<<sizeof(unsigned char)<<endl;
cout<<sizeof(short)<<endl;
cout<<sizeof(int)<<endl;
cout<<sizeof(long)<<endl;
cout<<sizeof(long long)<<endl;
cout<<sizeof(float)<<endl;
cout<<sizeof(double)<<endl;
cout<<sizeof(long double)<<endl;
}
| 26.64 | 74 | 0.527027 | imshenzhuo |
524b177fb74d415d855d19cebdeca29a669facf1 | 546 | cc | C++ | src/cpu/hamaji/util.cc | puyoai/puyoai | 575068dffab021cd42b0178699d480a743ca4e1f | [
"CC-BY-4.0"
] | 115 | 2015-02-21T15:08:26.000Z | 2022-02-05T01:38:10.000Z | src/cpu/hamaji/util.cc | haripo/puyoai | 575068dffab021cd42b0178699d480a743ca4e1f | [
"CC-BY-4.0"
] | 214 | 2015-01-16T04:53:35.000Z | 2019-03-23T11:39:59.000Z | src/cpu/hamaji/util.cc | haripo/puyoai | 575068dffab021cd42b0178699d480a743ca4e1f | [
"CC-BY-4.0"
] | 56 | 2015-01-16T05:14:13.000Z | 2020-09-22T07:22:49.000Z | #include "util.h"
#include <stdio.h>
#include <stdarg.h>
string ssprintf(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
char buf[4097];
int len = vsnprintf(buf, 4096, fmt, ap);
buf[len] = '\0';
va_end(ap);
return buf;
}
void split(const string& str, const string& delim, vector<string>* output) {
size_t prev = 0;
while (true) {
size_t found = str.find(delim, prev);
output->push_back(str.substr(prev, found - prev));
if (found == string::npos) {
break;
}
prev = found + delim.size();
}
}
| 20.222222 | 76 | 0.604396 | puyoai |
524cdc7a8b2796054517d198d905195c92e4fa79 | 617 | hpp | C++ | contrib/backends/nntpchan-daemon/include/nntpchan/template_engine.hpp | majestrate/nntpchan | f92f68c3cdce4b7ce6d4121ca4356b36ebcd933f | [
"MIT"
] | 233 | 2015-08-06T02:51:52.000Z | 2022-02-14T11:29:13.000Z | contrib/backends/nntpchan-daemon/include/nntpchan/template_engine.hpp | Revivify/nntpchan | 0d555bb88a2298dae9aacf11348e34c52befa3d8 | [
"MIT"
] | 98 | 2015-09-19T22:29:00.000Z | 2021-06-12T09:43:13.000Z | contrib/backends/nntpchan-daemon/include/nntpchan/template_engine.hpp | Revivify/nntpchan | 0d555bb88a2298dae9aacf11348e34c52befa3d8 | [
"MIT"
] | 49 | 2015-08-06T02:51:55.000Z | 2020-03-11T04:23:56.000Z | #ifndef NNTPCHAN_TEMPLATE_ENGINE_HPP
#define NNTPCHAN_TEMPLATE_ENGINE_HPP
#include "file_handle.hpp"
#include "model.hpp"
#include <any>
#include <map>
#include <memory>
#include <string>
namespace nntpchan
{
struct TemplateEngine
{
virtual ~TemplateEngine() {};
virtual bool WriteBoardPage(const nntpchan::model::BoardPage & page, const FileHandle_ptr &out) = 0;
virtual bool WriteThreadPage(const nntpchan::model::Thread & thread, const FileHandle_ptr &out) = 0;
};
typedef std::unique_ptr<TemplateEngine> TemplateEngine_ptr;
TemplateEngine * CreateTemplateEngine(const std::string &dialect);
}
#endif
| 22.035714 | 102 | 0.774716 | majestrate |
524eaf36a35357f069d8871bb54c4172835435c2 | 5,574 | cc | C++ | generated/aisClassBPositionReport.cc | rkuris/n2klib | e465a8f591d135d2e632186309d69a28ff7c9c4e | [
"MIT"
] | null | null | null | generated/aisClassBPositionReport.cc | rkuris/n2klib | e465a8f591d135d2e632186309d69a28ff7c9c4e | [
"MIT"
] | null | null | null | generated/aisClassBPositionReport.cc | rkuris/n2klib | e465a8f591d135d2e632186309d69a28ff7c9c4e | [
"MIT"
] | null | null | null | // class AisClassBPositionReport
// Automatically generated by mkmsgs - DO NOT EDIT
// Description: AIS Class B Position Report
#include "../n2k.h"
namespace n2k {
class AisClassBPositionReport : public Message {
public:
enum class RepeatIndicator:unsigned char {
Initial = 0,
First_retransmission = 1,
Second_retransmission = 2,
Final_retransmission = 3
};
enum class PositionAccuracy:unsigned char {
Low = 0,
High = 1
};
enum class Raim:unsigned char {
not_in_use = 0,
in_use = 1
};
enum class TimeStamp:unsigned char {
Not_available = 60,
Manual_input_mode = 61,
Dead_reckoning_mode = 62,
Positioning_system_is_inoperative = 63
};
enum class AisTransceiverInformation:unsigned char {
Channel_A_VDL_reception = 0,
Channel_B_VDL_reception = 1,
Channel_A_VDL_transmission = 2,
Channel_B_VDL_transmission = 3,
Own_information_not_broadcast = 4,
Reserved = 5
};
enum class UnitType:unsigned char {
SOTDMA = 0,
CS = 1
};
enum class IntegratedDisplay:unsigned char {
No = 0,
Yes = 1
};
enum class Dsc:unsigned char {
No = 0,
Yes = 1
};
enum class Band:unsigned char {
top_525_kHz_of_marine_band = 0,
entire_marine_band = 1
};
enum class CanHandleMsg22:unsigned char {
No = 0,
Yes = 1
};
enum class AisMode:unsigned char {
Autonomous = 0,
Assigned = 1
};
enum class AisCommunicationState:unsigned char {
SOTDMA = 0,
ITDMA = 1
};
AisClassBPositionReport() {};
AisClassBPositionReport(const Message &m) : Message(m) {};
void setMessageId(unsigned char value) { Set(value,0,6); }
unsigned char getMessageId() const { return Get(0,6); };
void setRepeatIndicator(RepeatIndicator value) { Set((unsigned char)value,6,2); }
RepeatIndicator getRepeatIndicator() const { return (RepeatIndicator)Get(6,2); };
void setUserId(unsigned long value) { Set(value,8,32); }
unsigned long getUserId() const { return Get(8,32); };
void setLongitude(double value) { Set(value/1E-07,40,32); }
double getLongitude() const { return 1E-07 * Get(40,32); };
void setLatitude(double value) { Set(value/1E-07,72,32); }
double getLatitude() const { return 1E-07 * Get(72,32); };
void setPositionAccuracy(PositionAccuracy value) { Set((unsigned char)value,104,1); }
PositionAccuracy getPositionAccuracy() const { return (PositionAccuracy)Get(104,1); };
void setRaim(Raim value) { Set((unsigned char)value,105,1); }
Raim getRaim() const { return (Raim)Get(105,1); };
void setTimeStamp(TimeStamp value) { Set((unsigned char)value,106,6); }
TimeStamp getTimeStamp() const { return (TimeStamp)Get(106,6); };
void setCogRadians(double value) { Set(value/0.0001,112,16); }
double getCogRadians() const { return 0.0001 * Get(112,16); }
void setCogDegrees(double value) { Set(value/0.00572958,112,16); }
double getCogDegrees() const { return 0.00572958 * Get(112,16); };
void setSogMetersPerSecond(double value) { Set(value/0.01,128,16); }
double getSogMetersPerSecond() const { return 0.01 * Get(128,16); }
void setSogKnots(double value) { Set(value/0.0194384,128,16); }
double getSogKnots() const { return 0.0194384 * Get(128,16); };
void setCommunicationState(unsigned long value) { Set(value,144,19); }
unsigned long getCommunicationState() const { return Get(144,19); };
void setAisTransceiverInformation(AisTransceiverInformation value) { Set((unsigned char)value,163,5); }
AisTransceiverInformation getAisTransceiverInformation() const { return (AisTransceiverInformation)Get(163,5); };
void setHeadingRadians(double value) { Set(value/0.0001,168,16); }
double getHeadingRadians() const { return 0.0001 * Get(168,16); }
void setHeadingDegrees(double value) { Set(value/0.00572958,168,16); }
double getHeadingDegrees() const { return 0.00572958 * Get(168,16); };
void setRegionalApplication(unsigned char value) { Set(value,184,8); }
unsigned char getRegionalApplication() const { return Get(184,8); };
void setRegionalApplication_1(unsigned char value) { Set(value,192,2); }
unsigned char getRegionalApplication_1() const { return Get(192,2); };
void setUnitType(UnitType value) { Set((unsigned char)value,194,1); }
UnitType getUnitType() const { return (UnitType)Get(194,1); };
void setIntegratedDisplay(IntegratedDisplay value) { Set((unsigned char)value,195,1); }
IntegratedDisplay getIntegratedDisplay() const { return (IntegratedDisplay)Get(195,1); };
void setDsc(Dsc value) { Set((unsigned char)value,196,1); }
Dsc getDsc() const { return (Dsc)Get(196,1); };
void setBand(Band value) { Set((unsigned char)value,197,1); }
Band getBand() const { return (Band)Get(197,1); };
void setCanHandleMsg22(CanHandleMsg22 value) { Set((unsigned char)value,198,1); }
CanHandleMsg22 getCanHandleMsg22() const { return (CanHandleMsg22)Get(198,1); };
void setAisMode(AisMode value) { Set((unsigned char)value,199,1); }
AisMode getAisMode() const { return (AisMode)Get(199,1); };
void setAisCommunicationState(AisCommunicationState value) { Set((unsigned char)value,200,1); }
AisCommunicationState getAisCommunicationState() const { return (AisCommunicationState)Get(200,1); };
static const pgn_t PGN = 129039;
static const PGNType Type = PGNType::Fast;
pgn_t getPGN() const { return PGN; }
};
}
| 41.597015 | 117 | 0.678507 | rkuris |
52538b9e11f80bfbc7629458198ad9823a0bdef1 | 1,128 | cpp | C++ | source/FAST/Examples/DataImport/importLineSetFromFile.cpp | SINTEFMedtek/FAST | d4c1ec49bd542f78d84c00e990bbedd2126cfffa | [
"BSD-2-Clause"
] | 3 | 2019-12-13T07:53:51.000Z | 2020-02-05T09:11:58.000Z | source/FAST/Examples/DataImport/importLineSetFromFile.cpp | SINTEFMedtek/FAST | d4c1ec49bd542f78d84c00e990bbedd2126cfffa | [
"BSD-2-Clause"
] | 1 | 2020-02-05T09:28:37.000Z | 2020-02-05T09:28:37.000Z | source/FAST/Examples/DataImport/importLineSetFromFile.cpp | SINTEFMedtek/FAST | d4c1ec49bd542f78d84c00e990bbedd2126cfffa | [
"BSD-2-Clause"
] | 1 | 2020-12-10T12:40:59.000Z | 2020-12-10T12:40:59.000Z | /**
* Examples/DataImport/importLineSetFromFile.cpp
*
* If you edit this example, please also update the wiki and source code file in the repository.
*/
#include <FAST/Tools/CommandLineParser.hpp>
#include "FAST/Importers/VTKMeshFileImporter.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
using namespace fast;
int main(int argc, char** argv) {
CommandLineParser parser("Import line set from file");
parser.addPositionVariable(1, "filename", Config::getTestDataPath() + "centerline.vtk");
parser.parse(argc, argv);
// Import line set from vtk file
auto importer = VTKMeshFileImporter::New();
importer->setFilename(parser.get("filename"));
// Renderer
auto renderer = LineRenderer::New();
renderer->addInputConnection(importer->getOutputPort());
// Setup window
auto window = SimpleWindow::New();
window->addRenderer(renderer);
#ifdef FAST_CONTINUOUS_INTEGRATION
// This will automatically close the window after 5 seconds, used for CI testing
window->setTimeout(5*1000);
#endif
window->start();
}
| 32.228571 | 96 | 0.73227 | SINTEFMedtek |
52553b6f38c3f8ee78eaaa8614d9030dea1b79c4 | 1,916 | cpp | C++ | animation/viewComponent/picScaleComp.cpp | seaCheng/animation- | 89a0cb0efbcfea202965a5851979ae6f1b67f8f0 | [
"BSD-3-Clause"
] | 6 | 2021-12-08T03:09:47.000Z | 2022-02-24T03:51:14.000Z | animation/viewComponent/picScaleComp.cpp | seaCheng/animation- | 89a0cb0efbcfea202965a5851979ae6f1b67f8f0 | [
"BSD-3-Clause"
] | null | null | null | animation/viewComponent/picScaleComp.cpp | seaCheng/animation- | 89a0cb0efbcfea202965a5851979ae6f1b67f8f0 | [
"BSD-3-Clause"
] | null | null | null | #include "picScaleComp.h"
#include <QLabel>
#include <QHBoxLayout>
#include "aspectRatioPixmapLabel.h"
#include "pictureItem.h"
#include "pictureItemcontroller.h"
PicScaleComp::PicScaleComp(PictureItem* item, QWidget *parent)
:QFrame(parent),
m_item(item), m_controller(std::make_unique<PictureItemController>(item, this))
{
initial();
}
void PicScaleComp::paintEvent(QPaintEvent *event)
{
QFrame::paintEvent(event);
}
void PicScaleComp::mouseReleaseEvent(QMouseEvent *ev)
{
QFrame::mouseReleaseEvent(ev);
emit s_clicked();
}
void PicScaleComp::setPicIndexInterval(QString index, QString interval)
{
m_labelLeft->setText(index);
m_labelRight->setText(interval);
}
void PicScaleComp::setPic(QPixmap pic)
{
m_lPic->setPixmapLabel(pic);
}
void PicScaleComp::initial()
{
setObjectName("PicScaleComp");
m_frameBottom = new QFrame();
m_frameBottom->setFrameShape(NoFrame);
m_frameBottom->setLineWidth(0);
m_frameBottom->setFixedHeight(40);
m_layout = new QVBoxLayout(this);
m_layout->setContentsMargins(12,12,12,5);
m_layout->setSpacing(0);
m_labelLeft = new QLabel();
m_labelLeft->setAlignment(Qt::AlignCenter);
m_labelLeft->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
m_labelRight = new QLabel();
m_labelRight->setAlignment(Qt::AlignCenter);
m_labelRight->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
QHBoxLayout * layout = new QHBoxLayout();
layout->setContentsMargins(0,0,0,0);
layout->setSpacing(0);
m_frameBottom->setLayout(layout);
layout->addWidget(m_labelLeft);
layout->addWidget(m_labelRight);
m_lPic = new AspectRatioPixmapLabel();
m_lPic->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_layout->addWidget(m_lPic);
m_layout->addWidget(m_frameBottom);
}
PictureItem* PicScaleComp::getPictureItem()
{
return m_item;
}
| 25.210526 | 83 | 0.730167 | seaCheng |
525a74659773292687da9bb529964f25e41707ee | 4,862 | cpp | C++ | libnaucrates/src/md/CMDIdScCmp.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-05T10:08:56.000Z | 2019-03-05T10:08:56.000Z | libnaucrates/src/md/CMDIdScCmp.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libnaucrates/src/md/CMDIdScCmp.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2013 EMC Corp.
//
// @filename:
// CMDIdScCmp.cpp
//
// @doc:
// Implementation of mdids for scalar comparisons functions
//---------------------------------------------------------------------------
#include "naucrates/md/CMDIdScCmp.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
using namespace gpos;
using namespace gpmd;
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::CMDIdScCmp
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CMDIdScCmp::CMDIdScCmp
(
CMDIdGPDB *pmdidLeft,
CMDIdGPDB *pmdidRight,
IMDType::ECmpType ecmpt
)
:
m_pmdidLeft(pmdidLeft),
m_pmdidRight(pmdidRight),
m_ecmpt(ecmpt),
m_str(m_wszBuffer, GPOS_ARRAY_SIZE(m_wszBuffer))
{
GPOS_ASSERT(pmdidLeft->FValid());
GPOS_ASSERT(pmdidRight->FValid());
GPOS_ASSERT(IMDType::EcmptOther != ecmpt);
GPOS_ASSERT(pmdidLeft->Sysid().FEquals(pmdidRight->Sysid()));
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::~CMDIdScCmp
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CMDIdScCmp::~CMDIdScCmp()
{
m_pmdidLeft->Release();
m_pmdidRight->Release();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::Serialize
//
// @doc:
// Serialize mdid into static string
//
//---------------------------------------------------------------------------
void
CMDIdScCmp::Serialize()
{
// serialize mdid as SystemType.mdidLeft;mdidRight;CmpType
m_str.AppendFormat
(
GPOS_WSZ_LIT("%d.%d.%d.%d;%d.%d.%d;%d"),
Emdidt(),
m_pmdidLeft->OidObjectId(),
m_pmdidLeft->UlVersionMajor(),
m_pmdidLeft->UlVersionMinor(),
m_pmdidRight->OidObjectId(),
m_pmdidRight->UlVersionMajor(),
m_pmdidRight->UlVersionMinor(),
m_ecmpt
);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::Wsz
//
// @doc:
// Returns the string representation of the mdid
//
//---------------------------------------------------------------------------
const WCHAR *
CMDIdScCmp::Wsz() const
{
return m_str.Wsz();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::PmdidLeft
//
// @doc:
// Returns the source type id
//
//---------------------------------------------------------------------------
IMDId *
CMDIdScCmp::PmdidLeft() const
{
return m_pmdidLeft;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::PmdidRight
//
// @doc:
// Returns the destination type id
//
//---------------------------------------------------------------------------
IMDId *
CMDIdScCmp::PmdidRight() const
{
return m_pmdidRight;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::UlHash
//
// @doc:
// Computes the hash value for the metadata id
//
//---------------------------------------------------------------------------
ULONG
CMDIdScCmp::UlHash() const
{
return gpos::UlCombineHashes
(
Emdidt(),
gpos::UlCombineHashes(m_pmdidLeft->UlHash(), m_pmdidRight->UlHash())
);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::FEquals
//
// @doc:
// Checks if the mdids are equal
//
//---------------------------------------------------------------------------
BOOL
CMDIdScCmp::FEquals
(
const IMDId *pmdid
)
const
{
if (NULL == pmdid || EmdidScCmp != pmdid->Emdidt())
{
return false;
}
const CMDIdScCmp *pmdidScCmp = CMDIdScCmp::PmdidConvert(pmdid);
return m_pmdidLeft->FEquals(pmdidScCmp->PmdidLeft()) &&
m_pmdidRight->FEquals(pmdidScCmp->PmdidRight()) &&
m_ecmpt == pmdidScCmp->Ecmpt();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::Serialize
//
// @doc:
// Serializes the mdid as the value of the given attribute
//
//---------------------------------------------------------------------------
void
CMDIdScCmp::Serialize
(
CXMLSerializer * pxmlser,
const CWStringConst *pstrAttribute
)
const
{
pxmlser->AddAttribute(pstrAttribute, &m_str);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdScCmp::OsPrint
//
// @doc:
// Debug print of the id in the provided stream
//
//---------------------------------------------------------------------------
IOstream &
CMDIdScCmp::OsPrint
(
IOstream &os
)
const
{
os << "(" << m_str.Wsz() << ")";
return os;
}
// EOF
| 22.719626 | 77 | 0.433155 | khannaekta |
525cb27c2ddd2bed9cf9436b0c1284064d608e15 | 2,384 | cpp | C++ | orm-cpp/orm/store_test/store_interface_test.cpp | ironbit/showcase-app | 3bb5fad9f616c04bdbec67b682713fbb671fce4a | [
"MIT"
] | null | null | null | orm-cpp/orm/store_test/store_interface_test.cpp | ironbit/showcase-app | 3bb5fad9f616c04bdbec67b682713fbb671fce4a | [
"MIT"
] | null | null | null | orm-cpp/orm/store_test/store_interface_test.cpp | ironbit/showcase-app | 3bb5fad9f616c04bdbec67b682713fbb671fce4a | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include <memory>
#include <cstring>
#include "orm/store/store.h"
#include "orm/store_mark/store.h"
#include "orm/store_test/person.h"
using ::testing::Return;
MATCHER_P(CompareProperty, expected, "") {
try {
for (const auto& attribute : PersonCoder::attributes) {
if (!(arg->get(attribute) == expected->get(attribute))) {
return false;
}
}
return true;
} catch(const std::bad_variant_access& e) {
std::cerr << e.what() << std::endl;
return false;
}
}
class StoreInterfaceTest : public ::testing::Test {
public:
// create data
const std::int64_t ID = 1234;
const std::int32_t AGE = 30;
const std::string NAME = "Christian";
const double HEIGHT = 1.80;
};
using ::testing::Matcher;
TEST_F(StoreInterfaceTest, EncodeTest) {
// retrieve mock
std::shared_ptr<orm::store::Store> store = std::make_shared<orm::store_mark::Store>();
auto& mock = static_cast<orm::store_mark::Store*>(store.get())->mock();
// populate data
Person person(ID);
person.age() = AGE;
person.name() = NAME;
person.height() = HEIGHT;
// create expected result
auto expectedProperty = orm::core::GenShareProperty({{PersonCoder::Age, AGE},
{PersonCoder::Name, NAME},
{PersonCoder::Height, HEIGHT}});
// test
EXPECT_CALL(mock, insert(ID, Matcher<std::shared_ptr<orm::core::Property>&&>(CompareProperty(expectedProperty))));
// execute main action
store->insert(person);
}
TEST_F(StoreInterfaceTest, DecodeTest) {
// retrieve mock
std::shared_ptr<orm::store::Store> store = std::make_shared<orm::store_mark::Store>();
auto& mock = static_cast<orm::store_mark::Store*>(store.get())->mock();
// populate data
Person person(ID);
// create expected result
auto expectedProperty = orm::core::GenShareProperty({{PersonCoder::Age, AGE},
{PersonCoder::Name, NAME},
{PersonCoder::Height, HEIGHT}});
// mock value
EXPECT_CALL(mock, query(ID))
.WillOnce(Return(expectedProperty));
// execute main action
store->query(person);
// test populated object
ASSERT_TRUE(person.identity() == ID);
ASSERT_TRUE(person.age() == AGE);
ASSERT_TRUE(person.name() == NAME);
ASSERT_TRUE(person.height() == HEIGHT);
}
| 27.72093 | 115 | 0.627936 | ironbit |
525e7c5607b680323acd83e64ef7159a3bbb638e | 545 | cpp | C++ | naked_asm/example.cpp | marziel/cpp-examples | 4c24639a9ec8807ed687e06e5fb96304ae34093a | [
"Unlicense"
] | 1 | 2020-02-22T12:05:52.000Z | 2020-02-22T12:05:52.000Z | naked_asm/example.cpp | marziel/cpp-examples | 4c24639a9ec8807ed687e06e5fb96304ae34093a | [
"Unlicense"
] | null | null | null | naked_asm/example.cpp | marziel/cpp-examples | 4c24639a9ec8807ed687e06e5fb96304ae34093a | [
"Unlicense"
] | null | null | null | #include <cstdio>
[[gnu::naked]] int check_sgx_support()
{
asm("\n\
push rbx \n\
push rcx \n\
mov rax, 7 \n\
xor rcx, rcx \n\
cpuid \n\
and rbx, 0x02 \n\
shr rbx, 1 \n\
mov rax, rbx \n\
pop rcx \n\
pop rbx \n\
ret \n\
");
}
int main()
{
printf("SGX supported?\t\t - %s\n", (check_sgx_support()) ? "YES" : "NO");
return 0;
}
| 20.961538 | 78 | 0.348624 | marziel |
525f92723cb8d105dbdb0f782835e8af287e3be4 | 644 | cpp | C++ | node_modules/lzz-gyp/lzz-source/smtc_GetNonTypeParam.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 3 | 2019-09-18T16:44:33.000Z | 2021-03-29T13:45:27.000Z | node_modules/lzz-gyp/lzz-source/smtc_GetNonTypeParam.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | null | null | null | node_modules/lzz-gyp/lzz-source/smtc_GetNonTypeParam.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 2 | 2019-03-29T01:06:38.000Z | 2019-09-18T16:44:34.000Z | // smtc_GetNonTypeParam.cpp
//
#include "smtc_GetNonTypeParam.h"
// semantic
#include "smtc_CheckParamName.h"
#include "smtc_CheckSpecFlags.h"
#include "smtc_CreateNonTypeParam.h"
#include "smtc_Message.h"
#define LZZ_INLINE inline
namespace smtc
{
ParamPtr getNonTypeParam (gram::SpecSel const & spec_sel, CvType const & cv_type, NamePtr const & name, gram::Block const & def_arg)
{
// no specifiers valid
checkValidSpecFlags (spec_sel, 0, msg::invalidNonTypeParamSpec);
// check name
checkParamName (name);
// return non-type param
return createNonTypeParam (0, cv_type, name, def_arg);
}
}
#undef LZZ_INLINE
| 24.769231 | 134 | 0.737578 | SuperDizor |
5261aedc5ba7563b9f11d36620eccc67e42321de | 1,177 | cpp | C++ | src/daisyHat.cpp | recursinging/daisyHat | 94a3a2f8da13ee4df372027058f2741c84493a0e | [
"MIT"
] | null | null | null | src/daisyHat.cpp | recursinging/daisyHat | 94a3a2f8da13ee4df372027058f2741c84493a0e | [
"MIT"
] | null | null | null | src/daisyHat.cpp | recursinging/daisyHat | 94a3a2f8da13ee4df372027058f2741c84493a0e | [
"MIT"
] | null | null | null | #include "daisyHat.h"
#include <daisy_seed.h>
namespace daisyhat
{
int numFailedAssertions = 0;
uint32_t startTime = 0;
daisy::DaisySeed* seed;
void StartTest(daisy::DaisySeed& _seed, const char* testName)
{
startTime = daisy::System::GetNow();
numFailedAssertions = 0;
seed = &_seed;
seed->SetLed(true);
StartLog(true);
daisy::System::Delay(3000);
PrintLine("=== Starting Test ===");
Print("> Name: ");
PrintLine(testName);
PrintLine("===");
}
void FinishTest()
{
const auto endTime = daisy::System::GetNow();
const auto testDuration = endTime - startTime;
PrintLine("=== Test Finished ===");
PrintLine("> numFailedAssertions = %d", numFailedAssertions);
PrintLine("> duration = %d ms", testDuration);
if (numFailedAssertions > 0)
PrintLine("> testResult = FAILURE");
else
PrintLine("> testResult = SUCCESS");
PrintLine("===");
seed->SetLed(false);
// trap processor in endless loop.
while (1)
{
};
}
} // namespace daisyhat | 25.042553 | 69 | 0.553951 | recursinging |
52621431098a8575346e7e54188cbab1feb2b0e5 | 12,088 | cc | C++ | test/sdk/message/subscribe_message-test.cc | iot-dsa-v2/sdk-dslink-cpp | d7734fba02237bd11bc887058f4d9573aac598d8 | [
"Apache-2.0"
] | 1 | 2018-02-09T21:20:31.000Z | 2018-02-09T21:20:31.000Z | test/sdk/message/subscribe_message-test.cc | iot-dsa-v2/sdk-dslink-cpp | d7734fba02237bd11bc887058f4d9573aac598d8 | [
"Apache-2.0"
] | 7 | 2017-11-20T22:22:12.000Z | 2018-03-21T13:00:06.000Z | test/sdk/message/subscribe_message-test.cc | iot-dsa-v2/sdk-dslink-cpp | d7734fba02237bd11bc887058f4d9573aac598d8 | [
"Apache-2.0"
] | null | null | null | #include "dsa/message.h"
#include "dsa/util.h"
#include <gtest/gtest.h>
using namespace dsa;
bool check_static_headers(SubscribeRequestMessage& message,
uint8_t* expected_values, size_t size) {
uint8_t buf[1024];
message.write(buf);
return (memcmp(expected_values, buf, size) == 0);
}
TEST(MessageTest, SubscribeRequestMessage) {
SubscribeRequestMessage subscribe_request;
EXPECT_EQ(0, subscribe_request.get_qos());
subscribe_request.set_qos(QosLevel::_2);
EXPECT_EQ(QosLevel::_2, subscribe_request.get_qos());
SubscribeOptions option = subscribe_request.get_subscribe_options();
EXPECT_EQ(QosLevel::_2, option.qos);
auto b = make_ref_<RefCountBytes>(256);
EXPECT_EQ(17, subscribe_request.size());
string_ path = "/a";
subscribe_request.set_target_path(path);
EXPECT_EQ(22, subscribe_request.size());
subscribe_request.write(b->data());
// parse a subscription message from the buffer
SubscribeRequestMessage subscribe_request2(&b->front(), b->size());
SubscribeOptions option2 = subscribe_request2.get_subscribe_options();
EXPECT_EQ(QosLevel::_2, option2.qos);
EXPECT_EQ(22, subscribe_request2.size());
EXPECT_EQ(path, subscribe_request2.get_target_path().full_str());
}
TEST(MessageTest, SubscribeRequestConstructor01) {
// public methods
// SubscribeRequestMessage();
SubscribeRequestMessage request;
EXPECT_EQ(15, request.size());
EXPECT_EQ(0, request.get_sequence_id());
EXPECT_EQ(0, request.get_page_id());
EXPECT_EQ(MessageType::SUBSCRIBE_REQUEST, request.type());
EXPECT_TRUE(request.is_request());
EXPECT_EQ(0, request.get_rid());
EXPECT_FALSE(request.get_priority());
EXPECT_EQ("", request.get_target_path().full_str());
EXPECT_EQ("", request.get_permission_token());
EXPECT_FALSE(request.get_no_stream());
EXPECT_EQ(0, request.get_alias_count());
}
TEST(MessageTest, SubscribeRequestConstructor02) {
// SubscribeRequestMessage(const SubscribeRequestMessage&);
const SubscribeRequestMessage src__request;
SubscribeRequestMessage target__request(src__request);
EXPECT_EQ(15, target__request.size());
EXPECT_EQ(0, target__request.get_sequence_id());
EXPECT_EQ(0, target__request.get_page_id());
EXPECT_EQ(MessageType::SUBSCRIBE_REQUEST, target__request.type());
EXPECT_TRUE(target__request.is_request());
EXPECT_EQ(0, target__request.get_rid());
EXPECT_FALSE(target__request.get_priority());
EXPECT_EQ("", target__request.get_target_path().full_str());
EXPECT_EQ("", target__request.get_permission_token());
EXPECT_FALSE(target__request.get_no_stream());
EXPECT_EQ(0, target__request.get_alias_count());
string_ target_path("path/to/abc");
target__request.set_target_path(target_path);
EXPECT_EQ("", src__request.get_target_path().full_str());
EXPECT_EQ(target_path, target__request.get_target_path().full_str());
EXPECT_EQ(29, target__request.size());
}
TEST(MessageTest, SubscribeRequestConstructor03) {
// SubscribeRequestMessage(const uint8_t* data, size_t size);
const uint8_t data[] = {0xf, 0x0, 0x0, 0x0, 0xf, 0x0, 0x1, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
size_t data_size = sizeof(data) / sizeof(uint8_t);
SubscribeRequestMessage request(data, data_size);
EXPECT_EQ(15, request.size());
EXPECT_EQ(0, request.get_sequence_id());
EXPECT_EQ(0, request.get_page_id());
EXPECT_EQ(MessageType::SUBSCRIBE_REQUEST, request.type());
EXPECT_TRUE(request.is_request());
EXPECT_EQ(0, request.get_rid());
EXPECT_FALSE(request.get_priority());
EXPECT_EQ("", request.get_target_path().full_str());
EXPECT_EQ("", request.get_permission_token());
EXPECT_FALSE(request.get_no_stream());
EXPECT_EQ(0, request.get_alias_count());
}
TEST(MessageTest, SubscribeRequestConstructor04) {
// SubscribeRequestMessage(const uint8_t* data, size_t size);
SubscribeRequestMessage request;
request.set_target_path("/request");
SubscribeRequestMessage other = request;
EXPECT_EQ("/request", other.get_target_path().full_str());
other.set_target_path("/other");
EXPECT_EQ("/request", request.get_target_path().full_str());
EXPECT_EQ("/other", other.get_target_path().full_str());
EXPECT_EQ(24, other.size());
EXPECT_EQ(0, other.get_sequence_id());
EXPECT_EQ(0, other.get_page_id());
EXPECT_EQ(MessageType::SUBSCRIBE_REQUEST, other.type());
EXPECT_TRUE(other.is_request());
EXPECT_EQ(0, other.get_rid());
EXPECT_FALSE(other.get_priority());
EXPECT_EQ("/other", other.get_target_path().full_str());
EXPECT_EQ("", other.get_permission_token());
EXPECT_FALSE(other.get_no_stream());
EXPECT_EQ(0, other.get_alias_count());
}
TEST(MessageTest, SubscribeRequestGetSubscribeOptions) {
// SubscribeOptions get_subscribe_options() const;
SubscribeRequestMessage request;
SubscribeOptions options = request.get_subscribe_options();
EXPECT_EQ(0, request.get_qos());
request.set_qos(QosLevel::_2);
EXPECT_EQ(QosLevel::_2, request.get_qos());
SubscribeOptions option = request.get_subscribe_options();
EXPECT_EQ(QosLevel::_2, option.qos);
}
TEST(MessageTest, SubscribeRequestUpdateStaticHeader) {
// void update_static_header();
SubscribeRequestMessage request;
request.size();
uint8_t expect_values[] = {0xf, 0x0, 0x0, 0x0, 0xf, 0x0};
EXPECT_TRUE(check_static_headers(request, expect_values,
sizeof(expect_values) / sizeof(uint8_t)));
}
TEST(MessageTest, SubscribeRequestPriority) {
SubscribeRequestMessage request;
EXPECT_FALSE(request.get_priority());
request.set_priority(true);
EXPECT_TRUE(request.get_priority());
}
TEST(MessageTest, SubscribeRequestTargetPath) {
SubscribeRequestMessage request;
EXPECT_EQ("", request.get_target_path().full_str());
request.set_target_path("path/to/node");
EXPECT_EQ("path/to/node", request.get_target_path().full_str());
}
TEST(MessageTest, SubscribeRequestPermissionToken) {
// TODO: to be implemented
SubscribeRequestMessage request;
EXPECT_EQ("", request.get_permission_token());
request.set_permission_token("permission-token");
EXPECT_EQ("permission-token", request.get_permission_token());
}
TEST(MessageTest, SubscribeRequestNoStream) {
SubscribeRequestMessage request;
EXPECT_FALSE(request.get_no_stream());
request.set_no_stream(true);
EXPECT_TRUE(request.get_no_stream());
}
TEST(MessageTest, SubscribeRequestWrite) {
SubscribeRequestMessage request;
request.set_target_path("path/to/dsa");
request.set_no_stream(true);
request.size();
uint8_t buf[1024];
request.write(buf);
uint8_t expected_values[] = {0x1e, 0x0, 0x0, 0x0, 0x1e, 0x0, 0x1, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80,
0x0b, 0x0, 0x70, 0x61, 0x74, 0x68, 0x2f, 0x74,
0x6f, 0x2f, 0x64, 0x73, 0x61, 0x11};
EXPECT_EQ(0, memcmp(expected_values, buf,
sizeof(expected_values) / sizeof(uint8_t)));
}
TEST(MessageTest, SubscribeRequestDynamicStructure) {
SubscribeRequestMessage request;
// request.set_status(Status::DONE);
request.set_sequence_id(1234); // no effect
request.set_page_id(4321); // no effect
request.set_alias_count(11);
request.set_priority(true);
request.set_no_stream(true);
request.set_qos(QosLevel::_2);
request.set_queue_size(5678);
request.set_queue_time(1248);
request.set_permission_token("ptoken");
request.set_target_path("/target/path");
request.size();
uint8_t buf[1024];
request.write(buf);
uint8_t expected_values[] = {
0x37, 0x0, 0x0, 0x0, 0x37, 0x0, 0x01, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x10, 0x08, 0x0b, 0x80, 0x0c, 0x0, 0x2f,
0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x2f, 0x70, 0x61, 0x74, 0x68,
0x60, 0x06, 0x0, 0x70, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x11, 0x12,
0x02, 0x14, 0x2e, 0x16, 0x0, 0x0, 0x15, 0xe0, 0x04, 0x0, 0x0};
EXPECT_EQ(0, memcmp(expected_values, buf,
sizeof(expected_values) / sizeof(uint8_t)));
}
TEST(MessageTest, SubscribeResponseConstructor01) {
SubscribeResponseMessage response;
EXPECT_EQ(15, response.size());
EXPECT_EQ(0, response.get_sequence_id());
EXPECT_EQ(0, response.get_page_id());
EXPECT_EQ(MessageType::SUBSCRIBE_RESPONSE, response.type());
EXPECT_FALSE(response.is_request());
EXPECT_EQ(0, response.get_rid());
EXPECT_EQ(MessageType::SUBSCRIBE_RESPONSE,
response.get_response_type(MessageType::SUBSCRIBE_REQUEST));
}
TEST(MessageTest, SubscribeResponseConstructor02) {
SubscribeResponseMessage source_response;
source_response.set_status(Status::DONE);
source_response.set_sequence_id(1234);
source_response.set_page_id(4321);
source_response.set_source_path("/source/path");
source_response.size();
uint8_t src_buf[1024];
source_response.write(src_buf);
//
size_t buf_size = 42;
SubscribeResponseMessage response(src_buf, buf_size);
response.size();
uint8_t buf[1024];
response.write(buf);
EXPECT_EQ(0, memcmp(src_buf, buf, buf_size));
}
TEST(MessageTest, SubscribeResponseSourcePath) {
SubscribeResponseMessage response;
EXPECT_EQ("", response.get_source_path());
response.set_source_path("/source/path");
EXPECT_EQ("/source/path", response.get_source_path());
}
TEST(MessageTest, SubscribeResponseStatus) {
SubscribeResponseMessage response;
static const Status message_status_all[]{
Status::OK,
Status::INITIALIZING,
Status::REFRESHED,
Status::NOT_AVAILABLE,
Status::DONE,
Status::DISCONNECTED,
Status::PERMISSION_DENIED,
Status::INVALID_MESSAGE,
Status::INVALID_PARAMETER,
Status::BUSY,
Status::ALIAS_LOOP,
Status::CONNECTION_ERROR,
};
for (const auto status : message_status_all) {
response.set_status(status);
EXPECT_EQ(status, response.get_status());
}
}
TEST(MessageTest, SubscribeResponseWrite) {
SubscribeResponseMessage response;
response.set_source_path("source/path");
response.set_status(Status::BUSY);
response.size();
uint8_t buf[1024];
response.write(buf);
uint8_t expected_values[] = {0x1f, 0x0, 0x0, 0x0, 0x1f, 0x0, 0x81, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x48, 0x81, 0x0b, 0x0, 0x73, 0x6f, 0x75, 0x72,
0x63, 0x65, 0x2f, 0x70, 0x61, 0x74, 0x68};
EXPECT_EQ(0, memcmp(expected_values, buf,
sizeof(expected_values) / sizeof(uint8_t)));
}
TEST(MessageTest, SubscribeResponseDynamicStructure) {
SubscribeResponseMessage response;
response.set_status(Status::DONE);
response.set_sequence_id(1234);
response.set_page_id(4321);
response.set_source_path("/source/path");
response.size();
uint8_t buf[1024];
response.write(buf);
uint8_t expected_values[] = {
0x2a, 0x0, 0x0, 0x0, 0x2a, 0x0, 0x81, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x01, 0xd2, 0x04, 0x0, 0x0,
0x02, 0xe1, 0x10, 0x0, 0x0, 0x81, 0x0c, 0x0, 0x2f, 0x73, 0x6f,
0x75, 0x72, 0x63, 0x65, 0x2f, 0x70, 0x61, 0x74, 0x68};
EXPECT_EQ(0, memcmp(expected_values, buf,
sizeof(expected_values) / sizeof(uint8_t)));
}
TEST(MessageTest, SubscribeResponseCopy) {
SubscribeResponseMessage response;
response.set_status(Status::DONE);
response.set_sequence_id(1234);
response.set_page_id(4321);
response.set_source_path("/source/path");
response.size();
SubscribeResponseMessage dup_response(response);
uint8_t buf[1024];
dup_response.write(buf);
uint8_t expected_values[] = {
0x2a, 0x0, 0x0, 0x0, 0x2a, 0x0, 0x81, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x01, 0xd2, 0x04, 0x0, 0x0,
0x02, 0xe1, 0x10, 0x0, 0x0, 0x81, 0x0c, 0x0, 0x2f, 0x73, 0x6f,
0x75, 0x72, 0x63, 0x65, 0x2f, 0x70, 0x61, 0x74, 0x68};
EXPECT_EQ(0, memcmp(expected_values, buf,
sizeof(expected_values) / sizeof(uint8_t)));
}
| 30.994872 | 78 | 0.708388 | iot-dsa-v2 |
526244c99d1ea9bbaa557b4233703972dfda8f79 | 4,123 | cpp | C++ | test/api/shared/test_utils.cpp | mcellteam/libbng | 1d9fe00a2cc9a8d223078aec2700e7b86b10426a | [
"MIT"
] | null | null | null | test/api/shared/test_utils.cpp | mcellteam/libbng | 1d9fe00a2cc9a8d223078aec2700e7b86b10426a | [
"MIT"
] | null | null | null | test/api/shared/test_utils.cpp | mcellteam/libbng | 1d9fe00a2cc9a8d223078aec2700e7b86b10426a | [
"MIT"
] | 1 | 2021-05-11T21:13:20.000Z | 2021-05-11T21:13:20.000Z |
#include "test_utils.h"
#include "bng/bng.h"
using namespace std;
using namespace BNG;
std::string get_test_bngl_file_name(const char* source_file) {
// source_file is a full path obtained with __FILE__
std::string src(source_file);
size_t pos = src.find_last_of("/\\");
release_assert(pos != string::npos);
return src.substr(0, pos+1) + "test.bngl";
}
static void insert_into_remaining_if_not_processed(
const species_id_t id,
set<species_id_t>& remaining_species,
const set<species_id_t>& processed_species) {
if (processed_species.count(id) == 0) {
remaining_species.insert(id);
}
}
static void collect_species_used_in_rxn_class(
RxnClass* rxn_class, // may be null
set<species_id_t>& remaining_species,
const set<species_id_t>& processed_species,
set<RxnClass*>& all_rxn_classes
) {
if (rxn_class == nullptr) {
return;
}
// what species are products? must initialize to get this information
rxn_class->init_rxn_pathways_and_rates();
for (uint pathway_index = 0; pathway_index < rxn_class->get_num_pathways(); pathway_index++) {
// collect reactants
for (species_id_t reactant: rxn_class->reactant_ids) {
insert_into_remaining_if_not_processed(
reactant,
remaining_species, processed_species);
}
// collect products, must use get_rxn_products_for_pathway to make sure that
// the products are initialized
for (const ProductSpeciesIdWIndices& prod_id_w_index:
rxn_class->get_rxn_products_for_pathway(pathway_index)) {
insert_into_remaining_if_not_processed(
prod_id_w_index.product_species_id,
remaining_species, processed_species);
}
}
// remember the rxn class
all_rxn_classes.insert(rxn_class);
}
// returns all reaction classes in the system reachable from seed species
// does not check for too large number of combinations
void generate_network(BNGEngine& bng_engine, set<RxnClass*>& all_rxn_classes) {
const BNGData& bng_data = bng_engine.get_data();
const BNGConfig& bng_config = bng_engine.get_config();
set<species_id_t> remaining_species;
set<species_id_t> processed_species;
// initialize set of remaining_species
for (const SeedSpecies& seed: bng_data.get_seed_species()) {
// create species from the seed species complex
Species s(seed.cplx, bng_data, bng_config);
// get its id
species_id_t id = bng_engine.get_all_species().find_or_add(s);
remaining_species.insert(id);
}
// process all species that we encounter
while (!remaining_species.empty()) {
species_id_t id = *remaining_species.begin();
assert(processed_species.count(id) == 0
&& "remaining_species must not contain species that were already processed");
processed_species.insert(id);
// zero-th order reactions are not supported yet
// unimolecular reactions:
RxnClass* rxn_class = bng_engine.get_all_rxns().get_unimol_rxn_class(id);
collect_species_used_in_rxn_class(
rxn_class,
remaining_species, processed_species,
all_rxn_classes);
// bimolecular reactions:
// get all reaction classes for each reactant (sets of
BNG::SpeciesRxnClassesMap* rxn_classes_map =
bng_engine.get_all_rxns().get_bimol_rxns_for_reactant(id, true);
if (rxn_classes_map != nullptr) {
// iterate over all potential reactants that can react with our species (id)
for (auto& species_rxn_class_pair: *rxn_classes_map) {
collect_species_used_in_rxn_class(
species_rxn_class_pair.second,
remaining_species, processed_species,
all_rxn_classes);
}
}
remaining_species.erase(id);
}
}
unsigned int get_num_rxns_in_network(const std::set<BNG::RxnClass*>& all_rxn_classes) {
unsigned int res = 0;
for (const RxnClass* rxn_class: all_rxn_classes) {
res += rxn_class->get_num_pathways();
}
return res;
}
void dump_network(const set<RxnClass*>& all_rxn_classes) {
for (const RxnClass* rxn_class: all_rxn_classes) {
std::cout << rxn_class->to_str("", true); // includes newline(s)
}
}
| 29.241135 | 96 | 0.718894 | mcellteam |
5262d3bf3a65ccf0f40e3d66e265422f4a540872 | 1,719 | cpp | C++ | Refureku/Generator/Source/Properties/InstantiatorPropertyCodeGen.cpp | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 143 | 2020-04-07T21:38:21.000Z | 2022-03-30T01:06:33.000Z | Refureku/Generator/Source/Properties/InstantiatorPropertyCodeGen.cpp | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 7 | 2021-03-30T07:26:21.000Z | 2022-03-28T16:31:02.000Z | Refureku/Generator/Source/Properties/InstantiatorPropertyCodeGen.cpp | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 11 | 2020-06-06T09:45:12.000Z | 2022-01-25T17:17:55.000Z | #include "RefurekuGenerator/Properties/InstantiatorPropertyCodeGen.h"
#include <Kodgen/InfoStructures/MethodInfo.h>
using namespace rfk;
InstantiatorPropertyCodeGen::InstantiatorPropertyCodeGen() noexcept:
kodgen::MacroPropertyCodeGen("Instantiator", kodgen::EEntityType::Method)
{
}
bool InstantiatorPropertyCodeGen::generateClassFooterCodeForEntity(kodgen::EntityInfo const& entity, kodgen::Property const& /*property*/, kodgen::uint8 /*propertyIndex*/,
kodgen::MacroCodeGenEnv& env, std::string& inout_result) noexcept
{
kodgen::MethodInfo const& method = static_cast<kodgen::MethodInfo const&>(entity);
std::string className = method.outerEntity->getFullName();
std::string parameters = method.getParameterTypes();
std::string methodPtr = "&" + className + "::" + method.name;
if (parameters.empty())
{
//CustomIntantiator with no parameters
inout_result += "static_assert(std::is_invocable_r_v<" + className + "*, decltype(" + methodPtr + ")>, \"[Refureku] Instantiator requires " + methodPtr + " to be a static method returning " + className + "* .\");" + env.getSeparator();
}
else
{
inout_result += "static_assert(std::is_invocable_r_v<" + className + "*, decltype(" + methodPtr + "), " + std::move(parameters) + ">, \"[Refureku] Instantiator requires " + methodPtr + " to be a static method returning " + className + "*.\");" + env.getSeparator();
}
return true;
}
void InstantiatorPropertyCodeGen::addInstantiatorToClass(std::string const& generatedClassVariableName, std::string const& generatedMethodVarName, std::string& inout_result) const noexcept
{
inout_result += generatedClassVariableName + "addInstantiator(" + generatedMethodVarName + "); ";
} | 47.75 | 267 | 0.731239 | jsoysouvanh |
526343b853d1ba13c5432a679c6ff9757fee0104 | 19,186 | hpp | C++ | wz4/wz4frlib/wz4_physx.hpp | wzman/werkkzeug4CE | af5ff27829ed4c501515ef5131165048e991c9b4 | [
"BSD-2-Clause"
] | 47 | 2015-03-22T05:58:47.000Z | 2022-03-29T19:13:37.000Z | wz4/wz4frlib/wz4_physx.hpp | whpskyeagle/werkkzeug4CE | af5ff27829ed4c501515ef5131165048e991c9b4 | [
"BSD-2-Clause"
] | null | null | null | wz4/wz4frlib/wz4_physx.hpp | whpskyeagle/werkkzeug4CE | af5ff27829ed4c501515ef5131165048e991c9b4 | [
"BSD-2-Clause"
] | 16 | 2015-12-31T08:13:18.000Z | 2021-03-09T02:07:30.000Z | /*+**************************************************************************/
/*** ***/
/*** This file is distributed under a BSD license. ***/
/*** See LICENSE.txt for details. ***/
/*** ***/
/**************************************************************************+*/
#ifndef FILE_WZ4FRLIB_PHYSX_HPP
#define FILE_WZ4FRLIB_PHYSX_HPP
#include "wz4frlib/wz4_demo2_ops.hpp"
#include "wz4frlib/wz4_physx_ops.hpp"
/****************************************************************************/
/****************************************************************************/
//#define COMPIL_WITH_PVD
#ifdef _DEBUG
#undef _DEBUG
#define _DEBUG_WAS_DEFINED
#endif
#undef new
#include "C:/library/PhysX-3.3.1_PC_SDK_Core/Include/PxPhysicsAPI.h"
#define new sDEFINE_NEW
#ifdef _DEBUG_WAS_DEFINED
#undef _DEBUG_WAS_DEFINED
#define _DEBUG
#endif
#ifdef _M_X64
// 64 bits
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win64/PhysX3CHECKED_x64.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win64/PhysX3CommonCHECKED_x64.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win64/PhysX3ExtensionsCHECKED.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win64/PhysX3CookingCHECKED_x64.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win64/PxTaskCHECKED.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win64/PhysXProfileSDKCHECKED.lib")
#ifdef COMPIL_WITH_PVD
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win64/PhysXVisualDebuggerSDKCHECKED.lib")
#endif
#else
// 32 bits
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win32/PhysX3CHECKED_x86.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win32/PhysX3CommonCHECKED_x86.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win32/PhysX3ExtensionsCHECKED.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win32/PhysX3CookingCHECKED_x86.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win32/PxTaskCHECKED.lib")
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win32/PhysXProfileSDKCHECKED.lib")
#ifdef COMPIL_WITH_PVD
#pragma comment(lib, "C:/library/PhysX-3.3.1_PC_SDK_Core/Lib/win32/PhysXVisualDebuggerSDKCHECKED.lib")
#endif
#endif
#ifdef _DEBUG
#pragma comment(linker, "/NODEFAULTLIB:libcmt.lib")
#endif
using namespace physx;
/****************************************************************************/
/****************************************************************************/
void PhysXInitEngine();
/****************************************************************************/
/****************************************************************************/
// A template tree scene for physx object
// Transform and Render objects in a graph
template <typename T, class T2, typename T3>
class WpxGenericGraph : public T2
{
public:
sArray<sMatrix34CM> Matrices; // matrices list
sArray<T *> Childs; // childs objects
~WpxGenericGraph();
virtual void Render(Wz4RenderContext &ctx, sMatrix34 &mat); // render
virtual void Transform(const sMatrix34 & mat, T3 * ptr); // build list of model matrices with GRAPH!
virtual void ClearMatricesR(); // clear matrices
void RenderChilds(Wz4RenderContext &ctx, sMatrix34 &mat); // recurse to childs
void TransformChilds(const sMatrix34 & mat, T3 * ptr); // recurse to childs
};
template <typename T, class T2, typename T3>
WpxGenericGraph<T, T2, T3>::~WpxGenericGraph()
{
sReleaseAll(Childs);
}
template <typename T, class T2, typename T3>
void WpxGenericGraph<T, T2, T3>::ClearMatricesR()
{
T *c;
Matrices.Clear();
sFORALL(Childs, c)
c->ClearMatricesR();
}
template <typename T, class T2, typename T3>
void WpxGenericGraph<T, T2, T3>::Transform(const sMatrix34 &mat, T3 * ptr)
{
TransformChilds(mat, ptr);
}
template <typename T, class T2, typename T3>
void WpxGenericGraph<T, T2, T3>::TransformChilds(const sMatrix34 &mat, T3 * ptr)
{
T *c;
Matrices.AddTail(sMatrix34CM(mat));
sFORALL(Childs, c)
c->Transform(mat, ptr);
}
template <typename T, class T2, typename T3>
void WpxGenericGraph<T, T2, T3>::Render(Wz4RenderContext &ctx, sMatrix34 &mat)
{
RenderChilds(ctx,mat);
}
template <typename T, class T2, typename T3>
void WpxGenericGraph<T, T2, T3>::RenderChilds(Wz4RenderContext &ctx, sMatrix34 &mat)
{
// recurse to childs
T *c;
sFORALL(Childs, c)
c->Render(ctx,mat);
}
/****************************************************************************/
/****************************************************************************/
// WpxColliderBase is the base type for all colliders operators
// WpxColliderBase inherited classes are used to preview a graph of colliders
class WpxColliderBase : public WpxGenericGraph<WpxColliderBase, wObject, PxRigidActor>
{
public:
WpxColliderBase();
void AddCollidersChilds(wCommand *cmd); // add childs
virtual void GetDensity(sArray<PxReal> * densities); // get shape density to compute final mass and inertia
void GetDensityChilds(sArray<PxReal> * densities); // recurse to childs
};
/****************************************************************************/
/****************************************************************************/
class WpxCollider : public WpxColliderBase
{
private:
Wz4Mesh * MeshCollider; // collider mesh, used to preview collider shape
Wz4Mesh * MeshInput; // ptr to optional mesh used to generate collider geometry (when GeometryType is hull or mesh)
PxConvexMesh * ConvexMesh; // convex mesh (when GeometryType is hull)
PxTriangleMesh * TriMesh; // triangle mesh (when GeometryType is mesh)
public:
WpxColliderParaCollider ParaBase, Para;
WpxCollider();
~WpxCollider();
void Transform(const sMatrix34 & mat, PxRigidActor * ptr);
void Render(Wz4RenderContext &ctx, sMatrix34 &mat);
sBool CreateGeometry(Wz4Mesh * input); // create collider mesh (to preview collider shape)
void CreatePhysxCollider(PxRigidActor * actor, sMatrix34 & mat); // create physx collider for actor
void GetDensity(sArray<PxReal> * densities); // get shape density
};
/****************************************************************************/
class WpxColliderAdd : public WpxColliderBase
{
public:
WpxColliderAddParaColliderAdd ParaBase, Para;
};
/****************************************************************************/
class WpxColliderTransform : public WpxColliderBase
{
public:
WpxColliderTransformParaColliderTransform ParaBase, Para;
void Transform(const sMatrix34 & mat, PxRigidActor * ptr);
};
/****************************************************************************/
class WpxColliderMul : public WpxColliderBase
{
public:
WpxColliderMulParaColliderMul ParaBase, Para;
void Transform(const sMatrix34 & mat, PxRigidActor * ptr);
};
/****************************************************************************/
/****************************************************************************/
// WpxActorBase is the base type for all actors operators
// WpxActorBase inherited classes are used to preview a graph of actors + associated colliders graph
class WpxRigidBody;
class WpxActorBase : public WpxGenericGraph<WpxActorBase, Wz4Render, PxScene>
{
public:
WpxActorBase();
virtual void PhysxReset(); // clear physx
virtual void PhysxWakeUp(); // wakeup physx
void AddActorsChilds(wCommand *cmd); // add childs
void PhysxResetChilds(); // recurse to childs
void PhysxWakeUpChilds(); // recurse to childs
WpxRigidBody * GetRigidBodyR(WpxActorBase * node); // recurse to childs to get a rigidbody (used by joints to find a rigidbody op in tree)
WpxRigidBody * GetRigidBodyR(WpxActorBase * node, sChar * name);
sChar Name[255];
};
/****************************************************************************/
/****************************************************************************/
struct sActor
{
PxRigidActor * actor; // physx actor ptr
sMatrix34 * matrix; // store matrix at actor creation (used by kinematics and debris)
};
struct sJoint
{
Wz4Mesh MeshPreview;
sMatrix34 Pose;
};
class WpxRigidBody : public WpxActorBase
{
public:
WpxColliderBase * RootCollider; // associated colliders geometries, root collider in collider graph
sArray<sActor*> AllActors; // list of actors
sArray<sVector31> ListPositions; // used to store position list, when building rigidbody from vertex mode
WpxRigidBodyParaRigidBody ParaBase, Para;
WpxRigidBody();
~WpxRigidBody();
void Transform(const sMatrix34 & mat, PxScene * ptr);
void Render(Wz4RenderContext &ctx, sMatrix34 &mat);
void ClearMatricesR();
void PhysxReset();
void AddRootCollider(WpxColliderBase * col);
void PhysxBuildActor(const sMatrix34 & mat, PxScene * scene, sArray<sActor*> &allActors); // build physx actor
void PhysxWakeUp();
void GetPositionsFromMeshVertices(Wz4Mesh * mesh, sInt selection);
void GetPositionsFromMeshChunks(Wz4Mesh * mesh);
// joints
void BuildAttachmentPoints(WpxRigidBodyArrayRigidBody * array, sInt arrayCount);
void CreateAttachmentPointMesh(sJoint * joint);
sArray<sJoint *> JointsFixations;
};
/****************************************************************************/
class WpxRigidBodyAdd : public WpxActorBase
{
public:
WpxRigidBodyAddParaRigidBodyAdd ParaBase, Para;
};
/****************************************************************************/
class WpxRigidBodyTransform : public WpxActorBase
{
public:
WpxRigidBodyTransformParaRigidBodyTransform ParaBase, Para;
void Transform(const sMatrix34 & mat, PxScene * ptr);
};
/****************************************************************************/
class WpxRigidBodyMul : public WpxActorBase
{
public:
WpxRigidBodyMulParaRigidBodyMul ParaBase, Para;
void Transform(const sMatrix34 & mat, PxScene * ptr);
};
/****************************************************************************/
class WpxRigidBodyJointsChained : public WpxActorBase
{
public:
WpxRigidBodyJointsChainedParaJointsChained ParaBase, Para;
void Transform(const sMatrix34 & mat, PxScene * ptr);
sChar NameA[255];
};
/****************************************************************************/
class WpxRigidBodyJoint : public WpxActorBase
{
public:
WpxRigidBodyJointParaJoint ParaBase, Para;
void Transform(const sMatrix34 & mat, PxScene * ptr);
sChar NameA[255];
sChar NameB[255];
};
/****************************************************************************/
struct sChunkCollider
{
WpxCollider * wCollider; // physx collider
Wz4Mesh * Mesh; // chunk mesh, used to compute collider shape
sChunkCollider() { wCollider=0; Mesh=0; }
};
class WpxRigidBodyDebris : public WpxActorBase
{
public:
Wz4Mesh * ChunkedMesh; // chunked mesh to render
sArray<sActor*> AllActors; // list of actors (per chunks)
sArray<sChunkCollider *> ChunksColliders; // list of colliders
sArray<WpxRigidBody *> ChunksRigidBodies; // list of rigidbodies
WpxRigidBodyDebrisParaRigidBodyDebris Para, ParaBase;
WpxRigidBodyDebris();
~WpxRigidBodyDebris();
void PhysxReset();
void Render(Wz4RenderContext &ctx, sMatrix34 &mat);
void Transform(const sMatrix34 & mat, PxScene * ptr);
void PhysxBuildDebris(const sMatrix34 & mat, PxScene * ptr);
int GetChunkedMesh(Wz4Render * in);
void PhysxWakeUp();
};
/****************************************************************************/
/****************************************************************************/
// next Wz4RenderNodes, are nodes associated with actors operators,
// they are computed in the Wz4Render graph process at each render loop,
// they are used for :
// - rendering RenderNode binded with physx
// - simulate and process manually physx features like kinematics, add forces, etc...
/****************************************************************************/
/****************************************************************************/
class WpxRigidBodyNodeBase : public Wz4RenderNode
{
public:
virtual void Init() {}
WpxRigidBodyParaRigidBody ParaBase, Para;
WpxRigidBodyAnimRigidBody Anim;
};
/****************************************************************************/
class WpxRigidBodyNodeActor : public WpxRigidBodyNodeBase
{
public:
sArray<sActor*> * AllActorsPtr; // ptr to an actors list (in WpxRigidBody)
WpxRigidBodyNodeActor();
void Transform(Wz4RenderContext *ctx, const sMatrix34 & mat);
};
/****************************************************************************/
class WpxRigidBodyNodeDynamic : public WpxRigidBodyNodeActor
{
public:
WpxRigidBodyNodeDynamic();
void Simulate(Wz4RenderContext *ctx);
};
/****************************************************************************/
class WpxRigidBodyNodeStatic : public WpxRigidBodyNodeActor
{
public:
};
/****************************************************************************/
class WpxRigidBodyNodeKinematic : public WpxRigidBodyNodeActor
{
public:
WpxRigidBodyNodeKinematic();
void Simulate(Wz4RenderContext *ctx);
};
/****************************************************************************/
class WpxRigidBodyNodeDebris : public WpxRigidBodyNodeActor
{
public:
Wz4Mesh * ChunkedMeshPtr; // ptr to single chunked mesh to render (init in WpxRigidBodyDebris)
WpxRigidBodyDebrisParaRigidBodyDebris Para, ParaBase;
WpxRigidBodyDebrisAnimRigidBodyDebris Anim;
WpxRigidBodyNodeDebris();
~WpxRigidBodyNodeDebris();
void Transform(Wz4RenderContext *ctx, const sMatrix34 & mat);
void Render(Wz4RenderContext *ctx);
void Simulate(Wz4RenderContext *ctx);
};
/****************************************************************************/
/****************************************************************************/
class WpxParticleNode;
class PhysxTarget;
/****************************************************************************/
class RNPhysx : public Wz4RenderNode
{
private:
sBool Executed; // flag for restart and pause simulation mechanism with F6/F5
sF32 PreviousTimeLine; // delta time line use to restart simulation
sF32 LastTime; // last frame time
sF32 Accumulator; // time accumulator
sArray<WpxActorBase *> WpxChilds; // wpx childs operators list for clean delete
PhysxTarget * SceneTarget; // target for particles
PxScene * CreateScene(); // create new physx scene
void CreateAllActors(wCommand *cmd); // create physx actors
void WakeUpScene(wCommand *cmd); // wake up all actors
public:
PxScene * Scene; // Physx scene
sArray<Wz4ParticleNode *> PartSystems; // all Wz4ParticlesNode binded to this physx (rebuild op mechanism)
Wz4RenderParaPhysx ParaBase, Para;
Wz4RenderAnimPhysx Anim;
RNPhysx::RNPhysx();
RNPhysx::~RNPhysx();
void Simulate(Wz4RenderContext *ctx);
sBool Init(wCommand *cmd); // init physx
void InitSceneTarget(PhysxTarget * target); // init scene target ptr
};
/****************************************************************************/
/****************************************************************************/
class PhysxObject : public wObject
{
public:
PxScene * PhysxSceneRef; // physx scene ptr
sArray<Wz4ParticleNode *> * PartSystemsRef; // ptr to the particles node list binded to a physx operator
PhysxObject() { Type = PhysxObjectType; PhysxSceneRef = 0; PartSystemsRef = 0; }
// call this to register a particle node for a physx operator
void RegisterParticleNode(Wz4ParticleNode * op)
{
if (PartSystemsRef)
PartSystemsRef->AddTail(op);
}
// call this to remove a particle node for a physx operator
void RemoveParticleNode(Wz4ParticleNode * op)
{
if(PartSystemsRef)
PartSystemsRef->Rem(op);
}
};
/****************************************************************************/
class PhysxTarget : public PhysxObject
{
public:
PhysxTarget() { AddRef(); }
~PhysxTarget() { Release(); }
};
/****************************************************************************/
/****************************************************************************/
class WpxParticleNode : public Wz4ParticleNode
{
public:
PhysxObject * Target;
WpxParticleNode() { Target = 0; }
};
/****************************************************************************/
class RPPhysxParticleTest : public WpxParticleNode
{
PxU32* pIndex;
PxVec3* pPosition;
PxVec3* pVelocity;
PxParticleSystem * PhysxPartSystem;
struct Particle
{
sVector31 Pos0;
sVector31 Pos1;
};
sArray<Particle> Particles;
public:
RPPhysxParticleTest();
~RPPhysxParticleTest();
void Init();
Wz4ParticlesParaPxCloud Para, ParaBase;
Wz4ParticlesAnimPxCloud Anim;
void Simulate(Wz4RenderContext *ctx);
sInt GetPartCount();
sInt GetPartFlags();
void Func(Wz4PartInfo &pinfo, sF32 time, sF32 dt);
};
/****************************************************************************/
class RPPxPart : public WpxParticleNode
{
PxU32* pIndex;
PxVec3* pPosition;
PxVec3* pVelocity;
PxParticleSystem * PhysxPartSystem;
struct Particle
{
sVector31 Pos0;
sVector31 Pos1;
};
sArray<Particle> Particles;
public:
RPPxPart();
~RPPxPart();
void Init();
Wz4ParticlesParaPxPart Para, ParaBase;
Wz4ParticlesAnimPxPart Anim;
void Simulate(Wz4RenderContext *ctx);
sInt GetPartCount();
sInt GetPartFlags();
void Func(Wz4PartInfo &pinfo, sF32 time, sF32 dt);
sBool NeedInit;
void DelayedInit();
PxVec3* bStartPosition;
Wz4ParticleNode *Source;
};
/****************************************************************************/
class RPRangeEmiter : public WpxParticleNode
{
struct Particle
{
sVector31 Position;
sVector30 Velocity;
sVector30 Acceleration;
sF32 Speed;
sF32 Life;
sF32 MaxLife;
sBool isDead;
Particle()
{
Position = sVector31(0,0,0);
Velocity = sVector30(0,0,0);
Acceleration = sVector30(0, 0, 0);
Speed = 1.0f;
Life = -1;
MaxLife = 1;
isDead = sTRUE;
}
};
sArray<Particle> Particles;
sF32 AccumultedTime;
sF32 Rate;
sInt EmitCount;
public:
RPRangeEmiter();
~RPRangeEmiter();
void Init();
Wz4ParticlesParaRangeEmiter Para, ParaBase;
Wz4ParticlesAnimRangeEmiter Anim;
void Simulate(Wz4RenderContext *ctx);
sInt GetPartCount();
sInt GetPartFlags();
void Func(Wz4PartInfo &pinfo, sF32 time, sF32 dt);
};
#endif FILE_WZ4FRLIB_PHYSX_HPP
| 31.095624 | 141 | 0.577504 | wzman |
52642bec5b476187a4b080365f0c2c21a954e68d | 8,857 | cpp | C++ | src/main.cpp | ZeroxCorbin/tm_driver | d0abe90b5dba42d48a4aa9825b378b130a5b745c | [
"MIT"
] | null | null | null | src/main.cpp | ZeroxCorbin/tm_driver | d0abe90b5dba42d48a4aa9825b378b130a5b745c | [
"MIT"
] | null | null | null | src/main.cpp | ZeroxCorbin/tm_driver | d0abe90b5dba42d48a4aa9825b378b130a5b745c | [
"MIT"
] | null | null | null | #include "tm_driver/tm_driver.h"
#include "tm_driver/tm_print.h"
#include <SctResponse.hpp>
#include <StaResponse.hpp>
#include <ConnectTM.hpp>
#include <SendScript.hpp>
#include <SetEvent.hpp>
#include <SetPositions.hpp>
#include <SetIO.hpp>
#include <AskSta.hpp>
#include <iostream>
TmDriver* iface_;
std::mutex sta_mtx_;
std::condition_variable sta_cond_;
std::condition_variable psrv_cv_cond_;
std::condition_variable pscv_cv_cond_;
bool sta_updated_;
int sct_reconnect_timeval_ms_;
int sct_reconnect_timeout_ms_;
struct SctMsg {
tm_msgs::msg::SctResponse sct_msg;
tm_msgs::msg::StaResponse sta_msg;
} sm_;
int main(int argc, char* argv[]) {
std::string host;
if (argc > 1) {
host = argv[1];
}
iface_ = new TmDriver(host, &psrv_cv_cond_, &pscv_cv_cond_);
iface_->start();
while (true) {
std::string test;
std::getline(std::cin, test);
if (test == "s")
iface_->state.print();
else
iface_->set_stop();
};
return 0;
}
bool connect_tmsct(
const std::shared_ptr<tm_msgs::srv::ConnectTM::Request> req,
std::shared_ptr<tm_msgs::srv::ConnectTM::Response> res)
{
bool rb = true;
int t_o = (int)(1000.0 * req->timeout);
int t_v = (int)(1000.0 * req->timeval);
if (req->connect) {
print_info("(TM_SCT) (re)connect(%d) TM_SCT", t_o);
iface_->sct.halt();
rb = iface_->sct.start(t_o);
}
if (req->reconnect) {
sct_reconnect_timeout_ms_ = t_o;
sct_reconnect_timeval_ms_ = t_v;
print_info("(TM_SCT) set SCT reconnect timeout %dms, timeval %dms", t_o, t_v);
}
else {
// no reconnect
sct_reconnect_timeval_ms_ = -1;
print_info("(TM_SCT) set SCT NOT reconnect");
}
res->ok = rb;
return rb;
}
bool send_script(
const std::shared_ptr<tm_msgs::srv::SendScript::Request> req,
std::shared_ptr<tm_msgs::srv::SendScript::Response> res)
{
bool rb = (iface_->sct.send_script_str(req->id, req->script) == iface_->RC_OK);
res->ok = rb;
return rb;
}
bool set_event(
const std::shared_ptr<tm_msgs::srv::SetEvent::Request> req,
std::shared_ptr<tm_msgs::srv::SetEvent::Response> res)
{
bool rb = false;
std::string content;
switch (req->func) {
case tm_msgs::srv::SetEvent::Request::EXIT:
rb = iface_->script_exit();
break;
case tm_msgs::srv::SetEvent::Request::TAG:
rb = iface_->set_tag((int)(req->arg0), (int)(req->arg1));
break;
case tm_msgs::srv::SetEvent::Request::WAIT_TAG:
rb = iface_->set_wait_tag((int)(req->arg0), (int)(req->arg1));
break;
case tm_msgs::srv::SetEvent::Request::STOP:
rb = iface_->set_stop();
break;
case tm_msgs::srv::SetEvent::Request::PAUSE:
rb = iface_->set_pause();
break;
case tm_msgs::srv::SetEvent::Request::RESUME:
rb = iface_->set_resume();
break;
}
res->ok = rb;
return rb;
}
bool set_io(
const std::shared_ptr<tm_msgs::srv::SetIO::Request> req,
std::shared_ptr<tm_msgs::srv::SetIO::Response> res)
{
bool rb = iface_->set_io(TmIOModule(req->module), TmIOType(req->type), int(req->pin), req->state);
res->ok = rb;
return rb;
}
bool set_positions(
const std::shared_ptr<tm_msgs::srv::SetPositions::Request> req,
std::shared_ptr<tm_msgs::srv::SetPositions::Response> res)
{
bool rb = false;
switch (req->motion_type) {
case tm_msgs::srv::SetPositions::Request::PTP_J:
rb = iface_->set_joint_pos_PTP(req->positions, req->velocity, req->acc_time, req->blend_percentage, req->fine_goal);
break;
case tm_msgs::srv::SetPositions::Request::PTP_T:
rb = iface_->set_tool_pose_PTP(req->positions, req->velocity, req->acc_time, req->blend_percentage, req->fine_goal);
break;
case tm_msgs::srv::SetPositions::Request::LINE_T:
rb = iface_->set_tool_pose_Line(req->positions, req->velocity, req->acc_time, req->blend_percentage, req->fine_goal);
break;
}
res->ok = rb;
return rb;
}
bool ask_sta(
const std::shared_ptr<tm_msgs::srv::AskSta::Request> req,
std::shared_ptr<tm_msgs::srv::AskSta::Response> res)
{
SctMsg& sm = sm_;
bool rb = false;
sta_updated_ = false;
rb = (iface_->sct.send_script_str(req->subcmd, req->subdata) == iface_->RC_OK);
if (req->wait_time > 0.0) {
std::mutex lock;
std::unique_lock<std::mutex> locker(lock);
if (!sta_updated_) {
sta_cond_.wait_for(locker, std::chrono::duration<double>(req->wait_time));
}
if (sta_updated_) {
sta_mtx_.lock();
res->subcmd = sm.sta_msg.subcmd;
res->subdata = sm.sta_msg.subdata;
sta_mtx_.unlock();
sta_updated_ = false;
}
else rb = false;
}
res->ok = rb;
return rb;
}
//void sct_msg()
//{
// SctMsg& sm = sm_;
// TmSctData& data = iface_->sct.sct_data;
//
// sm.sct_msg.id = data.script_id();
// sm.sct_msg.script = std::string{ data.script(), data.script_len() };
//
// if (data.has_error()) {
// print_info("(TM_SCT): err: (%s): %s", sm.sct_msg.id.c_str(), sm.sct_msg.script.c_str());
// }
// else {
// print_info("(TM_SCT): res: (%s): %s", sm.sct_msg.id.c_str(), sm.sct_msg.script.c_str());
// }
//
// //sm.sct_msg.header.stamp = rclcpp::Node::now();
// //sm.sct_pub->publish(sm.sct_msg);
//}
//void sta_msg()
//{
// SctMsg& sm = sm_;
// TmStaData& data = iface_->sct.sta_data;
//
// sta_mtx_.lock();
// sm.sta_msg.subcmd = data.subcmd_str();
// sm.sta_msg.subdata = std::string{ data.subdata(), data.subdata_len() };
// sta_mtx_.unlock();
//
// sta_updated_ = true;
// sta_cond_.notify_all();
//
// print_info("(TM_STA): res: (%s): %s", sm.sta_msg.subcmd.c_str(), sm.sta_msg.subdata.c_str());
//
// //sm.sta_msg.header.stamp = rclcpp::Node::now();
// //sm.sta_pub->publish(sm.sta_msg);
//}
//bool sct_func()
//{
// TmSctCommunication& sct = iface_->sct;
// int n;
// auto rc = sct.recv_spin_once(1000, &n);
// if (rc == TmCommRC::ERR ||
// rc == TmCommRC::NOTREADY ||
// rc == TmCommRC::NOTCONNECT) {
// return false;
// }
// else if (rc != TmCommRC::OK) {
// return true;
// }
// std::vector<TmPacket>& pack_vec = sct.packet_list();
//
// for (auto& pack : pack_vec) {
// switch (pack.type) {
// case TmPacket::Header::CPERR:
// print_info("(TM_SCT): CPERR");
// sct.err_data.set_CPError(pack.data.data(), pack.data.size());
// print_error(sct.err_data.error_code_str().c_str());
//
// // cpe response
//
// break;
//
// case TmPacket::Header::TMSCT:
//
// sct.err_data.error_code(TmCPError::Code::Ok);
//
// //TODO ? lock and copy for service response
// TmSctData::build_TmSctData(sct.sct_data, pack.data.data(), pack.data.size(), TmSctData::SrcType::Shallow);
//
// sct_msg();
// break;
//
// case TmPacket::Header::TMSTA:
//
// sct.err_data.error_code(TmCPError::Code::Ok);
//
// TmStaData::build_TmStaData(sct.sta_data, pack.data.data(), pack.data.size(), TmStaData::SrcType::Shallow);
//
// sta_msg();
// break;
//
// default:
// print_info("(TM_SCT): invalid header");
// break;
// }
// }
// return true;
//}
//void sct_responsor()
//{
// TmSctCommunication& sct = iface_->sct;
//
// std::this_thread::sleep_for(std::chrono::milliseconds(50));
//
// print_info("(TM_SCT): sct_response thread begin");
//
// while (true) {
// //bool reconnect = false;
// if (!sct.recv_init()) {
// print_info("(TM_SCT) is not connected");
// }
// while (sct.is_connected()) {
// if (!sct_func()) break;
// }
// sct.Close();
//
// // reconnect == true
// //if (!rclcpp::ok()) break;
// if (sct_reconnect_timeval_ms_ <= 0) {
// std::this_thread::sleep_for(std::chrono::milliseconds(100));
// }
// print_info("(TM_SCT) reconnect in ");
// int cnt = 0;
// while (cnt < sct_reconnect_timeval_ms_) {
// if (cnt % 1000 == 0) {
// print_info("%.1f sec...", 0.001 * (sct_reconnect_timeval_ms_ - cnt));
// }
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
// ++cnt;
// }
// if (sct_reconnect_timeval_ms_ >= 0) {
// print_info("0 sec\n(TM_SCT) connect(%d)...", sct_reconnect_timeout_ms_);
// sct.Connect(sct_reconnect_timeout_ms_);
// }
// }
// sct.Close();
// printf("(TM_SCT) sct_response thread end\n");
//}
| 29.134868 | 125 | 0.579767 | ZeroxCorbin |
52642c4a4142a47d7de99e089f15aee33b5afd86 | 2,513 | cpp | C++ | source/Editor/assetsWidget.cpp | nicovanbentum/GE | 1dd737b50bef306118116c6c4e1bd36c0ebb65c6 | [
"MIT"
] | null | null | null | source/Editor/assetsWidget.cpp | nicovanbentum/GE | 1dd737b50bef306118116c6c4e1bd36c0ebb65c6 | [
"MIT"
] | null | null | null | source/Editor/assetsWidget.cpp | nicovanbentum/GE | 1dd737b50bef306118116c6c4e1bd36c0ebb65c6 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "assetsWidget.h"
#include "editor.h"
#include "IconsFontAwesome5.h"
namespace Raekor {
AssetsWidget::AssetsWidget(Editor* editor) : IWidget(editor, "Asset Browser") {}
void AssetsWidget::draw(float dt) {
ImGui::Begin(title.c_str());
auto materials = IWidget::GetScene().view<Material, Name>();
auto& style = ImGui::GetStyle();
if (ImGui::BeginTable("Assets", 24)) {
for (auto entity : materials) {
auto& [material, name] = materials.get<Material, Name>(entity);
auto selectable_name = name.name.substr(0, 9).c_str() + std::string("...");
ImGui::TableNextColumn();
if (GetActiveEntity() == entity)
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ImGui::ColorConvertFloat4ToU32(ImVec4(1.0f, 1.0f, 1.0f, 0.2f)));
bool clicked = false;
ImGui::PushID(entt::to_integral(entity));
if (material.gpuAlbedoMap) {
clicked = ImGui::ImageButton(
(void*)((intptr_t)material.gpuAlbedoMap),
ImVec2(64 * ImGui::GetWindowDpiScale(), 64 * ImGui::GetWindowDpiScale()),
ImVec2(0, 0), ImVec2(1, 1), -1,
ImVec4(0, 1, 0, 1)
);
}
else {
ImGui::PushStyleColor(ImGuiCol_Button, ImVec(material.albedo));
clicked = ImGui::Button(
std::string("##" + name.name).c_str(),
ImVec2(64 * ImGui::GetWindowDpiScale() + style.FramePadding.x * 2, 64 * ImGui::GetWindowDpiScale() + style.FramePadding.y * 2)
);
ImGui::PopStyleColor();
}
if (clicked)
GetActiveEntity() = entity;
//if (ImGui::Button(ICON_FA_ARCHIVE, ImVec2(64 * ImGui::GetWindowDpiScale(), 64 * ImGui::GetWindowDpiScale()))) {
// editor->active = entity;
//}
ImGuiDragDropFlags src_flags = ImGuiDragDropFlags_SourceNoDisableHover;
src_flags |= ImGuiDragDropFlags_SourceNoHoldToOpenOthers;
if (ImGui::BeginDragDropSource(src_flags)) {
ImGui::SetDragDropPayload("drag_drop_mesh_material", &entity, sizeof(entt::entity));
ImGui::EndDragDropSource();
}
ImGui::PopID();
ImGui::Text(selectable_name.c_str());
}
ImGui::EndTable();
}
ImGui::End();
}
} // raekor | 33.065789 | 146 | 0.55193 | nicovanbentum |
52645cd5fee7053d4352bdd350085e063bbafe5d | 1,017 | cpp | C++ | PORT3/Box/Point/Point.cpp | Kush12747/CSC122 | 36c6f1c0f4a3ddd035529043d51217ec22961c84 | [
"MIT"
] | null | null | null | PORT3/Box/Point/Point.cpp | Kush12747/CSC122 | 36c6f1c0f4a3ddd035529043d51217ec22961c84 | [
"MIT"
] | null | null | null | PORT3/Box/Point/Point.cpp | Kush12747/CSC122 | 36c6f1c0f4a3ddd035529043d51217ec22961c84 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include "Point.h"
using namespace std;
//input function for (x,y) format
void Point::Input(std::istream& is)
{
char temp;
is >> temp >> x >> temp >> y >> temp;
return;
}
//output for (x,y) format
void Point::Output(std::ostream& os) const
{
os << '(' << x << ", " << y << ')';
return;
}
//calculate the distance between 2 points
double Point::distance(const Point& other)const
{
return sqrt(pow(other.x - x, 2.0) +
pow(other.y - y, 2.0));
}
//using setters functions
void Point::set_x(double new_x)
{
x = new_x;
return;
}
void Point::set_y(double new_y)
{
y = new_y;
return;
}
//function to flip points
Point Point::flip_x(void) const
{ return Point(x, -y); }
Point Point::flip_y(void) const
{ return Point(-x, y); }
//function to move points for x and y
Point Point::shift_x(double move_by) const
{ return Point(x + move_by, y); }
Point Point::shift_y(double move_by) const
{ return Point(x, y + move_by); }
| 21.1875 | 47 | 0.621436 | Kush12747 |
526df46baac02adbf5df94c02ed2422a11ca8f19 | 3,314 | cpp | C++ | hw5/src/Mass_spring_system.cpp | jrabasco/acg2015 | 419fd0fdf5293dda95ea0231cf6c6f4af5331120 | [
"MIT"
] | null | null | null | hw5/src/Mass_spring_system.cpp | jrabasco/acg2015 | 419fd0fdf5293dda95ea0231cf6c6f4af5331120 | [
"MIT"
] | null | null | null | hw5/src/Mass_spring_system.cpp | jrabasco/acg2015 | 419fd0fdf5293dda95ea0231cf6c6f4af5331120 | [
"MIT"
] | null | null | null | //=============================================================================
//
// Exercise code for the lecture
// "Advanced Computer Graphics"
//
// Adapted from Prof. Dr. Mario Botsch, Bielefeld University
//
// Copyright (C) 2013 LGG, epfl
//
// DO NOT REDISTRIBUTE
//=============================================================================
//== INCLUDES =================================================================
#include "Mass_spring_system.h"
//== IMPLEMENTATION ==========================================================
void Mass_spring_system::clear()
{
particles.clear();
springs.clear();
triangles.clear();
}
//-----------------------------------------------------------------------------
void Mass_spring_system::add_particle(vec2 position, vec2 velocity, float mass, bool locked)
{
particles.push_back( Particle(position, velocity, mass, locked) );
}
//-----------------------------------------------------------------------------
void Mass_spring_system::add_spring(unsigned int i0, unsigned int i1)
{
assert(i0 < particles.size());
assert(i1 < particles.size());
springs.push_back( Spring(particles[i0], particles[i1]) );
}
//-----------------------------------------------------------------------------
void Mass_spring_system::add_triangle(unsigned int i0, unsigned int i1, unsigned int i2)
{
assert(i0 < particles.size());
assert(i1 < particles.size());
assert(i2 < particles.size());
triangles.push_back( Triangle(particles[i0], particles[i1], particles[i2]) );
}
//-----------------------------------------------------------------------------
void Mass_spring_system::draw(float particle_radius, bool show_forces) const
{
// draw particles
glEnable(GL_LIGHTING);
glShadeModel(GL_SMOOTH);
glEnable(GL_COLOR_MATERIAL);
for (unsigned int i=0; i<particles.size(); ++i)
{
const Particle& p = particles[i];
if (p.locked)
glColor3f(0.6, 0.0, 0.0);
else
glColor3f(0.0, 0.6, 0.0);
glPushMatrix();
glTranslatef( p.position[0], p.position[1], 0.0 );
glutSolidSphere( particle_radius, 20, 20 );
glPopMatrix();
if (show_forces)
{
glLineWidth(1.0);
glBegin(GL_LINES);
glVertex2f(p.position[0], p.position[1]);
glVertex2f(p.position[0] + 0.05 * p.force[0], p.position[1] + 0.05 * p.force[1]);
glEnd();
}
}
glDisable(GL_COLOR_MATERIAL);
// draw springs
glDisable(GL_LIGHTING);
glLineWidth(5.0);
glColor3f(0,0,0);
glBegin(GL_LINES);
for (unsigned int i=0; i<springs.size(); ++i)
{
glVertex2fv( springs[i].particle0->position.data() );
glVertex2fv( springs[i].particle1->position.data() );
}
glEnd();
// draw area constraints
glDisable(GL_LIGHTING);
glColor3f(0.8, 1.0, 0.8);
glBegin(GL_TRIANGLES);
for (unsigned int i=0; i<triangles.size(); ++i)
{
glVertex2fv( triangles[i].particle0->position.data() );
glVertex2fv( triangles[i].particle1->position.data() );
glVertex2fv( triangles[i].particle2->position.data() );
}
glEnd();
}
//=============================================================================
| 27.38843 | 93 | 0.489439 | jrabasco |
526e0d7be42cc896ae48eb68811aea75cfc4f063 | 442 | cpp | C++ | src/Records/STAT.cpp | Koncord/ESx-Reader | fa7887c934141f7b0a956417392f2b618165cc34 | [
"Apache-2.0"
] | 1 | 2022-03-01T19:17:33.000Z | 2022-03-01T19:17:33.000Z | src/Records/STAT.cpp | Koncord/ESx-Reader | fa7887c934141f7b0a956417392f2b618165cc34 | [
"Apache-2.0"
] | 8 | 2015-04-17T12:04:15.000Z | 2015-07-02T14:40:28.000Z | src/Records/STAT.cpp | Koncord/ESx-Reader | fa7887c934141f7b0a956417392f2b618165cc34 | [
"Apache-2.0"
] | 1 | 2022-03-01T19:17:36.000Z | 2022-03-01T19:17:36.000Z | /*
* File: STAT.cpp
* Author: Koncord <koncord at rwa.su>
*
* Created on 8 Апрель 2015 г., 21:57
*/
#include "STAT.hpp"
using namespace std;
bool RecordSTAT::DoParse()
{
const string subType = GetLabel();
if(subType == "EDID")
data.edid = GetString();
else if(subType == "OBND")
data.objectBounds = GetData<ObjectBounds>();
else if(ModelCollection()) {}
else return false;
return true;
}
| 17.68 | 52 | 0.608597 | Koncord |
52701db43a8bcfffe51f676b52a0ce8710d52aae | 622 | hpp | C++ | libs/camera/include/sge/camera/ortho_freelook/optional_projection_rectangle_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/camera/include/sge/camera/ortho_freelook/optional_projection_rectangle_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/camera/include/sge/camera/ortho_freelook/optional_projection_rectangle_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// 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 SGE_CAMERA_ORTHO_FREELOOK_OPTIONAL_PROJECTION_RECTANGLE_FWD_HPP_INCLUDED
#define SGE_CAMERA_ORTHO_FREELOOK_OPTIONAL_PROJECTION_RECTANGLE_FWD_HPP_INCLUDED
#include <sge/renderer/projection/rect_fwd.hpp>
#include <fcppt/optional/object_fwd.hpp>
namespace sge::camera::ortho_freelook
{
using optional_projection_rectangle = fcppt::optional::object<sge::renderer::projection::rect>;
}
#endif
| 31.1 | 95 | 0.790997 | cpreh |
527428aef2ea21c9089c421310c198be0f7bcab4 | 16,949 | cpp | C++ | src/renderer/render.cpp | infosia/Raster | e53a6f9c10212ec50951198496800a866f40aaca | [
"MIT"
] | null | null | null | src/renderer/render.cpp | infosia/Raster | e53a6f9c10212ec50951198496800a866f40aaca | [
"MIT"
] | null | null | null | src/renderer/render.cpp | infosia/Raster | e53a6f9c10212ec50951198496800a866f40aaca | [
"MIT"
] | null | null | null | /* distributed under MIT license:
*
* Copyright (c) 2022 Kota Iguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "renderer/render.h"
#include "pch.h"
#include "observer.h"
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image.h>
#include <stb_image_write.h>
#include <chrono>
#include <map>
#include <sstream>
namespace renderer
{
static void generateVignette(Image *dst, const Color bgColor)
{
const auto R = bgColor.R();
const auto B = bgColor.B();
const auto G = bgColor.G();
const auto width = dst->width;
const auto height = dst->height;
for (uint32_t x = 0; x < width; ++x) {
for (uint32_t y = 0; y < height; ++y) {
const auto srcColor = dst->get(x, y);
// Stop filling when pixel is already painted
if (srcColor.A() != 0)
continue;
const float distance = sqrtf(powf((x - width / 2.f), 2) + powf((y - height / 2.f), 2));
const float factor = (height - distance) / height;
Color newColor = Color(R * factor, G * factor, B * factor, 255);
dst->set(x, y, newColor);
}
}
}
static void generateSSAA(Image *dst, const Image *src, uint8_t kernelSize = 2)
{
const uint8_t sq = kernelSize * kernelSize;
dst->reset(src->width / kernelSize, src->height / kernelSize, src->format);
for (uint32_t x = 0; x < dst->width; ++x) {
for (uint32_t y = 0; y < dst->height; ++y) {
uint32_t xx = x * kernelSize;
uint32_t yy = y * kernelSize;
uint32_t R = 0, G = 0, B = 0;
for (int i = 0; i < kernelSize; ++i) {
for (int j = 0; j < kernelSize; ++j) {
Color c = src->get(xx + i, yy + j);
R += c.R();
G += c.G();
B += c.B();
}
}
R /= (float)sq;
G /= (float)sq;
B /= (float)sq;
Color newColor = Color((uint8_t)R, (uint8_t)G, (uint8_t)B, 255);
dst->set(x, y, newColor);
}
}
}
static glm::vec3 barycentric(glm::vec3 &a, glm::vec3 &b, glm::vec3 &c, glm::vec3 &p)
{
const auto v0 = b - a;
const auto v1 = c - a;
const float denom = 1.0f / (v0.x * v1.y - v1.x * v0.y);
const auto v2 = p - a;
const float v = (v2.x * v1.y - v1.x * v2.y) * denom;
const float w = (v0.x * v2.y - v2.x * v0.y) * denom;
const float u = 1.0f - v - w;
return glm::vec3(u, v, w);
}
inline bool inBounds(int x, int y, int width, int height)
{
return (0 <= x && x < width) && (0 <= y && y < height);
}
inline bool isInTriangle(const glm::vec3 tri[3], int width, int height)
{
return inBounds(tri[0].x, tri[0].y, width, height)
|| inBounds(tri[1].x, tri[1].y, width, height)
|| inBounds(tri[2].x, tri[2].y, width, height);
}
inline glm::mat4 getModelMatrix(const Model &model)
{
return glm::translate(model.translation) * glm::toMat4(model.rotation) * glm::scale(model.scale) * glm::mat4(1.f);
}
inline glm::mat4 getViewMatrix(const Camera &camera)
{
glm::vec3 translation = -camera.translation;
translation.z = -translation.z; // Z+
return glm::translate(translation) * glm::toMat4(camera.rotation) * glm::scale(camera.scale);
}
inline glm::mat4 getOrthoMatrix(float width, float height, float near, float far)
{
const float aspect = width / height;
return glm::ortho(aspect, -aspect, 1.f, -1.f, near, far);
}
inline glm::mat4 getPerspectiveMatrix(float width, float height, float fov, float near, float far)
{
return glm::perspectiveFov(glm::radians(fov), width, height, near, far);
}
inline glm::mat4 getProjectionMatrix(uint32_t width, uint32_t height, Camera camera)
{
if (camera.mode == Projection::Orthographic) {
return getOrthoMatrix((float)width, (float)height, camera.znear, camera.zfar);
}
return getPerspectiveMatrix((float)width, (float)height, camera.fov, camera.znear, camera.zfar);
}
inline glm::uvec4 bb(const glm::vec3 tri[3], const int width, const int height)
{
int left = std::min(tri[0].x, std::min(tri[1].x, tri[2].x));
int right = std::max(tri[0].x, std::max(tri[1].x, tri[2].x));
int bottom = std::min(tri[0].y, std::min(tri[1].y, tri[2].y));
int top = std::max(tri[0].y, std::max(tri[1].y, tri[2].y));
left = std::max(left, 0);
right = std::min(right, width - 1);
bottom = std::max(bottom, 0);
top = std::min(top, height - 1);
return glm::uvec4{ left, bottom, right, top };
}
inline bool backfacing(const glm::vec3 tri[3])
{
const auto &a = tri[0];
const auto &b = tri[1];
const auto &c = tri[2];
return (a.x * b.y - a.y * b.x + b.x * c.y - b.y * c.x + c.x * a.y - c.y * a.x) > 0;
}
inline void drawBB(Shader *shader, ShaderContext &ctx, const glm::uvec4 &bbox, glm::vec3 tri[3], glm::vec3 depths)
{
const auto width = shader->framebuffer.width;
const auto height = shader->framebuffer.height;
for (auto y = bbox.y; y != bbox.w + 1; ++y) {
for (auto x = bbox.x; x != bbox.z + 1; ++x) {
auto p = glm::vec3(x, y, 1.f);
glm::vec3 bcoords = barycentric(tri[0], tri[1], tri[2], p);
if (bcoords.x >= 0.0f && bcoords.y >= 0.0f && bcoords.z >= 0.0f) {
const float frag_depth = glm::dot(bcoords, depths);
if (inBounds(x, y, width, height) && frag_depth > shader->zbuffer.at(x + y * width)) {
Color color(0, 0, 0, 0);
const auto discarded = shader->fragment(ctx, bcoords, p, backfacing(tri), color);
if (discarded)
continue;
shader->zbuffer[x + y * width] = frag_depth;
shader->framebuffer.set(x, y, color);
}
}
}
}
}
struct RenderOp
{
RenderOptions *options;
Shader *shader;
ShaderContext *ctx;
Node *node;
Primitive *primitive;
};
static void queue(RenderOptions &options, Shader *shader, ShaderContext &ctx, Node *node, std::map<uint32_t, std::vector<RenderOp>> *renderQueue)
{
if (node->mesh) {
for (auto &primitive : node->mesh->primitives) {
RenderOp op{ &options, shader, &ctx, node, &primitive };
if (primitive.material && primitive.material->vrm0) {
const auto vrm0 = primitive.material->vrm0;
const auto iter = renderQueue->find(vrm0->renderQueue);
if (iter == renderQueue->end()) {
std::vector<RenderOp> queue{ op };
renderQueue->emplace(vrm0->renderQueue, queue);
} else {
iter->second.push_back(op);
}
} else {
const auto iter = renderQueue->find(0);
if (iter == renderQueue->end()) {
std::vector<RenderOp> queue{ op };
renderQueue->emplace(0, queue);
} else {
iter->second.push_back(op);
}
}
}
}
for (const auto child : node->children) {
queue(options, shader, ctx, child, renderQueue);
}
}
static void draw(RenderOp *op)
{
const auto node = op->node;
const auto shader = op->shader;
auto &ctx = *op->ctx;
if (node->skin)
shader->jointMatrices = node->skin->jointMatrices.data();
else
shader->bindMatrix = &node->bindMatrix;
if (node->mesh) {
shader->morphs = &node->mesh->morphs;
shader->primitive = op->primitive;
const uint32_t num_faces = op->primitive->numFaces();
for (uint32_t i = 0; i < num_faces; i++) {
glm::vec3 tri[3] = {
shader->vertex(ctx, i, 0),
shader->vertex(ctx, i, 1),
shader->vertex(ctx, i, 2),
};
const glm::vec3 depths(tri[0].z, tri[1].z, tri[2].z);
if (isInTriangle(tri, shader->framebuffer.width, shader->framebuffer.height)) {
drawBB(shader, ctx, bb(tri, shader->framebuffer.width, shader->framebuffer.height), tri, depths);
}
}
}
}
static void draw(const RenderOptions &options, Shader *shader, ShaderContext &ctx, Node *node)
{
if (node->skin)
shader->jointMatrices = node->skin->jointMatrices.data();
else
shader->bindMatrix = &node->bindMatrix;
if (node->mesh) {
Observable::notifyMessage(SubjectType::Info, "Rendering " + node->name);
shader->morphs = &node->mesh->morphs;
for (const auto &primitive : node->mesh->primitives) {
shader->primitive = &primitive;
const uint32_t num_faces = primitive.numFaces();
for (uint32_t i = 0; i < num_faces; i++) {
glm::vec3 tri[3] = {
shader->vertex(ctx, i, 0),
shader->vertex(ctx, i, 1),
shader->vertex(ctx, i, 2),
};
const glm::vec3 depths(tri[0].z, tri[1].z, tri[2].z);
if (isInTriangle(tri, shader->framebuffer.width, shader->framebuffer.height)) {
drawBB(shader, ctx, bb(tri, shader->framebuffer.width, shader->framebuffer.height), tri, depths);
}
}
}
}
for (const auto child : node->children) {
draw(options, shader, ctx, child);
}
}
bool save(std::string filename, Image &framebuffer)
{
return stbi_write_png(filename.c_str(), framebuffer.width, framebuffer.height, framebuffer.format, framebuffer.buffer(), 0) != 0;
}
bool render(Scene &scene, Image &framebuffer)
{
Observable::notifyProgress(0.0f);
const auto start = std::chrono::system_clock::now();
ShaderContext ctx;
RenderOptions &options = scene.options;
const uint32_t width = options.width * (options.ssaa ? options.ssaaKernelSize : 1);
const uint32_t height = options.height * (options.ssaa ? options.ssaaKernelSize : 1);
Camera &camera = options.camera;
ctx.projection = getProjectionMatrix(width, height, camera);
ctx.view = getViewMatrix(camera);
ctx.model = getModelMatrix(options.model);
ctx.bgColor = options.background;
ctx.camera = camera;
ctx.light = scene.light;
auto zbuffer = std::vector<float>(width * height, std::numeric_limits<float>::min());
framebuffer.reset(width, height, options.format);
DefaultShader standard;
OutlineShader outline;
std::vector<Shader *> shaders{ &standard };
if (options.outline) {
shaders.push_back(&outline);
}
Observable::notifyProgress(0.1f);
std::vector<std::map<uint32_t, std::vector<RenderOp>>> renderQueues;
renderQueues.resize(shaders.size());
#pragma omp parallel for
for (int i = 0; i < shaders.size(); ++i) {
const auto shader = shaders.at(i);
shader->zbuffer = std::vector<float>(width * height, std::numeric_limits<float>::min());
shader->framebuffer.reset(width, height, options.format);
for (auto node : scene.children) {
queue(options, shader, ctx, node, &renderQueues.at(i));
}
}
Observable::notifyProgress(0.2f);
#pragma omp parallel for
for (int i = 0; i < shaders.size(); ++i) {
const auto shader = shaders.at(i);
auto &renderQueue = renderQueues.at(i);
for (auto &queue : renderQueue) {
std::stringstream ss;
ss << "RenderQueue " << queue.first;
Observable::notifyMessage(SubjectType::Info, ss.str());
auto &ops = queue.second;
// z sort for alpha blending
std::sort(ops.begin(), ops.end(), [](RenderOp a, RenderOp b) {
return a.primitive->center.z < b.primitive->center.z;
});
for (auto &op : ops) {
draw(&op);
}
}
}
Observable::notifyProgress(0.7f);
auto dst = framebuffer.buffer();
const auto stride = options.format;
for (uint32_t i = 0; i < zbuffer.size(); ++i) {
for (auto shader : shaders) {
const auto src = shader->framebuffer.buffer();
const auto current = i * stride;
const auto dstDepth = zbuffer.at(i);
const auto srcDepth = shader->zbuffer.at(i);
if (dstDepth < srcDepth) {
zbuffer[i] = srcDepth;
// mix color when alpha is color is set (Used by outline for now)
if (stride == Image::Format::RGBA && (src + current)[3] != 255) {
const auto srcColor = Color(src + current, stride);
const auto dstColor = Color(dst + current, stride);
const auto alpha = srcColor.Af();
Color dstAColor = dstColor * (1.f - alpha);
Color srcAColor = srcColor * alpha;
auto mixed = dstAColor + srcAColor;
memcpy(dst + current, mixed.buffer(), stride);
} else {
memcpy(dst + current, src + current, stride);
}
}
}
}
Observable::notifyProgress(0.8f);
if (options.vignette) {
Observable::notifyMessage(SubjectType::Info, "Generating Vignette");
generateVignette(&framebuffer, ctx.bgColor);
} else {
// Fill the background anywhere pixel alpha equals zero
framebuffer.fill(ctx.bgColor);
}
Observable::notifyProgress(0.9f);
if (options.ssaa) {
Observable::notifyMessage(SubjectType::Info, "Generating SSAA");
Image tmp(options.width, options.height, options.format);
generateSSAA(&tmp, &framebuffer, options.ssaaKernelSize);
framebuffer.reset(options.width, options.height, options.format);
framebuffer.copy(tmp);
}
const auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count();
Observable::notifyMessage(SubjectType::Info, "Rendering done in " + std::to_string(msec) + " msec");
Observable::notifyProgress(1.f);
return true;
}
}
| 38.963218 | 150 | 0.518792 | infosia |
5278996f201a4a3d69282c1bd7b0d230d0f6cd39 | 5,324 | hpp | C++ | 3rdparty/libprocess/3rdparty/stout/include/stout/os/setns.hpp | dharmeshkakadia/mesos | d418c17b89856a9e9d43ece0a7c656f2489a922a | [
"Apache-2.0"
] | 1 | 2015-07-18T09:47:35.000Z | 2015-07-18T09:47:35.000Z | 3rdparty/libprocess/3rdparty/stout/include/stout/os/setns.hpp | dharmeshkakadia/mesos | d418c17b89856a9e9d43ece0a7c656f2489a922a | [
"Apache-2.0"
] | 1 | 2015-12-21T23:47:34.000Z | 2015-12-21T23:47:47.000Z | 3rdparty/libprocess/3rdparty/stout/include/stout/os/setns.hpp | dharmeshkakadia/mesos | d418c17b89856a9e9d43ece0a7c656f2489a922a | [
"Apache-2.0"
] | null | null | null | /**
* 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.
*/
#ifndef __STOUT_OS_SETNS_HPP__
#define __STOUT_OS_SETNS_HPP__
// This file contains Linux-only OS utilities.
#ifndef __linux__
#error "stout/os/setns.hpp is only available on Linux systems."
#endif
#include <sched.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <set>
#include <string>
#include <stout/error.hpp>
#include <stout/hashmap.hpp>
#include <stout/nothing.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/proc.hpp>
#include <stout/stringify.hpp>
#include <stout/try.hpp>
#include <stout/os/exists.hpp>
#include <stout/os/ls.hpp>
namespace os {
// Returns all the supported namespaces by the kernel.
inline std::set<std::string> namespaces()
{
std::set<std::string> result;
Try<std::list<std::string> > entries = os::ls("/proc/self/ns");
if (entries.isSome()) {
foreach (const std::string& entry, entries.get()) {
result.insert(entry);
}
}
return result;
}
// Returns the nstype (e.g., CLONE_NEWNET, CLONE_NEWNS, etc.) for the
// given namespace which will be used when calling ::setns.
inline Try<int> nstype(const std::string& ns)
{
hashmap<std::string, int> nstypes;
#ifdef CLONE_NEWNS
nstypes["mnt"] = CLONE_NEWNS;
#else
nstypes["mnt"] = 0x00020000;
#endif
#ifdef CLONE_NEWUTS
nstypes["uts"] = CLONE_NEWUTS;
#else
nstypes["uts"] = 0x04000000;
#endif
#ifdef CLONE_NEWIPC
nstypes["ipc"] = CLONE_NEWIPC;
#else
nstypes["ipc"] = 0x08000000;
#endif
#ifdef CLONE_NEWNET
nstypes["net"] = CLONE_NEWNET;
#else
nstypes["net"] = 0x40000000;
#endif
#ifdef CLONE_NEWUSER
nstypes["user"] = CLONE_NEWUSER;
#else
nstypes["user"] = 0x10000000;
#endif
#ifdef CLONE_NEWPID
nstypes["pid"] = CLONE_NEWPID;
#else
nstypes["pid"] = 0x20000000;
#endif
if (!nstypes.contains(ns)) {
return Error("Unknown namespace '" + ns + "'");
}
return nstypes[ns];
}
// Re-associate the calling process with the specified namespace. The
// path refers to one of the corresponding namespace entries in the
// /proc/[pid]/ns/ directory (or bind mounted elsewhere). We do not
// allow a process with multiple threads to call this function because
// it will lead to some weird situations where different threads of a
// process are in different namespaces.
inline Try<Nothing> setns(const std::string& path, const std::string& ns)
{
// Return error if there're multiple threads in the calling process.
Try<std::set<pid_t> > threads = proc::threads(::getpid());
if (threads.isError()) {
return Error(
"Failed to get the threads of the current process: " +
threads.error());
} else if (threads.get().size() > 1) {
return Error("Multiple threads exist in the current process");
}
if (os::namespaces().count(ns) == 0) {
return Error("Namespace '" + ns + "' is not supported");
}
// Currently, we don't support pid namespace as its semantics is
// different from other namespaces (instead of re-associating the
// calling thread, it re-associates the *children* of the calling
// thread with the specified namespace).
if (ns == "pid") {
return Error("Pid namespace is not supported");
}
#ifdef O_CLOEXEC
Try<int> fd = os::open(path, O_RDONLY | O_CLOEXEC);
#else
Try<int> fd = os::open(path, O_RDONLY);
#endif
if (fd.isError()) {
return Error("Failed to open '" + path + "': " + fd.error());
}
#ifndef O_CLOEXEC
Try<Nothing> cloexec = os::cloexec(fd.get());
if (cloexec.isError()) {
os::close(fd.get());
return Error("Failed to cloexec: " + cloexec.error());
}
#endif
Try<int> nstype = os::nstype(ns);
if (nstype.isError()) {
return Error(nstype.error());
}
#ifdef SYS_setns
int ret = ::syscall(SYS_setns, fd.get(), nstype.get());
#elif __x86_64__
// A workaround for those hosts that have an old glibc (older than
// 2.14) but have a new kernel. The magic number '308' here is the
// syscall number for 'setns' on x86_64 architecture.
int ret = ::syscall(308, fd.get(), nstype.get());
#else
#error "setns is not available"
#endif
if (ret == -1) {
// Save the errno as it might be overwritten by 'os::close' below.
ErrnoError error;
os::close(fd.get());
return error;
}
os::close(fd.get());
return Nothing();
}
// Re-associate the calling process with the specified namespace. The
// pid specifies the process whose namespace we will associate.
inline Try<Nothing> setns(pid_t pid, const std::string& ns)
{
if (!os::exists(pid)) {
return Error("Pid " + stringify(pid) + " does not exist");
}
std::string path = path::join("/proc", stringify(pid), "ns", ns);
if (!os::exists(path)) {
return Error("Namespace '" + ns + "' is not supported");
}
return os::setns(path, ns);
}
} // namespace os {
#endif // __STOUT_OS_SETNS_HPP__
| 26.098039 | 75 | 0.680503 | dharmeshkakadia |
527a5477df3948238a67398ef99b72c8c6744789 | 1,462 | hpp | C++ | src/algorithms/math/sum_of_multiples.hpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 2 | 2020-07-31T14:13:56.000Z | 2021-02-03T09:51:43.000Z | src/algorithms/math/sum_of_multiples.hpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 28 | 2015-09-22T07:38:21.000Z | 2018-10-02T11:00:58.000Z | src/algorithms/math/sum_of_multiples.hpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 2 | 2018-10-11T14:10:50.000Z | 2021-02-27T08:53:50.000Z | #ifndef SUM_OF_MULTIPLES_OF_3_AND_5_HPP
#define SUM_OF_MULTIPLES_OF_3_AND_5_HPP
// https://projecteuler.net/problem=1
// If we list all the natural numbers below 10 that are multiples of 3 or 5,
// we get 3, 5, 6 and 9. The sum of these multiples is 23.
// Find the sum of all the multiples of 3 or 5 below 1000.
// Answer: 233168
#include <iostream>
#include <vector>
#include <algorithm>
namespace SumOfMultiples {
class Solution {
public:
unsigned int SumOfMultiples(const unsigned int& first,
const unsigned int& second,
const unsigned int& limit) {
unsigned int sumFirst = SumOfNumbersDivisebleByN(first, limit);
unsigned int sumSecond = SumOfNumbersDivisebleByN(second, limit);
unsigned int sumMultFirstSecond =
SumOfNumbersDivisebleByN(first * second, limit);
return sumFirst + sumSecond - sumMultFirstSecond;
}
private:
// Example: 3 and 1000 (non-inclusive)
// (1000 - 1) / 3 = 333 - number of multiples
// 3 + 6 + 9 + ... + 999 - 333 numbers
// 3 + 6 + 9 + ... + 999 ==
// 3 * (1 + 2 + 3 + ... + 333) ==
// 3 * 333 * (333 + 1) / 2
unsigned int SumOfNumbersDivisebleByN(const unsigned int& n,
const unsigned int& limit) {
unsigned int p = (limit -1) / n;
return (n * p * (p + 1)) / 2;
}
};
}
#endif // SUM_OF_MULTIPLES_OF_3_AND_5_HPP
| 31.106383 | 76 | 0.602599 | iamantony |
527bdf32aa48375a0031e961fc8f563997fa6425 | 4,575 | cpp | C++ | Engine/Source/Vulkan/VulkanRHICache.cpp | DanDanCool/GameEngine | 9afae8bc31c7e34b9afde0f01a5735607eb7870e | [
"Apache-2.0"
] | 1 | 2021-09-20T01:50:29.000Z | 2021-09-20T01:50:29.000Z | Engine/Source/Vulkan/VulkanRHICache.cpp | DanDanCool/GameEngine | 9afae8bc31c7e34b9afde0f01a5735607eb7870e | [
"Apache-2.0"
] | null | null | null | Engine/Source/Vulkan/VulkanRHICache.cpp | DanDanCool/GameEngine | 9afae8bc31c7e34b9afde0f01a5735607eb7870e | [
"Apache-2.0"
] | null | null | null | #include "VulkanRHICache.h"
#include "jpch.h"
#include "VulkanContext.h"
#include "VulkanPipeline.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
namespace VKRHI
{
VulkanRHICache::VulkanRHICache()
: m_VertexBuffer()
, m_IndexBuffer()
, m_ProjectionMatrix()
, m_DescriptorPool(VK_NULL_HANDLE)
, m_DescriptorSets()
, m_Context(nullptr)
, m_bDirty(false)
{
}
void VulkanRHICache::Init(VulkanContext* context)
{
m_Context = context;
glm::mat4 proj = glm::ortho(-16.0f / 9.0f, 16.0f / 9.0f, -1.0f, 1.0f);
// proj[1][1] *= -1;
BufferInfo bufferInfo{};
bufferInfo.Usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
bufferInfo.Size = sizeof(proj);
bufferInfo.MemoryFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
m_ProjectionMatrix = m_Context->GetRHI().CreateBuffer(bufferInfo);
m_ProjectionMatrix.SetData(sizeof(proj), &proj);
m_Framebuffers = m_Context->GetSwapchain()->CreateFramebuffers(m_Context->GetPipeline()->GetRenderPass());
// really bad
{
BufferInfo vbInfo;
vbInfo.Size = 100 * sizeof(float);
vbInfo.Usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
vbInfo.MemoryFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
BufferInfo ibInfo;
ibInfo.Size = 100 * sizeof(uint16_t);
ibInfo.Usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
ibInfo.MemoryFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
m_VertexBuffer = m_Context->GetRHI().CreateBuffer(vbInfo);
m_IndexBuffer = m_Context->GetRHI().CreateBuffer(ibInfo);
}
// create the descriptor sets
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = (uint32_t)m_Framebuffers.size();
VkDescriptorPoolCreateInfo descriptorPoolInfo{};
descriptorPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
descriptorPoolInfo.poolSizeCount = 1;
descriptorPoolInfo.pPoolSizes = &poolSize;
descriptorPoolInfo.maxSets = (uint32_t)m_Framebuffers.size();
VkDevice device = m_Context->GetRHI().GetDevice().GetHandle();
VkResult result = vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &m_DescriptorPool);
assert(result == VK_SUCCESS);
std::vector<VkDescriptorSetLayout> layouts(m_Framebuffers.size(),
m_Context->GetPipeline()->GetDescriptorSetLayout());
VkDescriptorSetAllocateInfo allocateInfo{};
allocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocateInfo.descriptorPool = m_DescriptorPool;
allocateInfo.descriptorSetCount = (uint32_t)m_Framebuffers.size();
allocateInfo.pSetLayouts = layouts.data();
m_DescriptorSets.resize(m_Framebuffers.size());
result = vkAllocateDescriptorSets(device, &allocateInfo, m_DescriptorSets.data());
assert(result == VK_SUCCESS);
for (size_t i = 0; i < m_DescriptorSets.size(); i++)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = m_ProjectionMatrix.GetHandle();
bufferInfo.offset = 0;
bufferInfo.range = sizeof(glm::mat4);
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = m_DescriptorSets[i];
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
}
void VulkanRHICache::Shutdown()
{
VkDevice device = m_Context->GetRHI().GetDevice().GetHandle();
for (auto& framebuffer : m_Framebuffers)
framebuffer.Free(device);
vkDestroyDescriptorPool(device, m_DescriptorPool, nullptr);
m_VertexBuffer.Free();
m_IndexBuffer.Free();
m_ProjectionMatrix.Free();
}
} // namespace VKRHI
| 38.125 | 114 | 0.64612 | DanDanCool |
528122c614618d2ecdc2c0adc4921b30e8978edd | 6,884 | cpp | C++ | awsconnection.cpp | recaisinekli/aws-iot-device-sdk-qt-integration | 9ba0b3aa4509e72667f3ccc58f3d0eee2c1f861c | [
"Apache-2.0"
] | null | null | null | awsconnection.cpp | recaisinekli/aws-iot-device-sdk-qt-integration | 9ba0b3aa4509e72667f3ccc58f3d0eee2c1f861c | [
"Apache-2.0"
] | null | null | null | awsconnection.cpp | recaisinekli/aws-iot-device-sdk-qt-integration | 9ba0b3aa4509e72667f3ccc58f3d0eee2c1f861c | [
"Apache-2.0"
] | null | null | null | #include "awsconnection.h"
AWSConnection::AWSConnection(QObject *parent) : QObject(parent)
{
}
bool AWSConnection::init(){
bool state = true;
Io::EventLoopGroup eventLoopGroup(1);
if (!eventLoopGroup)
{
fprintf(stderr, "Event Loop Group Creation failed with error %s\n", ErrorDebugString(eventLoopGroup.LastError()));
state = false;
}
Aws::Crt::Io::DefaultHostResolver defaultHostResolver(eventLoopGroup, 1, 5);
Io::ClientBootstrap bootstrap(eventLoopGroup, defaultHostResolver);
if (!bootstrap)
{
fprintf(stderr, "ClientBootstrap failed with error %s\n", ErrorDebugString(bootstrap.LastError()));
state = false;
}
Aws::Iot::MqttClientConnectionConfigBuilder builder;
builder = Aws::Iot::MqttClientConnectionConfigBuilder(m_path_to_crt.toStdString().c_str(), m_path_to_private_key.toStdString().c_str());
builder.WithCertificateAuthority(m_path_to_ca.toStdString().c_str());
builder.WithEndpoint(m_endpoint.toStdString().c_str());
auto clientConfig = builder.Build();
if (!clientConfig)
{
fprintf(stderr,"Client Configuration initialization failed with error %s\n",ErrorDebugString(clientConfig.LastError()));
state = false;
}
m_mqttClient = new Aws::Iot::MqttClient(bootstrap);
if (!m_mqttClient)
{
fprintf(stderr, "MQTT Client Creation failed with error %s\n", ErrorDebugString(m_mqttClient->LastError()));
state = false;
}
m_connection = m_mqttClient->NewConnection(clientConfig);
if (!m_connection)
{
fprintf(stderr, "MQTT Connection Creation failed with error %s\n", ErrorDebugString(m_mqttClient->LastError()));
state = false;
}
auto onConnectionCompleted = [&](Mqtt::MqttConnection &, int errorCode, Mqtt::ReturnCode returnCode, bool) {
if (errorCode)
{
fprintf(stdout, "Connection failed with error %s\n", ErrorDebugString(errorCode));
connectionCompletedPromise.set_value(false);
}
else
{
if (returnCode != AWS_MQTT_CONNECT_ACCEPTED)
{
fprintf(stdout, "Connection failed with mqtt return code %d\n", (int)returnCode);
connectionCompletedPromise.set_value(false);
}
else
{
fprintf(stdout, "Connection completed successfully.\n");
connectionCompletedPromise.set_value(true);
}
}
};
auto onInterrupted = [&](Mqtt::MqttConnection &, int error) {
fprintf(stdout, "Connection interrupted with error %s\n", ErrorDebugString(error));
};
auto onResumed = [&](Mqtt::MqttConnection &, Mqtt::ReturnCode, bool) { fprintf(stdout, "Connection resumed\n"); };
auto onDisconnect = [&](Mqtt::MqttConnection &) {
{
fprintf(stdout, "Disconnect completed\n");
connectionClosedPromise.set_value();
}
};
m_connection->OnConnectionCompleted = std::move(onConnectionCompleted);
m_connection->OnDisconnect = std::move(onDisconnect);
m_connection->OnConnectionInterrupted = std::move(onInterrupted);
m_connection->OnConnectionResumed = std::move(onResumed);
String topic(m_topic.toStdString().c_str());
String clientId(String("test-") + Aws::Crt::UUID().ToString());
qDebug()<<"Connecting...\n";
if (!m_connection->Connect(clientId.c_str(), false, 1000))
{
fprintf(stderr, "MQTT Connection failed with error %s\n", ErrorDebugString(m_connection->LastError()));
state = false;
}
if (connectionCompletedPromise.get_future().get())
{
auto onMessage = [&](Mqtt::MqttConnection &,
const String &topic,
const ByteBuf &byteBuf,
bool,
Mqtt::QOS,
bool) {
QString _topic = QString(topic.c_str());
QString _message = QString::fromUtf8(reinterpret_cast<char *>(byteBuf.buffer), byteBuf.len);
this->message_received_func(_message);
};
std::promise<void> subscribeFinishedPromise;
auto onSubAck =
[&](Mqtt::MqttConnection &, uint16_t packetId, const String &topic, Mqtt::QOS QoS, int errorCode) {
if (errorCode)
{
fprintf(stderr, "Subscribe failed with error %s\n", aws_error_debug_str(errorCode));
state = false;
}
else
{
if (!packetId || QoS == AWS_MQTT_QOS_FAILURE)
{
fprintf(stderr, "Subscribe rejected by the broker.");
state = false;
}
else
{
fprintf(stdout, "Subscribe on topic %s on packetId %d Succeeded\n", topic.c_str(), packetId);
}
}
subscribeFinishedPromise.set_value();
};
m_connection->Subscribe(topic.c_str(), AWS_MQTT_QOS_AT_LEAST_ONCE, onMessage, onSubAck);
subscribeFinishedPromise.get_future().wait();
}
return state;
}
void AWSConnection::unsubscribe(){
std::promise<void> unsubscribeFinishedPromise;
m_connection->Unsubscribe(
m_topic.toStdString().c_str(), [&](Mqtt::MqttConnection &, uint16_t, int) { unsubscribeFinishedPromise.set_value(); });
unsubscribeFinishedPromise.get_future().wait();
}
void AWSConnection::disconnect(){
if (m_connection->Disconnect())
{
connectionClosedPromise.get_future().wait();
}
}
void AWSConnection::set_crt_path(QString crt_path){
m_path_to_crt = crt_path;
}
void AWSConnection::set_ca_path(QString ca_path){
m_path_to_ca = ca_path;
}
void AWSConnection::set_private_key_path(QString key_path){
m_path_to_private_key = key_path;
}
void AWSConnection::set_enpoint(QString endpoint){
m_endpoint = endpoint;
}
void AWSConnection::set_topic(QString topic){
m_topic = topic;
}
void AWSConnection::message_received_func(QString message){
emit message_received_signal(message);
}
void AWSConnection::send_message(QString message){
std::string input = message.toStdString().c_str();
ByteBuf payload = ByteBufNewCopy(DefaultAllocator(), (const uint8_t *)input.data(), input.length());
ByteBuf *payloadPtr = &payload;
auto onPublishComplete = [payloadPtr](Mqtt::MqttConnection &, uint16_t packetId, int errorCode) {
aws_byte_buf_clean_up(payloadPtr);
if (packetId)
{
fprintf(stdout, "Operation on packetId %d Succeeded\n", packetId);
}
else
{
fprintf(stdout, "Operation failed with error %s\n", aws_error_debug_str(errorCode));
}
};
m_connection->Publish(m_topic.toStdString().c_str(), AWS_MQTT_QOS_AT_LEAST_ONCE, false, payload, onPublishComplete);
}
| 32.780952 | 140 | 0.633934 | recaisinekli |
5281beb60cb59b280a611d92f69c6cf314acbb4e | 1,329 | hpp | C++ | src/mbgl/shader/symbol_icon_shader.hpp | followtherider/mapbox-gl-native | 62b56b799a7d4fcd1a8f151eed878054b862da5b | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/shader/symbol_icon_shader.hpp | followtherider/mapbox-gl-native | 62b56b799a7d4fcd1a8f151eed878054b862da5b | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/shader/symbol_icon_shader.hpp | followtherider/mapbox-gl-native | 62b56b799a7d4fcd1a8f151eed878054b862da5b | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #pragma once
#include <mbgl/gl/shader.hpp>
#include <mbgl/gl/attribute.hpp>
#include <mbgl/gl/uniform.hpp>
namespace mbgl {
class SymbolVertex;
class SymbolIconShader : public gl::Shader {
public:
SymbolIconShader(gl::Context&, Defines defines = None);
using VertexType = SymbolVertex;
gl::Attribute<int16_t, 2> a_pos = { "a_pos", *this };
gl::Attribute<int16_t, 2> a_offset = { "a_offset", *this };
gl::Attribute<uint16_t, 2> a_texture_pos = { "a_texture_pos", *this };
gl::Attribute<uint8_t, 4> a_data = { "a_data", *this };
gl::UniformMatrix<4> u_matrix = {"u_matrix", *this};
gl::Uniform<std::array<float, 2>> u_extrude_scale = {"u_extrude_scale", *this};
gl::Uniform<float> u_zoom = {"u_zoom", *this};
gl::Uniform<float> u_opacity = {"u_opacity", *this};
gl::Uniform<std::array<float, 2>> u_texsize = {"u_texsize", *this};
gl::Uniform<int32_t> u_rotate_with_map = {"u_rotate_with_map", *this};
gl::Uniform<int32_t> u_texture = {"u_texture", *this};
gl::Uniform<int32_t> u_fadetexture = {"u_fadetexture", *this};
};
} // namespace mbgl
| 40.272727 | 87 | 0.551543 | followtherider |
5281c30c6b6d7bd81ef9284c262126f764d9ad0c | 4,170 | cpp | C++ | src/gameoflife_test.cpp | meteoritenhagel/conways_game_of_life | 5a15cc008b9e7b700cd1c900bcc2509a3a22f233 | [
"MIT"
] | null | null | null | src/gameoflife_test.cpp | meteoritenhagel/conways_game_of_life | 5a15cc008b9e7b700cd1c900bcc2509a3a22f233 | [
"MIT"
] | null | null | null | src/gameoflife_test.cpp | meteoritenhagel/conways_game_of_life | 5a15cc008b9e7b700cd1c900bcc2509a3a22f233 | [
"MIT"
] | null | null | null | #include "gameoflife_test.h"
#include "gameoflife.h"
#include <iostream>
void GameOfLife_Test::testAll()
{
// invoke all tests
testTogglingCellStatus();
testNeighbourUpdateWhenAddingCell();
testNeighbourUpdateWhenAddingAndRemovingCell();
testComplexGridNeighbours();
}
void GameOfLife_Test::testTogglingCellState()
{
bool testPassed = true;
GameOfLife game(5, 5);
const GameOfLife::SizeType i_toggle = 2;
const GameOfLife::SizeType j_toggle = 3;
// toggle cell
game.toggleCellState(i_toggle, j_toggle);
// check if everything is correct
// only the toggled cell should be alive
for (GameOfLife::SizeType i = 0; i < game.getHeight(); ++i)
for (GameOfLife::SizeType j = 0; j < game.getWidth(); ++j)
{
if (i == i_toggle && j == j_toggle)
testPassed = testPassed && game.isCellAlive(i, j);
else
testPassed = testPassed && !(game.isCellAlive(i, j));
}
std::cout << "testTogglingCellStatus: " << testPassedMessage[testPassed] << std::endl;
return;
}
void GameOfLife_Test::testNeighbourUpdateWhenAddingCell()
{
bool testPassed = true;
const int size = 5;
GameOfLife game(size, size);
// toggle two cells
game.toggleCellState(2, 3);
game.toggleCellState(1, 1);
// test against manually calculated grid of neighbours
const int correctNeighbours[size][size] = {1, 1, 1, 0, 0,
1, 0, 2, 1, 1,
1, 1, 2, 0, 1,
0, 0, 1, 1, 1,
0, 0, 0, 0, 0};
for (GameOfLife::SizeType i = 0; i < game.getHeight(); ++i)
for (GameOfLife::SizeType j = 0; j < game.getWidth(); ++j)
testPassed = testPassed && (game.getNumberOfNeighbours(i, j) == correctNeighbours[i][j]);
std::cout << "testNeighbourUpdateWhenAddingCell: " << testPassedMessage[testPassed] << std::endl;
return;
}
void GameOfLife_Test::testNeighbourUpdateWhenAddingAndRemovingCell()
{
bool testPassed = true;
const int size = 5;
GameOfLife game(size, size);
// toggle cells
game.toggleCellState(2, 3);
game.toggleCellState(1, 1);
game.toggleCellState(2, 3);
// test against manually calculated grid of neighbours
const int correctNeighbours[size][size] = {
1, 1, 1, 0, 0,
1, 0, 1, 0, 0,
1, 1, 1, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
for (GameOfLife::SizeType i = 0; i < game.getHeight(); ++i)
for (GameOfLife::SizeType j = 0; j < game.getWidth(); ++j)
testPassed = testPassed && (game.getNumberOfNeighbours(i, j) == correctNeighbours[i][j]);
std::cout << "testNeighbourUpdateWhenAddingAndRemovingCell: " << testPassedMessage[testPassed] << std::endl;
return;
}
void GameOfLife_Test::testComplexGridNeighbours()
{
bool testPassed = true;
const int size = 5;
GameOfLife game(size, size);
// toggle cells
game.toggleCellState(0, 1);
game.toggleCellState(1, 0);
game.toggleCellState(1, 1);
game.toggleCellState(1, 3);
game.toggleCellState(2, 0);
game.toggleCellState(2, 2);
game.toggleCellState(3, 3);
game.toggleCellState(4, 0);
game.toggleCellState(4, 1);
game.toggleCellState(4, 2);
game.toggleCellState(4, 4);
// test against manually calculated grid of neighbours
const int correctNeighbours[size][size] = {
3, 2, 3, 1, 1,
3, 4, 4, 1, 1,
2, 4, 3, 3, 2,
3, 5, 4, 3, 2,
1, 2, 2, 3, 1
};
for (GameOfLife::SizeType i = 0; i < game.getHeight(); ++i)
for (GameOfLife::SizeType j = 0; j < game.getWidth(); ++j)
testPassed = testPassed && (game.getNumberOfNeighbours(i, j) == correctNeighbours[i][j]);
std::cout << "testComplexGridNeighbours: " << testPassedMessage[testPassed] << std::endl;
return;
}
std::map<bool, std::string> GameOfLife_Test::testPassedMessage = {
{true, "passed"},
{false, "FAILED"}
};
| 29.785714 | 112 | 0.584892 | meteoritenhagel |
528355a5c46201bd35e151049bef5689434dd601 | 1,080 | cpp | C++ | apps/2d/advection/sine_example/AfterQinit.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | apps/2d/advection/sine_example/AfterQinit.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | apps/2d/advection/sine_example/AfterQinit.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | #include <cmath>
#include <iostream>
#include "dogdefs.h"
#include "IniParams.h"
#include "DogSolverCart2.h"
class DogSolverCart2;
void AfterQinit(DogSolverCart2& solver)
{
DogStateCart2* dogStateCart2 = &solver.fetch_dogStateCart2();
dTensorBC4& qnew = dogStateCart2->fetch_q();
dTensorBC4& aux = dogStateCart2->fetch_aux();
const int mx = qnew.getsize(1);
const int my = qnew.getsize(2);
const int meqn = qnew.getsize(3);
const int kmax = qnew.getsize(4);
const int mbc = qnew.getmbc();
const int maux = aux.getsize(3);
for(int i=1-mbc; i <= mx+mbc; i++ )
for(int j=1-mbc; j <= my+mbc; j++ )
{
// flatten out any cells that are negative
if( qnew.get(i,j,1,1) < 1e-13 )
{
for( int k=1 ; k <= kmax; k++ )
{
qnew.set(i,j,1,k, 0.0 );
}
}
}
// void ApplyPosLimiter(const dTensorBC4& aux, dTensorBC4& q);
// if( global_ini_params.using_moment_limiter() )
// {
// ApplyPosLimiter(aux, qnew);
// }
}
| 25.714286 | 65 | 0.566667 | dcseal |
52847f6a8298ad61698f6ed0084b9342f6b08fc5 | 762 | hpp | C++ | test/src/Algorithm/FindIf.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | 48 | 2019-05-14T10:07:08.000Z | 2021-04-08T08:26:20.000Z | test/src/Algorithm/FindIf.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | null | null | null | test/src/Algorithm/FindIf.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | 4 | 2019-11-18T15:35:32.000Z | 2021-12-02T05:23:04.000Z | #include "CppML/CppML.hpp"
namespace FindIfTest {
template <typename T> using Predicate = ml::f<ml::IsSame<>, char, T>;
template <typename T> struct R {};
void run() {
{
using T = ml::f<ml::FindIf<ml::F<Predicate>, ml::F<R>>, int, char, bool>;
static_assert(std::is_same<T, R<char>>::value,
"FindIf with a non-empty pack 1");
}
{
using T =
ml::f<ml::FindIf<ml::F<Predicate>, ml::F<R>>, int, double, int, char>;
static_assert(std::is_same<T, R<char>>::value,
"FindIf with a non-empty pack 2");
}
{
using T = ml::f<ml::FindIf<ml::F<Predicate>, ml::F<R>>>;
static_assert(std::is_same<T, R<ml::None>>::value,
"FindIf with empty pack");
}
}
} // namespace FindIfTest
| 29.307692 | 78 | 0.568241 | changjurhee |
528487b78082d510660b1cc934f048ec41668cab | 32,568 | hxx | C++ | couchbase/errors.hxx | jrawsthorne/couchbase-cxx-client | b8fea51f900af80abe09cbdda90aef944b05c10a | [
"Apache-2.0"
] | null | null | null | couchbase/errors.hxx | jrawsthorne/couchbase-cxx-client | b8fea51f900af80abe09cbdda90aef944b05c10a | [
"Apache-2.0"
] | null | null | null | couchbase/errors.hxx | jrawsthorne/couchbase-cxx-client | b8fea51f900af80abe09cbdda90aef944b05c10a | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2020-2021 Couchbase, Inc.
*
* 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 <system_error>
namespace couchbase::error
{
enum class common_errc {
/// A request is cancelled and cannot be resolved in a non-ambiguous way. Most likely the request is in-flight on the socket and the
/// socket gets closed.
request_canceled = 2,
/// It is unambiguously determined that the error was caused because of invalid arguments from the user.
/// Usually only thrown directly when doing request arg validation
invalid_argument = 3,
/// It can be determined from the config unambiguously that a given service is not available. I.e. no query node in the config, or a
/// memcached bucket is accessed and views or n1ql queries should be performed
service_not_available = 4,
/// Query: Error range 5xxx
/// Analytics: Error range 25xxx
/// KV: error code ERR_INTERNAL (0x84)
/// Search: HTTP 500
internal_server_failure = 5,
/// Query: Error range 10xxx
/// Analytics: Error range 20xxx
/// View: HTTP status 401
/// KV: error code ERR_ACCESS (0x24), ERR_AUTH_ERROR (0x20), AUTH_STALE (0x1f)
/// Search: HTTP status 401, 403
authentication_failure = 6,
/// Analytics: Errors: 23000, 23003
/// KV: Error code ERR_TMPFAIL (0x86), ERR_BUSY (0x85) ERR_OUT_OF_MEMORY (0x82), ERR_NOT_INITIALIZED (0x25)
temporary_failure = 7,
/// Query: code 3000
/// Analytics: codes 24000
parsing_failure = 8,
/// KV: ERR_EXISTS (0x02) when replace or remove with cas
/// Query: code 12009
cas_mismatch = 9,
/// A request is made but the current bucket is not found
bucket_not_found = 10,
/// A request is made but the current collection (including scope) is not found
collection_not_found = 11,
/// KV: 0x81 (unknown command), 0x83 (not supported)
unsupported_operation = 12,
/// A timeout occurs and we aren't sure if the underlying operation has completed. This normally occurs because we sent the request to
/// the server successfully, but timed out waiting for the response. Note that idempotent operations should never return this, as they
/// do not have ambiguity.
ambiguous_timeout = 13,
/// A timeout occurs and we are confident that the operation could not have succeeded. This normally would occur because we received
/// confident failures from the server, or never managed to successfully dispatch the operation.
unambiguous_timeout = 14,
/// A feature which is not available was used.
feature_not_available = 15,
/// A management API attempts to target a scope which does not exist.
scope_not_found = 16,
/// Query: Codes 12004, 12016 (warning: regex ahead!) Codes 5000 AND message contains index .+ not found
/// Analytics: Raised When 24047
/// Search: Http status code 400 AND text contains “index not found”
index_not_found = 17,
/// Query:
/// Note: the uppercase index for 5000 is not a mistake (also only match on exist not exists because there is a typo
/// somewhere in query engine which might either print exist or exists depending on the codepath)
/// Code 5000 AND message contains Index .+ already exist
/// Code 4300 AND message contains index .+ already exist
///
/// Analytics: Raised When 24048
index_exists = 18,
/// Raised when encoding of a user object failed while trying to write it to the cluster
encoding_failure = 19,
/// Raised when decoding of the data into the user object failed
decoding_failure = 20,
/**
* Raised when a service decides that the caller must be rate limited due to exceeding a rate threshold of some sort.
*
* * KeyValue
* 0x30 RateLimitedNetworkIngress -> NetworkIngressRateLimitReached
* 0x31 RateLimitedNetworkEgress -> NetworkEgressRateLimitReached
* 0x32 RateLimitedMaxConnections -> MaximumConnectionsReached
* 0x33 RateLimitedMaxCommands -> RequestRateLimitReached
*
* * Cluster Manager (body check tbd)
* HTTP 429, Body contains "Limit(s) exceeded [num_concurrent_requests]" -> ConcurrentRequestLimitReached
* HTTP 429, Body contains "Limit(s) exceeded [ingress]" -> NetworkIngressRateLimitReached
* HTTP 429, Body contains "Limit(s) exceeded [egress]" -> NetworkEgressRateLimitReached
* Note: when multiple user limits are exceeded the array would contain all the limits exceeded, as "Limit(s) exceeded
* [num_concurrent_requests,egress]"
*
* * Query
* Code 1191, Message E_SERVICE_USER_REQUEST_EXCEEDED -> RequestRateLimitReached
* Code 1192, Message E_SERVICE_USER_REQUEST_RATE_EXCEEDED -> ConcurrentRequestLimitReached
* Code 1193, Message E_SERVICE_USER_REQUEST_SIZE_EXCEEDED -> NetworkIngressRateLimitReached
* Code 1194, Message E_SERVICE_USER_RESULT_SIZE_EXCEEDED -> NetworkEgressRateLimitReached
*
* * Search
* HTTP 429, {"status": "fail", "error": "num_concurrent_requests, value >= limit"} -> ConcurrentRequestLimitReached
* HTTP 429, {"status": "fail", "error": "num_queries_per_min, value >= limit"}: -> RequestRateLimitReached
* HTTP 429, {"status": "fail", "error": "ingress_mib_per_min >= limit"} -> NetworkIngressRateLimitReached
* HTTP 429, {"status": "fail", "error": "egress_mib_per_min >= limit"} -> NetworkEgressRateLimitReached
*
* * Analytics
* Not applicable at the moment.
*
* * Views
* Not applicable.
*/
rate_limited = 21,
/**
* Raised when a service decides that the caller must be limited due to exceeding a quota threshold of some sort.
*
* * KeyValue
* 0x34 ScopeSizeLimitExceeded
*
* * Cluster Manager
* HTTP 429, Body contains "Maximum number of collections has been reached for scope "<scope_name>""
*
* * Query
* Code 5000, Body contains "Limit for number of indexes that can be created per scope has been reached. Limit : value"
*
* * Search
* HTTP 400 (Bad request), {"status": "fail", "error": "rest_create_index: error creating index: {indexName}, err: manager_api:
* CreateIndex, Prepare failed, err: num_fts_indexes (active + pending) >= limit"}
* * Analytics
* Not applicable at the moment
*
* * Views
* Not applicable
*/
quota_limited = 22,
};
/// Errors for related to KeyValue service (kv_engine)
enum class key_value_errc {
/// The document requested was not found on the server.
/// KV Code 0x01
document_not_found = 101,
/// In get_any_replica, the get_all_replicas returns an empty stream because all the individual errors are dropped (i.e. all returned a
/// document_not_found)
document_irretrievable = 102,
/// The document requested was locked.
/// KV Code 0x09
document_locked = 103,
/// The value that was sent was too large to store (typically > 20MB)
/// KV Code 0x03
value_too_large = 104,
/// An operation which relies on the document not existing fails because the document existed.
/// KV Code 0x02
document_exists = 105,
/// The specified durability level is invalid.
/// KV Code 0xa0
durability_level_not_available = 107,
/// The specified durability requirements are not currently possible (for example, there are an insufficient number of replicas online).
/// KV Code 0xa1
durability_impossible = 108,
/// A sync-write has not completed in the specified time and has an ambiguous result - it may have succeeded or failed, but the final
/// result is not yet known.
/// A SEQNO OBSERVE operation is performed and the vbucket UUID changes during polling.
/// KV Code 0xa3
durability_ambiguous = 109,
/// A durable write is attempted against a key which already has a pending durable write.
/// KV Code 0xa2
durable_write_in_progress = 110,
/// The server is currently working to synchronize all replicas for previously performed durable operations (typically occurs after a
/// rebalance).
/// KV Code 0xa4
durable_write_re_commit_in_progress = 111,
/// The path provided for a sub-document operation was not found.
/// KV Code 0xc0
path_not_found = 113,
/// The path provided for a sub-document operation did not match the actual structure of the document.
/// KV Code 0xc1
path_mismatch = 114,
/// The path provided for a sub-document operation was not syntactically correct.
/// KV Code 0xc2
path_invalid = 115,
/// The path provided for a sub-document operation is too long, or contains too many independent components.
/// KV Code 0xc3
path_too_big = 116,
/// The document contains too many levels to parse.
/// KV Code 0xc4
path_too_deep = 117,
/// The value provided, if inserted into the document, would cause the document to become too deep for the server to accept.
/// KV Code 0xca
value_too_deep = 118,
/// The value provided for a sub-document operation would invalidate the JSON structure of the document if inserted as requested.
/// KV Code 0xc5
value_invalid = 119,
/// A sub-document operation is performed on a non-JSON document.
/// KV Code 0xc6
document_not_json = 120,
/// The existing number is outside the valid range for arithmetic operations.
/// KV Code 0xc7
number_too_big = 121,
/// The delta value specified for an operation is too large.
/// KV Code 0xc8
delta_invalid = 122,
/// A sub-document operation which relies on a path not existing encountered a path which exists.
/// KV Code 0xc9
path_exists = 123,
/// A macro was used which the server did not understand.
/// KV Code: 0xd0
xattr_unknown_macro = 124,
/// A sub-document operation attempts to access multiple xattrs in one operation.
/// KV Code: 0xcf
xattr_invalid_key_combo = 126,
/// A sub-document operation attempts to access an unknown virtual attribute.
/// KV Code: 0xd1
xattr_unknown_virtual_attribute = 127,
/// A sub-document operation attempts to modify a virtual attribute.
/// KV Code: 0xd2
xattr_cannot_modify_virtual_attribute = 128,
/// The user does not have permission to access the attribute. Occurs when the user attempts to read or write a system attribute (name
/// starts with underscore) but does not have the SystemXattrRead / SystemXattrWrite permission.
/// KV Code: 0x24
xattr_no_access = 130,
/// Only deleted document could be revived
/// KV Code: 0xd6
cannot_revive_living_document = 131,
};
/// Errors related to Query service (N1QL)
enum class query_errc {
/// Raised When code range 4xxx other than those explicitly covered
planning_failure = 201,
/// Raised When code range 12xxx and 14xxx (other than 12004 and 12016)
index_failure = 202,
/// Raised When codes 4040, 4050, 4060, 4070, 4080, 4090
prepared_statement_failure = 203,
/// Raised when code 12009 AND message does not contain CAS mismatch
dml_failure = 204,
};
/// Errors related to Analytics service (CBAS)
enum class analytics_errc {
/// Error range 24xxx (excluded are specific codes in the errors below)
compilation_failure = 301,
/// Error code 23007
job_queue_full = 302,
/// Error codes 24044, 24045, 24025
dataset_not_found = 303,
/// Error code 24034
dataverse_not_found = 304,
/// Raised When 24040
dataset_exists = 305,
/// Raised When 24039
dataverse_exists = 306,
/// Raised When 24006
link_not_found = 307,
/// Raised When 24055
link_exists = 308,
};
/// Errors related to Search service (CBFT)
enum class search_errc {
index_not_ready = 401,
consistency_mismatch = 402,
};
/// Errors related to Views service (CAPI)
enum class view_errc {
/// Http status code 404
/// Reason or error contains "not_found"
view_not_found = 501,
/// Raised on the Management APIs only when
/// * Getting a design document
/// * Dropping a design document
/// * And the server returns 404
design_document_not_found = 502,
};
/// Errors related to management service (ns_server)
enum class management_errc {
/// Raised from the collection management API
collection_exists = 601,
/// Raised from the collection management API
scope_exists = 602,
/// Raised from the user management API
user_not_found = 603,
/// Raised from the user management API
group_not_found = 604,
/// Raised from the bucket management API
bucket_exists = 605,
/// Raised from the user management API
user_exists = 606,
/// Raised from the bucket management API
bucket_not_flushable = 607,
/// Occurs if the function is not found
/// name is "ERR_APP_NOT_FOUND_TS"
eventing_function_not_found = 608,
/// Occurs if the function is not deployed, but the action expects it to
/// name is "ERR_APP_NOT_DEPLOYED"
eventing_function_not_deployed = 609,
/// Occurs when the compilation of the function code failed
/// name is "ERR_HANDLER_COMPILATION"
eventing_function_compilation_failure = 610,
/// Occurs when source and metadata keyspaces are the same.
/// name is "ERR_SRC_MB_SAME"
eventing_function_identical_keyspace = 611,
/// Occurs when a function is deployed but not “fully” bootstrapped
/// name is "ERR_APP_NOT_BOOTSTRAPPED"
eventing_function_not_bootstrapped = 612,
/// Occurs when a function is deployed but the action does not expect it to
/// name is "ERR_APP_NOT_UNDEPLOYED"
eventing_function_deployed = 613,
/// Occurs when a function is paused but the action does not expect it to
/// name is "ERR_APP_PAUSED"
eventing_function_paused = 614,
};
/// Field-Level Encryption Error Definitions
enum class field_level_encryption_errc {
/// Generic cryptography failure.
generic_cryptography_failure = 700,
/// Raised by CryptoManager.encrypt() when encryption fails for any reason. Should have one of the other Field-Level Encryption errors
/// as a cause.
encryption_failure = 701,
/// Raised by CryptoManager.decrypt() when decryption fails for any reason. Should have one of the other Field-Level Encryption errors
/// as a cause.
decryption_failure = 702,
/// Raised when a crypto operation fails because a required key is missing.
crypto_key_not_found = 703,
/// Raised by an encrypter or decrypter when the key does not meet expectations (for example, if the key is the wrong size).
invalid_crypto_key = 704,
/// Raised when a message cannot be decrypted because there is no decrypter registered for the algorithm.
decrypter_not_found = 705,
/// Raised when a message cannot be encrypted because there is no encrypter registered under the requested alias.
encrypter_not_found = 706,
/// Raised when decryption fails due to malformed input, integrity check failure, etc.
invalid_ciphertext = 707
};
/// Errors related to networking IO
enum class network_errc {
/// Unable to resolve node address
resolve_failure = 1001,
/// No hosts left to connect
no_endpoints_left = 1002,
/// Failed to complete protocol handshake
handshake_failure = 1003,
/// Unexpected protocol state or input
protocol_error = 1004,
/// Configuration is not available for some reason
configuration_not_available = 1005,
};
namespace detail
{
struct common_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.common";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (common_errc(ev)) {
case common_errc::unambiguous_timeout:
return "unambiguous_timeout";
case common_errc::ambiguous_timeout:
return "ambiguous_timeout";
case common_errc::request_canceled:
return "request_canceled";
case common_errc::invalid_argument:
return "invalid_argument";
case common_errc::service_not_available:
return "service_not_available";
case common_errc::internal_server_failure:
return "internal_server_failure";
case common_errc::authentication_failure:
return "authentication_failure";
case common_errc::temporary_failure:
return "temporary_failure";
case common_errc::parsing_failure:
return "parsing_failure";
case common_errc::cas_mismatch:
return "cas_mismatch";
case common_errc::bucket_not_found:
return "bucket_not_found";
case common_errc::scope_not_found:
return "scope_not_found";
case common_errc::collection_not_found:
return "collection_not_found";
case common_errc::unsupported_operation:
return "unsupported_operation";
case common_errc::feature_not_available:
return "feature_not_available";
case common_errc::encoding_failure:
return "encoding_failure";
case common_errc::decoding_failure:
return "decoding_failure";
case common_errc::index_not_found:
return "index_not_found";
case common_errc::index_exists:
return "index_exists";
case common_errc::rate_limited:
return "rate_limited";
case common_errc::quota_limited:
return "quota_limited";
}
return "FIXME: unknown error code common (recompile with newer library)";
}
};
inline const std::error_category&
get_common_category()
{
static detail::common_error_category instance;
return instance;
}
struct key_value_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.key_value";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (key_value_errc(ev)) {
case key_value_errc::document_not_found:
return "document_not_found";
case key_value_errc::document_irretrievable:
return "document_irretrievable";
case key_value_errc::document_locked:
return "document_locked";
case key_value_errc::value_too_large:
return "value_too_large";
case key_value_errc::document_exists:
return "document_exists";
case key_value_errc::durability_level_not_available:
return "durability_level_not_available";
case key_value_errc::durability_impossible:
return "durability_impossible";
case key_value_errc::durability_ambiguous:
return "durability_ambiguous";
case key_value_errc::durable_write_in_progress:
return "durable_write_in_progress";
case key_value_errc::durable_write_re_commit_in_progress:
return "durable_write_re_commit_in_progress";
case key_value_errc::path_not_found:
return "path_not_found";
case key_value_errc::path_mismatch:
return "path_mismatch";
case key_value_errc::path_invalid:
return "path_invalid";
case key_value_errc::path_too_big:
return "path_too_big";
case key_value_errc::path_too_deep:
return "path_too_deep";
case key_value_errc::value_too_deep:
return "value_too_deep";
case key_value_errc::value_invalid:
return "value_invalid";
case key_value_errc::document_not_json:
return "document_not_json";
case key_value_errc::number_too_big:
return "number_too_big";
case key_value_errc::delta_invalid:
return "delta_invalid";
case key_value_errc::path_exists:
return "path_exists";
case key_value_errc::xattr_unknown_macro:
return "xattr_unknown_macro";
case key_value_errc::xattr_invalid_key_combo:
return "xattr_invalid_key_combo";
case key_value_errc::xattr_unknown_virtual_attribute:
return "xattr_unknown_virtual_attribute";
case key_value_errc::xattr_cannot_modify_virtual_attribute:
return "xattr_cannot_modify_virtual_attribute";
case key_value_errc::cannot_revive_living_document:
return "cannot_revive_living_document";
case key_value_errc::xattr_no_access:
return "xattr_no_access";
}
return "FIXME: unknown error code key_value (recompile with newer library)";
}
};
inline const std::error_category&
get_key_value_category()
{
static detail::key_value_error_category instance;
return instance;
}
struct query_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.query";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (query_errc(ev)) {
case query_errc::planning_failure:
return "planning_failure";
case query_errc::index_failure:
return "index_failure";
case query_errc::prepared_statement_failure:
return "prepared_statement_failure";
case query_errc::dml_failure:
return "dml_failure";
}
return "FIXME: unknown error code in query category (recompile with newer library)";
}
};
inline const std::error_category&
get_query_category()
{
static detail::query_error_category instance;
return instance;
}
struct search_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.search";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (search_errc(ev)) {
case search_errc::index_not_ready:
return "index_not_ready";
case search_errc::consistency_mismatch:
return "consistency_mismatch";
}
return "FIXME: unknown error code in search category (recompile with newer library)";
}
};
inline const std::error_category&
get_search_category()
{
static detail::search_error_category instance;
return instance;
}
struct view_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.view";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (view_errc(ev)) {
case view_errc::view_not_found:
return "view_not_found";
case view_errc::design_document_not_found:
return "design_document_not_found";
}
return "FIXME: unknown error code in view category (recompile with newer library)";
}
};
inline const std::error_category&
get_view_category()
{
static detail::view_error_category instance;
return instance;
}
struct analytics_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.analytics";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (analytics_errc(ev)) {
case analytics_errc::compilation_failure:
return "compilation_failure";
case analytics_errc::job_queue_full:
return "job_queue_full";
case analytics_errc::dataset_not_found:
return "dataset_not_found";
case analytics_errc::dataverse_not_found:
return "dataverse_not_found";
case analytics_errc::dataset_exists:
return "dataset_exists";
case analytics_errc::dataverse_exists:
return "dataverse_exists";
case analytics_errc::link_not_found:
return "link_not_found";
case analytics_errc::link_exists:
return "link_exists";
}
return "FIXME: unknown error code in analytics category (recompile with newer library)";
}
};
inline const std::error_category&
get_analytics_category()
{
static detail::analytics_error_category instance;
return instance;
}
struct management_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.management";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (management_errc(ev)) {
case management_errc::collection_exists:
return "collection_exists";
case management_errc::scope_exists:
return "scope_exists";
case management_errc::user_not_found:
return "user_not_found";
case management_errc::group_not_found:
return "group_not_found";
case management_errc::user_exists:
return "user_exists";
case management_errc::bucket_exists:
return "bucket_exists";
case management_errc::bucket_not_flushable:
return "bucket_not_flushable";
case management_errc::eventing_function_not_found:
return "eventing_function_not_found";
case management_errc::eventing_function_not_deployed:
return "eventing_function_not_deployed";
case management_errc::eventing_function_compilation_failure:
return "eventing_function_compilation_failure";
case management_errc::eventing_function_identical_keyspace:
return "eventing_function_identical_keyspace";
case management_errc::eventing_function_not_bootstrapped:
return "eventing_function_not_bootstrapped";
case management_errc::eventing_function_deployed:
return "eventing_function_deployed";
case management_errc::eventing_function_paused:
return "eventing_function_paused";
}
return "FIXME: unknown error code in management category (recompile with newer library)";
}
};
inline const std::error_category&
get_management_category()
{
static detail::management_error_category instance;
return instance;
}
struct network_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.network";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (network_errc(ev)) {
case network_errc::resolve_failure:
return "resolve_failure";
case network_errc::no_endpoints_left:
return "no_endpoints_left";
case network_errc::handshake_failure:
return "handshake_failure";
case network_errc::protocol_error:
return "protocol_error";
case network_errc::configuration_not_available:
return "configuration_not_available";
}
return "FIXME: unknown error code in network category (recompile with newer library)";
}
};
inline const std::error_category&
get_network_category()
{
static detail::network_error_category instance;
return instance;
}
struct field_level_encryption_error_category : std::error_category {
[[nodiscard]] const char* name() const noexcept override
{
return "couchbase.field_level_encryption";
}
[[nodiscard]] std::string message(int ev) const noexcept override
{
switch (field_level_encryption_errc(ev)) {
case field_level_encryption_errc::generic_cryptography_failure:
return "generic_cryptography_failure";
case field_level_encryption_errc::encryption_failure:
return "encryption_failure";
case field_level_encryption_errc::decryption_failure:
return "decryption_failure";
case field_level_encryption_errc::crypto_key_not_found:
return "crypto_key_not_found";
case field_level_encryption_errc::invalid_crypto_key:
return "invalid_crypto_key";
case field_level_encryption_errc::decrypter_not_found:
return "decrypter_not_found";
case field_level_encryption_errc::encrypter_not_found:
return "encrypter_not_found";
case field_level_encryption_errc::invalid_ciphertext:
return "invalid_ciphertext";
}
return "FIXME: unknown error code in field level encryption category (recompile with newer library)";
}
};
inline const std::error_category&
get_field_level_encryption_category()
{
static detail::field_level_encryption_error_category instance;
return instance;
}
} // namespace detail
} // namespace couchbase::error
namespace std
{
template<>
struct is_error_code_enum<couchbase::error::common_errc> : true_type {
};
template<>
struct is_error_code_enum<couchbase::error::key_value_errc> : true_type {
};
template<>
struct is_error_code_enum<couchbase::error::query_errc> : true_type {
};
template<>
struct is_error_code_enum<couchbase::error::search_errc> : true_type {
};
template<>
struct is_error_code_enum<couchbase::error::view_errc> : true_type {
};
template<>
struct is_error_code_enum<couchbase::error::analytics_errc> : true_type {
};
template<>
struct is_error_code_enum<couchbase::error::management_errc> : true_type {
};
template<>
struct is_error_code_enum<couchbase::error::network_errc> : true_type {
};
template<>
struct is_error_code_enum<couchbase::error::field_level_encryption_errc> : true_type {
};
} // namespace std
namespace couchbase::error
{
inline std::error_code
make_error_code(couchbase::error::common_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_common_category() };
}
inline std::error_code
make_error_code(couchbase::error::key_value_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_key_value_category() };
}
inline std::error_code
make_error_code(couchbase::error::query_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_query_category() };
}
inline std::error_code
make_error_code(couchbase::error::search_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_search_category() };
}
inline std::error_code
make_error_code(couchbase::error::view_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_view_category() };
}
inline std::error_code
make_error_code(couchbase::error::analytics_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_analytics_category() };
}
inline std::error_code
make_error_code(couchbase::error::management_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_management_category() };
}
inline std::error_code
make_error_code(couchbase::error::network_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_network_category() };
}
inline std::error_code
make_error_code(couchbase::error::field_level_encryption_errc e)
{
return { static_cast<int>(e), couchbase::error::detail::get_field_level_encryption_category() };
}
} // namespace couchbase::error
| 35.632385 | 140 | 0.675325 | jrawsthorne |
5284bf97e2825f1cf5d2bd7f256da9103a454f28 | 1,785 | hpp | C++ | include/dca/phys/dca_analysis/deprecated/cpe_solver/basis_functions/radial_function.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 27 | 2018-08-02T04:28:23.000Z | 2021-07-08T02:14:20.000Z | include/dca/phys/dca_analysis/deprecated/cpe_solver/basis_functions/radial_function.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 200 | 2018-08-02T18:19:03.000Z | 2022-03-16T21:28:41.000Z | include/dca/phys/dca_analysis/deprecated/cpe_solver/basis_functions/radial_function.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 22 | 2018-08-15T15:50:00.000Z | 2021-09-30T13:41:46.000Z | // Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Peter Staar (taa@zurich.ibm.com)
//
// Radial function.
#ifndef DCA_PHYS_DCA_ANALYSIS_CPE_SOLVER_BASIS_FUNCTIONS_RADIAL_FUNCTION_HPP
#define DCA_PHYS_DCA_ANALYSIS_CPE_SOLVER_BASIS_FUNCTIONS_RADIAL_FUNCTION_HPP
#include <cmath>
#include <complex>
#include <cstdlib>
#include <vector>
#include "dca/function/domains/dmn_0.hpp"
#include "dca/math/util/sgn.hpp"
#include "dca/phys/domains/time_and_frequency/frequency_domain_real_axis.hpp"
namespace dca {
namespace phys {
namespace analysis {
// dca::phys::analysis::
class RadialFunction {
public:
using element_type = double;
using w_REAL = func::dmn_0<domains::frequency_domain_real_axis>;
static int get_size() {
return get_elements().size();
}
static std::vector<double>& get_elements() {
static std::vector<double> elements(0, 0);
return elements;
}
template <typename parameters_type>
static void initialize(parameters_type& parameters);
static double volume(int n);
static std::complex<double> phi(int n, std::complex<double> z);
};
template <typename parameters_type>
void RadialFunction::initialize(parameters_type& parameters) {
std::vector<double> elements = w_REAL::get_elements();
for (std::size_t l = 0; l < elements.size(); l++) {
elements[l] = math::util::sgn(elements[l]) *
std::pow(std::abs(elements[l]) / std::abs(elements[0]), 2) * std::abs(elements[0]);
}
get_elements() = elements;
}
} // analysis
} // phys
} // dca
#endif // DCA_PHYS_DCA_ANALYSIS_CPE_SOLVER_BASIS_FUNCTIONS_RADIAL_FUNCTION_HPP
| 26.25 | 101 | 0.72493 | PMDee |
52860bf855c97239e852dd101375f82d7d058012 | 2,101 | cpp | C++ | inference-engine/tests_deprecated/functional/ie_tests/src/optimized_network_matcher.cpp | anton-potapov/openvino | 84119afe9a8c965e0a0cd920fff53aee67b05108 | [
"Apache-2.0"
] | 2 | 2020-11-18T14:14:06.000Z | 2020-11-28T04:55:57.000Z | inference-engine/tests_deprecated/functional/ie_tests/src/optimized_network_matcher.cpp | anton-potapov/openvino | 84119afe9a8c965e0a0cd920fff53aee67b05108 | [
"Apache-2.0"
] | 30 | 2020-11-13T11:44:07.000Z | 2022-02-21T13:03:16.000Z | inference-engine/tests_deprecated/functional/ie_tests/src/optimized_network_matcher.cpp | mmakridi/openvino | 769bb7709597c14debdaa356dd60c5a78bdfa97e | [
"Apache-2.0"
] | 3 | 2021-03-09T08:27:29.000Z | 2021-04-07T04:58:54.000Z | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <fstream>
#include <string>
#include <gtest/gtest.h>
#include <ie_plugin_config.hpp>
#include "optimized_network_matcher.hpp"
using namespace InferenceEngine;
using namespace InferenceEngine::PluginConfigParams;
void Regression :: Matchers :: OptimizedNetworkMatcher :: to(std::string path_to_reference_dump) {
ModelsPath path_to_firmware;
path_to_firmware << kPathSeparator << config._firmware << kPathSeparator;
auto compact_token = config.compactMode ? "_compact" : "";
this->path_to_reference_dump = path_to_firmware + path_to_reference_dump + compact_token + "_firmware.bin";
}
void Regression :: Matchers :: OptimizedNetworkMatcher :: matchCustom () {
ASSERT_NO_FATAL_FAILURE(createExecutableNetworkFromIR());
firmware = readDumpFromFile(config._tmp_firmware);
ASSERT_NE(firmware.size(), 0);
}
std::vector<uint8_t> Regression :: Matchers :: OptimizedNetworkMatcher :: readDumpFromFile(std::string path) {
std::ifstream file(path, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
if (size <=0) {
return std::vector<uint8_t>();
}
file.seekg(0, std::ios::beg);
std::vector<uint8_t> buffer(size);
file.read((char*)buffer.data(), size);
return buffer;
}
void Regression :: Matchers :: OptimizedNetworkMatcher :: checkResult() {
auto refFirmware = readDumpFromFile(path_to_reference_dump);
ASSERT_EQ(refFirmware.size(), firmware.size()) << "Reference: " << path_to_reference_dump;
for (int i = 0; i < refFirmware.size(); ++i) {
ASSERT_EQ(refFirmware[i], firmware[i]) << "firmware mismatch at: " << i << " byte";
}
}
////////////////////////////
void Regression :: Matchers :: OptimizedNetworkDumper::dump() {
ExecutableNetwork executableApi;
ASSERT_NO_FATAL_FAILURE(executableApi = createExecutableNetworkFromIR());
try {
executableApi.Export(config._path_to_aot_model);
}
catch (const std::exception &e) {
FAIL() << e.what();
}
}
| 31.358209 | 111 | 0.690624 | anton-potapov |
52876ae3972891c398c3f1bc637cb69486966a39 | 12,484 | cpp | C++ | fdbserver/MemoryPager.actor.cpp | timansky/foundationdb | 97dd83d94060145687395fe1fa440b88aaa078a8 | [
"Apache-2.0"
] | 1 | 2020-08-17T10:57:40.000Z | 2020-08-17T10:57:40.000Z | fdbserver/MemoryPager.actor.cpp | timansky/foundationdb | 97dd83d94060145687395fe1fa440b88aaa078a8 | [
"Apache-2.0"
] | 2 | 2019-02-06T08:10:00.000Z | 2019-02-06T08:12:11.000Z | fdbserver/MemoryPager.actor.cpp | timansky/foundationdb | 97dd83d94060145687395fe1fa440b88aaa078a8 | [
"Apache-2.0"
] | 1 | 2019-03-12T20:17:26.000Z | 2019-03-12T20:17:26.000Z | /*
* MemoryPager.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* 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 <cinttypes>
#include "fdbserver/MemoryPager.h"
#include "fdbserver/Knobs.h"
#include "flow/Arena.h"
#include "flow/UnitTest.h"
#include "flow/actorcompiler.h"
typedef uint8_t* PhysicalPageID;
typedef std::vector<std::pair<Version, PhysicalPageID>> PageVersionMap;
typedef std::vector<PageVersionMap> LogicalPageTable;
class MemoryPager;
class MemoryPage : public IPage, ReferenceCounted<MemoryPage> {
public:
MemoryPage();
MemoryPage(uint8_t *data);
virtual ~MemoryPage();
virtual void addref() const {
ReferenceCounted<MemoryPage>::addref();
}
virtual void delref() const {
ReferenceCounted<MemoryPage>::delref();
}
virtual int size() const;
virtual uint8_t const* begin() const;
virtual uint8_t* mutate();
private:
friend class MemoryPager;
uint8_t *data;
bool allocated;
static const int PAGE_BYTES;
};
class MemoryPagerSnapshot : public IPagerSnapshot, ReferenceCounted<MemoryPagerSnapshot> {
public:
MemoryPagerSnapshot(MemoryPager *pager, Version version) : pager(pager), version(version) {}
virtual Future<Reference<const IPage>> getPhysicalPage(LogicalPageID pageID);
virtual Version getVersion() const {
return version;
}
virtual void addref() {
ReferenceCounted<MemoryPagerSnapshot>::addref();
}
virtual void delref() {
ReferenceCounted<MemoryPagerSnapshot>::delref();
}
private:
MemoryPager *pager;
Version version;
};
class MemoryPager : public IPager, ReferenceCounted<MemoryPager> {
public:
MemoryPager();
virtual Reference<IPage> newPageBuffer();
virtual int getUsablePageSize();
virtual Reference<IPagerSnapshot> getReadSnapshot(Version version);
virtual LogicalPageID allocateLogicalPage();
virtual void freeLogicalPage(LogicalPageID pageID, Version version);
virtual void writePage(LogicalPageID pageID, Reference<IPage> contents, Version updateVersion, LogicalPageID referencePageID);
virtual void forgetVersions(Version begin, Version end);
virtual Future<Void> commit();
virtual StorageBytes getStorageBytes() {
// TODO: Get actual values for used and free memory
return StorageBytes();
}
virtual void setLatestVersion(Version version);
virtual Future<Version> getLatestVersion();
virtual Future<Void> getError();
virtual Future<Void> onClosed();
virtual void dispose();
virtual void close();
virtual Reference<const IPage> getPage(LogicalPageID pageID, Version version);
private:
Version latestVersion;
Version committedVersion;
Standalone<VectorRef<VectorRef<uint8_t>>> data;
LogicalPageTable pageTable;
Promise<Void> closed;
std::vector<PhysicalPageID> freeList; // TODO: is this good enough for now?
PhysicalPageID allocatePage(Reference<IPage> contents);
void extendData();
static const PhysicalPageID INVALID_PAGE;
};
IPager * createMemoryPager() {
return new MemoryPager();
}
MemoryPage::MemoryPage() : allocated(true) {
data = (uint8_t*)FastAllocator<4096>::allocate();
}
MemoryPage::MemoryPage(uint8_t *data) : data(data), allocated(false) {}
MemoryPage::~MemoryPage() {
if(allocated) {
FastAllocator<4096>::release(data);
}
}
uint8_t const* MemoryPage::begin() const {
return data;
}
uint8_t* MemoryPage::mutate() {
return data;
}
int MemoryPage::size() const {
return PAGE_BYTES;
}
const int MemoryPage::PAGE_BYTES = 4096;
Future<Reference<const IPage>> MemoryPagerSnapshot::getPhysicalPage(LogicalPageID pageID) {
return pager->getPage(pageID, version);
}
MemoryPager::MemoryPager() : latestVersion(0), committedVersion(0) {
extendData();
pageTable.resize(SERVER_KNOBS->PAGER_RESERVED_PAGES);
}
Reference<IPage> MemoryPager::newPageBuffer() {
return Reference<IPage>(new MemoryPage());
}
int MemoryPager::getUsablePageSize() {
return MemoryPage::PAGE_BYTES;
}
Reference<IPagerSnapshot> MemoryPager::getReadSnapshot(Version version) {
ASSERT(version <= latestVersion);
return Reference<IPagerSnapshot>(new MemoryPagerSnapshot(this, version));
}
LogicalPageID MemoryPager::allocateLogicalPage() {
ASSERT(pageTable.size() >= SERVER_KNOBS->PAGER_RESERVED_PAGES);
pageTable.push_back(PageVersionMap());
return pageTable.size() - 1;
}
void MemoryPager::freeLogicalPage(LogicalPageID pageID, Version version) {
ASSERT(pageID < pageTable.size());
PageVersionMap &pageVersionMap = pageTable[pageID];
ASSERT(!pageVersionMap.empty());
auto itr = std::lower_bound(pageVersionMap.begin(), pageVersionMap.end(), version, [](std::pair<Version, PhysicalPageID> p, Version v) {
return p.first < v;
});
pageVersionMap.erase(itr, pageVersionMap.end());
if(pageVersionMap.size() > 0 && pageVersionMap.back().second != INVALID_PAGE) {
pageVersionMap.push_back(std::make_pair(version, INVALID_PAGE));
}
}
void MemoryPager::writePage(LogicalPageID pageID, Reference<IPage> contents, Version updateVersion, LogicalPageID referencePageID) {
ASSERT(updateVersion > latestVersion || updateVersion == 0);
ASSERT(pageID < pageTable.size());
if(referencePageID != invalidLogicalPageID) {
PageVersionMap &rpv = pageTable[referencePageID];
ASSERT(!rpv.empty());
updateVersion = rpv.back().first;
}
PageVersionMap &pageVersionMap = pageTable[pageID];
ASSERT(updateVersion >= committedVersion || updateVersion == 0);
PhysicalPageID physicalPageID = allocatePage(contents);
ASSERT(pageVersionMap.empty() || pageVersionMap.back().second != INVALID_PAGE);
if(updateVersion == 0) {
ASSERT(pageVersionMap.size());
updateVersion = pageVersionMap.back().first;
pageVersionMap.back().second = physicalPageID;
// TODO: what to do with old page?
}
else {
ASSERT(pageVersionMap.empty() || pageVersionMap.back().first < updateVersion);
pageVersionMap.push_back(std::make_pair(updateVersion, physicalPageID));
}
}
void MemoryPager::forgetVersions(Version begin, Version end) {
ASSERT(begin <= end);
ASSERT(end <= latestVersion);
// TODO
}
Future<Void> MemoryPager::commit() {
ASSERT(committedVersion < latestVersion);
committedVersion = latestVersion;
return Void();
}
void MemoryPager::setLatestVersion(Version version) {
ASSERT(version > latestVersion);
latestVersion = version;
}
Future<Version> MemoryPager::getLatestVersion() {
return latestVersion;
}
Reference<const IPage> MemoryPager::getPage(LogicalPageID pageID, Version version) {
ASSERT(pageID < pageTable.size());
PageVersionMap const& pageVersionMap = pageTable[pageID];
auto itr = std::upper_bound(pageVersionMap.begin(), pageVersionMap.end(), version, [](Version v, std::pair<Version, PhysicalPageID> p) {
return v < p.first;
});
if(itr == pageVersionMap.begin()) {
return Reference<IPage>(); // TODO: should this be an error?
}
--itr;
ASSERT(itr->second != INVALID_PAGE);
return Reference<const IPage>(new MemoryPage(itr->second)); // TODO: Page memory owned by the pager. Change this?
}
Future<Void> MemoryPager::getError() {
return Void();
}
Future<Void> MemoryPager::onClosed() {
return closed.getFuture();
}
void MemoryPager::dispose() {
closed.send(Void());
delete this;
}
void MemoryPager::close() {
dispose();
}
PhysicalPageID MemoryPager::allocatePage(Reference<IPage> contents) {
if(freeList.size()) {
PhysicalPageID pageID = freeList.back();
freeList.pop_back();
memcpy(pageID, contents->begin(), contents->size());
return pageID;
}
else {
ASSERT(data.size() && data.back().capacity() - data.back().size() >= contents->size());
PhysicalPageID pageID = data.back().end();
data.back().append(data.arena(), contents->begin(), contents->size());
if(data.back().size() == data.back().capacity()) {
extendData();
}
else {
ASSERT(data.back().size() <= data.back().capacity() - 4096);
}
return pageID;
}
}
void MemoryPager::extendData() {
if(data.size() > 1000) { // TODO: is this an ok way to handle large data size?
throw io_error();
}
VectorRef<uint8_t> d;
d.reserve(data.arena(), 1 << 22);
data.push_back(data.arena(), d);
}
// TODO: these tests are not MemoryPager specific, we should make them more general
void fillPage(Reference<IPage> page, LogicalPageID pageID, Version version) {
ASSERT(page->size() > sizeof(LogicalPageID) + sizeof(Version));
memset(page->mutate(), 0, page->size());
memcpy(page->mutate(), (void*)&pageID, sizeof(LogicalPageID));
memcpy(page->mutate() + sizeof(LogicalPageID), (void*)&version, sizeof(Version));
}
bool validatePage(Reference<const IPage> page, LogicalPageID pageID, Version version) {
bool valid = true;
LogicalPageID readPageID = *(LogicalPageID*)page->begin();
if(readPageID != pageID) {
fprintf(stderr, "Invalid PageID detected: %u (expected %u)\n", readPageID, pageID);
valid = false;
}
Version readVersion = *(Version*)(page->begin()+sizeof(LogicalPageID));
if(readVersion != version) {
fprintf(stderr, "Invalid Version detected on page %u: %" PRId64 "(expected %" PRId64 ")\n", pageID, readVersion, version);
valid = false;
}
return valid;
}
void writePage(IPager *pager, Reference<IPage> page, LogicalPageID pageID, Version version, bool updateVersion=true) {
fillPage(page, pageID, version);
pager->writePage(pageID, page, updateVersion ? version : 0);
}
ACTOR Future<Void> commit(IPager *pager) {
static int commitNum = 1;
state int myCommit = commitNum++;
debug_printf("Commit%d\n", myCommit);
wait(pager->commit());
debug_printf("FinishedCommit%d\n", myCommit);
return Void();
}
ACTOR Future<Void> read(IPager *pager, LogicalPageID pageID, Version version, Version expectedVersion=-1) {
static int readNum = 1;
state int myRead = readNum++;
state Reference<IPagerSnapshot> readSnapshot = pager->getReadSnapshot(version);
debug_printf("Read%d\n", myRead);
Reference<const IPage> readPage = wait(readSnapshot->getPhysicalPage(pageID));
debug_printf("FinishedRead%d\n", myRead);
ASSERT(validatePage(readPage, pageID, expectedVersion >= 0 ? expectedVersion : version));
return Void();
}
ACTOR Future<Void> simplePagerTest(IPager *pager) {
state Reference<IPage> page = pager->newPageBuffer();
Version latestVersion = wait(pager->getLatestVersion());
debug_printf("Got latest version: %lld\n", latestVersion);
state Version version = latestVersion+1;
state Version v1 = version;
state LogicalPageID pageID1 = pager->allocateLogicalPage();
writePage(pager, page, pageID1, v1);
pager->setLatestVersion(v1);
wait(commit(pager));
state LogicalPageID pageID2 = pager->allocateLogicalPage();
state Version v2 = ++version;
writePage(pager, page, pageID1, v2);
writePage(pager, page, pageID2, v2);
pager->setLatestVersion(v2);
wait(commit(pager));
wait(read(pager, pageID1, v2));
wait(read(pager, pageID1, v1));
state Version v3 = ++version;
writePage(pager, page, pageID1, v3, false);
pager->setLatestVersion(v3);
wait(read(pager, pageID1, v2, v3));
wait(read(pager, pageID1, v3, v3));
state LogicalPageID pageID3 = pager->allocateLogicalPage();
state Version v4 = ++version;
writePage(pager, page, pageID2, v4);
writePage(pager, page, pageID3, v4);
pager->setLatestVersion(v4);
wait(commit(pager));
wait(read(pager, pageID2, v4, v4));
state Version v5 = ++version;
writePage(pager, page, pageID2, v5);
state LogicalPageID pageID4 = pager->allocateLogicalPage();
writePage(pager, page, pageID4, v5);
state Version v6 = ++version;
pager->freeLogicalPage(pageID2, v5);
pager->freeLogicalPage(pageID3, v3);
pager->setLatestVersion(v6);
wait(commit(pager));
pager->forgetVersions(0, v4);
wait(commit(pager));
wait(delay(3.0));
wait(commit(pager));
return Void();
}
/*
TEST_CASE("/fdbserver/memorypager/simple") {
state IPager *pager = new MemoryPager();
wait(simplePagerTest(pager));
Future<Void> closedFuture = pager->onClosed();
pager->dispose();
wait(closedFuture);
return Void();
}
*/
const PhysicalPageID MemoryPager::INVALID_PAGE = nullptr;
| 27.317287 | 137 | 0.734941 | timansky |
5288d48d136e2e32f4f3784eb0a99f770704f015 | 1,238 | cpp | C++ | test/features.cpp | Ogiwara-CostlierRain464/transaction-system | fb63b96e03e480bc2ae6ebc06f5c392af1ab9012 | [
"Apache-2.0"
] | 9 | 2020-06-09T04:28:36.000Z | 2022-02-02T05:27:51.000Z | test/features.cpp | Ogiwara-CostlierRain464/transaction-system | fb63b96e03e480bc2ae6ebc06f5c392af1ab9012 | [
"Apache-2.0"
] | null | null | null | test/features.cpp | Ogiwara-CostlierRain464/transaction-system | fb63b96e03e480bc2ae6ebc06f5c392af1ab9012 | [
"Apache-2.0"
] | null | null | null | #include <gtest/gtest.h>
using namespace std;
/**
* Used to check C++ features.
*/
class Features: public ::testing::Test{};
template <typename T>
bool typeCheck ( T x )
{
reference_wrapper<int> r=ref(x);
// should return false, so ref(int) ≠ int&
return is_same<T&,decltype(r)>::value;
}
/**
* A reference_wrapper object can be used to create an array of references
* which was not possible with T&.
*
* @see https://stackoverflow.com/questions/33240993/c-difference-between-stdreft-and-t/33241552
*/
TEST_F(Features, std_ref){
int x = 5;
EXPECT_EQ(typeCheck(x), false);
int x_ = 5, y = 7, z = 8;
//int& ar[] = {x,y,z}; NOT Possible
reference_wrapper<int> arr[] = {x, y, z};
}
TEST_F(Features, asm_ext_basic){
int src = 1;
int dst;
asm("mov %1, %0\n\t"
"add $1, %0"
: "=r" (dst) // output operands
: "r" (src)); // input operands
EXPECT_EQ(dst, 2);
}
TEST_F(Features, asm_volatile){
uint64_t msr;
asm volatile (
"rdtsc\n\t"
"shl $32, %%rdx\n\t"
"or %%rdx, %0"
: "=a" (msr)
:
: "rdx"
);
printf("%lld\n", msr);
asm volatile (
"rdtsc\n\t"
"shl $32, %%rdx\n\t"
"or %%rdx, %0"
: "=a" (msr)
:
: "rdx"
);
printf("%lld\n", msr);
}
| 17.942029 | 96 | 0.575929 | Ogiwara-CostlierRain464 |
52943455ab9c912707ad9d4daae1e997d6ae5f8a | 43,772 | cpp | C++ | R/src/rcpp_functions.cpp | hillarykoch/pGMCM | 2aeac31fdac4e87c8349222d595afd78dedf4b84 | [
"Artistic-2.0"
] | null | null | null | R/src/rcpp_functions.cpp | hillarykoch/pGMCM | 2aeac31fdac4e87c8349222d595afd78dedf4b84 | [
"Artistic-2.0"
] | null | null | null | R/src/rcpp_functions.cpp | hillarykoch/pGMCM | 2aeac31fdac4e87c8349222d595afd78dedf4b84 | [
"Artistic-2.0"
] | null | null | null | // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
#include <RcppArmadillo.h>
#include <algorithm>
using namespace Rcpp;
using namespace RcppArmadillo;
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
//
// Stuff for general penalized Gaussian mixture model
//
// Made this so that absolute value of double returns double, not integer
// [[Rcpp::export]]
double abs3(double val){
return std::abs(val);
}
// First derivative of SCAD penalty
// NOTE THAT THIS PENALTY LOOKS A LIL DIFFERENT THAN SCAD, BECAUSE HUANG PUTS LAMBDA OUTSIDE THE PENALIZATION TERM
// [[Rcpp::export]]
arma::rowvec SCAD_1d(arma::rowvec prop, double lambda, int k, double a = 3.7) {
arma::colvec term2(k, arma::fill::zeros);
arma::rowvec out(k, arma::fill::none);
for(int i = 0; i < k; ++i) {
if(a*lambda - prop(i) > 0) {
term2(i) = (a*lambda - prop(i))/(a*lambda-lambda);
}
out(i) = ((prop(i) <= lambda) + term2(i)*(prop(i) > lambda));
}
return out;
}
// First derivative of SCAD penalty, when only passing an integer and not a vector
// NOTE THAT THIS PENALTY LOOKS A LIL DIFFERENT THAN SCAD, BECAUSE HUANG PUTS LAMBDA OUTSIDE THE PENALIZATION TERM
// [[Rcpp::export]]
double double_SCAD_1d(double prop, double lambda, double a = 3.7) {
double term2 = 0.0;
double out;
if(a*lambda - prop > 0) {
term2 = (a*lambda - prop)/(a*lambda-lambda);
}
out = ((prop <= lambda) + term2*(prop > lambda));
return out;
}
// SCAD penalty
// NOTE THAT THIS PENALTY LOOKS A LIL DIFFERENT THAN SCAD, BECAUSE HUANG PUTS LAMBDA OUTSIDE THE PENALIZATION TERM
// [[Rcpp::export]]
arma::rowvec SCAD(arma::rowvec prop, double lambda, int k, double a = 3.7) {
arma::rowvec out(k, arma::fill::none);
double val;
for(int i = 0; i < k; ++i) {
val = abs3(prop(i));
if(val <= lambda) {
out(i) = lambda;
} else if(lambda < val & val <= a * lambda) {
out(i) = -((pow(val,2)-2*a*lambda*val+pow(lambda,2)) / (2 * (a-1) * lambda));
} else {
out(i) = ((a+1) * lambda) / 2;
}
}
return out;
}
// SCAD penalty, when only passing an integer and not a vector
// NOTE THAT THIS PENALTY LOOKS A LIL DIFFERENT THAN SCAD, BECAUSE HUANG PUTS LAMBDA OUTSIDE THE PENALIZATION TERM
// [[Rcpp::export]]
double double_SCAD(double prop, double lambda, double a = 3.7) {
double out;
double val;
val = abs3(prop);
if(val <= lambda) {
out = lambda;
} else if(lambda < val & val <= a * lambda) {
out = -((pow(val,2)-2*a*lambda*val+pow(lambda,2)) / (2 * (a-1) * lambda));
} else {
out = ((a+1) * lambda) / 2;
}
return out;
}
// choose slices from a cube given index
// [[Rcpp::export]]
arma::cube choose_slice(arma::cube& Q, arma::uvec idx, int d, int k) {
arma::cube y(d, d, k, arma::fill::none);
for(int i = 0; i < k; ++i) {
y.slice(i) = Q.slice(idx(i));
}
return y;
}
// compute Mahalanobis distance for multivariate normal
// [[Rcpp::export]]
arma::vec Mahalanobis(arma::mat x, arma::rowvec mu, arma::mat sigma){
const int n = x.n_rows;
arma::mat x_cen;
x_cen.copy_size(x);
for (int i=0; i < n; i++) {
x_cen.row(i) = x.row(i) - mu;
}
return sum((x_cen * sigma.i()) % x_cen, 1); // can probably change sigma.i() to inversion for positive semi-definite matrices (for speed!)
}
// Compute density of multivariate normal
// [[Rcpp::export]]
arma::vec cdmvnorm(arma::mat x, arma::rowvec mu, arma::mat sigma){
arma::vec mdist = Mahalanobis(x, mu, sigma);
double logdet = log(arma::det(sigma));
const double log2pi = std::log(2.0 * M_PI);
arma::vec logretval = -(x.n_cols * log2pi + logdet + mdist)/2;
return exp(logretval);
}
// estimation and model selection of penalized GMM
// [[Rcpp::export]]
Rcpp::List cfpGMM(arma::mat& x,
arma::rowvec prop,
arma::mat& mu,
arma::cube& sigma,
int k,
double df,
double lambda,
int citermax,
double tol
) {
const int n = x.n_rows;
const int d = x.n_cols;
double delta = 1;
arma::rowvec prop_old = prop;
arma::mat mu_old = mu;
arma::cube sigma_old = sigma;
arma::uvec tag(n, arma::fill::none);
arma::mat pdf_est(n, k, arma::fill::none);
arma::mat prob0(n, k, arma::fill::none);
arma::mat h_est(n, k, arma::fill::none);
//double thresh = 1/(log(n) * sqrt(n));
double thresh = 1E-03;
for(int step = 0; step < citermax; ++step) {
// E step
for(int i = 0; i < k; ++i) {
arma::rowvec tmp_mu = mu_old.row(i);
arma::mat tmp_sigma = sigma_old.slice(i);
pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
prob0.col(i) = pdf_est.col(i) * prop_old(i);
}
h_est.set_size(n, k);
for(int i = 0; i < n; ++i) {
h_est.row(i) = prob0.row(i)/(sum(prob0.row(i)) * 1.0L);
}
// M step
// update mean
arma::mat mu_new(k, d, arma::fill::none);
for(int i = 0; i < k; ++i) {
mu_new.row(i) = trans(h_est.col(i))*x/(sum(h_est.col(i)) * 1.0L);
}
// update sigma
arma::cube dist(n, d, k, arma::fill::none);
arma::cube sigma_new = sigma_old;
arma::mat ones(n, 1, arma::fill::ones);
for(int i = 0; i < k; ++i) {
dist.slice(i) = x - ones * mu_new.row(i);
sigma_new.slice(i) = trans(dist.slice(i)) * diagmat(h_est.col(i)) * dist.slice(i) / (sum(h_est.col(i)) * 1.0L);
}
// update proportion
arma::rowvec prop_new(k, arma::fill::none);
for(int i = 0; i < k; ++i){
prop_new(i) = (sum(h_est.col(i)) - lambda * df) / (n-k*lambda*df) * 1.0L;
if(prop_new(i) < thresh) // tolerance greater than 0 for numerical stability (Huang2013)
prop_new(i) = 0;
}
prop_new = prop_new/(sum(prop_new) * 1.0L);
// calculate difference between two iterations
delta = sum(abs(prop_new - prop_old));
// eliminate small clusters
if(sum(prop_new == 0) > 0) {
arma::uvec idx = find(prop_new > 0);
k = idx.size();
prop_old.set_size(k);
prop_old = trans(prop_new.elem(idx));
mu_old.set_size(k,d);
mu_old = mu_new.rows(idx);
sigma_old.set_size(d,d,k);
sigma_old = choose_slice(sigma_new, idx, d, k);
pdf_est = pdf_est.cols(idx);
prob0 = prob0.cols(idx);
h_est = h_est.cols(idx);
delta = 1;
}
else{
prop_old = prop_new;
mu_old = mu_new;
sigma_old = sigma_new;
}
//calculate cluster with maximum posterior probability
tag = index_max(h_est, 1);
if(delta < tol)
break;
if(k <= 1)
break;
}
// update likelihood for output
for(int i = 0; i < k; ++i) {
arma::rowvec tmp_mu = mu_old.row(i);
arma::mat tmp_sigma = sigma_old.slice(i);
pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
prob0.col(i) = pdf_est.col(i) * prop_old(i);
}
return Rcpp::List::create(Rcpp::Named("k") = k,
Rcpp::Named("prop") = prop_old,
Rcpp::Named("mu") = mu_old,
Rcpp::Named("sigma") = sigma_old,
Rcpp::Named("pdf_est") = pdf_est,
Rcpp::Named("ll") = sum(log(sum(prob0,1))),
Rcpp::Named("cluster") = tag+1,
Rcpp::Named("post_prob") = h_est);
}
//
// Stuff for constrained penalized Gaussian mixture model
//
// Calculate variance covariance matrix for constrained pGMM
// [[Rcpp::export]]
arma::mat cget_constr_sigma(arma::rowvec sigma, double rho, arma::rowvec combos, int d){
arma::mat Sigma = diagmat(sigma);
for(int i = 0; i < d-1; ++i){
for(int j = i+1; j < d; ++j){
if(combos(i) == combos(j) & combos(i) != 0){
Sigma(i,j) = rho;
Sigma(j,i) = rho;
} else if(combos(i) == -combos(j) & combos(i) != 0){
Sigma(i,j) = -rho;
Sigma(j,i) = -rho;
}
}
}
return Sigma;
}
// objective function to be optimized
// [[Rcpp::export]]
double func_to_optim(const arma::colvec& init_val,
arma::mat& x,
arma::mat& h_est,
arma::mat& combos) {
double mu = init_val(0);
double sigma = exp(init_val(1));
double rho = init_val(2);
int n = x.n_rows;
int d = x.n_cols;
int k = h_est.n_cols;
double nll;
arma::mat tmp_sigma(d, d, arma::fill::none);
arma::rowvec tmp_mu(d, arma::fill::none);
arma::mat pdf_est(n, k, arma::fill::none);
if( (abs3(rho) >= sigma)) {// || (abs3(rho) >= 1) ) {
return std::numeric_limits<double>::infinity();
}
for(int i = 0; i < k; ++i) {
// get sigma_in to pass to cget_constr_sigma
// This amount to finding the diagonal of Sigma
arma::rowvec sigma_in(abs(sigma*combos.row(i)));
arma::uvec zeroidx = find(combos.row(i) == 0);
sigma_in.elem(zeroidx).ones();
// This min part accounts for the possibility that sigma is actually bigger than 1
// Need to enforce strict inequality between rho and sigma
tmp_sigma = cget_constr_sigma(sigma_in, rho, combos.row(i), d); // rho * sigma should constrain rho to be less than sigma in the optimization
tmp_mu = mu*combos.row(i);
pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
}
// Adjust for numerically zero values
arma::uvec zeroidx = find(pdf_est == 0);
if(zeroidx.size() > 0) {
arma::uvec posidx = find(pdf_est != 0);
double clamper = pdf_est.elem(posidx).min();
arma::colvec populate_vec = arma::ones(zeroidx.size());
populate_vec = populate_vec * clamper;
pdf_est.elem(zeroidx) = populate_vec;
}
nll = -accu(h_est % log(pdf_est));
return nll;
}
// optimize objective function using 'optim' is R-package 'stats'
// [[Rcpp::export]]
arma::vec optim_rcpp(const arma::vec& init_val,
arma::mat& x,
arma::mat& h_est,
arma::mat& combos){
Rcpp::Environment stats("package:stats");
Rcpp::Function optim = stats["optim"];
try{
Rcpp::List opt = optim(Rcpp::_["par"] = init_val,
Rcpp::_["fn"] = Rcpp::InternalFunction(&func_to_optim),
Rcpp::_["method"] = "Nelder-Mead",
Rcpp::_["x"] = x,
Rcpp::_["h_est"] = h_est,
Rcpp::_["combos"] = combos);
arma::vec mles = Rcpp::as<arma::vec>(opt["par"]);
return mles;
}
catch(...){
arma::colvec err = { NA_REAL, NA_REAL, NA_REAL };
return err;
}
}
// // estimation and model selection of constrained penalized GMM
// // [[Rcpp::export]]
// Rcpp::List cfconstr_pGMM(arma::mat& x,
// arma::rowvec prop,
// arma::mat mu,
// arma::mat sigma,
// double rho,
// arma::mat combos,
// int k,
// arma::rowvec df,
// int lambda,
// int citermax,
// double tol,
// unsigned int LASSO) {
//
// const int n = x.n_rows;
// const int d = x.n_cols;
// double delta = 1;
// arma::rowvec prop_old = prop;
// arma::rowvec prop_new;
// arma::mat mu_old = mu;
// arma::mat sigma_old = sigma;
// double rho_old = rho;
// arma::uvec tag(n, arma::fill::none);
// arma::mat pdf_est(n, k, arma::fill::none);
// arma::mat prob0(n, k, arma::fill::none);
// arma::mat tmp_sigma(d,d,arma::fill::none);
// arma::mat h_est(n, k, arma::fill::none);
// double term; // for SCAD
// arma::colvec err_test = { NA_REAL };
//
// double thresh = 1E-03;
//
// for(int step = 0; step < citermax; ++step) {
// // E step
// for(int i = 0; i < k; ++i) {
// arma::rowvec tmp_mu = mu_old.row(i);
// tmp_sigma = cget_constr_sigma(sigma_old.row(i), rho_old, combos.row(i), d);
//
// try {
// pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
// prob0.col(i) = pdf_est.col(i) * prop_old(i);
// }
// catch(...){
// arma::colvec err = { NA_REAL, NA_REAL, NA_REAL };
// return Rcpp::List::create(Rcpp::Named("optim_err") = NA_REAL);
// }
// }
//
// h_est.set_size(n, k);
// for(int i = 0; i < n; ++i) {
// h_est.row(i) = prob0.row(i)/(sum(prob0.row(i)) * 1.0L);
// }
//
// // M step
// // update mean and variance covariance with numerical optimization
//
// // Select the mean and variance associated with reproducibility
// arma::uvec repidx = find(combos, 0);
// int idx = repidx(0);
// double mu_in = abs3(mu_old(idx));
// double sigma_in = sigma_old(idx);
// arma::colvec init_val = arma::colvec( { mu_in, log(sigma_in), rho_old } );
//
// // Optimize using optim (for now)
// arma::colvec param_new(3, arma::fill::none);
// param_new = optim_rcpp(init_val, x, h_est, combos);
//
// if(param_new(0) == err_test(0)) {
// return Rcpp::List::create(Rcpp::Named("optim_err") = NA_REAL);
// }
//
// // transform sigma back
// param_new(1) = exp(param_new(1));
//
// prop_new.set_size(k);
// if(LASSO == 1) {
// // update proportion via LASSO penalty
// for(int i = 0; i < k; ++i){
// prop_new(i) = (sum(h_est.col(i)) - lambda * df(i)) / (n-lambda*sum(df)) * 1.0L;
// if(prop_new(i) < thresh) // tolerance greater than 0 for numerical stability (Huang2013)
// prop_new(i) = 0;
// }
// } else {
// // proportion update via SCAD penalty
// term = accu((SCAD_1d(prop, lambda, k) % prop_old) % (1 / (1E-06 + SCAD(prop, lambda, k))));
// for(int i = 0; i < k; ++i) {
// prop_new(i) = sum(h_est.col(i)) /
// (n - (double_SCAD_1d(prop_old(i), lambda) / (1E-06 + double_SCAD(prop_old(i), lambda)) +
// term) * lambda * df(i)) * 1.0L;
// if(prop_new(i) < thresh) // tolerance greater than 0 for numerical stability (Huang2013)
// prop_new(i) = 0;
// }
// }
// prop_new = prop_new/(sum(prop_new) * 1.0L); // renormalize weights
//
// // calculate difference between two iterations
// delta = sum(abs(prop_new - prop_old));
//
// // eliminate small clusters
// if(sum(prop_new == 0) > 0) {
// arma::uvec idx = find(prop_new > 0);
// k = idx.size();
// prop_old = trans(prop_new.elem(idx));
// combos = combos.rows(idx);
// df = trans(df.elem(idx));
//
// mu_old.set_size(k,d);
// mu_old = combos*param_new(0);
//
// sigma_old.set_size(k,d);
// sigma_old = abs(combos*param_new(1));
// arma::uvec zeroidx2 = find(sigma_old == 0);
// sigma_old.elem(zeroidx2).ones();
//
// rho_old = param_new(2);
//
// pdf_est = pdf_est.cols(idx);
// prob0 = prob0.cols(idx);
// h_est = h_est.cols(idx);
// delta = 1;
// }
// else{
// prop_old = prop_new;
// mu_old = combos*param_new(0);
//
// sigma_old = abs(combos*param_new(1));
// arma::uvec zeroidx2 = find(sigma_old == 0);
// sigma_old.elem(zeroidx2).ones();
//
// rho_old = param_new(2);
// }
//
// //calculate cluster with maximum posterior probability
// tag = index_max(h_est, 1);
//
// if(delta < tol)
// break;
//
// if(k <= 1)
// break;
//
// }
//
// // update the likelihood for output
// for(int i = 0; i < k; ++i) {
// arma::rowvec tmp_mu = mu_old.row(i);
// tmp_sigma = cget_constr_sigma(sigma_old.row(i), rho_old, combos.row(i), d);
// pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
// prob0.col(i) = pdf_est.col(i) * prop_old(i);
// }
//
// return Rcpp::List::create(Rcpp::Named("k") = k,
// Rcpp::Named("prop") = prop_old,
// Rcpp::Named("mu") = mu_old,
// Rcpp::Named("sigma") = sigma_old,
// Rcpp::Named("rho") = rho_old,
// Rcpp::Named("df") = df,
// Rcpp::Named("pdf_est") = pdf_est,
// Rcpp::Named("ll") = sum(log(sum(prob0,1))),
// Rcpp::Named("cluster") = tag+1,
// Rcpp::Named("post_prob") = h_est,
// Rcpp::Named("combos") = combos);
// }
// objective function to be optimized
// [[Rcpp::export]]
double func_to_optim_bound(const arma::colvec& init_val,
arma::mat& x,
arma::mat& h_est,
arma::mat& combos,
double& bound) {
double mu = init_val(0);
double sigma = exp(init_val(1));
double rho = init_val(2);
int n = x.n_rows;
int d = x.n_cols;
int k = h_est.n_cols;
double nll;
if( (abs3(rho) >= sigma)) {
return std::numeric_limits<double>::infinity();
}
if( (abs3(mu) < bound)) {
return std::numeric_limits<double>::infinity();
}
arma::mat tmp_sigma(d, d, arma::fill::none);
arma::rowvec tmp_mu(d, arma::fill::none);
arma::mat pdf_est(n, k, arma::fill::none);
for(int i = 0; i < k; ++i) {
// get sigma_in to pass to cget_constr_sigma
// This amount to finding the diagonal of Sigma
arma::rowvec sigma_in(abs(sigma*combos.row(i)));
arma::uvec zeroidx = find(combos.row(i) == 0);
sigma_in.elem(zeroidx).ones();
// This min part accounts for the possibility that sigma is actually bigger than 1
// Need to enforce strict inequality between rho and sigma
tmp_sigma = cget_constr_sigma(sigma_in, rho, combos.row(i), d); // rho * sigma should constrain rho to be less than sigma in the optimization
tmp_mu = mu*combos.row(i);
pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
}
// Adjust for numerically zero values
arma::uvec zeroidx = find(pdf_est == 0);
if(zeroidx.size() > 0) {
arma::uvec posidx = find(pdf_est != 0);
double clamper = pdf_est.elem(posidx).min();
arma::colvec populate_vec = arma::ones(zeroidx.size());
populate_vec = populate_vec * clamper;
pdf_est.elem(zeroidx) = populate_vec;
}
nll = -accu(h_est % log(pdf_est));
return nll;
}
// optimize objective function using 'optim' is R-package 'stats'
// [[Rcpp::export]]
arma::vec optim_rcpp_bound(const arma::vec& init_val,
arma::mat& x,
arma::mat& h_est,
arma::mat& combos,
double& bound){
Rcpp::Environment stats("package:stats");
Rcpp::Function optim = stats["optim"];
try{
Rcpp::List opt = optim(Rcpp::_["par"] = init_val,
Rcpp::_["fn"] = Rcpp::InternalFunction(&func_to_optim_bound),
Rcpp::_["method"] = "Nelder-Mead",
Rcpp::_["x"] = x,
Rcpp::_["h_est"] = h_est,
Rcpp::_["combos"] = combos,
Rcpp::_["bound"] = bound);
arma::vec mles = Rcpp::as<arma::vec>(opt["par"]);
return mles;
}
catch(...){
arma::colvec err = { NA_REAL, NA_REAL, NA_REAL };
return err;
}
}
// estimation and model selection of constrained penalized GMM
// [[Rcpp::export]]
Rcpp::List cfconstr_pgmm(arma::mat& x,
arma::rowvec prop,
arma::mat mu,
arma::mat sigma,
double rho,
arma::mat combos,
int k,
arma::rowvec df,
int lambda,
int citermax,
double tol,
unsigned int LASSO,
double bound = 0.0) {
const int n = x.n_rows;
const int d = x.n_cols;
double delta = 1;
arma::rowvec prop_old = prop;
arma::rowvec prop_new;
arma::mat mu_old = mu;
arma::mat sigma_old = sigma;
double rho_old = rho;
arma::uvec tag(n, arma::fill::none);
arma::mat pdf_est(n, k, arma::fill::none);
arma::mat prob0(n, k, arma::fill::none);
arma::mat tmp_sigma(d,d,arma::fill::none);
arma::mat h_est(n, k, arma::fill::none);
double term; // for SCAD
arma::colvec err_test = { NA_REAL };
double thresh = 1E-03;
for(int step = 0; step < citermax; ++step) {
// E step
for(int i = 0; i < k; ++i) {
arma::rowvec tmp_mu = mu_old.row(i);
tmp_sigma = cget_constr_sigma(sigma_old.row(i), rho_old, combos.row(i), d);
try {
pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
prob0.col(i) = pdf_est.col(i) * prop_old(i);
}
catch(...){
arma::colvec err = { NA_REAL, NA_REAL, NA_REAL };
return Rcpp::List::create(Rcpp::Named("optim_err") = NA_REAL);
}
}
h_est.set_size(n, k);
for(int i = 0; i < n; ++i) {
h_est.row(i) = prob0.row(i)/(sum(prob0.row(i)) * 1.0L);
}
// M step
// update mean and variance covariance with numerical optimization
// Select the mean and variance associated with reproducibility
arma::uvec repidx = find(combos, 0);
int idx = repidx(0);
double mu_in = std::max(abs3(mu_old(idx)), bound);
double sigma_in = sigma_old(idx);
arma::colvec init_val = arma::colvec( { mu_in, log(sigma_in), rho_old } );
// Optimize using optim (for now)
arma::colvec param_new(3, arma::fill::none);
if(bound == 0.0) {
param_new = optim_rcpp(init_val, x, h_est, combos);
} else {
param_new = optim_rcpp_bound(init_val, x, h_est, combos, bound);
}
if(param_new(0) == err_test(0)) {
return Rcpp::List::create(Rcpp::Named("optim_err") = NA_REAL);
}
// transform sigma back
param_new(1) = exp(param_new(1));
prop_new.set_size(k);
if(LASSO == 1) {
// update proportion via LASSO penalty
for(int i = 0; i < k; ++i){
prop_new(i) = (sum(h_est.col(i)) - lambda * df(i)) / (n-lambda*sum(df)) * 1.0L;
if(prop_new(i) < thresh) // tolerance greater than 0 for numerical stability (Huang2013)
prop_new(i) = 0;
}
} else {
// proportion update via SCAD penalty
term = accu((SCAD_1d(prop, lambda, k) % prop_old) % (1 / (1E-06 + SCAD(prop, lambda, k))));
for(int i = 0; i < k; ++i) {
prop_new(i) = sum(h_est.col(i)) /
(n - (double_SCAD_1d(prop_old(i), lambda) / (1E-06 + double_SCAD(prop_old(i), lambda)) +
term) * lambda * df(i)) * 1.0L;
if(prop_new(i) < thresh) // tolerance greater than 0 for numerical stability (Huang2013)
prop_new(i) = 0;
}
}
prop_new = prop_new/(sum(prop_new) * 1.0L); // renormalize weights
// calculate difference between two iterations
delta = sum(abs(prop_new - prop_old));
// eliminate small clusters
if(sum(prop_new == 0) > 0) {
arma::uvec idx = find(prop_new > 0);
k = idx.size();
prop_old = trans(prop_new.elem(idx));
combos = combos.rows(idx);
df = trans(df.elem(idx));
mu_old.set_size(k,d);
mu_old = combos*param_new(0);
sigma_old.set_size(k,d);
sigma_old = abs(combos*param_new(1));
arma::uvec zeroidx2 = find(sigma_old == 0);
sigma_old.elem(zeroidx2).ones();
rho_old = param_new(2);
pdf_est = pdf_est.cols(idx);
prob0 = prob0.cols(idx);
h_est = h_est.cols(idx);
delta = 1;
}
else{
prop_old = prop_new;
mu_old = combos*param_new(0);
sigma_old = abs(combos*param_new(1));
arma::uvec zeroidx2 = find(sigma_old == 0);
sigma_old.elem(zeroidx2).ones();
rho_old = param_new(2);
}
//calculate cluster with maximum posterior probability
tag = index_max(h_est, 1);
if(delta < tol)
break;
if(k <= 1)
break;
}
// update the likelihood for output
for(int i = 0; i < k; ++i) {
arma::rowvec tmp_mu = mu_old.row(i);
tmp_sigma = cget_constr_sigma(sigma_old.row(i), rho_old, combos.row(i), d);
pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
prob0.col(i) = pdf_est.col(i) * prop_old(i);
}
return Rcpp::List::create(Rcpp::Named("k") = k,
Rcpp::Named("prop") = prop_old,
Rcpp::Named("mu") = mu_old,
Rcpp::Named("sigma") = sigma_old,
Rcpp::Named("rho") = rho_old,
Rcpp::Named("df") = df,
Rcpp::Named("pdf_est") = pdf_est,
Rcpp::Named("ll") = sum(log(sum(prob0,1))),
Rcpp::Named("cluster") = tag+1,
Rcpp::Named("post_prob") = h_est,
Rcpp::Named("combos") = combos);
}
// //
// // Stuff for the less constrained (constr0) penalized Gaussian mixture model
// //
//
// // Bind diagonals from covariances into one matrix (for use by optim)
// // [[Rcpp::export]]
// arma::mat bind_diags(arma::cube Sigma_in) {
// int n = Sigma_in.n_slices;
// arma::mat diagbind(n, 2, arma::fill::none);
// for(int i = 0; i < n; ++i) {
// diagbind.row(i) = Sigma_in.slice(i).diag().t();
// }
// return diagbind;
// }
//
// // Bind off-diagonals from covariances into one matrix (for use by optim)
// // [[Rcpp::export]]
// arma::colvec bind_offdiags(arma::cube Sigma_in) {
// arma::colvec rhobind = Sigma_in.tube(1,0);
// return rhobind;
// }
//
// // get vector of association-related variances for optim input
// // [[Rcpp::export]]
// arma::colvec get_sigma_optim(arma::mat diagbind, arma::mat combos) {
// arma::uvec neg = find(combos == -1);
// arma::uvec pos = find(combos == 1);
// arma::colvec sig_out;
//
// if(neg.n_rows > 0 & pos.n_rows > 0){
// sig_out = { diagbind(neg(0)), diagbind(pos(0)) };
// } else if(neg.n_rows > 0 & pos.n_rows == 0){
// sig_out = { diagbind(neg(0)) };
// } else if(neg.n_rows == 0 & pos.n_rows > 0){
// sig_out = { diagbind(pos(0)) };
// }
// return sig_out;
// }
//
// // get vector of association-related means for optim input
// // [[Rcpp::export]]
// arma::colvec get_mu_optim(arma::mat mu_in, arma::mat combos) {
// arma::uvec neg = find(combos == -1);
// arma::uvec pos = find(combos == 1);
// arma::colvec mu_out;
//
// if(neg.n_rows > 0 & pos.n_rows > 0){
// mu_out = { mu_in(neg(0)), mu_in(pos(0)) };
// } else if(neg.n_rows > 0 & pos.n_rows == 0){
// mu_out = { mu_in(neg(0)) };
// } else if(neg.n_rows == 0 & pos.n_rows > 0){
// mu_out = { mu_in(pos(0)) };
// }
// return mu_out;
// }
//
// // get rho for optim
// // [[Rcpp::export]]
// arma::colvec get_rho_optim(arma::colvec rhobind, arma::mat combos) {
// int n = combos.n_rows;
// int len = 0;
// arma::colvec rho_out(3);
//
// arma::colvec twoneg = { -1, -1 };
// arma::colvec twopos = { 1, 1 };
// arma::colvec cross1 = { -1, 1 };
// arma::colvec cross2 = { 1, -1 };
//
// for(int i = 0; i < n; ++i){
// if(combos(i,0) == twoneg(0) & combos(i,1) == twoneg(1)) {
// rho_out(len) = rhobind(i);
// ++len;
// break;
// }
// }
//
// for(int i = 0; i < n; ++i){
// if((combos(i,0) == cross1(0) & combos(i,1) == cross1(1)) ||
// (combos(i,0) == cross2(0) & combos(i,1) == cross2(1))){
// rho_out(len) = rhobind(i);
// ++len;
// break;
// }
// }
//
// for(int i = 0; i < n; ++i){
// if(combos(i,0) == twopos(0) & combos(i,1) == twopos(1)){
// rho_out(len) = rhobind(i);
// ++len;
// break;
// }
// }
// return rho_out.head(len);
// }
//
// // objective function to be optimized
// // [[Rcpp::export]]
// double func_to_optim0(const arma::colvec& init_val,
// const arma::mat& x,
// const arma::mat& h_est,
// const arma::mat& combos,
// const int& a, const int& b, const int& c,
// const arma::uvec& negidx) {
// arma::colvec mu(a);
// arma::colvec sigma(b);
// arma::colvec rho(c);
//
// mu.insert_rows(0, exp(init_val.subvec(0,a-1)));
// mu.elem(negidx) = -mu.elem(negidx);
// sigma.insert_rows(0, exp(init_val.subvec(a,a+b-1)));
// rho.insert_rows(0, init_val.subvec(a+b, a+b+c-1));
// for(int i = 0; i < c; ++i){
// rho(i) = trans_rho_inv(rho(i));
// }
//
// int n = x.n_rows;
// int d = x.n_cols;
// int k = h_est.n_cols;
// double nll;
//
// // get appropriate mean vector and covariance matrix to pass to cdmvnorm
// arma::mat tmp_sigma(d, d, arma::fill::zeros);
// arma::rowvec tmp_mu(d, arma::fill::zeros);
// arma::mat pdf_est(n, k, arma::fill::none);
//
// for(int i = 0; i < k; ++i) {
// for(int j = 0; j < d; ++j){
// if(combos(i,j) == -1){
// tmp_mu(j) = mu(0);
// tmp_sigma(j,j) = sigma(0);
// } else if(combos(i,j) == 0){
// tmp_sigma(j,j) = 1;
// } else{
// tmp_mu(j) = mu(a-1);
// tmp_sigma(j,j) = sigma(b-1);
// }
// }
//
// if(combos(i,0) == -1 & combos(i,1) == -1) {
// tmp_sigma(0,1) = rho(0);
// tmp_sigma(1,0) = rho(0);
// } else if(combos(i,0) == 1 & combos(i,1) == 1){
// tmp_sigma(0,1) = rho(c-1);
// tmp_sigma(1,0) = rho(c-1);
// } else if((combos(i,0) == -1 & combos(i,1) == 1) ||
// (combos(i,0) == 1 & combos(i,1) == -1)){
// if(rho(0) < 0){
// tmp_sigma(0,1) = rho(0);
// tmp_sigma(1,0) = rho(0);
// } else if(rho(1) < 0){
// tmp_sigma(0,1) = rho(1);
// tmp_sigma(1,0) = rho(1);
// } else{
// tmp_sigma(0,1) = rho(2);
// tmp_sigma(1,0) = rho(2);
// }
// }
// pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_sigma);
// }
// nll = -accu(h_est % log(pdf_est));
// return nll;
// }
//
// // optimize objective function using 'optim' is R-package 'stats'
// // [[Rcpp::export]]
// arma::vec optim0_rcpp(const arma::vec& init_val,
// arma::mat& x,
// arma::mat& h_est,
// arma::mat& combos,
// int& a, int& b, int& c,
// arma::uvec& negidx){
//
// Rcpp::Environment stats("package:stats");
// Rcpp::Function optim = stats["optim"];
//
// Rcpp::List opt = optim(Rcpp::_["par"] = init_val,
// Rcpp::_["fn"] = Rcpp::InternalFunction(&func_to_optim0),
// Rcpp::_["method"] = "Nelder-Mead",
// Rcpp::_["x"] = x,
// Rcpp::_["h_est"] = h_est,
// Rcpp::_["combos"] = combos,
// Rcpp::_["a"] = a,
// Rcpp::_["b"] = b,
// Rcpp::_["c"] = c,
// Rcpp::_["negidx"] = negidx);
// arma::vec mles = Rcpp::as<arma::vec>(opt["par"]);
//
// return mles;
// }
//
// // estimation and model selection of constrained penalized GMM
// // [[Rcpp::export]]
// Rcpp::List cfconstr0_pGMM(arma::mat& x,
// arma::rowvec prop,
// arma::mat mu,
// arma::cube Sigma,
// arma::mat combos,
// int k,
// arma::rowvec df,
// int lambda,
// int citermax,
// double tol) {
//
// const int n = x.n_rows;
// const int d = x.n_cols;
// double delta = 1;
// arma::rowvec prop_old = prop;
// arma::mat mu_old = mu;
// arma::cube Sigma_old = Sigma;
// arma::uvec tag(n, arma::fill::none);
// arma::mat pdf_est(n, k, arma::fill::none);
// arma::mat prob0(n, k, arma::fill::none);
// arma::mat tmp_Sigma(d,d,arma::fill::none);
// arma::mat h_est(n, k, arma::fill::none);
// arma::colvec init_val;
// arma::colvec param_new;
// arma::rowvec tmp_mu(d, arma::fill::none);
// arma::rowvec prop_new;
// double thresh = 1E-03;
//
// for(int step = 0; step < citermax; ++step) {
// // E step
// for(int i = 0; i < k; ++i) {
// tmp_mu = mu_old.row(i);
// tmp_Sigma = Sigma_old.slice(i);
//
// pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_Sigma);
// prob0.col(i) = pdf_est.col(i) * prop_old(i);
// }
//
// h_est.set_size(n, k);
// for(int i = 0; i < n; ++i) {
// h_est.row(i) = prob0.row(i)/(sum(prob0.row(i)) * 1.0L);
// }
//
// // M step
// // update mean and variance covariance with numerical optimization
// arma::colvec sgn_mu_in = get_mu_optim(mu_old, combos);
// arma::uvec negidx = find(sgn_mu_in < 0);
// arma::colvec sigma_in = get_sigma_optim(bind_diags(Sigma_old), combos);
// arma::colvec rho_in = get_rho_optim(bind_offdiags(Sigma_old), combos);
// int a = sgn_mu_in.n_rows;
// int b = sigma_in.n_rows;
// int c = rho_in.n_rows;
//
// for(int i = 0; i < c; ++i){
// rho_in(i) = trans_rho(rho_in(i));
// }
//
// init_val.set_size(a+b+c);
// init_val.subvec(0,a-1) = log(abs(sgn_mu_in));
// init_val.subvec(a,a+b-1) = log(sigma_in);
// init_val.subvec(a+b, a+b+c-1) = rho_in;
//
// // Optimize using optim
// param_new.copy_size(init_val);
// param_new = optim0_rcpp(init_val, x, h_est, combos, a, b, c, negidx);
//
// // Transform parameters back
// param_new.subvec(0,a-1) = exp(param_new.subvec(0,a-1));
// param_new.elem(negidx) = -param_new.elem(negidx);
// param_new.subvec(a,a+b-1) = exp(param_new.subvec(a,a+b-1));
// for(int i = 0; i < c; ++i){
// param_new(a+b+i) = trans_rho_inv(param_new(a+b+i));
// }
//
// // Make Sigma cube, mu matrix again
// for(int i = 0; i < k; ++i) {
// for(int j = 0; j < d; ++j){
// if(combos(i,j) == -1){
// mu_old(i,j) = param_new(0);
// Sigma_old(j,j,i) = param_new(a);
// } else if(combos(i,j) == 0){
// mu_old(i,j) = 0;
// Sigma_old(j,j,i) = 1;
// } else{
// mu_old(i,j) = param_new(a-1);
// Sigma_old(j,j,i) = param_new(a+b-1);
// }
// }
// if(combos(i,0) == -1 & combos(i,1) == -1) {
// Sigma_old(0,1,i) = param_new(a+b);
// Sigma_old(1,0,i) = param_new(a+b);
// } else if(combos(i,0) == 1 & combos(i,1) == 1){
// Sigma_old(0,1,i) = param_new(a+b+c-1);
// Sigma_old(1,0,i) = param_new(a+b+c-1);
// } else if((combos(i,0) == -1 & combos(i,1) == 1) ||
// (combos(i,0) == 1 & combos(i,1) == -1)){
// if(param_new(a+b) < 0){
// Sigma_old(0,1,i) = param_new(a+b);
// Sigma_old(1,0,i) = param_new(a+b);
// } else if(param_new(a+b+1) < 0){
// Sigma_old(0,1,i) = param_new(a+b+1);
// Sigma_old(1,0,i) = param_new(a+b+1);
// } else{
// Sigma_old(0,1,i) = param_new(a+b+c-1);
// Sigma_old(1,0,i) = param_new(a+b+c-1);
// }
// }
// }
//
// // update proportion
// prop_new.set_size(k);
// for(int i = 0; i < k; ++i){
// prop_new(i) = (sum(h_est.col(i)) - lambda * df(i)) / (n-lambda*sum(df)) * 1.0L;
// if(prop_new(i) < thresh) // tolerance greater than 0 for numerical stability (Huang2013)
// prop_new(i) = 0;
// }
// prop_new = prop_new/(sum(prop_new) * 1.0L);
//
// // calculate difference between two iterations
// delta = sum(abs(prop_new - prop_old));
//
// // eliminate small clusters
// if(sum(prop_new == 0) > 0) {
// arma::uvec idx = find(prop_new > 0);
// k = idx.size();
// prop_old = trans(prop_new.elem(idx));
// combos = combos.rows(idx);
// df = trans(df.elem(idx));
//
// mu_old = mu_old.rows(idx);
// Sigma_old = choose_slice(Sigma_old, idx, d, k);
//
// pdf_est = pdf_est.cols(idx);
// prob0 = prob0.cols(idx);
// h_est = h_est.cols(idx);
// delta = 1;
// }
// else{
// prop_old = prop_new;
// }
//
// //calculate cluster with maximum posterior probability
// tag = index_max(h_est, 1);
//
// if(delta < tol)
// break;
// if(k <= 1)
// break;
// }
//
// // update the likelihood for output
// for(int i = 0; i < k; ++i) {
// arma::rowvec tmp_mu = mu_old.row(i);
// tmp_Sigma = Sigma_old.slice(i);
// pdf_est.col(i) = cdmvnorm(x, tmp_mu, tmp_Sigma);
// prob0.col(i) = pdf_est.col(i) * prop_old(i);
// }
//
// return Rcpp::List::create(Rcpp::Named("k") = k,
// Rcpp::Named("prop") = prop_old,
// Rcpp::Named("mu") = mu_old,
// Rcpp::Named("Sigma") = Sigma_old,
// Rcpp::Named("df") = df,
// Rcpp::Named("pdf_est") = pdf_est,
// Rcpp::Named("ll") = sum(log(sum(prob0,1))),
// Rcpp::Named("cluster") = tag+1,
// Rcpp::Named("post_prob") = h_est);
// }
// Compute density of univariate normal
// [[Rcpp::export]]
arma::colvec cduvnorm(arma::colvec x, double mu, double sigma){
arma::colvec mdist = ((x-mu) % (x-mu))/(sigma);
const double log2pi = std::log(2.0 * M_PI);
double logcoef = -(log2pi + log(sigma));
arma::colvec logretval = (logcoef - mdist)/2;
return exp(logretval);
}
// computing marginal likelihood of constrained gmm (for copula likelihood)
// [[Rcpp::export]]
double cmarg_ll_gmm(arma::mat& z,
arma::mat mu,
arma::mat sigma,
arma::rowvec prop,
arma::mat combos,
int k) {
const int n = z.n_rows;
const int d = z.n_cols;
arma::mat mll(n,d,arma::fill::none);
arma::mat pdf_est(n,k,arma::fill::none);
double tmp_sigma;
double tmp_mu;
for(int i = 0; i < d; ++i){
for(int j = 0; j < k; ++j) {
tmp_mu = mu(j,i);
tmp_sigma = sigma(j,i);
pdf_est.col(j) = prop(j) * cduvnorm(z.col(i), tmp_mu, tmp_sigma);
}
mll.col(i) = log(sum(pdf_est,1));
}
return accu(mll);
}
// computing joint likelihood of constrained gmm (for copula likelihood)
// [[Rcpp::export]]
double cll_gmm(arma::mat& z,
arma::mat mu,
arma::mat sigma,
double rho,
arma::rowvec prop,
arma::mat combos,
int k) {
const int n = z.n_rows;
const int d = z.n_cols;
arma::rowvec tmp_mu(d, arma::fill::none);
arma::mat tmp_sigma(d, d, arma::fill::none);
arma::mat pdf_est(n,k,arma::fill::none);
for(int i = 0; i < k; ++i) {
tmp_mu = mu.row(i);
tmp_sigma = cget_constr_sigma(sigma.row(i), rho, combos.row(i), d);
pdf_est.col(i) = prop(i) * cdmvnorm(z, tmp_mu, tmp_sigma);
}
return accu(log(sum(pdf_est,1)));
}
// // computing marginal likelihood of LESS constrained (0) gmm (for copula likelihood)
// // [[Rcpp::export]]
// double cmarg0_ll_gmm(arma::mat& z,
// arma::mat mu,
// arma::cube Sigma,
// arma::rowvec prop,
// int k) {
// const int n = z.n_rows;
// const int d = z.n_cols;
// arma::mat mll(n,d,arma::fill::none);
// arma::mat pdf_est(n,k,arma::fill::none);
// double tmp_sigma;
// double tmp_mu;
// arma::mat tmp_Sigma(d,d,arma::fill::none);
//
// for(int i = 0; i < d; ++i){
// for(int j = 0; j < k; ++j) {
// tmp_mu = mu(j,i);
// tmp_Sigma = Sigma.slice(j);
// tmp_sigma = tmp_Sigma(i,i);
// pdf_est.col(j) = prop(j) * cduvnorm(z.col(i), tmp_mu, tmp_sigma);
// }
// mll.col(i) = log(sum(pdf_est,1));
// }
// return accu(mll);
// }
//
// // computing joint likelihood of LESS xconstrained (0) gmm (for copula likelihood)
// // [[Rcpp::export]]
// double cll0_gmm(arma::mat& z,
// arma::mat mu,
// arma::cube Sigma,
// arma::rowvec prop,
// int k) {
// const int n = z.n_rows;
// const int d = z.n_cols;
// arma::rowvec tmp_mu(d, arma::fill::none);
// arma::mat tmp_sigma(d, d, arma::fill::none);
// arma::mat pdf_est(n,k,arma::fill::none);
//
// for(int i = 0; i < k; ++i) {
// tmp_mu = mu.row(i);
// tmp_sigma = Sigma.slice(i);
// pdf_est.col(i) = prop(i) * cdmvnorm(z, tmp_mu, tmp_sigma);
// }
// return accu(log(sum(pdf_est,1)));
// }
//
//
| 35.271555 | 149 | 0.486018 | hillarykoch |
5296a365d54aa77ca2a68c2206565464ad489d93 | 2,086 | cpp | C++ | first/src/textures/Texture.cpp | DeeJack/opengl_first_project | 29a6ec89d80046ceb575c02d009e611b835f49fe | [
"MIT"
] | null | null | null | first/src/textures/Texture.cpp | DeeJack/opengl_first_project | 29a6ec89d80046ceb575c02d009e611b835f49fe | [
"MIT"
] | null | null | null | first/src/textures/Texture.cpp | DeeJack/opengl_first_project | 29a6ec89d80046ceb575c02d009e611b835f49fe | [
"MIT"
] | null | null | null | #include "GLEW/glew.h"
#include "Texture.h"
#include <stdexcept>
#include <thread>
#include "Image.h"
#include "../log.h"
Texture::Texture() = default;
Texture::Texture(const char* path)
{
load(path);
}
void Texture::load_texture(const unsigned char* const buffer)
{
glGenTextures(1, &_renderer_id);
bind(0);
// GL_TEXTURE_MIN_FILTER -> minification, scale down the texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// Mag -> magnification, if the area is bigger
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// The wrap (???)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// internal format: how openGL will store the data, format: how you provide the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
unbind();
}
void Texture::load(const char* path)
{
Image image;
image.load_image(path);
//stbi_set_flip_vertically_on_load(1); // OpenGL expect the texture to start from the bottom left
//int _bpp = 0; // Bits per pixel
//_local_buffer = stbi_load(path.c_str(), &_width, &_height, &_bpp, 4); // 4 because R, G, B, A
_width = image.width();
_height = image.height();
auto* buffer = image.local_buffer();
load_texture(buffer);
}
void Texture::load_async(const char* path, std::function<void()> callback)
{
Image* image = new Image();
image->load_image_async(path, [this, image, callback]
{
_height = image->height();
const auto* const buffer = image->local_buffer();
load_texture(buffer);
delete image;
callback();
});
}
Texture::~Texture()
{
unbind();
glDeleteTextures(1, &_renderer_id);
log("Destroyed Texture (" + std::to_string(_renderer_id) + ")");
}
void Texture::bind(const unsigned int slot) const
{
if (slot > 31)
throw std::invalid_argument("Invalid slot: " + std::to_string(slot));
glActiveTexture(GL_TEXTURE0 + slot);
glBindTexture(GL_TEXTURE_2D, _renderer_id);
}
void Texture::unbind()
{
glBindTexture(GL_TEXTURE_2D, 0);
}
| 25.439024 | 98 | 0.723873 | DeeJack |
529a8e2fab9f629782fa7a9d338c22dacac2a961 | 2,426 | hpp | C++ | dependencies/generator/include/ph_coroutines/generator/generator.hpp | phiwen96/ph_coroutines | 985c3ba5efa735d6756f8d777b9d2fcc3ac8fd18 | [
"Apache-2.0"
] | null | null | null | dependencies/generator/include/ph_coroutines/generator/generator.hpp | phiwen96/ph_coroutines | 985c3ba5efa735d6756f8d777b9d2fcc3ac8fd18 | [
"Apache-2.0"
] | null | null | null | dependencies/generator/include/ph_coroutines/generator/generator.hpp | phiwen96/ph_coroutines | 985c3ba5efa735d6756f8d777b9d2fcc3ac8fd18 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <experimental/coroutine>
#include <concepts>
#include "iterator.hpp"
//#include <ph_coroutines/coroutines.hpp>
//using namespace std;
using namespace std::experimental;
using namespace std::chrono_literals;
template <class promise>
struct generator
{
using value_type = typename promise::value_type;
using promise_type = promise;
coroutine_handle <promise_type> handle;
explicit generator (coroutine_handle <promise_type> h) : handle {h} {
cout << "generator(handle)" << endl;
}
generator (generator&& other) : handle {exchange (other.handle, {})} {
cout << "generator(other)" << endl;
}
generator& operator=(generator&& other) noexcept {
if (this != &other) {
if (handle) {
handle.destroy();
}
swap (handle, other.handle);
} else
{
throw std::runtime_error ("coro");
}
return *this;
}
~generator () {
cout << "~generator()" << endl;
// destroy the coroutine
if (handle)
{
handle.destroy();
}
}
generator(generator const&) = delete;
generator& operator=(const generator&) = delete;
explicit operator bool() {
return !handle.done();
}
template <typename O>
requires requires (value_type t, O o) {
o = t;
}
operator O () {
if (handle.done())
{
throw std::runtime_error ("no, coroutine is done");
}
handle.resume();
return handle.promise().value;
}
auto operator () () -> decltype (auto) {
// will allocate a new stack frame and store the return-address of the caller in the
// stack frame before transfering execution to the function.
// resumes the coroutine from the point it was suspended
if (handle.done())
{
throw std::runtime_error ("no, coroutine is done");
}
handle.resume();
return handle.promise().value;
}
using iterator = typename promise_type::iterator;
auto begin() -> decltype (auto) {
if (handle) {
handle.resume();
}
return iterator {handle};
}
auto end() -> decltype (auto) {
return typename iterator::sentinel{};
}
};
| 25.270833 | 92 | 0.545754 | phiwen96 |
529e0b142143ea50aa09452f74cab2708bdb2e4d | 315 | cc | C++ | tests/CompileTests/ElsaTestCases/t0179.cc | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | tests/CompileTests/ElsaTestCases/t0179.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | tests/CompileTests/ElsaTestCases/t0179.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z | // t0179.cc
// template, partially specialized to a template argument
// this one uncovered all kinds of subtle errors in the
// handling of template argument lists ...
template <class S, class T>
struct A {};
template <class T>
struct B {};
typedef int myint;
template <>
struct A<int, B<myint> >
{};
| 17.5 | 57 | 0.68254 | maurizioabba |
529e2642f50eda53c3d3955b56008286583d1536 | 224 | cpp | C++ | submit2/input8/87.cpp | czhongyu/kolmogorov-complexity | 0130f7b2116e77165788ce3ed153e9c2782f2599 | [
"Apache-2.0"
] | 1 | 2020-06-18T13:04:58.000Z | 2020-06-18T13:04:58.000Z | submit2/input8/87.cpp | zychn/kolmogorov-complexity | 0130f7b2116e77165788ce3ed153e9c2782f2599 | [
"Apache-2.0"
] | null | null | null | submit2/input8/87.cpp | zychn/kolmogorov-complexity | 0130f7b2116e77165788ce3ed153e9c2782f2599 | [
"Apache-2.0"
] | null | null | null | #include<ios>
int c[10],g=1,x,i;
q(int a)
{
if(a>9)
for(i=0;i<110;)
putchar(i%10==c[i/10]|i++/100|48);
for(int b=0;b<10;c[a]=b++,g?q(a+1):g++)
for(i=0;i<a;i++)x=b-c[i],g*=a-i^x&&x&&i-a^x;
}
main(){q(0);}
| 18.666667 | 47 | 0.459821 | czhongyu |
52a63af40245c4def7efe6e41064d43f6ce98764 | 595 | hpp | C++ | src/ai/common.hpp | synaodev/apostellein | f664a88d13f533df54ad6fb58c2ad8134f8f942c | [
"BSD-3-Clause"
] | 1 | 2022-01-16T07:06:13.000Z | 2022-01-16T07:06:13.000Z | src/ai/common.hpp | synaodev/apostellein | f664a88d13f533df54ad6fb58c2ad8134f8f942c | [
"BSD-3-Clause"
] | null | null | null | src/ai/common.hpp | synaodev/apostellein | f664a88d13f533df54ad6fb58c2ad8134f8f942c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <entt/core/hashed_string.hpp>
namespace ai {
constexpr entt::hashed_string null = "null";
constexpr entt::hashed_string hv_trigger = "hv-trigger";
constexpr entt::hashed_string full_chest = "full-chest";
constexpr entt::hashed_string empty_chest = "empty-chest";
constexpr entt::hashed_string door = "door";
constexpr entt::hashed_string spikes = "spikes";
constexpr entt::hashed_string bed = "bed";
constexpr entt::hashed_string ammo_station = "ammo-station";
constexpr entt::hashed_string computer = "computer";
constexpr entt::hashed_string fire = "fire";
}
| 35 | 61 | 0.759664 | synaodev |
52a885a1788b99d61de7d997ad48a0878adc4e5c | 1,637 | cpp | C++ | practice/binarySearch/AllocatePages.cpp | atpk/CP | 0eee3af02bb0466c85aeb8dd86cf3620567a354c | [
"MIT"
] | null | null | null | practice/binarySearch/AllocatePages.cpp | atpk/CP | 0eee3af02bb0466c85aeb8dd86cf3620567a354c | [
"MIT"
] | null | null | null | practice/binarySearch/AllocatePages.cpp | atpk/CP | 0eee3af02bb0466c85aeb8dd86cf3620567a354c | [
"MIT"
] | null | null | null | // { Driver Code Starts
// Initial template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template in C++
class Solution
{
public:
bool isValid(int a[], int n, int m, int k){
int sum=0,total=0;
int i=0;
while(i<n){
if(a[i]>k)return false;
if(sum+a[i]>k){
total++;
// if(total>m)return false;
sum=a[i];
}
else sum+=a[i];
i++;
}
total++;
// cout<<"______"<<k<<" "<<total<<endl;
if(total>m)return false;
return true;
}
int maxint(int a[], int n){
int maxi=a[0];
for(int i=0;i<n;i++)maxi=max(maxi,a[i]);
return maxi;
}
//Function to find minimum number of pages.
int findPages(int A[], int N, int M)
{
//code here
if(N<M)return -1;
if(N==M)return maxint(A, N);
int start=A[N-1],end=0;
for(int i=0;i<N;i++)end+=A[i];
int res=-1;
while(start<=end){
// cout<<"h"<<start<<" "<<end<<endl;
int mid = start + (end-start)/2;
if(isValid(A, N, M, mid)){
res=mid;
end=mid-1;
}
else start=mid+1;
}
return res;
}
};
// { Driver Code Starts.
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int A[n];
for(int i=0;i<n;i++){
cin>>A[i];
}
int m;
cin>>m;
Solution ob;
cout << ob.findPages(A, n, m) << endl;
}
return 0;
}
// } Driver Code Ends | 19.258824 | 48 | 0.435553 | atpk |
52b00100248ae4696a8454cebd4087b5dc4e8fbf | 925 | cpp | C++ | src/core/loader/internal/AbstractLoaderInternal.cpp | alexbatashev/athena | eafbb1e16ed0b273a63a20128ebd4882829aa2db | [
"MIT"
] | 2 | 2020-07-16T06:42:27.000Z | 2020-07-16T06:42:28.000Z | src/core/loader/internal/AbstractLoaderInternal.cpp | PolarAI/polarai-framework | c5fd886732afe787a06ebf6fb05fc38069257457 | [
"MIT"
] | null | null | null | src/core/loader/internal/AbstractLoaderInternal.cpp | PolarAI/polarai-framework | c5fd886732afe787a06ebf6fb05fc38069257457 | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
// Copyright (c) 2020 PolarAI. All rights reserved.
//
// Licensed under MIT license.
//
// 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 <polarai/core/loader/internal/AbstractLoaderInternal.hpp>
namespace polarai::core::internal {
AbstractLoaderInternal::AbstractLoaderInternal(
utils::WeakPtr<ContextInternal> context, utils::Index publicIndex,
utils::String name)
: Entity(std::move(context), publicIndex, std::move(name)) {}
} // namespace polarai::core::internal
| 44.047619 | 80 | 0.629189 | alexbatashev |
52b0d4b4284f3565532ef9c76599df007167424f | 1,306 | cpp | C++ | src/systems/RenderSystem.cpp | TheoVerhelst/Aphelion | 357df0ba5542ce22dcff10c434aa4a20da0c1b17 | [
"Beerware"
] | 8 | 2022-01-18T09:58:21.000Z | 2022-02-21T00:08:58.000Z | src/systems/RenderSystem.cpp | TheoVerhelst/Aphelion | 357df0ba5542ce22dcff10c434aa4a20da0c1b17 | [
"Beerware"
] | null | null | null | src/systems/RenderSystem.cpp | TheoVerhelst/Aphelion | 357df0ba5542ce22dcff10c434aa4a20da0c1b17 | [
"Beerware"
] | null | null | null | #include <SFML/System/Time.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <systems/RenderSystem.hpp>
#include <components/Body.hpp>
#include <components/components.hpp>
#include <components/Animations.hpp>
#include <vector.hpp>
RenderSystem::RenderSystem(Scene& scene):
_scene{scene} {
}
void RenderSystem::draw(sf::RenderTarget& target, sf::RenderStates states) const {
for (auto& [id, sprite] : _scene.view<Sprite>()) {
target.draw(sprite.sprite, states);
}
for (auto& [id, animations] : _scene.view<Animations>()) {
for (auto& [action, animationData] : animations) {
if (not animationData.animation.isStopped()) {
target.draw(animationData.animation.getSprite(), states);
}
}
}
}
void RenderSystem::update() {
for (auto& [id, body, sprite] : _scene.view<Body, Sprite>()) {
sprite.sprite.setPosition(body.position);
sprite.sprite.setRotation(radToDeg(body.rotation));
}
for (auto& [id, body, animations] : _scene.view<Body, Animations>()) {
for (auto& [action, animationData] : animations) {
animationData.animation.getSprite().setPosition(body.position);
animationData.animation.getSprite().setRotation(radToDeg(body.rotation));
}
}
}
| 34.368421 | 85 | 0.652374 | TheoVerhelst |
52b50a908db902afa0e13d51d584d664204d4995 | 1,371 | hpp | C++ | include/Buffer2OS2.hpp | notwa/crap | fe81ca33f7940a98321d9efce5bc43f400016955 | [
"MIT"
] | 1 | 2017-11-27T00:03:28.000Z | 2017-11-27T00:03:28.000Z | include/Buffer2OS2.hpp | notwa/crap | fe81ca33f7940a98321d9efce5bc43f400016955 | [
"MIT"
] | null | null | null | include/Buffer2OS2.hpp | notwa/crap | fe81ca33f7940a98321d9efce5bc43f400016955 | [
"MIT"
] | null | null | null | template<class Mixin>
struct Buffer2OS2 : public Mixin {
virtual void
process2(v2df *buf, ulong rem) = 0;
halfband_t<v2df> hb_up, hb_down;
TEMPLATE void
_process(T *in_L, T *in_R, T *out_L, T *out_R, ulong count)
{
disable_denormals();
v2df buf[BLOCK_SIZE];
v2df over[FULL_SIZE];
for (ulong pos = 0; pos < count; pos += BLOCK_SIZE) {
ulong rem = BLOCK_SIZE;
if (pos + BLOCK_SIZE > count)
rem = count - pos;
ulong rem2 = rem*OVERSAMPLING;
for (ulong i = 0; i < rem; i++) {
buf[i][0] = in_L[i];
buf[i][1] = in_R[i];
}
for (ulong i = 0; i < rem; i++) {
over[i*2+0] = interpolate_a(&hb_up, buf[i]);
over[i*2+1] = interpolate_b(&hb_up, buf[i]);
}
process2(over, rem2);
for (ulong i = 0; i < rem; i++) {
decimate_a(&hb_down, over[i*2+0]);
buf[i] = decimate_b(&hb_down, over[i*2+1]);
}
for (ulong i = 0; i < rem; i++) {
out_L[i] = (T)buf[i][0];
out_R[i] = (T)buf[i][1];
}
in_L += BLOCK_SIZE;
in_R += BLOCK_SIZE;
out_L += BLOCK_SIZE;
out_R += BLOCK_SIZE;
}
}
void
process(
double *in_L, double *in_R,
double *out_L, double *out_R,
ulong count)
{
_process(in_L, in_R, out_L, out_R, count);
}
void
process(
float *in_L, float *in_R,
float *out_L, float *out_R,
ulong count)
{
_process(in_L, in_R, out_L, out_R, count);
}
};
| 19.869565 | 60 | 0.574034 | notwa |
52b64135199edef65d9c32051761db1a2092f890 | 2,225 | cpp | C++ | mrstelephonedigits/mrstelephonedigits/mrstelephonedigits.cpp | msalazar266/ITSE-1307 | e224f535e2b2537833241df90877c1d9669db108 | [
"MIT"
] | 1 | 2019-09-11T04:55:06.000Z | 2019-09-11T04:55:06.000Z | mrstelephonedigits/mrstelephonedigits/mrstelephonedigits.cpp | msalazar266/ITSE-1307 | e224f535e2b2537833241df90877c1d9669db108 | [
"MIT"
] | null | null | null | mrstelephonedigits/mrstelephonedigits/mrstelephonedigits.cpp | msalazar266/ITSE-1307 | e224f535e2b2537833241df90877c1d9669db108 | [
"MIT"
] | null | null | null | // mrstelephonedigits.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
/*
Matthew Salazar
ITSE - 1307 Spring 2019
20190402
This program outputs telephone digits that correspond to uppercase letters.
Pseudo Code :
1. User inputs numbers and or letters
2. if(a, b, or c), cout << "2"....etc.
3. if invalid character input, cout << "Invalid character"
*/
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string strInput = "";
char chrLetter = ' ';
cout << "This program outputs telephone digits that correspond to uppercase letters.\n" << endl;
cout << "Please input something(letters and/or digits): ";
cin >> strInput; //User inputs something
cout << endl << endl;
cout << strInput << " is ";
for (unsigned int intLetter = 0; intLetter < strInput.length(); intLetter++) { // Checks each char
chrLetter = strInput.at(intLetter);
chrLetter = tolower(chrLetter);
switch (chrLetter) { //The corresponding digits is chosen
case '1': //User input 1
cout << "1";
break;
case '2': case 'a': case 'b': case 'c': //User input2, a, b, or c
cout << "2";
break;
case '3': case 'd': case 'e': case 'f': //User input 3, d, e, or f
cout << "3";
break;
case '4': case 'g': case 'h': case 'i': //User input 4, g, h, or i
cout << "4";
break;
case '5': case 'j': case 'k': case 'l': //User input 5, j, k, or l
cout << "5";
break;
case '6': case 'm': case 'n': case 'o': //User input 6, m, n, or o
cout << "6";
break;
case '7': case 'p': case 'q': case 'r': case 's': //User input 7, p, q, r, or s
cout << "7";
break;
case '8': case 't': case 'u': case 'v': //User input 8, t, u, or v
cout << "8";
break;
case '9': case 'w': case 'x': case 'y': case 'z': //User input 9, w, x, y, or z
cout << "9";
break;
case '0': //User input 0
cout << "0";
break;
default: //User input an invalid character
cout << ". ERROR: Invalid Character(s) " << "'" << strInput.at(intLetter) << "'" << ", " << endl;
cout << endl << endl;
}
}
}
| 25.872093 | 109 | 0.556404 | msalazar266 |
52ba60d470e838a0e432ca87c80b74b7bb598e68 | 9,226 | cpp | C++ | inetsrv/msmq/src/trigger/trigserv/tginit.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/msmq/src/trigger/trigserv/tginit.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/msmq/src/trigger/trigserv/tginit.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1995-97 Microsoft Corporation
Module Name:
TgInit.cpp
Abstract:
Trigger service initialization
Author:
Uri Habusha (urih) 3-Aug-2000
Environment:
Platform-independent
--*/
#include "stdafx.h"
#include "mq.h"
#include "Ev.h"
#include "Cm.h"
#include "mqsymbls.h"
#include "Svc.h"
#include "monitorp.hpp"
#include "queueutil.hpp"
#include "Tgp.h"
#include "privque.h"
#include "compl.h"
#include <autorel2.h>
#include "tginit.tmh"
//*******************************************************************
//
// Method : ValidateTriggerStore
//
// Description :
//
//*******************************************************************
static
void
ValidateTriggerStore(
IMSMQTriggersConfigPtr pITriggersConfig
)
{
pITriggersConfig->GetInitialThreads();
pITriggersConfig->GetMaxThreads();
_bstr_t bstrTemp = pITriggersConfig->GetTriggerStoreMachineName();
}
void ValidateTriggerNotificationQueue(void)
/*++
Routine Description:
The routine validates existing of notification queue. If the queue doesn't
exist, the routine creates it.
Arguments:
None
Returned Value:
None
Note:
If the queue can't opened for receive or it cannot be created, the
routine throw an exception
--*/
{
_bstr_t bstrFormatName;
_bstr_t bstrNotificationsQueue = _bstr_t(L".\\private$\\") + _bstr_t(TRIGGERS_QUEUE_NAME);
QUEUEHANDLE hQ = NULL;
HRESULT hr = OpenQueue(
bstrNotificationsQueue,
MQ_RECEIVE_ACCESS,
false,
&hQ,
&bstrFormatName
);
if(FAILED(hr))
{
TrERROR(GENERAL, "Failed to open trigger notification queue. Error 0x%x", hr);
WCHAR strError[256];
swprintf(strError, L"0x%x", hr);
EvReport(MSMQ_TRIGGER_OPEN_NOTIFICATION_QUEUE_FAILED, 1, strError);
throw bad_hresult(hr);
}
MQCloseQueue(hQ);
}
static
bool
IsInteractiveService(
SC_HANDLE hService
)
/*++
Routine Description:
Checks if the "Interactive with desktop" checkbox is set.
Arguments:
handle to service
Returned Value:
is interactive
--*/
{
P<QUERY_SERVICE_CONFIG> ServiceConfig = new QUERY_SERVICE_CONFIG;
DWORD Size = sizeof(QUERY_SERVICE_CONFIG);
DWORD BytesNeeded = 0;
memset(ServiceConfig, 0, Size);
BOOL fSuccess = QueryServiceConfig(hService, ServiceConfig, Size, &BytesNeeded);
if (!fSuccess)
{
DWORD gle = GetLastError();
if (gle == ERROR_INSUFFICIENT_BUFFER)
{
ServiceConfig.free();
ServiceConfig = reinterpret_cast<LPQUERY_SERVICE_CONFIG>(new BYTE[BytesNeeded]);
memset(ServiceConfig, 0, BytesNeeded);
Size = BytesNeeded;
fSuccess = QueryServiceConfig(hService, ServiceConfig, Size, &BytesNeeded);
}
}
if (!fSuccess)
{
//
// Could not verify if the service is inetractive. Assume it's not. If it is,
// ChangeServiceConfig will fail since network service cannot be interactive.
//
DWORD gle = GetLastError();
TrERROR(GENERAL, "QueryServiceConfig failed. Error: %!winerr!", gle);
return false;
}
return((ServiceConfig->dwServiceType & SERVICE_INTERACTIVE_PROCESS) == SERVICE_INTERACTIVE_PROCESS);
}
VOID
ChangeToNetworkServiceIfNeeded(
VOID
)
/*++
Routine Description:
Change the triggers logon account to network service if reg key is set.
Arguments:
None
Returned Value:
None
--*/
{
DWORD dwShouldChange;
RegEntry regEntry(
REGKEY_TRIGGER_PARAMETERS,
CONFIG_PARM_NAME_CHANGE_TO_NETWORK_SERVICE,
CONFIG_PARM_DFLT_NETWORK_SERVICE,
RegEntry::Optional,
HKEY_LOCAL_MACHINE
);
CmQueryValue(regEntry, &dwShouldChange);
if (dwShouldChange == CONFIG_PARM_DFLT_NETWORK_SERVICE)
{
TrTRACE(GENERAL, "Don't need to change triggers service account");
return;
}
//
// We should change the service account to network service. This will be effective
// only after restarting the service.
//
CServiceHandle hServiceCtrlMgr(OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS));
if (hServiceCtrlMgr == NULL)
{
DWORD gle = GetLastError();
TrERROR(GENERAL, "OpenSCManager failed. Error: %!winerr!. Not changing to network service", gle);
return;
}
CServiceHandle hService(OpenService(
hServiceCtrlMgr,
xDefaultTriggersServiceName,
SERVICE_CHANGE_CONFIG | SERVICE_QUERY_CONFIG));
if (hService == NULL)
{
DWORD gle = GetLastError();
TrERROR(GENERAL, "OpenService failed with error: %!winerr!. Not changing to network service", gle);
return;
}
if (IsInteractiveService(hService))
{
//
// A network service cannot be interactive with desktop. We don't want to break users that
// set this checkbox so we just warn in the eventlog that triggers service can't be changed
// to network service as long as the interactive option is set.
//
EvReport(EVENT_WARN_TRIGGER_ACCOUNT_CANNOT_BE_CHANGED);
return;
}
if (!ChangeServiceConfig(
hService,
SERVICE_NO_CHANGE,
SERVICE_NO_CHANGE,
SERVICE_NO_CHANGE,
NULL,
NULL,
NULL,
NULL,
L"NT AUTHORITY\\NetworkService",
L"",
NULL
))
{
DWORD gle = GetLastError();
TrERROR(GENERAL, "ChangeServiceConfig failed. Error: %!winerr!. Not changing to network service", gle);
return;
}
TrTRACE(GENERAL, "Service account changed to NetworkService");
EvReport(EVENT_INFO_TRIGGER_ACCOUNT_CHANGED);
CmSetValue(regEntry, CONFIG_PARM_DFLT_NETWORK_SERVICE);
}
CTriggerMonitorPool*
TriggerInitialize(
LPCTSTR pwzServiceName
)
/*++
Routine Description:
Initializes Trigger service
Arguments:
None
Returned Value:
pointer to trigger monitor pool.
--*/
{
//
// Report a 'Pending' progress to SCM.
//
SvcReportProgress(xMaxTimeToNextReport);
//
// Create the instance of the MSMQ Trigger COM component.
//
IMSMQTriggersConfigPtr pITriggersConfig;
HRESULT hr = pITriggersConfig.CreateInstance(__uuidof(MSMQTriggersConfig));
if FAILED(hr)
{
TrERROR(GENERAL, "Trigger start-up failed. Can't create an instance of the MSMQ Trigger Configuration component, Error 0x%x", hr);
throw bad_hresult(hr);
}
//
// If we have create the configuration COM component OK - we will now verify that
// the required registry definitions and queues are in place. Note that these calls
// will result in the appropraite reg-keys & queues being created if they are absent,
// the validation routine can throw _com_error. It will be catch in the caller
//
ValidateTriggerStore(pITriggersConfig);
SvcReportProgress(xMaxTimeToNextReport);
ValidateTriggerNotificationQueue();
SvcReportProgress(xMaxTimeToNextReport);
hr = RegisterComponentInComPlusIfNeeded(TRUE);
if (FAILED(hr))
{
TrERROR(GENERAL, "RegisterComponentInComPlusIfNeeded failed. Error: %!hresult!", hr);
WCHAR errorVal[128];
swprintf(errorVal, L"0x%x", hr);
EvReport(MSMQ_TRIGGER_COMPLUS_REGISTRATION_FAILED, 1, errorVal);
throw bad_hresult(hr);
}
SvcReportProgress(xMaxTimeToNextReport);
ChangeToNetworkServiceIfNeeded();
//
// Attempt to allocate a new trigger monitor pool
//
R<CTriggerMonitorPool> pTriggerMonitorPool = new CTriggerMonitorPool(
pITriggersConfig,
pwzServiceName);
//
// Initialise and start the pool of trigger monitors
//
bool fResumed = pTriggerMonitorPool->Resume();
if (!fResumed)
{
//
// Could not resume the thread. Stop the service.
//
TrERROR(GENERAL, "Resuming thread failed");
throw exception();
}
//
// The thread we created is using the pTriggerMonitorPool. After the new CTriggerMonitorPool thread is resumed, it is using
// this parameter and executing methods from this class. When it terminates it decrements the ref count.
//
pTriggerMonitorPool->AddRef();
try
{
//
// Block until initialization is complete
//
long timeOut = pITriggersConfig->InitTimeout;
SvcReportProgress(numeric_cast<DWORD>(timeOut));
if (! pTriggerMonitorPool->WaitForInitToComplete(timeOut))
{
//
// Initialization timeout. Stop the service.
//
TrERROR(GENERAL, "The MSMQTriggerService has failed to initialize the pool of trigger monitors. The service is being shutdown. No trigger processing will occur.");
throw exception();
}
if (!pTriggerMonitorPool->IsInitialized())
{
//
// Initilization failed. Stop the service
//
TrERROR(GENERAL, "Initilization failed. Stop the service");
throw exception();
}
EvReport(MSMQ_TRIGGER_INITIALIZED);
return pTriggerMonitorPool.detach();
}
catch(const exception&)
{
ASSERT(pTriggerMonitorPool.get() != NULL);
pTriggerMonitorPool->ShutdownThreadPool();
throw;
}
}
| 25.070652 | 173 | 0.658032 | npocmaka |
1ebefb266df852d2d45b7385b6198ba91e7d9983 | 254 | cpp | C++ | part1/1-2/inputoutput.cpp | seopbo/cpp101 | c23cfd6a131723404fe5659df709887817f54223 | [
"MIT"
] | null | null | null | part1/1-2/inputoutput.cpp | seopbo/cpp101 | c23cfd6a131723404fe5659df709887817f54223 | [
"MIT"
] | null | null | null | part1/1-2/inputoutput.cpp | seopbo/cpp101 | c23cfd6a131723404fe5659df709887817f54223 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main() {
int numOfWatermelon = 0;
cout << "How many watermelons do you have?" << endl;
cin >> numOfWatermelon;
cout << "I have " << numOfWatermelon << endl;
return 0;
}
| 19.538462 | 56 | 0.625984 | seopbo |
1ec13ce474f44a4f39295fdf3ddc6bec91cd769a | 4,746 | hh | C++ | AssocTools/AstSTLKeyMap.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | AssocTools/AstSTLKeyMap.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | AssocTools/AstSTLKeyMap.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | #ifndef ASTSTLKEYMAP_HH
#define ASTSTLKEYMAP_HH
//----------------------------------------------------------------
// File and Version Information:
// $Id: AstSTLKeyMap.hh 436 2010-01-13 16:51:56Z stroili $
//
// Description:
// one-directional association map ofbetween two data types.
// the operator [] returns a std::vector<T*>
// of the second data type. Based on AstMap, this stores the
// first data type by VALUE, not by pointer.
//
// User must provide a hashing function which takes a T1 and
// returns an unsigned (this may be a static member function
// or a global function).
//
// usage:
// T1 t1; T2* t2;
// static unsigned t1hash(const T1& aT1);
// IfrMap<T1, T2> map(&t1hash);
//
// // appends the asociation (t1, t2)
// map[t1].append(t2);
//
// // returns a vector of objects associated to t1
// std::vector<T2*> v1 = map[t1];
//
// // checks for the asociation (t1, t2)
// bool associated map[t1].contains(t2);
//
//
// Author List:
// Michael Kelsey <kelsey@slac.stanford.edu>
//
// Copyright (C) 2000 Princeton University
//
//---------------------------------------------------------------
//-------------
// C Headers --
//-------------
//---------------
// C++ Headers --
//---------------
#include <vector>
#include <set>
#include <map>
//----------------------
// Base Class Headers --
//----------------------
#include "AbsEvent/AbsEvtObj.hh"
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
//------------------------------------
// Collaborating Class Declarations --
//------------------------------------
// ---------------------
// -- Class Interface --
// ---------------------
template<class T1, class T2>
class AstSTLKeyMap :
public AbsEvtObj,
public std::map<T1, std::vector<T2*> >
{
public:
// NOTE: Unlike AstMap, the user _must_ provide a hashing function
AstSTLKeyMap(unsigned (*hashFunction)(const T1 &), size_t buckets=50);
virtual ~AstSTLKeyMap();
// Return a list of all T2
const std::vector<T2*> & allType2() const;
// This is the same as RW's insertKeyAndValue,
// but keeps a track of the T1s. There is nothing to stop
// users calling the original function, but no set
// operations will be possible thereafter.
void append(const T1&, T2* const&);
// Given a set of T1, return all associated T2. No check is made on the
// returned vector - if of non-zero length, items are simply appended.
// Returns false if no matches are found
bool findIntersectionSet(const std::set<T1> &, std::vector<T2*> &returned) const;
// As above but copies the intersection of the given HashSet and the known
// table into the final argument.
bool findIntersectionSet(const std::set<T1> &,
std::vector<T2*> &returned,
std::set<T1> &returnedSet) const;
// As above but saves user having to think about hash functions. Slower, as
// it has to copy the vector into a hash set first.
bool findIntersectionSet(const std::vector<T1> &,
std::vector<T2*> &returned) const;
// Given a set of T1, return all T2 for which no T1 in the given set exists.
// No check is made on the
// returned vector - if of non-zero length, items are simply appended.
// Returns false if no matches are found
bool findDifferenceSet(const std::set<T1> &,
std::vector<T2*> &returned) const;
// As above but copies the intersection of the given HashSet and the known
// table into the final argument.
bool findDifferenceSet(const std::set<T1> &,
std::vector<T2*> &returned,
std::set<T1> &) const;
// As above but saves user having to think about hash functions. Slower, as
// it has to copy the vector into a hash set first.
bool findDifferenceSet(const std::vector<T1> &,
std::vector<T2*> &returned) const;
// Compute the union with another map, modifying & returning self.
// Note that this is a union with the T1 type ONLY. No comparison
// is made with the associated (vector of) T2. Maybe one day I'll get
// around to writing one of those.
AstSTLKeyMap<T1, T2> &unionMap(const AstSTLKeyMap<T1, T2> &);
// Compute the union with another map, modifying & returningself.
AstSTLKeyMap<T1, T2> &intersectionMap(const AstSTLKeyMap<T1, T2> &);
private:
unsigned (*_myHashFunction)(const T1&);
std::vector<T2*> *_allT2;
std::set<T1> *_hashSetT1;
};
//--------------------
// Member functions --
//--------------------
//---------------
// Constructor --
//---------------
#ifdef BABAR_COMP_INST
#include "AssocTools/AstSTLKeyMap.icc"
#endif // BABAR_COMP_INST
#endif // ASTSTLKEYMAP_HH
| 31.223684 | 83 | 0.59271 | brownd1978 |
1ec2fbaca2371284f2ebc1edd5e492bee3a1717d | 5,517 | cpp | C++ | DNLS/cpu-implementation/DNLS.cpp | pisto/nlchains | 6e94b7a1dcacdd6fccb2b9e862bc648c1b263286 | [
"MIT"
] | 1 | 2019-06-25T01:09:19.000Z | 2019-06-25T01:09:19.000Z | DNLS/cpu-implementation/DNLS.cpp | pisto/nlchains | 6e94b7a1dcacdd6fccb2b9e862bc648c1b263286 | [
"MIT"
] | null | null | null | DNLS/cpu-implementation/DNLS.cpp | pisto/nlchains | 6e94b7a1dcacdd6fccb2b9e862bc648c1b263286 | [
"MIT"
] | null | null | null | #include <cmath>
#include <vector>
#include <fftw3.h>
#include "../../common/utilities.hpp"
#include "../../common/configuration.hpp"
#include "../../common/results.hpp"
#include "../../common/symplectic.hpp"
#include "../../common/loop_control.hpp"
#include "../../common/wisdom_sync.hpp"
#include "../DNLS.hpp"
using namespace std;
namespace DNLS {
namespace cpu {
namespace {
//XXX this is necessary because std::complex doesn't compile to SIMD
[[gnu::always_inline]] void split_complex_mul(double &r1, double &i1, double r2, double i2) {
double r3 = r1 * r2 - i1 * i2, i3 = i2 * r1 + i1 * r2;
r1 = r3, i1 = i3;
}
}
make_simd_clones("default,avx,avx512f")
int main(int argc, char *argv[]) {
double beta;
wisdom_sync wsync;
{
using namespace boost::program_options;
parse_cmdline parser("Options for "s + argv[0]);
parser.options.add_options()("beta", value(&beta)->required(), "fourth order nonlinearity");
wsync.add_options(parser.options);
parser.run(argc, argv);
}
auto omega = dispersion();
vector<complex<double>, simd_allocator<complex<double>>> evolve_linear_tables[7];
{
auto linear_tables_unaligned = DNLS::evolve_linear_table();
loopi(7) evolve_linear_tables[i].assign(linear_tables_unaligned[i].begin(),
linear_tables_unaligned[i].end());
}
vector<double> beta_dt_symplectic(8);
loopk(8) beta_dt_symplectic[k] = beta * gconf.dt * (k == 7 ? 2. : 1.) * symplectic_c[k];
results res(true);
vector<double, simd_allocator<double>> psi_r_buff(gconf.chain_length), psi_i_buff(gconf.chain_length);
double *__restrict__ psi_r = psi_r_buff.data();
double *__restrict__ psi_i = psi_i_buff.data();
BOOST_ALIGN_ASSUME_ALIGNED(psi_r, 64);
BOOST_ALIGN_ASSUME_ALIGNED(psi_i, 64);
destructor(fftw_cleanup);
wsync.gather();
fftw_iodim fft_dim{ gconf.chain_length, 1, 1 };
auto fft = fftw_plan_guru_split_dft(1, &fft_dim, 0, 0, psi_r, psi_i, psi_r, psi_i, FFTW_EXHAUSTIVE | wsync.fftw_flags);
//XXX fftw_execute_split_dft(fft, psi_i, psi_r, psi_i, psi_r) should do an inverse transform but it returns garbage
auto fft_back = fftw_plan_guru_split_dft(1, &fft_dim, 0, 0, psi_i, psi_r, psi_i, psi_r, FFTW_EXHAUSTIVE | wsync.fftw_flags);
destructor([=] { fftw_destroy_plan(fft); fftw_destroy_plan(fft_back); });
if (!fft || !fft_back) throw runtime_error("Cannot create FFTW3 plan");
wsync.scatter();
auto accumulate_linenergies = [&](size_t c) {
auto planar = &gres.shard_host[c * gconf.chain_length];
loopi(gconf.chain_length) psi_r[i] = planar[i].x, psi_i[i] = planar[i].y;
fftw_execute(fft);
loopi(gconf.chain_length) gres.linenergies_host[i] += psi_r[i] * psi_r[i] + psi_i[i] * psi_i[i];
};
//loop expects linenergies to be accumulated during move phase
loopi(gconf.shard_copies) accumulate_linenergies(i);
auto evolve_nonlinear = [&](double beta_dt_symplectic)[[gnu::always_inline]]{
openmp_simd
for (uint16_t i = 0; i < gconf.chain_length; i++) {
auto norm = psi_r[i] * psi_r[i] + psi_i[i] * psi_i[i];
double exp_r, exp_i, angle = -beta_dt_symplectic * norm;
#if 0
//XXX sincos is not being vectorized by GCC as of version 8.3, I don't know why
sincos(angle, &exp_i, &exp_r);
#else
//best-effort workaround
exp_r = cos(angle); //vectorized
#if 0
//naive
exp_i = sin(angle); //vectorized
#else
//This appears faster because of the sqrt opcode
exp_i = sqrt(1 - exp_r * exp_r); //vectorized (native VSQRTPD), exp_i = abs(sin(angle))
//branchless sign fix
auto invert_sign = int32_t(angle / M_PI) & 1; //0 -> even half-circles, 1 -> odd half-circles
exp_i *= (1. - 2. * invert_sign) * copysign(1., angle);
#endif
#endif
split_complex_mul(psi_r[i], psi_i[i], exp_r, exp_i);
}
};
loop_control loop_ctl;
while (1) {
loopi(gconf.chain_length) gres.linenergies_host[i] *= omega[i];
res.calc_linenergies(1. / gconf.shard_elements).calc_entropies().check_entropy().write_entropy(loop_ctl);
if (loop_ctl % gconf.dump_interval == 0) res.write_linenergies(loop_ctl).write_shard(loop_ctl);
if (loop_ctl.break_now()) break;
loopi(gconf.chain_length) gres.linenergies_host[i] = 0;
for (int c = 0; c < gconf.shard_copies; c++) {
auto planar = &gres.shard_host[c * gconf.chain_length];
loopi(gconf.chain_length) psi_r[i] = planar[i].x, psi_i[i] = planar[i].y;
for (uint32_t i = 0; i < gconf.kernel_batching; i++)
for (int k = 0; k < 7; k++) {
evolve_nonlinear(beta * gconf.dt * (!k && i ? 2. : 1.) * symplectic_c[k]);
fftw_execute(fft);
complex<double> * __restrict__ table = evolve_linear_tables[k].data();
BOOST_ALIGN_ASSUME_ALIGNED(table, 64);
openmp_simd
for (uint16_t i = 0; i < gconf.chain_length; i++)
split_complex_mul(psi_r[i], psi_i[i], table[i].real(), table[i].imag());
fftw_execute(fft_back);
}
evolve_nonlinear(beta * gconf.dt * symplectic_c[7]);
loopi(gconf.chain_length) planar[i] = { psi_r[i], psi_i[i] };
accumulate_linenergies(c);
}
loop_ctl += gconf.kernel_batching;
}
if (loop_ctl % gconf.dump_interval != 0) res.write_linenergies(loop_ctl).write_shard(loop_ctl);
return 0;
}
}
}
ginit = [] {
::programs()["DNLS-cpu"] = DNLS::cpu::main;
};
| 38.3125 | 127 | 0.649085 | pisto |
1ec3a8617265c163a3f252b88e8e6b6eaba4c3f3 | 79 | cpp | C++ | Tests/DigitTest.cpp | Bow0628/Qentem-Engine | 9d16acfaa4b9c8822edbb5903aa3e90cce1b0cd0 | [
"MIT"
] | 2 | 2021-07-03T06:26:42.000Z | 2021-08-16T12:22:22.000Z | Tests/DigitTest.cpp | fahad512/Qentem-Engine | 95090ea13058a2d3006c564c26d1f9474a1071c5 | [
"MIT"
] | null | null | null | Tests/DigitTest.cpp | fahad512/Qentem-Engine | 95090ea13058a2d3006c564c26d1f9474a1071c5 | [
"MIT"
] | null | null | null | #include "DigitTest.hpp"
int main() { return Qentem::Test::RunDigitTests(); }
| 19.75 | 52 | 0.696203 | Bow0628 |
1ec3dec06f90df9e2cc7d44b30a598fda650e931 | 3,644 | cpp | C++ | src/maiken/pack.cpp | Dekken/maiken | 57151345be77aa1ed9860f54908ded70ff6d8f55 | [
"BSD-3-Clause"
] | 61 | 2015-02-05T07:43:13.000Z | 2020-05-19T13:26:50.000Z | src/maiken/pack.cpp | Dekken/maiken | 57151345be77aa1ed9860f54908ded70ff6d8f55 | [
"BSD-3-Clause"
] | 29 | 2016-11-21T03:37:42.000Z | 2020-10-18T12:04:53.000Z | src/maiken/pack.cpp | Dekken/maiken | 57151345be77aa1ed9860f54908ded70ff6d8f55 | [
"BSD-3-Clause"
] | 12 | 2016-01-05T05:35:29.000Z | 2020-03-15T11:03:37.000Z | /**
Copyright (c) 2022, Philip Deegan.
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 Philip Deegan 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 "mkn/kul/string.hpp"
#include "maiken.hpp"
class LibFinder {
public:
static bool findAdd(std::string const& l, const mkn::kul::Dir& i, const mkn::kul::Dir& o) {
bool found = 0;
for (auto const& f : i.files(0)) {
auto const& fn(f.name());
if (fn.find(".") == std::string::npos) continue;
#ifdef _WIN32
if (fn.substr(0, fn.rfind(".")) == l) {
#else
if (fn.size() > (3 + l.size()) && fn.substr(0, 3) == "lib" &&
mkn::kul::String::NO_CASE_CMP(fn.substr(3, l.size()), l)) {
auto bits(mkn::kul::String::SPLIT(fn.substr(3 + l.size()), '.'));
#ifdef __APPLE__
if (bits[bits.size() - 1] != "dyn"
#else
if (!(bits[0] == "so" || bits[bits.size() - 1] == "so")
#endif //__APPLE__
&& bits[bits.size() - 1] != "a")
continue;
#endif //_WIN32
f.cp(o);
found = 1;
}
}
return found;
}
};
void maiken::Application::pack() KTHROW(mkn::kul::Exception) {
mkn::kul::Dir pk(buildDir().join("pack"));
if (!pk && !pk.mk()) KEXIT(1, "Cannot create: " + pk.path());
mkn::kul::Dir bin(pk.join("bin"), main_.has_value());
mkn::kul::Dir lib(pk.join("lib"));
if (main_ || !srcs.empty()) {
auto const v((inst ? inst : buildDir()).files(0));
if (v.empty()) KEXIT(1, "Current project lib/bin not found during pack");
for (auto const& f : v) f.cp(main_ ? bin : lib);
}
for (auto app = this->deps.rbegin(); app != this->deps.rend(); ++app)
if (!(*app)->srcs.empty()) {
auto& a = **app;
mkn::kul::Dir outD(a.inst ? a.inst.real() : a.buildDir());
std::string n = a.project().root()[STR_NAME].Scalar();
if (!LibFinder::findAdd(a.baseLibFilename(), outD, lib))
KEXIT(1, "Depedency Project lib not found, try building: ") << a.buildDir().real();
}
for (auto const& l : libs) {
bool found = 0;
for (auto const& p : paths) {
mkn::kul::Dir path(p);
if (!path) KEXIT(1, "Path does not exist: ") << pk.path();
found = LibFinder::findAdd(l, path, lib);
if (found) break;
}
if (!found) KOUT(NON) << "WARNING - Library not found during pack: " << l;
}
} | 38.357895 | 93 | 0.649835 | Dekken |
1ec4442b4ef23ec36e1c800acb9858ed777edeaa | 268 | hpp | C++ | src/stc/Optional.hpp | LunarWatcher/stc | 941888c967df2cf5e7c2d1e36edcdee09ed10153 | [
"MIT"
] | null | null | null | src/stc/Optional.hpp | LunarWatcher/stc | 941888c967df2cf5e7c2d1e36edcdee09ed10153 | [
"MIT"
] | null | null | null | src/stc/Optional.hpp | LunarWatcher/stc | 941888c967df2cf5e7c2d1e36edcdee09ed10153 | [
"MIT"
] | null | null | null | #pragma once
#if __has_include(<optional>)
#include <optional>
template <typename T>
using StdOptional = std::optional<T>;
#else
#include <experimental/optional>
template <typename T>
using StdOptional = std::experimental::optional<T>;
#endif
| 22.333333 | 55 | 0.69403 | LunarWatcher |
1eca1e3b0e17ddabf630826e466dd37cfa8ecae8 | 1,712 | cpp | C++ | impl/jamtemplate/common/sound_group.cpp | Laguna1989/JamTemplateCpp | 66f6e547b3702d106d26c29f9eb0e7d052bcbdb5 | [
"CC0-1.0"
] | 6 | 2021-09-05T08:31:36.000Z | 2021-12-09T21:14:37.000Z | impl/jamtemplate/common/sound_group.cpp | Laguna1989/JamTemplateCpp | 66f6e547b3702d106d26c29f9eb0e7d052bcbdb5 | [
"CC0-1.0"
] | 30 | 2021-05-19T15:33:03.000Z | 2022-03-30T19:26:37.000Z | impl/jamtemplate/common/sound_group.cpp | Laguna1989/JamTemplateCpp | 66f6e547b3702d106d26c29f9eb0e7d052bcbdb5 | [
"CC0-1.0"
] | 3 | 2021-05-23T16:06:01.000Z | 2021-10-01T01:17:08.000Z | #include "sound_group.hpp"
#include "random/random.hpp"
#include "sound.hpp"
#include <algorithm>
namespace {
std::shared_ptr<jt::Sound> loadSound(std::string const& filename)
{
auto snd = std::make_shared<jt::Sound>();
snd->load(filename);
return snd;
}
} // namespace
jt::SoundGroup::SoundGroup(std::vector<std::string> const& sounds)
{
for (auto const& f : sounds) {
m_sounds.emplace_back(loadSound(f));
}
m_isInitialized = true;
}
void jt::SoundGroup::doLoad(std::string const& fileName)
{
m_sounds.emplace_back(loadSound(fileName));
}
bool jt::SoundGroup::doIsPlaying() const
{
return std::any_of(m_sounds.cbegin(), m_sounds.cend(),
[](std::shared_ptr<SoundBase> const& snd) { return snd->isPlaying(); });
}
void jt::SoundGroup::doPlay()
{
if (m_sounds.empty()) {
return;
}
std::size_t const index = Random::getInt(0, static_cast<int>(m_sounds.size()) - 1);
m_sounds.at(index)->play();
}
void jt::SoundGroup::doStop()
{
for (auto& snd : m_sounds) {
snd->stop();
}
}
float jt::SoundGroup::doGetVolume() const
{
if (m_sounds.empty()) {
return 0.0f;
}
return m_sounds.at(0)->getVolume();
}
void jt::SoundGroup::doSetVolume(float newVolume)
{
for (auto& snd : m_sounds) {
snd->setVolume(newVolume);
}
}
void jt::SoundGroup::doSetLoop(bool doLoop)
{
for (auto& snd : m_sounds) {
snd->setLoop(doLoop);
}
}
bool jt::SoundGroup::doGetLoop()
{
if (m_sounds.empty()) {
return false;
}
return m_sounds.at(0)->getLoop();
}
float jt::SoundGroup::doGetDuration() const { return 0.0f; }
float jt::SoundGroup::doGetPosition() const { return 0.0f; }
| 20.380952 | 87 | 0.630257 | Laguna1989 |
1ecc97bde4e6e9e2e17ba8a0f1b0dc935d0f7a2f | 57,344 | cxx | C++ | PWG/EMCAL/EMCALtasks/AliAnalysisTaskEmcalTriggerPatchClusterMatch.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWG/EMCAL/EMCALtasks/AliAnalysisTaskEmcalTriggerPatchClusterMatch.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWG/EMCAL/EMCALtasks/AliAnalysisTaskEmcalTriggerPatchClusterMatch.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// 1) Analysis task to identify the cluster that fired the trigger patch
// 2) perform some QA on the patch / cluster
// 3) and pass the saved out collection of cluster(s) to other tasks
//
// currently set up for GA trigger
//
// Author: Joel Mazer (joel.mazer@cern.ch)
//-------------------------------------------------------------------------
// task head include
//#include "AliAnalysisTaskEmcalTriggerPatchClusterMatch.h"
#include <iostream>
// ROOT includes
#include <TClonesArray.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TProfile.h>
#include <THnSparse.h>
#include <TList.h>
#include <TLorentzVector.h>
// event handler (and pico's) includes
#include "AliAnalysisManager.h"
#include <AliInputEventHandler.h>
#include <AliVEventHandler.h>
#include "AliESDInputHandler.h"
#include "AliVCluster.h"
#include "AliVTrack.h"
#include "AliVVZERO.h"
#include "AliLog.h"
#include "AliEmcalParticle.h"
#include "AliAODCaloTrigger.h"
#include "AliEMCALGeometry.h"
#include "AliVCaloCells.h"
#include "AliClusterContainer.h"
#include "AliParticleContainer.h"
#include "AliEMCALTriggerPatchInfo.h"
#include "AliAODHeader.h"
#include "AliPicoTrack.h"
#include "AliAnalysisTaskEmcalTriggerPatchClusterMatch.h"
using std::cout;
using std::endl;
ClassImp(AliAnalysisTaskEmcalTriggerPatchClusterMatch)
//________________________________________________________________________
AliAnalysisTaskEmcalTriggerPatchClusterMatch::AliAnalysisTaskEmcalTriggerPatchClusterMatch() :
AliAnalysisTaskEmcal("AliAnalysisTaskEmcalTriggerPatchClusterMatch", kTRUE),
fDebug(kFALSE), fAttachToEvent(kTRUE),
fTriggerClass(""),
fMaxPatchEnergy(0), fMaxPatchADCEnergy(0),
fTriggerType(1), //-1),
fNFastOR(16),
fMainTrigCat(kTriggerLevel1Jet), // options: kTriggerLevel0, kTriggerLevel1Jet, kTriggerLevel1Gamma, kTriggerRecalcJet, kTriggerRecalGamma
//fMainTrigCat(kTriggerRecalcJet), // Recalculated max trigger patch; does not need to be above trigger threshold
//fMainTrigCat(kTriggerRecalcGamma),// Recalculated max trigger patch; does not need to be above trigger threshold
fTriggerCategory(kTriggerRecalcGamma),
fMainTrigSimple(kFALSE), // (kTRUE)
fPatchECut(10.0),
fTrkBias(0), fClusBias(0),
doComments(0), fUseALLrecalcPatches(0), // defaults to max patch only
fClusterTriggeredEventname("CLUSTERthatTriggeredEvent"),
fMaxPatch(0),
fMainPatchType(kManual), // (kEmcalJet)
fhNEvents(0),
fhTriggerbit(0),
fh3PtEtaPhiTracks(0), fh3PtEtaPhiTracksOnEmcal(0), fh3PtEtaPhiTracksToProp(0), fh3PtEtaPhiTracksProp(0), fh3PtEtaPhiTracksNoProp(0),
fh3EEtaPhiCluster(0),
fh3PatchEnergyEtaPhiCenterJ1(0), fh3PatchEnergyEtaPhiCenterJ2(0), fh3PatchEnergyEtaPhiCenterJ1J2(0),
fh3PatchADCEnergyEtaPhiCenterJ1(0), fh3PatchADCEnergyEtaPhiCenterJ2(0), fh3PatchADCEnergyEtaPhiCenterJ1J2(0),
fh3PatchEnergyEtaPhiCenterG1(0), fh3PatchEnergyEtaPhiCenterG2(0), fh3PatchEnergyEtaPhiCenterG1G2(0),
fh3PatchADCEnergyEtaPhiCenterG1(0), fh3PatchADCEnergyEtaPhiCenterG2(0), fh3PatchADCEnergyEtaPhiCenterG1G2(0),
fh3PatchADCEnergyEtaPhiCenterAll(0),
fh3EEtaPhiCell(0), fh2ECellVsCent(0), fh2CellEnergyVsTime(0), fh3EClusELeadingCellVsTime(0),
fHistClusEnergy(0),
fHistEventSelectionQA(0), fhQAinfoAllPatchesCounter(0), fhQAinfoCounter(0), fhQAmaxinfoCounter(0),
fhRecalcGammaPatchEnergy(0), fhGammaLowPatchEnergy(0), fhGammaLowSimplePatchEnergy(0),
fhRecalcJetPatchEnergy(0), fhJetLowPatchEnergy(0), fhJetLowSimplePatchEnergy(0),
fhMainTriggerPatchEnergy(0),
fClusterTriggeredEvent(0), fRecalcTriggerPatches(0),
fhnPatchMaxClus(0x0), fhnPatchMatch(0x0), fhnPatchMatch2(0x0)
{
// Default constructor.
for(Int_t j=0; j<16; j++) {
fHistdPhidEtaPatchCluster[j] = 0;
}
SetMakeGeneralHistograms(kTRUE);
}
//________________________________________________________________________
AliAnalysisTaskEmcalTriggerPatchClusterMatch::AliAnalysisTaskEmcalTriggerPatchClusterMatch(const char *name) :
AliAnalysisTaskEmcal(name, kTRUE),
fDebug(kFALSE), fAttachToEvent(kTRUE),
fTriggerClass(""),
fMaxPatchEnergy(0), fMaxPatchADCEnergy(0),
fTriggerType(1), //-1),
fNFastOR(16),
fMainTrigCat(kTriggerLevel1Jet), // options: kTriggerLevel0, kTriggerLevel1Jet, kTriggerLevel1Gamma, kTriggerRecalcJet, kTriggerRecalGamma
//fMainTrigCat(kTriggerRecalcJet), // Recalculated max trigger patch; does not need to be above trigger threshold
//fMainTrigCat(kTriggerRecalcGamma),// Recalculated max trigger patch; does not need to be above trigger threshold
fTriggerCategory(kTriggerRecalcGamma),
fMainTrigSimple(kFALSE), // kTRUE
fPatchECut(10.0),
fTrkBias(0), fClusBias(0),
doComments(0), fUseALLrecalcPatches(0), // defaults to max patch only
fClusterTriggeredEventname("CLUSTERthatTriggeredEvent"),
fMaxPatch(0),
fMainPatchType(kManual), //kEmcalJet
fhNEvents(0),
fhTriggerbit(0),
fh3PtEtaPhiTracks(0), fh3PtEtaPhiTracksOnEmcal(0), fh3PtEtaPhiTracksToProp(0), fh3PtEtaPhiTracksProp(0), fh3PtEtaPhiTracksNoProp(0),
fh3EEtaPhiCluster(0),
fh3PatchEnergyEtaPhiCenterJ1(0), fh3PatchEnergyEtaPhiCenterJ2(0), fh3PatchEnergyEtaPhiCenterJ1J2(0),
fh3PatchADCEnergyEtaPhiCenterJ1(0), fh3PatchADCEnergyEtaPhiCenterJ2(0), fh3PatchADCEnergyEtaPhiCenterJ1J2(0),
fh3PatchEnergyEtaPhiCenterG1(0), fh3PatchEnergyEtaPhiCenterG2(0), fh3PatchEnergyEtaPhiCenterG1G2(0),
fh3PatchADCEnergyEtaPhiCenterG1(0), fh3PatchADCEnergyEtaPhiCenterG2(0), fh3PatchADCEnergyEtaPhiCenterG1G2(0),
fh3PatchADCEnergyEtaPhiCenterAll(0),
fh3EEtaPhiCell(0), fh2ECellVsCent(0), fh2CellEnergyVsTime(0), fh3EClusELeadingCellVsTime(0),
fHistClusEnergy(0),
fHistEventSelectionQA(0), fhQAinfoAllPatchesCounter(0), fhQAinfoCounter(0), fhQAmaxinfoCounter(0),
fhRecalcGammaPatchEnergy(0), fhGammaLowPatchEnergy(0), fhGammaLowSimplePatchEnergy(0),
fhRecalcJetPatchEnergy(0), fhJetLowPatchEnergy(0), fhJetLowSimplePatchEnergy(0),
fhMainTriggerPatchEnergy(0),
fClusterTriggeredEvent(0), fRecalcTriggerPatches(0),
fhnPatchMaxClus(0x0), fhnPatchMatch(0x0), fhnPatchMatch2(0x0)
{
// Standard constructor.
for(Int_t j=0; j<16; j++) {
fHistdPhidEtaPatchCluster[j] = 0;
}
SetMakeGeneralHistograms(kTRUE);
}
//________________________________________________________________________
AliAnalysisTaskEmcalTriggerPatchClusterMatch::~AliAnalysisTaskEmcalTriggerPatchClusterMatch()
{
// Destructor.
}
//_____________________________________________________________________________
void AliAnalysisTaskEmcalTriggerPatchClusterMatch::ExecOnce(){
AliAnalysisTaskEmcal::ExecOnce();
// Init the analysis
if(fClusterTriggeredEventname=="") fClusterTriggeredEventname = Form("fClusterTriggeredEventname_%s", GetName());
fClusterTriggeredEvent = new TClonesArray("AliVCluster");
fClusterTriggeredEvent->SetName(fClusterTriggeredEventname);
fClusterTriggeredEvent->SetOwner(kTRUE);
fRecalcTriggerPatches = new TClonesArray("AliEMCALTriggerPatchInfo");
fRecalcTriggerPatches->SetName("RecalcTriggerPatches");
fRecalcTriggerPatches->SetOwner(kTRUE);
// add cluster object (of clustertriggering event) to event if not yet there
if(fAttachToEvent) {
if (InputEvent()->FindListObject(fClusterTriggeredEventname)) {
AliFatal(Form("%s: Container with same name %s already present. Aborting", GetName(), fClusterTriggeredEventname.Data()));
} else {
InputEvent()->AddObject(fClusterTriggeredEvent);
}
}
}
//________________________________________________________________________
Bool_t AliAnalysisTaskEmcalTriggerPatchClusterMatch::SelectEvent() {
// Decide if event should be selected for analysis
fhNEvents->Fill(3.5);
// this section isn't needed for LHC11h
if(!fTriggerClass.IsNull()) {
//Check if requested trigger was fired
TString trigType1 = "J1";
TString trigType2 = "J2";
if(fTriggerClass.Contains("G")) {
trigType1 = "G1";
trigType2 = "G2";
}
// get fired trigger classes
TString firedTrigClass = InputEvent()->GetFiredTriggerClasses();
if(fTriggerClass.Contains(trigType1.Data()) && fTriggerClass.Contains(trigType2.Data())) { //if events with J1&&J2 are requested
if(!firedTrigClass.Contains(trigType1.Data()) || !firedTrigClass.Contains(trigType2.Data()) ) //check if both are fired
return kFALSE;
} else {
if(!firedTrigClass.Contains(fTriggerClass)) return kFALSE;
else if(fTriggerClass.Contains(trigType1.Data()) && firedTrigClass.Contains(trigType2.Data())) //if J2 is requested also add triggers which have J1&&J2. Reject if J1 is requested and J2 is fired
return kFALSE;
}
}
fhNEvents->Fill(1.5);
return kTRUE;
}
//________________________________________________________________________
void AliAnalysisTaskEmcalTriggerPatchClusterMatch::FillTriggerPatchHistos() {
// Fill trigger patch histos for main trigger
if(!fTriggerPatchInfo) {
AliFatal(Form("%s: TriggerPatchInfo object %s does not exist. Aborting", GetName(), fClusterTriggeredEventname.Data()));
return;
}
// see if event was selected
UInt_t trig = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
ExtractMainPatch();
//if(fMainPatchType == kManual) ExtractMainPatch();
// not set up yet for jet patch
//else if(fMainPatchType == kEmcalJet) cout<<"kEmcalJet"<<endl; //fMaxPatch = GetMainTriggerPatch(fMainTrigCat,fMainTrigSimple);
//AliEMCALTriggerPatchInfo *patch = GetMainTriggerPatch(fMainTrigCat,fMainTrigSimple);
fMaxPatchEnergy = 0;
fMaxPatchADCEnergy = 0;
if(fMaxPatch) {
fMaxPatchEnergy = fMaxPatch->GetPatchE();
fMaxPatchADCEnergy = fMaxPatch->GetADCAmpGeVRough();
fh3PatchADCEnergyEtaPhiCenterAll->Fill(fMaxPatchADCEnergy,fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
// the following don't exist for LHC11h data
//Check if requested trigger was fired, relevant for data sets with 2 EMCal trigger thresholds
// JET trigger
if(fMaxPatch->IsJetLow() && !fMaxPatch->IsJetHigh()) { //main patch only fired low threshold trigger
fh3PatchEnergyEtaPhiCenterJ2->Fill(fMaxPatch->GetPatchE(),fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
fh3PatchADCEnergyEtaPhiCenterJ2->Fill(fMaxPatchADCEnergy,fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
}
else if(fMaxPatch->IsJetHigh() && !fMaxPatch->IsJetLow()) { //main patch only fired high threshold trigger - should never happen
fh3PatchEnergyEtaPhiCenterJ1->Fill(fMaxPatch->GetPatchE(),fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
fh3PatchADCEnergyEtaPhiCenterJ1->Fill(fMaxPatchADCEnergy,fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
}
else if(fMaxPatch->IsJetHigh() && fMaxPatch->IsJetLow()) { //main patch fired both triggers
fh3PatchEnergyEtaPhiCenterJ1J2->Fill(fMaxPatch->GetPatchE(),fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
fh3PatchADCEnergyEtaPhiCenterJ1J2->Fill(fMaxPatchADCEnergy,fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
} // JE
// GAMMA trigger
if(fMaxPatch->IsGammaLow() && !fMaxPatch->IsGammaHigh()) { //main patch only fired low threshold trigger
fh3PatchEnergyEtaPhiCenterG2->Fill(fMaxPatch->GetPatchE(),fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
fh3PatchADCEnergyEtaPhiCenterG2->Fill(fMaxPatchADCEnergy,fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
}
else if(fMaxPatch->IsGammaHigh() && !fMaxPatch->IsGammaLow()) { //main patch only fired high threshold trigger - should never happen
fh3PatchEnergyEtaPhiCenterG1->Fill(fMaxPatch->GetPatchE(),fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
fh3PatchADCEnergyEtaPhiCenterG1->Fill(fMaxPatchADCEnergy,fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
}
else if(fMaxPatch->IsGammaHigh() && fMaxPatch->IsGammaLow()) { //main patch fired both triggers
fh3PatchEnergyEtaPhiCenterG1G2->Fill(fMaxPatch->GetPatchE(),fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
fh3PatchADCEnergyEtaPhiCenterG1G2->Fill(fMaxPatchADCEnergy,fMaxPatch->GetEtaGeo(),fMaxPatch->GetPhiGeo());
} // GA
// fill max patch counters
FillTriggerPatchQA(fhQAmaxinfoCounter, trig, fMaxPatch);
} // have patch
}
//_________________________________________________________________________________________
void AliAnalysisTaskEmcalTriggerPatchClusterMatch::ExtractMainPatch() {
//Find main trigger
if(!fTriggerPatchInfo) return;
// reset array of patches to save
fRecalcTriggerPatches->Clear();
//number of patches in event
Int_t nPatch = fTriggerPatchInfo->GetEntriesFast();
//loop over patches to define trigger type of event
Int_t nG1 = 0, nG2 = 0, nJ1 = 0, nJ2 = 0, nL0 = 0;
// see if event was selected
UInt_t trig = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
// check the Fired Trigger Classes
TString firedTrigClass = InputEvent()->GetFiredTriggerClasses();
//extract main trigger patch
AliEMCALTriggerPatchInfo *patch;
Double_t emax = -1.;
for (Int_t iPatch = 0, patchacc = 0; iPatch < nPatch; iPatch++) {
patch = (AliEMCALTriggerPatchInfo*)fTriggerPatchInfo->At( iPatch );
if (!patch) continue;
// count trigger types
if (patch->IsGammaHigh()) nG1++;
if (patch->IsGammaLow()) nG2++;
if (patch->IsJetHigh()) nJ1++;
if (patch->IsJetLow()) nJ2++;
if (patch->IsLevel0()) nL0++;
// fill Energy spectra of recalculated Jet and GA patches
if(patch->IsRecalcGamma()) { fhRecalcGammaPatchEnergy->Fill(patch->GetPatchE()); }
if(patch->IsGammaLow()) { fhGammaLowPatchEnergy->Fill(patch->GetPatchE()); }
if(patch->IsGammaLowSimple()) { fhGammaLowSimplePatchEnergy->Fill(patch->GetPatchE()); }
if(patch->IsRecalcJet()) { fhRecalcJetPatchEnergy->Fill(patch->GetPatchE()); }
if(patch->IsJetLow()) { fhJetLowPatchEnergy->Fill(patch->GetPatchE()); }
if(patch->IsJetLowSimple()) { fhJetLowSimplePatchEnergy->Fill(patch->GetPatchE()); }
if(patch->IsMainTrigger()) { fhMainTriggerPatchEnergy->Fill(patch->GetPatchE()); }
// fill QA counter histo for all 'trig class' patches
FillTriggerPatchQA(fhQAinfoAllPatchesCounter, trig, patch);
// make sure trigger "fTriggerClass" actually was fired in event
if(!firedTrigClass.Contains(fTriggerClass)) continue;
// check that we have a recalculated (OFFLINE) trigger patch of type fTriggerCategory
if(fTriggerCategory == kTriggerRecalcGamma) {
if(!patch->IsRecalcGamma()) continue;
//if(doComments) cout<<Form("#Patch = %i, PatchE = %f", iPatch, patch->GetPatchE())<<endl;
} else if (fTriggerCategory == kTriggerRecalcJet) {
if(!patch->IsRecalcJet()) continue;
}
// method for filling collection output array of 'saved' recalculated patches
(*fRecalcTriggerPatches)[patchacc] = patch;
++patchacc;
if(doComments) {
cout<<"Have a recalculated patch: "<<endl;
cout<<Form("Cent = %f, #Patch = %i, #Acc = %i, PatchE = %f, PhiCM = %f, EtaCM = %f", fCent, iPatch, patchacc, patch->GetPatchE(), patch->GetPhiCM(), patch->GetEtaCM())<<endl;
}
// fill QA counter histo for Recalculated 'trig class' patches
FillTriggerPatchQA(fhQAinfoCounter, trig, patch);
// find max patch energy
if(patch->GetPatchE()>emax) {
fMaxPatch = patch;
emax = patch->GetPatchE();
} // max patch
} // loop over patches
// check on patch Energy
if(firedTrigClass.Contains(fTriggerClass) && fMaxPatch && fMaxPatch->GetPatchE() > fPatchECut) {
// get cluster container and find leading cluster
AliClusterContainer *clusContp = GetClusterContainer(0);
if(!clusContp) {
AliError(Form("ERROR: Cluster container doesn't exist\n"));
return;
}
AliVCluster* leadclus = clusContp->GetLeadingCluster();
if(!leadclus) return;
// initialize variables and get leading cluster parameters
double leadclusEta = 0, leadclusPhi = 0, leadclusE = 0;
TLorentzVector clusvect;
leadclus->GetMomentum(clusvect, const_cast<Double_t*>(fVertex));
leadclusEta = clusvect.Eta();
leadclusPhi = clusvect.Phi();
leadclusE = leadclus->E();
// get patch variables
double fMaxPatchPhiCM = fMaxPatch->GetPhiCM();
double fMaxPatchPhiGeo = fMaxPatch->GetPhiGeo();
double fMaxPatchEtaCM = fMaxPatch->GetEtaCM();
double fMaxPatchEtaGeo = fMaxPatch->GetEtaGeo();
/*
double fMaxPatchPhiMin = fMaxPatch->GetPhiMin();
double fMaxPatchPhiMax = fMaxPatch->GetPhiMax();
double fMaxPatchEtaMin = fMaxPatch->GetEtaMin();
double fMaxPatchEtaMax = fMaxPatch->GetEtaMax();
Int_t nTrigBit = fMaxPatch->GetTriggerBits();
*/
// positional variables
double dEtaGeo = 1.0*TMath::Abs(leadclusEta - fMaxPatchEtaGeo);
double dEtaCM = 1.0*TMath::Abs(leadclusEta - fMaxPatchEtaCM);
double dPhiGeo = 1.0*TMath::Abs(leadclusPhi - fMaxPatchPhiGeo);
double dPhiCM = 1.0*TMath::Abs(leadclusPhi - fMaxPatchPhiCM);
double maxPatchE = fMaxPatch->GetPatchE();
double maxPatchADC = fMaxPatch->GetADCAmpGeVRough();
// patch summary (meeting energy cut requirement)
/*
if(doComments) {
cout<<endl<<"Patch summary: "<<endl;
cout<<Form("Number of patches = %d, Max Patch Energy = %f GeV, MAXClusterE = %f, Phi = %f, Eta = %f", nPatch, fMaxPatch->GetPatchE(), leadclus->E(), leadclusPhi, leadclusEta)<<endl;
cout<<Form("CM in Phi = %f, in Eta = %f, Geo Center in Phi = %f, in Eta = %f, TriggerBits = %d", fMaxPatchPhiCM, fMaxPatchEtaCM, fMaxPatchPhiGeo, fMaxPatchEtaGeo, nTrigBit)<<endl;
cout<<Form("phi min = %f, phi max = %f, eta min = %f, eta max = %f", fMaxPatchPhiMin, fMaxPatchPhiMax, fMaxPatchEtaMin, fMaxPatchEtaMax)<<endl;
}
*/
Double_t fill[7] = {dEtaGeo, dEtaCM, dPhiGeo, dPhiCM, maxPatchADC, maxPatchE, leadclusE};
fhnPatchMaxClus->Fill(fill);
} // patch energy cut
// cout<<Form("Jet: low: %d, high: %d," ,nJ2, nJ1)<<" ";//<<endl;
// cout<<Form("Gamma: low: %d, high: %d," ,nG2, nG1)<<" ";//<<endl;
// cout<<Form("L0: %d", nL0)<<endl;
// cout<<Form("Max Patch Energy: %f GeV", fMaxPatch->GetPatchE())<<endl;
}
//________________________________________________________________________
void AliAnalysisTaskEmcalTriggerPatchClusterMatch::UserCreateOutputObjects()
{
// Create user output.
AliAnalysisTaskEmcal::UserCreateOutputObjects();
Bool_t oldStatus = TH1::AddDirectoryStatus();
TH1::AddDirectory(kFALSE);
fhNEvents = new TH1F("fhNEvents","fhNEvents;selection;N_{evt}",5,0,5);
fOutput->Add(fhNEvents);
fhTriggerbit = new TProfile("fhTriggerbit","fhTriggerbit;;TriggerBit",1,0,1);
fOutput->Add(fhTriggerbit);
Int_t fgkNCentBins = 21;
Float_t kMinCent = 0.;
Float_t kMaxCent = 105.;
Double_t *binsCent = new Double_t[fgkNCentBins+1];
for(Int_t i=0; i<=fgkNCentBins; i++) binsCent[i]=(Double_t)kMinCent + (kMaxCent-kMinCent)/fgkNCentBins*(Double_t)i ;
binsCent[fgkNCentBins-1] = 100.5;
binsCent[fgkNCentBins] = 101.5;
Int_t fgkNdEPBins = 18*8;
Float_t kMindEP = 0.;
Float_t kMaxdEP = 1.*TMath::Pi()/2.;
Double_t *binsdEP = new Double_t[fgkNdEPBins+1];
for(Int_t i=0; i<=fgkNdEPBins; i++) binsdEP[i]=(Double_t)kMindEP + (kMaxdEP-kMindEP)/fgkNdEPBins*(Double_t)i ;
Int_t fgkNPtBins = 200;
Float_t kMinPt = -50.;
Float_t kMaxPt = 150.;
Double_t *binsPt = new Double_t[fgkNPtBins+1];
for(Int_t i=0; i<=fgkNPtBins; i++) binsPt[i]=(Double_t)kMinPt + (kMaxPt-kMinPt)/fgkNPtBins*(Double_t)i ;
Int_t fgkNPhiBins = 18*8;
Float_t kMinPhi = 0.;
Float_t kMaxPhi = 2.*TMath::Pi();
Double_t *binsPhi = new Double_t[fgkNPhiBins+1];
for(Int_t i=0; i<=fgkNPhiBins; i++) binsPhi[i]=(Double_t)kMinPhi + (kMaxPhi-kMinPhi)/fgkNPhiBins*(Double_t)i ;
Int_t fgkNEtaBins = 100;
Float_t fgkEtaMin = -1.;
Float_t fgkEtaMax = 1.;
Double_t *binsEta=new Double_t[fgkNEtaBins+1];
for(Int_t i=0; i<=fgkNEtaBins; i++) binsEta[i]=(Double_t)fgkEtaMin + (fgkEtaMax-fgkEtaMin)/fgkNEtaBins*(Double_t)i ;
Int_t fgkNConstBins = 100;
Float_t kMinConst = 0.;
Float_t kMaxConst = 100.;
Double_t *binsConst = new Double_t[fgkNConstBins+1];
for(Int_t i=0; i<=fgkNConstBins; i++) binsConst[i]=(Double_t)kMinConst + (kMaxConst-kMinConst)/fgkNConstBins*(Double_t)i ;
Int_t fgkNTimeBins = 100;
Float_t kMinTime = -200.;
Float_t kMaxTime = 200;
Double_t *binsTime = new Double_t[fgkNTimeBins+1];
for(Int_t i=0; i<=fgkNTimeBins; i++) binsTime[i]=(Double_t)kMinTime + (kMaxTime-kMinTime)/fgkNTimeBins*(Double_t)i ;
Int_t fgkNVZEROBins = 100;
Float_t kMinVZERO = 0.;
Float_t kMaxVZERO = 25000;
Double_t *binsVZERO = new Double_t[fgkNVZEROBins+1];
for(Int_t i=0; i<=fgkNVZEROBins; i++) binsVZERO[i]=(Double_t)kMinVZERO + (kMaxVZERO-kMinVZERO)/fgkNVZEROBins*(Double_t)i ;
Double_t enBinEdges[3][2];
enBinEdges[0][0] = 1.; //10 bins
enBinEdges[0][1] = 0.1;
enBinEdges[1][0] = 5.; //8 bins
enBinEdges[1][1] = 0.5;
enBinEdges[2][0] = 100.;//95 bins
enBinEdges[2][1] = 1.;
const Float_t enmin1 = 0;
const Float_t enmax1 = enBinEdges[0][0];
const Float_t enmin2 = enmax1 ;
const Float_t enmax2 = enBinEdges[1][0];
const Float_t enmin3 = enmax2 ;
const Float_t enmax3 = enBinEdges[2][0];//fgkEnMax;
const Int_t nbin11 = (int)((enmax1-enmin1)/enBinEdges[0][1]);
const Int_t nbin12 = (int)((enmax2-enmin2)/enBinEdges[1][1])+nbin11;
const Int_t nbin13 = (int)((enmax3-enmin3)/enBinEdges[2][1])+nbin12;
Int_t fgkNEnBins=nbin13;
Double_t *binsEn=new Double_t[fgkNEnBins+1];
for(Int_t i=0; i<=fgkNEnBins; i++) {
if(i<=nbin11) binsEn[i]=(Double_t)enmin1 + (enmax1-enmin1)/nbin11*(Double_t)i ;
if(i<=nbin12 && i>nbin11) binsEn[i]=(Double_t)enmin2 + (enmax2-enmin2)/(nbin12-nbin11)*((Double_t)i-(Double_t)nbin11) ;
if(i<=nbin13 && i>nbin12) binsEn[i]=(Double_t)enmin3 + (enmax3-enmin3)/(nbin13-nbin12)*((Double_t)i-(Double_t)nbin12) ;
}
fh3PtEtaPhiTracks = new TH3F("fh3PtEtaPhiTracks","fh3PtEtaPhiTracks;#it{p}_{T}^{track}_{vtx};#eta_{vtx};#varphi_{vtx}",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PtEtaPhiTracks);
fh3PtEtaPhiTracksOnEmcal = new TH3F("fh3PtEtaPhiTracksOnEmcal","fh3PtEtaPhiTracksOnEmcal;#it{p}_{T}^{track}_{emc};#eta_{emc};#varphi_{emc}",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PtEtaPhiTracksOnEmcal);
fh3PtEtaPhiTracksToProp = new TH3F("fh3PtEtaPhiTracksToProp","fh3PtEtaPhiTracksToProp;#it{p}_{T}^{track}_{vtx};#eta_{vtx};#varphi_{vtx}",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PtEtaPhiTracksToProp);
fh3PtEtaPhiTracksProp = new TH3F("fh3PtEtaPhiTracksProp","fh3PtEtaPhiTracksProp;#it{p}_{T}^{track}_{vtx};#eta_{vtx};#varphi_{vtx}",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PtEtaPhiTracksProp);
fh3PtEtaPhiTracksNoProp = new TH3F("fh3PtEtaPhiTracksNoProp","fh3PtEtaPhiTracksNoProp;#it{p}_{T}^{track}_{vtx};#eta_{vtx};#varphi_{vtx}",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PtEtaPhiTracksNoProp);
fh3EEtaPhiCluster = new TH3F("fh3EEtaPhiCluster","fh3EEtaPhiCluster;E_{clus};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3EEtaPhiCluster);
fh3PatchEnergyEtaPhiCenterJ1 = new TH3F("fh3PatchEnergyEtaPhiCenterJ1","fh3PatchEnergyEtaPhiCenterJ1;E_{patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchEnergyEtaPhiCenterJ1);
fh3PatchEnergyEtaPhiCenterJ2 = new TH3F("fh3PatchEnergyEtaPhiCenterJ2","fh3PatchEnergyEtaPhiCenterJ2;E_{patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchEnergyEtaPhiCenterJ2);
fh3PatchEnergyEtaPhiCenterJ1J2 = new TH3F("fh3PatchEnergyEtaPhiCenterJ1J2","fh3PatchEnergyEtaPhiCenterJ1J2;E_{patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchEnergyEtaPhiCenterJ1J2);
fh3PatchADCEnergyEtaPhiCenterJ1 = new TH3F("fh3PatchADCEnergyEtaPhiCenterJ1","fh3PatchADCEnergyEtaPhiCenterJ1;E_{ADC,patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchADCEnergyEtaPhiCenterJ1);
fh3PatchADCEnergyEtaPhiCenterJ2 = new TH3F("fh3PatchADCEnergyEtaPhiCenterJ2","fh3PatchADCEnergyEtaPhiCenterJ2;E_{ADC,patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchADCEnergyEtaPhiCenterJ2);
fh3PatchADCEnergyEtaPhiCenterJ1J2 = new TH3F("fh3PatchADCEnergyEtaPhiCenterJ1J2","fh3PatchADCEnergyEtaPhiCenterJ1J2;E_{ADC,patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchADCEnergyEtaPhiCenterJ1J2);
fh3PatchEnergyEtaPhiCenterG1 = new TH3F("fh3PatchEnergyEtaPhiCenterG1","fh3PatchEnergyEtaPhiCenterG1;E_{patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchEnergyEtaPhiCenterG1);
fh3PatchEnergyEtaPhiCenterG2 = new TH3F("fh3PatchEnergyEtaPhiCenterG2","fh3PatchEnergyEtaPhiCenterG2;E_{patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchEnergyEtaPhiCenterG2);
fh3PatchEnergyEtaPhiCenterG1G2 = new TH3F("fh3PatchEnergyEtaPhiCenterG1G2","fh3PatchEnergyEtaPhiCenterG1G2;E_{patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchEnergyEtaPhiCenterG1G2);
fh3PatchADCEnergyEtaPhiCenterG1 = new TH3F("fh3PatchADCEnergyEtaPhiCenterG1","fh3PatchADCEnergyEtaPhiCenterG1;E_{ADC,patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchADCEnergyEtaPhiCenterG1);
fh3PatchADCEnergyEtaPhiCenterG2 = new TH3F("fh3PatchADCEnergyEtaPhiCenterG2","fh3PatchADCEnergyEtaPhiCenterG2;E_{ADC,patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchADCEnergyEtaPhiCenterG2);
fh3PatchADCEnergyEtaPhiCenterG1G2 = new TH3F("fh3PatchADCEnergyEtaPhiCenterG1G2","fh3PatchADCEnergyEtaPhiCenterG1G2;E_{ADC,patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchADCEnergyEtaPhiCenterG1G2);
fh3PatchADCEnergyEtaPhiCenterAll = new TH3F("fh3PatchADCEnergyEtaPhiCenterAll","fh3PatchADCEnergyEtaPhiCenterAll;E_{ADC,patch};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3PatchADCEnergyEtaPhiCenterAll);
fh3EEtaPhiCell = new TH3F("fh3EEtaPhiCell","fh3EEtaPhiCell;E_{cell};#eta;#phi",fgkNEnBins,binsEn,fgkNEtaBins,binsEta,fgkNPhiBins,binsPhi);
fOutput->Add(fh3EEtaPhiCell);
fh2ECellVsCent = new TH2F("fh2ECellVsCent","fh2ECellVsCent;centrality;E_{cell}",101,-1,100,500,0.,5.);
fOutput->Add(fh2ECellVsCent);
fh2CellEnergyVsTime = new TH2F("fh2CellEnergyVsTime","fh2CellEnergyVsTime;E_{cell};time",fgkNEnBins,binsEn,fgkNTimeBins,binsTime);
fOutput->Add(fh2CellEnergyVsTime);
fh3EClusELeadingCellVsTime = new TH3F("fh3EClusELeadingCellVsTime","fh3EClusELeadingCellVsTime;E_{cluster};E_{leading cell};time_{leading cell}",fgkNEnBins,binsEn,fgkNEnBins,binsEn,fgkNTimeBins,binsTime);
fOutput->Add(fh3EClusELeadingCellVsTime);
fhQAinfoAllPatchesCounter = new TH1F("fhQAinfoAllPatchesCounter", "QA trigger info counters for all patches", 20, 0.5, 20.5);
fOutput->Add(fhQAinfoAllPatchesCounter);
fhQAinfoCounter = new TH1F("fhQAinfoCounter", "QA trigger info counters", 20, 0.5, 20.5);
fOutput->Add(fhQAinfoCounter);
fhQAmaxinfoCounter = new TH1F("fhQAmaxinfoCounter", "QA Max patch trigger info counters", 20, 0.5, 20.5);
fOutput->Add(fhQAmaxinfoCounter);
fhRecalcGammaPatchEnergy = new TH1F("fhRecalcGammaPatchEnergy", "Recalculated Gamma Patch Energy", 200, 0, 50); //100
fOutput->Add(fhRecalcGammaPatchEnergy);
fhGammaLowPatchEnergy = new TH1F("fhGammaLowPatchEnergy", "Gamma Low Patch Energy", 200, 0, 50); //100
fOutput->Add(fhGammaLowPatchEnergy);
fhGammaLowSimplePatchEnergy = new TH1F("fhGammaLowSimplePatchEnergy", "Gamma Low Simple Patch Energy", 200, 0, 50); //100
fOutput->Add(fhGammaLowSimplePatchEnergy);
fhRecalcJetPatchEnergy = new TH1F("fhRecalcJetPatchEnergy", "Recalculated Jet Patch Energy", 200, 0, 100);
fOutput->Add(fhRecalcJetPatchEnergy);
fhJetLowPatchEnergy = new TH1F("fhJetLowPatchEnergy", "Jet Low Patch Energy", 200, 0, 100);
fOutput->Add(fhJetLowPatchEnergy);
fhJetLowSimplePatchEnergy = new TH1F("fhJetLowSimplePatchEnergy", "Jet Low Simple Patch Energy", 200, 0, 100);
fOutput->Add(fhJetLowSimplePatchEnergy);
fhMainTriggerPatchEnergy = new TH1F("fhMainTriggerPatchEnergy", "Main Trigger Patch Energy", 200, 0, 100);
fOutput->Add(fhMainTriggerPatchEnergy);
fHistClusEnergy = new TH1F("fHistClusEnergy", "Cluster Energy distribution", 200, 0, 50);
fOutput->Add(fHistClusEnergy);
for(Int_t j=0; j<16; j++) {
fHistdPhidEtaPatchCluster[j] = new TH2F(Form("fHistdPhidEtaPatchCluster_%d",j), "dPhi-dEta distribution between max recalculated Gamma patch and most energetic cluster", 144, 0, 2.016, 144, 0, 2.016);
fOutput->Add(fHistdPhidEtaPatchCluster[j]);
}
Int_t nDim=7;
Int_t *nbins = new Int_t[nDim];
Double_t *xmin = new Double_t[nDim];
Double_t *xmax = new Double_t[nDim];
for (Int_t i=0; i<nDim; i++){
nbins[i]=144;
xmin[i]=0;
xmax[i]=2.016;
}
nbins[4]=100; xmax[4]=100;
nbins[5]=100; xmax[5]=100.;
nbins[6]=100; xmax[6]=100.;
fhnPatchMaxClus = new THnSparseF("fhnPatchMaxClus","fhn Patch Max Cluster Distributions", nDim,nbins,xmin,xmax);
fhnPatchMaxClus->GetAxis(0)->SetTitle("#Delta#etaGeo"); // 0
fhnPatchMaxClus->GetAxis(1)->SetTitle("#Delta#etaCM"); // 1
fhnPatchMaxClus->GetAxis(2)->SetTitle("#Delta#phiGeo"); // 2
fhnPatchMaxClus->GetAxis(3)->SetTitle("#Delta#phiCM"); // 3
fhnPatchMaxClus->GetAxis(4)->SetTitle("Max Patch ADC"); // 4
fhnPatchMaxClus->GetAxis(5)->SetTitle("Max Patch Energy"); // 5
fhnPatchMaxClus->GetAxis(6)->SetTitle("Leading Cluster Energy"); // 6
fOutput->Add(fhnPatchMaxClus);
// QA before/after matching
Int_t nDim1=6;
Int_t *nbins1 = new Int_t[nDim1];
Double_t *xmin1 = new Double_t[nDim1];
Double_t *xmax1 = new Double_t[nDim1];
nbins1[0]=10; xmin1[0]=0.; xmax1[0]=100.;
nbins1[1]=200; xmin1[1]=0.; xmax1[1]=50;
nbins1[2]=144; xmin1[2]=0.; xmax1[2]=2.016;
nbins1[3]=144; xmin1[3]=0.; xmax1[3]=2.016;
nbins1[4]=300; xmin1[4]=0.; xmax1[4]=300;
nbins1[5]=500; xmin1[5]=0.; xmax1[5]=500;
// before cuts to perform match
fhnPatchMatch = new THnSparseF("fhnPatchMatch","fhn Patch Match before cuts", nDim1,nbins1,xmin1,xmax1);
fhnPatchMatch->GetAxis(0)->SetTitle("Centrality %"); // 0
fhnPatchMatch->GetAxis(1)->SetTitle("Cluster Energy"); // 1
fhnPatchMatch->GetAxis(2)->SetTitle("#Delta#phi Geo"); // 2
fhnPatchMatch->GetAxis(3)->SetTitle("#Delta#eta Geo"); // 3
fhnPatchMatch->GetAxis(4)->SetTitle("Max Patch Energy"); // 4
fhnPatchMatch->GetAxis(5)->SetTitle("Max Patch ADC"); // 5
fOutput->Add(fhnPatchMatch);
// after cuts to perform match
fhnPatchMatch2 = new THnSparseF("fhnPatchMatch2","fhn Patch Match after cuts", nDim1,nbins1,xmin1,xmax1);
fhnPatchMatch2->GetAxis(0)->SetTitle("Centrality %"); // 0
fhnPatchMatch2->GetAxis(1)->SetTitle("Cluster Energy"); // 1
fhnPatchMatch2->GetAxis(2)->SetTitle("#Delta#phi Geo"); // 2
fhnPatchMatch2->GetAxis(3)->SetTitle("#Delta#eta Geo"); // 3
fhnPatchMatch2->GetAxis(4)->SetTitle("Max Patch Energy"); // 4
fhnPatchMatch2->GetAxis(5)->SetTitle("Max Patch ADC"); // 5
fOutput->Add(fhnPatchMatch2);
// for cluster matched to patch
Int_t nDim2=10;
Int_t *nbins2 = new Int_t[nDim2];
Double_t *xmin2 = new Double_t[nDim2];
Double_t *xmax2 = new Double_t[nDim2];
for (Int_t i=0; i<nDim2; i++){
nbins2[i]=144;
xmin2[i]=0;
}
nbins2[0]=10; xmax2[0]=100;
nbins2[1]=200; xmax2[1]=50.;
nbins2[2]=72; xmin2[2]=1.2; xmax2[2]=3.4; //2.0*TMath::Pi();
nbins2[3]=56; xmin2[3]=-0.7; xmax2[3]=0.7;
nbins2[4]=500; xmax2[4]=500.;
nbins2[5]=500; xmax2[5]=500.;
nbins2[6]=300; xmax2[6]=300.;
nbins2[7]=300; xmax2[7]=300.;
nbins2[8]=72; xmin2[8]=1.4; xmax2[9]=3.2;
nbins2[9]=56; xmin2[9]=-0.7; xmax2[9]=0.7;
//Double_t fill[18] = {fCent, dEPJet, jet->Pt(), jet->Phi(), jet->Eta(), jet->Area(), jet->GetNumberOfTracks(), jet->MaxTrackPt(), jet->GetNumberOfClusters(), maxClusterE, maxClusterPhi, maxClusterEta, kAmplitudeOnline, kAmplitudeOnline, kEnergyOnline, kEnergyOffline, fMaxPatchPhiGeo, fMaxPatchEtaGeo}; ////
/*
fhnPatchMatchJetLeadClus = new THnSparseF("fhnPatchMatchJetLeadClus","fhn Patch Match to Jet Leading Cluster", nDim2, nbins2,xmin2,xmax2); ////
fhnPatchMatchJetLeadClus->GetAxis(0)->SetTitle("Centrality %"); // 0
fhnPatchMatchJetLeadClus->GetAxis(1)->SetTitle("Max Cluster Energy constituent of Jet"); // 1
fhnPatchMatchJetLeadClus->GetAxis(2)->SetTitle("Cluster #phi"); // 2
fhnPatchMatchJetLeadClus->GetAxis(3)->SetTitle("Cluster #eta"); // 3
fhnPatchMatchJetLeadClus->GetAxis(4)->SetTitle("Max Patch Amplitude Online"); // 4
fhnPatchMatchJetLeadClus->GetAxis(5)->SetTitle("Max Patch Amplitude Offline"); // 5
fhnPatchMatchJetLeadClus->GetAxis(6)->SetTitle("Max Patch Energy Online"); // 6
fhnPatchMatchJetLeadClus->GetAxis(7)->SetTitle("Max Patch Energy Offline"); // 7
fhnPatchMatchJetLeadClus->GetAxis(8)->SetTitle("Max Patch Geometric Center in #phi"); // 8
fhnPatchMatchJetLeadClus->GetAxis(9)->SetTitle("Max Patch Geometric Center in #eta"); // 9
fOutput->Add(fhnPatchMatchJetLeadClus); ////
*/
// Event Selection QA histo
fHistEventSelectionQA = new TH1F("fHistEventSelectionQA", "Trigger Selection Counter", 20, 0.5, 20.5);
fOutput->Add(fHistEventSelectionQA);
// =========== Switch on Sumw2 for all histos ===========
for (Int_t i=0; i<fOutput->GetEntries(); ++i) {
TH1 *h1 = dynamic_cast<TH1*>(fOutput->At(i));
if (h1){
h1->Sumw2();
continue;
}
TH2 *h2 = dynamic_cast<TH2*>(fOutput->At(i));
if (h2){
h2->Sumw2();
continue;
}
TH3 *h3 = dynamic_cast<TH3*>(fOutput->At(i));
if (h3){
h3->Sumw2();
continue;
}
THnSparse *hn = dynamic_cast<THnSparse*>(fOutput->At(i));
if(hn)hn->Sumw2();
}
TH1::AddDirectory(oldStatus);
PostData(1, fOutput); // Post data for ALL output slots > 0 here.
if(binsCent) delete [] binsCent;
if(binsdEP) delete [] binsdEP;
if(binsEn) delete [] binsEn;
if(binsPt) delete [] binsPt;
if(binsPhi) delete [] binsPhi;
if(binsEta) delete [] binsEta;
if(binsConst) delete [] binsConst;
if(binsTime) delete [] binsTime;
if(binsVZERO) delete [] binsVZERO;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskEmcalTriggerPatchClusterMatch::FillHistograms() {
// Fill histograms.
// check and fill a Event Selection QA histogram for different trigger selections
UInt_t trig = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
// get fired trigger classes
TString firedTrigClass = InputEvent()->GetFiredTriggerClasses();
// fill Event Trigger QA
FillEventTriggerQA(fHistEventSelectionQA, trig);
// create pointer to list of input event
TList *list = InputEvent()->GetList();
if(!list) {
AliError(Form("ERROR: list not attached\n"));
return kTRUE;
}
// reset collection at start of event
fClusterTriggeredEvent->Clear();
//Tracks
AliParticleContainer *partCont = GetParticleContainer(0);
if (partCont) {
partCont->ResetCurrentID();
AliVTrack *track = dynamic_cast<AliVTrack*>(partCont->GetNextAcceptParticle());
while(track) {
Double_t trkphi = track->Phi()*TMath::RadToDeg();
fh3PtEtaPhiTracks->Fill(track->Pt(),track->Eta(),track->Phi());
//Select tracks which should be propagated
if(track->Pt()>=0.350) {
if (TMath::Abs(track->Eta())<=0.9 && trkphi > 10 && trkphi < 250) {
fh3PtEtaPhiTracksOnEmcal->Fill(track->GetTrackPtOnEMCal(),track->GetTrackEtaOnEMCal(),track->GetTrackPhiOnEMCal());
fh3PtEtaPhiTracksToProp->Fill(track->Pt(),track->Eta(),track->Phi());
if(track->GetTrackPtOnEMCal()>=0) fh3PtEtaPhiTracksProp->Fill(track->Pt(),track->Eta(),track->Phi());
else
fh3PtEtaPhiTracksNoProp->Fill(track->Pt(),track->Eta(),track->Phi());
} // acceptance cut
} // track pt cut
track = dynamic_cast<AliPicoTrack*>(partCont->GetNextAcceptParticle());
} // track exist
} // particle container
//Clusters - get cluster collection
TClonesArray *clusters = 0x0;
clusters = dynamic_cast<TClonesArray*>(list->FindObject("EmcCaloClusters"));
if (!clusters) {
AliError(Form("Pointer to clusters %s == 0", "EmcCaloClusters"));
return kTRUE;
} // verify existence of clusters
// loop over clusters
const Int_t Nclusters = clusters->GetEntries();
for (Int_t iclus = 0; iclus < Nclusters; iclus++){
AliVCluster* clus = static_cast<AliVCluster*>(clusters->At(iclus));
if(!clus){
AliError(Form("Couldn't get AliVCluster %d\n", iclus));
continue;
}
// is cluster in EMCal?
if (!clus->IsEMCAL()) {
AliDebug(2,Form("%s: Cluster is not emcal",GetName()));
continue;
}
// get some info on cluster and fill histo
TLorentzVector lp;
clus->GetMomentum(lp, const_cast<Double_t*>(fVertex));
fHistClusEnergy->Fill(lp.E());
}
//Clusters
AliClusterContainer *clusCont = GetClusterContainer(0);
if (clusCont) {
Int_t nclusters = clusCont->GetNClusters();
for (Int_t ic = 0, clusacc = 0; ic < nclusters; ic++) {
AliVCluster *cluster = static_cast<AliVCluster*>(clusCont->GetCluster(ic));
if (!cluster) {
AliDebug(2,Form("Could not receive cluster %d", ic));
continue;
}
// is cluster in EMCal?
if (!cluster->IsEMCAL()) {
AliDebug(2,Form("%s: Cluster is not emcal",GetName()));
continue;
}
TLorentzVector lp;
cluster->GetMomentum(lp, const_cast<Double_t*>(fVertex));
fh3EEtaPhiCluster->Fill(lp.E(),lp.Eta(),lp.Phi());
if(fCaloCells) {
Double_t leadCellE = GetEnergyLeadingCell(cluster);
Double_t leadCellT = cluster->GetTOF();
fh3EClusELeadingCellVsTime->Fill(lp.E(),leadCellE,leadCellT*1e9);
} // if calo cells exist
// get cluster observables
Double_t ClusterEta = 0., ClusterPhi = 0., ClusterE = 0.;
ClusterEta = lp.Eta();
ClusterPhi = lp.Phi();
ClusterE = cluster->E();
// check that trigger class was fired and require we have a cluster meeting energy cut - Matches to MAX Patch
if(ClusterE > fClusBias && fMaxPatch && firedTrigClass.Contains(fTriggerClass) && (!fUseALLrecalcPatches)) {
//cout<<Form("#Clus in container = %i, NACCcluster = %i, LeadClusE = %f, isEMCal? = %s", clusCont->GetNClusters(), clusCont->GetNAcceptedClusters(), leadclus->E(), leadclus->IsEMCAL()? "true":"false")<<endl;
// get max patch location
double fMaxPatchPhiGeo = fMaxPatch->GetPhiGeo();
double fMaxPatchEtaGeo = fMaxPatch->GetEtaGeo();
double dPhiPatchLeadCl = 1.0*TMath::Abs(fMaxPatchPhiGeo - ClusterPhi);
double dEtaPatchLeadCl = 1.0*TMath::Abs(fMaxPatchEtaGeo - ClusterEta);
// get offline/online Energy and ADC count
double kAmplitudeOnline = fMaxPatch->GetADCAmp();
//double kAmplitudeOffline = fMaxPatch->GetADCOfflineAmp();
//double kEnergyOnline = fMaxPatch->GetADCAmpGeVRough();
double kEnergyOffline = fMaxPatch->GetPatchE();
// get patch variables
double etamin = TMath::Min(fMaxPatch->GetEtaMin(), fMaxPatch->GetEtaMax());
double etamax = TMath::Max(fMaxPatch->GetEtaMin(), fMaxPatch->GetEtaMax());
double phimin = TMath::Min(fMaxPatch->GetPhiMin(), fMaxPatch->GetPhiMax());
double phimax = TMath::Max(fMaxPatch->GetPhiMin(), fMaxPatch->GetPhiMax());
for(int maxbinE = 0; maxbinE<16; maxbinE++) { if(ClusterE > maxbinE) fHistdPhidEtaPatchCluster[maxbinE]->Fill(dPhiPatchLeadCl, dEtaPatchLeadCl); }
// fill sparse array before and after match
Double_t fillarr[6] = {fCent, ClusterE, dPhiPatchLeadCl, dEtaPatchLeadCl, kEnergyOffline, kAmplitudeOnline};
fhnPatchMatch->Fill(fillarr);
if(ClusterEta > etamin && ClusterEta < etamax && ClusterPhi > phimin && ClusterPhi < phimax) fhnPatchMatch2->Fill(fillarr);
// patch meeting offline energy cut
if(fMaxPatch->GetPatchE() > fPatchECut) {
// look to geometrically match patch to leading cluster of jet
if(ClusterEta > etamin && ClusterEta < etamax && ClusterPhi > phimin && ClusterPhi < phimax){
if(doComments) {
cout<<"*********************************************"<<endl;
cout<<"Proper match (cluster to fired max patch): "<<endl;
cout<<Form("MaxClusterE = %f, Phi = %f, Eta = %f", ClusterE, ClusterPhi, ClusterEta)<<endl;
cout<<"*********************************************"<<endl;
} // do comments
// fill sparse for match
//Double_t fill[10] = {fCent, ClusterE, ClusterPhi, ClusterEta, kAmplitudeOnline, kAmplitudeOffline, kEnergyOnline, kEnergyOffline, fMaxPatchPhiGeo, fMaxPatchEtaGeo};
//fhnPatchMatchJetLeadClus->Fill(fill);
// method for filling collection output array of 'saved' clusters
(*fClusterTriggeredEvent)[clusacc] = cluster;
++clusacc;
} // MATCH!
} // patch > Ecut GeV
} // cluster energy > cut
// switch for recalculated patches
if(fUseALLrecalcPatches) {
// apply cluster energy cut, make sure event fired trigger and require recalculated trigger patch object
if(ClusterE > fClusBias && firedTrigClass.Contains(fTriggerClass) && fRecalcTriggerPatches) {
// number of recalculated patches in event
Int_t nPatch = fRecalcTriggerPatches->GetEntriesFast();
AliEMCALTriggerPatchInfo *patch;
for(Int_t iPatch = 0; iPatch < nPatch; iPatch++) {
patch = (AliEMCALTriggerPatchInfo*)fRecalcTriggerPatches->At(iPatch);
if(!patch) continue;
// get max patch location
double fPatchPhiGeo = patch->GetPhiGeo();
double fPatchEtaGeo = patch->GetEtaGeo();
double dPhiPatchCl = 1.0*TMath::Abs(fPatchPhiGeo - ClusterPhi);
double dEtaPatchCl = 1.0*TMath::Abs(fPatchEtaGeo - ClusterEta);
// get offline/online Energy and ADC count
double kAmplitudeOnline = patch->GetADCAmp();
//double kAmplitudeOffline = patch->GetADCOfflineAmp();
//double kEnergyOnline = patch->GetADCAmpGeVRough();
double kEnergyOffline = patch->GetPatchE();
// get patch variables
double etamin = TMath::Min(patch->GetEtaMin(), patch->GetEtaMax());
double etamax = TMath::Max(patch->GetEtaMin(), patch->GetEtaMax());
double phimin = TMath::Min(patch->GetPhiMin(), patch->GetPhiMax());
double phimax = TMath::Max(patch->GetPhiMin(), patch->GetPhiMax());
for(int maxbinE = 0; maxbinE<16; maxbinE++) { if(ClusterE > maxbinE) fHistdPhidEtaPatchCluster[maxbinE]->Fill(dPhiPatchCl, dEtaPatchCl); }
// fill sparse array before and after match
Double_t fillarr[6] = {fCent, ClusterE, dPhiPatchCl, dEtaPatchCl, kEnergyOffline, kAmplitudeOnline};
fhnPatchMatch->Fill(fillarr);
// matched successfully
if(ClusterEta > etamin && ClusterEta < etamax && ClusterPhi > phimin && ClusterPhi < phimax) fhnPatchMatch2->Fill(fillarr);
// patch meeting offline energy cut
if(patch->GetPatchE() > fPatchECut) {
// look to geometrically match patch to leading cluster of jet
if(ClusterEta > etamin && ClusterEta < etamax && ClusterPhi > phimin && ClusterPhi < phimax){
if(doComments) {
cout<<"*********************************************"<<endl;
cout<<"Proper match (cluster to fired max patch): ";
cout<<Form("Centrality = %f", fCent)<<endl;
cout<<Form("PatchE = %f, PhiMin = %f, PhiMax = %f, EtaMin = %f, EtaMax = %f, Patch# = %i", kEnergyOffline, phimin, phimax, etamin, etamax, iPatch)<<endl;
cout<<Form("ClusterE = %f, Phi = %f, Eta = %f", ClusterE, ClusterPhi, ClusterEta)<<endl;
cout<<"*********************************************"<<endl;
} // do comments
// fill sparse for match
//Double_t fill[10] = {fCent, ClusterE, ClusterPhi, ClusterEta, kAmplitudeOnline, kAmplitudeOffline, kEnergyOnline, kEnergyOffline, fMaxPatchPhiGeo, fMaxPatchEtaGeo};
//fhnPatchMatchJetLeadClus->Fill(fill);
// method for filling collection output array of 'saved' clusters
(*fClusterTriggeredEvent)[clusacc] = cluster;
++clusacc;
} // MATCH!
} // patch energy cut (should not really need)
} // recalculated patch loop
} // cluster energy cut
} // recalulated patch switch
////////////////////////////////////////////
} // cluster loop
} // if cluster container exist
//Get VZERO amplitude
// Float_t VZEROAmp = InputEvent()->GetVZEROData()->GetTriggerChargeA() + InputEvent()->GetVZEROData()->GetTriggerChargeC();
//Cells - some QA plots
if(fCaloCells) {
const Short_t nCells = fCaloCells->GetNumberOfCells();
for(Int_t iCell=0; iCell<nCells; ++iCell) {
Short_t cellId = fCaloCells->GetCellNumber(iCell);
Double_t cellE = fCaloCells->GetCellAmplitude(cellId);
Double_t cellT = fCaloCells->GetCellTime(cellId);
TVector3 pos;
fGeom->GetGlobal(cellId, pos);
TLorentzVector lv(pos,cellE);
Double_t cellEta = lv.Eta();
Double_t cellPhi = lv.Phi();
if(cellPhi<0.) cellPhi+=TMath::TwoPi();
if(cellPhi>TMath::TwoPi()) cellPhi-=TMath::TwoPi();
AliDebug(2,Form("cell energy = %f time = %f",cellE,cellT*1e9));
fh2CellEnergyVsTime->Fill(cellE,cellT*1e9);
fh3EEtaPhiCell->Fill(cellE,cellEta,cellPhi);
fh2ECellVsCent->Fill(fCent,cellE);
}
}
return kTRUE;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskEmcalTriggerPatchClusterMatch::Run() {
// Run analysis code here, if needed. It will be executed before FillHistograms().
fhTriggerbit->Fill(0.5,GetCollisionCandidates());
// just in case, set the geometry scheme
fGeom = AliEMCALGeometry::GetInstance("EMCAL_COMPLETEV1");
//Check if event is selected (vertex & pile-up)
//if(!SelectEvent()) return kFALSE;
// when we have the patch object to match, peform analysis
if(fTriggerPatchInfo) FillTriggerPatchHistos();
return kTRUE; // If return kFALSE FillHistogram() will NOT be executed.
}
//_______________________________________________________________________
void AliAnalysisTaskEmcalTriggerPatchClusterMatch::Terminate(Option_t *) {
// Called once at the end of the analysis.
}
//________________________________________________________________________
Int_t AliAnalysisTaskEmcalTriggerPatchClusterMatch::GetLeadingCellId(const AliVCluster *clus) const {
//Get energy of leading cell in cluster
if(!fCaloCells) return -1;
Double_t emax = -1.;
Int_t iCellAbsIdMax = -1;
Int_t nCells = clus->GetNCells();
for(Int_t i = 0; i<nCells; i++) {
Int_t absId = clus->GetCellAbsId(i);
Double_t cellE = fCaloCells->GetCellAmplitude(absId);
if(cellE>emax) {
emax = cellE;
iCellAbsIdMax = absId;
}
}
return iCellAbsIdMax;
}
//________________________________________________________________________
Double_t AliAnalysisTaskEmcalTriggerPatchClusterMatch::GetEnergyLeadingCell(const AliVCluster *clus) const {
//Get energy of leading cell in cluster
if(!fCaloCells) return -1.;
Int_t absID = GetLeadingCellId(clus);
if(absID>-1) return fCaloCells->GetCellAmplitude(absID);
else return -1.;
}
//________________________________________________________________________
Double_t AliAnalysisTaskEmcalTriggerPatchClusterMatch::GetECross(Int_t absID) const {
//Get Ecross = sum of energy of neighbouring cells (using uncalibrated energy)
if(!fCaloCells) return -1.;
Double_t ecross = -1.;
Int_t absID1 = -1;
Int_t absID2 = -1;
Int_t absID3 = -1;
Int_t absID4 = -1;
Int_t imod = -1, iphi =-1, ieta=-1, iTower = -1, iIphi = -1, iIeta = -1;
fGeom->GetCellIndex(absID,imod,iTower,iIphi,iIeta);
fGeom->GetCellPhiEtaIndexInSModule(imod,iTower,iIphi, iIeta,iphi,ieta);
if( iphi < AliEMCALGeoParams::fgkEMCALRows-1)
absID1 = fGeom->GetAbsCellIdFromCellIndexes(imod, iphi+1, ieta);
if( iphi > 0 )
absID2 = fGeom->GetAbsCellIdFromCellIndexes(imod, iphi-1, ieta);
if( ieta == AliEMCALGeoParams::fgkEMCALCols-1 && !(imod%2) ) {
absID3 = fGeom->GetAbsCellIdFromCellIndexes(imod+1, iphi, 0);
absID4 = fGeom->GetAbsCellIdFromCellIndexes(imod, iphi, ieta-1);
}
else if( ieta == 0 && imod%2 ) {
absID3 = fGeom->GetAbsCellIdFromCellIndexes(imod, iphi, ieta+1);
absID4 = fGeom->GetAbsCellIdFromCellIndexes(imod-1, iphi, AliEMCALGeoParams::fgkEMCALCols-1);
}
else {
if( ieta < AliEMCALGeoParams::fgkEMCALCols-1 )
absID3 = fGeom->GetAbsCellIdFromCellIndexes(imod, iphi, ieta+1);
if( ieta > 0 )
absID4 = fGeom->GetAbsCellIdFromCellIndexes(imod, iphi, ieta-1);
}
Double_t ecell1 = fCaloCells->GetCellAmplitude(absID1);
Double_t ecell2 = fCaloCells->GetCellAmplitude(absID2);
Double_t ecell3 = fCaloCells->GetCellAmplitude(absID3);
Double_t ecell4 = fCaloCells->GetCellAmplitude(absID4);
ecross = ecell1+ecell2+ecell3+ecell4;
return ecross;
}
//_________________________________________________________________________
Float_t AliAnalysisTaskEmcalTriggerPatchClusterMatch::RelativeEP(Double_t objAng, Double_t EPAng) const {
// function to calculate angle between object and EP in the 1st quadrant (0,Pi/2)
Double_t dphi = EPAng - objAng;
if( dphi<-1*TMath::Pi() )
dphi = dphi + 1*TMath::Pi();
if( dphi>1*TMath::Pi())
dphi = dphi - 1*TMath::Pi();
if( (dphi>0) && (dphi<1*TMath::Pi()/2) ){
// Do nothing! we are in quadrant 1
}else if( (dphi>1*TMath::Pi()/2) && (dphi<1*TMath::Pi()) ){
dphi = 1*TMath::Pi() - dphi;
}else if( (dphi<0) && (dphi>-1*TMath::Pi()/2) ){
dphi = fabs(dphi);
}else if( (dphi<-1*TMath::Pi()/2) && (dphi>-1*TMath::Pi()) ){
dphi = dphi + 1*TMath::Pi();
}
return dphi; // dphi in [0, Pi/2]
}
TH1* AliAnalysisTaskEmcalTriggerPatchClusterMatch::FillTriggerPatchQA(TH1* h, UInt_t trig, AliEMCALTriggerPatchInfo *fPatch) {
// check and fill a QA histogram
if(fPatch->IsLevel0()) h->Fill(1);
if(fPatch->IsJetLow()) h->Fill(2);
if(fPatch->IsJetHigh()) h->Fill(3);
if(fPatch->IsGammaLow()) h->Fill(4);
if(fPatch->IsGammaHigh()) h->Fill(5);
if(fPatch->IsMainTrigger()) h->Fill(6);
if(fPatch->IsJetLowSimple()) h->Fill(7);
if(fPatch->IsJetHighSimple()) h->Fill(8);
if(fPatch->IsGammaLowSimple()) h->Fill(9);
if(fPatch->IsGammaHighSimple()) h->Fill(10);
if(fPatch->IsMainTriggerSimple()) h->Fill(11);
if(fPatch->IsOfflineSimple()) h->Fill(12);
if(fPatch->IsRecalcJet()) h->Fill(13);
if(fPatch->IsRecalcGamma()) h->Fill(14);
if(trig & AliVEvent::kEMCEJE) h->Fill(19);
if(trig & AliVEvent::kEMCEGA) h->Fill(20);
h->GetXaxis()->SetBinLabel(1, "Level0");
h->GetXaxis()->SetBinLabel(2, "JetLow");
h->GetXaxis()->SetBinLabel(3, "JetHigh");
h->GetXaxis()->SetBinLabel(4, "GammaLow");
h->GetXaxis()->SetBinLabel(5, "GammaHigh");
h->GetXaxis()->SetBinLabel(6, "MainTrigger");
h->GetXaxis()->SetBinLabel(7, "JetLowSimple");
h->GetXaxis()->SetBinLabel(8, "JetHighSimple");
h->GetXaxis()->SetBinLabel(9, "GammaLowSimple");
h->GetXaxis()->SetBinLabel(10, "GammaHighSimple");
h->GetXaxis()->SetBinLabel(11, "MainTriggerSimple");
h->GetXaxis()->SetBinLabel(12, "OfflineSimple");
h->GetXaxis()->SetBinLabel(13, "RecalcJet");
h->GetXaxis()->SetBinLabel(14, "RecalcGamma");
h->GetXaxis()->SetBinLabel(15, "");
h->GetXaxis()->SetBinLabel(16, "");
h->GetXaxis()->SetBinLabel(17, "");
h->GetXaxis()->SetBinLabel(18, "");
h->GetXaxis()->SetBinLabel(19, "kEMCEJE");
h->GetXaxis()->SetBinLabel(20, "kEMCEGA");
// set x-axis labels vertically
//h->LabelsOption("v");
//h->LabelsDeflate("X");
return h;
}
Bool_t AliAnalysisTaskEmcalTriggerPatchClusterMatch::CorrelateToTrigger(Double_t etaclust, Double_t phiclust, TList *triggerpatches) const {
Bool_t hasfound = kFALSE;
for(TIter patchIter = TIter(triggerpatches).Begin(); patchIter != TIter::End(); ++patchIter){
AliEMCALTriggerPatchInfo *mypatch = static_cast<AliEMCALTriggerPatchInfo *>(*patchIter);
Double_t etamin = TMath::Min(mypatch->GetEtaMin(), mypatch->GetEtaMax()),
etamax = TMath::Max(mypatch->GetEtaMin(), mypatch->GetEtaMax()),
phimin = TMath::Min(mypatch->GetPhiMin(), mypatch->GetPhiMax()),
phimax = TMath::Max(mypatch->GetPhiMin(), mypatch->GetPhiMax());
if(etaclust > etamin && etaclust < etamax && phiclust > phimin && phiclust < phimax){
hasfound = kTRUE;
break;
}
}
return hasfound;
}
TH1* AliAnalysisTaskEmcalTriggerPatchClusterMatch::FillEventTriggerQA(TH1* h, UInt_t trig) {
// check and fill a Event Selection QA histogram for different trigger selections after cuts
if(trig == 0) h->Fill(1);
if(trig & AliVEvent::kAny) h->Fill(2);
if(trig & AliVEvent::kAnyINT) h->Fill(3);
if(trig & AliVEvent::kMB) h->Fill(4);
if(trig & AliVEvent::kINT7) h->Fill(5);
if(trig & AliVEvent::kEMC1) h->Fill(6);
if(trig & AliVEvent::kEMC7) h->Fill(7);
if(trig & AliVEvent::kEMC8) h->Fill(8);
if(trig & AliVEvent::kEMCEJE) h->Fill(9);
if(trig & AliVEvent::kEMCEGA) h->Fill(10);
if(trig & AliVEvent::kCentral) h->Fill(11);
if(trig & AliVEvent::kSemiCentral) h->Fill(12);
if(trig & AliVEvent::kINT8) h->Fill(13);
if(trig & (AliVEvent::kEMCEJE | AliVEvent::kMB)) h->Fill(14);
if(trig & (AliVEvent::kEMCEGA | AliVEvent::kMB)) h->Fill(15);
if(trig & (AliVEvent::kAnyINT | AliVEvent::kMB)) h->Fill(16);
if(trig & (AliVEvent::kEMCEJE & (AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral))) h->Fill(17);
if(trig & (AliVEvent::kEMCEGA & (AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral))) h->Fill(18);
if(trig & (AliVEvent::kAnyINT & (AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral))) h->Fill(19);
// label bins of the analysis trigger selection summary
h->GetXaxis()->SetBinLabel(1, "no trigger");
h->GetXaxis()->SetBinLabel(2, "kAny");
h->GetXaxis()->SetBinLabel(3, "kAnyINT");
h->GetXaxis()->SetBinLabel(4, "kMB");
h->GetXaxis()->SetBinLabel(5, "kINT7");
h->GetXaxis()->SetBinLabel(6, "kEMC1");
h->GetXaxis()->SetBinLabel(7, "kEMC7");
h->GetXaxis()->SetBinLabel(8, "kEMC8");
h->GetXaxis()->SetBinLabel(9, "kEMCEJE");
h->GetXaxis()->SetBinLabel(10, "kEMCEGA");
h->GetXaxis()->SetBinLabel(11, "kCentral");
h->GetXaxis()->SetBinLabel(12, "kSemiCentral");
h->GetXaxis()->SetBinLabel(13, "kINT8");
h->GetXaxis()->SetBinLabel(14, "kEMCEJE or kMB");
h->GetXaxis()->SetBinLabel(15, "kEMCEGA or kMB");
h->GetXaxis()->SetBinLabel(16, "kAnyINT or kMB");
h->GetXaxis()->SetBinLabel(17, "kEMCEJE & (kMB or kCentral or kSemiCentral)");
h->GetXaxis()->SetBinLabel(18, "kEMCEGA & (kMB or kCentral or kSemiCentral)");
h->GetXaxis()->SetBinLabel(19, "kAnyINT & (kMB or kCentral or kSemiCentral)");
// set x-axis labels vertically
h->LabelsOption("v");
//h->LabelsDeflate("X");
return h;
}
| 46.059438 | 310 | 0.695679 | maroozm |
1ecca6b25bb8fe54956c9dc44601e315f9d0bf88 | 446 | hpp | C++ | src/Engine.hpp | AgaBuu/TankBotFight | 154b176b697b5d88fffb4b0c9c9c2f8dac334afb | [
"MIT"
] | null | null | null | src/Engine.hpp | AgaBuu/TankBotFight | 154b176b697b5d88fffb4b0c9c9c2f8dac334afb | [
"MIT"
] | null | null | null | src/Engine.hpp | AgaBuu/TankBotFight | 154b176b697b5d88fffb4b0c9c9c2f8dac334afb | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/System/Vector2.hpp>
#include <memory>
enum class Gear { Drive, Neutral, Reverse };
class Engine {
public:
virtual void set_gear(Gear) = 0;
[[nodiscard]] virtual float get_current_speed() const = 0;
[[nodiscard]] virtual sf::Vector2f get_position_delta(float rotation_radians) = 0;
virtual void update() = 0;
[[nodiscard]] virtual std::unique_ptr<Engine> copy() const = 0;
virtual ~Engine() = default;
};
| 29.733333 | 84 | 0.70852 | AgaBuu |
1eccfd96d413a263c0a9a473c59290c595bd7e45 | 1,134 | cpp | C++ | src/csapex_core/src/param/null_parameter.cpp | betwo/csapex | f2c896002cf6bd4eb7fba2903ebeea4a1e811191 | [
"BSD-3-Clause"
] | 21 | 2016-09-02T15:33:25.000Z | 2021-06-10T06:34:39.000Z | src/csapex_core/src/param/null_parameter.cpp | cogsys-tuebingen/csAPEX | e80051384e08d81497d7605e988cab8c19f6280f | [
"BSD-3-Clause"
] | null | null | null | src/csapex_core/src/param/null_parameter.cpp | cogsys-tuebingen/csAPEX | e80051384e08d81497d7605e988cab8c19f6280f | [
"BSD-3-Clause"
] | 10 | 2016-10-12T00:55:17.000Z | 2020-04-24T19:59:02.000Z | /// HEADER
#include <csapex/param/null_parameter.h>
/// PROJECT
#include <csapex/param/register_parameter.h>
#include <csapex/serialization/io/std_io.h>
#include <csapex/utility/yaml.h>
CSAPEX_REGISTER_PARAM(NullParameter)
using namespace csapex;
using namespace param;
NullParameter::NullParameter() : ParameterImplementation("null", ParameterDescription())
{
}
NullParameter::NullParameter(const std::string& name, const ParameterDescription& description) : ParameterImplementation(name, description)
{
}
NullParameter::~NullParameter()
{
}
bool NullParameter::hasState() const
{
return false;
}
const std::type_info& NullParameter::type() const
{
return typeid(void);
}
std::string NullParameter::toStringImpl() const
{
return std::string("[null]");
}
void NullParameter::get_unsafe(std::any& out) const
{
throw std::logic_error("cannot use null parameters");
}
bool NullParameter::set_unsafe(const std::any& /*v*/)
{
throw std::logic_error("cannot use null parameters");
}
void NullParameter::doSerialize(YAML::Node& /*n*/) const
{
}
void NullParameter::doDeserialize(const YAML::Node& /*n*/)
{
}
| 19.551724 | 139 | 0.738095 | betwo |
1ecd18516e68adf3b5710df766cbfee49a1ff29a | 599 | cpp | C++ | Dia2/C-PermutationDescentCounts.cpp | pauolivares/ICPCCL2018 | 72708a14ff5c1911ab87f7b758f131603603c808 | [
"Apache-2.0"
] | null | null | null | Dia2/C-PermutationDescentCounts.cpp | pauolivares/ICPCCL2018 | 72708a14ff5c1911ab87f7b758f131603603c808 | [
"Apache-2.0"
] | null | null | null | Dia2/C-PermutationDescentCounts.cpp | pauolivares/ICPCCL2018 | 72708a14ff5c1911ab87f7b758f131603603c808 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
long long dp[101][101];
long long mod = 1001113;
long long solve(long long a,long long b){
if(a==0 && b== 0) return 1;
if(b==0 ) return 1;
if(b>=a) return 0;
if(dp[a][b]!=-1) return dp[a][b];
return dp[a][b] = (((a-b)*solve(a-1,b-1))%mod + ((b+1)*solve(a-1,b))%mod)%mod;
}
int main(){
long long t;
for(long long i=0;i<101;i++){
for(long long j=0;j<101;j++){
dp[i][j]=-1;
}
}
dp[1][0]=1;
dp[1][1]=1;
cin>>t;
while(t--){
long long a,b,c;
cin>>a>>b>>c;
cout<<a<<" "<<solve(b,c)<<endl;
}
return 0;
}
| 18.71875 | 80 | 0.512521 | pauolivares |
1ecf5c4fb5a9e61cd9cf632b2401608d24e6c28b | 1,332 | hpp | C++ | include/tweedledum/utils/hash.hpp | AriJordan/tweedledum | 9f98aad8cb01587854247eb755ecf4a1eec41941 | [
"MIT"
] | null | null | null | include/tweedledum/utils/hash.hpp | AriJordan/tweedledum | 9f98aad8cb01587854247eb755ecf4a1eec41941 | [
"MIT"
] | null | null | null | include/tweedledum/utils/hash.hpp | AriJordan/tweedledum | 9f98aad8cb01587854247eb755ecf4a1eec41941 | [
"MIT"
] | null | null | null | /*--------------------------------------------------------------------------------------------------
| This file is distributed under the MIT License.
| See accompanying file /LICENSE for details.
*-------------------------------------------------------------------------------------------------*/
#pragma once
#include <functional>
#include <set>
#include <vector>
namespace tweedledum {
template<typename T>
struct hash : public std::hash<T> {};
template<>
struct hash<std::set<uint32_t>> {
using argument_type = std::set<uint32_t>;
using result_type = size_t;
void combine(std::size_t& seed, uint32_t const& v) const
{
seed ^= std::hash<uint32_t>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
result_type operator()(argument_type const& in) const
{
result_type seed = 0;
for (auto& element : in) {
combine(seed, element);
}
return seed;
}
};
template<>
struct hash<std::vector<uint32_t>> {
using argument_type = std::vector<uint32_t>;
using result_type = size_t;
void combine(std::size_t& seed, uint32_t const& v) const
{
seed ^= std::hash<uint32_t>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
result_type operator()(argument_type const& in) const
{
result_type seed = 0;
for (auto& element : in) {
combine(seed, element);
}
return seed;
}
};
} // namespace tweedledum
| 23.368421 | 100 | 0.567568 | AriJordan |
1ed0f2023f31e1426b8dc324ab909ba7ed20edde | 1,237 | hpp | C++ | 9_ranges/filter.hpp | rgrover/yap-demos | d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928 | [
"BSD-2-Clause"
] | null | null | null | 9_ranges/filter.hpp | rgrover/yap-demos | d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928 | [
"BSD-2-Clause"
] | null | null | null | 9_ranges/filter.hpp | rgrover/yap-demos | d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928 | [
"BSD-2-Clause"
] | null | null | null | #ifndef _FILTER_HPP
#define _FILTER_HPP
#include "range.hpp"
#include "range_expr.hpp"
#include <boost/yap/algorithm.hpp>
#include <boost/callable_traits/args.hpp>
#include <boost/callable_traits/return_type.hpp>
#include <boost/callable_traits/function_type.hpp>
#include <type_traits>
template <typename Predicate>
struct filter_function
{
Predicate predicate;
};
template <boost::yap::expr_kind Kind, typename Tuple>
struct filter_expr {
constexpr static boost::yap::expr_kind kind = Kind;
Tuple elements;
};
BOOST_YAP_USER_BINARY_OPERATOR(shift_left_assign, filter_expr, range_expr)
template <typename Predicate>
constexpr auto filter(Predicate&& predicate)
{
using arg_type = boost::callable_traits::args_t<Predicate>;
using return_type = boost::callable_traits::return_type_t<Predicate>;
static_assert(std::tuple_size_v<arg_type> == 1,
"Predicate argument for filter needs to take one argument");
static_assert(std::is_same_v<return_type, bool>,
"Predicate argument for filter needs to return a bool");
return boost::yap::make_terminal<filter_expr>(filter_function<Predicate>{std::forward<Predicate>(predicate)});
}
#endif //_FILTER_HPP
| 28.767442 | 114 | 0.742926 | rgrover |
1ed10d782a2f461a5471e60cc06762abc511c0dc | 20,585 | cc | C++ | src/CCA/Components/Arches/Properties.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | 2 | 2021-12-17T05:50:44.000Z | 2021-12-22T21:37:32.000Z | src/CCA/Components/Arches/Properties.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | null | null | null | src/CCA/Components/Arches/Properties.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | 1 | 2020-11-30T04:46:05.000Z | 2020-11-30T04:46:05.000Z | /*
* The MIT License
*
* Copyright (c) 1997-2020 The University of Utah
*
* 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.
*/
//----- Properties.cc --------------------------------------------------
#include <CCA/Components/Arches/Properties.h>
#include <CCA/Components/Arches/ArchesLabel.h>
# include <CCA/Components/Arches/ChemMix/ClassicTableInterface.h>
# include <CCA/Components/Arches/ChemMix/ColdFlow.h>
# include <CCA/Components/Arches/ChemMix/ConstantProps.h>
#include <CCA/Components/Arches/ArchesMaterial.h>
#include <CCA/Components/Arches/CellInformationP.h>
#include <CCA/Components/Arches/CellInformation.h>
#include <CCA/Components/Arches/PhysicalConstants.h>
#include <CCA/Components/Arches/TimeIntegratorLabel.h>
#include <CCA/Components/MPMArches/MPMArchesLabel.h>
#include <CCA/Components/Arches/TransportEqns/EqnFactory.h>
#include <CCA/Components/Arches/TransportEqns/EqnBase.h>
#include <CCA/Ports/Scheduler.h>
#include <CCA/Ports/DataWarehouse.h>
#include <Core/Grid/Variables/PerPatch.h>
#include <Core/Grid/Variables/CellIterator.h>
#include <Core/Grid/Variables/VarTypes.h>
#include <Core/Grid/MaterialManager.h>
#include <Core/Exceptions/InvalidValue.h>
#include <Core/Exceptions/ProblemSetupException.h>
#include <Core/Exceptions/VariableNotFoundInGrid.h>
#include <Core/Math/MiscMath.h>
#include <Core/Parallel/Parallel.h>
#include <Core/Parallel/ProcessorGroup.h>
#include <Core/ProblemSpec/ProblemSpec.h>
#include <iostream>
using namespace std;
using namespace Uintah;
//****************************************************************************
// Default constructor for Properties
//****************************************************************************
Properties::Properties(ArchesLabel* label,
const MPMArchesLabel* MAlb,
PhysicalConstants* phys_const,
const ProcessorGroup* myworld):
d_lab(label), d_MAlab(MAlb),
d_physicalConsts(phys_const),
d_myworld(myworld)
{
}
//****************************************************************************
// Destructor
//****************************************************************************
Properties::~Properties()
{
if ( mixModel == "TabProps" || mixModel == "ClassicTable"
|| mixModel == "ColdFlow" || mixModel == "ConstantProps" ){
delete d_mixingRxnTable;
}
}
//****************************************************************************
// Problem Setup for Properties
//****************************************************************************
void
Properties::problemSetup(const ProblemSpecP& params)
{
ProblemSpecP db = params->findBlock("Properties");
if ( db == nullptr ){
throw ProblemSetupException("Error: Please specify a <Properties> section in <Arches>.", __FILE__, __LINE__);
}
db->getWithDefault("filter_drhodt", d_filter_drhodt, false);
db->getWithDefault("first_order_drhodt", d_first_order_drhodt, true);
db->getWithDefault("inverse_density_average",d_inverse_density_average,false);
d_denRef = d_physicalConsts->getRefPoint();
// check to see if gas is adiabatic and (if DQMOM) particles are not:
d_adiabGas_nonadiabPart = false;
if (params->findBlock("DQMOM")) {
ProblemSpecP db_dqmom = params->findBlock("DQMOM");
db_dqmom->getWithDefault("adiabGas_nonadiabPart", d_adiabGas_nonadiabPart, false);
}
// // read type of mixing model
// mixModel = "NA";
// if (db->findBlock("ClassicTable"))
// mixModel = "ClassicTable";
// else if (db->findBlock("ColdFlow"))
// mixModel = "ColdFlow";
// else if (db->findBlock("ConstantProps"))
// mixModel = "ConstantProps";
// #if HAVE_TABPROPS
// else if (db->findBlock("TabProps"))
// mixModel = "TabProps";
// #endif
// else
// throw InvalidValue("ERROR!: No mixing/reaction table specified! If you are attempting to use the new TabProps interface, ensure that you configured properly with TabProps and Boost libs.",__FILE__,__LINE__);
//
// MaterialManagerP& materialManager = d_lab->d_materialManager;
//
// if (mixModel == "ClassicTable") {
//
// // New Classic interface
// d_mixingRxnTable = scinew ClassicTableInterface( materialManager );
// d_mixingRxnTable->problemSetup( db );
// } else if (mixModel == "ColdFlow") {
// d_mixingRxnTable = scinew ColdFlow( materialManager );
// d_mixingRxnTable->problemSetup( db );
// } else if (mixModel == "ConstantProps" ) {
// d_mixingRxnTable = scinew ConstantProps( materialManager );
// d_mixingRxnTable->problemSetup( db );
// }
// #if HAVE_TABPROPS
// else if (mixModel == "TabProps") {
// // New TabPropsInterface stuff...
// d_mixingRxnTable = scinew TabPropsInterface( materialManager );
// d_mixingRxnTable->problemSetup( db );
// }
// #endif
// else{
// throw InvalidValue("Mixing Model not supported: " + mixModel, __FILE__, __LINE__);
// }
}
//****************************************************************************
// Schedule the averaging of properties for Runge-Kutta step
//****************************************************************************
void
Properties::sched_averageRKProps( SchedulerP& sched, const PatchSet* patches,
const MaterialSet* matls,
const TimeIntegratorLabel* timelabels )
{
string taskname = "Properties::averageRKProps" +
timelabels->integrator_step_name;
Task* tsk = scinew Task(taskname, this,
&Properties::averageRKProps,
timelabels);
Ghost::GhostType gn = Ghost::None;
tsk->requires(Task::OldDW, d_lab->d_densityCPLabel, gn, 0);
tsk->requires(Task::NewDW, d_lab->d_densityTempLabel, gn, 0);
tsk->requires(Task::NewDW, d_lab->d_densityCPLabel, gn, 0);
tsk->modifies(d_lab->d_densityGuessLabel);
sched->addTask(tsk, patches, matls);
}
//****************************************************************************
// Actually average the Runge-Kutta properties here
//****************************************************************************
void
Properties::averageRKProps( const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset*,
DataWarehouse* old_dw,
DataWarehouse* new_dw,
const TimeIntegratorLabel* timelabels )
{
for (int p = 0; p < patches->size(); p++) {
const Patch* patch = patches->get(p);
int archIndex = 0; // only one arches material
int indx = d_lab->d_materialManager->
getMaterial( "Arches", archIndex)->getDWIndex();
constCCVariable<double> old_density;
constCCVariable<double> rho1_density;
constCCVariable<double> new_density;
CCVariable<double> density_guess;
Ghost::GhostType gn = Ghost::None;
old_dw->get(old_density, d_lab->d_densityCPLabel, indx, patch, gn, 0);
new_dw->get(rho1_density, d_lab->d_densityTempLabel, indx, patch, gn, 0);
new_dw->get(new_density, d_lab->d_densityCPLabel, indx, patch, gn, 0);
new_dw->getModifiable(density_guess, d_lab->d_densityGuessLabel, indx, patch);
double factor_old, factor_new, factor_divide;
factor_old = timelabels->factor_old;
factor_new = timelabels->factor_new;
factor_divide = timelabels->factor_divide;
IntVector indexLow = patch->getExtraCellLowIndex();
IntVector indexHigh = patch->getExtraCellHighIndex();
for (int colZ = indexLow.z(); colZ < indexHigh.z(); colZ ++) {
for (int colY = indexLow.y(); colY < indexHigh.y(); colY ++) {
for (int colX = indexLow.x(); colX < indexHigh.x(); colX ++) {
IntVector currCell(colX, colY, colZ);
if (new_density[currCell] > 0.0) {
double predicted_density;
if (old_density[currCell] > 0.0) {
//predicted_density = rho1_density[currCell];
if (d_inverse_density_average)
predicted_density = 1.0/((factor_old/old_density[currCell] + factor_new/new_density[currCell])/factor_divide);
else
predicted_density = (factor_old*old_density[currCell] + factor_new*new_density[currCell])/factor_divide;
} else {
predicted_density = new_density[currCell];
}
density_guess[currCell] = predicted_density;
}
}
}
}
}
}
//****************************************************************************
// Schedule saving of temp density
//****************************************************************************
void
Properties::sched_saveTempDensity(SchedulerP& sched,
const PatchSet* patches,
const MaterialSet* matls,
const TimeIntegratorLabel* timelabels)
{
string taskname = "Properties::saveTempDensity" +
timelabels->integrator_step_name;
Task* tsk = scinew Task(taskname, this,
&Properties::saveTempDensity,
timelabels);
tsk->requires(Task::NewDW, d_lab->d_densityCPLabel, Ghost::None, 0);
tsk->modifies(d_lab->d_densityTempLabel);
sched->addTask(tsk, patches, matls);
}
//****************************************************************************
// Actually save temp density here
//****************************************************************************
void
Properties::saveTempDensity(const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset*,
DataWarehouse*,
DataWarehouse* new_dw,
const TimeIntegratorLabel* )
{
for (int p = 0; p < patches->size(); p++) {
const Patch* patch = patches->get(p);
int archIndex = 0; // only one arches material
int indx = d_lab->d_materialManager->
getMaterial( "Arches", archIndex)->getDWIndex();
CCVariable<double> temp_density;
new_dw->getModifiable(temp_density, d_lab->d_densityTempLabel,indx, patch);
new_dw->copyOut(temp_density, d_lab->d_densityCPLabel, indx, patch);
}
}
//****************************************************************************
// Schedule the computation of drhodt
//****************************************************************************
void
Properties::sched_computeDrhodt(SchedulerP& sched,
const PatchSet* patches,
const MaterialSet* matls,
const TimeIntegratorLabel* timelabels)
{
string taskname = "Properties::computeDrhodt" +
timelabels->integrator_step_name;
Task* tsk = scinew Task(taskname, this,
&Properties::computeDrhodt,
timelabels);
tsk->requires( Task::OldDW, d_lab->d_timeStepLabel );
Task::WhichDW parent_old_dw;
if (timelabels->recursion){
parent_old_dw = Task::ParentOldDW;
}else{
parent_old_dw = Task::OldDW;
}
Ghost::GhostType gn = Ghost::None;
Ghost::GhostType ga = Ghost::AroundCells;
tsk->requires(Task::NewDW, d_lab->d_cellInfoLabel, gn);
tsk->requires(parent_old_dw, d_lab->d_delTLabel);
tsk->requires(parent_old_dw, d_lab->d_oldDeltaTLabel);
tsk->requires(Task::NewDW , d_lab->d_densityCPLabel , gn , 0);
tsk->requires(parent_old_dw , d_lab->d_densityCPLabel , gn , 0);
tsk->requires(Task::NewDW , d_lab->d_filterVolumeLabel , ga , 1);
tsk->requires(Task::NewDW , d_lab->d_cellTypeLabel , ga , 1);
//tsk->requires(Task::NewDW, VarLabel::find("mixture_fraction"), gn, 0);
if ( timelabels->integrator_step_number == TimeIntegratorStepNumber::First ) {
tsk->computes(d_lab->d_filterdrhodtLabel);
tsk->computes(d_lab->d_oldDeltaTLabel);
}
else{
tsk->modifies(d_lab->d_filterdrhodtLabel);
}
sched->addTask(tsk, patches, matls);
}
//****************************************************************************
// Compute drhodt
//****************************************************************************
void
Properties::computeDrhodt(const ProcessorGroup* pc,
const PatchSubset* patches,
const MaterialSubset*,
DataWarehouse* old_dw,
DataWarehouse* new_dw,
const TimeIntegratorLabel* timelabels)
{
// int timeStep = m_materialManager->getCurrentTopLevelTimeStep();
timeStep_vartype timeStep;
old_dw->get( timeStep, d_lab->d_timeStepLabel );
DataWarehouse* parent_old_dw;
if (timelabels->recursion){
parent_old_dw = new_dw->getOtherDataWarehouse(Task::ParentOldDW);
}else{
parent_old_dw = old_dw;
}
int drhodt_1st_order = 1;
if (d_MAlab){
drhodt_1st_order = 2;
}
delt_vartype delT, old_delT;
parent_old_dw->get(delT, d_lab->d_delTLabel );
if (timelabels->integrator_step_number == TimeIntegratorStepNumber::First){
new_dw->put(delT, d_lab->d_oldDeltaTLabel);
}
double delta_t = delT;
delta_t *= timelabels->time_multiplier;
delta_t *= timelabels->time_position_multiplier_after_average;
parent_old_dw->get(old_delT, d_lab->d_oldDeltaTLabel);
double old_delta_t = old_delT;
//__________________________________
for (int p = 0; p < patches->size(); p++) {
const Patch* patch = patches->get(p);
int archIndex = 0; // only one arches material
int indx = d_lab->d_materialManager->
getMaterial( "Arches", archIndex)->getDWIndex();
constCCVariable<double> new_density;
constCCVariable<double> old_density;
constCCVariable<double> old_old_density;
//constCCVariable<double> mf;
CCVariable<double> drhodt;
CCVariable<double> filterdrhodt;
constCCVariable<double> filterVolume;
constCCVariable<int> cellType;
Ghost::GhostType gn = Ghost::None;
Ghost::GhostType ga = Ghost::AroundCells;
parent_old_dw->get(old_density, d_lab->d_densityCPLabel, indx, patch,gn, 0);
new_dw->get( cellType, d_lab->d_cellTypeLabel, indx, patch, ga, 1 );
new_dw->get( filterVolume, d_lab->d_filterVolumeLabel, indx, patch, ga, 1 );
//new_dw->get( mf, VarLabel::find("mixture_fraction"), indx, patch, gn, 0);
PerPatch<CellInformationP> cellInfoP;
new_dw->get(cellInfoP, d_lab->d_cellInfoLabel, indx, patch);
CellInformation* cellinfo = cellInfoP.get().get_rep();
new_dw->get(new_density, d_lab->d_densityCPLabel, indx, patch, gn, 0);
if ( timelabels->integrator_step_number == TimeIntegratorStepNumber::First ){
new_dw->allocateAndPut(filterdrhodt, d_lab->d_filterdrhodtLabel, indx, patch);
}else{
new_dw->getModifiable(filterdrhodt, d_lab->d_filterdrhodtLabel, indx, patch);
}
filterdrhodt.initialize(0.0);
// Get the patch and variable indices
IntVector idxLo = patch->getFortranCellLowIndex();
IntVector idxHi = patch->getFortranCellHighIndex();
// compute drhodt and its filtered value
drhodt.allocate(patch->getExtraCellLowIndex(), patch->getExtraCellHighIndex());
drhodt.initialize(0.0);
//__________________________________
if ((d_first_order_drhodt)||(timeStep <= (unsigned int)drhodt_1st_order)) {
// 1st order drhodt
for (int kk = idxLo.z(); kk <= idxHi.z(); kk++) {
for (int jj = idxLo.y(); jj <= idxHi.y(); jj++) {
for (int ii = idxLo.x(); ii <= idxHi.x(); ii++) {
IntVector currcell(ii,jj,kk);
double vol =cellinfo->sns[jj]*cellinfo->stb[kk]*cellinfo->sew[ii];
//double rho_f = 1.18;
//double rho_ox = 0.5;
//double newnewrho = mf[currcell]/rho_ox + (1.0 - mf[currcell])/rho_f;
drhodt[currcell] = (new_density[currcell] -
old_density[currcell])*vol/delta_t;
//drhodt[currcell] = (newnewrho - old_density[currcell]*vol/delta_t);
}
}
}
}
else {
// 2nd order drhodt, assuming constant volume
double factor = 1.0 + old_delta_t/delta_t;
double new_factor = factor * factor - 1.0;
double old_factor = factor * factor;
for (int kk = idxLo.z(); kk <= idxHi.z(); kk++) {
for (int jj = idxLo.y(); jj <= idxHi.y(); jj++) {
for (int ii = idxLo.x(); ii <= idxHi.x(); ii++) {
IntVector currcell(ii,jj,kk);
double vol =cellinfo->sns[jj]*cellinfo->stb[kk]*cellinfo->sew[ii];
drhodt[currcell] = (new_factor*new_density[currcell] -
old_factor*old_density[currcell] +
old_old_density[currcell])*vol /
(old_delta_t*factor);
//double rho_f = 1.18;
//double rho_ox = 0.5;
//double newnewrho = mf[currcell]/rho_f + (1.0 - mf[currcell])/rho_ox;
}
}
}
}
if ((d_filter_drhodt)&&(!(d_3d_periodic))) {
// filtering for periodic case is not implemented
// if it needs to be then drhodt will require 1 layer of boundary cells to be computed
d_filter->applyFilter_noPetsc<CCVariable<double> >(pc, patch, drhodt, filterVolume, cellType, filterdrhodt);
}else{
filterdrhodt.copy(drhodt, drhodt.getLowIndex(),
drhodt.getHighIndex());
}
for (int kk = idxLo.z(); kk <= idxHi.z(); kk++) {
for (int jj = idxLo.y(); jj <= idxHi.y(); jj++) {
for (int ii = idxLo.x(); ii <= idxHi.x(); ii++) {
IntVector currcell(ii,jj,kk);
double vol =cellinfo->sns[jj]*cellinfo->stb[kk]*cellinfo->sew[ii];
if (Abs(filterdrhodt[currcell]/vol) < 1.0e-9){
filterdrhodt[currcell] = 0.0;
}
}
}
}
}
}
void
Properties::sched_computeProps( const LevelP& level,
SchedulerP& sched,
const bool initialize,
const bool modify_ref_den,
const int time_substep )
{
// this method is temporary while we get rid of properties.cc
d_mixingRxnTable->sched_getState( level, sched, time_substep, initialize, modify_ref_den );
}
void
Properties::sched_checkTableBCs( const LevelP& level,
SchedulerP& sched )
{
d_mixingRxnTable->sched_checkTableBCs( level, sched );
}
void
Properties::addLookupSpecies( ){
ChemHelper& helper = ChemHelper::self();
std::vector<std::string> sps;
sps = helper.model_req_species;
if ( mixModel == "ClassicTable" || mixModel == "TabProps"
|| "ColdFlow" || "ConstantProps" ) {
for ( vector<string>::iterator i = sps.begin(); i != sps.end(); i++ ){
bool test = d_mixingRxnTable->insertIntoMap( *i );
if ( !test ){
throw InvalidValue("Error: Cannot locate the following variable for lookup in the table: "+*i, __FILE__, __LINE__ );
}
}
}
std::vector<std::string> old_sps;
old_sps = helper.model_req_old_species;
if ( mixModel == "ClassicTable" || mixModel == "TabProps"
|| "ColdFlow" || "ConstantProps") {
for ( vector<string>::iterator i = old_sps.begin(); i != old_sps.end(); i++ ){
d_mixingRxnTable->insertOldIntoMap( *i );
}
}
}
void
Properties::doTableMatching(){
d_mixingRxnTable->tableMatching();
}
| 38.12037 | 214 | 0.595579 | damu1000 |
1ed1f24df57c20bbed87b228585b3e7dce5e5730 | 1,982 | cc | C++ | pw_rpc/fake_channel_output.cc | ffzwadd/pigweed | 75e038f0d852b310d135b93061bc769cb8bf90c4 | [
"Apache-2.0"
] | null | null | null | pw_rpc/fake_channel_output.cc | ffzwadd/pigweed | 75e038f0d852b310d135b93061bc769cb8bf90c4 | [
"Apache-2.0"
] | null | null | null | pw_rpc/fake_channel_output.cc | ffzwadd/pigweed | 75e038f0d852b310d135b93061bc769cb8bf90c4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The Pigweed Authors
//
// 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
//
// https://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 "pw_rpc_private/fake_channel_output.h"
#include "pw_assert/check.h"
#include "pw_result/result.h"
#include "pw_rpc/internal/packet.h"
namespace pw::rpc::internal::test {
void FakeChannelOutput::clear() {
ClearResponses();
total_responses_ = 0;
last_status_ = Status::Unknown();
done_ = false;
}
Status FakeChannelOutput::SendAndReleaseBuffer(
std::span<const std::byte> buffer) {
PW_CHECK_PTR_EQ(buffer.data(), packet_buffer_.data());
// If the buffer is empty, this is just releasing an unused buffer.
if (buffer.empty()) {
return OkStatus();
}
PW_CHECK(!done_);
Result<Packet> result = Packet::FromBuffer(buffer);
PW_CHECK_OK(result.status());
last_status_ = result.value().status();
switch (result.value().type()) {
case PacketType::RESPONSE:
// Server streaming RPCs don't have a payload in their response packet.
if (!server_streaming_) {
ProcessResponse(result.value().payload());
}
done_ = true;
break;
case PacketType::SERVER_ERROR:
PW_CRASH("Server error: %s", result.value().status().str());
case PacketType::SERVER_STREAM:
ProcessResponse(result.value().payload());
break;
default:
PW_CRASH("Unhandled PacketType %d",
static_cast<int>(result.value().type()));
}
return OkStatus();
}
} // namespace pw::rpc::internal::test
| 29.58209 | 80 | 0.692735 | ffzwadd |
1ed31cfaff50f31ffc6baa199f9a6071773c54ea | 1,054 | cpp | C++ | src/6_2_voxel_grid.cpp | liwind/PCL_Example | 9f807412ecf8110e0e05d5f41df31335a1c7d4ae | [
"MIT"
] | 2 | 2019-12-05T15:05:11.000Z | 2021-04-17T09:15:04.000Z | src/6_2_voxel_grid.cpp | liwind/PCL_Example | 9f807412ecf8110e0e05d5f41df31335a1c7d4ae | [
"MIT"
] | null | null | null | src/6_2_voxel_grid.cpp | liwind/PCL_Example | 9f807412ecf8110e0e05d5f41df31335a1c7d4ae | [
"MIT"
] | 2 | 2019-12-05T15:05:15.000Z | 2021-04-18T01:57:24.000Z | #include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/PCLPointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
using namespace std;
int main(int argc, char** argv)
{
pcl::PCLPointCloud2::Ptr cloud(new pcl::PCLPointCloud2());
pcl::PCLPointCloud2::Ptr cloud_filtered(new pcl::PCLPointCloud2());
pcl::PCDReader reader;
reader.read("../data/table_scene_lms400.pcd", *cloud);
std::cerr << "PointCloud before filtering: " << cloud->width * cloud->height
<< " data points (" << pcl::getFieldsList(*cloud) << ").\n";
pcl::VoxelGrid<pcl::PCLPointCloud2> vg;
vg.setInputCloud(cloud);
vg.setLeafSize(0.1f, 0.1f, 0.1f);
vg.filter(*cloud_filtered);
std::cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height
<< " data points (" << pcl::getFieldsList(*cloud_filtered) << ").";
pcl::PCDWriter writer;
writer.write("../data/table_scene_lms400_downsampled.pcd", *cloud_filtered,
Eigen::Vector4f::Zero(), Eigen::Quaternionf::Identity(), false);
system("pause");
return (0);
}
| 31.939394 | 94 | 0.701139 | liwind |
1ed9532e2da37d7fb8b2fe6f2e25983f51b0106e | 5,492 | cpp | C++ | src/wcmodel.cpp | anrichter/qsvn | d048023ddcf7c23540cdde47096c2187b19e3710 | [
"MIT"
] | 22 | 2015-02-12T07:38:09.000Z | 2021-11-03T07:42:39.000Z | src/wcmodel.cpp | anrichter/qsvn | d048023ddcf7c23540cdde47096c2187b19e3710 | [
"MIT"
] | null | null | null | src/wcmodel.cpp | anrichter/qsvn | d048023ddcf7c23540cdde47096c2187b19e3710 | [
"MIT"
] | 17 | 2015-01-26T01:11:51.000Z | 2020-10-29T10:00:28.000Z | /********************************************************************************
* This file is part of QSvn Project http://www.anrichter.net/projects/qsvn *
* Copyright (c) 2004-2010 Andreas Richter <ar@anrichter.net> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License Version 2 *
* as published by the Free Software Foundation. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*******************************************************************************/
//QSvn
#include "config.h"
#include "wcmodel.h"
#include "wcmodel.moc"
//SvnCpp
#include "svnqt/wc.hpp"
//Qt
#include <QtGui>
WcModel::WcModel(QObject *parent)
: QStandardItemModel(parent)
{
setHorizontalHeaderLabels(QStringList("Working Copy"));
loadWcList();
}
WcModel::~WcModel()
{
saveWcList();
}
bool WcModel::hasChildren(const QModelIndex &parent) const
{
if (!parent.isValid())
return true;
else {
QStandardItem *_item = itemFromIndex(parent);
if (!_item->data(PopulatedRole).toBool())
populate(_item);
return _item->rowCount();
}
}
void WcModel::populate(QStandardItem * parent) const
{
parent->removeRows(0, parent->rowCount());
foreach (QString _dir, QDir(parent->data(PathRole).toString()).entryList(QDir::AllDirs).filter(QRegExp("^[^.]")))
insertDir(_dir, parent, parent->rowCount());
parent->setData(true, PopulatedRole);
}
void WcModel::insertWc(QString dir)
{
dir = QDir::toNativeSeparators(QDir::cleanPath(dir));
int row = 0;
for (int i = 0; i < invisibleRootItem()->rowCount(); i++)
{
if (dir > getPath(invisibleRootItem()->child(i)->index()))
row = i + 1;
}
insertDir(dir, invisibleRootItem(), row);
}
void WcModel::removeWc(QString dir)
{
foreach(QStandardItem* _item, findItems(dir))
{
removeRow(_item->row(), _item->index().parent());
}
}
void WcModel::updateWc(QString dir)
{
QStandardItem *_item = itemFromDirectory(dir);
if (_item)
populate(_item->parent());
}
QString WcModel::getPath(const QModelIndex &index) const
{
return itemFromIndex(index)->data(PathRole).toString();
}
void WcModel::insertDir(QString dir, QStandardItem * parent, int row) const
{
QStandardItem *item = new QStandardItem();
item->setText(QDir::toNativeSeparators(QDir::cleanPath(dir)));
//complete dir in data(PathRole) to full path for subdirectories of root-wc-items
if (parent != invisibleRootItem())
dir = parent->data(PathRole).toString() + QDir::separator() + dir;
item->setData(QDir::toNativeSeparators(dir), PathRole);
if (svn::Wc::checkWc(dir.toLocal8Bit()))
item->setIcon(QIcon(":/images/folder.png"));
else
item->setIcon(QIcon(":/images/unknownfolder.png"));
parent->insertRow(row, item);
}
void WcModel::saveWcList()
{
QStringList wcList;
for (int i = 0; i < invisibleRootItem()->rowCount(); i++)
wcList << invisibleRootItem()->child(i)->data(PathRole).toString();
Config::instance()->saveStringList("workingCopies", wcList);
}
void WcModel::loadWcList()
{
QStringList wcList = Config::instance()->getStringList("workingCopies");
wcList.sort();
foreach (QString wc, wcList)
insertDir(wc, invisibleRootItem(), invisibleRootItem()->rowCount());
}
void WcModel::doCollapse(const QModelIndex & index)
{
itemFromIndex(index)->setData(false, PopulatedRole);
}
QStandardItem * WcModel::itemFromDirectory(const QString dir, const QStandardItem * parent)
{
if (parent)
{
for (int i = 0; i < parent->rowCount(); i++)
{
if (parent->child(i)->data(PathRole) == dir)
return parent->child(i);
}
//search recursive
QStandardItem *_result;
for (int i = 0; i < parent->rowCount(); i++)
{
_result = itemFromDirectory(dir, parent->child(i));
if (_result)
return _result;
}
}
else
{
for (int i = 0; i < rowCount(); i++)
{
if (item(i)->data(PathRole) == dir)
return item(i);
}
//search recursive
QStandardItem *_result;
for (int i = 0; i < rowCount(); i++)
{
_result = itemFromDirectory(dir, item(i));
if (_result)
return _result;
}
}
return 0;
}
| 31.028249 | 117 | 0.5437 | anrichter |
1eda477cefef2a4c78c409045f5588eaf7277aec | 9,855 | cpp | C++ | src/ExpressionContext.cpp | VincentPT/xpression | 3aed63a899e20ac0fe36eaa090f49f1ed85e4673 | [
"MIT"
] | null | null | null | src/ExpressionContext.cpp | VincentPT/xpression | 3aed63a899e20ac0fe36eaa090f49f1ed85e4673 | [
"MIT"
] | null | null | null | src/ExpressionContext.cpp | VincentPT/xpression | 3aed63a899e20ac0fe36eaa090f49f1ed85e4673 | [
"MIT"
] | null | null | null | #include "ExpressionContext.h"
#include "SimpleCompilerSuite.h"
#include "xutility.h"
#include <string.h>
#include <DefaultPreprocessor.h>
#include <CLamdaProg.h>
#include <Program.h>
#include <string>
#include <list>
#include "VariableManager.h"
#include "ExpressionGlobalScope.h"
#include "ExpressionInternal.h"
namespace xpression {
#if _WIN32 || _WIN64
__declspec(thread) ExpressionContext* _threadExpressionContext = nullptr;
// Check GCC
#elif __GNUC__
__thread ExpressionContext* _threadExpressionContext = nullptr;
#endif
class ExpressionEventManager {
std::list<ExpressionEventHandler*> _handlers;
public:
void addHandler(ExpressionEventHandler* handler) {
_handlers.push_back(handler);
}
void removeHandler(ExpressionEventHandler* handler) {
_handlers.remove(handler);
}
void notifyUpdate() {
for(auto hander : _handlers) {
hander->onRequestUpdate();
}
}
};
class ExpressionGlobalScopeCreator : public GlobalScopeCreator {
std::function<ffscript::GlobalScope*(int, ffscript::ScriptCompiler*)> _funcCreator;
public:
ExpressionGlobalScopeCreator(std::function<ffscript::GlobalScope*(int, ffscript::ScriptCompiler*)>&& fx) : _funcCreator(fx) {}
ffscript::GlobalScope* create(int stackSize, ffscript::ScriptCompiler* scriptCompiler) {
return _funcCreator(stackSize, scriptCompiler);
}
};
ExpressionContext::ExpressionContext(int stackSize) :
_pRawProgram(nullptr), _allocatedDataSize(0), _allocatedScopeSize(0),
_pVariableManager(nullptr), _needUpdateVariable(false),
_needRunGlobalCode(false), _needRegenerateCode(false) {
ExpressionGlobalScopeCreator globalScopeCreator([this](int stackSize, ffscript::ScriptCompiler* scriptCompiler){
return new ExpressionGlobalScope(this, stackSize, scriptCompiler);
});
_pCompilerSuite = new SimpleCompilerSuite(stackSize, &globalScopeCreator);
_pCompilerSuite->setPreprocessor(std::make_shared<DefaultPreprocessor>());
_userData.data = nullptr;
_userData.dt = UserDataType::NotUsed;
_pVariableManager = new VariableManager(_pCompilerSuite->getGlobalScope()->getContext());
_eventManager = new ExpressionEventManager();
}
ExpressionContext::~ExpressionContext() {
if(_pRawProgram) {
delete _pRawProgram;
}
if(_pCompilerSuite) {
delete _pCompilerSuite;
}
if(_pVariableManager) {
delete _pVariableManager;
}
if(_eventManager) {
delete _eventManager;
}
}
SimpleCompilerSuite* ExpressionContext::getCompilerSuite() const {
return _pCompilerSuite;
}
ExpressionContext* ExpressionContext::getCurrentContext() {
return _threadExpressionContext;
}
void ExpressionContext::setCurrentContext(ExpressionContext* pContext) {
_threadExpressionContext = pContext;
}
void ExpressionContext::setCustomScript(const wchar_t* customScript) {
if(_pRawProgram) {
throw std::runtime_error("custom script is already available");
}
auto len = wcslen(customScript);
_pRawProgram = _pCompilerSuite->compileProgram(customScript, customScript + len);
// check if the compiling process is failed...
if (_pRawProgram == nullptr) {
// ...then get error information
// then shows to user
int line, column;
_pCompilerSuite->getLastCompliedPosition(line, column);
string errorMsg("error at line = ");
errorMsg.append(std::to_string(line + 1));
errorMsg.append(", column = ");
errorMsg.append(std::to_string(column + 1));
errorMsg.append(" msg: ");
errorMsg.append(_pCompilerSuite->getCompiler()->getLastError());
throw std::runtime_error(errorMsg);
}
_needRunGlobalCode = true;
}
void ExpressionContext::startEvaluating() {
if(_pVariableManager && _needUpdateVariable) {
_pVariableManager->requestUpdateVariables();
_pVariableManager->checkVariablesFullFilled();
// all registered variables are updated now
_needUpdateVariable = false;
}
auto globalScope = _pCompilerSuite->getGlobalScope();
if(_needRegenerateCode && _pRawProgram) {
_pRawProgram->resetExcutors();
_pRawProgram->resetFunctionMap();
if(!globalScope->extractCode(_pRawProgram)) {
throw std::runtime_error("Regenerate code is failed");
}
_needRunGlobalCode = true;
}
// check if need to run global code
if(!_needRunGlobalCode) return;
auto context = globalScope->getContext();
if(_allocatedDataSize || _allocatedScopeSize) {
context->scopeUnallocate(_allocatedDataSize, _allocatedScopeSize);
}
_allocatedDataSize = globalScope->getDataSize();
_allocatedScopeSize = globalScope->getScopeSize(); // space need to run the code
context->pushContext(globalScope->getConstructorCommandCount());
context->scopeAllocate(_allocatedDataSize, _allocatedScopeSize);
context->run();
context->runDestructorCommands();
}
ffscript::Variable* ExpressionContext::addVariable(xpression::Variable* pVariable) {
if(pVariable->name == nullptr || pVariable->name[0] == 0) {
throw std::runtime_error("Variable name cannot be empty");
}
if(pVariable->type == DataType::Unknown) {
throw std::runtime_error("type of variable '" + std::string(pVariable->name) + "' is unknown");
}
auto globalScope = _pCompilerSuite->getGlobalScope();
// convert static type to lambda script type
auto& typeManager = _pCompilerSuite->getTypeManager();
auto& basicType = typeManager->getBasicTypes();
int iType = staticToDynamic(basicType, pVariable->type);
if(DATA_TYPE_UNKNOWN == iType) {
throw std::runtime_error("type of variable '" + std::string(pVariable->name) + "' is not supported");
}
// regist variable with specified name
auto pScriptVariable = globalScope->registVariable(pVariable->name);
if(pScriptVariable == nullptr) {
throw std::runtime_error("Variable '" + std::string(pVariable->name) + "' is already exist");
}
// set variable type
ScriptType type(iType, typeManager->getType(iType));
pScriptVariable->setDataType(type);
_pVariableManager->addVariable(pVariable);
_pVariableManager->addRequestUpdateVariable(pScriptVariable, pVariable->dataPtr == nullptr);
// the variable now is register success, then it need evaluate before expression evaluate
_needUpdateVariable = true;
// request existing expression in current scope update when new variable is added to the scope
_eventManager->notifyUpdate();
// update the last added variable' offset
globalScope->updateLastVariableOffset();
// need re-generate code after add new variable
_needRegenerateCode = true;
return pScriptVariable;
}
void ExpressionContext::removeVariable(Variable* pVariable) {
_pVariableManager->removeVariable(pVariable);
}
VariableUpdater* ExpressionContext::getVariableUpdater() {
if(_pVariableManager == nullptr) {
return nullptr;
}
return _pVariableManager->getVariableUpdater();
}
void ExpressionContext::setVariableUpdater(VariableUpdater* pVariableUpdater, bool deleteIt) {
_pVariableManager->setVariableUdater(pVariableUpdater, deleteIt);
}
void ExpressionContext::setUserData(const UserData& userData) {
_userData = userData;
}
UserData& ExpressionContext::getUserData() {
return _userData;
}
void ExpressionContext::addExpressionEventHandler(ExpressionEventHandler* handler) {
_eventManager->addHandler(handler);
}
void ExpressionContext::removeExpressionEventHandler(ExpressionEventHandler* handler) {
_eventManager->removeHandler(handler);
}
void ExpressionContext::fillVariable(const char* name, Variable* resultVariable) {
auto globalScope = _pCompilerSuite->getGlobalScope();
auto& compiler = _pCompilerSuite->getCompiler();
auto scriptVarible = globalScope->findVariable(name);
if(scriptVarible == nullptr) {
throw std::runtime_error("variable '" + std::string(name) + "'not found");
}
// need run global code before fill variable
startEvaluating();
auto variableContext = globalScope->getContext();
auto& typeManager = _pCompilerSuite->getTypeManager();
auto& basicType = typeManager->getBasicTypes();
resultVariable->type = dynamicToStatic(basicType, scriptVarible->getDataType().iType());
resultVariable->dataSize = compiler->getTypeSize(scriptVarible->getDataType());
void* variableDataAddressDst =
variableContext->getAbsoluteAddress(variableContext->getCurrentOffset() + scriptVarible->getOffset());
resultVariable->dataPtr = variableDataAddressDst;
}
VariableManager* ExpressionContext::getVariableManager() {
return _pVariableManager;
}
} | 38.197674 | 135 | 0.645561 | VincentPT |
1edb5939708559a1085f61d7cc47d748fce51752 | 4,982 | hpp | C++ | include/robotoc/cost/task_space_3d_cost.hpp | mcx/robotoc | 4a1d2f522ecc8f9aa8dea17330b97148a2085270 | [
"BSD-3-Clause"
] | 58 | 2021-11-11T09:47:02.000Z | 2022-03-27T20:13:08.000Z | include/robotoc/cost/task_space_3d_cost.hpp | mcx/robotoc | 4a1d2f522ecc8f9aa8dea17330b97148a2085270 | [
"BSD-3-Clause"
] | 30 | 2021-10-30T10:31:38.000Z | 2022-03-28T14:12:08.000Z | include/robotoc/cost/task_space_3d_cost.hpp | mcx/robotoc | 4a1d2f522ecc8f9aa8dea17330b97148a2085270 | [
"BSD-3-Clause"
] | 12 | 2021-11-17T10:59:20.000Z | 2022-03-18T07:34:02.000Z | #ifndef ROBOTOC_TASK_SPACE_3D_COST_HPP_
#define ROBOTOC_TASK_SPACE_3D_COST_HPP_
#include "Eigen/Core"
#include "robotoc/robot/robot.hpp"
#include "robotoc/robot/contact_status.hpp"
#include "robotoc/robot/impulse_status.hpp"
#include "robotoc/cost/cost_function_component_base.hpp"
#include "robotoc/cost/cost_function_data.hpp"
#include "robotoc/ocp/split_solution.hpp"
#include "robotoc/ocp/split_kkt_residual.hpp"
#include "robotoc/ocp/split_kkt_matrix.hpp"
#include "robotoc/impulse/impulse_split_solution.hpp"
#include "robotoc/impulse/impulse_split_kkt_residual.hpp"
#include "robotoc/impulse/impulse_split_kkt_matrix.hpp"
namespace robotoc {
///
/// @class TaskSpace3DCost
/// @brief Cost on the task space position.
///
class TaskSpace3DCost final : public CostFunctionComponentBase {
public:
///
/// @brief Constructor.
/// @param[in] robot Robot model.
/// @param[in] frame_id Frame of interest.
///
TaskSpace3DCost(const Robot& robot, const int frame_id);
///
/// @brief Default constructor.
///
TaskSpace3DCost();
///
/// @brief Destructor.
///
~TaskSpace3DCost();
///
/// @brief Default copy constructor.
///
TaskSpace3DCost(const TaskSpace3DCost&) = default;
///
/// @brief Default copy operator.
///
TaskSpace3DCost& operator=(const TaskSpace3DCost&) = default;
///
/// @brief Default move constructor.
///
TaskSpace3DCost(TaskSpace3DCost&&) noexcept = default;
///
/// @brief Default move assign operator.
///
TaskSpace3DCost& operator=(TaskSpace3DCost&&) noexcept = default;
///
/// @brief Sets the reference position.
/// @param[in] x3d_ref Reference position.
///
void set_x3d_ref(const Eigen::Vector3d& x3d_ref);
///
/// @brief Sets the weight vector.
/// @param[in] x3d_weight Weight vector on the position error.
///
void set_x3d_weight(const Eigen::Vector3d& x3d_weight);
///
/// @brief Sets the weight vector at the terminal stage.
/// @param[in] x3df_weight Weight vector on the position error at the
/// terminal stage.
///
void set_x3df_weight(const Eigen::Vector3d& x3df_weight);
///
/// @brief Sets the weight vector at the impulse stage.
/// @param[in] x3di_weight Weight vector on the position error at the
/// impulse stage.
///
void set_x3di_weight(const Eigen::Vector3d& x3di_weight);
bool useKinematics() const override;
double evalStageCost(Robot& robot, const ContactStatus& contact_status,
CostFunctionData& data, const GridInfo& grid_info,
const SplitSolution& s) const override;
void evalStageCostDerivatives(Robot& robot, const ContactStatus& contact_status,
CostFunctionData& data, const GridInfo& grid_info,
const SplitSolution& s,
SplitKKTResidual& kkt_residual) const override;
void evalStageCostHessian(Robot& robot, const ContactStatus& contact_status,
CostFunctionData& data, const GridInfo& grid_info,
const SplitSolution& s,
SplitKKTMatrix& kkt_matrix) const override;
double evalTerminalCost(Robot& robot, CostFunctionData& data,
const GridInfo& grid_info,
const SplitSolution& s) const override;
void evalTerminalCostDerivatives(Robot& robot, CostFunctionData& data,
const GridInfo& grid_info,
const SplitSolution& s,
SplitKKTResidual& kkt_residual) const override;
void evalTerminalCostHessian(Robot& robot, CostFunctionData& data,
const GridInfo& grid_info,
const SplitSolution& s,
SplitKKTMatrix& kkt_matrix) const override;
double evalImpulseCost(Robot& robot, const ImpulseStatus& impulse_status,
CostFunctionData& data, const GridInfo& grid_info,
const ImpulseSplitSolution& s) const override;
void evalImpulseCostDerivatives(Robot& robot, const ImpulseStatus& impulse_status,
CostFunctionData& data, const GridInfo& grid_info,
const ImpulseSplitSolution& s,
ImpulseSplitKKTResidual& kkt_residual) const;
void evalImpulseCostHessian(Robot& robot, const ImpulseStatus& impulse_status,
CostFunctionData& data, const GridInfo& grid_info,
const ImpulseSplitSolution& s,
ImpulseSplitKKTMatrix& kkt_matrix) const override;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
int frame_id_;
Eigen::Vector3d x3d_ref_, x3d_weight_, x3df_weight_, x3di_weight_;
};
} // namespace robotoc
#endif // ROBOTOC_TASK_SPACE_3D_COST_HPP_ | 34.358621 | 85 | 0.644721 | mcx |
1edecb27d8e09c4670cba165a18a2b56fe1b62df | 5,438 | cpp | C++ | android/jni/JNIRegistStaticMethod.cpp | 15d23/NUIEngine | a1369d5cea90cca81d74a39b8a853b3fba850595 | [
"Apache-2.0"
] | 204 | 2017-05-08T05:41:29.000Z | 2022-03-29T16:57:44.000Z | android/jni/JNIRegistStaticMethod.cpp | 15d23/NUIEngine | a1369d5cea90cca81d74a39b8a853b3fba850595 | [
"Apache-2.0"
] | 7 | 2017-05-10T15:32:09.000Z | 2020-12-23T06:00:30.000Z | android/jni/JNIRegistStaticMethod.cpp | 15d23/NUIEngine | a1369d5cea90cca81d74a39b8a853b3fba850595 | [
"Apache-2.0"
] | 65 | 2017-05-25T05:46:56.000Z | 2021-02-06T11:07:38.000Z | #include "JNIRegistStaticMethod.h"
#include <stdlib.h>
extern JavaVM * gJavaVM; // 全局变量, 在JNI_OnLoad时获取
#define JR_MUTEX
JNIRegistStaticMethod::JNIRegistStaticMethod()
{
m_bRegistered = false;
m_isAttached = false;
m_class = NULL;
m_methodCallback = NULL;
}
int JNIRegistStaticMethod::UnregisterCallback(JNIEnv * env)
{
JR_MUTEX
m_bRegistered = false;
if(m_class)
{
env->DeleteGlobalRef(m_class);
m_class = NULL;
}
return 0;
}
// 避免抛出异常挂掉
void AvoidException(JNIEnv* env)
{
if(env->ExceptionCheck())
{
// 通过System.out.err 输出
env->ExceptionDescribe();
// 清除异常
env->ExceptionClear();
}
}
int JNIRegistStaticMethod::RegisterCallback(JNIEnv* env, const char* pszClassName, const char* szMethodName, const char* szMethodSign)
{
JR_MUTEX // register 和 Call不能同时进行
m_bRegistered = false;
if(m_class)
{
// 避免重复Register
env->DeleteGlobalRef(m_class);
m_class = NULL;
}
// 获取类名 "android/navi/ui/mainmap/MainMapActivity"
jclass jcLocal = env->FindClass(pszClassName);
if(jcLocal == NULL)
{
LOGE("FindClass %s error", pszClassName);
AvoidException(env);
return -1;
}
m_class = (jclass)env->NewGlobalRef(jcLocal);
LOGI ("RegisterCallback jcLocal = %p, m_class = %p", jcLocal, m_class);
env->DeleteLocalRef(jcLocal);
if(m_class == NULL)
{
LOGE("NewGlobalRef %s error", pszClassName);
AvoidException(env);
return -3;
}
// 获取方法的签名 javap -s -public MainActivity
// "requestRenderFromLocator", "()V"
// 获取方法
m_methodCallback = env->GetStaticMethodID(m_class, szMethodName, szMethodSign);
if (m_methodCallback == NULL)
{
LOGE("GetMethodID %s - %s error", szMethodName, szMethodSign);
AvoidException(env);
return -2;
}
LOGI("RegisterCallback ok");
m_bRegistered = true;
m_strClassName = pszClassName;
m_strMethodName = szMethodName;
m_strMethodSign = szMethodSign;
return 0;
}
// 获取JNIEnv
JNIEnv *JNIRegistStaticMethod::BeginCallback()
{
if (!m_bRegistered)
{
return NULL;
}
JavaVM *jvm = gJavaVM;
JNIEnv *env = NULL;
m_isAttached = false;
int status = jvm->GetEnv((void **) &env, JNI_VERSION_1_6);
if (status != JNI_OK)
{
// LOGI("CallRequestRenderFromLocator jvm->GetEnv = %p, iStatus = %d", env, status);
status = jvm->AttachCurrentThread(&env, NULL);
//LOGI("CallRequestRenderFromLocator AttachCurrentThread = %d, Env = %p", status, env);
if (status != JNI_OK)
{
LOGE("CallRequestRenderFromLocator: failed to AttachCurrentThread = %d", status);
return NULL;
}
m_isAttached = true;
}
return env;
}
void JNIRegistStaticMethod::EndCallback(JNIEnv * env)
{
//LOGI ("CallRequestRenderFromLocator end");
AvoidException(env);
if(m_isAttached)
{
gJavaVM->DetachCurrentThread();
}
}
void JNIRegistStaticMethod::CallRequestedMothod()
{
JR_MUTEX
JNIEnv * env = BeginCallback();
if(env != NULL)
{
env->CallStaticVoidMethod(m_class, m_methodCallback);
EndCallback(env);
}
//LOGI ("JNIRegistStaticMethod::CallRequestedMothod");
}
void JNIRegistStaticMethod::CallRequestedMothod(int p1, int p2)
{
JR_MUTEX
JNIEnv * env = BeginCallback();
if(env != NULL)
{
env->CallStaticVoidMethod(m_class, m_methodCallback, p1, p2);
EndCallback(env);
}
//LOGI ("JNIRegistStaticMethod::CallRequestedMothod p1(%d) p2(%d)", p1, p2);
}
void JNIRegistStaticMethod::CallRequestedMothod(int p1)
{
JR_MUTEX
JNIEnv * env = BeginCallback();
if(env != NULL)
{
env->CallStaticVoidMethod(m_class, m_methodCallback, p1);
EndCallback(env);
}
//LOGI ("JNIRegistStaticMethod::CallRequestedMothod p1(%d)", p1);
}
int JNIRegistStaticMethod::CallRequestedMothodRet()
{
JR_MUTEX
JNIEnv * env = BeginCallback();
int ret = 0;
if(env != NULL)
{
ret = env->CallStaticIntMethod(m_class, m_methodCallback);
EndCallback(env);
}
//LOGI ("JNIRegistStaticMethod::CallRequestedMothod ret(%d)", ret);
return ret;
}
kn_string JNIRegistStaticMethod::CallRequestedMothodObjectRet(short* points, int iArraySize)
{
JR_MUTEX
JNIEnv * env = BeginCallback();
kn_string strRet;
if(env != NULL)
{
jshortArray jShortArray= env->NewShortArray(iArraySize);
jshort* pJavaBuf = env->GetShortArrayElements(jShortArray, NULL);
memcpy(pJavaBuf, points, iArraySize * sizeof(short));
jobject ret = env->CallStaticObjectMethod(m_class, m_methodCallback, jShortArray, iArraySize);
env->ReleaseShortArrayElements(jShortArray, pJavaBuf, 0);
jsize iStringLen = env->GetStringLength((jstring)ret);
if(iStringLen > 0)
{
const jchar* pWChars = env->GetStringChars((jstring)ret, NULL);
kn_char* pszTemp = new kn_char [iStringLen + 1];
pszTemp[iStringLen] = 0;
for(int i = 0; i < iStringLen; i++)
{
pszTemp[i] = pWChars[i];
}
strRet = pszTemp;
delete [] pszTemp;
env->ReleaseStringChars((jstring)ret, pWChars);
}
EndCallback(env);
}
//LOGI ("JNIRegistStaticMethod::CallRequestedMothod ret(%d)", ret);
return strRet;
}
int JNIRegistStaticMethod::CallRequestedMothodIntRet(int p1, int p2, int p3, const char* szp4)
{
JR_MUTEX
JNIEnv * env = BeginCallback();
int iRet = 0;
if(env != NULL)
{
jstring jstr = env->NewStringUTF(szp4);
iRet = env->CallStaticIntMethod(m_class, m_methodCallback, p1, p2, p3, jstr);
env->DeleteLocalRef(jstr);
EndCallback(env);
}
return iRet;
}
| 24.944954 | 135 | 0.683523 | 15d23 |
1edf28b4c16873887af05e48cd01f1bbd7fd38b0 | 1,508 | cpp | C++ | dependencies/PyMesh/tests/tools/Assembler/unit_test_driver.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | 5 | 2018-06-04T19:52:02.000Z | 2022-01-22T09:04:00.000Z | dependencies/PyMesh/tests/tools/Assembler/unit_test_driver.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | null | null | null | dependencies/PyMesh/tests/tools/Assembler/unit_test_driver.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | null | null | null | /* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "Mesh/TriangleMeshTest.h"
#include "Mesh/TetrahedronMeshTest.h"
#include "ShapeFunctions/ShapeFunctionTest.h"
#include "ShapeFunctions/IntegratorTest.h"
#include "ShapeFunctions/FEBasisTest.h"
#include "FESetting/FESettingTest.h"
#include "Assemblers/StiffnessAssemblerTest.h"
#include "Assemblers/MassAssemblerTest.h"
#include "Assemblers/LumpedMassAssemblerTest.h"
#include "Assemblers/LaplacianAssemblerTest.h"
#include "Assemblers/DisplacementStrainAssemblerTest.h"
#include "Assemblers/ElasticityTensorAssemblerTest.h"
#include "Assemblers/EngineerStrainStressAssemblerTest.h"
#include "Assemblers/RigidMotionAssemblerTest.h"
#include "Assemblers/GradientAssemblerTest.h"
#include "Elements/ElementsTest.h"
#include "Elements/TetrahedronElementsTest.h"
#include "Elements/TriangleElementsTest.h"
#include "Elements/EdgeElementsTest.h"
#include "Materials/ElementWiseIsotropicMaterialTest.h"
#include "Materials/ElementWiseOrthotropicMaterialTest.h"
#include "Materials/ElementWiseSymmetricMaterialTest.h"
#include "Materials/IsotropicMaterialTest.h"
#include "Materials/MaterialTest.h"
#include "Materials/OrthotropicMaterialTest.h"
#include "Materials/PeriodicMaterialTest.h"
#include "Materials/SymmetricMaterialTest.h"
#include "Materials/UniformMaterialTest.h"
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 40.756757 | 69 | 0.820955 | aprieels |
1edf879c820917e2e08561cc1df1f33663f58404 | 9,301 | hpp | C++ | include/aikido/constraint/uniform/detail/RnBoxConstraint-impl.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 181 | 2016-04-22T15:11:23.000Z | 2022-03-26T12:51:08.000Z | include/aikido/constraint/uniform/detail/RnBoxConstraint-impl.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 514 | 2016-04-20T04:29:51.000Z | 2022-02-10T19:46:21.000Z | include/aikido/constraint/uniform/detail/RnBoxConstraint-impl.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 31 | 2017-03-17T09:53:02.000Z | 2022-03-23T10:35:05.000Z | #include <stdexcept>
#include "aikido/constraint/uniform/RnBoxConstraint.hpp"
namespace aikido {
namespace constraint {
namespace uniform {
using constraint::ConstraintType;
//==============================================================================
extern template class RBoxConstraint<0>;
extern template class RBoxConstraint<1>;
extern template class RBoxConstraint<2>;
extern template class RBoxConstraint<3>;
extern template class RBoxConstraint<6>;
extern template class RBoxConstraint<Eigen::Dynamic>;
//==============================================================================
template <int N>
class RnBoxConstraintSampleGenerator : public constraint::SampleGenerator
{
public:
using VectorNd = Eigen::Matrix<double, N, 1>;
statespace::ConstStateSpacePtr getStateSpace() const override;
bool sample(statespace::StateSpace::State* _state) override;
int getNumSamples() const override;
bool canSample() const override;
private:
RnBoxConstraintSampleGenerator(
std::shared_ptr<const statespace::R<N>> _space,
std::unique_ptr<common::RNG> _rng,
const VectorNd& _lowerLimits,
const VectorNd& _upperLimits);
std::shared_ptr<const statespace::R<N>> mSpace;
std::unique_ptr<common::RNG> mRng;
std::vector<std::uniform_real_distribution<double>> mDistributions;
friend class RBoxConstraint<N>;
};
//==============================================================================
template <int N>
RnBoxConstraintSampleGenerator<N>::RnBoxConstraintSampleGenerator(
std::shared_ptr<const statespace::R<N>> _space,
std::unique_ptr<common::RNG> _rng,
const VectorNd& _lowerLimits,
const VectorNd& _upperLimits)
: mSpace(std::move(_space)), mRng(std::move(_rng))
{
const auto dimension = mSpace->getDimension();
mDistributions.reserve(dimension);
for (std::size_t i = 0; i < dimension; ++i)
mDistributions.emplace_back(_lowerLimits[i], _upperLimits[i]);
}
//==============================================================================
template <int N>
statespace::ConstStateSpacePtr
RnBoxConstraintSampleGenerator<N>::getStateSpace() const
{
return mSpace;
}
//==============================================================================
template <int N>
bool RnBoxConstraintSampleGenerator<N>::sample(
statespace::StateSpace::State* _state)
{
VectorNd value(mDistributions.size());
for (auto i = 0; i < value.size(); ++i)
value[i] = mDistributions[i](*mRng);
mSpace->setValue(
static_cast<typename statespace::R<N>::State*>(_state), value);
return true;
}
//==============================================================================
template <int N>
int RnBoxConstraintSampleGenerator<N>::getNumSamples() const
{
return NO_LIMIT;
}
//==============================================================================
template <int N>
bool RnBoxConstraintSampleGenerator<N>::canSample() const
{
return true;
}
//==============================================================================
template <int N>
RBoxConstraint<N>::RBoxConstraint(
std::shared_ptr<const statespace::R<N>> _space,
std::unique_ptr<common::RNG> _rng,
const VectorNd& _lowerLimits,
const VectorNd& _upperLimits)
: mSpace(std::move(_space))
, mRng(std::move(_rng))
, mLowerLimits(_lowerLimits)
, mUpperLimits(_upperLimits)
{
if (!mSpace)
throw std::invalid_argument("StateSpace is null.");
const auto dimension = mSpace->getDimension();
if (static_cast<std::size_t>(mLowerLimits.size()) != dimension)
{
std::stringstream msg;
msg << "Lower limits have incorrect dimension: expected "
<< mSpace->getDimension() << ", got " << mLowerLimits.size() << ".";
throw std::invalid_argument(msg.str());
}
if (static_cast<std::size_t>(mUpperLimits.size()) != dimension)
{
std::stringstream msg;
msg << "Upper limits have incorrect dimension: expected "
<< mSpace->getDimension() << ", got " << mUpperLimits.size() << ".";
throw std::invalid_argument(msg.str());
}
for (std::size_t i = 0; i < dimension; ++i)
{
if (mLowerLimits[i] > mUpperLimits[i])
{
std::stringstream msg;
msg << "Unable to sample from StateSpace because lower limit exceeds"
<< " upper limit on dimension " << i << ": " << mLowerLimits[i]
<< " > " << mUpperLimits[i] << ".";
throw std::invalid_argument(msg.str());
}
}
}
//==============================================================================
template <int N>
statespace::ConstStateSpacePtr RBoxConstraint<N>::getStateSpace() const
{
return mSpace;
}
//==============================================================================
template <int N>
std::size_t RBoxConstraint<N>::getConstraintDimension() const
{
// TODO: Only create constraints for bounded dimensions.
return mSpace->getDimension();
}
//==============================================================================
template <int N>
std::vector<ConstraintType> RBoxConstraint<N>::getConstraintTypes() const
{
return std::vector<ConstraintType>(
mSpace->getDimension(), ConstraintType::INEQUALITY);
}
//==============================================================================
template <int N>
bool RBoxConstraint<N>::isSatisfied(
const statespace::StateSpace::State* state, TestableOutcome* outcome) const
{
auto defaultOutcomeObject
= dynamic_cast_or_throw<DefaultTestableOutcome>(outcome);
const auto value = mSpace->getValue(
static_cast<const typename statespace::R<N>::State*>(state));
for (auto i = 0; i < value.size(); ++i)
{
if (value[i] < mLowerLimits[i] || value[i] > mUpperLimits[i])
{
if (defaultOutcomeObject)
defaultOutcomeObject->setSatisfiedFlag(false);
return false;
}
}
if (defaultOutcomeObject)
defaultOutcomeObject->setSatisfiedFlag(true);
return true;
}
//==============================================================================
template <int N>
std::unique_ptr<TestableOutcome> RBoxConstraint<N>::createOutcome() const
{
return std::unique_ptr<TestableOutcome>(new DefaultTestableOutcome);
}
//==============================================================================
template <int N>
bool RBoxConstraint<N>::project(
const statespace::StateSpace::State* _s,
statespace::StateSpace::State* _out) const
{
VectorNd value = mSpace->getValue(
static_cast<const typename statespace::R<N>::State*>(_s));
for (auto i = 0; i < value.size(); ++i)
{
if (value[i] < mLowerLimits[i])
value[i] = mLowerLimits[i];
else if (value[i] > mUpperLimits[i])
value[i] = mUpperLimits[i];
}
mSpace->setValue(static_cast<typename statespace::R<N>::State*>(_out), value);
return true;
}
//==============================================================================
template <int N>
void RBoxConstraint<N>::getValue(
const statespace::StateSpace::State* _s, Eigen::VectorXd& _out) const
{
auto stateValue = mSpace->getValue(
static_cast<const typename statespace::R<N>::State*>(_s));
const std::size_t dimension = mSpace->getDimension();
_out.resize(dimension);
for (std::size_t i = 0; i < dimension; ++i)
{
if (stateValue[i] < mLowerLimits[i])
_out[i] = stateValue[i] - mLowerLimits[i];
else if (stateValue[i] > mUpperLimits[i])
_out[i] = mUpperLimits[i] - stateValue[i];
else
_out[i] = 0.;
}
}
//==============================================================================
template <int N>
void RBoxConstraint<N>::getJacobian(
const statespace::StateSpace::State* _s, Eigen::MatrixXd& _out) const
{
auto stateValue = mSpace->getValue(
static_cast<const typename statespace::R<N>::State*>(_s));
const std::size_t dimension = mSpace->getDimension();
_out = Eigen::MatrixXd::Zero(dimension, dimension);
for (auto i = 0; i < _out.rows(); ++i)
{
if (stateValue[i] < mLowerLimits[i])
_out(i, i) = -1.;
else if (stateValue[i] > mUpperLimits[i])
_out(i, i) = 1.;
else
_out(i, i) = 0.;
}
}
//==============================================================================
template <int N>
std::unique_ptr<constraint::SampleGenerator>
RBoxConstraint<N>::createSampleGenerator() const
{
if (!mRng)
throw std::invalid_argument("mRng is null.");
for (std::size_t i = 0; i < mSpace->getDimension(); ++i)
{
if (!std::isfinite(mLowerLimits[i]) || !std::isfinite(mUpperLimits[i]))
{
std::stringstream msg;
msg << "Unable to sample from StateSpace because dimension " << i
<< " is unbounded.";
throw std::runtime_error(msg.str());
}
}
return std::unique_ptr<RnBoxConstraintSampleGenerator<N>>(
new RnBoxConstraintSampleGenerator<N>(
mSpace, mRng->clone(), mLowerLimits, mUpperLimits));
}
//==============================================================================
template <int N>
auto RBoxConstraint<N>::getLowerLimits() const -> const VectorNd&
{
return mLowerLimits;
}
//==============================================================================
template <int N>
auto RBoxConstraint<N>::getUpperLimits() const -> const VectorNd&
{
return mUpperLimits;
}
} // namespace uniform
} // namespace constraint
} // namespace aikido
| 29.433544 | 80 | 0.571551 | personalrobotics |
1ee0729bb215ca814e8f741dc25b511d1e4734bb | 7,652 | cpp | C++ | lib/stages/RawReader.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 19 | 2018-12-14T00:51:52.000Z | 2022-02-20T02:43:50.000Z | lib/stages/RawReader.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 487 | 2018-12-13T00:59:53.000Z | 2022-02-07T16:12:56.000Z | lib/stages/RawReader.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 5 | 2019-05-09T19:52:19.000Z | 2021-03-27T20:13:21.000Z | #include "RawReader.hpp"
#include "Config.hpp" // for Config
#include "Hash.hpp" // for Hash, operator<, operator==
#include "StageFactory.hpp" // for REGISTER_KOTEKAN_STAGE, StageMakerTemplate
#include "buffer.h" // for mark_frame_full, wait_for_empty_frame, mark_frame_empty
#include "bufferContainer.hpp" // for bufferContainer
#include "datasetManager.hpp" // for state_id_t, dset_id_t, datasetManager, DS_UNIQUE_NAME
#include "datasetState.hpp" // for freqState, timeState, metadataState
#include "kotekanLogging.hpp" // for INFO, FATAL_ERROR, DEBUG, WARN, ERROR
#include "visBuffer.hpp" // for VisFrameView
#include "visUtil.hpp" // for time_ctype, freq_ctype, frameID, modulo, current_time
#include "json.hpp" // for basic_json<>::object_t, json, basic_json, basic_json<>::v...
#include <atomic> // for atomic_bool
#include <cxxabi.h> // for __forced_unwind
#include <exception> // for exception
#include <functional> // for _Bind_helper<>::type, bind, function
#include <future> // for async, future
#include <memory> // for allocator_traits<>::value_type
#include <regex> // for match_results<>::_Base_type
#include <stdexcept> // for runtime_error, invalid_argument, out_of_range
#include <system_error> // for system_error
#include <tuple> // for get
using kotekan::bufferContainer;
using kotekan::Config;
using kotekan::Stage;
using nlohmann::json;
REGISTER_KOTEKAN_STAGE(ensureOrdered);
ensureOrdered::ensureOrdered(Config& config, const std::string& unique_name,
bufferContainer& buffer_container) :
Stage(config, unique_name, buffer_container, std::bind(&ensureOrdered::main_thread, this)) {
max_waiting = config.get_default<size_t>(unique_name, "max_waiting", 100);
chunked = config.exists(unique_name, "chunk_size");
if (chunked) {
chunk_size = config.get<std::vector<int>>(unique_name, "chunk_size");
if (chunk_size.size() != 3) {
FATAL_ERROR("Chunk size needs exactly three elements (got {:d}).", chunk_size.size());
return;
}
chunk_t = chunk_size[2];
chunk_f = chunk_size[0];
if (chunk_size[0] < 1 || chunk_size[1] < 1 || chunk_size[2] < 1) {
FATAL_ERROR("Chunk dimensions need to be >= 1 (got ({:d}, {:d}, {:d}).", chunk_size[0],
chunk_size[1], chunk_size[2]);
return;
}
}
// Get the list of buffers that this stage should connect to
out_buf = get_buffer("out_buf");
register_producer(out_buf, unique_name.c_str());
in_buf = get_buffer("in_buf");
register_consumer(in_buf, unique_name.c_str());
}
bool ensureOrdered::get_dataset_state(dset_id_t ds_id) {
datasetManager& dm = datasetManager::instance();
// Get the states synchronously.
auto tstate_fut = std::async(&datasetManager::dataset_state<timeState>, &dm, ds_id);
auto fstate_fut = std::async(&datasetManager::dataset_state<freqState>, &dm, ds_id);
const timeState* tstate = tstate_fut.get();
const freqState* fstate = fstate_fut.get();
if (tstate == nullptr || fstate == nullptr) {
ERROR("One of time or freq dataset states is null for dataset {}.", ds_id);
return false;
}
auto times = tstate->get_times();
auto freq_pairs = fstate->get_freqs();
// construct map of times to axis index
for (size_t i = 0; i < times.size(); i++) {
time_map.insert({times.at(i), i});
}
// construct map of freq_ind to axis index
for (size_t i = 0; i < freq_pairs.size(); i++) {
freq_map.insert({freq_pairs.at(i).first, i});
}
return true;
}
void ensureOrdered::main_thread() {
// The index to the current buffer frame
frameID frame_id(in_buf);
frameID output_frame_id(out_buf);
// The index of the current frame relative to the first frame
size_t output_ind = 0;
// Frequency and time indices
size_t fi, ti;
time_ctype t;
// The dataset ID we read from the frame
dset_id_t ds_id;
// Get axes from dataset state
uint32_t first_ind = 0;
while (true) {
// Wait for a frame in the input buffer in order to get the dataset ID
if ((wait_for_full_frame(in_buf, unique_name.c_str(), first_ind)) == nullptr) {
return;
}
auto frame = VisFrameView(in_buf, first_ind);
if (frame.fpga_seq_length == 0) {
INFO("Got empty frame ({:d}).", first_ind);
first_ind++;
} else {
ds_id = frame.dataset_id;
break;
}
}
auto future_ds_state = std::async(&ensureOrdered::get_dataset_state, this, ds_id);
if (!future_ds_state.get()) {
FATAL_ERROR("Couldn't find ancestor of dataset {}. "
"Make sure there is a stage upstream in the config, that adds the dataset "
"states.\nExiting...",
ds_id);
return;
}
// main loop:
while (!stop_thread) {
// Wait for a full frame in the input buffer
if ((wait_for_full_frame(in_buf, unique_name.c_str(), frame_id)) == nullptr) {
break;
}
auto frame = VisFrameView(in_buf, frame_id);
// Figure out the ordered index of this frame
t = {std::get<0>(frame.time), ts_to_double(std::get<1>(frame.time))};
ti = time_map.at(t);
fi = freq_map.at(frame.freq_id);
size_t ordered_ind = get_frame_ind(ti, fi);
// Check if this is the index we are ready to send
if (ordered_ind == output_ind) {
// copy frame into output buffer
if (wait_for_empty_frame(out_buf, unique_name.c_str(), output_frame_id) == nullptr) {
return;
}
auto output_frame =
VisFrameView::copy_frame(in_buf, frame_id, out_buf, output_frame_id);
mark_frame_full(out_buf, unique_name.c_str(), output_frame_id++);
// release input frame
mark_frame_empty(in_buf, unique_name.c_str(), frame_id++);
// increment output index
output_ind++;
} else if (waiting.size() <= max_waiting) {
INFO("Frame {:d} arrived out of order. Expected {:d}. Adding it to waiting buffer.",
ordered_ind, output_ind);
// Add to waiting frames and move to next (without marking empty!)
waiting.insert({ordered_ind, (int)frame_id});
frame_id++;
} else {
FATAL_ERROR("Number of frames arriving out of order exceeded maximum buffer size.");
return;
}
// Check if any of the waiting frames are ready
auto ready = waiting.find(output_ind);
while (ready != waiting.end()) {
// remove this index from waiting map
uint32_t waiting_id = ready->second;
waiting.erase(ready);
INFO("Frame {:d} is ready to be sent. Releasing buffer.", output_ind);
// copy frame into output buffer
auto past_frame = VisFrameView(in_buf, waiting_id);
if (wait_for_empty_frame(out_buf, unique_name.c_str(), output_frame_id) == nullptr) {
return;
}
auto output_frame =
VisFrameView::copy_frame(in_buf, waiting_id, out_buf, output_frame_id);
mark_frame_full(out_buf, unique_name.c_str(), output_frame_id++);
mark_frame_empty(in_buf, unique_name.c_str(), waiting_id);
output_ind++;
ready = waiting.find(output_ind);
}
}
}
| 38.646465 | 99 | 0.618008 | eschnett |
1ee1c1a03180101329705d42a18c44e34535805b | 3,011 | cc | C++ | Source/BladeBase/source/utility/Delegate.cc | OscarGame/blade | 6987708cb011813eb38e5c262c7a83888635f002 | [
"MIT"
] | 146 | 2018-12-03T08:08:17.000Z | 2022-03-21T06:04:06.000Z | Source/BladeBase/source/utility/Delegate.cc | huangx916/blade | 3fa398f4d32215bbc7e292d61e38bb92aad1ee1c | [
"MIT"
] | 1 | 2019-01-18T03:35:49.000Z | 2019-01-18T03:36:08.000Z | Source/BladeBase/source/utility/Delegate.cc | huangx916/blade | 3fa398f4d32215bbc7e292d61e38bb92aad1ee1c | [
"MIT"
] | 31 | 2018-12-03T10:32:43.000Z | 2021-10-04T06:31:44.000Z | /********************************************************************
created: 2013/11/21
filename: Delegate.cc
author: Crazii
purpose:
*********************************************************************/
#include <BladePCH.h>
#include <utility/Delegate.h>
namespace Blade
{
//////////////////////////////////////////////////////////////////////////
const char Delegate::ZERO[Delegate::MAX_SIZE] = {0};
//////////////////////////////////////////////////////////////////////////
namespace Impl
{
class DelegateListImpl : public List<Delegate>, public Allocatable {};
}//namespace Impl
using namespace Impl;
//////////////////////////////////////////////////////////////////////////
DelegateList::DelegateList()
{
}
//////////////////////////////////////////////////////////////////////////
DelegateList::~DelegateList()
{
}
//////////////////////////////////////////////////////////////////////////
DelegateList::DelegateList(const DelegateList& src)
{
if(src.mList != NULL)
*mList = *src.mList;
}
//////////////////////////////////////////////////////////////////////////
DelegateList& DelegateList::operator=(const DelegateList& rhs)
{
if (rhs.mList != NULL)
*mList = *rhs.mList;
else
mList.destruct();
return *this;
}
//////////////////////////////////////////////////////////////////////////
void DelegateList::push_back(const Delegate& _delegate)
{
mList->push_back(_delegate);
}
//////////////////////////////////////////////////////////////////////////
bool DelegateList::erase(index_t index)
{
if(mList != NULL && index < mList->size() )
{
DelegateListImpl::iterator i = mList->begin();
while( index-- > 0)
++i;
mList->erase(i);
return true;
}
else
{
assert(false);
return false;
}
}
//////////////////////////////////////////////////////////////////////////
const Delegate& DelegateList::at(index_t index) const
{
if(mList != NULL && index < mList->size() )
{
DelegateListImpl::const_iterator i = mList->begin();
while( index-- > 0)
++i;
return *i;
}
else
BLADE_EXCEPT(EXC_OUT_OF_RANGE, BTString("index out of range"));
}
//////////////////////////////////////////////////////////////////////////
size_t DelegateList::size() const
{
return mList != NULL ? mList->size() : 0;
}
//////////////////////////////////////////////////////////////////////////
void DelegateList::call(void* data) const
{
if (mList == NULL)
return;
for (DelegateListImpl::const_iterator i = mList->begin(); i != mList->end(); ++i)
{
const Delegate& d = (*i);
if (d.hasParameter())
d.call(data);
else
d.call();
}
}
//////////////////////////////////////////////////////////////////////////
void DelegateList::call() const
{
if (mList == NULL)
return;
for (DelegateListImpl::const_iterator i = mList->begin(); i != mList->end(); ++i)
{
const Delegate& d = (*i);
if (!d.hasParameter())
d.call();
}
}
}//namespace Blade | 24.088 | 83 | 0.406177 | OscarGame |
1ee378688d73b111128c3a5e92105221a99bfaff | 8,324 | cpp | C++ | GameEngine/cMesh.cpp | GottaCodeHarder/GT-Engine | 44ae4d8c974605cc1cd5fd240af81f999b613e8a | [
"MIT"
] | 1 | 2017-09-15T23:56:00.000Z | 2017-09-15T23:56:00.000Z | GameEngine/cMesh.cpp | GottaCodeHarder/GT-Engine | 44ae4d8c974605cc1cd5fd240af81f999b613e8a | [
"MIT"
] | 5 | 2017-09-20T07:13:20.000Z | 2017-10-12T10:57:16.000Z | GameEngine/cMesh.cpp | GottaCodeHarder/GT-Engine | 44ae4d8c974605cc1cd5fd240af81f999b613e8a | [
"MIT"
] | null | null | null | #include "glew/include/glew.h"
#include "SDL/include/SDL_opengl.h"
#include <gl/GL.h>
#include <gl/GLU.h>
#include "cMesh.h"
#include "ResourceMesh.h"
#include "cTransform.h"
#include "Application.h"
#include "ModuleRenderer3D.h"
#include "GameObject.h"
cMesh::cMesh(GameObject* _gameObject) : Component(MESH, _gameObject)
{
type = MESH;
}
cMesh::~cMesh()
{
}
void cMesh::RealUpdate()
{
}
void cMesh::DrawUI()
{
if (ImGui::CollapsingHeader("Mesh"))
{
if (ImGui::TreeNodeEx("Geometry", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Text("Vertex Count: %i", resource->numVertex);
ImGui::Text("Triangle Count: %i", resource->numIndex / 3);
ImGui::TreePop();
}
ImGui::Spacing();
if (ImGui::Checkbox("AABB box", &aabbActive)){}
if (aabbActive)
{
DrawAABB(gameObject->aabbBox);
}
if (ImGui::TreeNodeEx("AABB information", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Text("Center Point: %f, %f, %f", gameObject->aabbBox.CenterPoint().x, gameObject->aabbBox.CenterPoint().y, gameObject->aabbBox.CenterPoint().z);
//ImGui::Text("Scale: %f, %f, %f", scaleLocal.x, scaleLocal.y, scaleLocal.z);
//ImGui::Text("Rotation: %f, %f, %f, %f ", rotationLocal.x, rotationLocal.y, rotationLocal.z, rotationLocal.w);
ImGui::TreePop();
}
ImGui::Spacing();
//glColor3f(color.r, color.g, color.b);
}
}
void cMesh::DrawAABB(AABB aabbBox)
{
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.minPoint.x, aabbBox.minPoint.y, aabbBox.minPoint.z), btVector3(aabbBox.minPoint.x, aabbBox.maxPoint.y, aabbBox.minPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.minPoint.x, aabbBox.minPoint.y, aabbBox.minPoint.z), btVector3(aabbBox.maxPoint.x, aabbBox.minPoint.y, aabbBox.minPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.minPoint.x, aabbBox.minPoint.y, aabbBox.minPoint.z), btVector3(aabbBox.minPoint.x, aabbBox.minPoint.y, aabbBox.maxPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.maxPoint.x, aabbBox.minPoint.y, aabbBox.maxPoint.z), btVector3(aabbBox.minPoint.x, aabbBox.minPoint.y, aabbBox.maxPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.maxPoint.x, aabbBox.minPoint.y, aabbBox.maxPoint.z), btVector3(aabbBox.maxPoint.x, aabbBox.minPoint.y, aabbBox.minPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.maxPoint.x, aabbBox.maxPoint.y, aabbBox.maxPoint.z), btVector3(aabbBox.maxPoint.x, aabbBox.minPoint.y, aabbBox.maxPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.maxPoint.x, aabbBox.maxPoint.y, aabbBox.maxPoint.z), btVector3(aabbBox.maxPoint.x, aabbBox.maxPoint.y, aabbBox.minPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.maxPoint.x, aabbBox.maxPoint.y, aabbBox.maxPoint.z), btVector3(aabbBox.minPoint.x, aabbBox.maxPoint.y, aabbBox.maxPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.minPoint.x, aabbBox.maxPoint.y, aabbBox.maxPoint.z), btVector3(aabbBox.minPoint.x, aabbBox.minPoint.y, aabbBox.maxPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.minPoint.x, aabbBox.maxPoint.y, aabbBox.maxPoint.z), btVector3(aabbBox.minPoint.x, aabbBox.maxPoint.y, aabbBox.minPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.maxPoint.x, aabbBox.maxPoint.y, aabbBox.minPoint.z), btVector3(aabbBox.minPoint.x, aabbBox.maxPoint.y, aabbBox.minPoint.z), btVector3(0, 0.7f, 0));
App->renderer3D->debugDraw->drawLine(btVector3(aabbBox.maxPoint.x, aabbBox.maxPoint.y, aabbBox.minPoint.z), btVector3(aabbBox.maxPoint.x, aabbBox.minPoint.y, aabbBox.minPoint.z), btVector3(0, 0.7f, 0));
}
uint cMesh::Serialize(char * &buffer)
{
uint length = 0;
length += sizeof(int);
length += sizeof(uint);
length += resource->numVertex * sizeof(float3);
length += sizeof(uint);
length += resource->numIndex * sizeof(uint);
length += sizeof(uint);
length += resource->numVertex * sizeof(float3);
length += resource->numVertex * sizeof(float2);
buffer = new char[length];
char* it = buffer;
int iType = (int)componentType::MESH;
memcpy(it, &iType, sizeof(int));
it += sizeof(int);
// Normals
uint size = resource->numVertex;
memcpy(it, &size, sizeof(uint));
it += sizeof(uint);
memcpy(it, resource->normals.data(), sizeof(float3) * resource->numVertex);
it += resource->numVertex * sizeof(float3);
// Index
size = resource->numIndex;
memcpy(it, &size, sizeof(uint));
it += sizeof(uint);
memcpy(it, resource->index.data(), sizeof(uint) * resource->numIndex);
it += resource->numIndex * sizeof(uint);
// Vertex
size = resource->numVertex;
memcpy(it, &size, sizeof(uint));
it += sizeof(uint);
memcpy(it, resource->vertex.data(), sizeof(float3) * resource->numVertex);
it += resource->numVertex * sizeof(float3);
float2* uv = new float2[resource->numVertex];
glGetBufferSubData(resource->buffUv, NULL, resource->vertex.size() * sizeof(float2), uv);
memcpy(it, uv, resource->numVertex * sizeof(float2));
it += resource->numVertex * sizeof(float2);
delete[] uv;
return length;
}
uint cMesh::DeSerialize(char * &buffer, GameObject * parent)
{
char* it = buffer;
uint ret = 0;
resource = new ResourceMesh();
// Normals Size
uint size;
memcpy(&size, it, sizeof(uint));
resource->numVertex = size;
it += sizeof(uint);
ret += sizeof(uint);
// Normals
if (resource->numVertex > 0)
{
resource->normals.reserve(resource->numVertex);
memcpy(resource->normals.data(), it, resource->numVertex * sizeof(float3));
}
it += resource->numVertex * sizeof(float3);
ret += resource->numVertex * sizeof(float3);
// Index Size
memcpy(&size, it, sizeof(uint));
resource->numIndex = size;
it += sizeof(uint);
ret += sizeof(uint);
// Index
if (resource->numIndex > 0)
{
resource->index.reserve(resource->numIndex);
memcpy(resource->index.data(), it, resource->numIndex * sizeof(uint));
}
it += resource->numIndex * sizeof(uint);
ret += resource->numIndex * sizeof(uint);
// Vertex Size
memcpy(&size, it, sizeof(uint));
resource->numVertex = size;
it += sizeof(uint);
ret += sizeof(uint);
// Vertex
if (resource->numVertex > 0)
{
resource->vertex.reserve(resource->numVertex);
memcpy(resource->vertex.data(), it, resource->numVertex * sizeof(float3));
}
it += resource->numVertex * sizeof(float3);
ret += resource->numVertex * sizeof(float3);
// UVs
float2* uv = new float2[resource->numVertex];
//memcpy(&uv, it, resource->numVertex * sizeof(float2));
it += resource->numVertex * sizeof(float2);
ret += resource->numVertex * sizeof(float2);
///////////////////////
// Vertex
if (resource->vertex.empty() != false)
{
glGenBuffers(1, (GLuint*) &(resource->buffVertex));
glBindBuffer(GL_ARRAY_BUFFER, resource->buffVertex);
glBufferData(GL_ARRAY_BUFFER, sizeof(float3) * resource->numVertex, resource->vertex.data(), GL_STATIC_DRAW);
MYLOG("DeSerialize - Loading %i vertex succesful!", resource->numVertex);
}
else
{
MYLOG("WARNING, the .GTE scene has 0 vertex!");
}
if (resource->vertex.size() == 0)
{
for (int j = 0; j < resource->numVertex; j++)
{
//SAVE VERTEX
//resource->vertex.push_back(float3(scene->mMeshes[i]->mVertices[j].x, scene->mMeshes[i]->mVertices[j].y, scene->mMeshes[i]->mVertices[j].z));
}
}
// Normals
if (resource->normals.empty() != false)
{
glGenBuffers(1, (GLuint*) &(resource->buffNormals));
glBindBuffer(GL_ARRAY_BUFFER, resource->buffNormals);
glBufferData(GL_ARRAY_BUFFER, sizeof(float3) * resource->numVertex, resource->normals.data(), GL_STATIC_DRAW);
}
// UVs
if (uv->Size > NULL)
{
glGenBuffers(1, (GLuint*) &(resource->buffUv));
glBindBuffer(GL_ARRAY_BUFFER, resource->buffUv);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * resource->numVertex * 2, uv, GL_STATIC_DRAW);
}
// Index
if (resource->numIndex > 0)
{
glGenBuffers(1, (GLuint*) &(resource->buffIndex));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource->buffIndex);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, resource->numIndex * 3, &resource->index, GL_STATIC_DRAW);
MYLOG("DeSerialize - Loading %i index succesful!", resource->numIndex * 3);
}
return ret;
}
| 34.396694 | 203 | 0.704469 | GottaCodeHarder |
1ee59a5ae98048b0f7ffa8b13de4f4aab1e432bc | 4,703 | cpp | C++ | problem/Sumo.cpp | esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation | cfe6e3e8f333f906430d668f4f2b475dfdd71d9e | [
"MIT"
] | null | null | null | problem/Sumo.cpp | esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation | cfe6e3e8f333f906430d668f4f2b475dfdd71d9e | [
"MIT"
] | null | null | null | problem/Sumo.cpp | esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation | cfe6e3e8f333f906430d668f4f2b475dfdd71d9e | [
"MIT"
] | null | null | null | /***********************************************************************************
* AUTHOR
* - Eduardo Segredo
*
* LAST MODIFIED
* October 2018
************************************************************************************/
#include "Sumo.h"
bool Sumo::init (const vector<string> ¶ms) {
if (params.size() != 6) {
cerr << "Error in init - Parameters: instanceFile execDir tlFileName resultsFileName mut_op cross_op" << endl;
exit(-1);
}
instance.read(params[0]);
command = "mkdir -p " + instance.getPath() + params[1] + "/";
execCommandPipe(command);
tlFile = instance.getPath() + params[1] + "/" + params[2];
resultsFile = instance.getPath() + params[1] + "/" + params[3];
command = "~/sumo-wrapper/sumo-wrapper " + params[0] + " " + params[1] + " " + tlFile + " " + resultsFile + " 0";
mut_op = params[4];
cross_op = params[5];
setNumberOfVar(instance.getNumberOfTLlogics() + instance.getTotalNumberOfPhases());
setNumberOfObj(NOBJ);
return true;
}
// Evaluation
void Sumo::evaluate (void) {
doubleToIntSolution();
writeSolutionFile();
//cout << "command: " << command << endl;
string result = execCommandPipe(command);
//cout << "result: " << result << endl;
double fitness = readFitnessFile();
//cout << "fitness: " << fitness << endl;
setObj(0, fitness);
}
// Cloning procedure
Individual* Sumo::clone (void) const {
Sumo* aux = new Sumo();
aux->instance = instance;
aux->command = command;
aux->tlFile = tlFile;
aux->resultsFile = resultsFile;
aux->mut_op = mut_op;
aux->cross_op = cross_op;
return aux;
}
void Sumo::print(ostream &os) const {
for (unsigned int i = 0; i < getNumberOfVar(); i++)
os << getVar(i) << " " << flush;
for (unsigned int i = 0; i < getNumberOfObj(); i++)
os << getObj(i) << " " << flush;
os << endl << flush;
}
void Sumo::dependentMutation(double pm) {
if (mut_op == "Mutate_Uniform") {
mutate_uniform(pm, 0, getNumberOfVar());
}
else if (mut_op == "Mutate_Pol") {
mutate_Pol(pm, 0, getNumberOfVar());
}
repair();
}
void Sumo::dependentCrossover(Individual* ind) {
if (cross_op == "Crossover_Uniform") {
crossover_uniform(ind, 0, getNumberOfVar());
}
else if (cross_op == "Crossover_SBX") {
crossover_SBX(ind, 0, getNumberOfVar());
}
((Sumo*)ind)->repair();
repair();
}
void Sumo::restart(void) {
int abs_pos = 0;
for(int j = 0; j < instance.getNumberOfTLlogics(); j++) {
setVar(abs_pos, rand() % 120);
abs_pos++;
for(int k = 0; k < instance.getPhases(j).size(); k++) {
setVar(abs_pos, ((double) rand () / (double) RAND_MAX));
setVar(abs_pos, getVar(abs_pos) * (getMaximum(abs_pos) - getMinimum(abs_pos)) + getMinimum(abs_pos));
abs_pos++;
}
}
repair();
}
void Sumo::repair(void) {
int abs_pos = 0;
for(int j = 0; j < instance.getNumberOfTLlogics(); j++) {
if (getVar(abs_pos) >= 120.0) {
setVar(abs_pos, rand() % 120);
}
abs_pos++;
vector<string> phases = instance.getPhases(j);
for(int k = 0; k < phases.size(); k++) {
int pos;
// Those cases where all the TLs belonging to a phase change from "G"reen to "y"ellow
if (areAllYellow(phases[k]))
setVar(abs_pos, (double) 4.0 * phases[k].size());
// Remaining cases where there exist TLs that change from "G"reen to "y"ellow
else if (isSubString(phases[k], "y", pos))
setVar(abs_pos, (double) 4.0);
abs_pos++;
}
}
}
void Sumo::doubleToIntSolution(void) {
for (int i = 0; i < getNumberOfVar(); i++)
// if (((double) rand () / (double) RAND_MAX) >= 0.5)
// setVar(i, ceil(getVar(i)));
// else
// setVar(i, floor(getVar(i)));
setVar(i, round(getVar(i)));
}
bool Sumo::areAllYellow(string phase) {
for (int i = 0; i < phase.size(); i++)
if (phase[i] != 'y')
return false;
return true;
}
void Sumo::writeSolutionFile() {
ofstream f(tlFile);
for(int i = 0; i < getNumberOfVar(); i++)
f << (unsigned int)getVar(i) << " ";
f.close();
}
double Sumo::readFitnessFile() {
double fitness;
ifstream f(resultsFile);
string s;
for(int i = 0; i < 6; i++) // skip lines
getline(f, s);
f >> fitness;
f.close();
return fitness;
}
string Sumo::execCommandPipe(string command) {
const int MAX_BUFFER_SIZE = 128;
FILE* pipe = popen(command.c_str(), "r");
// Waits until the execution ends
if (wait(NULL) == -1){
cerr << "Error waiting for simulator results" << endl;
return "-1";
}
char buffer[MAX_BUFFER_SIZE];
string result = "";
while (!feof(pipe)) {
if (fgets(buffer, MAX_BUFFER_SIZE, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
| 26.273743 | 115 | 0.584946 | esegredo |
1ee6ca3ec182f0d67d3a2ffa921535469bee15ba | 366 | cpp | C++ | src/main.cpp | mwerlberger/cpp11_tutorial | e02e7a1fb61b029681060db97ff16e1b8be53ad1 | [
"BSD-3-Clause"
] | null | null | null | src/main.cpp | mwerlberger/cpp11_tutorial | e02e7a1fb61b029681060db97ff16e1b8be53ad1 | [
"BSD-3-Clause"
] | null | null | null | src/main.cpp | mwerlberger/cpp11_tutorial | e02e7a1fb61b029681060db97ff16e1b8be53ad1 | [
"BSD-3-Clause"
] | null | null | null | // system includes
#include <assert.h>
#include <cstdint>
#include <iostream>
int main(int /*argc*/, char** /*argv*/)
{
try
{
std::cout << "Hello World" << std::endl;
}
catch (std::exception& e)
{
std::cout << "[exception] " << e.what() << std::endl;
assert(false);
}
// std::cout << imp::ok_msg << std::endl;
return EXIT_SUCCESS;
}
| 17.428571 | 57 | 0.557377 | mwerlberger |
1ef07f284291c1d3a93f5d07346049b8236e62f4 | 5,687 | cpp | C++ | lib/src/platform/gtk/dialog.cpp | perjonsson/DeskGap | 5e74de37c057de3bac3ac16b3fabdb79b934d21e | [
"MIT"
] | 1,910 | 2019-02-08T05:41:48.000Z | 2022-03-24T23:41:33.000Z | lib/src/platform/gtk/dialog.cpp | perjonsson/DeskGap | 5e74de37c057de3bac3ac16b3fabdb79b934d21e | [
"MIT"
] | 73 | 2019-02-13T02:58:20.000Z | 2022-03-02T05:49:34.000Z | lib/src/platform/gtk/dialog.cpp | ci010/DeskGap | b3346fea3dd3af7df9a0420131da7f4ac1518092 | [
"MIT"
] | 88 | 2019-02-13T12:41:00.000Z | 2022-03-25T05:04:31.000Z | #include "./BrowserWindow_impl.h"
#include "dialog.hpp"
namespace DeskGap {
namespace {
inline const char* NullableCStr(const std::optional<std::string>& str, const char* fallback = nullptr) {
return str.has_value() ? str->c_str() : fallback;
}
}
struct Dialog::Impl {
static GtkFileChooserDialog* FileChooserDialogNew(
std::optional<std::reference_wrapper<BrowserWindow>> browserWindow,
GtkFileChooserAction action,
const char* defaultCancelLabel,
const char* defaultAcceptLabel,
const Dialog::CommonFileDialogOptions& commonOptions
) {
GtkWidget* dialog = gtk_file_chooser_dialog_new(
NullableCStr(commonOptions.title),
browserWindow.has_value() ? browserWindow->get().impl_->gtkWindow : nullptr,
action,
defaultCancelLabel,
GTK_RESPONSE_CANCEL,
NullableCStr(commonOptions.buttonLabel, defaultAcceptLabel),
GTK_RESPONSE_ACCEPT,
nullptr
);
if (commonOptions.defaultDirectory.has_value()) {
gtk_file_chooser_set_current_folder(
GTK_FILE_CHOOSER(dialog),
commonOptions.defaultDirectory->c_str()
);
}
if (commonOptions.defaultFilename.has_value()) {
gtk_file_chooser_set_current_name(
GTK_FILE_CHOOSER(dialog),
commonOptions.defaultFilename->c_str()
);
}
for (const auto& filter: commonOptions.filters) {
GtkFileFilter* gtkFilter = gtk_file_filter_new();
gtk_file_filter_set_name(gtkFilter, filter.name.c_str());
for (const std::string& extension: filter.extensions) {
gtk_file_filter_add_pattern(gtkFilter, ("*." + extension).c_str());
}
gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), gtkFilter);
}
return GTK_FILE_CHOOSER_DIALOG(dialog);
}
};
void Dialog::ShowErrorBox(const std::string& title, const std::string& content) {
GtkWidget* dialog = gtk_message_dialog_new(
nullptr,
GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
title.c_str(),
content.c_str()
);
gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog), "%s", content.c_str());
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
}
void Dialog::ShowOpenDialog(
std::optional<std::reference_wrapper<BrowserWindow>> browserWindow,
const OpenDialogOptions& options,
Callback<OpenDialogResult>&& callback
) {
GtkFileChooserDialog* dialog = Impl::FileChooserDialogNew(
browserWindow,
(options.properties & OpenDialogOptions::PROPERTY_OPEN_DIRECTORY) != 0 ?
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER :
GTK_FILE_CHOOSER_ACTION_OPEN,
"Cancel", "Open",
options.commonOptions
);
gtk_file_chooser_set_select_multiple(
GTK_FILE_CHOOSER(dialog),
(options.properties & OpenDialogOptions::PROPERTY_MULTI_SELECTIONS) != 0
);
gtk_file_chooser_set_show_hidden(
GTK_FILE_CHOOSER(dialog),
(options.properties & OpenDialogOptions::PROPERTY_SHOW_HIDDEN_FILES) != 0
);
Dialog::OpenDialogResult result;
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
std::vector<std::string> filePaths;
GSList *filenameList = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER (dialog));
GSList* currentNode = filenameList;
while (currentNode != nullptr) {
filePaths.emplace_back(static_cast<const char*>(currentNode->data));
currentNode = currentNode->next;
}
g_slist_free_full(filenameList, g_free);
result.filePaths.emplace(std::move(filePaths));
}
gtk_widget_destroy(GTK_WIDGET(dialog));
callback(std::move(result));
// gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE);
// Dialog::SaveDialogResult result;
// if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
// char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (dialog));
// result.filePath.emplace(filename);
// g_free(filename);
// }
// gtk_widget_destroy(GTK_WIDGET(dialog));
// callback(std::move(result));
}
void Dialog::ShowSaveDialog(
std::optional<std::reference_wrapper<BrowserWindow>> browserWindow,
const SaveDialogOptions& options,
Callback<SaveDialogResult>&& callback
) {
GtkFileChooserDialog* dialog = Impl::FileChooserDialogNew(
browserWindow,
GTK_FILE_CHOOSER_ACTION_SAVE,
"Cancel", "Save",
options.commonOptions
);
gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE);
Dialog::SaveDialogResult result;
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (dialog));
result.filePath.emplace(filename);
g_free(filename);
}
gtk_widget_destroy(GTK_WIDGET(dialog));
callback(std::move(result));
}
}
| 37.913333 | 112 | 0.611043 | perjonsson |
1ef1fd4571a534f87a45240fe528c374e53a8d2c | 10,706 | cpp | C++ | pwiz/data/misc/PeakDataTest.cpp | edyp-lab/pwiz-mzdb | d13ce17f4061596c7e3daf9cf5671167b5996831 | [
"Apache-2.0"
] | 11 | 2015-01-08T08:33:44.000Z | 2019-07-12T06:14:54.000Z | pwiz/data/misc/PeakDataTest.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 61 | 2015-05-27T11:20:11.000Z | 2019-12-20T15:06:21.000Z | pwiz/data/misc/PeakDataTest.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 4 | 2016-02-03T09:41:16.000Z | 2021-08-01T18:42:36.000Z | //
// $Id: PeakDataTest.cpp 4129 2012-11-20 00:05:37Z chambm $
//
//
// Original author: Darren Kessner <darren@proteowizard.org>
//
// Copyright 2007 Spielberg Family Center for Applied Proteomics
// Cedars Sinai Medical Center, Los Angeles, California 90048
//
// 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 "PeakData.hpp"
#include "pwiz/utility/misc/unit.hpp"
#include <boost/filesystem/operations.hpp>
#include "pwiz/utility/misc/Std.hpp"
using namespace pwiz::util;
using namespace pwiz::minimxml;
using namespace pwiz::math;
using namespace pwiz::data::peakdata;
ostream* os_ = 0;
PeakFamily initializePeakFamily()
{
PeakFamily peakFamily;
peakFamily.mzMonoisotopic = 329.86;
peakFamily.charge = 3;
peakFamily.score = 0.11235811;
Peak peak;
Peak a;
Peak boo;
peak.mz = 329.86;
a.mz = 109.87;
boo.mz = 6.022141730;
peakFamily.peaks.push_back(peak);
peakFamily.peaks.push_back(a);
peakFamily.peaks.push_back(boo);
return peakFamily;
}
Scan initializeScan()
{
Scan scan;
scan.index = 12;
scan.nativeID = "24";
scan.scanNumber = 24;
scan.retentionTime = 12.345;
scan.observationDuration = 6.78;
scan.calibrationParameters.A = 987.654;
scan.calibrationParameters.B = 321.012;
PeakFamily flintstones = initializePeakFamily();
PeakFamily jetsons = initializePeakFamily();
scan.peakFamilies.push_back(flintstones);
scan.peakFamilies.push_back(jetsons);
return scan;
}
Software initializeSoftware()
{
Software software;
software.name = "World of Warcraft";
software.version = "Wrath of the Lich King";
software.source = "Blizzard Entertainment";
Software::Parameter parameter1("Burke ping","level 70");
Software::Parameter parameter2("Kate ping", "level 0");
software.parameters.push_back(parameter1);
software.parameters.push_back(parameter2);
return software;
}
PeakData initializePeakData()
{
PeakData pd;
Software software = initializeSoftware();
pd.software = software;
Scan scan = initializeScan();
pd.scans.push_back(scan);
pd.scans.push_back(scan);
return pd;
}
PeakelPtr initializePeakel()
{
PeakelPtr pkl(new Peakel);
pkl->mz = 432.1;
pkl->retentionTime = 1234.56;
pkl->maxIntensity = 9876.54;
pkl->totalIntensity = 32123.45;
pkl->mzVariance = 6.023;
PeakFamily peakFamily = initializePeakFamily();
pkl->peaks = peakFamily.peaks;
return pkl;
}
void testPeakEquality()
{
if (os_) *os_ << "testPeakEquality()" <<endl;
Peak peak;
peak.id = 5;
peak.mz = 1;
peak.retentionTime = 1.5;
peak.intensity = 2;
peak.area = 3;
peak.error = 4;
Peak peak2 = peak;
unit_assert(peak == peak2);
peak.attributes[Peak::Attribute_Phase] = 4.20;
unit_assert(peak != peak2);
peak2.attributes[Peak::Attribute_Phase] = 4.20;
peak2.attributes[Peak::Attribute_Decay] = 6.66;
unit_assert(peak != peak2);
peak.attributes[Peak::Attribute_Decay] = 6.66;
unit_assert(peak == peak2);
}
void testPeak()
{
if (os_) *os_ << "testPeak()" <<endl;
// instantiate a Peak
Peak peak;
peak.id = 5;
peak.mz = 1;
peak.retentionTime = 1.5;
peak.intensity = 2;
peak.area = 3;
peak.error = 4;
peak.data.push_back(OrderedPair(1,2));
peak.data.push_back(OrderedPair(3,4));
peak.attributes[Peak::Attribute_Frequency] = 5;
peak.attributes[Peak::Attribute_Phase] = 6;
peak.attributes[Peak::Attribute_Decay] = 7;
if (os_) *os_ << peak << endl;
// write out XML to a stream
ostringstream oss;
XMLWriter writer(oss);
peak.write(writer);
// allocate a new Peak
Peak peakIn;
unit_assert(peak != peakIn);
// read from stream into new Peak
istringstream iss(oss.str());
peakIn.read(iss);
if (os_) *os_ << peakIn << endl;
// verify that new Peak is the same as old Peak
unit_assert(peak == peakIn);
}
void testPeakFamily()
{
// initialize a PeakFamily
PeakFamily jetsons = initializePeakFamily();
// write out XML to a stream
ostringstream oss;
XMLWriter writer(oss);
jetsons.write(writer);
// instantiate new PeakFamily
PeakFamily flintstones;
// read from stream into new PeakFamily
istringstream iss(oss.str());
flintstones.read(iss);
// verify that new PeakFamily is the same as old PeakFamily
unit_assert(flintstones == jetsons);
if (os_) *os_ << "Testing PeakFamily ... " << endl << oss.str() <<endl;
}
void testScan()
{
// initialize a new Scan
Scan scan = initializeScan();
// write out XML to a stream
ostringstream oss_scan;
XMLWriter writer_scan(oss_scan);
scan.write(writer_scan);
// instantiate a second Scan
Scan scan2;
// read it back in
istringstream iss_scan(oss_scan.str());
scan2.read(iss_scan);
// assert that the two Scans are equal
unit_assert(scan == scan2);
if (os_) *os_ << "Testing Scan ... " << endl << oss_scan.str() << endl;
}
void testSoftware()
{
// initialize a new Software
Software software = initializeSoftware();
// write out XML to a stream
ostringstream oss_soft;
XMLWriter writer_soft(oss_soft);
software.write(writer_soft);
// instantiate another Software
Software software2;
// read it back in
istringstream iss_soft(oss_soft.str());
software2.read(iss_soft);
// assert that the two Softwares are equal
unit_assert(software == software2);
if (os_) *os_ << "Testing Software ... " << endl << oss_soft.str() <<endl;
}
void testPeakData()
{
// initialize a PeakData
PeakData pd = initializePeakData();
ostringstream oss_pd;
XMLWriter writer_pd(oss_pd);
pd.write(writer_pd);
// instantiate another PeakData
PeakData pd2;
// read into it
istringstream iss_pd(oss_pd.str());
pd2.read(iss_pd);
// assert that the two PeakData are equal
unit_assert(pd == pd2);
if (os_) *os_ << "Testing PeakData ... " << endl << oss_pd.str()<<endl;
}
void testPeakel()
{
// initialize a peakel
PeakelPtr dill = initializePeakel();
// write it out
ostringstream oss_pkl;
XMLWriter writer_pkl(oss_pkl);
dill->write(writer_pkl);
// instantiate another Peakel
Peakel gherkin;
// read into it
istringstream iss_pkl(oss_pkl.str());
gherkin.read(iss_pkl);
// assert that the two Peakels are equal
unit_assert(*dill == gherkin);
if (os_) *os_ << "Testing Peakel ... " << endl << oss_pkl.str() << endl;
}
void testPeakelAux()
{
Peakel p;
p.retentionTime = 420;
unit_assert(p.retentionTimeMin() == 420);
unit_assert(p.retentionTimeMax() == 420);
p.peaks.resize(2);
p.peaks[0].retentionTime = 666;
p.peaks[1].retentionTime = 667;
unit_assert(p.retentionTimeMin() == 666);
unit_assert(p.retentionTimeMax() == 667);
}
void testPeakelConstruction()
{
Peak peak(420, 666);
Peakel peakel(Peak(420,666));
unit_assert(peakel.mz == 420);
unit_assert(peakel.retentionTime == 666);
unit_assert(peakel.peaks.size() == 1);
unit_assert(peakel.peaks[0] == peak);
}
void testFeature()
{
// initialize a new Feature
Feature feature;
feature.mz = 1863.0101;
feature.retentionTime = 1492.1012;
feature.charge = 3;
feature.totalIntensity = 1776.0704;
feature.rtVariance = 1969.0720;
feature.score = 420.0;
feature.error = 666.0;
PeakelPtr stateFair = initializePeakel();
PeakelPtr deli = initializePeakel();
feature.peakels.push_back(stateFair);
feature.peakels.push_back(deli);
// write it out
ostringstream oss_f;
XMLWriter writer_f(oss_f);
feature.write(writer_f);
// instantiate another feature
Feature feature2;
// read into it
istringstream iss(oss_f.str());
feature2.read(iss);
// assert that the two Features are equal
if (os_)
{
*os_ << "Testing Feature ... " << endl << oss_f.str() << endl;
*os_ << "feature2:\n";
XMLWriter writer(*os_);
feature2.write(writer);
}
unit_assert(feature == feature2);
}
void testFeatureAux()
{
Feature feature;
feature.retentionTime = 420;
unit_assert(feature.retentionTimeMin() == 420);
unit_assert(feature.retentionTimeMax() == 420);
// retention time ranges determined by first two peakels
PeakelPtr dill(new Peakel);
dill->peaks.push_back(Peak(666,419));
dill->peaks.push_back(Peak(666,423));
PeakelPtr sweet(new Peakel);
sweet->peaks.push_back(Peak(666,421));
sweet->peaks.push_back(Peak(666,424));
PeakelPtr gherkin(new Peakel);
gherkin->peaks.push_back(Peak(666,418));
gherkin->peaks.push_back(Peak(666,425));
feature.peakels.push_back(dill);
feature.peakels.push_back(sweet);
feature.peakels.push_back(gherkin);
unit_assert(feature.retentionTimeMin() == 419);
unit_assert(feature.retentionTimeMax() == 424);
}
void test()
{
testPeakEquality();
testPeak();
testPeakFamily();
testScan();
testSoftware();
testPeakData();
testPeakel();
testPeakelAux();
testPeakelConstruction();
testFeature();
testFeatureAux();
}
int main(int argc, char* argv[])
{
TEST_PROLOG(argc, argv)
try
{
if (argc>1 && !strcmp(argv[1],"-v")) os_ = &cout;
if (os_) *os_ << "PeakDataTest\n";
test();
}
catch (exception& e)
{
TEST_FAILED(e.what())
}
catch (...)
{
TEST_FAILED("Caught unknown exception.")
}
TEST_EPILOG
}
| 22.211618 | 180 | 0.6204 | edyp-lab |
1ef6aab4ec1b0b6130682c2a119de5a12944fce4 | 3,277 | cpp | C++ | Day 18/solution2.cpp | Ocete/Advent-Of-Code-2017 | 201295b6ac7a2dfdb149ab3e6709525708ca66dd | [
"MIT"
] | 1 | 2018-02-02T20:07:01.000Z | 2018-02-02T20:07:01.000Z | Day 18/solution2.cpp | Ocete/Advent-Of-Code-2017 | 201295b6ac7a2dfdb149ab3e6709525708ca66dd | [
"MIT"
] | null | null | null | Day 18/solution2.cpp | Ocete/Advent-Of-Code-2017 | 201295b6ac7a2dfdb149ab3e6709525708ca66dd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <list>
using namespace std;
void ReadCode (vector<vector<string> > & code) {
code.clear();
string str;
cin >> str;
while (cin) {
vector<string> new_line;
new_line.push_back(str);
if (str != "snd" && str != "rcv" ){
cin >> str;
new_line.push_back(str);
}
cin >> str;
new_line.push_back(str);
code.push_back(new_line);
cin >> str;
}
}
void PrintCode(vector<vector<string> > & code) {
for (vector<vector<string> >::iterator it1 = code.begin(); it1!=code.end(); it1++){
for (vector<string>::iterator it2=(*it1).begin(); it2!=(*it1).end(); it2++) {
cout << *it2 << " ";
}
cout << endl;
}
}
int ctoi(char c) {
return c - 'a';
}
void PrintRegisters(const vector<long long unsigned> & registers) {
for (char c='a'; c<='z'; c++) {
cout << c << " -> " << registers[ctoi(c)] << endl;
}
}
int RegisterToInt(vector<long long unsigned> registers, string r) {
if (r[0] >= 'a' && r[0] <= 'z')
return registers[ ctoi(r[0]) ];
else
return atoi( r.c_str() );
}
void Operation(const vector<vector<string> > & code, vector<long long unsigned> & registers,
int & PC, list<long long unsigned> & my_queue, list<long long unsigned> & other_queue,
bool & i_stopped, bool & other_stopped, unsigned & num_sent) {
string op = code[PC][0];
if (op == "add") {
registers[ctoi( code[PC][1][0] )] += RegisterToInt(registers, code[PC][2]);
PC++;
} else if (op == "mul") {
registers[ctoi( code[PC][1][0] )] *= RegisterToInt(registers, code[PC][2]);
PC++;
} else if (op == "mod") {
registers[ctoi( code[PC][1][0] )] %= RegisterToInt(registers, code[PC][2]);
PC++;
} else if (op == "set") {
registers[ctoi( code[PC][1][0] )] = RegisterToInt(registers, code[PC][2]);
PC++;
} else if (op == "snd") {
other_queue.push_back( RegisterToInt(registers, code[PC][1]) );
other_stopped = false;
PC++;
num_sent++;
} else if (op == "rcv") {
if ( my_queue.empty() ) {
i_stopped = true;
} else {
registers[ctoi( code[PC][1][0] )] = my_queue.front();
my_queue.pop_front();
PC++;
}
} else if (op == "jgz") {
if ( RegisterToInt(registers, code[PC][1]) > 0) {
PC += RegisterToInt(registers, code[PC][2]);
} else {
PC++;
}
} else {
cout << "This shoud never appear" << endl;
}
}
int Duet() {
vector<vector<string> > code;
vector<long long unsigned> registers0, registers1;
list<long long unsigned> queue0, queue1;
int PC0 = 0, PC1 = 0;
unsigned num_sent0 = 0, num_sent1 = 0;
bool stopped0 = false, stopped1 = false;
ReadCode(code);
//PrintCode(code);
for (char c='a'; c<='z'; c++) {
registers0.push_back(0);
if (c == 'p')
registers1.push_back(1);
else
registers1.push_back(0);
}
while ( !stopped0 || !stopped1 ) {
if (!stopped0) {
Operation (code, registers0, PC0, queue0, queue1, stopped0, stopped1, num_sent0);
} else {
Operation (code, registers1, PC1, queue1, queue0, stopped1, stopped0, num_sent1);
}
}
//PrintRegisters(registers0);
//PrintRegisters(registers1);
return num_sent1;
}
int main() {
cout << "\tSolucion: " << Duet() << endl;
}
| 25.403101 | 92 | 0.575526 | Ocete |
1ef7f1c2d833232fe7f318f76626a80379ce42d9 | 4,087 | cpp | C++ | 3rdParty/boost/1.77.0/libs/asio/test/experimental/coro/exception.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | 106 | 2015-08-07T04:23:50.000Z | 2020-12-27T18:25:15.000Z | 3rdParty/boost/1.77.0/libs/asio/test/experimental/coro/exception.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | 130 | 2016-06-22T22:11:25.000Z | 2020-11-29T20:24:09.000Z | 3rdParty/boost/1.77.0/libs/asio/test/experimental/coro/exception.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | 41 | 2015-07-08T19:18:35.000Z | 2021-01-14T16:39:56.000Z | //
// experimental/coro/exception.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// 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)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include <boost/asio/experimental/coro.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/use_awaitable.hpp>
#include <boost/asio/awaitable.hpp>
#include "../../unit_test.hpp"
using namespace boost::asio::experimental;
namespace coro {
template <typename Func>
struct on_scope_exit
{
Func func;
static_assert(noexcept(func()));
on_scope_exit(const Func &f)
: func(static_cast< Func && >(f))
{
}
on_scope_exit(Func &&f)
: func(f)
{
}
on_scope_exit(const on_scope_exit &) = delete;
~on_scope_exit()
{
func();
}
};
boost::asio::experimental::coro<int> throwing_generator(
boost::asio::any_io_executor, int &last, bool &destroyed)
{
on_scope_exit x = [&]() noexcept { destroyed = true; };
(void)x;
int i = 0;
while (i < 3)
co_yield last = ++i;
throw std::runtime_error("throwing-generator");
}
boost::asio::awaitable<void> throwing_generator_test()
{
int val = 0;
bool destr = false;
{
auto gi = throwing_generator(
co_await boost::asio::this_coro::executor,
val, destr);
bool caught = false;
try
{
for (int i = 0; i < 10; i++)
{
BOOST_ASIO_CHECK(val == i);
const auto next = co_await gi.async_resume(boost::asio::use_awaitable);
BOOST_ASIO_CHECK(next);
BOOST_ASIO_CHECK(val == *next);
BOOST_ASIO_CHECK(val == i + 1);
}
}
catch (std::runtime_error &err)
{
caught = true;
using std::operator ""sv;
BOOST_ASIO_CHECK(err.what() == "throwing-generator"sv);
}
BOOST_ASIO_CHECK(val == 3);
BOOST_ASIO_CHECK(caught);
}
BOOST_ASIO_CHECK(destr);
};
void run_throwing_generator_test()
{
boost::asio::io_context ctx;
boost::asio::co_spawn(ctx, throwing_generator_test(), boost::asio::detached);
ctx.run();
}
boost::asio::experimental::coro<int(int)> throwing_stacked(
boost::asio::any_io_executor exec, int &val,
bool &destroyed_inner, bool &destroyed)
{
on_scope_exit x = [&]() noexcept { destroyed = true; };
(void)x;
auto gen = throwing_generator(exec, val, destroyed_inner);
while (auto next = co_await gen) // 1, 2, 4, 8, ...
BOOST_ASIO_CHECK(42 ==(co_yield *next)); // offset is delayed by one cycle
}
boost::asio::awaitable<void> throwing_generator_stacked_test()
{
int val = 0;
bool destr = false, destr_inner = false;
{
auto gi = throwing_stacked(
co_await boost::asio::this_coro::executor,
val, destr, destr_inner);
bool caught = false;
try
{
for (int i = 0; i < 10; i++)
{
BOOST_ASIO_CHECK(val == i);
const auto next =
co_await gi.async_resume(42, boost::asio::use_awaitable);
BOOST_ASIO_CHECK(next);
BOOST_ASIO_CHECK(val == *next);
BOOST_ASIO_CHECK(val == i + 1);
}
}
catch (std::runtime_error &err)
{
caught = true;
using std::operator ""sv;
BOOST_ASIO_CHECK(err.what() == "throwing-generator"sv);
}
BOOST_ASIO_CHECK(val == 3);
BOOST_ASIO_CHECK(caught);
}
BOOST_ASIO_CHECK(destr);
BOOST_ASIO_CHECK(destr_inner);
};
void run_throwing_generator_stacked_test()
{
boost::asio::io_context ctx;
boost::asio::co_spawn(ctx,
throwing_generator_stacked_test,
boost::asio::detached);
ctx.run();
}
} // namespace coro
BOOST_ASIO_TEST_SUITE
(
"coro/exception",
BOOST_ASIO_TEST_CASE(::coro::run_throwing_generator_stacked_test)
BOOST_ASIO_TEST_CASE(::coro::run_throwing_generator_test)
)
| 23.900585 | 79 | 0.649865 | Mu-L |
1ef9dcfadf57af939eb6934da5e0edde6fc2abc0 | 901 | cpp | C++ | MultiComposite/MultiComposite/Compositor.cpp | DrPotatoNet/MultiComposite | d71e065661a55b22bfcec8b162859e4fbec18782 | [
"MIT"
] | 2 | 2020-09-06T08:14:15.000Z | 2020-09-06T19:03:12.000Z | MultiComposite/MultiComposite/Compositor.cpp | Bluscream/MultiComposite | eac46d3fc7167629181b0652087cb6c2ab12747a | [
"MIT"
] | 4 | 2020-09-07T09:50:31.000Z | 2020-09-30T05:16:31.000Z | MultiComposite/MultiComposite/Compositor.cpp | Bluscream/MultiComposite | eac46d3fc7167629181b0652087cb6c2ab12747a | [
"MIT"
] | 1 | 2020-09-29T20:57:15.000Z | 2020-09-29T20:57:15.000Z | #include "Compositor.h"
#include <cassert>
#include "Logger.h"
#include <string>
ICompositor* ICompositor::pD11Compositor;
D3D_FEATURE_LEVEL featureLevel;
UINT flags = D3D11_CREATE_DEVICE_SINGLETHREADED;
void D3D11Compositor::Init()
{
HRESULT hr = D3D11CreateDevice(
NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
D3D11_CREATE_DEVICE_DEBUG,
NULL,
0,
D3D11_SDK_VERSION,
&pDevice,
&featureLevel,
&pContext);
assert(S_OK == hr && pDevice && pContext);
}
void D3D11Compositor::SetupTexture(vr::Texture_t* texture, HANDLE handle)
{
if (handle == nullptr)
return;
pDevice->OpenSharedResource(handle, __uuidof(ID3D11Texture2D), (void**)&texture->handle);
}
void D3D11Compositor::ReleaseTexture(vr::Texture_t* texture)
{
((ID3D11Texture2D*)texture->handle)->Release();
texture->handle = nullptr;
}
| 21.452381 | 93 | 0.674806 | DrPotatoNet |
1efa947bdb52c2df00c3e74faa120ae5d53fab46 | 7,679 | cpp | C++ | Microsoft.WindowsAzure.Storage/src/xml_wrapper.cpp | JasonDictos/azure-storage-cpp | 8accecace59ad631cd7686f9e11fa7498fe717ac | [
"Apache-2.0"
] | null | null | null | Microsoft.WindowsAzure.Storage/src/xml_wrapper.cpp | JasonDictos/azure-storage-cpp | 8accecace59ad631cd7686f9e11fa7498fe717ac | [
"Apache-2.0"
] | null | null | null | Microsoft.WindowsAzure.Storage/src/xml_wrapper.cpp | JasonDictos/azure-storage-cpp | 8accecace59ad631cd7686f9e11fa7498fe717ac | [
"Apache-2.0"
] | 2 | 2020-04-06T11:22:08.000Z | 2020-11-14T19:16:58.000Z | /***
* ==++==
*
* Copyright (c) Microsoft Corporation. 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.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* xml_wrapper.cpp
*
* This file contains wrapper for libxml2
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
#include "wascore/xml_wrapper.h"
#ifndef _WIN32
namespace azure { namespace storage { namespace core { namespace xml {
std::string xml_char_to_string(const xmlChar * xml_char)
{
return std::string(reinterpret_cast<const char*>(xml_char));
}
xml_text_reader_wrapper::xml_text_reader_wrapper(const unsigned char * buffer, unsigned int size)
{
m_reader = xmlReaderForMemory((const char*)buffer, size, NULL, 0, 0);
}
xml_text_reader_wrapper::~xml_text_reader_wrapper()
{
if (!m_reader)
{
xmlFreeTextReader(m_reader);
m_reader = nullptr;
}
}
bool xml_text_reader_wrapper::read()
{
return xmlTextReaderRead(m_reader) != 0;
}
unsigned xml_text_reader_wrapper::get_node_type()
{
return xmlTextReaderNodeType(m_reader);
}
bool xml_text_reader_wrapper::is_empty_element()
{
return xmlTextReaderIsEmptyElement(m_reader) != 0;
}
std::string xml_text_reader_wrapper::get_local_name()
{
return xml_char_to_string(xmlTextReaderLocalName(m_reader));
}
std::string xml_text_reader_wrapper::get_value()
{
return xml_char_to_string(xmlTextReaderValue(m_reader));
}
bool xml_text_reader_wrapper::move_to_first_attribute()
{
return xmlTextReaderMoveToFirstAttribute(m_reader) != 0;
}
bool xml_text_reader_wrapper::move_to_next_attribute()
{
return xmlTextReaderMoveToNextAttribute(m_reader) != 0;
}
xml_element_wrapper::~xml_element_wrapper()
{
}
xml_element_wrapper::xml_element_wrapper(xmlNode * node)
{
m_ele = node;
m_ele->_private = this;
}
xml_element_wrapper * xml_element_wrapper::add_child(const std::string & name, const std::string & prefix)
{
xmlNs* ns = nullptr;
xmlNode* child = nullptr;
if (m_ele->type != XML_ELEMENT_NODE)
{
return nullptr;
}
if (!prefix.empty())
{
ns = xmlSearchNs(m_ele->doc, m_ele, (const xmlChar*)prefix.c_str());
if (!ns)
{
return nullptr;
}
}
child = xmlNewNode(ns, (const xmlChar*)name.c_str()); //mem leak?
if (!child)
return nullptr;
xmlNode* node = xmlAddChild(m_ele, child);
if (!node)
return nullptr;
node->_private = new xml_element_wrapper(node);
return reinterpret_cast<xml_element_wrapper*>(node->_private);
}
void xml_element_wrapper::set_namespace_declaration(const std::string & uri, const std::string & prefix)
{
xmlNewNs(m_ele, (const xmlChar*)(uri.empty() ? nullptr : uri.c_str()),
(const xmlChar*)(prefix.empty() ? nullptr : prefix.c_str()));
}
void xml_element_wrapper::set_namespace(const std::string & prefix)
{
xmlNs* ns = xmlSearchNs(m_ele->doc, m_ele, (xmlChar*)(prefix.empty() ? nullptr : prefix.c_str()));
if (ns)
{
xmlSetNs(m_ele, ns);
}
}
void xml_element_wrapper::set_attribute(const std::string & name, const std::string & value, const std::string & prefix)
{
xmlAttr* attr = 0;
if (prefix.empty())
{
attr = xmlSetProp(m_ele, (const xmlChar*)name.c_str(), (const xmlChar*)value.c_str());
}
else
{
xmlNs* ns = xmlSearchNs(m_ele->doc, m_ele, (const xmlChar*)prefix.c_str());
if (ns)
{
attr = xmlSetNsProp(m_ele, ns, (const xmlChar*)name.c_str(),
(const xmlChar*)value.c_str());
}
else
{
return;
}
}
if (attr)
{
attr->_private = new xml_element_wrapper(reinterpret_cast<xmlNode*>(attr));
}
}
void xml_element_wrapper::set_child_text(const std::string & text)
{
xml_element_wrapper* node = nullptr;
for (xmlNode* child = m_ele->children; child; child = child->next)
if (child->type == xmlElementType::XML_TEXT_NODE)
{
child->_private = new xml_element_wrapper(child);
node = reinterpret_cast<xml_element_wrapper*>(child->_private);
}
if (node)
{
if (node->m_ele->type != xmlElementType::XML_ELEMENT_NODE)
{
xmlNodeSetContent(node->m_ele, (xmlChar*)text.c_str());
}
}
else {
if (m_ele->type == XML_ELEMENT_NODE)
{
xmlNode* node = xmlNewText((const xmlChar*)text.c_str());
node = xmlAddChild(m_ele, node);
node->_private = new xml_element_wrapper(node);
}
}
}
void xml_element_wrapper::free_wrappers(xmlNode * node)
{
if (!node)
return;
for (xmlNode* child = node->children; child; child = child->next)
free_wrappers(child);
switch (node->type)
{
case XML_DTD_NODE:
case XML_ELEMENT_DECL:
case XML_ATTRIBUTE_NODE:
case XML_ATTRIBUTE_DECL:
case XML_ENTITY_DECL:
if (node->_private)
{
delete reinterpret_cast<xml_element_wrapper*>(node->_private);
node->_private = nullptr;
}
break;
case XML_DOCUMENT_NODE:
break;
default:
if (node->_private)
{
delete reinterpret_cast<xml_element_wrapper*>(node->_private);
node->_private = nullptr;
}
break;
}
}
xml_document_wrapper::xml_document_wrapper()
{
m_doc = xmlNewDoc(reinterpret_cast<const xmlChar*>("1.0"));
}
xml_document_wrapper::~xml_document_wrapper()
{
xml_element_wrapper::free_wrappers(reinterpret_cast<xmlNode*>(m_doc));
xmlFreeDoc(m_doc);
m_doc = nullptr;
}
std::string xml_document_wrapper::write_to_string()
{
xmlIndentTreeOutput = 0;
xmlChar* buffer = 0;
int size = 0;
xmlDocDumpFormatMemoryEnc(m_doc, &buffer, &size, 0, 0);
std::string result;
if (buffer)
{
result = std::string(reinterpret_cast<const char *>(buffer), reinterpret_cast<const char *>(buffer + size));
xmlFree(buffer);
}
return result;
}
xml_element_wrapper* xml_document_wrapper::create_root_node(const std::string & name, const std::string & namespace_name, const std::string & prefix)
{
xmlNode* node = xmlNewDocNode(m_doc, 0, (const xmlChar*)name.c_str(), 0);
xmlDocSetRootElement(m_doc, node);
xml_element_wrapper* element = get_root_node();
if (!namespace_name.empty())
{
element->set_namespace_declaration(namespace_name, prefix);
element->set_namespace(prefix);
}
return element;
}
xml_element_wrapper* xml_document_wrapper::get_root_node() const
{
xmlNode* root = xmlDocGetRootElement(m_doc);
if (root == NULL)
return NULL;
else
{
root->_private = new xml_element_wrapper(root);
return reinterpret_cast<xml_element_wrapper*>(root->_private);
}
return nullptr;
}
}}}};// namespace azure::storage::core::xml
#endif //#ifdef _WIN32
| 25.768456 | 149 | 0.63029 | JasonDictos |
1efd3eec8179fcabb009c7b871ffb59ca240e0f0 | 519 | cpp | C++ | HDUOJ/2107/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | HDUOJ/2107/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | HDUOJ/2107/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
#include <climits>
#include <iomanip>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int num;
while (cin >> num)
{
if (num == 0)
break;
int maxAC = -1;
for (int i = 0; i < num; i++)
{
int cnt;
cin >> cnt;
maxAC = max(maxAC, cnt);
}
cout << maxAC << endl;
}
return 0;
}
| 17.3 | 37 | 0.493256 | codgician |
480045f02400a442128bc7f8dac3c4f556842671 | 845 | cpp | C++ | examples/convex_hull/example_small.cpp | digu-007/Boost_Geometry_Competency_Test_2020 | 53a75c82ddf29bc7f842e653e2a1664839113b53 | [
"MIT"
] | null | null | null | examples/convex_hull/example_small.cpp | digu-007/Boost_Geometry_Competency_Test_2020 | 53a75c82ddf29bc7f842e653e2a1664839113b53 | [
"MIT"
] | null | null | null | examples/convex_hull/example_small.cpp | digu-007/Boost_Geometry_Competency_Test_2020 | 53a75c82ddf29bc7f842e653e2a1664839113b53 | [
"MIT"
] | null | null | null | /*
Boost Competency Test - GSoC 2020
digu_J - Digvijay Janartha
NIT Hamirpur - INDIA
*/
#include <algorithm>
#include <iostream>
#include <utility>
#include "../../includes/convex_hull_gift_wrapping.hpp"
#include <boost/geometry/geometry.hpp>
namespace bg = boost::geometry;
using bg::dsv;
int main()
{
typedef bg::model::point<double, 2, bg::cs::cartesian> point_t;
typedef bg::model::multi_point<point_t> mpoint_t;
mpoint_t mpt1, hull;
bg::read_wkt("MULTIPOINT(0 0,6 0,2 2,4 2,5 3,5 5,-2 2)", mpt1);
algo1::GiftWrapping(mpt1, hull);
std::cout << "Dataset: " << dsv(mpt1) << std::endl;
std::cout << "Convex hull: " << dsv(hull) << std::endl;
return 0;
}
/*
Output:
Dataset: ((0, 0), (6, 0), (2, 2), (4, 2), (5, 3), (5, 5), (-2, 2))
Convex hull: ((-2, 2), (0, 0), (6, 0), (5, 5), (-2, 2))
*/ | 22.236842 | 67 | 0.595266 | digu-007 |
4803a70814664920e2971465545e5535280eedd8 | 31,198 | cc | C++ | gobi-cromo-plugin/gobi_gsm_modem.cc | doitmovin/chromiumos-platform2 | 6462aaf43072307b5a40eb045a89e473381b5fda | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | gobi-cromo-plugin/gobi_gsm_modem.cc | doitmovin/chromiumos-platform2 | 6462aaf43072307b5a40eb045a89e473381b5fda | [
"BSD-3-Clause"
] | null | null | null | gobi-cromo-plugin/gobi_gsm_modem.cc | doitmovin/chromiumos-platform2 | 6462aaf43072307b5a40eb045a89e473381b5fda | [
"BSD-3-Clause"
] | 2 | 2021-01-26T12:37:19.000Z | 2021-05-18T13:37:57.000Z | // Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gobi-cromo-plugin/gobi_gsm_modem.h"
#include <ctype.h> // for isspace(), to implement TrimWhitespaceASCII()
#include <stdio.h> // for sscanf()
#include <memory>
#include <sstream>
#include <base/macros.h>
#include <cromo/carrier.h>
#include <cromo/sms_message.h>
#include <mm/mm-modem.h>
#include "gobi-cromo-plugin/gobi_modem_handler.h"
using cromo::SmsMessage;
using cromo::SmsMessageFragment;
static const uint32_t kPinRetriesNotKnown = 999;
//======================================================================
// Construct and destruct
GobiGsmModem::~GobiGsmModem() {}
//======================================================================
// Callbacks and callback utilities
void GobiGsmModem::SignalStrengthHandler(INT8 signal_strength,
ULONG radio_interface) {
unsigned long ss_percent = MapDbmToPercent(signal_strength);
// TODO(ers) make sure radio interface corresponds to the network
// on which we're registered
SignalQuality(ss_percent); // NB: org.freedesktop...Modem.Gsm.Network
// See whether we're going from no signal to signal. If so, that's an
// indication that we're now registered on a network, so get registration
// info and send it out.
if (!signal_available_) {
signal_available_ = true;
RegistrationStateHandler();
}
}
void GobiGsmModem::RegistrationStateHandler() {
uint32_t registration_status;
std::string operator_code;
std::string operator_name;
DBus::Error error;
LOG(INFO) << "RegistrationStateHandler";
GetGsmRegistrationInfo(®istration_status,
&operator_code, &operator_name, error);
if (!error) {
MMModemState mm_modem_state;
RegistrationInfo(registration_status, operator_code, operator_name);
switch (registration_status) {
case MM_MODEM_GSM_NETWORK_REG_STATUS_IDLE:
case MM_MODEM_GSM_NETWORK_REG_STATUS_DENIED:
mm_modem_state = MM_MODEM_STATE_ENABLED;
break;
case MM_MODEM_GSM_NETWORK_REG_STATUS_HOME:
case MM_MODEM_GSM_NETWORK_REG_STATUS_ROAMING:
// The modem may reregister with the network when starting the data
// session. Ignore the state changes associated with the
// reregistration.
if ((mm_state() == MM_MODEM_STATE_REGISTERED ||
mm_state() == MM_MODEM_STATE_CONNECTING) &&
session_starter_in_flight_)
mm_modem_state = MM_MODEM_STATE_CONNECTING;
else
mm_modem_state = MM_MODEM_STATE_REGISTERED;
break;
case MM_MODEM_GSM_NETWORK_REG_STATUS_SEARCHING:
// The modem may reregister with the network when starting the data
// session. Ignore the state changes associated with the
// reregistration.
if (session_starter_in_flight_)
mm_modem_state = MM_MODEM_STATE_CONNECTING;
else
mm_modem_state = MM_MODEM_STATE_SEARCHING;
break;
case MM_MODEM_GSM_NETWORK_REG_STATUS_UNKNOWN:
mm_modem_state = MM_MODEM_STATE_ENABLED; // ???
break;
default:
LOG(ERROR) << "Unknown registration status: " << registration_status;
mm_modem_state = MM_MODEM_STATE_ENABLED; // ???
break;
}
if (mm_modem_state != MM_MODEM_STATE_REGISTERED ||
mm_state() <= MM_MODEM_STATE_SEARCHING)
SetMmState(mm_modem_state, MM_MODEM_STATE_CHANGED_REASON_UNKNOWN);
}
}
#define MASKVAL(cap) (1 << static_cast<int>(cap))
#define HASCAP(mask, cap) (mask & MASKVAL(cap))
static uint32_t DataCapabilitiesToMmAccessTechnology(BYTE num_data_caps,
ULONG* data_caps) {
uint32_t capmask = 0;
if (num_data_caps == 0) // TODO(ers) indicates not registered?
return MM_MODEM_GSM_ACCESS_TECH_UNKNOWN;
// Put the values into a bit mask, where they'll be easier
// to work with.
for (int i = 0; i < num_data_caps; i++) {
LOG(INFO) << " Cap: " << static_cast<int>(data_caps[i]);
if (data_caps[i] >= gobi::kDataCapGprs &&
data_caps[i] <= gobi::kDataCapGsm)
capmask |= 1 << static_cast<int>(data_caps[i]);
}
// Of the data capabilities reported, select the one with the
// highest theoretical bandwidth.
uint32_t mm_access_tech;
switch (capmask & (MASKVAL(gobi::kDataCapHsdpa) |
(MASKVAL(gobi::kDataCapHsupa)))) {
case MASKVAL(gobi::kDataCapHsdpa) | MASKVAL(gobi::kDataCapHsupa):
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_HSPA;
break;
case MASKVAL(gobi::kDataCapHsupa):
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_HSUPA;
break;
case MASKVAL(gobi::kDataCapHsdpa):
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_HSDPA;
break;
default:
if (HASCAP(capmask, gobi::kDataCapWcdma))
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_UMTS;
else if (HASCAP(capmask, gobi::kDataCapEdge))
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_EDGE;
else if (HASCAP(capmask, gobi::kDataCapGprs))
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_GPRS;
else if (HASCAP(capmask, gobi::kDataCapGsm))
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_GSM;
else
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_UNKNOWN;
break;
}
LOG(INFO) << "MM access tech: " << mm_access_tech;
return mm_access_tech;
}
#undef MASKVAL
#undef HASCAP
void GobiGsmModem::DataCapabilitiesHandler(BYTE num_data_caps,
ULONG* data_caps) {
LOG(INFO) << "GsmDataCapabilitiesHandler";
uint32_t registration_status;
std::string operator_code;
std::string operator_name;
DBus::Error error;
// Sometimes when we lose registration, we don't get a
// RegistrationStateChange callback, but we often do get
// a DataCapabilitiesHandler callback!
GetGsmRegistrationInfo(®istration_status,
&operator_code, &operator_name, error);
// The modem may reregister with the network when starting the data
// session. Ignore the state changes associated with the reregistration.
if (registration_status == MM_MODEM_GSM_NETWORK_REG_STATUS_SEARCHING &&
session_starter_in_flight_)
return;
switch (registration_status) {
case MM_MODEM_GSM_NETWORK_REG_STATUS_IDLE:
case MM_MODEM_GSM_NETWORK_REG_STATUS_DENIED:
RegistrationInfo(registration_status, operator_code, operator_name);
SetMmState(MM_MODEM_STATE_ENABLED, MM_MODEM_STATE_CHANGED_REASON_UNKNOWN);
break;
case MM_MODEM_GSM_NETWORK_REG_STATUS_SEARCHING:
RegistrationInfo(registration_status, operator_code, operator_name);
SetMmState(MM_MODEM_STATE_SEARCHING,
MM_MODEM_STATE_CHANGED_REASON_UNKNOWN);
break;
case MM_MODEM_GSM_NETWORK_REG_STATUS_UNKNOWN:
// Ignore the unknown state. The registration state will
// eventually be reported as IDLE, SEACHING, DENIED, etc...
break;
case MM_MODEM_GSM_NETWORK_REG_STATUS_ROAMING:
case MM_MODEM_GSM_NETWORK_REG_STATUS_HOME:
// The modem may reregister with the network when starting the data
// session. Ignore the state changes associated with the
// reregistration.
if (mm_state() == MM_MODEM_STATE_REGISTERED &&
session_starter_in_flight_)
SetMmState(MM_MODEM_STATE_CONNECTING,
MM_MODEM_STATE_CHANGED_REASON_UNKNOWN);
SendNetworkTechnologySignal(
DataCapabilitiesToMmAccessTechnology(num_data_caps, data_caps));
break;
}
}
void GobiGsmModem::DataBearerTechnologyHandler(ULONG technology) {
uint32_t mm_access_tech;
LOG(INFO) << "DataBearerTechnologyHandler: " << technology;
switch (technology) {
case gobi::kDataBearerGprs:
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_GPRS;
break;
case gobi::kDataBearerWcdma:
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_UMTS;
break;
case gobi::kDataBearerEdge:
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_EDGE;
break;
case gobi::kDataBearerHsdpaDlWcdmaUl:
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_HSDPA;
break;
case gobi::kDataBearerWcdmaDlUsupaUl:
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_HSUPA;
break;
case gobi::kDataBearerHsdpaDlHsupaUl:
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_HSPA;
break;
default:
mm_access_tech = MM_MODEM_GSM_ACCESS_TECH_UNKNOWN;
break;
}
SendNetworkTechnologySignal(mm_access_tech);
}
void GobiGsmModem::SendNetworkTechnologySignal(uint32_t mm_access_tech) {
if (mm_access_tech != MM_MODEM_GSM_ACCESS_TECH_UNKNOWN) {
AccessTechnology = mm_access_tech;
utilities::DBusPropertyMap props;
props["AccessTechnology"].writer().append_uint32(mm_access_tech);
MmPropertiesChanged(
org::freedesktop::ModemManager::Modem::Gsm::Network_adaptor
::introspect()->name, props);
}
}
gboolean GobiGsmModem::CheckDataCapabilities(gpointer data) {
CallbackArgs* args = static_cast<CallbackArgs*>(data);
GobiGsmModem* modem =
static_cast<GobiGsmModem *>(handler_->LookupByDbusPath(*args->path));
if (modem)
modem->SendNetworkTechnologySignal(modem->GetMmAccessTechnology());
return FALSE;
}
gboolean GobiGsmModem::NewSmsCallback(gpointer data) {
NewSmsArgs* args = static_cast<NewSmsArgs*>(data);
LOG(INFO) << "New SMS Callback: type " << args->storage_type
<< " index " << args->message_index;
GobiGsmModem* modem =
static_cast<GobiGsmModem *>(handler_->LookupByDbusPath(*args->path));
if (!modem)
return FALSE;
DBus::Error error;
SmsMessage* sms = modem->sms_cache_.SmsReceived(args->message_index, error,
modem);
if (error.is_set())
return FALSE;
modem->SmsReceived(sms->index(), sms->IsComplete());
return FALSE;
}
void GobiGsmModem::RegisterCallbacks() {
GobiModem::RegisterCallbacks();
sdk_->SetNewSMSCallback(NewSmsCallbackTrampoline);
}
static std::string MakeOperatorCode(WORD mcc, WORD mnc) {
std::ostringstream opercode;
if (mcc != 0xffff && mnc != 0xffff)
opercode << mcc << mnc;
return opercode.str();
}
// Trims any whitespace from both ends of the input string
// Local implementation to avoid the need to pull in <base/string_util.h>
static void TrimWhitespaceASCII(const std::string& input, std::string* output) {
size_t start, end, size;
size = input.size();
for (start = 0; start < size && isspace(input[start]); start++) {}
for (end = size; end > start && isspace(input[end - 1]); end--) {}
*output = input.substr(start, end-start);
}
// returns <registration status, operator code, operator name>
void GobiGsmModem::GetGsmRegistrationInfo(uint32_t* registration_state,
std::string* operator_code,
std::string* operator_name,
DBus::Error& error) {
ULONG gobi_reg_state, roaming_state;
ULONG l1;
WORD mcc, mnc;
CHAR netname[32];
ULONG radio_interfaces[10];
BYTE num_radio_interfaces = arraysize(radio_interfaces);
ULONG rc = sdk_->GetServingNetwork(&gobi_reg_state, &l1,
&num_radio_interfaces,
reinterpret_cast<BYTE*>(radio_interfaces),
&roaming_state, &mcc, &mnc,
sizeof(netname), netname);
if (rc != 0) {
// All errors are treated as if the registration state is unknown
gobi_reg_state = gobi::kRegistrationStateUnknown;
mcc = 0xffff;
mnc = 0xffff;
netname[0] = '\0';
}
switch (gobi_reg_state) {
case gobi::kUnregistered:
*registration_state = MM_MODEM_GSM_NETWORK_REG_STATUS_IDLE;
break;
case gobi::kRegistered:
// TODO(ers) should RoamingPartner be reported as HOME?
if (roaming_state == gobi::kHome)
*registration_state = MM_MODEM_GSM_NETWORK_REG_STATUS_HOME;
else
*registration_state = MM_MODEM_GSM_NETWORK_REG_STATUS_ROAMING;
break;
case gobi::kSearching:
*registration_state = MM_MODEM_GSM_NETWORK_REG_STATUS_SEARCHING;
break;
case gobi::kRegistrationDenied:
*registration_state = MM_MODEM_GSM_NETWORK_REG_STATUS_DENIED;
break;
case gobi::kRegistrationStateUnknown:
*registration_state = MM_MODEM_GSM_NETWORK_REG_STATUS_UNKNOWN;
break;
}
*operator_code = MakeOperatorCode(mcc, mnc);
TrimWhitespaceASCII(netname, operator_name);
LOG(INFO) << "GSM reg info: "
<< *registration_state << ", "
<< *operator_code << ", "
<< *operator_name;
}
// Determine the current network technology and map it to
// ModemManager's MM_MODEM_GSM_ACCESS_TECH enum
uint32_t GobiGsmModem::GetMmAccessTechnology() {
BYTE data_caps[48];
BYTE num_data_caps = 12;
DBus::Error error;
ULONG rc = sdk_->GetServingNetworkCapabilities(&num_data_caps, data_caps);
ENSURE_SDK_SUCCESS_WITH_RESULT(GetServingNetworkCapabilities, rc, kSdkError,
MM_MODEM_GSM_ACCESS_TECH_UNKNOWN);
return DataCapabilitiesToMmAccessTechnology(
num_data_caps,
reinterpret_cast<ULONG*>(data_caps));
}
bool GobiGsmModem::GetPinStatus(bool* enabled,
std::string* status,
uint32_t* retries_left) {
ULONG pin_status, verify_retries_left, unblock_retries_left;
DBus::Error error;
ULONG rc = sdk_->UIMGetPINStatus(gobi::kPinId1, &pin_status,
&verify_retries_left,
&unblock_retries_left);
ENSURE_SDK_SUCCESS_WITH_RESULT(UIMGetPINStatus, rc, kPinError, false);
if (pin_status == gobi::kPinStatusPermanentlyBlocked) {
*status = "sim-puk";
*retries_left = 0;
} else if (pin_status == gobi::kPinStatusBlocked) {
*status = "sim-puk";
*retries_left = unblock_retries_left;
} else if (pin_status == gobi::kPinStatusNotInitialized ||
pin_status == gobi::kPinStatusVerified ||
pin_status == gobi::kPinStatusDisabled) {
*status = "";
if (verify_retries_left != gobi::kPinRetriesLeftUnknown)
*retries_left = verify_retries_left;
else
*retries_left = kPinRetriesNotKnown;
} else if (pin_status == gobi::kPinStatusEnabled) {
*status = "sim-pin";
*retries_left = verify_retries_left;
}
*enabled = pin_status != gobi::kPinStatusDisabled &&
pin_status != gobi::kPinStatusNotInitialized;
return true;
}
bool GobiGsmModem::CheckEnableOk(DBus::Error &error) {
ULONG pin_status, verify_retries_left, unblock_retries_left;
ULONG error_code;
ULONG rc = sdk_->UIMGetPINStatus(gobi::kPinId1, &pin_status,
&verify_retries_left,
&unblock_retries_left);
ENSURE_SDK_SUCCESS_WITH_RESULT(UIMGetPINStatus, rc, kPinError, false);
const char *errname;
switch (pin_status) {
case gobi::kPinStatusNotInitialized:
case gobi::kPinStatusVerified:
case gobi::kPinStatusDisabled:
return true;
case gobi::kPinStatusEnabled:
error_code = gobi::kAccessToRequiredEntityNotAvailable;
break;
case gobi::kPinStatusBlocked:
error_code = gobi::kPinBlocked;
break;
case gobi::kPinStatusPermanentlyBlocked:
error_code = gobi::kPinPermanentlyBlocked;
break;
default:
error.set(kPinError, "UIMGetPINStatus: Unkown status");
return false;
}
errname = QMIReturnCodeToMMError(error_code);
if (errname)
error.set(errname, "PIN locked");
else
error.set(kPinError, "PIN error");
return false;
}
void GobiGsmModem::SetTechnologySpecificProperties() {
AccessTechnology = GetMmAccessTechnology();
bool enabled;
std::string status;
uint32_t retries_left;
if (!GetPinStatus(&enabled, &status, &retries_left))
retries_left = kPinRetriesNotKnown;
UnlockRequired = status;
UnlockRetries = retries_left;
EnabledFacilityLocks = enabled ? MM_MODEM_GSM_FACILITY_SIM : 0;
// TODO(ers) also need to set AllowedModes property. For the Gsm.Card
// interface, need to set SupportedBands and SupportedModes properties
}
void GobiGsmModem::UpdatePinStatus() {
bool enabled;
std::string status;
uint32_t retries_left;
uint32_t mm_enabled_locks;
if (!GetPinStatus(&enabled, &status, &retries_left))
return;
UnlockRequired = status;
UnlockRetries = retries_left;
mm_enabled_locks = enabled ? MM_MODEM_GSM_FACILITY_SIM : 0;
EnabledFacilityLocks = mm_enabled_locks;
utilities::DBusPropertyMap props;
props["UnlockRequired"].writer().append_string(status.c_str());
props["UnlockRetries"].writer().append_uint32(retries_left);
MmPropertiesChanged(
org::freedesktop::ModemManager::Modem_adaptor::introspect()->name, props);
utilities::DBusPropertyMap cardprops;
cardprops["EnabledFacilityLocks"].writer().append_uint32(mm_enabled_locks);
MmPropertiesChanged(
org::freedesktop::ModemManager::Modem::Gsm::Card_adaptor
::introspect()->name,
cardprops);
}
void GobiGsmModem::GetTechnologySpecificStatus(
utilities::DBusPropertyMap* properties) {
}
//======================================================================
// DBUS Methods: Modem.Gsm.Network
void GobiGsmModem::Register(const std::string& network_id,
DBus::Error& error) {
ULONG rc;
ULONG regtype, rat;
WORD mcc, mnc;
// This is a blocking call, and may take a while (up to 30 seconds)
LOG(INFO) << "Register request for [" << network_id << "]";
if (network_id.empty()) {
regtype = gobi::kRegistrationTypeAutomatic;
mcc = 0;
mnc = 0;
rat = 0;
LOG(INFO) << "Initiating automatic registration";
} else {
int n = sscanf(network_id.c_str(), "%3hu%3hu", &mcc, &mnc);
if (n != 2) {
error.set(kRegistrationError, "Malformed network ID");
return;
}
regtype = gobi::kRegistrationTypeManual;
rat = gobi::kRfiUmts;
LOG(INFO) << "Initiating manual registration for " << mcc << mnc;
}
rc = sdk_->InitiateNetworkRegistration(regtype, mcc, mnc, rat);
if (rc == gobi::kOperationHasNoEffect)
return; // already registered on requested network
ENSURE_SDK_SUCCESS(InitiateNetworkRegistration, rc, kSdkError);
}
ScannedNetworkList GobiGsmModem::Scan(DBus::Error& error) {
gobi::GsmNetworkInfoInstance networks[40];
BYTE num_networks = sizeof(networks)/sizeof(networks[0]);
ScannedNetworkList list;
// This is a blocking call, and may take a while (i.e., a minute or more)
LOG(INFO) << "Beginning network scan";
ULONG rc = sdk_->PerformNetworkScan(
&num_networks, static_cast<BYTE*>(reinterpret_cast<void*>(&networks[0])));
ENSURE_SDK_SUCCESS_WITH_RESULT(PerformNetworkScan, rc, kSdkError, list);
LOG(INFO) << "Network scan returned " << static_cast<int>(num_networks)
<< " networks";
for (int i = 0; i < num_networks; i++) {
gobi::GsmNetworkInfoInstance *net = &networks[i];
std::map<std::string, std::string> netprops;
// status, operator-long, operator-short, operator-num, access-tech
const char* status;
if (net->inUse == gobi::kGsmNetInfoYes)
status = "2";
else if (net->forbidden == gobi::kGsmNetInfoYes)
status = "3";
else if (net->inUse == gobi::kGsmNetInfoNo)
status = "1";
else
status = "0";
netprops["status"] = status;
netprops["operator-num"] = MakeOperatorCode(net->mcc, net->mnc);
if (strlen(net->description) != 0) {
std::string operator_name;
TrimWhitespaceASCII(net->description, &operator_name);
netprops["operator-short"] = operator_name;
}
list.push_back(netprops);
}
return list;
}
void GobiGsmModem::SetApn(const std::string& apn, DBus::Error& error) {
LOG(WARNING) << "GobiGsmModem::SetApn not implemented";
}
uint32_t GobiGsmModem::GetSignalQuality(DBus::Error& error) {
return GobiModem::CommonGetSignalQuality(error);
}
void GobiGsmModem::SetBand(const uint32_t& band, DBus::Error& error) {
LOG(WARNING) << "GobiGsmModem::SetBand not implemented";
}
uint32_t GobiGsmModem::GetBand(DBus::Error& error) {
LOG(WARNING) << "GobiGsmModem::GetBand not implemented";
return 0;
}
void GobiGsmModem::SetNetworkMode(const uint32_t& mode, DBus::Error& error) {
LOG(WARNING) << "GobiGsmModem::SetNetworkMode not implemented";
}
uint32_t GobiGsmModem::GetNetworkMode(DBus::Error& error) {
LOG(WARNING) << "GobiGsmModem::GetNetworkMode not implemented";
return 0;
}
// returns <registration status, operator code, operator name>
// reg status = idle, home, searching, denied, unknown, roaming
DBus::Struct<uint32_t,
std::string,
std::string> GobiGsmModem::GetRegistrationInfo(
DBus::Error& error) {
DBus::Struct<uint32_t, std::string, std::string> result;
GetGsmRegistrationInfo(&result._1, &result._2, &result._3, error);
// We don't always get an SDK callback when the network technology
// changes, so simulate a callback here to make sure that the
// most up-to-date idea of network technology gets signaled.
PostCallbackRequest(CheckDataCapabilities, new CallbackArgs());
return result;
}
void GobiGsmModem::SetAllowedMode(const uint32_t& mode,
DBus::Error& error) {
LOG(WARNING) << "GobiGsmModem::SetAllowedMmode not implemented";
}
//======================================================================
// DBUS Methods: Modem.Gsm.Card
std::string GobiGsmModem::GetImei(DBus::Error& error) {
SerialNumbers serials;
ScopedApiConnection connection(*this);
connection.ApiConnect(error);
if (error.is_set())
return "";
GetSerialNumbers(&serials, error);
return error.is_set() ? "" : serials.imei;
}
std::string GobiGsmModem::GetImsi(DBus::Error& error) {
char imsi[kDefaultBufferSize];
ScopedApiConnection connection(*this);
connection.ApiConnect(error);
if (error.is_set())
return "";
ULONG rc = sdk_->GetIMSI(kDefaultBufferSize, imsi);
ENSURE_SDK_SUCCESS_WITH_RESULT(GetIMSI, rc, kSdkError, "");
return imsi;
}
void GobiGsmModem::SendPuk(const std::string& puk,
const std::string& pin,
DBus::Error& error) {
ULONG verify_retries_left;
ULONG unblock_retries_left;
CHAR *pukP = const_cast<CHAR*>(puk.c_str());
CHAR *pinP = const_cast<CHAR*>(pin.c_str());
// If we're not enabled, then we're not connected to the SDK
ScopedApiConnection connection(*this);
DBus::Error tmperror;
connection.ApiConnect(tmperror);
ULONG rc = sdk_->UIMUnblockPIN(gobi::kPinId1, pukP, pinP,
&verify_retries_left,
&unblock_retries_left);
UpdatePinStatus();
ENSURE_SDK_SUCCESS(UIMUnblockPIN, rc, kPinError);
}
void GobiGsmModem::SendPin(const std::string& pin, DBus::Error& error) {
ULONG verify_retries_left;
ULONG unblock_retries_left;
CHAR* pinP = const_cast<CHAR*>(pin.c_str());
// If we're not enabled, then we're not connected to the SDK
ScopedApiConnection connection(*this);
DBus::Error tmperror;
connection.ApiConnect(tmperror);
ULONG rc = sdk_->UIMVerifyPIN(gobi::kPinId1, pinP, &verify_retries_left,
&unblock_retries_left);
UpdatePinStatus();
ENSURE_SDK_SUCCESS(UIMVerifyPIN, rc, kPinError);
}
void GobiGsmModem::EnablePin(const std::string& pin,
const bool& enabled,
DBus::Error& error) {
ULONG bEnable = enabled;
ULONG verify_retries_left;
ULONG unblock_retries_left;
CHAR* pinP = const_cast<CHAR*>(pin.c_str());
ULONG rc = sdk_->UIMSetPINProtection(gobi::kPinId1, bEnable,
pinP, &verify_retries_left,
&unblock_retries_left);
UpdatePinStatus();
if (rc == gobi::kOperationHasNoEffect)
return;
ENSURE_SDK_SUCCESS(UIMSetPINProtection, rc, kPinError);
}
void GobiGsmModem::ChangePin(const std::string& old_pin,
const std::string& new_pin,
DBus::Error& error) {
ULONG verify_retries_left;
ULONG unblock_retries_left;
CHAR* old_pinP = const_cast<CHAR*>(old_pin.c_str());
CHAR* new_pinP = const_cast<CHAR*>(new_pin.c_str());
ULONG rc = sdk_->UIMChangePIN(gobi::kPinId1, old_pinP, new_pinP,
&verify_retries_left, &unblock_retries_left);
UpdatePinStatus();
ENSURE_SDK_SUCCESS(UIMChangePIN, rc, kPinError);
}
std::string GobiGsmModem::GetOperatorId(DBus::Error& error) {
std::string result;
WORD mcc, mnc, sid, nid;
CHAR netname[32];
ULONG rc = sdk_->GetHomeNetwork(&mcc, &mnc,
sizeof(netname), netname, &sid, &nid);
ENSURE_SDK_SUCCESS_WITH_RESULT(GetHomeNetwork, rc, kSdkError, result);
return MakeOperatorCode(mcc, mnc);
}
std::string GobiGsmModem::GetSpn(DBus::Error& error) {
std::string result;
BYTE names[256];
ULONG namesLen = sizeof(names);
ULONG rc = sdk_->GetPLMNName(0, 0, &namesLen, names);
ENSURE_SDK_SUCCESS_WITH_RESULT(GetPLMNName, rc, kSdkError, result);
if (namesLen < 2) {
LOG(WARNING) << "GetSpn: name structure too short"
<< " (" << namesLen << " < 2)";
return "";
}
size_t spnLen = names[1];
if (namesLen - 2 < (ULONG)spnLen) {
LOG(WARNING) << "GetSpn: SPN length too long"
<< " (" << (ULONG)spnLen << " < " << namesLen << " - 2)";
return "";
}
switch (names[0]) {
case 0x00: { // ASCII
const char *spnAscii = (const char *)names + 2;
result = std::string(spnAscii, spnLen);
}
break;
case 0x01: { // UCS2
const uint8_t *spnUcs2 = (const uint8_t *)names + 2;
result = std::string(utilities::Ucs2ToUtf8String(spnUcs2, spnLen));
}
break;
default:
LOG(WARNING) << "GetSpn: invalid encoding byte " << names[0];
break;
}
LOG(INFO) << " GetSpn: returning \"" << result << "\"";
return result;
}
std::string GobiGsmModem::GetMsIsdn(DBus::Error& error) {
char mdn[kDefaultBufferSize], min[kDefaultBufferSize];
ULONG rc = sdk_->GetVoiceNumber(kDefaultBufferSize, mdn,
kDefaultBufferSize, min);
ENSURE_SDK_SUCCESS_WITH_RESULT(GetVoiceNumber, rc, kSdkError, "");
return mdn;
}
//======================================================================
// DBUS Methods: Modem.Gsm.SMS
SmsMessageFragment* GobiGsmModem::GetSms(int index, DBus::Error& error) {
ULONG tag, format, size;
BYTE message[200];
size = sizeof(message);
ULONG rc = sdk_->GetSMS(gobi::kSmsNonVolatileMemory, index,
&tag, &format, &size, message);
ENSURE_SDK_SUCCESS_WITH_RESULT(GetSMS, rc, kSdkError, nullptr);
LOG(INFO) << "GetSms: " << "tag " << tag << " format " << format
<< " size " << size;
SmsMessageFragment *fragment =
SmsMessageFragment::CreateFragment(message, size, index);
if (!fragment) {
error.set(kInvalidArgumentError, "Couldn't decode PDU");
LOG(WARNING) << "Couldn't decode PDU";
}
return fragment;
}
void GobiGsmModem::DeleteSms(int index, DBus::Error& error) {
ULONG lindex = index;
ULONG rc = sdk_->DeleteSMS(gobi::kSmsNonVolatileMemory, &lindex, nullptr);
ENSURE_SDK_SUCCESS(DeleteSMS, rc, kSdkError);
}
std::vector<int>* GobiGsmModem::ListSms(DBus::Error& error) {
ULONG items[100];
ULONG num_items;
num_items = sizeof(items) / (2 * sizeof(items[0]));
ULONG rc = sdk_->GetSMSList(gobi::kSmsNonVolatileMemory, nullptr, &num_items,
reinterpret_cast<BYTE*>(items));
ENSURE_SDK_SUCCESS_WITH_RESULT(GetSMSList, rc, kSdkError, nullptr);
LOG(INFO) << "GetSmsList: got " << num_items << " messages";
std::vector<int>* result = new std::vector<int>();
for (ULONG i = 0 ; i < num_items ; i++)
result->push_back(items[2 * i]);
return result;
}
void GobiGsmModem::Delete(const uint32_t& index, DBus::Error &error) {
sms_cache_.Delete(index, error, this);
}
utilities::DBusPropertyMap GobiGsmModem::Get(const uint32_t& index,
DBus::Error &error) {
std::unique_ptr<utilities::DBusPropertyMap> message(
sms_cache_.Get(index, error, this));
return *(message.get());
}
std::vector<utilities::DBusPropertyMap> GobiGsmModem::List(DBus::Error &error) {
std::unique_ptr<std::vector<utilities::DBusPropertyMap>> list(
sms_cache_.List(error, this));
return *(list.get());
}
std::string GobiGsmModem::GetSmsc(DBus::Error &error) {
CHAR address[100];
CHAR address_type[100];
std::string result;
ULONG rc = sdk_->GetSMSCAddress(sizeof(address), address,
sizeof(address_type), address_type);
ENSURE_SDK_SUCCESS_WITH_RESULT(GetSMSCAddress, rc, kSdkError, result);
LOG(INFO) << "SMSC address: " << address << " type: " << address_type;
result = address;
return result;
}
void GobiGsmModem::SetSmsc(const std::string& smsc, DBus::Error &error) {
CHAR *addr = const_cast<CHAR*>(smsc.c_str());
ULONG rc = sdk_->SetSMSCAddress(addr, nullptr);
ENSURE_SDK_SUCCESS(GetSMSCAddress, rc, kSdkError);
}
std::vector<uint32_t> GobiGsmModem::Save(
const utilities::DBusPropertyMap& properties,
DBus::Error &error) {
LOG(WARNING) << "GobiGsmModem::Save not implemented";
return std::vector<uint32_t>();
}
std::vector<uint32_t> GobiGsmModem::Send(
const utilities::DBusPropertyMap& properties,
DBus::Error &error) {
LOG(WARNING) << "GobiGsmModem::Send not implemented";
return std::vector<uint32_t>();
}
void GobiGsmModem::SendFromStorage(const uint32_t& index, DBus::Error &error) {
LOG(WARNING) << "GobiGsmModem::SendFromStorage not implemented";
}
// What is this supposed to do?
void GobiGsmModem::SetIndication(const uint32_t& mode,
const uint32_t& mt,
const uint32_t& bm,
const uint32_t& ds,
const uint32_t& bfr,
DBus::Error &error) {
LOG(WARNING) << "GobiGsmModem::SetIndication not implemented";
}
// The API documentation says nothing about what this is supposed
// to return. Most likely it's intended to report whether messages
// are being sent and received in text mode or PDU mode. But the
// meanings of the return values are undocumented.
uint32_t GobiGsmModem::GetFormat(DBus::Error &error) {
LOG(WARNING) << "GobiGsmModem::GetFormat not implemented";
return 0;
}
// The API documentation says nothing about what this is supposed
// to return. Most likely it's intended for specifying whether messages
// are being sent and received in text mode or PDU mode. But the
// meanings of the argument values are undocumented.
void GobiGsmModem::SetFormat(const uint32_t& format, DBus::Error &error) {
LOG(WARNING) << "GobiGsmModem::SetFormat not implemented";
}
| 35.614155 | 80 | 0.668504 | doitmovin |
4804cc559d007f9a4ec71d6b82738d862d9b10fd | 2,961 | cpp | C++ | clang/test/CXX/stmt.stmt/stmt.select/p3.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | clang/test/CXX/stmt.stmt/stmt.select/p3.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang/test/CXX/stmt.stmt/stmt.select/p3.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // RUN: %clang_cc1 -fsyntax-only -Wno-unused-value -verify %s
// RUN: %clang_cc1 -fsyntax-only -Wno-unused-value -std=c++1z -Wc++14-compat -verify %s -DCPP17
int f();
void g() {
if (int x = f()) { // expected-note 2{{previous definition}}
int x; // expected-error{{redefinition of 'x'}}
} else {
int x; // expected-error{{redefinition of 'x'}}
}
}
void h() {
if (int x = f()) // expected-note 2{{previous definition}}
int x; // expected-error{{redefinition of 'x'}}
else
int x; // expected-error{{redefinition of 'x'}}
}
void ifInitStatement() {
int Var = 0;
if (int I = 0; true) {}
if (Var + Var; true) {}
if (; true) {}
#ifdef CPP17
// expected-warning@-4 {{if initialization statements are incompatible with C++ standards before C++17}}
// expected-warning@-4 {{if initialization statements are incompatible with C++ standards before C++17}}
// expected-warning@-4 {{if initialization statements are incompatible with C++ standards before C++17}}
#else
// expected-warning@-8 {{'if' initialization statements are a C++17 extension}}
// expected-warning@-8 {{'if' initialization statements are a C++17 extension}}
// expected-warning@-8 {{'if' initialization statements are a C++17 extension}}
#endif
}
void switchInitStatement() {
int Var = 0;
switch (int I = 0; Var) {}
switch (Var + Var; Var) {}
switch (; Var) {}
#ifdef CPP17
// expected-warning@-4 {{switch initialization statements are incompatible with C++ standards before C++17}}
// expected-warning@-4 {{switch initialization statements are incompatible with C++ standards before C++17}}
// expected-warning@-4 {{switch initialization statements are incompatible with C++ standards before C++17}}
#else
// expected-warning@-8 {{'switch' initialization statements are a C++17 extension}}
// expected-warning@-8 {{'switch' initialization statements are a C++17 extension}}
// expected-warning@-8 {{'switch' initialization statements are a C++17 extension}}
#endif
}
// TODO: Better diagnostics for while init statements.
void whileInitStatement() {
while (int I = 10; I--); // expected-error {{expected ')'}}
// expected-note@-1 {{to match this '('}}
// expected-error@-2 {{use of undeclared identifier 'I'}}
int Var = 10;
while (Var + Var; Var--) {} // expected-error {{expected ')'}}
// expected-note@-1 {{to match this '('}}
// expected-error@-2 {{expected ';' after expression}}
// expected-error@-3 {{expected expression}}
// expected-warning@-4 {{while loop has empty body}}
// expected-note@-5 {{put the semicolon on a separate line to silence this warning}}
}
// TODO: This is needed because clang can't seem to diagnose invalid syntax after the
// last loop above. It would be nice to remove this.
void whileInitStatement2() {
while (; false) {} // expected-error {{expected expression}}
// expected-error@-1 {{expected ';' after expression}}
// expected-error@-2 {{expected expression}}
}
| 38.454545 | 110 | 0.670382 | medismailben |
48051423bc5c493b50ebae69a545a1c307765da5 | 834 | cpp | C++ | google/2015/r1a/a/a.cpp | suhwanhwang/problem-solving | 9421488fb97c4628bea831ac59ad5c5d9b8131d4 | [
"MIT"
] | null | null | null | google/2015/r1a/a/a.cpp | suhwanhwang/problem-solving | 9421488fb97c4628bea831ac59ad5c5d9b8131d4 | [
"MIT"
] | null | null | null | google/2015/r1a/a/a.cpp | suhwanhwang/problem-solving | 9421488fb97c4628bea831ac59ad5c5d9b8131d4 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void printSolution(const vector<int>& m) {
int m1 = 0;
for (int i = 1; i < (int)m.size(); ++i) {
if (m[i - 1] > m[i]) {
m1 += m[i - 1] - m[i];
}
}
int max_d = 0;
for (int i = 1; i < (int)m.size(); ++i) {
max_d = max(max_d, m[i - 1] - m[i]);
}
int m2 = 0;
for (int i = 0; i < (int)m.size() - 1; ++i) {
m2 += min(max_d, m[i]);
}
cout << m1 << ' ' << m2 << endl;
}
int main(int argc, char* argv[]) {
int t;
cin >> t;
for (int i = 1; i <= t; ++i) {
int n;
cin >> n;
vector<int> m(n);
for (int j = 0; j < n; ++j) {
cin >> m[j];
}
cout << "Case #" << i << ": ";
printSolution(m);
}
return 0;
} | 19.857143 | 49 | 0.383693 | suhwanhwang |
4808e862bfc0d52cf5df59d3ce7118508cf15f97 | 1,933 | hpp | C++ | include/hfsm2/detail/shared/macros_off.hpp | amessing/HFSM2 | 419c6847adcc644cabb6634757ec1b403bf2e192 | [
"MIT"
] | null | null | null | include/hfsm2/detail/shared/macros_off.hpp | amessing/HFSM2 | 419c6847adcc644cabb6634757ec1b403bf2e192 | [
"MIT"
] | null | null | null | include/hfsm2/detail/shared/macros_off.hpp | amessing/HFSM2 | 419c6847adcc644cabb6634757ec1b403bf2e192 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
#if defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#if _MSC_VER == 1900
#pragma warning(pop)
#endif
////////////////////////////////////////////////////////////////////////////////
//#undef HFSM2_UNUSED
//#undef HFSM2_ATTRIBUTE
//#undef HFSM2_ATTRIBUTE_FALLTHROUGH
//#undef HFSM2_ATTRIBUTE_NO_UNIQUE_ADDRESS
//#undef HFSM2_CONSTEXPR
//#undef HFSM2_CONSTEXPR_EXTENDED
//#undef HFSM2_ARCHITECTURE
//#undef HFSM2_ARCHITECTURE_64
//#undef HFSM2_ARCHITECTURE_32
#undef HFSM2_64BIT_OR_32BIT
//#undef HFSM2_BREAK
#undef HFSM2_BREAK_AVAILABLE
#undef HFSM2_IF_DEBUG
#undef HFSM2_UNLESS_DEBUG
#undef HFSM2_DEBUG_OR
//#undef HFSM2_ASSERT_AVAILABLE
#undef HFSM2_IF_ASSERT
//#undef HFSM2_CHECKED
#undef HFSM2_ASSERT
#undef HFSM2_ASSERT_OR
#undef HFSM2_EXPLICIT_MEMBER_SPECIALIZATION_AVAILABLE
#undef HFSM2_IF_TYPEINDEX
#undef HFSM2_TYPEINDEX_AVAILABLE
#undef HFSM2_IF_TYPEINDEX
//#undef HFSM2_DEBUG_STATE_TYPE_AVAILABLE
//#undef HFSM2_PLANS_AVAILABLE
#undef HFSM2_IF_PLANS
#undef HFSM2_SERIALIZATION_AVAILABLE
#undef HFSM2_IF_SERIALIZATION
#undef HFSM2_STRUCTURE_REPORT_AVAILABLE
#undef HFSM2_IF_STRUCTURE_REPORT
//#undef HFSM2_TRANSITION_HISTORY_AVAILABLE
#undef HFSM2_IF_TRANSITION_HISTORY
//#undef HFSM2_UTILITY_THEORY_AVAILABLE
#undef HFSM2_IF_UTILITY_THEORY
#undef HFSM2_VERBOSE_DEBUG_LOG_AVAILABLE
#undef HFSM2_LOG_INTERFACE_AVAILABLE
#undef HFSM2_IF_LOG_INTERFACE
#undef HFSM2_LOG_TRANSITION
#if HFSM2_PLANS_AVAILABLE()
#undef HFSM2_LOG_TASK_STATUS
#undef HFSM2_LOG_PLAN_STATUS
#endif
#undef HFSM2_LOG_CANCELLED_PENDING
#if HFSM2_UTILITY_THEORY_AVAILABLE()
#undef HFSM2_LOG_UTILITY_RESOLUTION
#undef HFSM2_LOG_RANDOM_RESOLUTION
#endif
#undef HFSM2_LOG_STATE_METHOD
////////////////////////////////////////////////////////////////////////////////
| 21.965909 | 80 | 0.741852 | amessing |
48091586f2316542b3f3dcd6f8f27847601a2096 | 439 | cpp | C++ | C/2019122001CppStringManipulation/2019122001CppStringManipulation/stringmanipulation.cpp | AungWinnHtut/POL | ee8bdf655073134df8b8529ab0ece20e118b19e1 | [
"MIT"
] | 2 | 2016-02-10T10:22:13.000Z | 2020-01-19T09:49:28.000Z | C/2019122001CppStringManipulation/2019122001CppStringManipulation/stringmanipulation.cpp | AungWinnHtut/POL | ee8bdf655073134df8b8529ab0ece20e118b19e1 | [
"MIT"
] | null | null | null | C/2019122001CppStringManipulation/2019122001CppStringManipulation/stringmanipulation.cpp | AungWinnHtut/POL | ee8bdf655073134df8b8529ab0ece20e118b19e1 | [
"MIT"
] | 1 | 2020-01-19T09:22:29.000Z | 2020-01-19T09:22:29.000Z | #include<stdio.h>
#include<conio.h>
#include<string.h>
//size_t strlen(const char *s);
int myStrlen(const char *s);
int main()
{
char s1[4]={'a','b','c','d'};
char s2[4]={'e',' ','g','h'};
int i=0;
while(s2[i]>0)
{
i++;
}
printf("count = %d",i);
printf("\ncount2 = %d",strlen(s2));
printf("\ncount3 = %d",myStrlen(s2));
getch();
return 0;
}
int myStrlen(const char *s)
{
int i=0;
while(s[i]!='\0')
{
i++;
}
return i;
} | 14.633333 | 38 | 0.544419 | AungWinnHtut |
480cc56e31a8c4c9948f2c76f1a697313526ba52 | 2,306 | cpp | C++ | implementations/divisors.cpp | LeoRiether/Competicao-Programativa | ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e | [
"MIT"
] | 1 | 2019-12-15T22:23:20.000Z | 2019-12-15T22:23:20.000Z | implementations/divisors.cpp | LeoRiether/Competicao-Programativa | ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e | [
"MIT"
] | null | null | null | implementations/divisors.cpp | LeoRiether/Competicao-Programativa | ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <iterator>
// Just so I can cout a vector
template <class T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
int a{0};
for (const auto& e : v) {
os << (a++ ? " " : "") << e;
}
return os;
}
// O(sqrt(n))
std::vector<int> getDivisors(int n) {
std::vector<int> front, back;
for (int i = 1; i*i <= n; i++) {
if (n % i == 0) {
int j = n/i;
front.push_back(i);
if (i != j) back.push_back(j);
}
}
std::move(back.rbegin(), back.rend(), std::back_inserter(front));
return front;
}
// O(n*log n)
std::vector<int> countMultiplesTill(int n) {
std::vector<int> divCount(n, 1);
for (int i = 2; i < n; i++) {
for (int d = i; d < n; d += i) {
divCount[d]++;
}
}
return divCount;
}
// O (n*log(log n))
std::vector<int> sieve(int n) {
std::vector<int> primes;
std::vector<bool> marked(n, false);
for (int i = 2; i < n; i++) {
if (!marked[i]) {
primes.push_back(i);
for (int j = i+i; j < n; j += i) marked[j] = true;
}
}
return primes;
}
// O(n*log(log n))
std::vector<int> maxFactorTable(int n) {
std::vector<int> f(n, 0);
for (int i {2}; i < n; i++) {
if (f[i] == 0)
for (int j = i; j < n; j += i) f[j] = i;
}
return f;
}
// O(log n) with a maxFactorTable
std::vector<int> factorize(int n, const std::vector<int>& mft) {
if (static_cast<int>(mft.size()) <= n) return {-1};
std::vector<int> f;
while (mft[n]) {
f.push_back(mft[n]);
n /= mft[n];
}
return f;
}
int main() {
std::cout << getDivisors(10) << std::endl;
std::cout << getDivisors(12) << std::endl;
std::cout << getDivisors(16) << std::endl;
std::cout << getDivisors(7727) << std::endl;
std::cout << std::endl;
std::cout << countMultiplesTill(50) << std::endl;
std::cout << std::endl;
std::cout << sieve(100) << std::endl;
std::cout << std::endl;
std::vector<int> mft {maxFactorTable(50)};
std::cout << mft << std::endl;
std::cout << std::endl;
std::cout << factorize(32, mft) << std::endl;
std::cout << factorize(42, mft) << std::endl;
std::cout << factorize(47, mft) << std::endl;
std::cout << std::endl;
return 0;
} | 23.773196 | 70 | 0.519081 | LeoRiether |
480dd44b55b36de2c87762ac429a259273a77a24 | 1,754 | hpp | C++ | ext/hdmi/native/FillView.hpp | rsperanza/BB10-WebWorks-Framework | 4d68e97f07bba2eeca5b4299e6fafae042a4cbc2 | [
"Apache-2.0"
] | 1 | 2022-01-27T17:02:37.000Z | 2022-01-27T17:02:37.000Z | ext/hdmi/native/FillView.hpp | rsperanza/BB10-WebWorks-Framework | 4d68e97f07bba2eeca5b4299e6fafae042a4cbc2 | [
"Apache-2.0"
] | null | null | null | ext/hdmi/native/FillView.hpp | rsperanza/BB10-WebWorks-Framework | 4d68e97f07bba2eeca5b4299e6fafae042a4cbc2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2011-2012 Research In Motion Limited.
*
* 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.
*/
#ifndef FILLVIEW_HPP
#define FILLVIEW_HPP
#include <assert.h>
#include <screen/screen.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <bps/navigator.h>
#include <bps/screen.h>
#include <bps/bps.h>
#include <bps/event.h>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include <QtCore/QObject>
#include <QtCore/QString>
#include "OpenGLView.hpp"
#include "OpenGLThread.hpp"
class FillView : public OpenGLView {
Q_OBJECT
Q_PROPERTY(QVariantList objectColor READ objectColor WRITE setObjectColor) // object color
public:
FillView(VIEW_DISPLAY display);
virtual ~FillView();
// property signals
QVariantList& objectColor();
public Q_SLOTS:
// property slots
void setObjectColor(QVariantList objectColor);
// action slots
void reset(bool skipColour);
public:
// overriden methods from OpenGLView
int initialize();
int regenerate();
void cleanup();
void handleScreenEvent(bps_event_t *event);
void update();
void render();
private:
float obj_color[4];
};
#endif /* FILLVIEW_HPP */
| 21.654321 | 91 | 0.701254 | rsperanza |
480df195db6e5c1d6d9427e60cbd5dffe2b84d32 | 2,000 | cpp | C++ | modules/trustchain/src/KeyPublishAction.cpp | TankerHQ/sdk-native | 5d9eb7c2048fdefae230590a3110e583f08c2c49 | [
"Apache-2.0"
] | 19 | 2018-12-05T12:18:02.000Z | 2021-07-13T07:33:22.000Z | modules/trustchain/src/KeyPublishAction.cpp | TankerHQ/sdk-native | 5d9eb7c2048fdefae230590a3110e583f08c2c49 | [
"Apache-2.0"
] | 3 | 2020-03-16T15:52:06.000Z | 2020-08-01T11:14:30.000Z | modules/trustchain/src/KeyPublishAction.cpp | TankerHQ/sdk-native | 5d9eb7c2048fdefae230590a3110e583f08c2c49 | [
"Apache-2.0"
] | 3 | 2020-01-07T09:55:32.000Z | 2020-08-01T01:29:28.000Z | #include <Tanker/Trustchain/KeyPublishAction.hpp>
#include <Tanker/Errors/AssertionError.hpp>
#include <Tanker/Errors/Exception.hpp>
#include <Tanker/Serialization/Serialization.hpp>
#include <Tanker/Trustchain/Errors/Errc.hpp>
#include <Tanker/Trustchain/Serialization.hpp>
#include <nlohmann/json.hpp>
#include <stdexcept>
using namespace Tanker::Trustchain::Actions;
namespace Tanker::Trustchain
{
Crypto::Hash getHash(KeyPublishAction const& action)
{
return boost::variant2::visit([&](auto const& val) { return val.hash(); },
action);
}
Actions::Nature getNature(KeyPublishAction const& action)
{
return boost::variant2::visit([&](auto const& val) { return val.nature(); },
action);
}
Crypto::Hash const& getAuthor(KeyPublishAction const& action)
{
return boost::variant2::visit(
[&](auto const& val) -> decltype(auto) { return val.author(); }, action);
}
Crypto::Signature const& getSignature(KeyPublishAction const& action)
{
return boost::variant2::visit(
[&](auto const& val) -> decltype(auto) { return val.signature(); },
action);
}
KeyPublishAction deserializeKeyPublishAction(
gsl::span<std::uint8_t const> block)
{
auto const nature = getBlockNature(block);
switch (nature)
{
case Nature::KeyPublishToUser:
return Serialization::deserialize<KeyPublishToUser>(block);
case Nature::KeyPublishToUserGroup:
return Serialization::deserialize<KeyPublishToUserGroup>(block);
case Nature::KeyPublishToProvisionalUser:
return Serialization::deserialize<KeyPublishToProvisionalUser>(block);
default:
// remove the static_cast and this line will make fmt dereference a null
// pointer, deep in its internals
throw Errors::formatEx(Errors::Errc::UpgradeRequired,
"{} is not a known key publish block nature, Tanker "
"needs to be updated",
static_cast<int>(nature));
}
}
}
| 30.30303 | 80 | 0.6845 | TankerHQ |
480e4057f810f381ed34a96ffd35ccec1dae750d | 576 | cpp | C++ | tests/test_strcspn.cpp | sushisharkjl/aolc | 6658f7954611de969b1fe1de017ad96bbfadf759 | [
"BSD-3-Clause"
] | null | null | null | tests/test_strcspn.cpp | sushisharkjl/aolc | 6658f7954611de969b1fe1de017ad96bbfadf759 | [
"BSD-3-Clause"
] | null | null | null | tests/test_strcspn.cpp | sushisharkjl/aolc | 6658f7954611de969b1fe1de017ad96bbfadf759 | [
"BSD-3-Clause"
] | null | null | null | #include "aolc/_test_string.h"
#include <string.h>
#include "aolc/compare_buffer_functions.h"
#include "gtest/gtest.h"
TEST(strcspn, Basic) {
char str[] = {'x', 'x', 'x', 'X', 'y', 'X', 'X', '\0'};
char x[] = "x";
char xX[] = "xX";
char X[] = "X";
char y[] = "y";
char xyX[] = "xyX";
EXPECT_EQ(strcspn(str, x), _strcspn(str, x));
EXPECT_EQ(strcspn(str, xX), _strcspn(str, xX));
EXPECT_EQ(strcspn(str, X), _strcspn(str, X));
EXPECT_EQ(strcspn(str, y), _strcspn(str, y));
EXPECT_EQ(strcspn(str, xyX), _strcspn(str, xyX));
}
| 27.428571 | 59 | 0.564236 | sushisharkjl |
480eecc0a0c8d313706107d8572398af58326e8b | 2,229 | hpp | C++ | src/assembler/Assembler.hpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | src/assembler/Assembler.hpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | src/assembler/Assembler.hpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | #ifndef ASSEMBLER_HPP
#define ASSEMBLER_HPP
#include <polyfem/ElementAssemblyValues.hpp>
#include <polyfem/Problem.hpp>
#include <Eigen/Sparse>
#include <vector>
#include <iostream>
#include <cmath>
#include <memory>
namespace polyfem
{
template<class LocalAssembler>
class Assembler
{
public:
void assemble(
const bool is_volume,
const int n_basis,
const std::vector< ElementBases > &bases,
const std::vector< ElementBases > &gbases,
StiffnessMatrix &stiffness) const;
inline LocalAssembler &local_assembler() { return local_assembler_; }
inline const LocalAssembler &local_assembler() const { return local_assembler_; }
private:
LocalAssembler local_assembler_;
};
template<class LocalAssembler>
class MixedAssembler
{
public:
void assemble(
const bool is_volume,
const int n_psi_basis,
const int n_phi_basis,
const std::vector< ElementBases > &psi_bases,
const std::vector< ElementBases > &phi_bases,
const std::vector< ElementBases > &gbases,
StiffnessMatrix &stiffness) const;
inline LocalAssembler &local_assembler() { return local_assembler_; }
inline const LocalAssembler &local_assembler() const { return local_assembler_; }
private:
LocalAssembler local_assembler_;
};
template<class LocalAssembler>
class NLAssembler
{
public:
void assemble_grad(
const bool is_volume,
const int n_basis,
const std::vector< ElementBases > &bases,
const std::vector< ElementBases > &gbases,
const Eigen::MatrixXd &displacement,
Eigen::MatrixXd &rhs) const;
void assemble_hessian(
const bool is_volume,
const int n_basis,
const std::vector< ElementBases > &bases,
const std::vector< ElementBases > &gbases,
const Eigen::MatrixXd &displacement,
StiffnessMatrix &grad) const;
double assemble(
const bool is_volume,
const std::vector< ElementBases > &bases,
const std::vector< ElementBases > &gbases,
const Eigen::MatrixXd &displacement) const;
inline LocalAssembler &local_assembler() { return local_assembler_; }
inline const LocalAssembler &local_assembler() const { return local_assembler_; }
void clear_cache() { }
private:
LocalAssembler local_assembler_;
};
}
#endif //ASSEMBLER_HPP
| 23.967742 | 83 | 0.740691 | ldXiao |
481455ffabbc21e4d72ae04a61143c43ed73ea65 | 3,694 | cpp | C++ | irob_vision_support/src/camera_preprocessor.cpp | BenGab/irob-saf | 3a0fee98239bd935aa99c9d9526eb9b4cfc8963c | [
"MIT"
] | 11 | 2018-06-07T22:56:06.000Z | 2021-11-04T14:56:36.000Z | irob_vision_support/src/camera_preprocessor.cpp | BenGab/irob-saf | 3a0fee98239bd935aa99c9d9526eb9b4cfc8963c | [
"MIT"
] | 2 | 2019-12-19T10:04:02.000Z | 2021-04-19T13:45:25.000Z | irob_vision_support/src/camera_preprocessor.cpp | BenGab/irob-saf | 3a0fee98239bd935aa99c9d9526eb9b4cfc8963c | [
"MIT"
] | 8 | 2018-05-24T23:45:01.000Z | 2021-05-07T23:33:43.000Z | /*
* camera_preprocessor.cpp
*
* Author(s): Tamas D. Nagy
* Created on: 2018-03-13
*
*/
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
#include <ros/ros.h>
#include <ros/package.h>
#include <sensor_msgs/Image.h>
#include <irob_vision_support/camera_preprocessor.hpp>
namespace saf {
CameraPreprocessor::CameraPreprocessor(ros::NodeHandle nh,
std::string camera, std::string command):
nh(nh), camera(camera)
{
if (!command.compare("none"))
{
this->command = Command::NONE;
}
else if (!command.compare("avg_adjacent"))
{
this->command = Command::AVG_ADJACENT;
}
subscribeTopics();
advertiseTopics();
cam_info_service = nh.advertiseService("preprocessed/" + camera + "/set_camera_info", &CameraPreprocessor::setCameraInfoCB, this);
}
CameraPreprocessor::~CameraPreprocessor() {}
void CameraPreprocessor::subscribeTopics()
{
image_sub = nh.subscribe<sensor_msgs::Image>(
camera + "/image_raw", 1000,
&CameraPreprocessor::imageCB,this);
camera_info_sub = nh.subscribe<sensor_msgs::CameraInfo>(
camera + "/camera_info", 1000,
&CameraPreprocessor::cameraInfoCB,this);
}
void CameraPreprocessor::advertiseTopics()
{
image_pub = nh.advertise<sensor_msgs::Image>("preprocessed/" + camera + "/image_raw", 1000);
camera_info_pub =
nh.advertise<sensor_msgs::CameraInfo>("preprocessed/" + camera + "/camera_info", 1);
}
void CameraPreprocessor::imageCB(
const sensor_msgs::ImageConstPtr& msg)
{
try
{
cv_bridge::CvImagePtr image_ptr =
cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
cv::Mat processed_image;
image_ptr->image.copyTo(processed_image);
switch(command)
{
case Command::NONE:
break;
case Command::AVG_ADJACENT:
if(!prev_image.empty())
processed_image = (processed_image + prev_image) / 2.0;
break;
}
sensor_msgs::ImagePtr processed_msg =
cv_bridge::CvImage(msg->header, "bgr8",
processed_image).toImageMsg();
image_pub.publish(processed_msg);
image_ptr->image.copyTo(prev_image);
} catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
}
void CameraPreprocessor::cameraInfoCB(
const sensor_msgs::CameraInfoConstPtr& msg)
{
camera_info_pub.publish(*msg);
}
bool CameraPreprocessor::setCameraInfoCB(sensor_msgs::SetCameraInfo::Request& request, sensor_msgs::SetCameraInfo::Response& response)
{
ros::ServiceClient client = nh.serviceClient<sensor_msgs::SetCameraInfo>(camera +"/set_camera_info");
sensor_msgs::SetCameraInfo srv;
srv.request = request;
srv.response = response;
if (client.call(srv))
{
response = srv.response;
return true;
}
response = srv.response;
return false;
}
}
using namespace saf;
/**
* Image preprocessor main
*/
int main(int argc, char **argv)
{
// Initialize ros node
ros::init(argc, argv, "camera_preprocessor");
ros::NodeHandle nh;
ros::NodeHandle priv_nh("~");
std::string command;
priv_nh.getParam("command", command);
std::string camera;
priv_nh.getParam("camera", camera);
std::string calibration;
priv_nh.getParam("calibration", calibration);
// Start Vision server
try {
CameraPreprocessor prep(nh, camera, command);
ros::spin();
ROS_INFO_STREAM("Program finished succesfully, shutting down ...");
} catch (const std::exception& e) {
ROS_ERROR_STREAM(e.what());
ROS_ERROR_STREAM("Program stopped by an error, shutting down ...");
}
// Exit
ros::shutdown();
return 0;
}
| 18.107843 | 134 | 0.67163 | BenGab |
4816d6f0f4fdd0fe18cbe816d1a799ce007d8a03 | 8,544 | hpp | C++ | gsa/wit/COIN/include/CglProbing.hpp | kant/CMMPPT | c64b339712db28a619880c4c04839aef7d3b6e2b | [
"Apache-2.0"
] | 1 | 2019-10-25T05:25:23.000Z | 2019-10-25T05:25:23.000Z | gsa/wit/COIN/include/CglProbing.hpp | kant/CMMPPT | c64b339712db28a619880c4c04839aef7d3b6e2b | [
"Apache-2.0"
] | 2 | 2019-09-04T17:34:59.000Z | 2020-09-16T08:10:57.000Z | gsa/wit/COIN/include/CglProbing.hpp | kant/CMMPPT | c64b339712db28a619880c4c04839aef7d3b6e2b | [
"Apache-2.0"
] | 18 | 2019-07-22T19:01:25.000Z | 2022-03-03T15:36:11.000Z | // Copyright (C) 2002, International Business Machines
// Corporation and others. All Rights Reserved.
#ifndef CglProbing_H
#define CglProbing_H
#include <string>
#include "CglCutGenerator.hpp"
/** Probing Cut Generator Class */
class CglProbing : public CglCutGenerator {
friend void CglProbingUnitTest(const OsiSolverInterface * siP,
const std::string mpdDir );
public:
/**@name Generate Cuts */
//@{
/** Generate probing/disaggregation cuts for the model of the
solver interface, si.
This is a simplification of probing ideas put into OSL about
ten years ago. The only known documentation is a copy of a
talk handout - we think Robin Lougee-Heimer has a copy!
For selected integer variables (e.g. unsatisfied ones) the effect of
setting them up or down is investigated. Setting a variable up
may in turn set other variables (continuous as well as integer).
There are various possible results:
1) It is shown that problem is infeasible (this may also be
because objective function or reduced costs show worse than
best solution). If the other way is feasible we can generate
a column cut (and continue probing), if not feasible we can
say problem infeasible.
2) If both ways are feasible, it can happen that x to 0 implies y to 1
** and x to 1 implies y to 1 (again a column cut). More common
is that x to 0 implies y to 1 and x to 1 implies y to 0 so we could
substitute for y which might lead later to more powerful cuts.
** This is not done in this code as there is no mechanism for
returning information.
3) When x to 1 a constraint went slack by c. We can tighten the
constraint ax + .... <= b (where a may be zero) to
(a+c)x + .... <= b. If this cut is violated then it is
generated.
4) Similarly we can generate implied disaggregation cuts
Note - differences to cuts in OSL.
a) OSL had structures intended to make this faster.
b) The "chaining" in 2) was done
c) Row cuts modified original constraint rather than adding cut
b) This code can cope with general integer variables.
Insert the generated cuts into OsiCut, cs.
If a "snapshot" of a matrix exists then this will be used.
Presumably this will give global cuts and will be faster.
No check is done to see if cuts will be global.
Otherwise use current matrix.
Both row cuts and column cuts may be returned
The mode options are:
0) Only unsatisfied integer variables will be looked at.
If no information exists for that variable then
probing will be done so as a by-product you "may" get a fixing
or infeasibility. This will be fast and is only available
if a snapshot exists (otherwise as 1).
The bounds in the snapshot are the ones used.
1) Look at unsatisfied integer variables, using current bounds.
Probing will be done on all looked at.
2) Look at all integer variables, using current bounds.
Probing will be done on all
** If generateCutsAndModify is used then new relaxed
row bounds and tightened coliumn bounds are generated
Returns number of infeasibilities
*/
virtual void generateCuts( const OsiSolverInterface & si,
OsiCuts & cs) const;
int generateCutsAndModify( const OsiSolverInterface & si,
OsiCuts & cs);
//@}
/**@name snapshot */
//@{
/// Create a copy of matrix which is to be used
/// this is to speed up process and to give global cuts
/// Can give an array with 1 set to select, 0 to ignore
/// column bounds are tightened
/// If array given then values of 1 will be set to 0 if redundant
void snapshot ( const OsiSolverInterface & si,
char * possible=NULL);
//@}
/**@name deleteSnapshot */
//@{
/// Deletes snapshot
void deleteSnapshot ( );
//@}
/**@name Get tighter column bounds */
//@{
/// Lower
const double * tightLower() const;
/// Upper
const double * tightUpper() const;
//@}
/**@name Get possible freed up row bounds - only valid after mode==3 */
//@{
/// Lower
const double * relaxedRowLower() const;
/// Upper
const double * relaxedRowUpper() const;
//@}
/**@name Change mode */
//@{
/// Set
void setMode(int mode);
/// Get
int getMode() const;
//@}
/**@name Change maxima */
//@{
/// Set maximum number of passes per node
void setMaxPass(int value);
/// Get maximum number of passes per node
int getMaxPass() const;
/// Set maximum number of unsatisfied variables to look at
void setMaxProbe(int value);
/// Get maximum number of unsatisfied variables to look at
int getMaxProbe() const;
/// Set maximum number of variables to look at in one probe
void setMaxLook(int value);
/// Get maximum number of variables to look at in one probe
int getMaxLook() const;
//@}
/**@name Stop or restart row cuts (otherwise just fixing from probing) */
//@{
/// Set
/// 0 no cuts, 1 just disaggregation type, 2 coefficient ( 3 both)
void setRowCuts(int type);
/// Get
int rowCuts() const;
//@}
/**@name Whether use objective as constraint */
//@{
/// Set
void setUsingObjective(bool yesNo);
/// Get
int getUsingObjective() const;
//@}
/**@name Constructors and destructors */
//@{
/// Default constructor
CglProbing ();
/// Copy constructor
CglProbing (
const CglProbing &);
/// Assignment operator
CglProbing &
operator=(
const CglProbing& rhs);
/// Destructor
virtual
~CglProbing ();
/// This can be used to refresh any inforamtion
virtual void refreshSolver(OsiSolverInterface * solver);
//@}
private:
// Private member methods
/**@name probe */
//@{
/// Does probing and adding cuts
int probe( const OsiSolverInterface & si,
const OsiRowCutDebugger * debugger,
OsiCuts & cs,
double * colLower, double * colUpper, CoinPackedMatrix *rowCopy,
double * rowLower, double * rowUpper,
char * intVar, double * minR, double * maxR, int * markR,
int * look, int nlook) const;
/** Does most of work of generateCuts
Returns number of infeasibilities */
int gutsOfGenerateCuts( const OsiSolverInterface & si,
OsiCuts & cs,
double * rowLower, double * rowUpper,
double * colLower, double * colUpper) const;
//@}
// Private member data
/**@name Private member data */
//@{
/// Row copy
CoinPackedMatrix * rowCopy_;
/// Lower bounds on rows
double * rowLower_;
/// Upper bounds on rows
double * rowUpper_;
/// Lower bounds on columns
double * colLower_;
/// Upper bounds on columns
double * colUpper_;
/// Number of rows in snapshot (0 if no snapshot)
int numberRows_;
/// Number of columns in snapshot (must == current)
int numberColumns_;
/// Tolerance to see if infeasible
double primalTolerance_;
/// Mode - 0 lazy using snapshot, 1 just unsatisfied, 2 all
int mode_;
/// Row cuts flag
/// 0 no cuts, 1 just disaggregation type, 2 coefficient ( 3 both)
int rowCuts_;
/// Maximum number of passes to do in probing
int maxPass_;
/// Maximum number of unsatisfied variables to probe
int maxProbe_;
/// Maximum number of variables to look at in one probe
int maxStack_;
/// Whether to include objective as constraint
bool usingObjective_;
/// Number of integer variables
int numberIntegers_;
/// Disaggregation cuts
typedef struct{
int sequence; // integer variable
// newValue will be NULL if no probing done yet
// lastLBWhenAt1 gives length of newValue;
int lastUBWhenAt0; // last UB changed when integer at lb
int lastLBWhenAt0; // last LB changed when integer at lb
int lastUBWhenAt1; // last UB changed when integer at ub
int lastLBWhenAt1; // last LB changed when integer at ub
int * index; // columns whose bounds will be changed
double * newValue; // new values
} disaggregation;
disaggregation * cutVector_;
//@}
};
//#############################################################################
/** A function that tests the methods in the CglProbing class. The
only reason for it not to be a member method is that this way it doesn't
have to be compiled into the library. And that's a gain, because the
library should be compiled with optimization on, but this method should be
compiled with debugging. */
void CglProbingUnitTest(const OsiSolverInterface * siP,
const std::string mpdDir );
#endif
| 31.762082 | 79 | 0.670529 | kant |