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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
92fd3892f8ba4a2fc53f95059b82150b7caf1a3e
| 1,248
|
hpp
|
C++
|
extensions/cli/src/basic_interactive_terminal.hpp
|
pxscope-swkang/perfkit
|
a30b56fdeb6975dbd253e85da5f79865d16d9d80
|
[
"MIT"
] | null | null | null |
extensions/cli/src/basic_interactive_terminal.hpp
|
pxscope-swkang/perfkit
|
a30b56fdeb6975dbd253e85da5f79865d16d9d80
|
[
"MIT"
] | null | null | null |
extensions/cli/src/basic_interactive_terminal.hpp
|
pxscope-swkang/perfkit
|
a30b56fdeb6975dbd253e85da5f79865d16d9d80
|
[
"MIT"
] | 1
|
2021-08-28T07:10:56.000Z
|
2021-08-28T07:10:56.000Z
|
//
// Created by Seungwoo on 2021-09-25.
//
#pragma once
#include <future>
#include <list>
#include "perfkit/common/circular_queue.hxx"
#include "perfkit/detail/commands.hpp"
#include "perfkit/terminal.h"
namespace perfkit {
class basic_interactive_terminal : public if_terminal
{
public:
basic_interactive_terminal();
public:
commands::registry* commands() override { return &_registry; }
std::optional<std::string> fetch_command(milliseconds timeout) override;
void write(std::string_view str, termcolor fg, termcolor bg) override;
std::shared_ptr<spdlog::sinks::sink> sink() override { return _sink; }
void push_command(std::string_view command) override;
bool set(std::string_view key, std::string_view value) override;
bool get(std::string_view key, double* out) override;
private:
void _register_autocomplete();
void _unregister_autocomplete();
private:
commands::registry _registry;
std::shared_ptr<spdlog::sinks::sink> _sink;
std::future<std::string> _cmd;
circular_queue<std::string> _cmd_history{16};
size_t _cmd_counter = 0;
std::mutex _cmd_queue_lock;
std::list<std::string> _cmd_queued;
std::string _prompt = "$ ";
};
} // namespace perfkit
| 27.130435
| 76
| 0.713942
|
pxscope-swkang
|
1300a0b256fdbdf6885168d3e2471b63795ca7dd
| 13,964
|
cpp
|
C++
|
src/client/communication/client_protocol.cpp
|
Santoi/quantum-chess
|
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
|
[
"MIT"
] | 9
|
2021-12-22T02:10:34.000Z
|
2021-12-30T17:14:25.000Z
|
src/client/communication/client_protocol.cpp
|
Santoi/quantum-chess
|
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
|
[
"MIT"
] | null | null | null |
src/client/communication/client_protocol.cpp
|
Santoi/quantum-chess
|
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
|
[
"MIT"
] | null | null | null |
#include <string>
#include <unistd.h>
#include <arpa/inet.h>
#include <map>
#include <vector>
#include <list>
#include <utility>
#include "../../common/unique_ptr.h"
#include "client_protocol.h"
#include "../../common/client_data.h"
#include "chessman_data.h"
#include "../../common/socket_closed.h"
std::map<uint16_t, std::vector<ClientData>>
ClientProtocol::receiveMatchesInfo(const Socket &socket) {
std::map<uint16_t, std::vector<ClientData>> matches_info;
uint16_t matches_amount = getNumber16FromSocket(socket);
for (uint16_t i = 0; i < matches_amount; i++) {
uint16_t match_id = getNumber16FromSocket(socket);
uint16_t clients_amount = getNumber16FromSocket(socket);
std::vector<ClientData> client_data_vector;
client_data_vector.reserve(clients_amount);
for (uint16_t j = 0; j < clients_amount; j++) {
uint16_t client_id = getNumber16FromSocket(socket);
std::string client_name;
getMessageFromSocket(socket, client_name);
auto role = (ClientData::Role) getNumber8FromSocket(socket);
ClientData data(client_id, client_name, role);
client_data_vector.push_back(std::move(data));
}
matches_info.insert(
std::make_pair(match_id, std::move(client_data_vector)));
}
return matches_info;
}
void ClientProtocol::getAvailableRoles(const Socket &socket,
std::list<ClientData::Role> &roles) {
uint8_t amount = getNumber8FromSocket(socket);
for (uint8_t i = 0; i < amount; i++) {
roles.push_back((ClientData::Role) getNumber8FromSocket(socket));
}
}
void ClientProtocol::sendChosenGame(const Socket &socket,
uint16_t game_number) {
Packet packet;
this->changeNumberToBigEndianAndAddToPacket(packet, (uint16_t) game_number);
socket.send(packet);
}
void
ClientProtocol::sendClientsNickName(const Socket &socket,
const std::string &nick_name) {
Packet packet;
this->addStringAndItsLengthToPacket(packet, nick_name);
socket.send(packet);
}
void
ClientProtocol::sendChosenRole(const Socket &socket, ClientData::Role role) {
Packet packet;
addNumber8ToPacket(packet, role);
socket.send(packet);
}
void ClientProtocol::fillPacketWithChatMessage(Packet &packet,
const std::string &message) {
packet.addByte(CHAT_PREFIX);
addStringAndItsLengthToPacket(packet, message);
}
void
ClientProtocol::fillPacketWithMoveMessage(Packet &packet,
const BoardPosition &initial,
const BoardPosition &final) {
packet.addByte(MOVE_PREFIX);
packet.addByte(initial.x());
packet.addByte(initial.y());
packet.addByte(final.x());
packet.addByte(final.y());
}
void
ClientProtocol::fillPacketWithSplitMessage(Packet &packet,
const BoardPosition &from,
const BoardPosition &to1,
const BoardPosition &to2) {
packet.addByte(SPLIT_PREFIX);
packet.addByte(from.x());
packet.addByte(from.y());
packet.addByte(to1.x());
packet.addByte(to1.y());
packet.addByte(to2.x());
packet.addByte(to2.y());
}
void ClientProtocol::fillPacketWithMergeMessage(Packet &packet,
const BoardPosition &from1,
const BoardPosition &from2,
const BoardPosition &to) {
packet.addByte(MERGE_PREFIX);
packet.addByte(from1.x());
packet.addByte(from1.y());
packet.addByte(from2.x());
packet.addByte(from2.y());
packet.addByte(to.x());
packet.addByte(to.y());
}
void ClientProtocol::
fillPacketWithPossibleMovesMessage(Packet &packet,
const BoardPosition &position) {
packet.addByte(POSSIBLE_MOVES_PREFIX);
addNumber8ToPacket(packet, position.x());
addNumber8ToPacket(packet, position.y());
}
void ClientProtocol::
fillPacketWithPossibleSplitsMessage(Packet &packet,
const BoardPosition &position) {
packet.addByte(POSSIBLE_SPLITS_PREFIX);
addNumber8ToPacket(packet, position.x());
addNumber8ToPacket(packet, position.y());
}
void ClientProtocol::
fillPacketWithPossibleMergesMessage(Packet &packet,
const BoardPosition &position) {
packet.addByte(POSSIBLE_MERGES_PREFIX);
addNumber8ToPacket(packet, 1);
addNumber8ToPacket(packet, position.x());
addNumber8ToPacket(packet, position.y());
}
void ClientProtocol::
fillPacketWithPossibleMergesMessage(Packet &packet,
const BoardPosition &position1,
const BoardPosition &position2) {
packet.addByte(POSSIBLE_MERGES_PREFIX);
addNumber8ToPacket(packet, 2);
addNumber8ToPacket(packet, position1.x());
addNumber8ToPacket(packet, position1.y());
addNumber8ToPacket(packet, position2.x());
addNumber8ToPacket(packet, position2.y());
}
void ClientProtocol::
fillPacketWithSameChessmanInstruction(Packet &packet,
const BoardPosition &position) {
packet.addByte(SAME_CHESSMAN_PREFIX);
addNumber8ToPacket(packet, position.x());
addNumber8ToPacket(packet, position.y());
}
void ClientProtocol::
fillPacketWithEntangledChessmanInstruction(Packet &packet,
const BoardPosition &position) {
packet.addByte(ENTANGLED_CHESSMEN_PREFIX);
addNumber8ToPacket(packet, position.x());
addNumber8ToPacket(packet, position.y());
}
void ClientProtocol::fillPacketWithSurrenderMessage(Packet &packet) {
packet.addByte(SURRENDER_PREFIX);
}
void ClientProtocol::
sendInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction> &instruction) {
Packet packet;
instruction->fillPacketWithInstructionsToSend(packet, *this);
socket.send(packet);
}
void
ClientProtocol::fillChatInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction> &
ptr_instruction) {
std::string nick_name;
uint16_t client_id;
std::string message;
std::string timestamp;
client_id = getNumber16FromSocket(socket);
getMessageFromSocket(socket, nick_name);
getMessageFromSocket(socket, timestamp);
getMessageFromSocket(socket, message);
ptr_instruction = make_unique<RemoteClientChatInstruction>(client_id,
nick_name,
message,
timestamp);
}
void
ClientProtocol::fillExitInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction> &
ptr_instruction) {
std::string nick_name;
this->getMessageFromSocket(socket, nick_name);
ptr_instruction = make_unique<RemoteClientExitMessageInstruction>(nick_name);
}
void ClientProtocol::
fillLoadBoardInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction> &
ptr_instruction) {
uint8_t amount = getNumber8FromSocket(socket);
std::vector<ChessmanData> chessman_data_vector;
chessman_data_vector.reserve(amount);
for (uint8_t i = 0; i < amount; i++) {
char character_ = getCharFromSocket(socket);
character_ = std::tolower(character_);
char character[] = {character_, '\0'};
bool white = getCharFromSocket(socket);
std::string chessman(character);
chessman += white ? "w" : "b";
uint8_t x = getNumber8FromSocket(socket);
uint8_t y = getNumber8FromSocket(socket);
BoardPosition position(x, y);
uint16_t prob_int = getNumber16FromSocket(socket);
double prob = ((double) prob_int + 1) / (UINT16_MAX + 1);
chessman_data_vector.push_back(ChessmanData(position, chessman, prob));
}
bool white = getNumber8FromSocket(socket);
ptr_instruction = make_unique<RemoteClientLoadBoardInstruction>(
std::move(chessman_data_vector), white);
}
void ClientProtocol::fillShortLogInstruction(const Socket &socket,
std::shared_ptr<
RemoteClientInstruction>
&ptr_instruction) {
std::string message;
this->getMessageFromSocket(socket, message);
ptr_instruction = make_unique<RemoteClientExceptionInstruction>(message);
}
void ClientProtocol::
fillPossibleMovesInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction>
&ptr_instruction) {
uint8_t amount = getNumber8FromSocket(socket);
std::list<BoardPosition> posible_moves;
for (uint8_t i = 0; i < amount; i++) {
uint8_t x = getNumber8FromSocket(socket);
uint8_t y = getNumber8FromSocket(socket);
BoardPosition position(x, y);
posible_moves.push_back(position);
}
ptr_instruction = make_unique<RemoteClientPossibleMovesInstruction>(
std::move(posible_moves));
}
void ClientProtocol::
fillPossibleSplitsInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction>
&ptr_instruction) {
uint8_t amount = getNumber8FromSocket(socket);
std::list<BoardPosition> posible_moves;
for (uint8_t i = 0; i < amount; i++) {
uint8_t x = getNumber8FromSocket(socket);
uint8_t y = getNumber8FromSocket(socket);
BoardPosition position(x, y);
posible_moves.push_back(position);
}
ptr_instruction = make_unique<RemoteClientPossibleSplitsInstruction>(
std::move(posible_moves));
}
void ClientProtocol::fillPossibleMergesInstruction(const Socket &socket,
std::shared_ptr<
RemoteClientInstruction>
&ptr_instruction) {
uint8_t amount = getNumber8FromSocket(socket);
std::list<BoardPosition> posible_moves;
for (uint8_t i = 0; i < amount; i++) {
uint8_t x = getNumber8FromSocket(socket);
uint8_t y = getNumber8FromSocket(socket);
BoardPosition position(x, y);
posible_moves.push_back(position);
}
ptr_instruction = make_unique<RemoteClientPossibleMergesInstruction>(
std::move(posible_moves));
}
void ClientProtocol::
fillSameChessmanInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction>
&ptr_instruction) {
uint8_t amount = getNumber8FromSocket(socket);
std::list<BoardPosition> posible_moves;
for (uint8_t i = 0; i < amount; i++) {
uint8_t x = getNumber8FromSocket(socket);
uint8_t y = getNumber8FromSocket(socket);
BoardPosition position(x, y);
posible_moves.push_back(position);
}
ptr_instruction = make_unique<RemoteClientSameChessmanInstruction>(
std::move(posible_moves));
}
void ClientProtocol::
fillEntangledChessmanInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction>
&ptr_instruction) {
uint8_t amount = getNumber8FromSocket(socket);
std::list<BoardPosition> posible_moves;
for (uint8_t i = 0; i < amount; i++) {
uint8_t x = getNumber8FromSocket(socket);
uint8_t y = getNumber8FromSocket(socket);
BoardPosition position(x, y);
posible_moves.push_back(position);
}
ptr_instruction = make_unique<RemoteClientEntangledChessmanInstruction>(
std::move(posible_moves));
}
void ClientProtocol::
fillSoundInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction>
&ptr_instruction) {
uint8_t sound = getNumber8FromSocket(socket);
ptr_instruction = std::make_shared<RemoteClientSoundInstruction>(sound);
}
void ClientProtocol::
fillLogInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction> &ptr) {
std::list<std::string> log;
uint16_t amount = getNumber16FromSocket(socket);
for (uint16_t i = 0; i < amount; i++) {
std::string message;
getMessageFromSocket(socket, message);
log.push_back(std::move(message));
}
ptr = std::make_shared<RemoteClientLogInstruction>(std::move(log));
}
void ClientProtocol::receiveInstruction(const Socket &socket,
std::shared_ptr<RemoteClientInstruction>
&ptr_instruction) {
Packet packet;
socket.receive(packet, 1);
if (packet.size() != 1)
throw SocketClosed();
char action = packet.getByte();
switch (action) {
case CHAT_PREFIX:
fillChatInstruction(socket, ptr_instruction);
break;
case LOAD_BOARD_PREFIX:
fillLoadBoardInstruction(socket, ptr_instruction);
break;
case EXIT_PREFIX:
fillExitInstruction(socket, ptr_instruction);
break;
case EXCEPTION_PREFIX:
fillShortLogInstruction(socket, ptr_instruction);
break;
case POSSIBLE_MOVES_PREFIX:
fillPossibleMovesInstruction(socket, ptr_instruction);
break;
case POSSIBLE_SPLITS_PREFIX:
fillPossibleSplitsInstruction(socket, ptr_instruction);
break;
case POSSIBLE_MERGES_PREFIX:
fillPossibleMergesInstruction(socket, ptr_instruction);
break;
case SAME_CHESSMAN_PREFIX:
fillSameChessmanInstruction(socket, ptr_instruction);
break;
case ENTANGLED_CHESSMEN_PREFIX:
fillEntangledChessmanInstruction(socket, ptr_instruction);
break;
case SOUND_PREFIX:
fillSoundInstruction(socket, ptr_instruction);
break;
case LOG_PREFIX:
fillLogInstruction(socket, ptr_instruction);
break;
default:
break;
}
}
| 36.082687
| 80
| 0.655758
|
Santoi
|
13022bae3d38f95e25a88dfd2e86d7f3a7a935b9
| 2,922
|
cpp
|
C++
|
EngineLuke/src/ML_ENGINE/ML_ENGINE/ML/Utilities/Statistics.cpp
|
speed0606/team.luke
|
6354d8237227276316a8f1e4bb10486a9ab968bf
|
[
"MIT"
] | 3
|
2016-12-03T08:24:51.000Z
|
2017-02-26T21:28:29.000Z
|
EngineLuke/src/ML_ENGINE/ML_ENGINE/ML/Utilities/Statistics.cpp
|
dk-seo/team.luke
|
6354d8237227276316a8f1e4bb10486a9ab968bf
|
[
"MIT"
] | null | null | null |
EngineLuke/src/ML_ENGINE/ML_ENGINE/ML/Utilities/Statistics.cpp
|
dk-seo/team.luke
|
6354d8237227276316a8f1e4bb10486a9ab968bf
|
[
"MIT"
] | 2
|
2017-02-19T23:41:27.000Z
|
2017-02-26T21:28:31.000Z
|
#include "Similarity.h"
#include "../Dataframe/Dataframe.h"
#include <algorithm>
#include "Statistics.h"
double CalculateMean(
const std::vector<Instance*>& instances, size_t attributeIdx)
{
if (instances.size() == 0)
return 0.0;
double mean = 0.0f;
for (auto instance : instances)
mean += double(instance->GetAttribute(attributeIdx).AsDouble());
mean /= double(instances.size());
return mean;
}
double CalculateMedian(
std::vector<Instance*> instances, size_t attributeIdx)
{
// sort instances by attribute value
std::sort(instances.begin(), instances.end(),
[&attributeIdx](const Instance* lhs, const Instance* rhs) {
return lhs->GetAttribute(attributeIdx).AsDouble()
< rhs->GetAttribute(attributeIdx).AsDouble();
}
);
// calculate median
size_t middle = instances.size() / 2;
double median;
if (instances.size() % 2)
{
// if there are an even number of instances, median is the middlemost value
median = instances[middle]->GetAttribute(attributeIdx).AsDouble();
}
else
{
// if there are an odd number of instances, median is the average of the two middlemost values
median = (instances[middle]->GetAttribute(attributeIdx).AsDouble()
+ instances[middle - 1]->GetAttribute(attributeIdx).AsDouble())
* 0.5;
}
return median;
}
std::vector<double> CalculateMode(
const std::vector<Instance*>& instances, size_t attributeIdx)
{
// find modes
std::unordered_map<double, int> frequencies;
int highestFrequency = std::numeric_limits<int>::min();
for (unsigned i = 0; i < instances.size(); ++i)
{
auto frequency = frequencies.find(
instances[i]->GetAttribute(attributeIdx).AsDouble());
if (frequency == frequencies.end())
frequencies.emplace(
instances[i]->GetAttribute(attributeIdx).AsDouble(), 1);
else if (++frequency->second > highestFrequency)
highestFrequency = frequency->second;
}
// frequency 1 is not considered as mode, so exclude the case
std::vector<double> modes;
if (highestFrequency > 1)
{
for (auto frequency : frequencies)
{
if (frequency.second == highestFrequency)
modes.emplace_back(frequency.first);
}
}
return std::move(modes);
}
double FindMax(const std::vector<Instance*>& instances, size_t attributeIdx)
{
if (instances.size() == 0)
return 0.0;
double max = double(instances[0]->GetAttribute(attributeIdx).AsDouble());
for (auto instance : instances)
{
if(max <double(instance->GetAttribute(attributeIdx).AsDouble()))
max = double(instance->GetAttribute(attributeIdx).AsDouble());
}
return max;
}
double FindMin(const std::vector<Instance*>& instances, size_t attributeIdx)
{
if (instances.size() == 0)
return 0.0;
double min = double(instances[0]->GetAttribute(attributeIdx).AsDouble());
for (auto instance : instances)
{
if (min > double(instance->GetAttribute(attributeIdx).AsDouble()))
min = double(instance->GetAttribute(attributeIdx).AsDouble());
}
return min;
}
| 26.807339
| 96
| 0.709788
|
speed0606
|
13029a4976338faf7e38f2672316abeedd4bcdb5
| 118
|
cpp
|
C++
|
main.cpp
|
Ruixues/Judo
|
47925aec22edb49d41846e21a4add11411380ffb
|
[
"Apache-2.0"
] | 9
|
2020-09-14T15:16:47.000Z
|
2021-06-05T07:36:32.000Z
|
main.cpp
|
Ruixues/Judo
|
47925aec22edb49d41846e21a4add11411380ffb
|
[
"Apache-2.0"
] | 1
|
2020-12-28T04:06:58.000Z
|
2020-12-28T04:06:58.000Z
|
main.cpp
|
Ruixues/Judo
|
47925aec22edb49d41846e21a4add11411380ffb
|
[
"Apache-2.0"
] | 1
|
2020-12-20T09:42:16.000Z
|
2020-12-20T09:42:16.000Z
|
#include "args.h"
#include <iostream>
int main(int argc, char *argv[]) {
HandleInput(argc, argv);
return 0;
}
| 16.857143
| 34
| 0.635593
|
Ruixues
|
1303c7a7f4741f4c42fa49ee45fd19c7d22ca865
| 969
|
cpp
|
C++
|
dev/g++/projects/ttcn3/internal_tci/src/tci_type_impl.cpp
|
YannGarcia/repo
|
0f3de24c71d942c752ada03c10861e83853fdf71
|
[
"MIT"
] | null | null | null |
dev/g++/projects/ttcn3/internal_tci/src/tci_type_impl.cpp
|
YannGarcia/repo
|
0f3de24c71d942c752ada03c10861e83853fdf71
|
[
"MIT"
] | null | null | null |
dev/g++/projects/ttcn3/internal_tci/src/tci_type_impl.cpp
|
YannGarcia/repo
|
0f3de24c71d942c752ada03c10861e83853fdf71
|
[
"MIT"
] | 1
|
2017-01-27T12:53:50.000Z
|
2017-01-27T12:53:50.000Z
|
/**
* @file tci_type_impl.h
* @brief Main implementation file for the tci_type_impl class.
* @author garciay.yann@gmail.com
* @copyright Copyright (c) 2015 ygarcia. All rights reserved
* @license This project is released under the MIT License
* @version 0.1
*/
#include "tci_module_id_impl.h"
namespace internal::ttcn3::tci::impl {
tci_type_impl::tci_type_impl() :
_module_id(),
_name(),
_type_encoding()
_type_encoding_variant(),
_type_encoding_extension()
{
} // End of ctor
tci_type_impl::tci_type_impl(const tci_type & p_tci_type) :
_module_id(p_tci_type.get_defining_module()),
_name(p_tci_type),
_type_encoding(p_tci_type)
_type_encoding_variant(p_tci_type),
_type_encoding_extension(p_tci_type)
{
} // End of copy ctor
tci_type_impl::~tci_type_impl() {
} // End of dtor
}; // End of namespace internal::ttcn3::tci
| 26.916667
| 65
| 0.652219
|
YannGarcia
|
1306b7f69ccf390d57496a769ff2857a16e27893
| 1,447
|
cpp
|
C++
|
src/vector.cpp
|
S-VIN/GraphicLib
|
c57e6828a51f29ca06281e9ac2a8759565298f20
|
[
"MIT"
] | null | null | null |
src/vector.cpp
|
S-VIN/GraphicLib
|
c57e6828a51f29ca06281e9ac2a8759565298f20
|
[
"MIT"
] | null | null | null |
src/vector.cpp
|
S-VIN/GraphicLib
|
c57e6828a51f29ca06281e9ac2a8759565298f20
|
[
"MIT"
] | null | null | null |
#include "../headers/vector.h"
Vector::Vector() {}
Vector::~Vector() {}
void Vector:: addFigure(Figure* figure){
figures.push_back(figure);
};
void Vector:: deleteFigure(int i){
figures.erase(figures.begin() + i);
}
bool Vector:: isSquareHere(Point point, Square* square){
if(point.x <= square->zeroPoint.x + square->side &&
point.x >= square->zeroPoint.x &&
point.y <= square->zeroPoint.y &&
point.y >= square->zeroPoint.y - square->side){
return true;
}
return false;
}
bool Vector:: isDotHere(Point point, Dot* dot){
if(point.x == dot->zeroPoint.x && point.y == dot->zeroPoint.y){
return true;
}
return false;
}
bool Vector::isLineHere(Point point, Line *line) {
return false;//////////////////////////////
}
Figure * Vector:: getFigure(int number){
return figures[number];
};
bool Vector:: isFilled(Point point){
for(auto item : figures){
switch (item->type)
{
case SQUARE:
if(isSquareHere(point, (Square*)item))
return true;
break;
case LINE:
if(isLineHere(point, (Line*)item))
return true;
break;
case DOT:
if(isDotHere(point, (Dot*)item))
return true;
break;
default:
break;
}
}
return false;
}
| 21.924242
| 67
| 0.516932
|
S-VIN
|
130c6d8312e00e0b2128a3d0361f18d9bc7e0e7c
| 1,479
|
hpp
|
C++
|
code/libuipf/src/include/data/opencv.hpp
|
jdkuhnke/uipf
|
a944237e71cc61be29c641f7320e8ee3a0f0624f
|
[
"BSD-2-Clause"
] | 4
|
2017-03-26T05:56:57.000Z
|
2020-02-04T23:14:13.000Z
|
code/libuipf/src/include/data/opencv.hpp
|
jdkuhnke/uipf
|
a944237e71cc61be29c641f7320e8ee3a0f0624f
|
[
"BSD-2-Clause"
] | 3
|
2017-05-13T21:30:39.000Z
|
2018-03-20T17:00:52.000Z
|
code/libuipf/src/include/data/opencv.hpp
|
jdkuhnke/uipf
|
a944237e71cc61be29c641f7320e8ee3a0f0624f
|
[
"BSD-2-Clause"
] | 3
|
2017-11-29T10:26:13.000Z
|
2021-06-15T13:14:04.000Z
|
#ifndef LIBUIPF_DATA_OPENCV_HPP
#define LIBUIPF_DATA_OPENCV_HPP
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <map>
#include <string>
#include "../data.hpp"
#include "list.hpp"
namespace uipf {
namespace data {
// create types for OpenCV if built with OpenCV support
UIPF_DATA_TYPE_BEGIN (OpenCVMat, "uipf.opencv.Mat", cv::Mat)
public:
/**
* The file name of the original image file.
*/
std::string filename;
/**
* EXIF meta data, if any was found in the file.
*/
std::map<std::string, std::string> exif;
/**
* @return whether this images is stored on the disk. If true, filename is set.
*/
bool getIsStored() const;
// TODO store does not store EXIF data right now
void store(const std::string& f, const std::vector<int>& params=std::vector<int>());
std::vector<std::string> visualizations() const;
void visualize(std::string option, VisualizationContext& context) const;
UIPF_DATA_TYPE_END
OpenCVMat::ptr load_image_color(const std::string& filename);
OpenCVMat::ptr load_image_greyscale(const std::string& filename);
std::map<std::string, std::string> load_image_exif_data(const std::string& filename);
uipf::data::List::ptr load_images_color(const std::string& path);
uipf::data::List::ptr load_images_greyscale(const std::string& path);
std::vector<std::string> load_image_names(const std::string& path);
};
};
#endif // LIBUIPF_DATA_OPENCV_HPP
| 25.5
| 87
| 0.705882
|
jdkuhnke
|
130c8f6ba144264ea19fe6be78d592faecf81d78
| 1,674
|
hpp
|
C++
|
src/vendor/cget/include/pqrs/osx/system_preferences/system_preferences.hpp
|
egelwan/Karabiner-Elements
|
896439dd2130904275553282063dd7fe4852e1a8
|
[
"Unlicense"
] | 5,422
|
2019-10-27T17:51:04.000Z
|
2022-03-31T15:45:41.000Z
|
src/vendor/cget/include/pqrs/osx/system_preferences/system_preferences.hpp
|
XXXalice/Karabiner-Elements
|
52f579cbf60251cf18915bd938eb4431360b763b
|
[
"Unlicense"
] | 1,310
|
2019-10-28T04:57:24.000Z
|
2022-03-31T04:55:37.000Z
|
src/vendor/cget/include/pqrs/osx/system_preferences/system_preferences.hpp
|
XXXalice/Karabiner-Elements
|
52f579cbf60251cf18915bd938eb4431360b763b
|
[
"Unlicense"
] | 282
|
2019-10-28T02:36:04.000Z
|
2022-03-19T06:18:54.000Z
|
#pragma once
// (C) Copyright Takayama Fumihiko 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See http://www.boost.org/LICENSE_1_0.txt)
#include "keyboard_type_key.hpp"
#include <pqrs/cf/number.hpp>
namespace pqrs {
namespace osx {
namespace system_preferences {
inline std::optional<bool> find_bool_property(CFStringRef key,
CFStringRef application_id) {
std::optional<bool> value = std::nullopt;
if (auto v = CFPreferencesCopyAppValue(key, application_id)) {
if (CFBooleanGetTypeID() == CFGetTypeID(v)) {
value = CFBooleanGetValue(static_cast<CFBooleanRef>(v));
}
CFRelease(v);
}
return value;
}
inline std::optional<float> find_float_property(CFStringRef key,
CFStringRef application_id) {
std::optional<float> value = std::nullopt;
if (auto v = CFPreferencesCopyAppValue(key, application_id)) {
if (CFNumberGetTypeID() == CFGetTypeID(v)) {
float vv;
if (CFNumberGetValue(static_cast<CFNumberRef>(v), kCFNumberFloatType, &vv)) {
value = vv;
}
}
CFRelease(v);
}
return value;
}
inline cf::cf_ptr<CFDictionaryRef> find_dictionary_property(CFStringRef key,
CFStringRef application_id) {
cf::cf_ptr<CFDictionaryRef> result;
if (auto v = CFPreferencesCopyAppValue(key, application_id)) {
if (CFDictionaryGetTypeID() == CFGetTypeID(v)) {
result = static_cast<CFDictionaryRef>(v);
}
CFRelease(v);
}
return result;
}
} // namespace system_preferences
} // namespace osx
} // namespace pqrs
| 27.9
| 89
| 0.642772
|
egelwan
|
130cf73bec693b1d4720ecd16c3ac0ca97a10a14
| 5,740
|
hpp
|
C++
|
ZeroLibraries/Common/Containers/HashSet.hpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | 52
|
2018-09-11T17:18:35.000Z
|
2022-03-13T15:28:21.000Z
|
ZeroLibraries/Common/Containers/HashSet.hpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | 1,409
|
2018-09-19T18:03:43.000Z
|
2021-06-09T08:33:33.000Z
|
ZeroLibraries/Common/Containers/HashSet.hpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | 26
|
2018-09-11T17:16:32.000Z
|
2021-11-22T06:21:19.000Z
|
///////////////////////////////////////////////////////////////////////////////
///
/// \file HashSet.hpp
/// Definition of the HashSet associative container.
///
/// Authors: Chris Peters
/// Copyright 2010-2011, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "ContainerCommon.hpp"
#include "HashedContainer.hpp"
namespace Zero
{
template<typename Hasher, typename ValueType>
struct SetHashAdapter
{
Hasher mHasher;
size_t operator()(const ValueType& value)
{
return (size_t)mHasher(value);
}
bool Equal(const ValueType& left, const ValueType& right)
{
return mHasher.Equal(left, right);
}
template<typename othertype>
bool Equal(const ValueType& left, const othertype& right)
{
return mHasher.Equal(left, right);
}
};
///Hash Set is an Associative Hashed Container.
template< typename ValueType,
typename Hasher = HashPolicy<ValueType>,
typename Allocator = DefaultAllocator >
class ZeroSharedTemplate HashSet : public HashedContainer< ValueType,
SetHashAdapter< Hasher, ValueType >,
Allocator >
{
public:
typedef ValueType value_type;
typedef size_t size_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef HashSet<ValueType, Hasher, Allocator> this_type;
typedef HashedContainer< ValueType,
SetHashAdapter< Hasher, ValueType >,
Allocator > base_type;
typedef typename base_type::Node* iterator;
typedef typename base_type::Node Node;
typedef typename base_type::range range;
HashSet()
{
}
HashSet(ContainerInitializerDummy*, const_reference p0)
{
Insert(p0);
}
HashSet(ContainerInitializerDummy*, const_reference p0, const_reference p1)
{
Insert(p0);
Insert(p1);
}
HashSet(ContainerInitializerDummy*, const_reference p0, const_reference p1, const_reference p2)
{
Insert(p0);
Insert(p1);
Insert(p2);
}
HashSet(ContainerInitializerDummy*, const_reference p0, const_reference p1, const_reference p2, const_reference p3)
{
Insert(p0);
Insert(p1);
Insert(p2);
Insert(p3);
}
HashSet(ContainerInitializerDummy*, const_reference p0, const_reference p1, const_reference p2, const_reference p3, const_reference p4)
{
Insert(p0);
Insert(p1);
Insert(p2);
Insert(p3);
Insert(p4);
}
HashSet(ContainerInitializerDummy*, const_reference p0, const_reference p1, const_reference p2, const_reference p3, const_reference p4, const_reference p5)
{
Insert(p0);
Insert(p1);
Insert(p2);
Insert(p3);
Insert(p4);
Insert(p5);
}
///Warning: Depending on the contents of the hash sets, this may be expensive.
HashSet(const HashSet& other)
{
*this = other;
}
///Warning: Depending on the contents of the hash sets, this may be expensive.
void operator = (const HashSet& other)
{
// Don't self Assign
if(&other == this)
return;
this->Clear();
range r = other.All();
while(!r.Empty())
{
base_type::InsertInternal(r.Front(), base_type::OnCollisionOverride);
r.PopFront();
}
}
range Find(const value_type& value)
{
//searching for the actual type of the container.
Node* node = base_type::InternalFindAs(value, base_type::mHasher);
if(node != cHashOpenNode)
return range(node, node + 1, 1);
else
return range((Node*)cHashOpenNode, (Node*)cHashOpenNode, 0);
}
template<typename searchType, typename searchHasher>
range FindAs(const searchType& searchKey,
searchHasher keyHasher = HashPolicy<searchType>()) const
{
Node* node = base_type::InternalFindAs(searchKey, keyHasher);
if(node != cHashOpenNode)
return range(node, node + 1, 1);
else
return range((Node*)cHashOpenNode, (Node*)cHashOpenNode, 0);
}
value_type FindValue(const value_type& searchKey, const value_type& ifNotFound) const
{
Node* node = base_type::InternalFindAs(searchKey, base_type::mHasher);
if(node != cHashOpenNode)
return node->Value;
else
return ifNotFound;
}
//Returns a pointer to the value if found, or null if not found
value_type* FindPointer(const value_type& searchKey) const
{
Node* foundNode = base_type::InternalFindAs(searchKey, base_type::mHasher);
if(foundNode != cHashOpenNode)
return &(foundNode->Value);
else
return nullptr;
}
template<typename inputRangeType>
void Append(inputRangeType inputRange)
{
for(; !inputRange.Empty(); inputRange.PopFront())
Insert(inputRange.Front());
}
void Insert(const value_type& value)
{
base_type::InsertInternal(value, base_type::OnCollisionOverride);
}
bool InsertOrError(const value_type& value)
{
return base_type::InsertInternal(value, base_type::OnCollisionError) != false;
}
bool InsertOrError(const value_type& value, cstr error)
{
bool result = InsertOrError(value);
ErrorIf(result == false, "%s", error);
return result;
}
bool InsertNoOverwrite(const value_type& value)
{
return base_type::InsertInternal(value, base_type::OnCollisionReturn) != false;
}
bool Contains(const value_type& value) const
{
return base_type::InternalFindAs(value, base_type::mHasher)!=cHashOpenNode;
}
~HashSet()
{
}
};
}//namespace Zero
| 28
| 158
| 0.63101
|
jodavis42
|
1310d125c3eb1723d3bc97c7388de8b5b03a1ab5
| 9,392
|
cpp
|
C++
|
openbr/plugins/validate.cpp
|
clcarwin/openbr
|
00700cc8c3d19df5ff08045ef1b19bacfbe22b25
|
[
"Apache-2.0"
] | 1
|
2015-11-06T05:29:35.000Z
|
2015-11-06T05:29:35.000Z
|
openbr/plugins/validate.cpp
|
guker/openbr
|
20fd2aaec557a51ad46b47d55dea9cf7e364818a
|
[
"Apache-2.0"
] | null | null | null |
openbr/plugins/validate.cpp
|
guker/openbr
|
20fd2aaec557a51ad46b47d55dea9cf7e364818a
|
[
"Apache-2.0"
] | null | null | null |
#include <QFutureSynchronizer>
#include <QtConcurrentRun>
#include "openbr_internal.h"
#include "openbr/core/common.h"
#include <openbr/core/qtutils.h>
namespace br
{
static void _train(Transform *transform, TemplateList data) // think data has to be a copy -cao
{
transform->train(data);
}
/*!
* \ingroup transforms
* \brief Cross validate a trainable transform.
* \author Josh Klontz \cite jklontz
* \author Scott Klum \cite sklum
* \note To use an extended gallery, add an allPartitions="true" flag to the gallery sigset for those images that should be compared
* against for all testing partitions.
*/
class CrossValidateTransform : public MetaTransform
{
Q_OBJECT
Q_PROPERTY(QString description READ get_description WRITE set_description RESET reset_description STORED false)
Q_PROPERTY(bool leaveOneImageOut READ get_leaveOneImageOut WRITE set_leaveOneImageOut RESET reset_leaveOneImageOut STORED false)
BR_PROPERTY(QString, description, "Identity")
BR_PROPERTY(bool, leaveOneImageOut, false)
// numPartitions copies of transform specified by description.
QList<br::Transform*> transforms;
// Treating this transform as a leaf (in terms of update training scheme), the child transform
// of this transform will lose any structure present in the training QList<TemplateList>, which
// is generally incorrect behavior.
void train(const TemplateList &data)
{
int numPartitions = 0;
QList<int> partitions; partitions.reserve(data.size());
foreach (const File &file, data.files()) {
partitions.append(file.get<int>("Partition", 0));
numPartitions = std::max(numPartitions, partitions.last()+1);
}
while (transforms.size() < numPartitions)
transforms.append(make(description));
if (numPartitions < 2) {
transforms.first()->train(data);
return;
}
QFutureSynchronizer<void> futures;
for (int i=0; i<numPartitions; i++) {
QList<int> partitionsBuffer = partitions;
TemplateList partitionedData = data;
int j = partitionedData.size()-1;
while (j>=0) {
// Remove all templates belonging to partition i
// if leaveOneImageOut is true,
// and i is greater than the number of images for a particular subject
// even if the partitions are different
if (leaveOneImageOut) {
const QString label = partitionedData.at(j).file.get<QString>("Label");
QList<int> subjectIndices = partitionedData.find("Label",label);
QList<int> removed;
// Remove target only data
for (int k=subjectIndices.size()-1; k>=0; k--)
if (partitionedData[subjectIndices[k]].file.getBool("targetOnly")) {
removed.append(subjectIndices[k]);
subjectIndices.removeAt(k);
}
// Remove template that was repeated to make the testOnly template
if (subjectIndices.size() > 1 && subjectIndices.size() <= i) {
removed.append(subjectIndices[i%subjectIndices.size()]);
} else if (partitionsBuffer[j] == i) {
removed.append(j);
}
if (!removed.empty()) {
typedef QPair<int,int> Pair;
foreach (Pair pair, Common::Sort(removed,true)) {
partitionedData.removeAt(pair.first); partitionsBuffer.removeAt(pair.first); j--;
}
} else {
j--;
}
} else if (partitions[j] == i) {
// Remove data, it's designated for testing
partitionedData.removeAt(j);
j--;
} else j--;
}
// Train on the remaining templates
futures.addFuture(QtConcurrent::run(_train, transforms[i], partitionedData));
}
futures.waitForFinished();
}
void project(const Template &src, Template &dst) const
{
// Remember, the partition should never be -1
// since it is assumed that the allPartitions
// flag is only used during comparison
// (i.e. only used when making a mask)
// If we want to duplicate templates but use the same training data
// for all partitions (i.e. transforms.size() == 1), we need to
// restrict the partition
int partition = src.file.get<int>("Partition", 0);
partition = (partition >= transforms.size()) ? 0 : partition;
transforms[partition]->project(src, dst);
}
void store(QDataStream &stream) const
{
stream << transforms.size();
foreach (Transform *transform, transforms)
transform->store(stream);
}
void load(QDataStream &stream)
{
int numTransforms;
stream >> numTransforms;
while (transforms.size() < numTransforms)
transforms.append(make(description));
foreach (Transform *transform, transforms)
transform->load(stream);
}
};
BR_REGISTER(Transform, CrossValidateTransform)
/*!
* \ingroup distances
* \brief Cross validate a distance metric.
* \author Josh Klontz \cite jklontz
*/
class CrossValidateDistance : public Distance
{
Q_OBJECT
float compare(const Template &a, const Template &b) const
{
static const QString key("Partition"); // More efficient to preallocate this
const int partitionA = a.file.get<int>(key, 0);
const int partitionB = b.file.get<int>(key, 0);
return (partitionA != partitionB) ? -std::numeric_limits<float>::max() : 0;
}
};
BR_REGISTER(Distance, CrossValidateDistance)
/*!
* \ingroup distances
* \brief Checks target metadata against filters.
* \author Josh Klontz \cite jklontz
*/
class FilterDistance : public Distance
{
Q_OBJECT
float compare(const Template &a, const Template &b) const
{
(void) b; // Query template isn't checked
foreach (const QString &key, Globals->filters.keys()) {
bool keep = false;
const QString metadata = a.file.get<QString>(key, "");
if (Globals->filters[key].isEmpty()) continue;
if (metadata.isEmpty()) return -std::numeric_limits<float>::max();
foreach (const QString &value, Globals->filters[key]) {
if (metadata == value) {
keep = true;
break;
}
}
if (!keep) return -std::numeric_limits<float>::max();
}
return 0;
}
};
BR_REGISTER(Distance, FilterDistance)
/*!
* \ingroup distances
* \brief Checks target metadata against query metadata.
* \author Scott Klum \cite sklum
*/
class MetadataDistance : public Distance
{
Q_OBJECT
Q_PROPERTY(QStringList filters READ get_filters WRITE set_filters RESET reset_filters STORED false)
BR_PROPERTY(QStringList, filters, QStringList())
float compare(const Template &a, const Template &b) const
{
foreach (const QString &key, filters) {
QString aValue = a.file.get<QString>(key, QString());
QString bValue = b.file.get<QString>(key, QString());
// The query value may be a range. Let's check.
if (bValue.isEmpty()) bValue = QtUtils::toString(b.file.get<QPointF>(key, QPointF()));
if (aValue.isEmpty() || bValue.isEmpty()) continue;
bool keep = false;
bool ok;
QPointF range = QtUtils::toPoint(bValue,&ok);
if (ok) /* Range */ {
int value = range.x();
int upperBound = range.y();
while (value <= upperBound) {
if (aValue == QString::number(value)) {
keep = true;
break;
}
value++;
}
}
else if (aValue == bValue) keep = true;
if (!keep) return -std::numeric_limits<float>::max();
}
return 0;
}
};
BR_REGISTER(Distance, MetadataDistance)
/*!
* \ingroup distances
* \brief Sets distance to -FLOAT_MAX if a target template has/doesn't have a key.
* \author Scott Klum \cite sklum
*/
class RejectDistance : public Distance
{
Q_OBJECT
Q_PROPERTY(QStringList keys READ get_keys WRITE set_keys RESET reset_keys STORED false)
BR_PROPERTY(QStringList, keys, QStringList())
Q_PROPERTY(bool rejectIfContains READ get_rejectIfContains WRITE set_rejectIfContains RESET reset_rejectIfContains STORED false)
BR_PROPERTY(bool, rejectIfContains, false)
float compare(const Template &a, const Template &b) const
{
// We don't look at the query
(void) b;
foreach (const QString &key, keys)
if ((rejectIfContains && a.file.contains(key)) || (!rejectIfContains && !a.file.contains(key)))
return -std::numeric_limits<float>::max();
return 0;
}
};
BR_REGISTER(Distance, RejectDistance)
} // namespace br
#include "validate.moc"
| 34.529412
| 132
| 0.592845
|
clcarwin
|
131182ee70ef5f641dbb8f99ef45aa1e0922ad6e
| 2,118
|
cpp
|
C++
|
Part1/Chapter5/P5731.cpp
|
flics04/SSQCbook-Base-Luogu
|
c7ddbcfec58d6cc8f6396309daa8b511b6c8673d
|
[
"MIT"
] | null | null | null |
Part1/Chapter5/P5731.cpp
|
flics04/SSQCbook-Base-Luogu
|
c7ddbcfec58d6cc8f6396309daa8b511b6c8673d
|
[
"MIT"
] | null | null | null |
Part1/Chapter5/P5731.cpp
|
flics04/SSQCbook-Base-Luogu
|
c7ddbcfec58d6cc8f6396309daa8b511b6c8673d
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int n;
int main() {
cin >> n;
if (n == 1)
cout << " 1\n";
if (n == 2)
cout << " 1 2\n 4 3\n";
if (n == 3) {
cout << " 1 2 3\n";
cout << " 8 9 4\n";
cout << " 7 6 5\n";
}
if (n == 4) {
cout << " 1 2 3 4\n";
cout << " 12 13 14 5\n";
cout << " 11 15 16 6\n";
cout << " 10 9 8 7\n";
}
if (n == 5) {
cout << " 1 2 3 4 5\n";
cout << " 16 17 18 19 6\n";
cout << " 15 24 25 20 7\n";
cout << " 14 23 22 21 8\n";
cout << " 13 12 11 10 9\n";
}
if (n == 6) {
cout << " 1 2 3 4 5 6\n";
cout << " 20 21 22 23 24 7\n";
cout << " 19 32 33 34 25 8\n";
cout << " 18 31 36 35 26 9\n";
cout << " 17 30 29 28 27 10\n";
cout << " 16 15 14 13 12 11\n";
}
if (n == 7) {
cout << " 1 2 3 4 5 6 7\n";
cout << " 24 25 26 27 28 29 8\n";
cout << " 23 40 41 42 43 30 9\n";
cout << " 22 39 48 49 44 31 10\n";
cout << " 21 38 47 46 45 32 11\n";
cout << " 20 37 36 35 34 33 12\n";
cout << " 19 18 17 16 15 14 13\n";
}
if (n == 8) {
cout << " 1 2 3 4 5 6 7 8\n";
cout << " 28 29 30 31 32 33 34 9\n";
cout << " 27 48 49 50 51 52 35 10\n";
cout << " 26 47 60 61 62 53 36 11\n";
cout << " 25 46 59 64 63 54 37 12\n";
cout << " 24 45 58 57 56 55 38 13\n";
cout << " 23 44 43 42 41 40 39 14\n";
cout << " 22 21 20 19 18 17 16 15\n";
}
if (n == 9) {
cout << " 1 2 3 4 5 6 7 8 9\n";
cout << " 32 33 34 35 36 37 38 39 10\n";
cout << " 31 56 57 58 59 60 61 40 11\n";
cout << " 30 55 72 73 74 75 62 41 12\n";
cout << " 29 54 71 80 81 76 63 42 13\n";
cout << " 28 53 70 79 78 77 64 43 14\n";
cout << " 27 52 69 68 67 66 65 44 15\n";
cout << " 26 51 50 49 48 47 46 45 16\n";
cout << " 25 24 23 22 21 20 19 18 17\n";
}
return 0;
}
| 30.257143
| 48
| 0.383853
|
flics04
|
13155166fd496ef370cc43ab6e3115a972db7527
| 52,758
|
cpp
|
C++
|
src/3dstool.cpp
|
dnasdw/3dstool
|
29ca751fef5edc6c865ced64777b4141d43fa433
|
[
"MIT"
] | 281
|
2015-01-01T03:53:15.000Z
|
2022-03-22T11:08:31.000Z
|
src/3dstool.cpp
|
dnasdw/3dstool-circleci
|
878549e5a0b53f84c12d91ead2dff54f606c98e5
|
[
"MIT"
] | 21
|
2016-11-10T02:09:28.000Z
|
2022-01-04T14:52:25.000Z
|
src/3dstool.cpp
|
PMArkive/3dstool
|
29ca751fef5edc6c865ced64777b4141d43fa433
|
[
"MIT"
] | 38
|
2015-03-12T05:56:37.000Z
|
2021-12-29T15:25:01.000Z
|
#include "3dstool.h"
#include "3dscrypt.h"
#include "backwardlz77.h"
#include "banner.h"
#include "code.h"
#include "exefs.h"
#include "huffman.h"
#include "lz77.h"
#include "ncch.h"
#include "ncsd.h"
#include "patch.h"
#include "romfs.h"
#include "runlength.h"
#include "url_manager.h"
#include "yaz0.h"
C3dsTool::SOption C3dsTool::s_Option[] =
{
{ nullptr, 0, USTR("action:") },
{ USTR("extract"), USTR('x'), USTR("extract the target file") },
{ USTR("create"), USTR('c'), USTR("create the target file") },
{ USTR("encrypt"), USTR('e'), USTR("encrypt the target file") },
{ USTR("uncompress"), USTR('u'), USTR("uncompress the target file") },
{ USTR("compress"), USTR('z'), USTR("compress the target file") },
{ USTR("trim"), USTR('r'), USTR("trim the cci file") },
{ USTR("pad"), USTR('p'), USTR("pad the cci file") },
{ USTR("diff"), 0, USTR("create the patch file from the old file and the new file") },
{ USTR("patch"), 0, USTR("apply the patch file to the target file") },
{ USTR("lock"), 0, USTR("modify some function in the code file") },
{ USTR("download"), USTR('d'), USTR("download ext key") },
{ USTR("sample"), 0, USTR("show the samples") },
{ USTR("help"), USTR('h'), USTR("show this help") },
{ nullptr, 0, USTR("\ncommon:") },
{ USTR("type"), USTR('t'), USTR("[[card|cci|3ds]|[exec|cxi]|[data|cfa]|exefs|romfs|banner]\n\t\tthe type of the file, optional") },
{ USTR("file"), USTR('f'), USTR("the target file, required") },
{ USTR("verbose"), USTR('v'), USTR("show the info") },
{ nullptr, 0, USTR(" extract/create:") },
{ nullptr, 0, USTR(" cci/cxi/cfa/exefs:") },
{ USTR("header"), 0, USTR("the header file of the target file") },
{ nullptr, 0, USTR(" create:") },
{ nullptr, 0, USTR(" cxi:") },
{ USTR("not-remove-ext-key"), 0, USTR("not remove ext key") },
{ nullptr, 0, USTR(" cfa:") },
{ USTR("not-encrypt"), 0, USTR("not encrypt, modify the flag only") },
{ USTR("fixed-key"), 0, USTR("AES-CTR encryption using fixedkey") },
{ nullptr, 0, USTR(" extract:") },
{ nullptr, 0, USTR(" cxi/cfa:") },
{ USTR("dev"), 0, USTR("auto encryption for dev") },
{ nullptr, 0, USTR(" encrypt:") },
{ USTR("key"), 0, USTR("the hex string of the key used by the AES-CTR encryption") },
{ USTR("counter"), 0, USTR("the hex string of the counter used by the AES-CTR encryption") },
{ USTR("xor"), 0, USTR("the xor data file used by the xor encryption") },
{ nullptr, 0, USTR(" compress:") },
{ USTR("compress-align"), 0, USTR("[1|4|8|16|32]\n\t\tthe alignment of the compressed filesize, optional") },
{ nullptr, 0, USTR(" uncompress:") },
{ USTR("compress-type"), 0, USTR("[blz|lz(ex)|h4|h8|rl|yaz0]\n\t\tthe type of the compress") },
{ USTR("compress-out"), 0, USTR("the output file of uncompressed or compressed") },
{ nullptr, 0, USTR(" yaz0:") },
{ USTR("yaz0-align"), 0, USTR("[0|128|8192]\n\t\tthe alignment property of the yaz0 compressed file, optional") },
{ nullptr, 0, USTR(" diff:") },
{ USTR("old"), 0, USTR("the old file") },
{ USTR("new"), 0, USTR("the new file") },
{ nullptr, 0, USTR(" patch:") },
{ USTR("patch-file"), 0, USTR("the patch file") },
{ nullptr, 0, USTR(" download:") },
{ USTR("download-begin"), 0, USTR("[0-9A-Fa-f]{1,5}\n\t\tthe begin unique id of download range") },
{ USTR("download-end"), 0, USTR("[0-9A-Fa-f]{1,5}\n\t\tthe end unique id of download range") },
{ nullptr, 0, USTR("\ncci:") },
{ nullptr, 0, USTR(" create:") },
{ USTR("not-pad"), 0, USTR("do not add the pad data") },
{ nullptr, 0, USTR(" extract:") },
{ USTR("partition0"), USTR('0'), USTR("the cxi file of the cci file at partition 0") },
{ USTR("partition1"), USTR('1'), USTR("the cfa file of the cci file at partition 1") },
{ USTR("partition2"), USTR('2'), USTR("the cfa file of the cci file at partition 2") },
{ USTR("partition3"), USTR('3'), USTR("the cfa file of the cci file at partition 3") },
{ USTR("partition4"), USTR('4'), USTR("the cfa file of the cci file at partition 4") },
{ USTR("partition5"), USTR('5'), USTR("the cfa file of the cci file at partition 5") },
{ USTR("partition6"), USTR('6'), USTR("the cfa file of the cci file at partition 6") },
{ USTR("partition7"), USTR('7'), USTR("the cfa file of the cci file at partition 7") },
{ nullptr, 0, USTR(" trim:") },
{ USTR("trim-after-partition"), 0, USTR("[0~7], the index of the last reserve partition, optional") },
{ nullptr, 0, USTR("\ncxi:") },
{ nullptr, 0, USTR(" extract/create:") },
{ USTR("exh"), 0, nullptr },
{ USTR("extendedheader"), 0, USTR("the extendedheader file of the cxi file") },
{ USTR("logo"), 0, nullptr },
{ USTR("logoregion"), 0, USTR("the logoregion file of the cxi file") },
{ USTR("plain"), 0, nullptr },
{ USTR("plainregion"), 0, USTR("the plainregion file of the cxi file") },
{ nullptr, 0, USTR(" cfa:") },
{ nullptr, 0, USTR(" extract/create:") },
{ USTR("exefs"), 0, USTR("the exefs file of the cxi/cfa file") },
{ USTR("romfs"), 0, USTR("the romfs file of the cxi/cfa file") },
{ nullptr, 0, USTR("\nexefs:") },
{ nullptr, 0, USTR(" extract/create:") },
{ USTR("exefs-dir"), 0, USTR("the exefs dir for the exefs file") },
{ nullptr, 0, USTR("\nromfs:") },
{ nullptr, 0, USTR(" extract/create:") },
{ USTR("romfs-dir"), 0, USTR("the romfs dir for the romfs file") },
{ nullptr, 0, USTR("\nbanner:") },
{ nullptr, 0, USTR(" extract/create:") },
{ USTR("banner-dir"), 0, USTR("the banner dir for the banner file") },
{ nullptr, 0, USTR("\ncode:") },
{ nullptr, 0, USTR(" lock:") },
{ USTR("region"), 0, USTR("[JPN|USA|EUR|AUS|CHN|KOR|TWN]") },
{ USTR("language"), 0, USTR("[JP|EN|FR|GE|IT|SP|CN|KR|DU|PO|RU|TW]") },
{ nullptr, 0, nullptr }
};
C3dsTool::C3dsTool()
: m_eAction(kActionNone)
, m_eFileType(kFileTypeUnknown)
, m_bVerbose(false)
, m_nEncryptMode(CNcch::kEncryptModeNone)
, m_bRemoveExtKey(true)
, m_bDev(false)
, m_nCompressAlign(1)
, m_eCompressType(kCompressTypeNone)
, m_nYaz0Align(0)
, m_nRegionCode(-1)
, m_nLanguageCode(-1)
, m_nDownloadBegin(-1)
, m_nDownloadEnd(-1)
, m_bNotPad(false)
, m_nLastPartitionIndex(7)
, m_bKeyValid(false)
, m_bCounterValid(false)
, m_bUncompress(false)
, m_bCompress(false)
{
CUrlManager::Initialize();
}
C3dsTool::~C3dsTool()
{
CUrlManager::Finalize();
}
int C3dsTool::ParseOptions(int a_nArgc, UChar* a_pArgv[])
{
if (a_nArgc <= 1)
{
return 1;
}
for (int i = 1; i < a_nArgc; i++)
{
int nArgpc = static_cast<int>(UCslen(a_pArgv[i]));
if (nArgpc == 0)
{
continue;
}
int nIndex = i;
if (a_pArgv[i][0] != USTR('-'))
{
UPrintf(USTR("ERROR: illegal option\n\n"));
return 1;
}
else if (nArgpc > 1 && a_pArgv[i][1] != USTR('-'))
{
for (int j = 1; j < nArgpc; j++)
{
switch (parseOptions(a_pArgv[i][j], nIndex, a_nArgc, a_pArgv))
{
case kParseOptionReturnSuccess:
break;
case kParseOptionReturnIllegalOption:
UPrintf(USTR("ERROR: illegal option\n\n"));
return 1;
case kParseOptionReturnNoArgument:
UPrintf(USTR("ERROR: no argument\n\n"));
return 1;
case kParseOptionReturnUnknownArgument:
UPrintf(USTR("ERROR: unknown argument \"%") PRIUS USTR("\"\n\n"), m_sMessage.c_str());
return 1;
case kParseOptionReturnOptionConflict:
UPrintf(USTR("ERROR: option conflict\n\n"));
return 1;
}
}
}
else if (nArgpc > 2 && a_pArgv[i][1] == USTR('-'))
{
switch (parseOptions(a_pArgv[i] + 2, nIndex, a_nArgc, a_pArgv))
{
case kParseOptionReturnSuccess:
break;
case kParseOptionReturnIllegalOption:
UPrintf(USTR("ERROR: illegal option\n\n"));
return 1;
case kParseOptionReturnNoArgument:
UPrintf(USTR("ERROR: no argument\n\n"));
return 1;
case kParseOptionReturnUnknownArgument:
UPrintf(USTR("ERROR: unknown argument \"%") PRIUS USTR("\"\n\n"), m_sMessage.c_str());
return 1;
case kParseOptionReturnOptionConflict:
UPrintf(USTR("ERROR: option conflict\n\n"));
return 1;
}
}
i = nIndex;
}
return 0;
}
int C3dsTool::CheckOptions()
{
if (m_eAction == kActionNone)
{
UPrintf(USTR("ERROR: nothing to do\n\n"));
return 1;
}
if (m_eAction != kActionDiff && m_eAction != kActionDownload && m_eAction != kActionSample && m_eAction != kActionHelp && m_sFileName.empty())
{
UPrintf(USTR("ERROR: no --file option\n\n"));
return 1;
}
if (m_nEncryptMode == CNcch::kEncryptModeNone)
{
m_nEncryptMode = CNcch::kEncryptModeAuto;
}
if (m_eAction == kActionExtract)
{
if (!checkFileType())
{
UPrintf(USTR("ERROR: %") PRIUS USTR("\n\n"), m_sMessage.c_str());
return 1;
}
switch (m_eFileType)
{
case kFileTypeCci:
if (m_sHeaderFileName.empty())
{
bool bEmpty = true;
for (int i = 0; i < 8; i++)
{
if (!m_mNcchFileName[i].empty())
{
bEmpty = false;
break;
}
}
if (bEmpty)
{
UPrintf(USTR("ERROR: nothing to be extract\n\n"));
return 1;
}
}
break;
case kFileTypeCxi:
if (m_sHeaderFileName.empty() && m_sExtendedHeaderFileName.empty() && m_sLogoRegionFileName.empty() && m_sPlainRegionFileName.empty() && m_sExeFsFileName.empty() && m_sRomFsFileName.empty())
{
UPrintf(USTR("ERROR: nothing to be extract\n\n"));
return 1;
}
if (m_nEncryptMode != CNcch::kEncryptModeAuto)
{
UPrintf(USTR("ERROR: encrypt error\n\n"));
return 1;
}
break;
case kFileTypeCfa:
if (m_sHeaderFileName.empty() && m_sRomFsFileName.empty())
{
UPrintf(USTR("ERROR: nothing to be extract\n\n"));
return 1;
}
if (m_nEncryptMode != CNcch::kEncryptModeAuto)
{
UPrintf(USTR("ERROR: encrypt error\n\n"));
return 1;
}
break;
case kFileTypeExeFs:
if (m_sHeaderFileName.empty() && m_sExeFsDirName.empty())
{
UPrintf(USTR("ERROR: nothing to be extract\n\n"));
return 1;
}
break;
case kFileTypeRomFs:
if (m_sRomFsDirName.empty())
{
UPrintf(USTR("ERROR: no --romfs-dir option\n\n"));
return 1;
}
break;
case kFileTypeBanner:
if (m_sBannerDirName.empty())
{
UPrintf(USTR("ERROR: no --banner-dir option\n\n"));
return 1;
}
break;
default:
break;
}
}
if (m_eAction == kActionCreate)
{
if (m_eFileType == kFileTypeUnknown)
{
UPrintf(USTR("ERROR: no --type option\n\n"));
return 1;
}
else
{
if (m_eFileType == kFileTypeCci || m_eFileType == kFileTypeCxi || m_eFileType == kFileTypeCfa || m_eFileType == kFileTypeExeFs)
{
if (m_sHeaderFileName.empty())
{
UPrintf(USTR("ERROR: no --header option\n\n"));
return 1;
}
}
switch (m_eFileType)
{
case kFileTypeCci:
if (m_mNcchFileName[0].empty())
{
UPrintf(USTR("ERROR: no --partition0 option\n\n"));
return 1;
}
break;
case kFileTypeCxi:
if (m_sExtendedHeaderFileName.empty() || m_sExeFsFileName.empty())
{
UPrintf(USTR("ERROR: no --extendedheader or --exefs option\n\n"));
return 1;
}
if (m_nEncryptMode != CNcch::kEncryptModeNotEncrypt && m_nEncryptMode != CNcch::kEncryptModeFixedKey && m_nEncryptMode != CNcch::kEncryptModeAuto)
{
UPrintf(USTR("ERROR: encrypt error\n\n"));
return 1;
}
break;
case kFileTypeCfa:
if (m_sRomFsFileName.empty())
{
UPrintf(USTR("ERROR: no --romfs option\n\n"));
return 1;
}
if (m_nEncryptMode != CNcch::kEncryptModeNotEncrypt && m_nEncryptMode != CNcch::kEncryptModeFixedKey && m_nEncryptMode != CNcch::kEncryptModeAuto)
{
UPrintf(USTR("ERROR: encrypt error\n\n"));
return 1;
}
break;
case kFileTypeExeFs:
if (m_sExeFsDirName.empty())
{
UPrintf(USTR("ERROR: no --exefs-dir option\n\n"));
return 1;
}
break;
case kFileTypeRomFs:
if (m_sRomFsDirName.empty())
{
UPrintf(USTR("ERROR: no --romfs-dir option\n\n"));
return 1;
}
break;
case kFileTypeBanner:
if (m_sBannerDirName.empty())
{
UPrintf(USTR("ERROR: no --banner-dir option\n\n"));
return 1;
}
break;
default:
break;
}
}
}
if (m_eAction == kActionEncrypt)
{
if (m_nEncryptMode == CNcch::kEncryptModeAesCtr)
{
if (!m_bKeyValid)
{
UPrintf(USTR("ERROR: no --key option\n\n"));
return 1;
}
if (!m_bCounterValid)
{
UPrintf(USTR("ERROR: no --counter option\n\n"));
return 1;
}
}
else if (m_nEncryptMode == CNcch::kEncryptModeXor)
{
if (m_sXorFileName.empty())
{
UPrintf(USTR("ERROR: no --xor option\n\n"));
return 1;
}
}
}
if (m_eAction == kActionUncompress || m_eAction == kActionCompress)
{
if (m_eCompressType == kCompressTypeNone)
{
UPrintf(USTR("ERROR: no --compress-type option\n\n"));
return 1;
}
if (m_sCompressOutFileName.empty())
{
m_sCompressOutFileName = m_sFileName;
}
}
if (m_eAction == kActionTrim || m_eAction == kActionPad)
{
if (!CNcsd::IsNcsdFile(m_sFileName))
{
UPrintf(USTR("ERROR: %") PRIUS USTR(" is not a ncsd file\n\n"), m_sFileName.c_str());
return 1;
}
else if (m_eFileType != kFileTypeUnknown && m_eFileType != kFileTypeCci && m_bVerbose)
{
UPrintf(USTR("INFO: ignore --type option\n"));
}
}
if (m_eAction == kActionDiff)
{
if (m_sOldFileName.empty())
{
UPrintf(USTR("ERROR: no --old option\n\n"));
return 1;
}
if (m_sNewFileName.empty())
{
UPrintf(USTR("ERROR: no --new option\n\n"));
return 1;
}
if (m_sPatchFileName.empty())
{
UPrintf(USTR("ERROR: no --patch-file option\n\n"));
return 1;
}
}
if (m_eAction == kActionPatch)
{
if (m_sPatchFileName.empty())
{
UPrintf(USTR("ERROR: no --patch-file option\n\n"));
return 1;
}
}
if (m_eAction == kActionLock)
{
if (m_nRegionCode < 0 && m_nLanguageCode < 0)
{
UPrintf(USTR("ERROR: no --region or --language option\n\n"));
return 1;
}
}
if (m_eAction == kActionDownload)
{
if (m_nDownloadBegin < 0 && m_nDownloadEnd < 0)
{
UPrintf(USTR("ERROR: no --download-begin or --download-end option\n\n"));
return 1;
}
}
return 0;
}
int C3dsTool::Help()
{
UPrintf(USTR("3dstool %") PRIUS USTR(" by dnasdw\n\n"), AToU(_3DSTOOL_VERSION).c_str());
UPrintf(USTR("usage: 3dstool [option...] [option]...\n\n"));
UPrintf(USTR("option:\n"));
SOption* pOption = s_Option;
while (pOption->Name != nullptr || pOption->Doc != nullptr)
{
if (pOption->Name != nullptr)
{
UPrintf(USTR(" "));
if (pOption->Key != 0)
{
UPrintf(USTR("-%c,"), pOption->Key);
}
else
{
UPrintf(USTR(" "));
}
UPrintf(USTR(" --%-8") PRIUS, pOption->Name);
if (UCslen(pOption->Name) >= 8 && pOption->Doc != nullptr)
{
UPrintf(USTR("\n%16") PRIUS, USTR(""));
}
}
if (pOption->Doc != nullptr)
{
UPrintf(USTR("%") PRIUS, pOption->Doc);
}
UPrintf(USTR("\n"));
pOption++;
}
return 0;
}
int C3dsTool::Action()
{
if (m_eAction == kActionExtract)
{
if (!extractFile())
{
UPrintf(USTR("ERROR: extract file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionCreate)
{
if (!createFile())
{
UPrintf(USTR("ERROR: create file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionEncrypt)
{
if (!encryptFile())
{
UPrintf(USTR("ERROR: encrypt file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionUncompress)
{
if (!uncompressFile())
{
UPrintf(USTR("ERROR: uncompress file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionCompress)
{
if (!compressFile())
{
UPrintf(USTR("ERROR: compress file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionTrim)
{
if (!trimFile())
{
UPrintf(USTR("ERROR: trim file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionPad)
{
if (!padFile())
{
UPrintf(USTR("ERROR: pad file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionDiff)
{
if (!diffFile())
{
UPrintf(USTR("ERROR: create patch file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionPatch)
{
if (!patchFile())
{
UPrintf(USTR("ERROR: apply patch file failed\n\n"));
return 1;
}
}
if (m_eAction == kActionLock)
{
if (!lock())
{
UPrintf(USTR("ERROR: modify function failed\n\n"));
return 1;
}
}
if (m_eAction == kActionDownload)
{
if (!download())
{
UPrintf(USTR("ERROR: download failed\n\n"));
return 1;
}
}
if (m_eAction == kActionSample)
{
return sample();
}
if (m_eAction == kActionHelp)
{
return Help();
}
return 0;
}
C3dsTool::EParseOptionReturn C3dsTool::parseOptions(const UChar* a_pName, int& a_nIndex, int a_nArgc, UChar* a_pArgv[])
{
if (UCscmp(a_pName, USTR("extract")) == 0)
{
if (m_eAction == kActionNone || m_eAction == kActionUncompress)
{
m_eAction = kActionExtract;
}
else if (m_eAction != kActionExtract && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("create")) == 0)
{
if (m_eAction == kActionNone || m_eAction == kActionCompress)
{
m_eAction = kActionCreate;
}
else if (m_eAction != kActionCreate && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("encrypt")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionEncrypt;
}
else if (m_eAction != kActionEncrypt && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("uncompress")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionUncompress;
}
else if (m_eAction != kActionExtract && m_eAction != kActionUncompress && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
m_bUncompress = true;
}
else if (UCscmp(a_pName, USTR("compress")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionCompress;
}
else if (m_eAction != kActionCreate && m_eAction != kActionCompress && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
m_bCompress = true;
}
else if (UCscmp(a_pName, USTR("trim")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionTrim;
}
else if (m_eAction != kActionTrim && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("pad")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionPad;
}
else if (m_eAction != kActionPad && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("diff")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionDiff;
}
else if (m_eAction != kActionDiff && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("patch")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionPatch;
}
else if (m_eAction != kActionPatch && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("lock")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionLock;
}
else if (m_eAction != kActionLock && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("download")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionDownload;
}
else if (m_eAction != kActionDownload && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("sample")) == 0)
{
if (m_eAction == kActionNone)
{
m_eAction = kActionSample;
}
else if (m_eAction != kActionSample && m_eAction != kActionHelp)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("help")) == 0)
{
m_eAction = kActionHelp;
}
else if (UCscmp(a_pName, USTR("type")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
UChar* pType = a_pArgv[++a_nIndex];
if (UCscmp(pType, USTR("card")) == 0 || UCscmp(pType, USTR("cci")) == 0 || UCscmp(pType, USTR("3ds")) == 0)
{
m_eFileType = kFileTypeCci;
}
else if (UCscmp(pType, USTR("exec")) == 0 || UCscmp(pType, USTR("cxi")) == 0)
{
m_eFileType = kFileTypeCxi;
}
else if (UCscmp(pType, USTR("data")) == 0 || UCscmp(pType, USTR("cfa")) == 0)
{
m_eFileType = kFileTypeCfa;
}
else if (UCscmp(pType, USTR("exefs")) == 0)
{
m_eFileType = kFileTypeExeFs;
}
else if (UCscmp(pType, USTR("romfs")) == 0)
{
m_eFileType = kFileTypeRomFs;
}
else if (UCscmp(pType, USTR("banner")) == 0)
{
m_eFileType = kFileTypeBanner;
}
else
{
m_sMessage = pType;
return kParseOptionReturnUnknownArgument;
}
}
else if (UCscmp(a_pName, USTR("file")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("verbose")) == 0)
{
m_bVerbose = true;
}
else if (UCscmp(a_pName, USTR("header")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sHeaderFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("not-remove-ext-key")) == 0)
{
if (m_nEncryptMode == CNcch::kEncryptModeNone)
{
m_nEncryptMode = CNcch::kEncryptModeAuto;
}
else if (m_nEncryptMode != CNcch::kEncryptModeAuto)
{
return kParseOptionReturnOptionConflict;
}
m_bRemoveExtKey = false;
}
else if (UCscmp(a_pName, USTR("not-encrypt")) == 0)
{
if (m_nEncryptMode == CNcch::kEncryptModeNone)
{
m_nEncryptMode = CNcch::kEncryptModeNotEncrypt;
}
else if (m_nEncryptMode != CNcch::kEncryptModeNotEncrypt)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("fixed-key")) == 0)
{
if (m_nEncryptMode == CNcch::kEncryptModeNone)
{
m_nEncryptMode = CNcch::kEncryptModeFixedKey;
}
else if (m_nEncryptMode != CNcch::kEncryptModeFixedKey)
{
return kParseOptionReturnOptionConflict;
}
}
else if (UCscmp(a_pName, USTR("dev")) == 0)
{
if (m_nEncryptMode == CNcch::kEncryptModeNone)
{
m_nEncryptMode = CNcch::kEncryptModeAuto;
}
else if (m_nEncryptMode != CNcch::kEncryptModeAuto)
{
return kParseOptionReturnOptionConflict;
}
m_bDev = true;
}
else if (UCscmp(a_pName, USTR("key")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
if (m_nEncryptMode == CNcch::kEncryptModeNone)
{
m_nEncryptMode = CNcch::kEncryptModeAesCtr;
}
else if (m_nEncryptMode != CNcch::kEncryptModeAesCtr)
{
return kParseOptionReturnOptionConflict;
}
UString sKey = a_pArgv[++a_nIndex];
if (sKey.size() != 32 || sKey.find_first_not_of(USTR("0123456789ABCDEFabcdef")) != UString::npos)
{
m_sMessage = sKey;
return kParseOptionReturnUnknownArgument;
}
m_Key = UToA(sKey).c_str();
m_bKeyValid = true;
}
else if (UCscmp(a_pName, USTR("counter")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
if (m_nEncryptMode == CNcch::kEncryptModeNone)
{
m_nEncryptMode = CNcch::kEncryptModeAesCtr;
}
else if (m_nEncryptMode != CNcch::kEncryptModeAesCtr)
{
return kParseOptionReturnOptionConflict;
}
UString sCounter = a_pArgv[++a_nIndex];
if (sCounter.size() != 32 || sCounter.find_first_not_of(USTR("0123456789ABCDEFabcdef")) != UString::npos)
{
m_sMessage = sCounter;
return kParseOptionReturnUnknownArgument;
}
m_Counter = UToA(sCounter).c_str();
m_bCounterValid = true;
}
else if (UCscmp(a_pName, USTR("xor")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
if (m_nEncryptMode == CNcch::kEncryptModeNone)
{
m_nEncryptMode = CNcch::kEncryptModeXor;
}
else if (m_nEncryptMode != CNcch::kEncryptModeXor)
{
return kParseOptionReturnOptionConflict;
}
m_sXorFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("compress-align")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
UString sCompressAlign = a_pArgv[++a_nIndex];
n32 nCompressAlign = SToN32(sCompressAlign);
if (nCompressAlign != 1 && nCompressAlign != 4 && nCompressAlign != 8 && nCompressAlign != 16 && nCompressAlign != 32)
{
m_sMessage = sCompressAlign;
return kParseOptionReturnUnknownArgument;
}
m_nCompressAlign = nCompressAlign;
}
else if (UCscmp(a_pName, USTR("compress-type")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
UChar* pType = a_pArgv[++a_nIndex];
if (UCscmp(pType, USTR("blz")) == 0)
{
m_eCompressType = kCompressTypeBlz;
}
else if (UCscmp(pType, USTR("lz")) == 0)
{
m_eCompressType = kCompressTypeLz;
}
else if (UCscmp(pType, USTR("lzex")) == 0)
{
m_eCompressType = kCompressTypeLzEx;
}
else if (UCscmp(pType, USTR("h4")) == 0)
{
m_eCompressType = kCompressTypeH4;
}
else if (UCscmp(pType, USTR("h8")) == 0)
{
m_eCompressType = kCompressTypeH8;
}
else if (UCscmp(pType, USTR("rl")) == 0)
{
m_eCompressType = kCompressTypeRl;
}
else if (UCscmp(pType, USTR("yaz0")) == 0)
{
m_eCompressType = kCompressTypeYaz0;
}
else
{
m_sMessage = pType;
return kParseOptionReturnUnknownArgument;
}
}
else if (UCscmp(a_pName, USTR("compress-out")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sCompressOutFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("yaz0-align")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
UString sYaz0Align = a_pArgv[++a_nIndex];
n32 nYaz0Align = SToN32(sYaz0Align);
if (nYaz0Align != 0 && nYaz0Align != 128 && nYaz0Align != 8192)
{
m_sMessage = sYaz0Align;
return kParseOptionReturnUnknownArgument;
}
m_nYaz0Align = nYaz0Align;
}
else if (UCscmp(a_pName, USTR("old")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sOldFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("new")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sNewFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("patch-file")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sPatchFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("download-begin")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
UString sDownloadBegin = a_pArgv[++a_nIndex];
static URegex uniqueId(USTR("[0-9A-Fa-f]{1,5}"), regex_constants::ECMAScript | regex_constants::icase);
if (!regex_match(sDownloadBegin, uniqueId))
{
m_sMessage = sDownloadBegin;
return kParseOptionReturnUnknownArgument;
}
m_nDownloadBegin = SToN32(sDownloadBegin, 16);
}
else if (UCscmp(a_pName, USTR("download-end")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
UString sDownloadEnd = a_pArgv[++a_nIndex];
static URegex uniqueId(USTR("[0-9A-Fa-f]{1,5}"), regex_constants::ECMAScript | regex_constants::icase);
if (!regex_match(sDownloadEnd, uniqueId))
{
m_sMessage = sDownloadEnd;
return kParseOptionReturnUnknownArgument;
}
m_nDownloadEnd = SToN32(sDownloadEnd, 16);
}
else if (StartWith<UString>(a_pName, USTR("partition")))
{
int nIndex = SToN32(a_pName + UCslen(USTR("partition")));
if (nIndex < 0 || nIndex >= 8)
{
return kParseOptionReturnIllegalOption;
}
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_mNcchFileName[nIndex] = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("not-pad")) == 0)
{
m_bNotPad = true;
}
else if (UCscmp(a_pName, USTR("trim-after-partition")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_nLastPartitionIndex = SToN32(a_pArgv[++a_nIndex]);
if (m_nLastPartitionIndex < 0 || m_nLastPartitionIndex >= 8)
{
return kParseOptionReturnIllegalOption;
}
}
else if (UCscmp(a_pName, USTR("extendedheader")) == 0 || UCscmp(a_pName, USTR("exh")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sExtendedHeaderFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("logoregion")) == 0 || UCscmp(a_pName, USTR("logo")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sLogoRegionFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("plainregion")) == 0 || UCscmp(a_pName, USTR("plain")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sPlainRegionFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("exefs")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sExeFsFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("romfs")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sRomFsFileName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("exefs-dir")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sExeFsDirName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("romfs-dir")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sRomFsDirName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("banner-dir")) == 0)
{
if (a_nIndex + 1 > a_nArgc)
{
return kParseOptionReturnNoArgument;
}
m_sBannerDirName = a_pArgv[++a_nIndex];
}
else if (UCscmp(a_pName, USTR("region")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
UChar* pRegion = a_pArgv[++a_nIndex];
if (UCscmp(pRegion, USTR("JPN")) == 0)
{
m_nRegionCode = 0;
}
else if (UCscmp(pRegion, USTR("USA")) == 0)
{
m_nRegionCode = 1;
}
else if (UCscmp(pRegion, USTR("EUR")) == 0)
{
m_nRegionCode = 2;
}
else if (UCscmp(pRegion, USTR("AUS")) == 0)
{
m_nRegionCode = 3;
}
else if (UCscmp(pRegion, USTR("CHN")) == 0)
{
m_nRegionCode = 4;
}
else if (UCscmp(pRegion, USTR("KOR")) == 0)
{
m_nRegionCode = 5;
}
else if (UCscmp(pRegion, USTR("TWN")) == 0)
{
m_nRegionCode = 6;
}
else
{
m_sMessage = pRegion;
return kParseOptionReturnUnknownArgument;
}
}
else if (UCscmp(a_pName, USTR("language")) == 0)
{
if (a_nIndex + 1 >= a_nArgc)
{
return kParseOptionReturnNoArgument;
}
UChar* pLanguage = a_pArgv[++a_nIndex];
if (UCscmp(pLanguage, USTR("JP")) == 0)
{
m_nLanguageCode = 0;
}
else if (UCscmp(pLanguage, USTR("EN")) == 0)
{
m_nLanguageCode = 1;
}
else if (UCscmp(pLanguage, USTR("FR")) == 0)
{
m_nLanguageCode = 2;
}
else if (UCscmp(pLanguage, USTR("GE")) == 0)
{
m_nLanguageCode = 3;
}
else if (UCscmp(pLanguage, USTR("IT")) == 0)
{
m_nLanguageCode = 4;
}
else if (UCscmp(pLanguage, USTR("SP")) == 0)
{
m_nLanguageCode = 5;
}
else if (UCscmp(pLanguage, USTR("CN")) == 0)
{
m_nLanguageCode = 6;
}
else if (UCscmp(pLanguage, USTR("KR")) == 0)
{
m_nLanguageCode = 7;
}
else if (UCscmp(pLanguage, USTR("DU")) == 0)
{
m_nLanguageCode = 8;
}
else if (UCscmp(pLanguage, USTR("PO")) == 0)
{
m_nLanguageCode = 9;
}
else if (UCscmp(pLanguage, USTR("RU")) == 0)
{
m_nLanguageCode = 10;
}
else if (UCscmp(pLanguage, USTR("TW")) == 0)
{
m_nLanguageCode = 11;
}
else
{
m_sMessage = pLanguage;
return kParseOptionReturnUnknownArgument;
}
}
return kParseOptionReturnSuccess;
}
C3dsTool::EParseOptionReturn C3dsTool::parseOptions(int a_nKey, int& a_nIndex, int a_nArgc, UChar* a_pArgv[])
{
for (SOption* pOption = s_Option; pOption->Name != nullptr || pOption->Key != 0 || pOption->Doc != nullptr; pOption++)
{
if (pOption->Key == a_nKey)
{
return parseOptions(pOption->Name, a_nIndex, a_nArgc, a_pArgv);
}
}
return kParseOptionReturnIllegalOption;
}
bool C3dsTool::checkFileType()
{
if (m_eFileType == kFileTypeUnknown)
{
if (CNcsd::IsNcsdFile(m_sFileName))
{
m_eFileType = kFileTypeCci;
}
else if (CNcch::IsCxiFile(m_sFileName))
{
m_eFileType = kFileTypeCxi;
}
else if (CNcch::IsCfaFile(m_sFileName))
{
m_eFileType = kFileTypeCfa;
}
else if (CExeFs::IsExeFsFile(m_sFileName, 0))
{
m_eFileType = kFileTypeExeFs;
}
else if (CRomFs::IsRomFsFile(m_sFileName))
{
m_eFileType = kFileTypeRomFs;
}
else if (CBanner::IsBannerFile(m_sFileName))
{
m_eFileType = kFileTypeBanner;
}
else
{
m_sMessage = USTR("unknown file type");
return false;
}
}
else
{
bool bMatch = false;
switch (m_eFileType)
{
case kFileTypeCci:
bMatch = CNcsd::IsNcsdFile(m_sFileName);
break;
case kFileTypeCxi:
bMatch = CNcch::IsCxiFile(m_sFileName);
break;
case kFileTypeCfa:
bMatch = CNcch::IsCfaFile(m_sFileName);
break;
case kFileTypeExeFs:
bMatch = CExeFs::IsExeFsFile(m_sFileName, 0);
break;
case kFileTypeRomFs:
bMatch = CRomFs::IsRomFsFile(m_sFileName);
break;
case kFileTypeBanner:
bMatch = CBanner::IsBannerFile(m_sFileName);
break;
default:
break;
}
if (!bMatch)
{
m_sMessage = USTR("the file type is mismatch");
return false;
}
}
return true;
}
bool C3dsTool::extractFile()
{
bool bResult = false;
switch (m_eFileType)
{
case kFileTypeCci:
{
CNcsd ncsd;
ncsd.SetFileName(m_sFileName);
ncsd.SetVerbose(m_bVerbose);
ncsd.SetHeaderFileName(m_sHeaderFileName);
ncsd.SetNcchFileName(m_mNcchFileName);
bResult = ncsd.ExtractFile();
}
break;
case kFileTypeCxi:
{
CNcch ncch;
ncch.SetFileName(m_sFileName);
ncch.SetVerbose(m_bVerbose);
ncch.SetHeaderFileName(m_sHeaderFileName);
ncch.SetEncryptMode(m_nEncryptMode);
ncch.SetDev(m_bDev);
ncch.SetExtendedHeaderFileName(m_sExtendedHeaderFileName);
ncch.SetLogoRegionFileName(m_sLogoRegionFileName);
ncch.SetPlainRegionFileName(m_sPlainRegionFileName);
ncch.SetExeFsFileName(m_sExeFsFileName);
ncch.SetRomFsFileName(m_sRomFsFileName);
bResult = ncch.ExtractFile();
}
break;
case kFileTypeCfa:
{
CNcch ncch;
ncch.SetFileName(m_sFileName);
ncch.SetVerbose(m_bVerbose);
ncch.SetHeaderFileName(m_sHeaderFileName);
ncch.SetEncryptMode(m_nEncryptMode);
ncch.SetDev(m_bDev);
ncch.SetExeFsFileName(m_sExeFsFileName);
ncch.SetRomFsFileName(m_sRomFsFileName);
bResult = ncch.ExtractFile();
}
break;
case kFileTypeExeFs:
{
CExeFs exeFs;
exeFs.SetFileName(m_sFileName);
exeFs.SetVerbose(m_bVerbose);
exeFs.SetHeaderFileName(m_sHeaderFileName);
exeFs.SetExeFsDirName(m_sExeFsDirName);
exeFs.SetUncompress(m_bUncompress);
bResult = exeFs.ExtractFile();
}
break;
case kFileTypeRomFs:
{
CRomFs romFs;
romFs.SetFileName(m_sFileName);
romFs.SetVerbose(m_bVerbose);
romFs.SetRomFsDirName(m_sRomFsDirName);
bResult = romFs.ExtractFile();
}
break;
case kFileTypeBanner:
{
CBanner banner;
banner.SetFileName(m_sFileName);
banner.SetVerbose(m_bVerbose);
banner.SetBannerDirName(m_sBannerDirName);
bResult = banner.ExtractFile();
}
break;
default:
break;
}
return bResult;
}
bool C3dsTool::createFile()
{
bool bResult = false;
switch (m_eFileType)
{
case kFileTypeCci:
{
CNcsd ncsd;
ncsd.SetFileName(m_sFileName);
ncsd.SetVerbose(m_bVerbose);
ncsd.SetHeaderFileName(m_sHeaderFileName);
ncsd.SetNcchFileName(m_mNcchFileName);
ncsd.SetNotPad(m_bNotPad);
bResult = ncsd.CreateFile();
}
break;
case kFileTypeCxi:
{
CNcch ncch;
ncch.SetFileName(m_sFileName);
ncch.SetVerbose(m_bVerbose);
ncch.SetHeaderFileName(m_sHeaderFileName);
ncch.SetEncryptMode(m_nEncryptMode);
ncch.SetRemoveExtKey(m_bRemoveExtKey);
ncch.SetDev(m_bDev);
ncch.SetExtendedHeaderFileName(m_sExtendedHeaderFileName);
ncch.SetLogoRegionFileName(m_sLogoRegionFileName);
ncch.SetPlainRegionFileName(m_sPlainRegionFileName);
ncch.SetExeFsFileName(m_sExeFsFileName);
ncch.SetRomFsFileName(m_sRomFsFileName);
bResult = ncch.CreateFile();
}
break;
case kFileTypeCfa:
{
CNcch ncch;
ncch.SetFileName(m_sFileName);
ncch.SetVerbose(m_bVerbose);
ncch.SetHeaderFileName(m_sHeaderFileName);
ncch.SetEncryptMode(m_nEncryptMode);
ncch.SetRemoveExtKey(false);
ncch.SetDev(m_bDev);
ncch.SetExeFsFileName(m_sExeFsFileName);
ncch.SetRomFsFileName(m_sRomFsFileName);
bResult = ncch.CreateFile();
}
break;
case kFileTypeExeFs:
{
CExeFs exeFs;
exeFs.SetFileName(m_sFileName);
exeFs.SetVerbose(m_bVerbose);
exeFs.SetHeaderFileName(m_sHeaderFileName);
exeFs.SetExeFsDirName(m_sExeFsDirName);
exeFs.SetCompress(m_bCompress);
bResult = exeFs.CreateFile();
}
break;
case kFileTypeRomFs:
{
CRomFs romFs;
romFs.SetFileName(m_sFileName);
romFs.SetVerbose(m_bVerbose);
romFs.SetRomFsDirName(m_sRomFsDirName);
romFs.SetRomFsFileName(m_sRomFsFileName);
bResult = romFs.CreateFile();
}
break;
case kFileTypeBanner:
{
CBanner banner;
banner.SetFileName(m_sFileName);
banner.SetVerbose(m_bVerbose);
banner.SetBannerDirName(m_sBannerDirName);
bResult = banner.CreateFile();
}
break;
default:
break;
}
return bResult;
}
bool C3dsTool::encryptFile()
{
bool bResult = false;
if (m_nEncryptMode == CNcch::kEncryptModeAesCtr)
{
if (m_bKeyValid && m_bCounterValid)
{
bResult = FEncryptAesCtrFile(m_sFileName, m_Key, m_Counter, 0, 0, true, 0);
}
}
else if (m_nEncryptMode == CNcch::kEncryptModeXor)
{
if (!m_sXorFileName.empty())
{
bResult = FEncryptXorFile(m_sFileName, m_sXorFileName);
}
}
return bResult;
}
bool C3dsTool::uncompressFile()
{
FILE* fp = UFopen(m_sFileName.c_str(), USTR("rb"));
bool bResult = fp != nullptr;
if (bResult)
{
Fseek(fp, 0, SEEK_END);
u32 uCompressedSize = static_cast<u32>(Ftell(fp));
Fseek(fp, 0, SEEK_SET);
u8* pCompressed = new u8[uCompressedSize];
fread(pCompressed, 1, uCompressedSize, fp);
fclose(fp);
u32 uUncompressedSize = 0;
switch (m_eCompressType)
{
case kCompressTypeBlz:
bResult = CBackwardLz77::GetUncompressedSize(pCompressed, uCompressedSize, uUncompressedSize);
break;
case kCompressTypeLz:
case kCompressTypeLzEx:
bResult = CLz77::GetUncompressedSize(pCompressed, uCompressedSize, uUncompressedSize);
break;
case kCompressTypeH4:
case kCompressTypeH8:
bResult = CHuffman::GetUncompressedSize(pCompressed, uCompressedSize, uUncompressedSize);
break;
case kCompressTypeRl:
bResult = CRunLength::GetUncompressedSize(pCompressed, uCompressedSize, uUncompressedSize);
break;
case kCompressTypeYaz0:
bResult = CYaz0::GetUncompressedSize(pCompressed, uCompressedSize, uUncompressedSize);
break;
default:
break;
}
if (bResult)
{
u8* pUncompressed = new u8[uUncompressedSize];
switch (m_eCompressType)
{
case kCompressTypeBlz:
bResult = CBackwardLz77::Uncompress(pCompressed, uCompressedSize, pUncompressed, uUncompressedSize);
break;
case kCompressTypeLz:
case kCompressTypeLzEx:
bResult = CLz77::Uncompress(pCompressed, uCompressedSize, pUncompressed, uUncompressedSize);
break;
case kCompressTypeH4:
case kCompressTypeH8:
bResult = CHuffman::Uncompress(pCompressed, uCompressedSize, pUncompressed, uUncompressedSize);
break;
case kCompressTypeRl:
bResult = CRunLength::Uncompress(pCompressed, uCompressedSize, pUncompressed, uUncompressedSize);
break;
case kCompressTypeYaz0:
bResult = CYaz0::Uncompress(pCompressed, uCompressedSize, pUncompressed, uUncompressedSize);
break;
default:
break;
}
if (bResult)
{
fp = UFopen(m_sCompressOutFileName.c_str(), USTR("wb"));
bResult = fp != nullptr;
if (bResult)
{
fwrite(pUncompressed, 1, uUncompressedSize, fp);
fclose(fp);
}
}
else
{
UPrintf(USTR("ERROR: uncompress error\n\n"));
}
delete[] pUncompressed;
}
else
{
UPrintf(USTR("ERROR: get uncompressed size error\n\n"));
}
delete[] pCompressed;
}
return bResult;
}
bool C3dsTool::compressFile()
{
FILE* fp = UFopen(m_sFileName.c_str(), USTR("rb"));
bool bResult = fp != nullptr;
if (bResult)
{
Fseek(fp, 0, SEEK_END);
u32 uUncompressedSize = static_cast<u32>(Ftell(fp));
Fseek(fp, 0, SEEK_SET);
u8* pUncompressed = new u8[uUncompressedSize];
fread(pUncompressed, 1, uUncompressedSize, fp);
fclose(fp);
u32 uCompressedSize = 0;
switch (m_eCompressType)
{
case kCompressTypeBlz:
uCompressedSize = uUncompressedSize;
break;
case kCompressTypeLz:
case kCompressTypeLzEx:
uCompressedSize = CLz77::GetCompressBoundSize(uUncompressedSize, m_nCompressAlign);
break;
case kCompressTypeH4:
case kCompressTypeH8:
uCompressedSize = CHuffman::GetCompressBoundSize(uUncompressedSize, m_nCompressAlign);
break;
case kCompressTypeRl:
uCompressedSize = CRunLength::GetCompressBoundSize(uUncompressedSize, m_nCompressAlign);
break;
case kCompressTypeYaz0:
uCompressedSize = CYaz0::GetCompressBoundSize(uUncompressedSize, m_nCompressAlign);
break;
default:
break;
}
u8* pCompressed = new u8[uCompressedSize];
switch (m_eCompressType)
{
case kCompressTypeBlz:
bResult = CBackwardLz77::Compress(pUncompressed, uUncompressedSize, pCompressed, uCompressedSize);
break;
case kCompressTypeLz:
bResult = CLz77::CompressLz(pUncompressed, uUncompressedSize, pCompressed, uCompressedSize, m_nCompressAlign);
break;
case kCompressTypeLzEx:
bResult = CLz77::CompressLzEx(pUncompressed, uUncompressedSize, pCompressed, uCompressedSize, m_nCompressAlign);
break;
case kCompressTypeH4:
bResult = CHuffman::CompressH4(pUncompressed, uUncompressedSize, pCompressed, uCompressedSize, m_nCompressAlign);
break;
case kCompressTypeH8:
bResult = CHuffman::CompressH8(pUncompressed, uUncompressedSize, pCompressed, uCompressedSize, m_nCompressAlign);
break;
case kCompressTypeRl:
bResult = CRunLength::Compress(pUncompressed, uUncompressedSize, pCompressed, uCompressedSize, m_nCompressAlign);
break;
case kCompressTypeYaz0:
bResult = CYaz0::Compress(pUncompressed, uUncompressedSize, pCompressed, uCompressedSize, m_nCompressAlign, m_nYaz0Align);
break;
default:
break;
}
if (bResult)
{
fp = UFopen(m_sCompressOutFileName.c_str(), USTR("wb"));
bResult = fp != nullptr;
if (bResult)
{
fwrite(pCompressed, 1, uCompressedSize, fp);
fclose(fp);
}
}
else
{
UPrintf(USTR("ERROR: compress error\n\n"));
}
delete[] pCompressed;
delete[] pUncompressed;
}
return bResult;
}
bool C3dsTool::trimFile()
{
CNcsd ncsd;
ncsd.SetFileName(m_sFileName);
ncsd.SetVerbose(m_bVerbose);
ncsd.SetLastPartitionIndex(m_nLastPartitionIndex);
bool bResult = ncsd.TrimFile();
return bResult;
}
bool C3dsTool::padFile()
{
CNcsd ncsd;
ncsd.SetFileName(m_sFileName);
ncsd.SetVerbose(m_bVerbose);
bool bResult = ncsd.PadFile();
return bResult;
}
bool C3dsTool::diffFile()
{
CPatch patch;
patch.SetFileType(m_eFileType);
patch.SetVerbose(m_bVerbose);
patch.SetOldFileName(m_sOldFileName);
patch.SetNewFileName(m_sNewFileName);
patch.SetPatchFileName(m_sPatchFileName);
return patch.CreatePatchFile();
}
bool C3dsTool::patchFile()
{
CPatch patch;
patch.SetFileName(m_sFileName);
patch.SetVerbose(m_bVerbose);
patch.SetPatchFileName(m_sPatchFileName);
return patch.ApplyPatchFile();
}
bool C3dsTool::lock()
{
CCode code;
code.SetFileName(m_sFileName);
code.SetVerbose(m_bVerbose);
code.SetRegionCode(m_nRegionCode);
code.SetLanguageCode(m_nLanguageCode);
return code.Lock();
}
bool C3dsTool::download()
{
if (m_nDownloadBegin > m_nDownloadEnd)
{
n32 nTemp = m_nDownloadBegin;
m_nDownloadBegin = m_nDownloadEnd;
m_nDownloadEnd = nTemp;
}
if (m_nDownloadBegin < 0)
{
m_nDownloadBegin = m_nDownloadEnd;
}
CNcch ncch;
ncch.SetVerbose(m_bVerbose);
ncch.SetDownloadBegin(m_nDownloadBegin);
ncch.SetDownloadEnd(m_nDownloadEnd);
return ncch.Download();
}
int C3dsTool::sample()
{
UPrintf(USTR("sample:\n"));
UPrintf(USTR("# extract cci\n"));
UPrintf(USTR("3dstool -xvt01267f cci 0.cxi 1.cfa 2.cfa 6.cfa 7.cfa input.3ds --header ncsdheader.bin\n\n"));
UPrintf(USTR("# extract cxi with auto encryption for dev\n"));
UPrintf(USTR("3dstool -xvtf cxi 0.cxi --header ncchheader.bin --exh exh.bin --logo logo.darc.lz --plain plain.bin --exefs exefs.bin --romfs romfs.bin --dev\n\n"));
UPrintf(USTR("# extract cxi with auto encryption for retail\n"));
UPrintf(USTR("3dstool -xvtf cxi 0.cxi --header ncchheader.bin --exh exh.bin --logo logo.darc.lz --plain plain.bin --exefs exefs.bin --romfs romfs.bin\n\n"));
UPrintf(USTR("# extract cfa with auto encryption for dev\n"));
UPrintf(USTR("3dstool -xvtf cfa 1.cfa --header ncchheader.bin --romfs romfs.bin --dev\n\n"));
UPrintf(USTR("# extract cfa with auto encryption for retail\n"));
UPrintf(USTR("3dstool -xvtf cfa 1.cfa --header ncchheader.bin --romfs romfs.bin\n\n"));
UPrintf(USTR("# extract exefs without Backward LZ77 uncompress\n"));
UPrintf(USTR("3dstool -xvtf exefs exefs.bin --header exefsheader.bin --exefs-dir exefs\n\n"));
UPrintf(USTR("# extract exefs with Backward LZ77 uncompress\n"));
UPrintf(USTR("3dstool -xuvtf exefs exefs.bin --header exefsheader.bin --exefs-dir exefs\n\n"));
UPrintf(USTR("# extract romfs\n"));
UPrintf(USTR("3dstool -xvtf romfs romfs.bin --romfs-dir romfs\n\n"));
UPrintf(USTR("# extract banner\n"));
UPrintf(USTR("3dstool -xvtf banner banner.bnr --banner-dir banner\n\n"));
UPrintf(USTR("# create cci with pad 0xFF\n"));
UPrintf(USTR("3dstool -cvt01267f cci 0.cxi 1.cfa 2.cfa 6.cfa 7.cfa output.3ds --header ncsdheader.bin\n\n"));
UPrintf(USTR("# create cci without pad\n"));
UPrintf(USTR("3dstool -cvt01267f cci 0.cxi 1.cfa 2.cfa 6.cfa 7.cfa output.3ds --header ncsdheader.bin --not-pad\n\n"));
UPrintf(USTR("# create cxi without encryption\n"));
UPrintf(USTR("3dstool -cvtf cxi 0.cxi --header ncchheader.bin --exh exh.bin --logo logo.darc.lz --plain plain.bin --exefs exefs.bin --romfs romfs.bin --not-encrypt\n\n"));
UPrintf(USTR("# create cxi with AES-CTR encryption using fixedkey\n"));
UPrintf(USTR("3dstool -cvtf cxi 0.cxi --header ncchheader.bin --exh exh.bin --logo logo.darc.lz --plain plain.bin --exefs exefs.bin --romfs romfs.bin --fixed-key\n\n"));
UPrintf(USTR("# create cxi with auto encryption for dev\n"));
UPrintf(USTR("3dstool -cvtf cxi 0.cxi --header ncchheader.bin --exh exh.bin --logo logo.darc.lz --plain plain.bin --exefs exefs.bin --romfs romfs.bin --dev\n\n"));
UPrintf(USTR("# create cxi with auto encryption for retail, not remove ext key\n"));
UPrintf(USTR("3dstool -cvtf cxi 0.cxi --header ncchheader.bin --exh exh.bin --logo logo.darc.lz --plain plain.bin --exefs exefs.bin --romfs romfs.bin --not-remove-ext-key\n\n"));
UPrintf(USTR("# create cxi with auto encryption for retail\n"));
UPrintf(USTR("3dstool -cvtf cxi 0.cxi --header ncchheader.bin --exh exh.bin --logo logo.darc.lz --plain plain.bin --exefs exefs.bin --romfs romfs.bin\n\n"));
UPrintf(USTR("# create cfa without encryption\n"));
UPrintf(USTR("3dstool -cvtf cfa 1.cfa --header ncchheader.bin --romfs romfs.bin --not-encrypt\n\n"));
UPrintf(USTR("# create cfa with AES-CTR encryption using fixedkey\n"));
UPrintf(USTR("3dstool -cvtf cfa 1.cfa --header ncchheader.bin --romfs romfs.bin --fixed-key\n\n"));
UPrintf(USTR("# create cfa with auto encryption for dev\n"));
UPrintf(USTR("3dstool -cvtf cfa 1.cfa --header ncchheader.bin --romfs romfs.bin --dev\n\n"));
UPrintf(USTR("# create cfa with auto encryption for retail\n"));
UPrintf(USTR("3dstool -cvtf cfa 1.cfa --header ncchheader.bin --romfs romfs.bin\n\n"));
UPrintf(USTR("# create exefs without Backward LZ77 compress\n"));
UPrintf(USTR("3dstool -cvtf exefs exefs.bin --header exefsheader.bin --exefs-dir exefs\n\n"));
UPrintf(USTR("# create exefs with Backward LZ77 compress\n"));
UPrintf(USTR("3dstool -czvtf exefs exefs.bin --header exefsheader.bin --exefs-dir exefs\n\n"));
UPrintf(USTR("# create romfs without reference\n"));
UPrintf(USTR("3dstool -cvtf romfs romfs.bin --romfs-dir romfs\n\n"));
UPrintf(USTR("# create romfs with reference\n"));
UPrintf(USTR("3dstool -cvtf romfs romfs.bin --romfs-dir romfs --romfs original_romfs.bin\n\n"));
UPrintf(USTR("# create banner\n"));
UPrintf(USTR("3dstool -cvtf banner banner.bnr --banner-dir banner\n\n"));
UPrintf(USTR("# encrypt file with AES-CTR encryption, standalone\n"));
UPrintf(USTR("3dstool -evf file.bin --key 0123456789ABCDEF0123456789abcdef --counter 0123456789abcdef0123456789ABCDEF\n\n"));
UPrintf(USTR("# encrypt file with xor encryption, standalone\n"));
UPrintf(USTR("3dstool -evf file.bin --xor xor.bin\n\n"));
UPrintf(USTR("# uncompress file with Backward LZ77, standalone\n"));
UPrintf(USTR("3dstool -uvf code.bin --compress-type blz --compress-out code.bin\n\n"));
UPrintf(USTR("# compress file with Backward LZ77, standalone\n"));
UPrintf(USTR("3dstool -zvf code.bin --compress-type blz --compress-out code.bin\n\n"));
UPrintf(USTR("# uncompress file with LZ77, standalone\n"));
UPrintf(USTR("3dstool -uvf input.lz --compress-type lz --compress-out output.bin\n\n"));
UPrintf(USTR("# compress file with LZ77, standalone\n"));
UPrintf(USTR("3dstool -zvf input.bin --compress-type lz --compress-out output.lz\n\n"));
UPrintf(USTR("# compress file with LZ77 and align to 4 bytes, standalone\n"));
UPrintf(USTR("3dstool -zvf input.bin --compress-type lz --compress-out output.lz --compress-align 4\n\n"));
UPrintf(USTR("# uncompress file with LZ77Ex, standalone\n"));
UPrintf(USTR("3dstool -uvf logo.darc.lz --compress-type lzex --compress-out logo.darc\n\n"));
UPrintf(USTR("# compress file with LZ77Ex, standalone\n"));
UPrintf(USTR("3dstool -zvf logo.darc --compress-type lzex --compress-out logo.darc.lz\n\n"));
UPrintf(USTR("# uncompress file with Huffman 4bits, standalone\n"));
UPrintf(USTR("3dstool -uvf input.bin --compress-type h4 --compress-out output.bin\n\n"));
UPrintf(USTR("# compress file with Huffman 4bits, standalone\n"));
UPrintf(USTR("3dstool -zvf input.bin --compress-type h4 --compress-out output.bin\n\n"));
UPrintf(USTR("# uncompress file with Huffman 8bits, standalone\n"));
UPrintf(USTR("3dstool -uvf input.bin --compress-type h8 --compress-out output.bin\n\n"));
UPrintf(USTR("# compress file with Huffman 8bits, standalone\n"));
UPrintf(USTR("3dstool -zvf input.bin --compress-type h8 --compress-out output.bin\n\n"));
UPrintf(USTR("# uncompress file with RunLength, standalone\n"));
UPrintf(USTR("3dstool -uvf input.bin --compress-type rl --compress-out output.bin\n\n"));
UPrintf(USTR("# compress file with RunLength, standalone\n"));
UPrintf(USTR("3dstool -zvf input.bin --compress-type rl --compress-out output.bin\n\n"));
UPrintf(USTR("# uncompress file with Yaz0, standalone\n"));
UPrintf(USTR("3dstool -uvf input.szs --compress-type yaz0 --compress-out output.sarc\n\n"));
UPrintf(USTR("# compress file with Yaz0, standalone\n"));
UPrintf(USTR("3dstool -zvf input.sarc --compress-type yaz0 --compress-out output.szs\n\n"));
UPrintf(USTR("# compress file with Yaz0 and set the alignment property, standalone\n"));
UPrintf(USTR("3dstool -zvf input.sarc --compress-type yaz0 --compress-out output.szs --yaz0-align 128\n\n"));
UPrintf(USTR("# trim cci without pad\n"));
UPrintf(USTR("3dstool --trim -vtf cci input.3ds\n\n"));
UPrintf(USTR("# trim cci reserve partition 0~2\n"));
UPrintf(USTR("3dstool --trim -vtf cci input.3ds --trim-after-partition 2\n\n"));
UPrintf(USTR("# pad cci with 0xFF\n"));
UPrintf(USTR("3dstool --pad -vtf cci input.3ds\n\n"));
UPrintf(USTR("# create patch file without optimization\n"));
UPrintf(USTR("3dstool --diff -v --old old.bin --new new.bin --patch-file patch.3ps\n\n"));
UPrintf(USTR("# create patch file with cci optimization\n"));
UPrintf(USTR("3dstool --diff -vt cci --old old.3ds --new new.3ds --patch-file patch.3ps\n\n"));
UPrintf(USTR("# create patch file with cxi optimization\n"));
UPrintf(USTR("3dstool --diff -vt cxi --old old.cxi --new new.cxi --patch-file patch.3ps\n\n"));
UPrintf(USTR("# create patch file with cfa optimization\n"));
UPrintf(USTR("3dstool --diff -vt cfa --old old.cfa --new new.cfa --patch-file patch.3ps\n\n"));
UPrintf(USTR("# apply patch file\n"));
UPrintf(USTR("3dstool --patch -vf input.bin --patch-file patch.3ps\n\n"));
UPrintf(USTR("# lock region JPN and lock language JP\n"));
UPrintf(USTR("3dstool --lock -vf code.bin --region JPN --language JP\n\n"));
UPrintf(USTR("# download ext key\n"));
UPrintf(USTR("3dstool -dv --download-begin 00000 --download-end 02FFF\n\n"));
return 0;
}
int UMain(int argc, UChar* argv[])
{
C3dsTool tool;
if (tool.ParseOptions(argc, argv) != 0)
{
return tool.Help();
}
if (tool.CheckOptions() != 0)
{
return 1;
}
return tool.Action();
}
| 28.318841
| 193
| 0.668335
|
dnasdw
|
1316383c5bd61321c42690abd0d076610a9dc2aa
| 151
|
cpp
|
C++
|
2739.cpp
|
devlphj/BaekjoonOJ
|
ecf715ece2a81bb69aa2e2b045e53acec01d3736
|
[
"MIT"
] | null | null | null |
2739.cpp
|
devlphj/BaekjoonOJ
|
ecf715ece2a81bb69aa2e2b045e53acec01d3736
|
[
"MIT"
] | null | null | null |
2739.cpp
|
devlphj/BaekjoonOJ
|
ecf715ece2a81bb69aa2e2b045e53acec01d3736
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
int N; cin >> N;
for(int i=1; i<=9; i++)
cout << N << " * " << i << " = " << N*i << endl;
}
| 16.777778
| 50
| 0.463576
|
devlphj
|
1317396c49bcc72492e971e9540e11a806b4fbe6
| 406
|
hpp
|
C++
|
Giga_v1/src/ui/KDUIUnitCommunication.hpp
|
azarashi2931/Giga-Project
|
2acbd937bec01e6042453fe777f4182b6d67d9b7
|
[
"MIT"
] | null | null | null |
Giga_v1/src/ui/KDUIUnitCommunication.hpp
|
azarashi2931/Giga-Project
|
2acbd937bec01e6042453fe777f4182b6d67d9b7
|
[
"MIT"
] | null | null | null |
Giga_v1/src/ui/KDUIUnitCommunication.hpp
|
azarashi2931/Giga-Project
|
2acbd937bec01e6042453fe777f4182b6d67d9b7
|
[
"MIT"
] | null | null | null |
#ifndef KD_UI_UNIT_COMMUNICATION_h
#define KD_UI_UNIT_COMMUNICATION_h
class KDUIUnitCommunication
{
public:
KDUIUnitCommunication(HardwareSerial *serialInstance) : _serialInstance(serialInstance) {}
void init();
void reset();
int read();
void printValue();
private:
HardwareSerial *_serialInstance;
int value = 0;
static constexpr char HederCharacter = 'S';
};
#endif
| 21.368421
| 94
| 0.729064
|
azarashi2931
|
1317f90e28428d14ce6522fac3da086d5bec7b55
| 3,402
|
cpp
|
C++
|
sources/modules/levelset/SpatialDerivative/UpwindFirst/UpwindFirstWENO5.cpp
|
mdoshi96/beacls
|
860426ed1336d9539dea195987efcdd8a8276a1c
|
[
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 30
|
2017-12-17T22:57:50.000Z
|
2022-01-30T17:06:34.000Z
|
sources/modules/levelset/SpatialDerivative/UpwindFirst/UpwindFirstWENO5.cpp
|
codingblazes/beacls
|
6c1d685ee00e3b39d8100c4a170a850682679abc
|
[
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 2
|
2017-03-24T06:18:16.000Z
|
2017-04-04T16:16:06.000Z
|
sources/modules/levelset/SpatialDerivative/UpwindFirst/UpwindFirstWENO5.cpp
|
codingblazes/beacls
|
6c1d685ee00e3b39d8100c4a170a850682679abc
|
[
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 8
|
2018-07-06T01:47:21.000Z
|
2021-07-23T15:50:34.000Z
|
#include <vector>
#include <cstdint>
#include <cmath>
#include <typeinfo>
#include <levelset/SpatialDerivative/UpwindFirst/UpwindFirstWENO5.hpp>
#include <levelset/SpatialDerivative/UpwindFirst/UpwindFirstWENO5a.hpp>
#include "UpwindFirstWENO5_impl.hpp"
using namespace levelset;
UpwindFirstWENO5_impl::UpwindFirstWENO5_impl(
const HJI_Grid *hji_grid,
const beacls::UVecType type
) :
type(type)
{
upwindFirstWENO5a = new UpwindFirstWENO5a(hji_grid, type);
}
UpwindFirstWENO5_impl::~UpwindFirstWENO5_impl() {
if (upwindFirstWENO5a) delete upwindFirstWENO5a;
}
UpwindFirstWENO5_impl::UpwindFirstWENO5_impl(const UpwindFirstWENO5_impl& rhs) :
type(rhs.type),
upwindFirstWENO5a(rhs.upwindFirstWENO5a->clone())
{}
bool UpwindFirstWENO5_impl::operator==(const UpwindFirstWENO5_impl& rhs) const {
if (this == &rhs) return true;
else if (type != rhs.type) return false;
else if (!upwindFirstWENO5a->operator==(*rhs.upwindFirstWENO5a)) return false;
else if ((upwindFirstWENO5a != rhs.upwindFirstWENO5a) && (!upwindFirstWENO5a || !rhs.upwindFirstWENO5a || !upwindFirstWENO5a->operator==(*rhs.upwindFirstWENO5a))) return false;
else return true;
}
bool UpwindFirstWENO5_impl::execute(
beacls::UVec& dst_deriv_l,
beacls::UVec& dst_deriv_r,
const HJI_Grid *grid,
const FLOAT_TYPE* src,
const size_t dim,
const bool generateAll,
const size_t loop_begin,
const size_t slice_length,
const size_t num_of_slices
) {
if (upwindFirstWENO5a) return upwindFirstWENO5a->execute(dst_deriv_l, dst_deriv_r, grid, src, dim, generateAll, loop_begin, slice_length, num_of_slices);
else return false;
}
UpwindFirstWENO5::UpwindFirstWENO5(
const HJI_Grid *hji_grid,
const beacls::UVecType type
) {
pimpl = new UpwindFirstWENO5_impl(hji_grid,type);
}
UpwindFirstWENO5::~UpwindFirstWENO5() {
if (pimpl) delete pimpl;
}
bool UpwindFirstWENO5::execute(
beacls::UVec& dst_deriv_l,
beacls::UVec& dst_deriv_r,
const HJI_Grid *grid,
const FLOAT_TYPE* src,
const size_t dim,
const bool generateAll,
const size_t loop_begin,
const size_t slice_length,
const size_t num_of_slices
) {
if (pimpl) return pimpl->execute(dst_deriv_l, dst_deriv_r, grid, src, dim, generateAll, loop_begin, slice_length, num_of_slices);
else return false;
}
bool UpwindFirstWENO5_impl::synchronize(const size_t dim) {
if (upwindFirstWENO5a) return upwindFirstWENO5a->synchronize(dim);
return false;
}
bool UpwindFirstWENO5::synchronize(const size_t dim) {
if (pimpl) return pimpl->synchronize(dim);
else return false;
}
bool UpwindFirstWENO5::operator==(const UpwindFirstWENO5& rhs) const {
if (this == &rhs) return true;
else if (!pimpl) {
if (!rhs.pimpl) return true;
else return false;
}
else {
if (!rhs.pimpl) return false;
else {
if (pimpl == rhs.pimpl) return true;
else if (*pimpl == *rhs.pimpl) return true;
else return false;
}
}
}
bool UpwindFirstWENO5::operator==(const SpatialDerivative& rhs) const {
if (this == &rhs) return true;
else if (typeid(*this) != typeid(rhs)) return false;
else return operator==(dynamic_cast<const UpwindFirstWENO5&>(rhs));
}
UpwindFirstWENO5::UpwindFirstWENO5(const UpwindFirstWENO5& rhs) :
pimpl(rhs.pimpl->clone())
{
}
UpwindFirstWENO5* UpwindFirstWENO5::clone() const {
return new UpwindFirstWENO5(*this);
}
beacls::UVecType UpwindFirstWENO5::get_type() const {
if (pimpl) return pimpl->get_type();
else return beacls::UVecType_Invalid;
};
| 29.842105
| 177
| 0.762787
|
mdoshi96
|
131d1ed752dbfa1f44199ace6533d5b45b7b9af1
| 929
|
hpp
|
C++
|
include/ashespp/Enum/DescriptorPoolCreateFlags.hpp
|
DragonJoker/Ashes
|
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
|
[
"MIT"
] | 227
|
2018-09-17T16:03:35.000Z
|
2022-03-19T02:02:45.000Z
|
include/ashespp/Enum/DescriptorPoolCreateFlags.hpp
|
DragonJoker/RendererLib
|
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
|
[
"MIT"
] | 39
|
2018-02-06T22:22:24.000Z
|
2018-08-29T07:11:06.000Z
|
include/ashespp/Enum/DescriptorPoolCreateFlags.hpp
|
DragonJoker/Ashes
|
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
|
[
"MIT"
] | 8
|
2019-05-04T10:33:32.000Z
|
2021-04-05T13:19:27.000Z
|
/*
This file belongs to Ashes.
See LICENSE file in root folder.
*/
#ifndef ___AshesPP_DescriptorPoolCreateFlags_HPP___
#define ___AshesPP_DescriptorPoolCreateFlags_HPP___
#pragma once
namespace ashes
{
/**
*\brief
* Gets the name of the given element type.
*\param[in] value
* The element type.
*\return
* The name.
*/
inline std::string getName( VkDescriptorPoolCreateFlagBits value )
{
switch ( value )
{
case VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT:
return "free_descriptor_set";
#if defined( VK_API_VERSION_1_2 )
case VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT:
return "update_after_bind";
#elif defined( VK_EXT_descriptor_indexing )
case VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT:
return "update_after_bind";
#endif
default:
assert( false && "Unsupported VkDescriptorPoolCreateFlagBits." );
return "Unsupported VkDescriptorPoolCreateFlagBits";
}
}
}
#endif
| 23.225
| 68
| 0.779333
|
DragonJoker
|
131f72a4fbffcc6341dff9bbeec5b34a62484d5a
| 751
|
cpp
|
C++
|
Almond/src/Platform/OpenGL/OpenGLContext.cpp
|
joshrudesill/Almond
|
aab1e74eb5f85b9e06d5159ff3d429b728f7ac5e
|
[
"Apache-2.0"
] | null | null | null |
Almond/src/Platform/OpenGL/OpenGLContext.cpp
|
joshrudesill/Almond
|
aab1e74eb5f85b9e06d5159ff3d429b728f7ac5e
|
[
"Apache-2.0"
] | null | null | null |
Almond/src/Platform/OpenGL/OpenGLContext.cpp
|
joshrudesill/Almond
|
aab1e74eb5f85b9e06d5159ff3d429b728f7ac5e
|
[
"Apache-2.0"
] | null | null | null |
#include "hzpch.h"
#include "OpenGLContext.h"
#include <GLFW/glfw3.h>
#include "glad/glad.h"
namespace Almond {
OpenGLContext::OpenGLContext(GLFWwindow* windowHandle)
:m_WindowHandle(windowHandle)
{
AL_CORE_ASSERT(windowHandle, "Handle is null.");
}
void OpenGLContext::init()
{
glfwMakeContextCurrent(m_WindowHandle);
int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
AL_CORE_ASSERT(status, "Failed to initialize Glad.");
AL_CORE_TRACE("***OpenGL Info***");
AL_CORE_INFO(" Renderer: {0}", glGetString(GL_RENDERER));
AL_CORE_INFO(" Version: {0}", glGetString(GL_VERSION));
AL_CORE_INFO(" Vendor: {0}", glGetString(GL_VENDOR));
}
void OpenGLContext::swapBuffers()
{
glfwSwapBuffers(m_WindowHandle);
}
}
| 27.814815
| 67
| 0.733688
|
joshrudesill
|
13208b68947bb2b80288b77122f4eb365debe157
| 8,191
|
hpp
|
C++
|
src/messaging_implementation/ZmqZmfMessagingServiceImplementation.hpp
|
zeroSDN/ZeroModuleFramework
|
a2262a77891b9c6b34d33dc6ff1b9734175fdcce
|
[
"Apache-2.0"
] | null | null | null |
src/messaging_implementation/ZmqZmfMessagingServiceImplementation.hpp
|
zeroSDN/ZeroModuleFramework
|
a2262a77891b9c6b34d33dc6ff1b9734175fdcce
|
[
"Apache-2.0"
] | null | null | null |
src/messaging_implementation/ZmqZmfMessagingServiceImplementation.hpp
|
zeroSDN/ZeroModuleFramework
|
a2262a77891b9c6b34d33dc6ff1b9734175fdcce
|
[
"Apache-2.0"
] | null | null | null |
#ifndef ZMF_ZMQ_SERVICE_H
#define ZMF_ZMQ_SERVICE_H
#include "ModuleHandle.hpp"
#include "../messaging/IZmfMessagingService.hpp"
#include "ExternalRequestIdentity.hpp"
#include "../messaging/IZmfMessagingCoreInterface.hpp"
#include "../proto/FrameworkProto.pb.h"
#include <zmqpp/message.hpp>
#include <zmqpp/poller.hpp>
#include <zmqpp/socket.hpp>
#include <zmqpp/context.hpp>
#include <queue>
#include <mutex>
#include <map>
#include <future>
#include <Poco/DynamicAny.h>
#include <sstream>
#include <iostream>
#include <stdint.h>
namespace zmf {
namespace messaging {
/**
* @details "real" implementation of the IZmfMessagingService. Public interface matches IZmfMessagingService
* @author Jan Strauß
* @date created on 7/7/15.
*/
class ZmqZmfMessagingServiceImplementation : public IZmfMessagingService {
public:
ZmqZmfMessagingServiceImplementation(zmf::data::ModuleUniqueId moduleId);
virtual ~ZmqZmfMessagingServiceImplementation();
virtual bool start(IZmfMessagingCoreInterface* const corePtr,
std::shared_ptr<zmf::data::ModuleHandle> selfHandle,
std::shared_ptr<zmf::config::IConfigurationProvider> config);
virtual void stop();
virtual void peerJoin(std::shared_ptr<zmf::data::ModuleHandle> module);
virtual void peerLeave(std::shared_ptr<zmf::data::ModuleHandle> module);
virtual void subscribe(const zmf::data::MessageType& topic);
virtual void unsubscribe(const zmf::data::MessageType& topic);
virtual void publish(const zmf::data::ZmfMessage& msg);
virtual zmf::data::ZmfInReply sendRequest(
const zmf::data::ModuleUniqueId& target, const zmf::data::ZmfMessage& msg);
virtual void cancelRequest(uint64_t requestID, bool manual);
virtual void sendReply(ExternalRequestIdentity requestID, const zmf::data::ZmfMessage& response);
virtual void onDisable();
private:
/**
* address of the inproc notification channel
*/
const std::string NOTIFY_ADDRESS = "inproc://zmf_zmq_notify";
/**
* address to bind the pub and rep sockets on
*/
const std::string ENDPOINT_STRING = "tcp://*:*";
static const uint8_t MESSAGE_TYPE_REQUEST = 0;
static const uint8_t MESSAGE_TYPE_REPLY = 1;
static const uint8_t MESSAGE_TYPE_HELLO = 2;
/**
* enum containing the possible notification types
*/
enum NotifyType {
SUBSCRIPTION_CHANGE,
MEMBERSHIP_CHANGE,
SHUTDOWN,
};
/**
* pointer to the counterpart interface
*/
IZmfMessagingCoreInterface* core;
/**
* pointer to the config
*/
std::shared_ptr<config::IConfigurationProvider> config;
Poco::Logger& logger_main;
Poco::Logger& logger_poller;
/**
* pointer to the selfHandle
*/
std::shared_ptr<zmf::data::ModuleHandle> self;
zmf::proto::SenderId selfSenderId;
/**
* pointer to the internal thread handling socket IO
*/
std::unique_ptr<std::thread> poll_thread;
/**
* boolean flag indicating the current state of the service (started/stopped)
*/
std::atomic_bool alive = ATOMIC_VAR_INIT(false);
/**
* ZMQ context
*/
zmqpp::context_t context;
/**
* ZMQ publish socket
*/
std::unique_ptr<zmqpp::socket> socket_pub;
/**
* ZMQ Subscribe socket
*/
std::unique_ptr<zmqpp::socket> socket_sub;
/**
* ZMQ Request socket (router)
*/
std::map<zmf::data::ModuleUniqueId, std::unique_ptr<zmqpp::socket>> map_sockets_req;
/**
* ZMQ Reply socket (router)
*/
std::unique_ptr<zmqpp::socket> socket_rep;
/**
* ZMQ Push socket
*/
std::unique_ptr<zmqpp::socket> socket_notify_send;
/**
* ZMQ Pull socket
*/
std::unique_ptr<zmqpp::socket> socket_notify_recv;
/**
* ZMQ Poller
*/
std::unique_ptr<zmqpp::poller> poller;
/**
* queue containing subscription changes
*/
std::queue<std::pair<zmf::data::MessageType, bool>> queue_subscription_changes;
/**
* queue containing membership changes
*/
std::queue<std::pair<std::string, bool>> queue_membership_changes;
/**
* map containing the promise of sent requests not yet answered by peer (or cancelled locally)
*/
std::map<uint64_t, std::promise<zmf::data::ZmfMessage>> outstanding_requests;
/**
* map containing the reply-to address of requests not yet answered by own module
*/
std::map<ExternalRequestIdentity, zmf::data::ModuleUniqueId> outstanding_replies;
/**
* next request id to use
*/
uint64_t next_request_id = 0;
/**
* locks for the various maps/queues/..
*/
std::mutex lock_notify_send;
std::mutex lock_pub_socket;
std::mutex lock_queue_subscription_changes;
std::mutex lock_queue_membership_changes;
std::mutex lock_map_replies;
std::mutex lock_map_requests;
std::mutex lock_map_sockets_req;
std::mutex lock_ids;
int32_t ZMF_ZMQ_ZMQ_RCVBUF = 0;
int32_t ZMF_ZMQ_ZMQ_RCVHWM = 100000;
int32_t ZMF_ZMQ_ZMQ_SNDBUF = 0;
int32_t ZMF_ZMQ_ZMQ_SNDHWM = 100000;
/**
* Poller thread method: apply membership changes from queue
*/
void applyMembershipChange();
/**
* Poller thread method: apply subscription changes from queue
*/
void applySubscriptionChange();
/**
* Poller thread method: handle input on sub socket
*/
void handleSubIn();
/**
* Poller thread method: handle input on notify socket
*/
void handleNotify();
/**
* Poller thread method: handle input on rep socket
*/
void handleRepIn();
/**
* util method to check if the alive flag is true
*/
void checkAlive();
/**
* Poller thread method: main loop for the poller thread
*/
void pollerLoop();
/**
* util method to close all zmq sockets
*/
void closeSockets();
/**
* util method to put a notify msg in the notify queue
*/
void notifyPoller(const NotifyType type);
/**
* util method to extract the port from the zmq socket option ĺast_endpoint
*/
uint16_t extractPort(std::unique_ptr<zmqpp::socket>& socket) const;
/**
* util/debug method to print a zmq message
*/
void printMessage(zmqpp::message& msg);
void handleRequestReceived(zmqpp::message& message);
void handleReplyReceived(zmqpp::message& message);
void handleHelloReceived(zmqpp::message& message);
void internalConnect(zmf::data::ModuleUniqueId identity, std::string rep_addr, std::string pub_addr);
std::string getIp();
};
}
}
#endif //ZMF_ZMQ_SERVICE_H
| 30.677903
| 116
| 0.54511
|
zeroSDN
|
1321fa202f00669ce132cf5d976a7df88fb940b6
| 4,130
|
cpp
|
C++
|
QP/v5.4.2/qpcpp/source/qs_fp.cpp
|
hyller/GladiatorCots
|
36a69df68675bb40b562081c531e6674037192a8
|
[
"Unlicense"
] | null | null | null |
QP/v5.4.2/qpcpp/source/qs_fp.cpp
|
hyller/GladiatorCots
|
36a69df68675bb40b562081c531e6674037192a8
|
[
"Unlicense"
] | null | null | null |
QP/v5.4.2/qpcpp/source/qs_fp.cpp
|
hyller/GladiatorCots
|
36a69df68675bb40b562081c531e6674037192a8
|
[
"Unlicense"
] | null | null | null |
/// @file
/// @brief QS floating point output implementation
/// @ingroup qs
/// @cond
///***************************************************************************
/// Product: QS/C++
/// Last updated for version 5.4.0
/// Last updated on 2015-04-29
///
/// Q u a n t u m L e a P s
/// ---------------------------
/// innovating embedded systems
///
/// Copyright (C) Quantum Leaps, www.state-machine.com.
///
/// This program is open source software: you can redistribute it and/or
/// modify it under the terms of the GNU General Public License as published
/// by the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// Alternatively, this program may be distributed and modified under the
/// terms of Quantum Leaps commercial licenses, which expressly supersede
/// the GNU General Public License and are specifically designed for
/// licensees interested in retaining the proprietary status of their code.
///
/// 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, see <http://www.gnu.org/licenses/>.
///
/// Contact information:
/// Web: www.state-machine.com
/// Email: info@state-machine.com
///***************************************************************************
/// @endcond
#define QP_IMPL // this is QF/QK implementation
#include "qs_port.h" // QS port
#include "qs_pkg.h" // QS package-scope internal interface
namespace QP {
//****************************************************************************
/// @note This function is only to be used through macros, never in the
/// client code directly.
///
void QS::f32(uint8_t format, float32_t const d) {
union F32Rep {
float32_t f;
uint32_t u;
} fu32; // the internal binary representation
uint8_t chksum_ = priv_.chksum; // put in a temporary (register)
uint8_t *buf_ = priv_.buf; // put in a temporary (register)
QSCtr head_ = priv_.head; // put in a temporary (register)
QSCtr end_ = priv_.end; // put in a temporary (register)
fu32.f = d; // assign the binary representation
priv_.used += static_cast<QSCtr>(5); // 5 bytes about to be added
QS_INSERT_ESC_BYTE(format) // insert the format byte
for (int_t i = static_cast<int_t>(4); i != static_cast<int_t>(0); --i) {
format = static_cast<uint8_t>(fu32.u);
QS_INSERT_ESC_BYTE(format)
fu32.u >>= 8;
}
priv_.head = head_; // save the head
priv_.chksum = chksum_; // save the checksum
}
//****************************************************************************
/// @note This function is only to be used through macros, never in the
/// client code directly.
///
void QS::f64(uint8_t format, float64_t const d) {
union F64Rep {
float64_t d;
struct UInt2 {
uint32_t u1;
uint32_t u2;
} i;
} fu64; // the internal binary representation
uint8_t chksum_ = priv_.chksum;
uint8_t *buf_ = priv_.buf;
QSCtr head_ = priv_.head;
QSCtr end_ = priv_.end;
int_t i;
fu64.d = d; // assign the binary representation
priv_.used += static_cast<QSCtr>(9); // 9 bytes about to be added
QS_INSERT_ESC_BYTE(format) // insert the format byte
for (i = static_cast<int_t>(4); i != static_cast<int_t>(0); --i) {
format = static_cast<uint8_t>(fu64.i.u1);
QS_INSERT_ESC_BYTE(format)
fu64.i.u1 >>= 8;
}
for (i = static_cast<int_t>(4); i != static_cast<int_t>(0); --i) {
format = static_cast<uint8_t>(fu64.i.u2);
QS_INSERT_ESC_BYTE(format)
fu64.i.u2 >>= 8;
}
priv_.head = head_; // update the head
priv_.chksum = chksum_; // update the checksum
}
} // namespace QP
| 35.913043
| 78
| 0.584988
|
hyller
|
1325537386dd8318d1360a7b92335ef2017989b4
| 11,543
|
cpp
|
C++
|
test/marshall/shared_buffer_test.cpp
|
oxenran/utility-rack
|
5d757feea65e9e83375f4be0a770225ebf39d019
|
[
"BSL-1.0"
] | null | null | null |
test/marshall/shared_buffer_test.cpp
|
oxenran/utility-rack
|
5d757feea65e9e83375f4be0a770225ebf39d019
|
[
"BSL-1.0"
] | null | null | null |
test/marshall/shared_buffer_test.cpp
|
oxenran/utility-rack
|
5d757feea65e9e83375f4be0a770225ebf39d019
|
[
"BSL-1.0"
] | null | null | null |
/** @file
*
* @ingroup test_module
*
* @brief Test scenarios for @c mutable_shared_buffer and
* @c const_shared_buffer classes.
*
* @author Cliff Green
*
* Copyright (c) 2017-2018 by Cliff Green
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
#include "catch2/catch.hpp"
#include <cstddef> // std::byte
#include <list>
#include <string_view>
#include "marshall/shared_buffer.hpp"
#include "utility/repeat.hpp"
#include "utility/make_byte_array.hpp"
#include "utility/cast_ptr_to.hpp"
constexpr std::byte Harhar { 42 };
constexpr int N = 11;
template <typename SB, typename T>
void pointer_check(const T* bp, typename SB::size_type sz) {
GIVEN ("An arbitrary buf pointer and a size") {
WHEN ("A shared buffer is constructed with the buf and size") {
SB sb(bp, sz);
THEN ("the shared buffer is not empty, the size matches and the contents match") {
REQUIRE_FALSE (sb.empty());
REQUIRE (sb.size() == sz);
const std::byte* buf = chops::cast_ptr_to<std::byte>(bp);
chops::repeat(sz, [&sb, buf] (const int& i) { REQUIRE(*(sb.data()+i) == *(buf+i)); } );
}
}
} // end given
}
template <typename SB>
void shared_buffer_common(const std::byte* buf, typename SB::size_type sz) {
REQUIRE (sz > 2);
pointer_check<SB>(buf, sz);
const void* vp = static_cast<const void*>(buf);
pointer_check<SB>(vp, sz);
pointer_check<SB>(static_cast<const char*>(vp), sz);
pointer_check<SB>(static_cast<const unsigned char*>(vp), sz);
pointer_check<SB>(static_cast<const signed char*>(vp), sz);
GIVEN ("A shared buffer") {
SB sb(buf, sz);
REQUIRE_FALSE (sb.empty());
WHEN ("A separate shared buffer is constructed with the buf and size") {
SB sb2(buf, sz);
REQUIRE_FALSE (sb2.empty());
THEN ("the two shared buffers compare equal") {
REQUIRE (sb == sb2);
}
}
AND_WHEN ("A second shared buffer is copy constructed") {
SB sb2(sb);
REQUIRE_FALSE (sb2.empty());
THEN ("the two shared buffers compare equal") {
REQUIRE (sb == sb2);
}
}
AND_WHEN ("A shared buffer is constructed from another container") {
std::list<std::byte> lst (buf, buf+sz);
SB sb2(lst.cbegin(), lst.cend());
REQUIRE_FALSE (sb2.empty());
THEN ("the two shared buffers compare equal") {
REQUIRE (sb == sb2);
}
}
AND_WHEN ("A separate shared buffer is constructed shorter than the first") {
auto ba = chops::make_byte_array(buf[0], buf[1]);
SB sb2(ba.cbegin(), ba.cend());
REQUIRE_FALSE (sb2.empty());
THEN ("the separate shared buffer compares less than the first") {
REQUIRE (sb2 < sb);
REQUIRE (sb2 != sb);
}
}
AND_WHEN ("A separate shared buffer is constructed with values less than the first") {
auto ba = chops::make_byte_array(0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
SB sb2(ba.cbegin(), ba.cend());
REQUIRE_FALSE (sb2.empty());
THEN ("the separate shared buffer compares less than the first") {
REQUIRE (sb2 != sb);
}
}
} // end given
}
template <typename SB>
void shared_buffer_byte_vector_move() {
auto arr = chops::make_byte_array (0x01, 0x02, 0x03, 0x04, 0x05);
GIVEN ("A vector of bytes") {
std::vector<std::byte> bv { arr.cbegin(), arr.cend() };
WHEN ("A shared buffer is constructed by moving from the byte vector") {
SB sb(std::move(bv));
THEN ("the shared buffer will contain the data and the byte vector will not") {
REQUIRE (sb == SB(arr.cbegin(), arr.cend()));
REQUIRE_FALSE (bv.size() == sb.size());
}
}
} // end given
}
SCENARIO ( "Const shared buffer common test",
"[const_shared_buffer] [common]" ) {
auto arr = chops::make_byte_array( 40, 41, 42, 43, 44, 60, 59, 58, 57, 56, 42, 42 );
shared_buffer_common<chops::const_shared_buffer>(arr.data(), arr.size());
}
SCENARIO ( "Mutable shared buffer common test",
"[mutable_shared_buffer] [common]" ) {
auto arr = chops::make_byte_array ( 80, 81, 82, 83, 84, 90, 91, 92 );
shared_buffer_common<chops::const_shared_buffer>(arr.data(), arr.size());
}
SCENARIO ( "Mutable shared buffer copy construction and assignment",
"[mutable_shared_buffer] [copy]" ) {
GIVEN ("A default constructed mutable shared_buffer") {
auto arr = chops::make_byte_array ( 80, 81, 82, 83, 84, 90, 91, 92 );
chops::mutable_shared_buffer sb;
REQUIRE (sb.empty());
WHEN ("Another mutable shared buffer is assigned into it") {
chops::mutable_shared_buffer sb2(arr.cbegin(), arr.cend());
sb = sb2;
THEN ("the size has changed and the two shared buffers compare equal") {
REQUIRE (sb.size() == arr.size());
REQUIRE (sb == sb2);
}
}
AND_WHEN ("Another mutable shared buffer is copy constructed") {
sb = chops::mutable_shared_buffer(arr.cbegin(), arr.cend());
chops::mutable_shared_buffer sb2(sb);
THEN ("the two shared buffers compare equal and a change to the first shows in the second") {
REQUIRE (sb == sb2);
*(sb.data()+0) = Harhar;
*(sb.data()+1) = Harhar;
REQUIRE (sb == sb2);
}
}
} // end given
}
SCENARIO ( "Mutable shared buffer resize and clear",
"[mutable_shared_buffer] [resize_and_clear]" ) {
GIVEN ("A default constructed mutable shared_buffer") {
chops::mutable_shared_buffer sb;
WHEN ("Resize is called") {
sb.resize(N);
THEN ("the internal buffer will have all zeros") {
REQUIRE (sb.size() == N);
chops::repeat(N, [&sb] (const int& i) { REQUIRE (*(sb.data() + i) == std::byte{0} ); } );
}
}
AND_WHEN ("Another mutable shared buffer with a size is constructed") {
sb.resize(N);
chops::mutable_shared_buffer sb2(N);
THEN ("the two shared buffers compare equal, with all zeros in the buffer") {
REQUIRE (sb == sb2);
chops::repeat(N, [&sb, &sb2] (const int& i) {
REQUIRE (*(sb.data() + i) == std::byte{0} );
REQUIRE (*(sb2.data() + i) == std::byte{0} );
} );
}
}
AND_WHEN ("The mutable shared buffer is cleared") {
sb.resize(N);
sb.clear();
THEN ("the size will be zero and the buffer is empty") {
REQUIRE (sb.size() == 0);
REQUIRE (sb.empty());
}
}
} // end given
}
SCENARIO ( "Mutable shared buffer swap",
"[mutable_shared_buffer] [swap]" ) {
GIVEN ("Two mutable shared_buffers") {
auto arr1 = chops::make_byte_array (0xaa, 0xbb, 0xcc);
auto arr2 = chops::make_byte_array (0x01, 0x02, 0x03, 0x04, 0x05);
chops::mutable_shared_buffer sb1(arr1.cbegin(), arr1.cend());
chops::mutable_shared_buffer sb2(arr2.cbegin(), arr2.cend());
WHEN ("The buffers are swapped") {
chops::swap(sb1, sb2);
THEN ("the sizes and contents will be swapped") {
REQUIRE (sb1.size() == arr2.size());
REQUIRE (sb2.size() == arr1.size());
REQUIRE (*(sb1.data()+0) == *(arr2.data()+0));
REQUIRE (*(sb1.data()+1) == *(arr2.data()+1));
REQUIRE (*(sb2.data()+0) == *(arr1.data()+0));
REQUIRE (*(sb2.data()+1) == *(arr1.data()+1));
}
}
} // end given
}
SCENARIO ( "Mutable shared buffer append",
"[mutable_shared_buffer] [append]" ) {
auto arr = chops::make_byte_array (0xaa, 0xbb, 0xcc);
auto arr2 = chops::make_byte_array (0xaa, 0xbb, 0xcc, 0xaa, 0xbb, 0xcc);
chops::mutable_shared_buffer ta(arr.cbegin(), arr.cend());
chops::mutable_shared_buffer ta2(arr2.cbegin(), arr2.cend());
GIVEN ("A default constructed mutable shared_buffer") {
chops::mutable_shared_buffer sb;
WHEN ("Append with a pointer and size is called") {
sb.append(arr.data(), arr.size());
THEN ("the internal buffer will contain the appended data") {
REQUIRE (sb == ta);
}
}
AND_WHEN ("Append with a mutable shared buffer is called") {
sb.append(ta);
THEN ("the internal buffer will contain the appended data") {
REQUIRE (sb == ta);
}
}
AND_WHEN ("Append is called twice") {
sb.append(ta);
sb.append(ta);
THEN ("the internal buffer will contain twice the appended data") {
REQUIRE (sb == ta2);
}
}
AND_WHEN ("Appending with single bytes") {
sb.append(std::byte(0xaa));
sb.append(std::byte(0xbb));
sb += std::byte(0xcc);
THEN ("the internal buffer will contain the appended data") {
REQUIRE (sb == ta);
}
}
AND_WHEN ("Appending with a char* to test templated append") {
std::string_view sv("Haha, Bro!");
chops::mutable_shared_buffer cb(sv.data(), sv.size());
sb.append(sv.data(), sv.size());
THEN ("the internal buffer will contain the appended data") {
REQUIRE (sb == cb);
}
}
} // end given
}
SCENARIO ( "Compare a mutable shared_buffer with a const shared buffer",
"[mutable_shared_buffer] [const_shared_buffer] [compare]" ) {
GIVEN ("An array of bytes") {
auto arr = chops::make_byte_array (0xaa, 0xbb, 0xcc);
WHEN ("A mutable_shared_buffer and a const_shared_buffer are created from the bytes") {
chops::mutable_shared_buffer msb(arr.cbegin(), arr.cend());
chops::const_shared_buffer csb(arr.cbegin(), arr.cend());
THEN ("the shared buffers will compare equal") {
REQUIRE (msb == csb);
REQUIRE (csb == msb);
}
}
} // end given
}
SCENARIO ( "Mutable shared buffer move into const shared buffer",
"[mutable_shared_buffer] [const_shared_buffer] [move]" ) {
auto arr1 = chops::make_byte_array (0xaa, 0xbb, 0xcc);
auto arr2 = chops::make_byte_array (0x01, 0x02, 0x03, 0x04, 0x05);
GIVEN ("A mutable_shared_buffer") {
chops::mutable_shared_buffer msb(arr1.cbegin(), arr1.cend());
WHEN ("A const_shared_buffer is move constructed from the mutable_shared_buffer") {
chops::const_shared_buffer csb(std::move(msb));
THEN ("the const_shared_buffer will contain the data and the mutable_shared_buffer will not") {
REQUIRE (csb == chops::const_shared_buffer(arr1.cbegin(), arr1.cend()));
REQUIRE_FALSE (msb == csb);
msb.clear();
msb.resize(arr2.size());
msb.append(arr2.cbegin(), arr2.size());
REQUIRE_FALSE (msb == csb);
}
}
} // end given
}
SCENARIO ( "Move a vector of bytes into a mutable shared buffer",
"[mutable_shared_buffer] [move_byte_vec]" ) {
shared_buffer_byte_vector_move<chops::mutable_shared_buffer>();
}
SCENARIO ( "Move a vector of bytes into a const shared buffer",
"[const_shared_buffer] [move_byte_vec]" ) {
shared_buffer_byte_vector_move<chops::const_shared_buffer>();
}
SCENARIO ( "Use get_byte_vec for external modification of buffer",
"[mutable_shared_buffer] [get_byte_vec]" ) {
auto arr = chops::make_byte_array (0xaa, 0xbb, 0xcc);
chops::mutable_shared_buffer::byte_vec bv (arr.cbegin(), arr.cend());
GIVEN ("A mutable_shared_buffer") {
chops::mutable_shared_buffer msb(bv.cbegin(), bv.cend());
WHEN ("get_byte_vec is called") {
auto r = msb.get_byte_vec();
THEN ("the refererence can be used to access and modify data") {
REQUIRE (r == bv);
r[0] = std::byte(0xdd);
REQUIRE_FALSE (r == bv);
}
}
} // end given
}
| 33.361272
| 101
| 0.616737
|
oxenran
|
132ba4a63a21d9dfff4b8e474b90818c8214b51c
| 5,187
|
cpp
|
C++
|
Common/IniFile.cpp
|
wolfgang1991/CommonLibraries
|
949251019cc8dd532938d16ab85a4e772eb6817e
|
[
"Zlib"
] | null | null | null |
Common/IniFile.cpp
|
wolfgang1991/CommonLibraries
|
949251019cc8dd532938d16ab85a4e772eb6817e
|
[
"Zlib"
] | 1
|
2020-07-31T13:20:54.000Z
|
2020-08-06T15:45:39.000Z
|
Common/IniFile.cpp
|
wolfgang1991/CommonLibraries
|
949251019cc8dd532938d16ab85a4e772eb6817e
|
[
"Zlib"
] | null | null | null |
#include <IniFile.h>
#include <IniIterator.h>
#include <IniParser.h>
#include <iostream>
#include <cstring>
#include <cassert>
#include <string>
#include <map>
#include <fstream>
#include <sstream>
using namespace std;
static const char characters[] = { '\n', '\\', '#', ';', ' ', '\t', '[', ']', '=', '\r'};
static const char escapes[] = {'n', '\\', '#', ';', ' ', 't', '0', '1', '2', 'r'};
static const int escapeSize = sizeof(escapes)/sizeof(escapes[0]);
static inline int findChar(const char* chars, int size, char toFind){
for(int i=0; i<size; i++){
if(chars[i]==toFind){
return i;
}
}
return size;
}
std::string escapeIniStrings(const std::string& s){
std::stringstream ss;
bool sthToEscape = false;
for(uint32_t i=0; i<s.size(); i++){
int idx = findChar(characters, escapeSize, s[i]);
if(sthToEscape){
if(idx!=escapeSize){
ss << '\\' << escapes[idx];
}else{
ss << s[i];
}
}else{
if(idx!=escapeSize){
sthToEscape = true;
ss << s.substr(0, i) << '\\' << escapes[idx];
}
}
}
if(sthToEscape){
return ss.str();
}else{
return s;
}
}
std::string unescapeIniStrings(const std::string& s){
std::stringstream ss;
bool sthToEscape = false;
for(uint32_t i=0; i<s.size(); i++){
bool escapeChar = s[i]=='\\';
if(sthToEscape){
if(escapeChar){
i++;
if(i>=s.size()){return s;}//assert(i<s.size())
int idx = findChar(escapes, escapeSize, s[i]);
if(idx>=escapeSize){return s;}//assert(idx<escapeSize)
ss << characters[idx];
}else{
ss << s[i];
}
}else if(escapeChar){
sthToEscape = true;
i++;
if(i>=s.size()){return s;}//assert(i<s.size())
int idx = findChar(escapes, escapeSize, s[i]);
if(idx>=escapeSize){return s;}//assert(idx<escapeSize)
ss << s.substr(0, i-1) << characters[idx];
}
}
if(sthToEscape){
return ss.str();
}else{
return s;
}
}
std::string& IniFile::get(const std::string& section, const std::string& key){
return data[section][key];
}
const std::string& IniFile::get(const std::string& section, const std::string& key, const std::string& defaultValue) const{
auto it = data.find(section);
if(it!=data.end()){
auto it2 = it->second.find(key);
if(it2!=it->second.end()){
return it2->second;
}
}
return defaultValue;
}
const std::string& IniFile::get(const std::string& section, const std::string& key) const{
static const std::string empty("");
return get(section, key, empty);
}
void IniFile::set(const std::string& section, const std::string& key, const std::string& value){
data[section][key] = value;
}
void IniFile::removeSection(const std::string& section){
data.erase(section);
}
void IniFile::removeValue(const std::string& section, const std::string& key){
data[section].erase(key);
}
IniIterator* IniFile::createNewIterator() const{
return new IniIterator(&data);
}
void IniFile::print() const{
cout << toString();
}
std::string IniFile::toString() const{
std::stringstream ss;
IniIterator* it = createNewIterator();
while(it->isSectionAvail()){
string cs = it->getCurrentSection();
if(cs.size()>0){ss<<"["<<escapeIniStrings(cs)<<"]\n";}
while(it->isValueAvail()){
ss << escapeIniStrings(it->getCurrentKey()) << " = " << escapeIniStrings(it->getCurrentValue()) << "\n";
it->gotoNextValue();
}
it->gotoNextSection();
ss << "\n";
}
delete it;
return ss.str();
}
bool IniFile::save(const std::string& file) const{
ofstream fp(file.c_str(), std::ofstream::binary | std::ofstream::trunc);
if(fp.good()){
fp << toString();
return true;
}
return false;
}
bool IniFile::isSectionAvailable(const std::string& section) const{
std::map< std::string, std::map<std::string, std::string> >::const_iterator it = data.find(section);
return !(it==data.end());
}
bool IniFile::isAvailable(const std::string& section, const std::string& key) const{
std::map< std::string, std::map<std::string, std::string> >::const_iterator it = data.find(section);
if(it==data.end()){return false;}
std::map<std::string, std::string>::const_iterator itb = it->second.find(key);
return itb!=it->second.end();
}
IniFile::IniFile(const std::string& file){
IniParser* p = new IniParser;
ifstream infile(file.c_str(), ifstream::binary);
if (infile.is_open()){
char ch; infile.get(ch);
while (infile.good()) {
if(p->doStep(ch)){
set(unescapeIniStrings(p->curSection), unescapeIniStrings(p->curKey), unescapeIniStrings(p->curValue));
}
infile.get(ch);
}
if(p->doStep('\n')){//EOF
set(unescapeIniStrings(p->curSection), unescapeIniStrings(p->curKey), unescapeIniStrings(p->curValue));
}
infile.close();
}
delete p;
}
void IniFile::setFromString(const char* str){
IniParser* p = new IniParser;
int i = 0;
char c = str[i];
while(c!='\0'){
if(p->doStep(c)){
set(unescapeIniStrings(p->curSection), unescapeIniStrings(p->curKey), unescapeIniStrings(p->curValue));
}
i++;
c = str[i];
}
if(p->doStep('\n')){//EOF
set(unescapeIniStrings(p->curSection), unescapeIniStrings(p->curKey), unescapeIniStrings(p->curValue));
}
delete p;
}
void IniFile::moveSection(const std::string& start, const std::string& end){
data[end] = data[start];
removeSection(start);
}
| 25.551724
| 123
| 0.644496
|
wolfgang1991
|
132bcb5535c6c01c1332eb6f41d2efb4c34ab682
| 3,037
|
cc
|
C++
|
lib/jxl/bits_test.cc
|
jxl-bot/libjxl
|
44778c6902084bd239c5fb8eaa53bfd90dd9face
|
[
"Apache-2.0"
] | 1
|
2021-08-05T12:14:05.000Z
|
2021-08-05T12:14:05.000Z
|
lib/jxl/bits_test.cc
|
jxl-bot/libjxl
|
44778c6902084bd239c5fb8eaa53bfd90dd9face
|
[
"Apache-2.0"
] | null | null | null |
lib/jxl/bits_test.cc
|
jxl-bot/libjxl
|
44778c6902084bd239c5fb8eaa53bfd90dd9face
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) the JPEG XL Project
//
// 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 "lib/jxl/base/bits.h"
#include "gtest/gtest.h"
namespace jxl {
namespace {
TEST(BitsTest, TestNumZeroBits) {
// Zero input is well-defined.
EXPECT_EQ(32, Num0BitsAboveMS1Bit(0u));
EXPECT_EQ(64, Num0BitsAboveMS1Bit(0ull));
EXPECT_EQ(32, Num0BitsBelowLS1Bit(0u));
EXPECT_EQ(64, Num0BitsBelowLS1Bit(0ull));
EXPECT_EQ(31, Num0BitsAboveMS1Bit(1u));
EXPECT_EQ(30, Num0BitsAboveMS1Bit(2u));
EXPECT_EQ(63, Num0BitsAboveMS1Bit(1ull));
EXPECT_EQ(62, Num0BitsAboveMS1Bit(2ull));
EXPECT_EQ(0, Num0BitsBelowLS1Bit(1u));
EXPECT_EQ(0, Num0BitsBelowLS1Bit(1ull));
EXPECT_EQ(1, Num0BitsBelowLS1Bit(2u));
EXPECT_EQ(1, Num0BitsBelowLS1Bit(2ull));
EXPECT_EQ(0, Num0BitsAboveMS1Bit(0x80000000u));
EXPECT_EQ(0, Num0BitsAboveMS1Bit(0x8000000000000000ull));
EXPECT_EQ(31, Num0BitsBelowLS1Bit(0x80000000u));
EXPECT_EQ(63, Num0BitsBelowLS1Bit(0x8000000000000000ull));
}
TEST(BitsTest, TestFloorLog2) {
// for input = [1, 7]
const int expected[7] = {0, 1, 1, 2, 2, 2, 2};
for (uint32_t i = 1; i <= 7; ++i) {
EXPECT_EQ(expected[i - 1], FloorLog2Nonzero(i)) << " " << i;
EXPECT_EQ(expected[i - 1], FloorLog2Nonzero(uint64_t(i))) << " " << i;
}
EXPECT_EQ(31, FloorLog2Nonzero(0x80000000u));
EXPECT_EQ(31, FloorLog2Nonzero(0x80000001u));
EXPECT_EQ(31, FloorLog2Nonzero(0xFFFFFFFFu));
EXPECT_EQ(31, FloorLog2Nonzero(0x80000000ull));
EXPECT_EQ(31, FloorLog2Nonzero(0x80000001ull));
EXPECT_EQ(31, FloorLog2Nonzero(0xFFFFFFFFull));
EXPECT_EQ(63, FloorLog2Nonzero(0x8000000000000000ull));
EXPECT_EQ(63, FloorLog2Nonzero(0x8000000000000001ull));
EXPECT_EQ(63, FloorLog2Nonzero(0xFFFFFFFFFFFFFFFFull));
}
TEST(BitsTest, TestCeilLog2) {
// for input = [1, 7]
const int expected[7] = {0, 1, 2, 2, 3, 3, 3};
for (uint32_t i = 1; i <= 7; ++i) {
EXPECT_EQ(expected[i - 1], CeilLog2Nonzero(i)) << " " << i;
EXPECT_EQ(expected[i - 1], CeilLog2Nonzero(uint64_t(i))) << " " << i;
}
EXPECT_EQ(31, CeilLog2Nonzero(0x80000000u));
EXPECT_EQ(32, CeilLog2Nonzero(0x80000001u));
EXPECT_EQ(32, CeilLog2Nonzero(0xFFFFFFFFu));
EXPECT_EQ(31, CeilLog2Nonzero(0x80000000ull));
EXPECT_EQ(32, CeilLog2Nonzero(0x80000001ull));
EXPECT_EQ(32, CeilLog2Nonzero(0xFFFFFFFFull));
EXPECT_EQ(63, CeilLog2Nonzero(0x8000000000000000ull));
EXPECT_EQ(64, CeilLog2Nonzero(0x8000000000000001ull));
EXPECT_EQ(64, CeilLog2Nonzero(0xFFFFFFFFFFFFFFFFull));
}
} // namespace
} // namespace jxl
| 34.123596
| 75
| 0.726045
|
jxl-bot
|
132f355fe8e539026d9ba7a8464fb28294042b51
| 1,703
|
cpp
|
C++
|
src/planner/interface/goal_interface.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 3
|
2020-03-05T23:56:14.000Z
|
2021-02-17T19:06:50.000Z
|
src/planner/interface/goal_interface.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 1
|
2021-03-07T01:23:47.000Z
|
2021-03-07T01:23:47.000Z
|
src/planner/interface/goal_interface.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 1
|
2021-03-03T07:54:16.000Z
|
2021-03-03T07:54:16.000Z
|
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file goal_interface.cpp
* \author Collin Johnson
*
* Definition of GoalInterface.
*/
#include "planner/interface/goal_interface.h"
#include <iostream>
#include <iterator>
namespace vulcan
{
namespace planner
{
void GoalInterface::addGlobalPose(const std::string& name, const pose_t& pose)
{
auto goalIt = std::find_if(goals_.begin(), goals_.end(), [&name](const Goal& g) {
return g.name() == name;
});
if (goalIt != goals_.end()) {
goalIt->setGlobalPose(pose);
} else {
goals_.emplace_back(name, pose);
}
}
void GoalInterface::addLocalArea(const std::string& name, hssh::LocalArea::Id area)
{
auto goalIt = std::find_if(goals_.begin(), goals_.end(), [&name](const Goal& g) {
return g.name() == name;
});
if (goalIt != goals_.end()) {
goalIt->setLocalArea(area);
} else {
goals_.emplace_back(name, area);
}
}
std::size_t GoalInterface::load(std::istream& in)
{
// Load the Goals
std::copy(std::istream_iterator<Goal>(in), std::istream_iterator<Goal>(), std::back_inserter(goals_));
return goals_.size();
}
bool GoalInterface::save(std::ostream& out)
{
std::copy(goals_.begin(), goals_.end(), std::ostream_iterator<Goal>(out, ""));
return out.good();
}
} // namespace planner
} // namespace vulcan
| 24.328571
| 106
| 0.660012
|
anuranbaka
|
132ff6aded62f2d54d7817a6fad24398df1e71f1
| 311
|
cpp
|
C++
|
src/fe/subsystems/scripting/tableHandler.cpp
|
TheCandianVendingMachine/TCVM_Flat_Engine
|
13797b91f6f4199d569f80baa29e2584652fc4b5
|
[
"MIT"
] | 1
|
2018-06-15T23:49:37.000Z
|
2018-06-15T23:49:37.000Z
|
src/fe/subsystems/scripting/tableHandler.cpp
|
TheCandianVendingMachine/TCVM_Flat_Engine
|
13797b91f6f4199d569f80baa29e2584652fc4b5
|
[
"MIT"
] | 5
|
2017-04-23T03:25:10.000Z
|
2018-02-23T07:48:16.000Z
|
src/fe/subsystems/scripting/tableHandler.cpp
|
TheCandianVendingMachine/TCVM_Flat_Engine
|
13797b91f6f4199d569f80baa29e2584652fc4b5
|
[
"MIT"
] | null | null | null |
#include "fe/subsystems/scripting/tableHandler.hpp"
#include "fe/subsystems/scripting/scriptHelpers.hpp"
fe::tableHandler::tableHandler(sol::state &state) : m_state(state)
{
}
sol::table fe::tableHandler::getTable(const char *path)
{
return fe::imp::getTableFromPath(path, m_state);
}
| 25.916667
| 66
| 0.70418
|
TheCandianVendingMachine
|
133146c26ff37c5deed5f187fa747066237395af
| 4,834
|
cpp
|
C++
|
3rdParty/iresearch/core/store/data_output.cpp
|
specimen151/arangodb
|
1a3a31dace16293426a19364eb4d93c8f17c0d68
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null |
3rdParty/iresearch/core/store/data_output.cpp
|
specimen151/arangodb
|
1a3a31dace16293426a19364eb4d93c8f17c0d68
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null |
3rdParty/iresearch/core/store/data_output.cpp
|
specimen151/arangodb
|
1a3a31dace16293426a19364eb4d93c8f17c0d68
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 by EMC 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.
///
/// Copyright holder is EMC Corporation
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////
#include "shared.hpp"
#include "data_input.hpp"
#include "data_output.hpp"
#include "utils/std.hpp"
#include "utils/unicode_utils.hpp"
#include <memory>
NS_ROOT
/* -------------------------------------------------------------------
* data_output
* ------------------------------------------------------------------*/
data_output::~data_output() {}
void data_output::write_short( int16_t i ) {
write_byte( static_cast< byte_type >( i >> 8 ) );
write_byte( static_cast< byte_type >( i ) );
}
void data_output::write_int( int32_t i ) {
write_byte( static_cast< byte_type >( i >> 24 ) );
write_byte( static_cast< byte_type >( i >> 16 ) );
write_byte( static_cast< byte_type >( i >> 8 ) );
write_byte( static_cast< byte_type >( i ) );
}
void data_output::write_vint(uint32_t i) {
while (i >= 0x80) {
write_byte(static_cast<byte_type>(i | 0x80));
i >>= 7;
}
write_byte(static_cast<byte_type>(i));
}
void data_output::write_long( int64_t i ) {
write_int( static_cast< int32_t >( i >> 32 ) );
write_int( static_cast< int32_t >( i ) );
}
void data_output::write_vlong( uint64_t i ) {
while (i >= uint64_t(0x80)) {
write_byte(static_cast<byte_type>(i | uint64_t(0x80)));
i >>= 7;
}
write_byte(static_cast<byte_type>(i));
}
/* -------------------------------------------------------------------
* index_output
* ------------------------------------------------------------------*/
index_output::~index_output() {}
/* -------------------------------------------------------------------
* output_buf
* ------------------------------------------------------------------*/
output_buf::output_buf( index_output* out ) : out_( out ) {
assert( out_ );
}
std::streamsize output_buf::xsputn( const char_type* c, std::streamsize size ) {
out_->write_bytes( reinterpret_cast< const byte_type* >( c ), size );
return size;
}
output_buf::int_type output_buf::overflow( int_type c ) {
out_->write_int( c );
return c;
}
/* -------------------------------------------------------------------
* buffered_index_output
* ------------------------------------------------------------------*/
buffered_index_output::buffered_index_output( size_t buf_size )
: buf(memory::make_unique<byte_type[]>(buf_size)),
start( 0 ),
pos( 0 ),
buf_size( buf_size ) {
}
buffered_index_output::~buffered_index_output() {}
void buffered_index_output::write_byte( byte_type b ) {
if ( pos >= buf_size ) {
flush();
}
buf[pos++] = b;
}
void buffered_index_output::write_bytes( const byte_type* b, size_t length ) {
auto left = buf_size - pos;
// is there enough space in the buffer?
if ( left >= length ) {
// we add the data to the end of the buffer
std::memcpy( buf.get() + pos, b, length );
pos += length;
// if the buffer is full, flush it
if ( buf_size == pos ) {
flush();
}
} else {
// is data larger then buffer?
if ( length > buf_size ) {
// we flush the buffer
if ( pos > 0 ) {
flush();
}
// and write data at once
flush_buffer( b, length );
start += length;
} else {
// we fill/flush the buffer (until the input is written)
size_t slice_pos = 0; // position in the input data
while ( slice_pos < length ) {
auto slice_len = std::min( length - slice_pos, left );
std::memcpy( buf.get() + pos, b + slice_pos, slice_len );
slice_pos += slice_len;
pos += slice_len;
// if the buffer is full, flush it
left = buf_size - pos;
if ( left == 0 ) {
flush();
left = buf_size;
}
}
}
}
}
size_t buffered_index_output::file_pointer() const {
return start + pos;
}
void buffered_index_output::flush() {
flush_buffer( buf.get(), pos );
start += pos;
pos = 0U;
}
void buffered_index_output::close() {
flush();
start = 0;
pos = 0;
}
NS_END
| 26.271739
| 80
| 0.542201
|
specimen151
|
1331e825b4644c1d0da7f3b11954ec2cad7201df
| 61,827
|
cpp
|
C++
|
src/electionguard/election.cpp
|
msprotz/electionguard-cpp
|
206002a8873450141451c9b6f3da6cd389ee5c05
|
[
"MIT"
] | null | null | null |
src/electionguard/election.cpp
|
msprotz/electionguard-cpp
|
206002a8873450141451c9b6f3da6cd389ee5c05
|
[
"MIT"
] | null | null | null |
src/electionguard/election.cpp
|
msprotz/electionguard-cpp
|
206002a8873450141451c9b6f3da6cd389ee5c05
|
[
"MIT"
] | null | null | null |
#include "electionguard/election.hpp"
#include "electionguard/hash.hpp"
#include "log.hpp"
#include "serialize.hpp"
#include <cstring>
#include <iostream>
#include <utility>
using std::make_unique;
using std::map;
using std::move;
using std::out_of_range;
using std::ref;
using std::reference_wrapper;
using std::string;
using std::to_string;
using std::unique_ptr;
using std::vector;
using std::chrono::system_clock;
using DescriptionSerializer = electionguard::Serialize::ElectionDescription;
using InternalDescriptionSerializer = electionguard::Serialize::InternalElectionDescription;
using ContextSerializer = electionguard::Serialize::CiphertextelectionContext;
namespace electionguard
{
template <typename K, typename V>
K findByValue(const map<K, const V> &collection, const V &value)
{
for (auto &element : collection) {
if (element.second == value) {
return element.first;
}
}
throw out_of_range("value not found");
}
#pragma region ElectionType
template <typename> struct _election_type {
static const map<ElectionType, const string> _map;
};
template <typename T>
const map<ElectionType, const string> _election_type<T>::_map = {
{ElectionType::unknown, "unknown"},
{ElectionType::general, "general"},
{ElectionType::partisanPrimaryClosed, "partisanPrimaryClosed"},
{ElectionType::partisanPrimaryOpen, "partisanPrimaryOpen"},
{ElectionType::primary, "primary"},
{ElectionType::runoff, "runoff"},
{ElectionType::special, "special"},
{ElectionType::other, "other"},
};
EG_API const string getElectionTypeString(const ElectionType &value)
{
return _election_type<ElectionType>::_map.find(value)->second;
}
EG_API ElectionType getElectionType(const string &value)
{
try {
auto item = findByValue(_election_type<ElectionType>::_map, value);
return item;
} catch (const std::exception &e) {
Log::error(": error", e);
return ElectionType::unknown;
}
}
#pragma endregion
#pragma region ReportingUnitType
template <typename> struct _reporting_unit_type {
static const map<ReportingUnitType, const string> _map;
};
template <typename T>
const map<ReportingUnitType, const string> _reporting_unit_type<T>::_map = {
{ReportingUnitType::unknown, "unknown"},
{ReportingUnitType::ballotBatch, "ballotBatch"},
{ReportingUnitType::ballotStyleArea, "ballotStyleArea"},
{ReportingUnitType::borough, "borough"},
{ReportingUnitType::city, "city"},
{ReportingUnitType::cityCouncil, "cityCouncil"},
{ReportingUnitType::combinedPrecinct, "combinedPrecinct"},
{ReportingUnitType::congressional, "congressional"},
{ReportingUnitType::country, "country"},
{ReportingUnitType::county, "county"},
{ReportingUnitType::countyCouncil, "countyCouncil"},
{ReportingUnitType::dropBox, "dropBox"},
{ReportingUnitType::judicial, "judicial"},
{ReportingUnitType::municipality, "municipality"},
{ReportingUnitType::polling_place, "polling_place"},
{ReportingUnitType::precinct, "precinct"},
{ReportingUnitType::school, "school"},
{ReportingUnitType::special, "special"},
{ReportingUnitType::splitPrecinct, "splitPrecinct"},
{ReportingUnitType::state, "state"},
{ReportingUnitType::stateHouse, "stateHouse"},
{ReportingUnitType::stateSenate, "stateSenate"},
{ReportingUnitType::township, "township"},
{ReportingUnitType::utility, "utility"},
{ReportingUnitType::village, "village"},
{ReportingUnitType::voteCenter, "voteCenter"},
{ReportingUnitType::ward, "ward"},
{ReportingUnitType::water, "water"},
{ReportingUnitType::other, "other"},
};
EG_API const string getReportingUnitTypeString(const ReportingUnitType &value)
{
return _reporting_unit_type<ReportingUnitType>::_map.find(value)->second;
}
EG_API ReportingUnitType getReportingUnitType(const string &value)
{
try {
auto item = findByValue(_reporting_unit_type<ReportingUnitType>::_map, value);
return item;
} catch (const std::exception &e) {
Log::error(": error", e);
return ReportingUnitType::unknown;
}
}
#pragma endregion
#pragma region VoteVariationType
template <typename> struct _vote_variation_type {
static const map<VoteVariationType, const string> _map;
};
template <typename T>
const map<VoteVariationType, const string> _vote_variation_type<T>::_map = {
{VoteVariationType::unknown, "unknown"},
{VoteVariationType::one_of_m, "one_of_m"},
{VoteVariationType::borda, "borda"},
{VoteVariationType::cumulative, "cumulative"},
{VoteVariationType::majority, "majority"},
{VoteVariationType::n_of_m, "n_of_m"},
{VoteVariationType::plurality, "plurality"},
{VoteVariationType::proportional, "proportional"},
{VoteVariationType::range, "range"},
{VoteVariationType::rcv, "rcv"},
{VoteVariationType::super_majority, "super_majority"},
{VoteVariationType::other, "other"},
};
EG_API const string getVoteVariationTypeString(const VoteVariationType &value)
{
return _vote_variation_type<VoteVariationType>::_map.find(value)->second;
}
EG_API VoteVariationType getVoteVariationType(const string &value)
{
try {
auto item = findByValue(_vote_variation_type<VoteVariationType>::_map, value);
return item;
} catch (const std::exception &e) {
Log::error(": error", e);
return VoteVariationType::unknown;
}
}
#pragma endregion
#pragma region AnnotatedString
struct AnnotatedString::Impl {
string annotation;
string value;
explicit Impl(string annotation, string value)
: annotation(move(annotation)), value(move(value))
{
}
[[nodiscard]] unique_ptr<AnnotatedString::Impl> clone() const
{
// TODO: verify string copy
return make_unique<AnnotatedString::Impl>(*this);
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
return hash_elems({annotation, value});
}
};
// Lifecycle Methods
AnnotatedString::AnnotatedString(const AnnotatedString &other) : pimpl(other.pimpl->clone()) {}
AnnotatedString::AnnotatedString(string annotation, string value)
: pimpl(new Impl(move(annotation), move(value)))
{
}
AnnotatedString::~AnnotatedString() = default;
AnnotatedString &AnnotatedString::operator=(const AnnotatedString &other)
{
if (this == &other) {
return *this;
}
pimpl = other.pimpl->clone();
return *this;
}
AnnotatedString &AnnotatedString::operator=(AnnotatedString &&other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
string AnnotatedString::getAnnotation() const { return pimpl->annotation; }
string AnnotatedString::getValue() const { return pimpl->value; }
// Interface Overrides
unique_ptr<ElementModQ> AnnotatedString::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> AnnotatedString::crypto_hash() const { return pimpl->crypto_hash(); }
#pragma endregion
#pragma region Language
struct Language::Impl {
string value;
string language;
explicit Impl(string value, string language) : value(move(value)), language(move(language))
{
}
[[nodiscard]] unique_ptr<Language::Impl> clone() const
{
// TODO: verify string copy
return make_unique<Language::Impl>(*this);
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
return hash_elems({value, language});
}
};
// Lifecycle Methods
Language::Language(const Language &other) : pimpl(other.pimpl->clone()) {}
Language::Language(string value, string language) : pimpl(new Impl(move(value), move(language)))
{
}
Language::~Language() = default;
Language &Language::operator=(const Language &other)
{
if (this == &other) {
return *this;
}
pimpl = other.pimpl->clone();
return *this;
}
Language &Language::operator=(Language &&other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
string Language::getValue() const { return pimpl->value; }
string Language::getLanguage() const { return pimpl->language; }
// Interface Overrides
unique_ptr<ElementModQ> Language::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> Language::crypto_hash() const { return pimpl->crypto_hash(); }
#pragma endregion
#pragma region InternationalizedText
struct InternationalizedText::Impl {
vector<unique_ptr<Language>> text;
explicit Impl(vector<unique_ptr<Language>> text) : text(move(text)) {}
[[nodiscard]] unique_ptr<InternationalizedText::Impl> clone() const
{
vector<unique_ptr<Language>> _text;
_text.reserve(text.size());
for (const auto &element : text) {
_text.push_back(make_unique<Language>(*element));
}
return make_unique<InternationalizedText::Impl>(move(_text));
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
vector<reference_wrapper<CryptoHashable>> refs;
refs.reserve(this->text.size());
for (const auto &i : this->text) {
refs.push_back(ref<CryptoHashable>(*i));
}
return hash_elems(refs);
}
};
// Lifecycle Methods
InternationalizedText::InternationalizedText(const InternationalizedText &other)
: pimpl(other.pimpl->clone())
{
}
InternationalizedText::InternationalizedText(vector<unique_ptr<Language>> text)
: pimpl(new Impl(move(text)))
{
}
InternationalizedText::~InternationalizedText() = default;
InternationalizedText &InternationalizedText::operator=(InternationalizedText other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
vector<reference_wrapper<Language>> InternationalizedText::getText() const
{
vector<reference_wrapper<Language>> refs;
refs.reserve(pimpl->text.size());
for (const auto &i : pimpl->text) {
refs.push_back(ref(*i));
}
return refs;
}
// Interface Overrides
unique_ptr<ElementModQ> InternationalizedText::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> InternationalizedText::crypto_hash() const
{
return pimpl->crypto_hash();
}
#pragma endregion
#pragma region ContactInformation
struct ContactInformation::Impl {
vector<string> addressLine;
vector<unique_ptr<AnnotatedString>> email;
vector<unique_ptr<AnnotatedString>> phone;
string name;
explicit Impl(string name) : name(move(name)) {}
explicit Impl(vector<string> addressLine, string name)
: addressLine(move(addressLine)), name(move(name))
{
}
explicit Impl(vector<string> addressLine, vector<unique_ptr<AnnotatedString>> phone,
string name)
: addressLine(move(addressLine)), phone(move(phone)), name(move(name))
{
}
explicit Impl(vector<string> addressLine, vector<unique_ptr<AnnotatedString>> email,
vector<unique_ptr<AnnotatedString>> phone, string name)
: addressLine(move(addressLine)), email(move(email)), phone(move(phone)),
name(move(name))
{
}
[[nodiscard]] unique_ptr<ContactInformation::Impl> clone() const
{
vector<string> _addressLine;
_addressLine.reserve(addressLine.size());
for (const auto &element : addressLine) {
_addressLine.push_back(element);
}
vector<unique_ptr<AnnotatedString>> _email;
_email.reserve(email.size());
for (const auto &element : email) {
_email.push_back(make_unique<AnnotatedString>(*element));
}
vector<unique_ptr<AnnotatedString>> _phone;
_phone.reserve(phone.size());
for (const auto &element : phone) {
_phone.push_back(make_unique<AnnotatedString>(*element));
}
return make_unique<ContactInformation::Impl>(move(_addressLine), move(_email),
move(_phone), name);
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
vector<reference_wrapper<CryptoHashable>> emailRefs;
emailRefs.reserve(this->email.size());
for (const auto &i : this->email) {
emailRefs.push_back(ref<CryptoHashable>(*i));
}
vector<reference_wrapper<CryptoHashable>> phoneRefs;
phoneRefs.reserve(this->phone.size());
for (const auto &i : this->phone) {
phoneRefs.push_back(ref<CryptoHashable>(*i));
}
return hash_elems({name, addressLine, emailRefs, phoneRefs});
}
};
// Lifecycle Methods
ContactInformation::ContactInformation(const ContactInformation &other)
: pimpl(other.pimpl->clone())
{
}
ContactInformation::ContactInformation(string name) : pimpl(new Impl(move(name))) {}
ContactInformation::ContactInformation(vector<string> addressLine, string name)
: pimpl(new Impl(move(addressLine), move(name)))
{
}
ContactInformation::ContactInformation(vector<string> addressLine,
vector<unique_ptr<AnnotatedString>> phone, string name)
: pimpl(new Impl(move(addressLine), move(phone), move(name)))
{
}
ContactInformation::ContactInformation(vector<string> addressLine,
vector<unique_ptr<AnnotatedString>> email,
vector<unique_ptr<AnnotatedString>> phone, string name)
: pimpl(new Impl(move(addressLine), move(email), move(phone), move(name)))
{
}
ContactInformation::~ContactInformation() = default;
ContactInformation &ContactInformation::operator=(ContactInformation other)
{
swap(pimpl, other.pimpl);
return *this;
}
vector<string> ContactInformation::getAddressLine() const { return pimpl->addressLine; }
vector<reference_wrapper<AnnotatedString>> ContactInformation::getEmail() const
{
vector<reference_wrapper<AnnotatedString>> refs;
refs.reserve(pimpl->email.size());
for (const auto &i : pimpl->email) {
refs.push_back(ref(*i));
}
return refs;
}
vector<reference_wrapper<AnnotatedString>> ContactInformation::getPhone() const
{
vector<reference_wrapper<AnnotatedString>> refs;
refs.reserve(pimpl->phone.size());
for (const auto &i : pimpl->phone) {
refs.push_back(ref(*i));
}
return refs;
}
// Property Getters
string ContactInformation::getName() const { return pimpl->name; }
// Interface Overrides
unique_ptr<ElementModQ> ContactInformation::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> ContactInformation::crypto_hash() const { return pimpl->crypto_hash(); }
#pragma endregion
#pragma region GeopoliticalUnit
struct GeopoliticalUnit::Impl : public ElectionObjectBase {
string name;
ReportingUnitType type;
unique_ptr<ContactInformation> contactInformation;
explicit Impl(const string &objectId, string name, const ReportingUnitType type,
unique_ptr<ContactInformation> contactInformation)
: name(move(name)), contactInformation(move(contactInformation))
{
this->object_id = objectId;
this->type = type;
}
explicit Impl(const string &objectId, string name, const ReportingUnitType type)
: name(move(name))
{
this->object_id = objectId;
this->type = type;
}
[[nodiscard]] unique_ptr<GeopoliticalUnit::Impl> clone() const
{
if (contactInformation != nullptr) {
auto _contactInfo = make_unique<ContactInformation>(*contactInformation);
return make_unique<GeopoliticalUnit::Impl>(object_id, name, type,
move(_contactInfo));
}
return make_unique<GeopoliticalUnit::Impl>(object_id, name, type);
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
if (contactInformation != nullptr) {
return hash_elems(
{object_id, name, getReportingUnitTypeString(type), contactInformation.get()});
}
return hash_elems({object_id, name, getReportingUnitTypeString(type)});
}
};
// Lifecycle Methods
GeopoliticalUnit::GeopoliticalUnit(const GeopoliticalUnit &other) : pimpl(other.pimpl->clone())
{
}
GeopoliticalUnit::GeopoliticalUnit(const string &objectId, const string &name,
const ReportingUnitType type)
: pimpl(new Impl(objectId, name, type))
{
}
GeopoliticalUnit::GeopoliticalUnit(const string &objectId, const string &name,
const ReportingUnitType type,
unique_ptr<ContactInformation> contactInformation)
: pimpl(new Impl(objectId, name, type, move(contactInformation)))
{
}
GeopoliticalUnit::~GeopoliticalUnit() = default;
GeopoliticalUnit &GeopoliticalUnit::operator=(GeopoliticalUnit other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
string GeopoliticalUnit::getObjectId() const { return pimpl->object_id; }
string GeopoliticalUnit::getName() const { return pimpl->name; }
ReportingUnitType GeopoliticalUnit::getType() const { return pimpl->type; }
ContactInformation *GeopoliticalUnit::getContactInformation() const
{
return pimpl->contactInformation.get();
}
// Interface Overrides
unique_ptr<ElementModQ> GeopoliticalUnit::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> GeopoliticalUnit::crypto_hash() const { return pimpl->crypto_hash(); }
#pragma endregion
#pragma region BallotStyle
struct BallotStyle::Impl : public ElectionObjectBase {
vector<string> geopoliticalUnitIds;
vector<string> partyIds;
string imageUri;
explicit Impl(const string &objectId, vector<string> geopoliticalUnitIds)
: geopoliticalUnitIds(move(geopoliticalUnitIds))
{
this->object_id = objectId;
}
explicit Impl(const string &objectId, vector<string> geopoliticalUnitIds,
vector<string> partyIds, const string &imageUri)
: geopoliticalUnitIds(move(geopoliticalUnitIds)), partyIds(move(partyIds)),
imageUri(imageUri)
{
this->object_id = objectId;
}
[[nodiscard]] unique_ptr<BallotStyle::Impl> clone() const
{
vector<string> _gpUnitIds;
_gpUnitIds.reserve(geopoliticalUnitIds.size());
for (const auto &element : geopoliticalUnitIds) {
_gpUnitIds.push_back(element);
}
vector<string> _partyIds;
_partyIds.reserve(partyIds.size());
for (const auto &element : partyIds) {
_partyIds.push_back(element);
}
return make_unique<BallotStyle::Impl>(object_id, _gpUnitIds, _partyIds, imageUri);
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
return hash_elems({object_id, geopoliticalUnitIds, geopoliticalUnitIds, imageUri});
}
};
// Lifecycle Methods
BallotStyle::BallotStyle(const BallotStyle &other) : pimpl(other.pimpl->clone()) {}
BallotStyle::BallotStyle(const string &objectId, vector<string> geopoliticalUnitIds)
: pimpl(new Impl(objectId, move(geopoliticalUnitIds)))
{
}
BallotStyle::BallotStyle(const string &objectId, vector<string> geopoliticalUnitIds,
vector<string> partyIds, const string &imageUri)
: pimpl(new Impl(objectId, move(geopoliticalUnitIds), move(partyIds), imageUri))
{
}
BallotStyle::~BallotStyle() = default;
BallotStyle &BallotStyle::operator=(BallotStyle other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
string BallotStyle::getObjectId() const { return pimpl->object_id; }
vector<string> BallotStyle::getGeopoliticalUnitIds() const
{
return pimpl->geopoliticalUnitIds;
}
vector<string> BallotStyle::getPartyIds() const { return pimpl->partyIds; }
string BallotStyle::getImageUri() const { return pimpl->imageUri; }
// Interface Overrides
unique_ptr<ElementModQ> BallotStyle::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> BallotStyle::crypto_hash() const { return pimpl->crypto_hash(); }
#pragma endregion
#pragma region Party
struct Party::Impl : public ElectionObjectBase {
unique_ptr<InternationalizedText> name;
string abbreviation;
string color;
string logoUri;
explicit Impl(const string &objectId) { this->object_id = objectId; }
explicit Impl(const string &objectId, const string &abbreviation, const string &color,
const string &logoUri)
: abbreviation(abbreviation), color(color), logoUri(logoUri)
{
this->object_id = objectId;
}
explicit Impl(const string &objectId, unique_ptr<InternationalizedText> name,
const string &abbreviation, const string &color, const string &logoUri)
: name(move(name)), abbreviation(abbreviation), color(color), logoUri(logoUri)
{
this->object_id = objectId;
}
[[nodiscard]] unique_ptr<Party::Impl> clone() const
{
if (name != nullptr) {
auto _name = make_unique<InternationalizedText>(*name);
return make_unique<Party::Impl>(object_id, move(_name), abbreviation, color,
logoUri);
}
return make_unique<Party::Impl>(object_id, abbreviation, color, logoUri);
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
if (name != nullptr) {
return hash_elems({object_id, name.get(), abbreviation, color, logoUri});
}
return hash_elems({object_id, abbreviation, color, logoUri});
}
};
// Lifecycle Methods
Party::Party(const Party &other) : pimpl(other.pimpl->clone()) {}
Party::Party(const string &objectId) : pimpl(new Impl(objectId)) {}
Party::Party(const string &objectId, unique_ptr<InternationalizedText> name,
const string &abbreviation, const string &color, const string &logoUri)
: pimpl(new Impl(objectId, move(name), abbreviation, color, logoUri))
{
}
Party::~Party() = default;
Party &Party::operator=(Party other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
string Party::getObjectId() const { return pimpl->object_id; }
InternationalizedText *Party::getName() const { return pimpl->name.get(); }
string Party::getAbbreviation() const { return pimpl->abbreviation; }
string Party::getColor() const { return pimpl->color; }
string Party::getLogoUri() const { return pimpl->logoUri; }
// Interface Overrides
unique_ptr<ElementModQ> Party::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> Party::crypto_hash() const { return pimpl->crypto_hash(); }
#pragma endregion
#pragma region Candidate
struct Candidate::Impl : public ElectionObjectBase {
unique_ptr<InternationalizedText> name;
string partyId;
string imageUri;
bool isWriteIn;
explicit Impl(const string &objectId, bool isWriteIn)
{
this->object_id = objectId;
this->isWriteIn = isWriteIn;
}
explicit Impl(const string &objectId, const string &partyId, const string &imageUri,
bool isWriteIn)
: partyId(partyId), imageUri(imageUri)
{
this->object_id = objectId;
this->isWriteIn = isWriteIn;
}
explicit Impl(const string &objectId, unique_ptr<InternationalizedText> name,
const string &partyId, const string &imageUri, bool isWriteIn)
: name(move(name)), partyId(partyId), imageUri(imageUri)
{
this->object_id = objectId;
this->isWriteIn = isWriteIn;
}
[[nodiscard]] unique_ptr<Candidate::Impl> clone() const
{
if (name != nullptr) {
auto _name = make_unique<InternationalizedText>(*name);
return make_unique<Candidate::Impl>(object_id, move(_name), partyId, imageUri,
isWriteIn);
}
return make_unique<Candidate::Impl>(object_id, partyId, imageUri, isWriteIn);
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
if (name != nullptr) {
return hash_elems({object_id, name.get(), partyId, imageUri});
}
return hash_elems({object_id, name.get(), partyId, imageUri});
}
};
// Lifecycle Methods
Candidate::Candidate(const Candidate &other) : pimpl(other.pimpl->clone()) {}
Candidate::Candidate(const string &objectId, bool isWriteIn)
: pimpl(new Impl(objectId, isWriteIn))
{
}
Candidate::Candidate(const string &objectId, unique_ptr<InternationalizedText> name,
const string &partyId, const string &imageUri, bool isWriteIn)
: pimpl(new Impl(objectId, move(name), partyId, imageUri, isWriteIn))
{
}
Candidate::~Candidate() = default;
Candidate &Candidate::operator=(Candidate other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
string Candidate::getObjectId() const { return pimpl->object_id; }
string Candidate::getCandidateId() const { return pimpl->object_id; }
InternationalizedText *Candidate::getName() const { return pimpl->name.get(); }
string Candidate::getPartyId() const { return pimpl->partyId; }
string Candidate::getImageUri() const { return pimpl->imageUri; }
bool Candidate::isWriteIn() const { return pimpl->isWriteIn; }
// Interface Overrides
unique_ptr<ElementModQ> Candidate::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> Candidate::crypto_hash() const { return pimpl->crypto_hash(); }
#pragma endregion
#pragma region SelectionDescription
struct SelectionDescription::Impl : public ElectionObjectBase {
string candidateId;
uint64_t sequenceOrder;
Impl(const string &objectId, const string &candidateId, const uint64_t sequenceOrder)
: candidateId(candidateId)
{
this->object_id = objectId;
this->sequenceOrder = sequenceOrder;
}
[[nodiscard]] unique_ptr<SelectionDescription::Impl> clone() const
{
return make_unique<SelectionDescription::Impl>(object_id, candidateId, sequenceOrder);
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
return hash_elems({object_id, sequenceOrder, candidateId});
}
};
// Lifecycle Methods
SelectionDescription::SelectionDescription(const SelectionDescription &other)
: pimpl(other.pimpl->clone())
{
}
SelectionDescription::SelectionDescription(const string &objectId, const string &candidateId,
const uint64_t sequenceOrder)
: pimpl(new Impl(objectId, candidateId, sequenceOrder))
{
}
SelectionDescription::~SelectionDescription() = default;
SelectionDescription &SelectionDescription::operator=(SelectionDescription other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
string SelectionDescription::getObjectId() const { return pimpl->object_id; }
string SelectionDescription::getCandidateId() const { return pimpl->candidateId; }
uint64_t SelectionDescription::getSequenceOrder() const { return pimpl->sequenceOrder; }
// Interface Overrides
unique_ptr<ElementModQ> SelectionDescription::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> SelectionDescription::crypto_hash() const
{
return pimpl->crypto_hash();
}
#pragma endregion
#pragma region ContestDescription
struct ContestDescription::Impl : ElectionObjectBase {
string electoralDistrictId;
uint64_t sequenceOrder;
VoteVariationType voteVariation;
uint64_t numberElected;
uint64_t votesAllowed;
string name;
unique_ptr<InternationalizedText> ballotTitle;
unique_ptr<InternationalizedText> ballotSubtitle;
vector<unique_ptr<SelectionDescription>> selections;
Impl(const string &objectId, const string &electoralDistrictId,
const uint64_t sequenceOrder, const VoteVariationType voteVariation,
const uint64_t numberElected, const string &name,
vector<unique_ptr<SelectionDescription>> selections)
: electoralDistrictId(electoralDistrictId), name(name), selections(move(selections))
{
this->object_id = objectId;
this->sequenceOrder = sequenceOrder;
this->voteVariation = voteVariation;
this->numberElected = numberElected;
this->votesAllowed = 0UL;
}
Impl(const string &objectId, const string &electoralDistrictId,
const uint64_t sequenceOrder, const VoteVariationType voteVariation,
const uint64_t numberElected, const uint64_t votesAllowed, const string &name,
unique_ptr<InternationalizedText> ballotTitle,
unique_ptr<InternationalizedText> ballotSubtitle,
vector<unique_ptr<SelectionDescription>> selections)
: electoralDistrictId(electoralDistrictId), name(name), ballotTitle(move(ballotTitle)),
ballotSubtitle(move(ballotSubtitle)), selections(move(selections))
{
this->object_id = objectId;
this->sequenceOrder = sequenceOrder;
this->voteVariation = voteVariation;
this->numberElected = numberElected;
this->votesAllowed = votesAllowed;
}
[[nodiscard]] unique_ptr<ContestDescription::Impl> clone() const
{
vector<unique_ptr<SelectionDescription>> _selections;
_selections.reserve(selections.size());
for (const auto &element : selections) {
_selections.push_back(make_unique<SelectionDescription>(*element));
}
// TODO: handle optional values
if (ballotTitle != nullptr) {
auto _ballotTitle = make_unique<InternationalizedText>(*ballotTitle);
auto _ballotSubtitle = make_unique<InternationalizedText>(*ballotSubtitle);
return make_unique<ContestDescription::Impl>(
object_id, electoralDistrictId, sequenceOrder, voteVariation, numberElected,
votesAllowed, name, move(_ballotTitle), move(_ballotSubtitle), move(_selections));
}
return make_unique<ContestDescription::Impl>(object_id, electoralDistrictId,
sequenceOrder, voteVariation,
numberElected, name, move(_selections));
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
vector<reference_wrapper<CryptoHashable>> selectionRefs;
selectionRefs.reserve(selections.size());
for (const auto &selection : selections) {
selectionRefs.push_back(ref<CryptoHashable>(*selection));
}
// TODO: handle optional values
if (ballotTitle != nullptr) {
return hash_elems({object_id, sequenceOrder, electoralDistrictId,
getVoteVariationTypeString(voteVariation),
ref<CryptoHashable>(*ballotTitle),
ref<CryptoHashable>(*ballotSubtitle), name, numberElected,
votesAllowed, selectionRefs});
}
return hash_elems({object_id, sequenceOrder, electoralDistrictId,
getVoteVariationTypeString(voteVariation), name, numberElected,
votesAllowed, selectionRefs});
}
};
// Lifecycle Methods
ContestDescription::ContestDescription(const ContestDescription &other)
: pimpl(other.pimpl->clone())
{
}
ContestDescription::ContestDescription(const string &objectId,
const string &electoralDistrictId,
const uint64_t sequenceOrder,
const VoteVariationType voteVariation,
const uint64_t numberElected, const string &name,
vector<unique_ptr<SelectionDescription>> selections)
: pimpl(new Impl(objectId, electoralDistrictId, sequenceOrder, voteVariation, numberElected,
name, move(selections)))
{
}
ContestDescription::ContestDescription(const string &objectId,
const string &electoralDistrictId,
const uint64_t sequenceOrder,
const VoteVariationType voteVariation,
const uint64_t numberElected,
const uint64_t votesAllowed, const string &name,
unique_ptr<InternationalizedText> ballotTitle,
unique_ptr<InternationalizedText> ballotSubtitle,
vector<unique_ptr<SelectionDescription>> selections)
: pimpl(new Impl(objectId, electoralDistrictId, sequenceOrder, voteVariation, numberElected,
votesAllowed, name, move(ballotTitle), move(ballotSubtitle),
move(selections)))
{
}
ContestDescription::~ContestDescription() = default;
ContestDescription &ContestDescription::operator=(ContestDescription other)
{
swap(pimpl, other.pimpl);
return *this;
}
//Property Getters
string ContestDescription::getObjectId() const { return pimpl->object_id; }
string ContestDescription::getElectoralDistrictId() const { return pimpl->electoralDistrictId; }
uint64_t ContestDescription::getSequenceOrder() const { return pimpl->sequenceOrder; }
VoteVariationType ContestDescription::getVoteVariation() const { return pimpl->voteVariation; }
uint64_t ContestDescription::getNumberElected() const { return pimpl->numberElected; }
uint64_t ContestDescription::getVotesAllowed() const { return pimpl->votesAllowed; }
string ContestDescription::getName() const { return pimpl->name; }
InternationalizedText *ContestDescription::getBallotTitle() const
{
return pimpl->ballotTitle.get();
}
InternationalizedText *ContestDescription::getBallotSubtitle() const
{
return pimpl->ballotSubtitle.get();
}
vector<reference_wrapper<SelectionDescription>> ContestDescription::getSelections() const
{
vector<reference_wrapper<SelectionDescription>> selections;
selections.reserve(pimpl->selections.size());
for (const auto &selection : pimpl->selections) {
selections.push_back(ref(*selection));
}
return selections;
}
// Interface Overrides
unique_ptr<ElementModQ> ContestDescription::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> ContestDescription::crypto_hash() const { return pimpl->crypto_hash(); }
#pragma endregion
#pragma region ContestDescriptionWithPlaceholders
struct ContestDescriptionWithPlaceholders::Impl : ElectionObjectBase {
vector<unique_ptr<SelectionDescription>> placeholderSelections;
explicit Impl(vector<unique_ptr<SelectionDescription>> placeholderSelections)
: placeholderSelections(move(placeholderSelections))
{
}
};
// Lifecycle Methods
ContestDescriptionWithPlaceholders::ContestDescriptionWithPlaceholders(
const ContestDescription &other,
vector<unique_ptr<SelectionDescription>> placeholderSelections)
: ContestDescription(other), pimpl(new Impl(move(placeholderSelections)))
{
}
ContestDescriptionWithPlaceholders::ContestDescriptionWithPlaceholders(
const string &objectId, const string &electoralDistrictId, const uint64_t sequenceOrder,
const VoteVariationType voteVariation, const uint64_t numberElected, const string &name,
vector<unique_ptr<SelectionDescription>> selections,
vector<unique_ptr<SelectionDescription>> placeholderSelections)
: ContestDescription(objectId, electoralDistrictId, sequenceOrder, voteVariation,
numberElected, name, move(selections)),
pimpl(new Impl(move(placeholderSelections)))
{
}
ContestDescriptionWithPlaceholders::ContestDescriptionWithPlaceholders(
const string &objectId, const string &electoralDistrictId, const uint64_t sequenceOrder,
const VoteVariationType voteVariation, const uint64_t numberElected,
const uint64_t votesAllowed, const string &name,
unique_ptr<InternationalizedText> ballotTitle,
unique_ptr<InternationalizedText> ballotSubtitle,
vector<unique_ptr<SelectionDescription>> selections,
vector<unique_ptr<SelectionDescription>> placeholderSelections)
: ContestDescription(objectId, electoralDistrictId, sequenceOrder, voteVariation,
numberElected, votesAllowed, name, move(ballotTitle),
move(ballotSubtitle), move(selections)),
pimpl(new Impl(move(placeholderSelections)))
{
}
ContestDescriptionWithPlaceholders::~ContestDescriptionWithPlaceholders() = default;
ContestDescriptionWithPlaceholders &
ContestDescriptionWithPlaceholders::operator=(ContestDescriptionWithPlaceholders other)
{
// TODO: swap the base as well via cast?
//(ContestDescription) this = (ContestDescription)other;
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
vector<reference_wrapper<SelectionDescription>>
ContestDescriptionWithPlaceholders::getPlaceholders() const
{
vector<reference_wrapper<SelectionDescription>> placeholders;
placeholders.reserve(pimpl->placeholderSelections.size());
for (const auto &selection : pimpl->placeholderSelections) {
placeholders.push_back(ref(*selection));
}
return placeholders;
}
// Public Methods
bool ContestDescriptionWithPlaceholders::IsPlaceholder(SelectionDescription &selection) const
{
for (const auto &placeholder : pimpl->placeholderSelections) {
if (selection.getObjectId() == placeholder->getObjectId()) {
return true;
}
}
return false;
}
reference_wrapper<SelectionDescription>
ContestDescriptionWithPlaceholders::selectionFor(string &selectionId)
{
for (const auto &selection : this->getSelections()) {
if (selectionId == selection.get().getObjectId()) {
return selection.get();
}
}
for (const auto &placeholder : this->getPlaceholders()) {
if (selectionId == placeholder.get().getObjectId()) {
return placeholder.get();
}
}
throw out_of_range("could not find the item");
}
#pragma endregion
#pragma region ElectionDescription
struct ElectionDescription::Impl {
string electionScopeId;
ElectionType type;
system_clock::time_point startDate;
system_clock::time_point endDate;
vector<unique_ptr<GeopoliticalUnit>> geopoliticalUnits;
vector<unique_ptr<Party>> parties;
vector<unique_ptr<Candidate>> candidates;
vector<unique_ptr<ContestDescription>> contests;
vector<unique_ptr<BallotStyle>> ballotStyles;
unique_ptr<InternationalizedText> name;
unique_ptr<ContactInformation> contactInformation;
Impl(const string &electionScopeId, ElectionType type, system_clock::time_point startDate,
system_clock::time_point endDate,
vector<unique_ptr<GeopoliticalUnit>> geopoliticalUnits,
vector<unique_ptr<Party>> parties, vector<unique_ptr<Candidate>> candidates,
vector<unique_ptr<ContestDescription>> contests,
vector<unique_ptr<BallotStyle>> ballotStyles)
: electionScopeId(electionScopeId), geopoliticalUnits(move(geopoliticalUnits)),
parties(move(parties)), candidates(move(candidates)), contests(move(contests)),
ballotStyles(move(ballotStyles))
{
this->type = type;
this->startDate = startDate;
this->endDate = endDate;
}
Impl(const string &electionScopeId, ElectionType type, system_clock::time_point startDate,
system_clock::time_point endDate,
vector<unique_ptr<GeopoliticalUnit>> geopoliticalUnits,
vector<unique_ptr<Party>> parties, vector<unique_ptr<Candidate>> candidates,
vector<unique_ptr<ContestDescription>> contests,
vector<unique_ptr<BallotStyle>> ballotStyles, unique_ptr<InternationalizedText> name,
unique_ptr<ContactInformation> contactInformation)
: electionScopeId(electionScopeId), geopoliticalUnits(move(geopoliticalUnits)),
parties(move(parties)), candidates(move(candidates)), contests(move(contests)),
ballotStyles(move(ballotStyles)), name(move(name)),
contactInformation(move(contactInformation))
{
this->type = type;
this->startDate = startDate;
this->endDate = endDate;
}
[[nodiscard]] unique_ptr<ElementModQ> crypto_hash() const
{
vector<reference_wrapper<CryptoHashable>> geopoliticalUnitRefs;
geopoliticalUnitRefs.reserve(geopoliticalUnits.size());
for (const auto &element : geopoliticalUnits) {
geopoliticalUnitRefs.push_back(ref<CryptoHashable>(*element));
}
vector<reference_wrapper<CryptoHashable>> partyRefs;
partyRefs.reserve(parties.size());
for (const auto &element : parties) {
partyRefs.push_back(ref<CryptoHashable>(*element));
}
vector<reference_wrapper<CryptoHashable>> contestRefs;
contestRefs.reserve(contests.size());
for (const auto &element : contests) {
contestRefs.push_back(ref<CryptoHashable>(*element));
}
vector<reference_wrapper<CryptoHashable>> ballotStyleRefs;
ballotStyleRefs.reserve(ballotStyles.size());
for (const auto &element : ballotStyles) {
ballotStyleRefs.push_back(ref<CryptoHashable>(*element));
}
// TODO: handle optional cases
if (name == nullptr) {
return hash_elems({electionScopeId, getElectionTypeString(type),
timePointToIsoString(startDate, "%FT%TZ"),
timePointToIsoString(endDate, "%FT%TZ"), geopoliticalUnitRefs,
partyRefs, contestRefs, ballotStyleRefs});
}
// TODO: verify hash time format is iso string
return hash_elems({electionScopeId, getElectionTypeString(type),
timePointToIsoString(startDate, "%FT%TZ"),
timePointToIsoString(endDate, "%FT%TZ"), ref<CryptoHashable>(*name),
ref<CryptoHashable>(*contactInformation), geopoliticalUnitRefs,
partyRefs, contestRefs, ballotStyleRefs});
}
};
// Lifecycle Methods
ElectionDescription::ElectionDescription(
const string &electionScopeId, ElectionType type, system_clock::time_point startDate,
system_clock::time_point endDate, vector<unique_ptr<GeopoliticalUnit>> geopoliticalUnits,
vector<unique_ptr<Party>> parties, vector<unique_ptr<Candidate>> candidates,
vector<unique_ptr<ContestDescription>> contests, vector<unique_ptr<BallotStyle>> ballotStyles)
: pimpl(new Impl(electionScopeId, type, startDate, endDate, move(geopoliticalUnits),
move(parties), move(candidates), move(contests), move(ballotStyles)))
{
}
ElectionDescription::ElectionDescription(
const string &electionScopeId, ElectionType type, system_clock::time_point startDate,
system_clock::time_point endDate, vector<unique_ptr<GeopoliticalUnit>> geopoliticalUnits,
vector<unique_ptr<Party>> parties, vector<unique_ptr<Candidate>> candidates,
vector<unique_ptr<ContestDescription>> contests, vector<unique_ptr<BallotStyle>> ballotStyles,
unique_ptr<InternationalizedText> name, unique_ptr<ContactInformation> contactInformation)
: pimpl(new Impl(electionScopeId, type, startDate, endDate, move(geopoliticalUnits),
move(parties), move(candidates), move(contests), move(ballotStyles),
move(name), move(contactInformation)))
{
}
ElectionDescription::~ElectionDescription() = default;
ElectionDescription &ElectionDescription::operator=(ElectionDescription other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
string ElectionDescription::getElectionScopeId() const { return pimpl->electionScopeId; }
ElectionType ElectionDescription::getElectionType() const { return pimpl->type; }
system_clock::time_point ElectionDescription::getStartDate() const { return pimpl->startDate; }
system_clock::time_point ElectionDescription::getEndDate() const { return pimpl->endDate; }
vector<reference_wrapper<GeopoliticalUnit>> ElectionDescription::getGeopoliticalUnits() const
{
vector<reference_wrapper<GeopoliticalUnit>> references;
references.reserve(pimpl->geopoliticalUnits.size());
for (auto &reference : pimpl->geopoliticalUnits) {
references.push_back(ref(*reference));
}
return references;
}
vector<reference_wrapper<Party>> ElectionDescription::getParties() const
{
vector<reference_wrapper<Party>> references;
references.reserve(pimpl->parties.size());
for (auto &reference : pimpl->parties) {
references.push_back(ref(*reference));
}
return references;
}
vector<reference_wrapper<Candidate>> ElectionDescription::getCandidates() const
{
vector<reference_wrapper<Candidate>> references;
references.reserve(pimpl->candidates.size());
for (auto &reference : pimpl->candidates) {
references.push_back(ref(*reference));
}
return references;
}
vector<reference_wrapper<ContestDescription>> ElectionDescription::getContests() const
{
vector<reference_wrapper<ContestDescription>> references;
references.reserve(pimpl->contests.size());
for (auto &reference : pimpl->contests) {
references.push_back(ref(*reference));
}
return references;
}
vector<reference_wrapper<BallotStyle>> ElectionDescription::getBallotStyles() const
{
vector<reference_wrapper<BallotStyle>> references;
references.reserve(pimpl->ballotStyles.size());
for (auto &reference : pimpl->ballotStyles) {
references.push_back(ref(*reference));
}
return references;
}
InternationalizedText *ElectionDescription::getName() const { return pimpl->name.get(); }
ContactInformation *ElectionDescription::getContactInformation() const
{
return pimpl->contactInformation.get();
}
// Public Methods
vector<uint8_t> ElectionDescription::toBson() const
{
return DescriptionSerializer::toBson(*this);
}
string ElectionDescription::toJson() { return DescriptionSerializer::toJson(*this); }
string ElectionDescription::toJson() const { return DescriptionSerializer::toJson(*this); }
unique_ptr<ElectionDescription> ElectionDescription::fromJson(string data)
{
return DescriptionSerializer::fromJson(move(data));
}
unique_ptr<ElectionDescription> ElectionDescription::fromBson(vector<uint8_t> data)
{
return DescriptionSerializer::fromBson(move(data));
}
unique_ptr<ElementModQ> ElectionDescription::crypto_hash() { return pimpl->crypto_hash(); }
unique_ptr<ElementModQ> ElectionDescription::crypto_hash() const
{
return pimpl->crypto_hash();
}
#pragma endregion
#pragma region InternalElectionDescription
struct InternalElectionDescription::Impl {
vector<unique_ptr<GeopoliticalUnit>> geopoliticalUnits;
vector<unique_ptr<ContestDescriptionWithPlaceholders>> contests;
vector<unique_ptr<BallotStyle>> ballotStyles;
unique_ptr<ElementModQ> descriptionHash;
Impl(vector<unique_ptr<GeopoliticalUnit>> geopoliticalUnits,
vector<unique_ptr<ContestDescriptionWithPlaceholders>> contests,
vector<unique_ptr<BallotStyle>> ballotStyles, unique_ptr<ElementModQ> descriptionHash)
: geopoliticalUnits(move(geopoliticalUnits)), contests(move(contests)),
ballotStyles(move(ballotStyles)), descriptionHash(move(descriptionHash))
{
}
};
// Lifecycle Methods
InternalElectionDescription::InternalElectionDescription(
vector<unique_ptr<GeopoliticalUnit>> geopoliticalUnits,
vector<unique_ptr<ContestDescriptionWithPlaceholders>> contests,
vector<unique_ptr<BallotStyle>> ballotStyles, const ElementModQ &descriptionHash)
: pimpl(new Impl(move(geopoliticalUnits), move(contests), move(ballotStyles),
make_unique<ElementModQ>(descriptionHash)))
{
}
InternalElectionDescription::InternalElectionDescription(const ElectionDescription &description)
: pimpl(new Impl(copyGeopoliticalUnits(description),
generateContestsWithPlaceholders(description),
copyBallotStyles(description), description.crypto_hash()))
{
}
InternalElectionDescription::~InternalElectionDescription() = default;
InternalElectionDescription &
InternalElectionDescription::operator=(InternalElectionDescription other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
const ElementModQ *InternalElectionDescription::getDescriptionHash() const
{
return pimpl->descriptionHash.get();
}
vector<reference_wrapper<GeopoliticalUnit>>
InternalElectionDescription::getGeopoliticalUnits() const
{
vector<reference_wrapper<GeopoliticalUnit>> references;
references.reserve(pimpl->geopoliticalUnits.size());
for (auto &reference : pimpl->geopoliticalUnits) {
references.push_back(ref(*reference));
}
return references;
}
vector<reference_wrapper<ContestDescriptionWithPlaceholders>>
InternalElectionDescription::getContests() const
{
vector<reference_wrapper<ContestDescriptionWithPlaceholders>> references;
references.reserve(pimpl->contests.size());
for (auto &reference : pimpl->contests) {
references.push_back(ref(*reference));
}
return references;
}
vector<reference_wrapper<BallotStyle>> InternalElectionDescription::getBallotStyles() const
{
vector<reference_wrapper<BallotStyle>> references;
references.reserve(pimpl->ballotStyles.size());
for (auto &reference : pimpl->ballotStyles) {
references.push_back(ref(*reference));
}
return references;
}
// Public Methods
vector<uint8_t> InternalElectionDescription::toBson() const
{
return InternalDescriptionSerializer::toBson(*this);
}
string InternalElectionDescription::toJson()
{
return InternalDescriptionSerializer::toJson(*this);
}
string InternalElectionDescription::toJson() const
{
return InternalDescriptionSerializer::toJson(*this);
}
unique_ptr<InternalElectionDescription> InternalElectionDescription::fromJson(string data)
{
return InternalDescriptionSerializer::fromJson(move(data));
}
unique_ptr<InternalElectionDescription>
InternalElectionDescription::fromBson(vector<uint8_t> data)
{
return InternalDescriptionSerializer::fromBson(move(data));
}
// Protected Methods
vector<unique_ptr<ContestDescriptionWithPlaceholders>>
InternalElectionDescription::generateContestsWithPlaceholders(
const ElectionDescription &description)
{
vector<unique_ptr<ContestDescriptionWithPlaceholders>> contests;
for (const auto &contest : description.getContests()) {
vector<unique_ptr<SelectionDescription>> placeholders;
placeholders.reserve(contest.get().getNumberElected());
uint32_t maxSequenceOrder = 0;
for (const auto &selection : contest.get().getSelections()) {
auto sequenceOrder = selection.get().getSequenceOrder();
if (sequenceOrder > maxSequenceOrder) {
maxSequenceOrder = sequenceOrder;
}
}
maxSequenceOrder += 1;
for (uint64_t i = 0; i < contest.get().getNumberElected(); i++) {
auto placeholder =
generatePlaceholderSelectionFrom(contest.get(), maxSequenceOrder + i);
placeholders.push_back(move(placeholder));
}
contests.push_back(
make_unique<ContestDescriptionWithPlaceholders>(contest.get(), move(placeholders)));
}
return contests;
}
vector<unique_ptr<GeopoliticalUnit>>
InternalElectionDescription::copyGeopoliticalUnits(const ElectionDescription &description)
{
vector<unique_ptr<GeopoliticalUnit>> collection;
auto source = description.getGeopoliticalUnits();
collection.reserve(source.size());
for (auto element : source) {
collection.push_back(make_unique<GeopoliticalUnit>(element.get()));
}
return collection;
}
vector<unique_ptr<BallotStyle>>
InternalElectionDescription::copyBallotStyles(const ElectionDescription &description)
{
vector<unique_ptr<BallotStyle>> collection;
auto source = description.getBallotStyles();
collection.reserve(source.size());
for (auto &element : source) {
collection.push_back(make_unique<BallotStyle>(element.get()));
}
return collection;
}
#pragma endregion
#pragma region CiphertextElectionContext
struct CiphertextElectionContext::Impl {
uint64_t numberOfGuardians;
uint64_t quorum;
unique_ptr<ElementModP> elGamalPublicKey;
unique_ptr<ElementModQ> descriptionHash;
unique_ptr<ElementModQ> cryptoBaseHash;
unique_ptr<ElementModQ> cryptoExtendedBaseHash;
Impl(uint64_t numberOfGuardians, uint64_t quorum, unique_ptr<ElementModP> elGamalPublicKey,
unique_ptr<ElementModQ> descriptionHash, unique_ptr<ElementModQ> cryptoBaseHash,
unique_ptr<ElementModQ> cryptoExtendedBaseHash)
: elGamalPublicKey(move(elGamalPublicKey)), descriptionHash(move(descriptionHash)),
cryptoBaseHash(move(cryptoBaseHash)),
cryptoExtendedBaseHash(move(cryptoExtendedBaseHash))
{
this->numberOfGuardians = numberOfGuardians;
this->quorum = quorum;
}
};
// Lifecycle Methods
CiphertextElectionContext::CiphertextElectionContext(
uint64_t numberOfGuardians, uint64_t quorum, unique_ptr<ElementModP> elGamalPublicKey,
unique_ptr<ElementModQ> descriptionHash, unique_ptr<ElementModQ> cryptoBaseHash,
unique_ptr<ElementModQ> cryptoExtendedBaseHash)
: pimpl(new Impl(numberOfGuardians, quorum, move(elGamalPublicKey), move(descriptionHash),
move(cryptoBaseHash), move(cryptoExtendedBaseHash)))
{
}
CiphertextElectionContext::~CiphertextElectionContext() = default;
CiphertextElectionContext &CiphertextElectionContext::operator=(CiphertextElectionContext other)
{
swap(pimpl, other.pimpl);
return *this;
}
// Property Getters
uint64_t CiphertextElectionContext::getNumberOfGuardians() const
{
return pimpl->numberOfGuardians;
}
uint64_t CiphertextElectionContext::getQuorum() const { return pimpl->quorum; }
const ElementModP *CiphertextElectionContext::getElGamalPublicKey() const
{
return pimpl->elGamalPublicKey.get();
}
const ElementModQ *CiphertextElectionContext::getDescriptionHash() const
{
return pimpl->descriptionHash.get();
}
const ElementModQ *CiphertextElectionContext::getCryptoBaseHash() const
{
return pimpl->cryptoBaseHash.get();
}
const ElementModQ *CiphertextElectionContext::getCryptoExtendedBaseHash() const
{
return pimpl->cryptoExtendedBaseHash.get();
}
// Public Methods
vector<uint8_t> CiphertextElectionContext::toBson() const
{
return ContextSerializer::toBson(*this);
}
string CiphertextElectionContext::toJson() const { return ContextSerializer::toJson(*this); }
unique_ptr<CiphertextElectionContext> CiphertextElectionContext::fromJson(string data)
{
return ContextSerializer::fromJson(move(data));
}
unique_ptr<CiphertextElectionContext> CiphertextElectionContext::fromBson(vector<uint8_t> data)
{
return ContextSerializer::fromBson(move(data));
}
// Public Static Methods
unique_ptr<CiphertextElectionContext>
CiphertextElectionContext::make(uint64_t numberOfGuardians, uint64_t quorum,
unique_ptr<ElementModP> elGamalPublicKey,
unique_ptr<ElementModQ> descriptionHash)
{
auto cryptoBaseHash = hash_elems(
{&const_cast<ElementModP &>(P()), &const_cast<ElementModQ &>(Q()),
&const_cast<ElementModP &>(G()), numberOfGuardians, quorum, descriptionHash.get()});
auto cryptoExtendedBaseHash = hash_elems({cryptoBaseHash.get(), elGamalPublicKey.get()});
return make_unique<CiphertextElectionContext>(
numberOfGuardians, quorum, move(elGamalPublicKey), move(descriptionHash),
move(cryptoBaseHash), move(cryptoExtendedBaseHash));
}
unique_ptr<CiphertextElectionContext>
CiphertextElectionContext::make(uint64_t numberOfGuardians, uint64_t quorum,
const string &elGamalPublicKeyInHex,
const string &descriptionHashInHex)
{
auto elGamalPublicKey = ElementModP::fromHex(elGamalPublicKeyInHex);
auto descriptionHash = ElementModQ::fromHex(descriptionHashInHex);
return make(numberOfGuardians, quorum, move(elGamalPublicKey), move(descriptionHash));
}
#pragma endregion
unique_ptr<SelectionDescription>
generatePlaceholderSelectionFrom(const ContestDescription &contest, uint64_t useSequenceId)
{
auto placeholderObjectId = contest.getObjectId() + "-" + to_string(useSequenceId);
return make_unique<SelectionDescription>(placeholderObjectId + "-placeholder",
placeholderObjectId + "-candidate", useSequenceId);
}
} // namespace electionguard
| 37
| 100
| 0.646481
|
msprotz
|
1335e4bcd9bf40fb7bf1b663775829b57b2d3ac0
| 1,907
|
cc
|
C++
|
src/MEPED_SteppingAction.cc
|
kbyando/meped-etelescope
|
cb1805cb8d1662a561fb1b7a405aecbfffac8f2c
|
[
"Apache-2.0"
] | null | null | null |
src/MEPED_SteppingAction.cc
|
kbyando/meped-etelescope
|
cb1805cb8d1662a561fb1b7a405aecbfffac8f2c
|
[
"Apache-2.0"
] | null | null | null |
src/MEPED_SteppingAction.cc
|
kbyando/meped-etelescope
|
cb1805cb8d1662a561fb1b7a405aecbfffac8f2c
|
[
"Apache-2.0"
] | null | null | null |
// NOAA POES Monte Carlo Simulation v1.4, 03/07/2010e
// MEPED :: Electron Telescope
// Karl Yando, Professor Robyn Millan
// Dartmouth College, 2008
//
// "MEPED_SteppingAction.cc"
#include "MEPED_SteppingAction.hh"
#include "MEPED_DetectorConstruction.hh"
#include "MEPED_EventAction.hh"
#include "G4Step.hh"
MEPED_SteppingAction::MEPED_SteppingAction(MEPED_DetectorConstruction* det, MEPED_EventAction* evt)
:detector(det), eventaction(evt)
{ }
MEPED_SteppingAction::~MEPED_SteppingAction()
{ }
// Collect Relevant Data for Output
void MEPED_SteppingAction::UserSteppingAction(const G4Step* aStep)
{
// Get Volume of the Current Step
G4VPhysicalVolume* volume
= aStep->GetPreStepPoint()->GetTouchableHandle()->GetVolume();
// Collect Energy and Track Length Step by Step
G4double edep = aStep->GetTotalEnergyDeposit();
// Data read from stepping dynamics and passed to EventAction.cc
if (aStep->GetPreStepPoint()->GetGlobalTime() == 0.) {
G4double eTotal = aStep->GetPreStepPoint()->GetKineticEnergy();
eventaction->StoreE(eTotal);
G4double x, y, z, px, py, pz; // Added 04/24/2008. Generalized
x = aStep->GetPreStepPoint()->GetPosition().x(); // coordinates
y = aStep->GetPreStepPoint()->GetPosition().y();
z = aStep->GetPreStepPoint()->GetPosition().z();
px = aStep->GetPreStepPoint()->GetMomentumDirection().x();
py = aStep->GetPreStepPoint()->GetMomentumDirection().y();
pz = aStep->GetPreStepPoint()->GetMomentumDirection().z();
eventaction->StoreQ(x, y, z); // Stores position data
eventaction->StoreP(px, py, pz); // Stores momentum data
}
G4double stepl = 0.;
if (aStep->GetTrack()->GetDefinition()->GetPDGCharge() != 0.)
stepl = aStep->GetStepLength();
// Declare "detector" volumes (recognized via reference to MEPED_DetectorC[...])
if (volume == detector->GetDete1()) eventaction->AddDete1(edep,stepl);
}
| 33.45614
| 99
| 0.712638
|
kbyando
|
13366cb9cf1dba78fb79af64657a9770aaa04e69
| 2,217
|
cpp
|
C++
|
src/raspberry/bridge_wiringpi.cpp
|
OpenWinch/test-workflow
|
bb2dc7ae955d5b6f248518182ec78dd02fc8e7e4
|
[
"Apache-2.0"
] | null | null | null |
src/raspberry/bridge_wiringpi.cpp
|
OpenWinch/test-workflow
|
bb2dc7ae955d5b6f248518182ec78dd02fc8e7e4
|
[
"Apache-2.0"
] | null | null | null |
src/raspberry/bridge_wiringpi.cpp
|
OpenWinch/test-workflow
|
bb2dc7ae955d5b6f248518182ec78dd02fc8e7e4
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file bridge_.cpp
* @author Mickael GAILLARD (mick.gaillard@gmail.com)
* @brief OpenWinch Project
*
* @copyright Copyright © 2020
*/
#include "openwinch.hpp"
#include "bridge_io.hpp"
#ifdef OW_BD_PI
#ifdef OW_BG_WIRINGPI
#ifdef __cplusplus
extern "C" {
#endif
#include <wiringPi.h>
#include <softPwm.h>
#ifdef __cplusplus
}
#endif
std::once_flag init_flag;
void Device::init_gpio() {
std::call_once(init_flag, [](){
#ifdef OW_BG_DEBUG
#endif // OW_BG_DEBUG
});
}
void Device::terminate_gpio() {
#ifdef OW_BG_DEBUG
#endif // OW_BG_DEBUG
}
OutputDevice::OutputDevice(uint8_t _pin): pin(_pin) {
Device::init_gpio();
pinMode(this->pin, OUTPUT);
// pullUpDnControl(this->pin, PUD_UP);
}
void OutputDevice::on() {
digitalWrite(this->pin, HIGH);
}
void OutputDevice::off() {
digitalWrite(this->pin, LOW);
}
PWMOutputDevice::PWMOutputDevice(uint8_t _pin): pin(_pin) {
Device::init_gpio();
if (this->pin == PWM_HARDWARE_PIN) {
pinMode(this->pin, PWM_OUTPUT);
} else {
softPwmCreate(this->pin, PWM_LOW, PWM_HIGH);
}
// pullUpDnControl(this->pin, PUD_UP);
}
void PWMOutputDevice::on() {
this->value = 1;
if (this->pin == PWM_HARDWARE_PIN) {
pwmWrite(this->pin, PWM_HIGH);
} else {
softPwmWrite(this->pin, PWM_HIGH);
}
}
void PWMOutputDevice::off() {
this->value = 0;
if (this->pin == PWM_HARDWARE_PIN) {
pwmWrite(this->pin, PWM_LOW);
} else {
softPwmWrite(this->pin, PWM_LOW);
}
}
void PWMOutputDevice::setValue(float _value) {
// Assertion
if (_value > 1) { _value = 1; }
if (_value < 0) { _value = 0; }
// Affectation
this->value = _value;
// Action
uint16_t lvalue = PWM_HIGH * value;
pwmWrite(this->pin, lvalue);
}
float PWMOutputDevice::getValue() {
return this->value;
}
InputDevice::InputDevice(uint8_t _pin): pin(_pin) {
Device::init_gpio();
pinMode(this->pin, INPUT);
pullUpDnControl(this->pin, PUD_UP);
// if (wiringPiISR(this->pin, INT_EDGE_FALLING, &__challSensorU) < 0) {
// error_exit("Unable to setup ISR U: ");
// }
}
void InputDevice::interruptEdge(InputDevice* instance) {
}
void InputDevice::when_pressed(void*) {
}
#endif // OW_BG_WIRINGPI
#endif // OW_BD_PI
| 17.595238
| 73
| 0.664862
|
OpenWinch
|
133aa04b1f093de1358e9fe5e042ee83e61a4cc5
| 1,869
|
cpp
|
C++
|
source/cxx/src/princomp.cpp
|
RBigData/coral2
|
1d20dde80319277cf59f84e9d1e47aeb9a1038f5
|
[
"BSD-2-Clause"
] | null | null | null |
source/cxx/src/princomp.cpp
|
RBigData/coral2
|
1d20dde80319277cf59f84e9d1e47aeb9a1038f5
|
[
"BSD-2-Clause"
] | null | null | null |
source/cxx/src/princomp.cpp
|
RBigData/coral2
|
1d20dde80319277cf59f84e9d1e47aeb9a1038f5
|
[
"BSD-2-Clause"
] | null | null | null |
#define ARMA_DONT_USE_WRAPPER
#include <armadillo>
#include <cstdio>
#include <mpi.h>
#include <string>
#define ALLREDUCE(X) MPI_Allreduce(MPI_IN_PLACE, X.memptr(), X.n_elem, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD)
class Shaq
{
public:
Shaq()
{
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
};
void ranshaq(int seed, arma::uword m_local, arma::uword n)
{
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
Data.resize(m_local, n);
arma::arma_rng::set_seed(seed + rank);
Data.randn();
nrows = m_local*size;
ncols = n;
};
void center()
{
arma::rowvec colmeans = sum(Data, 0);
ALLREDUCE(colmeans);
colmeans /= (double) nrows;
Data.each_row() -= colmeans;
};
arma::mat Data;
arma::uword nrows;
arma::uword ncols;
int rank;
};
// shows the first and last singular values, computed via covariance matrix
static arma::vec princomp(Shaq &X)
{
X.center();
arma::mat Cov = X.Data.t() * X.Data;
Cov /= X.nrows - 1;
ALLREDUCE(Cov);
arma::vec d;
eig_sym(d, Cov);
return sqrt(d);
}
static void get_dims(int argc, char **argv, arma::uword *m_local, arma::uword *n)
{
if (argc != 3)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0)
fprintf(stderr, "ERROR incorrect number of arguments: usage is 'mpirun -np n princomp num_local_rows num_global_cols\n");
exit(-1);
}
*m_local = (arma::uword) std::stoi(argv[1]);
*n = (arma::uword) std::stoi(argv[2]);
}
int main(int argc, char **argv)
{
arma::uword m_local, n;
MPI_Init(NULL, NULL);
get_dims(argc, argv, &m_local, &n);
Shaq X;
X.ranshaq(1234, m_local, n);
arma::vec d = princomp(X);
if (X.rank == 0)
printf("%f %f\n", d[n-1], d[0]);
MPI_Finalize();
return 0;
}
| 19.268041
| 127
| 0.59176
|
RBigData
|
133b45b975ea6f0a8ed32025afd2259f9248e408
| 2,380
|
cpp
|
C++
|
src/butil/class_name.cpp
|
wu-hanqing/incubator-brpc
|
7de0d7eaf6fca2b73b9f6018eb1b9128ce0a8f21
|
[
"Apache-2.0"
] | 5,379
|
2019-03-02T14:35:09.000Z
|
2022-03-31T14:19:19.000Z
|
src/butil/class_name.cpp
|
RichPure/incubator-brpc
|
846f7998799dd3c9103ef743fecc3c75d6dcb7ef
|
[
"BSL-1.0",
"Apache-2.0"
] | 921
|
2019-03-02T00:57:34.000Z
|
2022-03-30T08:58:23.000Z
|
src/butil/class_name.cpp
|
RichPure/incubator-brpc
|
846f7998799dd3c9103ef743fecc3c75d6dcb7ef
|
[
"BSL-1.0",
"Apache-2.0"
] | 1,641
|
2019-03-02T06:53:17.000Z
|
2022-03-31T11:35:07.000Z
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Date: Mon. Nov 7 14:47:36 CST 2011
#include <cxxabi.h> // __cxa_demangle
#include <string> // std::string
#include <stdlib.h> // free()
namespace butil {
// Try to convert mangled |name| to human-readable name.
// Returns:
// |name| - Fail to demangle |name|
// otherwise - demangled name
std::string demangle(const char* name) {
// mangled_name
// A NULL-terminated character string containing the name to
// be demangled.
// output_buffer:
// A region of memory, allocated with malloc, of *length bytes,
// into which the demangled name is stored. If output_buffer is
// not long enough, it is expanded using realloc. output_buffer
// may instead be NULL; in that case, the demangled name is placed
// in a region of memory allocated with malloc.
// length
// If length is non-NULL, the length of the buffer containing the
// demangled name is placed in *length.
// status
// *status is set to one of the following values:
// 0: The demangling operation succeeded.
// -1: A memory allocation failure occurred.
// -2: mangled_name is not a valid name under the C++ ABI
// mangling rules.
// -3: One of the arguments is invalid.
int status = 0;
char* buf = abi::__cxa_demangle(name, NULL, NULL, &status);
if (status == 0) {
std::string s(buf);
free(buf);
return s;
}
return std::string(name);
}
} // namespace butil
| 38.387097
| 72
| 0.65
|
wu-hanqing
|
1340445bddb6a9819e70226bb542b7aff2478b6b
| 7,531
|
cc
|
C++
|
tests/route_UT.cc
|
KnochJ/bus-sim
|
5c736ad74200e4e69b73e730661a66f355b6daaf
|
[
"FSFAP"
] | null | null | null |
tests/route_UT.cc
|
KnochJ/bus-sim
|
5c736ad74200e4e69b73e730661a66f355b6daaf
|
[
"FSFAP"
] | null | null | null |
tests/route_UT.cc
|
KnochJ/bus-sim
|
5c736ad74200e4e69b73e730661a66f355b6daaf
|
[
"FSFAP"
] | null | null | null |
/*
* Please note, the assessment tests for grading, will use the same include
* files, class names, and function names for accessing students' code that you
* find in this file. So students, if you write your code so that it passes
* these feedback tests, you can be assured that the auto-grader will at least
* be able to properly link with your code.
*/
/*******************************************************************************
* Includes
******************************************************************************/
#include <gtest/gtest.h>
#include "../src/bus.h"
#include "../src/stop.h"
#include "../src/route.h"
#include "../src/passenger.h"
/******************************************************
* TEST FEATURE SetUp
*******************************************************/
class RouteTests : public ::testing::Test {
protected:
// Bus* bus1;
Stop** CC_EB_stops;
Stop** CC_WB_stops;
Stop * stop_CC_EB_1; //West bank station
Stop * stop_CC_EB_2;
Stop * stop_CC_EB_3;
Stop * stop_CC_WB_1;
Stop * stop_CC_WB_2;
Stop * stop_CC_WB_3;
double* CC_EB_distances;
double* CC_WB_distances;
Route* CC1_EB;
Route* CC1_WB;
Route * route1;
Route * route2;
virtual void SetUp() {
CC_EB_stops = new Stop *[3];
CC_WB_stops = new Stop *[3];
stop_CC_EB_1 = new Stop(0, 43, -92.5); //West bank station
stop_CC_EB_2 = new Stop(1); //student union station
stop_CC_EB_3 = new Stop(2, 44.973820, -93.227117); //Oak St & Washington Ave
stop_CC_WB_1 = new Stop(2, 44.973820, -93.227117); //Oak St & Washington Ave
stop_CC_WB_2 = new Stop(1); //student union station
stop_CC_WB_3 = new Stop(0, 43, -92.5); //West bank station
CC_EB_stops[0] = stop_CC_EB_1;
CC_EB_stops[1] = stop_CC_EB_2;
CC_EB_stops[2] = stop_CC_EB_3;
CC_WB_stops[0] = stop_CC_WB_1;
CC_WB_stops[1] = stop_CC_WB_2;
CC_WB_stops[2] = stop_CC_WB_3;
CC_EB_distances = new double[3];
CC_WB_distances = new double[3];
CC_EB_distances[0] = 3;
CC_EB_distances[1] = 2;
CC_EB_distances[2] = 1;
CC_WB_distances[0] = 1;
CC_WB_distances[1] = 2;
CC_WB_distances[2] = 3;
CC1_EB = new Route("Campus Connector 1- Eastbound", CC_EB_stops, CC_EB_distances, 3, NULL);
CC1_WB = new Route("Campus Connector 1- Westbound", CC_WB_stops, CC_WB_distances, 3, NULL);
route1 = CC1_EB -> Clone();
route2 = CC1_WB -> Clone();
// bus1 = new Bus("bus-1", route1, route2, 60, 1);
}
virtual void TearDown() {
delete CC_EB_stops;
delete CC_WB_stops;
delete stop_CC_EB_1;
delete stop_CC_EB_2;
delete stop_CC_EB_3;
delete stop_CC_WB_1;
delete stop_CC_WB_2;
delete stop_CC_WB_3;
delete CC_EB_distances;
delete CC_WB_distances;
delete CC1_EB;
delete CC1_WB;
// delete bus1;
}
};
/*******************************************************************************
* Test Cases
******************************************************************************/
TEST_F(RouteTests, IsAtEnd) {
EXPECT_FALSE(route1 -> IsAtEnd()) << "IsAtEnd for route clone not working." << std::endl;
EXPECT_FALSE(route2 -> IsAtEnd()) << "IsAtEnd for route clone not working." << std::endl;
EXPECT_FALSE(route1 -> IsAtEnd()) << "IsAtEnd for route not working." << std::endl;
EXPECT_FALSE(route2 -> IsAtEnd()) << "IsAtEnd for route not working." << std::endl;
route1 -> NextStop();
EXPECT_FALSE(route1 -> IsAtEnd()) << "IsAtEnd for route clone not working after first stop." << std::endl;
route1 -> NextStop();
EXPECT_FALSE(route1 -> IsAtEnd()) << "IsAtEnd for route clone not working after second stop." << std::endl;
route1 -> NextStop();
EXPECT_FALSE(route1 -> IsAtEnd()) << "IsAtEnd for route clone not working after third stop." << std::endl;
route1 -> NextStop();
EXPECT_TRUE(route1 -> IsAtEnd()) << "IsAtEnd for route clone not working reaching end." << std::endl;
route1 -> NextStop();
EXPECT_TRUE(route1 -> IsAtEnd()) << "IsAtEnd for route clone not working when already at end." << std::endl;
};
TEST_F(RouteTests, GetSpecificStop) {
Stop * test0 = CC1_EB -> GetSpecificStop(0);
int id0 = test0 -> GetId();
EXPECT_EQ(id0, 0) << "GetSpecificStop not working" << std::endl;
Stop* test1 = CC1_EB -> GetSpecificStop(-1);
EXPECT_EQ(test1, nullptr) << "GetSpecificStop index -1 out of bounds not working" << std::endl;
Stop* test2 = CC1_EB -> GetSpecificStop(3);
EXPECT_EQ(test2, nullptr) << "GetSpecificStop index 3 out of bounds not working" << std::endl;
};
TEST_F(RouteTests, GetSpecificDistance) {
double test0 = CC1_EB -> GetSpecificDistance(0);
EXPECT_EQ(test0, 3) << "GetSpecificDistance not working" << std::endl;
double test1 = CC1_EB -> GetSpecificDistance(-1);
EXPECT_EQ(test1, -1) << "GetSpecificDistance index -1 out of bounds not working" << std::endl;
double test2 = CC1_EB -> GetSpecificDistance(3);
EXPECT_EQ(test2, -1) << "GetSpecificDistance index 3 out of bounds not working" << std::endl;
};
TEST_F(RouteTests, GetDestinationStop) {
Stop * test0 = CC1_EB -> GetDestinationStop();
EXPECT_EQ(test0, nullptr) << "Getting destination when not initialized is not working." << std::endl;
CC1_EB -> NextStop();
Stop * test1 = CC1_EB -> GetDestinationStop();
EXPECT_EQ(test1 -> GetId(), 0) << "Getting destination for first stop is not working." << std::endl;
CC1_EB -> NextStop();
Stop * test2 = CC1_EB -> GetDestinationStop();
EXPECT_EQ(test2 -> GetId(), 1) << "Getting destination for second stop is not working." << std::endl;
CC1_EB -> NextStop();
Stop * test3 = CC1_EB -> GetDestinationStop();
EXPECT_EQ(test3 -> GetId(), 2) << "Getting destination for third stop is not working." << std::endl;
};
TEST_F(RouteTests, GetPreviousDestinationStop) {
Stop * test0 = CC1_EB -> GetPreviousDestinationStop();
EXPECT_EQ(test0, nullptr) << "Getting previous destination when not initialized is not working." << std::endl;
CC1_EB -> NextStop();
Stop * test1 = CC1_EB -> GetPreviousDestinationStop();
EXPECT_EQ(test1 -> GetId(), 0) << "Getting previous destination for first stop is not working." << std::endl;
CC1_EB -> NextStop();
Stop * test2 = CC1_EB -> GetPreviousDestinationStop();
EXPECT_EQ(test2 -> GetId(), 0) << "Getting previous destination for second stop is not working." << std::endl;
CC1_EB -> NextStop();
Stop * test3 = CC1_EB -> GetPreviousDestinationStop();
EXPECT_EQ(test3 -> GetId(), 1) << "Getting previous destination for third stop is not working." << std::endl;
CC1_EB -> NextStop();
Stop * test4 = CC1_EB -> GetPreviousDestinationStop();
EXPECT_EQ(test4 -> GetId(), 1);
CC1_EB -> NextStop();
Stop * test5 = CC1_EB -> GetPreviousDestinationStop();
EXPECT_EQ(test5 -> GetId(), 1);
};
TEST_F(RouteTests, GetNextStopDistance) {
double test0 = CC1_EB -> GetNextStopDistance();
EXPECT_EQ(test0, -1) << "GetNextStopDistance is not setup properly" << std::endl;
CC1_EB -> NextStop();
double test1 = CC1_EB -> GetNextStopDistance();
EXPECT_EQ(test1, 3);
CC1_EB -> NextStop();
double test2 = CC1_EB -> GetNextStopDistance();
EXPECT_EQ(test2, 2);
CC1_EB -> NextStop();
double test3 = CC1_EB -> GetNextStopDistance();
EXPECT_EQ(test3, -1);
};
TEST_F(RouteTests, GetName) {
EXPECT_EQ(CC1_EB -> GetName() , "Campus Connector 1- Eastbound") << "GetName not setup properly." << std::endl;
EXPECT_EQ(CC1_WB -> GetName() , "Campus Connector 1- Westbound") << "GetName not setup properly." << std::endl;
};
| 36.558252
| 113
| 0.636303
|
KnochJ
|
13431a63a4004bbabf286b936771d2ea19b0e147
| 3,475
|
cpp
|
C++
|
niv/src/exchange/shared_memory.cpp
|
HBPVIS/nest-in-situ-vis
|
289956a9a352dcf76f3fa8a8c694a1b044df1b41
|
[
"Apache-2.0"
] | null | null | null |
niv/src/exchange/shared_memory.cpp
|
HBPVIS/nest-in-situ-vis
|
289956a9a352dcf76f3fa8a8c694a1b044df1b41
|
[
"Apache-2.0"
] | null | null | null |
niv/src/exchange/shared_memory.cpp
|
HBPVIS/nest-in-situ-vis
|
289956a9a352dcf76f3fa8a8c694a1b044df1b41
|
[
"Apache-2.0"
] | null | null | null |
//------------------------------------------------------------------------------
// nest in situ vis
//
// Copyright (c) 2017-2018 RWTH Aachen University, Germany,
// Virtual Reality & Immersive Visualisation Group.
//------------------------------------------------------------------------------
// License
//
// 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 "niv/exchange/shared_memory.hpp"
#include <string>
#include <utility>
#include <vector>
#include "conduit/conduit_node.hpp"
#include "conduit/conduit_schema.hpp"
namespace niv {
namespace exchange {
SharedMemory::SharedMemory(const Create&)
: segment_{boost::interprocess::create_only, SegmentName(), InitialSize()},
node_storage_{ConstructSchemaStorage(), ConstructDataStorage()},
reference_count_{ConstructReferenceCount()} {}
SharedMemory::SchemaStorage* SharedMemory::ConstructSchemaStorage() {
return segment_.construct<SchemaStorage>(SchemaStorageName())(
SchemaStorage::allocator_type(segment_.get_segment_manager()));
}
SharedMemory::DataStorage* SharedMemory::ConstructDataStorage() {
return segment_.construct<DataStorage>(DataStorageName())(
DataStorage::allocator_type(segment_.get_segment_manager()));
}
int* SharedMemory::ConstructReferenceCount() {
return segment_.construct<int>(ReferenceCountName())(0);
}
SharedMemory::SharedMemory(const Access&)
: segment_{boost::interprocess::open_only, SegmentName()},
node_storage_{FindSchemaStorage(), FindDataStorage()},
reference_count_{FindReferenceCount()} {
++(*reference_count_);
}
SharedMemory::SchemaStorage* SharedMemory::FindSchemaStorage() {
return segment_.find<SchemaStorage>(SchemaStorageName()).first;
}
SharedMemory::DataStorage* SharedMemory::FindDataStorage() {
return segment_.find<DataStorage>(DataStorageName()).first;
}
int* SharedMemory::FindReferenceCount() {
return segment_.find<int>(ReferenceCountName()).first;
}
SharedMemory::~SharedMemory() { --(*reference_count_); }
void SharedMemory::Destroy() {
segment_.destroy<SchemaStorage>(SchemaStorageName());
segment_.destroy<DataStorage>(DataStorageName());
boost::interprocess::shared_memory_object::remove(SegmentName());
}
std::size_t SharedMemory::GetFreeSize() const {
return segment_.get_free_memory();
}
void SharedMemory::Store(const conduit::Node& node) {
node_storage_.Store(node);
}
void SharedMemory::Update(const conduit::Node& node) {
node_storage_.Update(node);
}
conduit::Node SharedMemory::Read() { return node_storage_.Read(); }
conduit::Node SharedMemory::Listen() { return node_storage_.Listen(); }
void SharedMemory::Clear() { node_storage_.Clear(); }
bool SharedMemory::IsEmpty() const { return node_storage_.IsEmpty(); }
int SharedMemory::GetReferenceCount() const { return *reference_count_; }
} // namespace exchange
} // namespace niv
| 33.737864
| 80
| 0.69554
|
HBPVIS
|
134373ddd6377308c009d166499412c05d2ec103
| 5,632
|
cc
|
C++
|
shell/common/gin_converters/gfx_converter.cc
|
jdwalker/electron
|
69be9fa798dbb8d49a6550cdb287be900db13ac1
|
[
"MIT"
] | 16
|
2020-11-08T21:58:19.000Z
|
2022-03-23T20:11:13.000Z
|
shell/common/gin_converters/gfx_converter.cc
|
jdwalker/electron
|
69be9fa798dbb8d49a6550cdb287be900db13ac1
|
[
"MIT"
] | 350
|
2020-09-02T21:26:05.000Z
|
2022-03-31T20:18:55.000Z
|
shell/common/gin_converters/gfx_converter.cc
|
ColleenKeegan/electron
|
f3dc3997b10fd79439ad22ff5973b3d3541d8e9d
|
[
"MIT"
] | 5
|
2020-12-14T23:25:47.000Z
|
2021-08-12T02:31:25.000Z
|
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
namespace gin {
v8::Local<v8::Value> Converter<gfx::Point>::ToV8(v8::Isolate* isolate,
const gfx::Point& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
return dict.GetHandle();
}
bool Converter<gfx::Point>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Point* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
double x, y;
if (!dict.Get("x", &x) || !dict.Get("y", &y))
return false;
*out = gfx::Point(static_cast<int>(std::round(x)),
static_cast<int>(std::round(y)));
return true;
}
v8::Local<v8::Value> Converter<gfx::PointF>::ToV8(v8::Isolate* isolate,
const gfx::PointF& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
return dict.GetHandle();
}
bool Converter<gfx::PointF>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::PointF* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
float x, y;
if (!dict.Get("x", &x) || !dict.Get("y", &y))
return false;
*out = gfx::PointF(x, y);
return true;
}
v8::Local<v8::Value> Converter<gfx::Size>::ToV8(v8::Isolate* isolate,
const gfx::Size& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("width", val.width());
dict.Set("height", val.height());
return dict.GetHandle();
}
bool Converter<gfx::Size>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Size* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
int width, height;
if (!dict.Get("width", &width) || !dict.Get("height", &height))
return false;
*out = gfx::Size(width, height);
return true;
}
v8::Local<v8::Value> Converter<gfx::Rect>::ToV8(v8::Isolate* isolate,
const gfx::Rect& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
dict.Set("width", val.width());
dict.Set("height", val.height());
return dict.GetHandle();
}
bool Converter<gfx::Rect>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Rect* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
int x, y, width, height;
if (!dict.Get("x", &x) || !dict.Get("y", &y) || !dict.Get("width", &width) ||
!dict.Get("height", &height))
return false;
*out = gfx::Rect(x, y, width, height);
return true;
}
template <>
struct Converter<display::Display::AccelerometerSupport> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const display::Display::AccelerometerSupport& val) {
switch (val) {
case display::Display::AccelerometerSupport::AVAILABLE:
return StringToV8(isolate, "available");
case display::Display::AccelerometerSupport::UNAVAILABLE:
return StringToV8(isolate, "unavailable");
default:
return StringToV8(isolate, "unknown");
}
}
};
template <>
struct Converter<display::Display::TouchSupport> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const display::Display::TouchSupport& val) {
switch (val) {
case display::Display::TouchSupport::AVAILABLE:
return StringToV8(isolate, "available");
case display::Display::TouchSupport::UNAVAILABLE:
return StringToV8(isolate, "unavailable");
default:
return StringToV8(isolate, "unknown");
}
}
};
v8::Local<v8::Value> Converter<display::Display>::ToV8(
v8::Isolate* isolate,
const display::Display& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("id", val.id());
dict.Set("bounds", val.bounds());
dict.Set("workArea", val.work_area());
dict.Set("accelerometerSupport", val.accelerometer_support());
dict.Set("monochrome", val.is_monochrome());
dict.Set("colorDepth", val.color_depth());
dict.Set("colorSpace", val.color_spaces().GetRasterColorSpace().ToString());
dict.Set("depthPerComponent", val.depth_per_component());
dict.Set("size", val.size());
dict.Set("workAreaSize", val.work_area_size());
dict.Set("scaleFactor", val.device_scale_factor());
dict.Set("rotation", val.RotationAsDegree());
dict.Set("internal", val.IsInternal());
dict.Set("touchSupport", val.touch_support());
return dict.GetHandle();
}
} // namespace gin
| 34.552147
| 79
| 0.604936
|
jdwalker
|
13472aaad9749a0f86cdc35b3343d8f7b37281fe
| 570
|
cpp
|
C++
|
2. Yellow/Week 5/01. Inheritance/main.cpp
|
AmaterasuOmikami/The-art-of-modern-Cpp-development
|
4f0958197da92d216ee526384a6f7386a0fe62a0
|
[
"MIT"
] | 1
|
2022-02-17T10:58:58.000Z
|
2022-02-17T10:58:58.000Z
|
2. Yellow/Week 5/01. Inheritance/main.cpp
|
AmaterasuOmikami/The-art-of-modern-Cpp-development
|
4f0958197da92d216ee526384a6f7386a0fe62a0
|
[
"MIT"
] | null | null | null |
2. Yellow/Week 5/01. Inheritance/main.cpp
|
AmaterasuOmikami/The-art-of-modern-Cpp-development
|
4f0958197da92d216ee526384a6f7386a0fe62a0
|
[
"MIT"
] | null | null | null |
/*
* Определите до конца тела классов, соблюдая следующие требования:
* - Класс Dog должен являться наследником класса Animal.
* - Конструктор класса Dog должен принимать параметр типа string и
* инициализировать им поле Name в классе Animal.
*/
#include <iostream>
using namespace std;
class Animal {
public:
explicit Animal(string name)
: Name(move(name)) {}
const string Name;
};
class Dog : public Animal {
public:
explicit Dog(const string& name)
: Animal(name) {}
void Bark() {
cout << Name << " barks: woof!" << endl;
}
};
| 20.357143
| 67
| 0.673684
|
AmaterasuOmikami
|
13487b34f87a8e2378695c946db6ebcecde63d41
| 3,466
|
cpp
|
C++
|
hi_sampler/sampler/MachFiveImporter.cpp
|
MIDIculous/HISE
|
cb4c567bacb02c6bf7ca46a78daa06d3ce0b2b78
|
[
"Intel",
"MIT"
] | 1
|
2021-03-04T19:37:06.000Z
|
2021-03-04T19:37:06.000Z
|
hi_sampler/sampler/MachFiveImporter.cpp
|
psobot/HISE
|
cb97378039bae22c8eade3d4b699931bfd65c7d1
|
[
"Intel",
"MIT"
] | null | null | null |
hi_sampler/sampler/MachFiveImporter.cpp
|
psobot/HISE
|
cb97378039bae22c8eade3d4b699931bfd65c7d1
|
[
"Intel",
"MIT"
] | null | null | null |
namespace hise { using namespace juce;
StringArray MachFiveImporter::getLayerNames(const File &machFiveFile)
{
ScopedPointer<XmlElement> rootXml = XmlDocument::parse(machFiveFile);
if (rootXml != nullptr)
{
ValueTree root = ValueTree::fromXml(*rootXml);
ValueTree layers = root.getChildWithName("Program").getChildWithName("Layers");
StringArray layerNames;
for (int i = 0; i < layers.getNumChildren(); i++)
{
layerNames.add(layers.getChild(i).getProperty("DisplayName"));
}
return layerNames;
}
return StringArray();
}
ValueTree MachFiveImporter::getSampleMapValueTree(const File &machFiveFile, const String &layerName)
{
ScopedPointer<XmlElement> rootXml = XmlDocument::parse(machFiveFile);
if (rootXml != nullptr)
{
ValueTree root = ValueTree::fromXml(*rootXml);
ValueTree layers = root.getChildWithName("Program").getChildWithName("Layers");
ValueTree layer;
for (int i = 0; i < layers.getNumChildren(); i++)
{
if (layers.getChild(i).getProperty("DisplayName") == layerName)
{
layer = layers.getChild(i);
break;
}
}
if (layer.isValid())
{
ValueTree sampleMap("samplemap");
sampleMap.setProperty("ID", layer.getProperty("DisplayName"), nullptr);
ValueTree keyGroups = layer.getChildWithName("Keygroups");
for (int i = 0; i < keyGroups.getNumChildren(); i++)
{
ValueTree keyGroup = keyGroups.getChild(i);
ValueTree samplePlayer = keyGroup.getChildWithName("Oscillators").getChildWithName("SamplePlayer");
ValueTree sample = ValueTree("sample");
sample.setProperty("ID", i, nullptr);
sample.setProperty("FileName", samplePlayer.getProperty("SamplePath"), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::RootNote),
samplePlayer.getProperty("BaseNote"), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::KeyLow),
keyGroup.getProperty("LowKey"), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::KeyHigh),
keyGroup.getProperty("HighKey"), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::VeloLow),
keyGroup.getProperty("LowVelocity"), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::VeloHigh),
keyGroup.getProperty("HighVelocity"), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::RRGroup),
1, nullptr); // TODO
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::Volume),
Decibels::gainToDecibels<double>((double)keyGroup.getProperty("Gain")), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::Pan),
keyGroup.getProperty("Pan"), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::Pitch),
0, nullptr); // TODO
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::SampleStart),
samplePlayer.getChildWithName("PlaybackOptions").getProperty("Start"), nullptr);
sample.setProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::SampleEnd),
samplePlayer.getChildWithName("PlaybackOptions").getProperty("Stop"), nullptr);
sampleMap.addChild(sample, -1, nullptr);
}
return sampleMap;
}
}
return ValueTree();
}
} // namespace hise
| 32.392523
| 103
| 0.746682
|
MIDIculous
|
1349f07778caeaa9029f1de1d08bfbab60742c03
| 2,871
|
cpp
|
C++
|
src/as/multithread_task/task_interface.cpp
|
asmith-git/multithread-task
|
4b09b854aff2cf24651fd75bbed8d3019f8be379
|
[
"Apache-2.0"
] | null | null | null |
src/as/multithread_task/task_interface.cpp
|
asmith-git/multithread-task
|
4b09b854aff2cf24651fd75bbed8d3019f8be379
|
[
"Apache-2.0"
] | null | null | null |
src/as/multithread_task/task_interface.cpp
|
asmith-git/multithread-task
|
4b09b854aff2cf24651fd75bbed8d3019f8be379
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2017 Adam Smith
//
// 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 "as/multithread_task/task_interface.hpp"
#include "as/multithread_task/task_controller.hpp"
namespace as {
// task_interface
task_interface::task_interface() :
mState(STATE_INITIALISED),
mPauseLocation(0),
mPauseRequest(false)
{}
task_interface::~task_interface() {
}
task_interface::state task_interface::get_state() const {
return mState;
}
bool task_interface::should_resume() const {
return true;
}
void task_interface::execute(task_controller& aController) throw() {
// Try to execute the function
try{
// Check if the task has already been paused mid-execution
switch(mState) {
case STATE_INITIALISED:
mState = STATE_EXECUTING;
on_execute(aController);
break;
case STATE_PAUSED:
mState = STATE_EXECUTING;
on_resume(aController, mPauseLocation);
break;
}
// Catch an exception
}catch(std::exception&) {
set_exception(std::current_exception());
}
// If the task hasn't been paused then it is now complete
if(mState == STATE_EXECUTING) mState = STATE_COMPLETE;
}
bool task_interface::pause(task_controller& aController, uint8_t aLocation) throw() {
if(mState != task_interface::STATE_EXECUTING) return false;
mPauseRequest = false;
if(aController.on_pause(*this)) {
mState = task_interface::STATE_PAUSED;
mPauseLocation = aLocation;
return true;
}else {
return false;
}
}
bool task_interface::cancel(task_controller& aController) throw() {
if(mState != task_interface::STATE_INITIALISED) return false;
return aController.on_cancel(*this);
}
bool task_interface::reschedule(task_controller& aController, implementation::task_priority aPriority) throw() {
if(mState != task_interface::STATE_INITIALISED) return false;
return aController.on_reschedule(*this, aPriority);
}
bool task_interface::reinitialise() throw() {
if(mState != task_interface::STATE_COMPLETE) return false;
const bool tmp = on_reinitialise();
if(tmp) {
mState = STATE_INITIALISED;
mPauseLocation = 0;
mPauseRequest = false;
return true;
}
return false;
}
bool task_interface::is_pause_requested() const throw() {
return mPauseRequest;
}
void task_interface::request_pause() throw() {
if(mState == STATE_EXECUTING) mPauseRequest = true;
}
}
| 27.605769
| 113
| 0.730408
|
asmith-git
|
134c1ecf57b5efca1a1c1ac5178f89108e77076e
| 1,450
|
cpp
|
C++
|
test/catch/map-test.cpp
|
malachi-iot/estdlib
|
b455315c567ede54cea02eee5174036170d8fd26
|
[
"MIT"
] | 11
|
2019-01-04T12:02:02.000Z
|
2021-06-17T01:38:56.000Z
|
test/catch/map-test.cpp
|
malachi-iot/estdlib
|
b455315c567ede54cea02eee5174036170d8fd26
|
[
"MIT"
] | 5
|
2020-01-01T06:12:48.000Z
|
2022-03-29T20:49:21.000Z
|
test/catch/map-test.cpp
|
malachi-iot/estdlib
|
b455315c567ede54cea02eee5174036170d8fd26
|
[
"MIT"
] | 1
|
2020-10-19T11:10:13.000Z
|
2020-10-19T11:10:13.000Z
|
#include <catch.hpp>
#include <estd/map.h>
#include <estd/string.h>
#include "mem.h"
using namespace estd;
TEST_CASE("map-test")
{
SECTION("layer 1 map")
{
typedef layer1::map<int, int, 4> map_t;
estd::array<map_t::value_type, 4> buf;
#ifdef FEATURE_ESTD_LEGACY_ARRAY
buf[0].first = 0;
buf[1].first = 0;
buf[2].first = 0;
buf[3].first = 0;
map_t map(buf);
const int* result = map[3];
REQUIRE(result == NULLPTR);
#endif
}
SECTION("layer 1 map init list")
{
layer1::map<int, int, 4> map =
{
{ 1, 77 },
{ 2, 78 },
{ 3, 79 },
{ 4, 80 }
};
auto result = map[2];
REQUIRE(*result == 78);
}
SECTION("layer 2 map")
{
layer2::map<int, int, 4>::value_type buf[4] =
{
{ 1, 77 },
{ 2, 78 },
{ 4, 79 },
{ 5, 80 }
};
layer2::map<int, int, 4> map(buf);
const int* result = map[3];
REQUIRE(result == NULLPTR);
}
SECTION("layer 3 map")
{
layer3::map<int, int>::value_type buf[] =
{
{ 1, 77 },
{ 2, 78 },
{ 3, 79 },
{ 4, 80 }
};
layer3::map<int, int> map(buf);
const int* result = map[3];
REQUIRE(result != NULLPTR);
REQUIRE(*result == 79);
}
}
| 18.589744
| 53
| 0.428276
|
malachi-iot
|
134f18a3ab88ec3a236b4a635c131977d6789cb3
| 4,708
|
cpp
|
C++
|
src/main.cpp
|
FranciscoPDNeto/mpi-sum-reduction
|
0221b0ccada6de85be8c28a3745ba56d7942ec78
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
FranciscoPDNeto/mpi-sum-reduction
|
0221b0ccada6de85be8c28a3745ba56d7942ec78
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
FranciscoPDNeto/mpi-sum-reduction
|
0221b0ccada6de85be8c28a3745ba56d7942ec78
|
[
"MIT"
] | null | null | null |
#include <mpi.h>
#include <cassert>
#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#define MAINPROC 0
int main(int argc, char** argv) {
int numProcessors;
int myRank;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &numProcessors);
MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
std::string type;
auto startTime = std::chrono::high_resolution_clock::now();
float value = 0;
if (myRank == MAINPROC) {
std::cin >> type;
int elementsLenght;
std::cin >> elementsLenght;
const int elementsPerProcLenght = elementsLenght / (numProcessors - 1);
const int lastElementLenght =
elementsPerProcLenght + elementsLenght % (numProcessors - 1);
std::vector<float> elements;
elements.resize(lastElementLenght * (numProcessors - 1), 0.0);
for (int i = 0; i < elementsLenght; i++)
std::cin >> elements[i];
startTime = std::chrono::high_resolution_clock::now();
for (int dest = 1; dest < numProcessors; dest++) {
MPI_Send(&lastElementLenght, 1, MPI_INT, dest, 0, MPI_COMM_WORLD);
for (int i = lastElementLenght * (dest - 1);
i - lastElementLenght * (dest - 1) < lastElementLenght; i++) {
MPI_Send(&elements[i], 1, MPI_FLOAT, dest, 0, MPI_COMM_WORLD);
}
}
} else {
int elementsLenght;
MPI_Recv(&elementsLenght, 1, MPI_INT, 0, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
std::vector<float> elements;
elements.reserve(elementsLenght);
for (int i = 0; i < elementsLenght; i++) {
float element;
MPI_Recv(&element, 1, MPI_FLOAT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
elements.push_back(element);
}
const int processComm =
myRank % 2 == 0 ? myRank - 1
: myRank + 1 < numProcessors ? myRank + 1 : myRank;
// Manda todos os elementos para o outro processo.
for (int i = 1; i < elementsLenght; i++) {
const float operand2 = elements.back();
elements.pop_back();
MPI_Send(&operand2, 1, MPI_FLOAT, processComm, 0, MPI_COMM_WORLD);
}
// Recebe todos os elementos do outro processo.
for (int i = 0; i < elementsLenght - 1; i++) {
const float operand = elements.back();
elements.pop_back();
float operand2;
MPI_Recv(&operand2, 1, MPI_FLOAT, processComm, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
elements.push_back(operand + operand2);
}
value = elements.back();
elements.pop_back();
assert(elements.empty());
}
#ifndef SEQUENTIAL
// Remoção de processos excedentes
const int limit = pow(2, (int)log2(numProcessors)) -1;
const int numExceeds = (numProcessors - 1 - limit);
const int initIndex = numProcessors - 1 - numExceeds*2;
if (myRank > initIndex) {
if (myRank <= limit) {
float received;
MPI_Recv(&received, 1, MPI_FLOAT, myRank + numExceeds, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
value += received;
} else {
MPI_Send(&value, 1, MPI_FLOAT, myRank - numExceeds, 0, MPI_COMM_WORLD);
}
}
// Árvore de redução
if (myRank <= limit) {
if (myRank % 2 == 0)
MPI_Send(&value, 1, MPI_FLOAT, myRank + 1, 0, MPI_COMM_WORLD);
for (int d = 0; d < log2(limit + 1); d++) {
const int power = pow(2, d + 1);
if ((myRank + 1) % power != 0)
continue;
float received;
MPI_Recv(&received, 1, MPI_FLOAT, myRank - power / 2, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
value += received;
if (myRank != limit)
MPI_Send(&value, 1, MPI_FLOAT, myRank + power, 0, MPI_COMM_WORLD);
}
}
#else
const int limit = numProcessors - 1;
// Redução sequencial
if (myRank == MAINPROC)
MPI_Send(&value, 1, MPI_FLOAT, 1, 0, MPI_COMM_WORLD);
else if (myRank <= limit) {
float acc;
MPI_Recv(&acc, 1, MPI_FLOAT, myRank - 1, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
value += acc;
if (myRank != limit)
MPI_Send(&value, 1, MPI_FLOAT, myRank + 1, 0, MPI_COMM_WORLD);
}
#endif
if (myRank == limit)
MPI_Send(&value, 1, MPI_FLOAT, MAINPROC, 0, MPI_COMM_WORLD);
// Apresentação do resultado
if (myRank == MAINPROC) {
float sum;
MPI_Recv(&sum, 1, MPI_FLOAT, limit, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
const auto endTime = std::chrono::high_resolution_clock::now();
const auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
endTime - startTime);
if (type == "sum" || type == "all") {
std::cout << sum << std::endl;
}
if (type == "time" || type == "all") {
std::cout << duration.count() << std::endl;
}
}
MPI_Finalize();
return 0;
}
| 30.973684
| 99
| 0.620221
|
FranciscoPDNeto
|
13538a7b4390c75483f9bb78940212f8a49151ec
| 56
|
hpp
|
C++
|
src/boost_graph_planar_detail_face_iterators.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_graph_planar_detail_face_iterators.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_graph_planar_detail_face_iterators.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/graph/planar_detail/face_iterators.hpp>
| 28
| 55
| 0.839286
|
miathedev
|
13548d3a2be2e80e5cff44b2291af10f5cc2cef4
| 1,383
|
cpp
|
C++
|
helpers/tail.cpp
|
ideeinc/Deepagent
|
5d37ecf8e196d54d3914edc0c7b309377f772c1f
|
[
"BSD-3-Clause"
] | null | null | null |
helpers/tail.cpp
|
ideeinc/Deepagent
|
5d37ecf8e196d54d3914edc0c7b309377f772c1f
|
[
"BSD-3-Clause"
] | null | null | null |
helpers/tail.cpp
|
ideeinc/Deepagent
|
5d37ecf8e196d54d3914edc0c7b309377f772c1f
|
[
"BSD-3-Clause"
] | null | null | null |
#include <QFileInfo>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "tail.h"
Tail::Tail(const QString &filePath)
: ApplicationHelper(), path(filePath)
{ }
QByteArray Tail::tail(int maxlen, qint64 offset) const
{
static const qint64 BUFSIZE = sysconf(_SC_PAGE_SIZE);
QByteArray ret;
ret.reserve(qMin(maxlen, (int)BUFSIZE));
if (Q_UNLIKELY(path.isEmpty())) {
return ret;
}
int fd = open(path.toLocal8Bit(), O_RDONLY);
if (Q_UNLIKELY(fd < 0)) {
// error
return ret;
}
qint64 fsize = QFileInfo(path).size();
if (maxlen <= 0) {
maxlen = INT_MAX;
}
while (offset < fsize && ret.length() < maxlen) {
qint64 paOffset = offset & ~(BUFSIZE - 1); // must be page aligned
const qint64 len = qMin(qMin(BUFSIZE, fsize - paOffset), (qint64)maxlen - ret.length());
if (len > offset - paOffset) {
char *addr = (char*)mmap(nullptr, len, PROT_READ, MAP_PRIVATE, fd, paOffset);
if (addr == MAP_FAILED) {
// error
break;
}
ret.append(addr + offset - paOffset, len - (offset - paOffset)); // deep copy
munmap(addr, len);
offset = paOffset + len;
}
// next loop
fsize = QFileInfo(path).size();
}
close(fd);
return ret;
}
| 24.263158
| 96
| 0.556038
|
ideeinc
|
135618d3fdccbe5f47a6caa7b342baab54481a4c
| 11,285
|
cpp
|
C++
|
games/games/BrickBash/BrickBash.cpp
|
timskillman/pico-arcade
|
9c036f8507319bd6e4552e86a6d7211ed74a2670
|
[
"MIT"
] | 1
|
2022-02-27T15:46:13.000Z
|
2022-02-27T15:46:13.000Z
|
games/games/BrickBash/BrickBash.cpp
|
timskillman/pico-arcade
|
9c036f8507319bd6e4552e86a6d7211ed74a2670
|
[
"MIT"
] | null | null | null |
games/games/BrickBash/BrickBash.cpp
|
timskillman/pico-arcade
|
9c036f8507319bd6e4552e86a6d7211ed74a2670
|
[
"MIT"
] | null | null | null |
#include "BrickBash.h"
#include "hardware/adc.h"
#include "pico/stdlib.h" // stdlib
#include "hardware/irq.h" // interrupts
#include "hardware/pwm.h" // pwm
#include "hardware/sync.h" // wait for interrupt
// Audio PIN is to match some of the design guide shields.
#define AUDIO_PIN 28 // you can change this to whatever you like
/*
* This include brings in static arrays which contain audio samples.
* if you want to know how to make these please see the python code
* for converting audio samples into static arrays.
*/
#include "thats_cool.h"
int wav_position = 0;
/*
* PWM Interrupt Handler which outputs PWM level and advances the
* current sample.
*
* We repeat the same value for 8 cycles this means sample rate etc
* adjust by factor of 8 (this is what bitshifting <<3 is doing)
*
*/
void pwm_interrupt_handler() {
pwm_clear_irq(pwm_gpio_to_slice_num(AUDIO_PIN));
if (wav_position < (WAV_DATA_LENGTH<<3) - 1) {
// set pwm level
// allow the pwm value to repeat for 8 cycles this is >>3
pwm_set_gpio_level(AUDIO_PIN, WAV_DATA[wav_position>>3]);
wav_position++;
} else {
// reset to start
wav_position = 0;
}
}
void BrickBash::init(PicoDisplay &pico_display)
{
ball.x = (rand() % 200)<<16;
ball.y = (rand() % 120)<<16;
ball.dx = (1<<15);
ball.dy = (int32_t)(-1.0f * 65536.f);
ball.r = 5;
bat.r = 30;
bat.x = hw - bat.r/2;
bat.y = h - 22;
btx = (float)bat.x;
bricks[0][0] = 0b0011111101111110;
bricks[0][1] = 0b0111111010111111;
bricks[0][2] = 0b0110110101011011;
bricks[0][3] = 0b0111001010100111;
bricks[0][4] = 0b0111110101011111;
bricks[0][5] = 0b0111111010111111;
bricks[0][6] = 0b0000000000000000; //0b0011110101011110;
bricks[0][7] = 0b0000000000000000;
bricks[1][0] = 0b0011111111111110;
bricks[1][1] = 0b0111001001001111;
bricks[1][2] = 0b0111110000111111;
bricks[1][3] = 0b0111001111001111;
bricks[1][4] = 0b0110010110100111;
bricks[1][5] = 0b0111001111001111;
bricks[1][6] = 0b0111110000111111;
bricks[1][7] = 0b0011111111111110;
bricks[2][0] = 0b0011111111111110;
bricks[2][1] = 0b0111001111100111;
bricks[2][2] = 0b0110110111011011;
bricks[2][3] = 0b0111001111100111;
bricks[2][4] = 0b0111111111111111;
bricks[2][5] = 0b0111001111100111;
bricks[2][6] = 0b0111110000011111;
bricks[2][7] = 0b0011111111111110;
bricks[3][0] = 0b0111111111111111;
bricks[3][1] = 0b0111111111111111;
bricks[3][2] = 0b0111111111111111;
bricks[3][3] = 0b0111111111111111;
bricks[3][4] = 0b0111111111111111;
bricks[3][5] = 0b0111111111111111;
bricks[3][6] = 0b0111111111111111;
bricks[3][7] = 0b0111111111111111;
bricks[4][0] = 0b0111111000111111;
bricks[4][1] = 0b0111111000111111;
bricks[4][2] = 0b0111000000000111;
bricks[4][3] = 0b0111000000000111;
bricks[4][4] = 0b0111111000111111;
bricks[4][5] = 0b0111111000111111;
bricks[4][6] = 0b0111111000111111;
bricks[4][7] = 0b0111111111111111;
bricks[5][0] = 0b0011101111111000;
bricks[5][1] = 0b0101011111100111;
bricks[5][2] = 0b0110111111011111;
bricks[5][3] = 0b0111001110111111;
bricks[5][4] = 0b0111110001111111;
bricks[5][5] = 0b0111101110011111;
bricks[5][6] = 0b0111011111100111;
bricks[5][7] = 0b0111101111111000;
bricks[6][0] = 0b0001111111111100;
bricks[6][1] = 0b0011001111100110;
bricks[6][2] = 0b0110110111011011;
bricks[6][3] = 0b0111001111100111;
bricks[6][4] = 0b0111110000011111;
bricks[6][5] = 0b0111001111100111;
bricks[6][6] = 0b0011110000011110;
bricks[6][7] = 0b0001111111111100;
bricks[7][0] = 0b0111111111111111;
bricks[7][1] = 0b0101010101010101;
bricks[7][2] = 0b0110101010101011;
bricks[7][3] = 0b0101010101010101;
bricks[7][4] = 0b0110101010101011;
bricks[7][5] = 0b0101010101010101;
bricks[7][6] = 0b0110101010101011;
bricks[7][7] = 0b0111111111111111;
brick_cols[0] = pico_display.create_pen(255, 0, 0);
brick_cols[1] = pico_display.create_pen(255, 128, 0);
brick_cols[2] = pico_display.create_pen(255, 255, 0);
brick_cols[3] = pico_display.create_pen(0, 255, 0);
brick_cols[4] = pico_display.create_pen(0, 128, 255);
brick_cols[5] = pico_display.create_pen(0, 0, 255);
brick_cols[6] = pico_display.create_pen(128, 0, 255);
brick_cols[7] = pico_display.create_pen(255, 0, 128);
bat_cols[0] = pico_display.create_pen(0, 0, 255);
bat_cols[1] = pico_display.create_pen(0, 255, 255);
bat_cols[2] = pico_display.create_pen(255, 255, 255);
bat_cols[3] = pico_display.create_pen(0, 255, 255);
bat_cols[4] = pico_display.create_pen(0, 0, 255);
lives = 3;
score = 0;
level = 0;
start = true;
skycols.clear();
skycols.push_back(Colour(0,0,128));
skycols.push_back(Colour(0,0,0));
/*
stdio_init_all();
set_sys_clock_khz(176000, true);
gpio_set_function(AUDIO_PIN, GPIO_FUNC_PWM);
int audio_pin_slice = pwm_gpio_to_slice_num(AUDIO_PIN);
// Setup PWM interrupt to fire when PWM cycle is complete
pwm_clear_irq(audio_pin_slice);
pwm_set_irq_enabled(audio_pin_slice, true);
// set the handle function above
irq_set_exclusive_handler(PWM_IRQ_WRAP, pwm_interrupt_handler);
irq_set_enabled(PWM_IRQ_WRAP, true);
// Setup PWM for audio output
pwm_config config = pwm_get_default_config();
/* Base clock 176,000,000 Hz divide by wrap 250 then the clock divider further divides
* to set the interrupt rate.
*
* 11 KHz is fine for speech. Phone lines generally sample at 8 KHz
*
*
* So clkdiv should be as follows for given sample rate
* 8.0f for 11 KHz
* 4.0f for 22 KHz
* 2.0f for 44 KHz etc
*/
/*
pwm_config_set_clkdiv(&config, 8.0f);
pwm_config_set_wrap(&config, 250);
pwm_init(audio_pin_slice, &config, true);
pwm_set_gpio_level(AUDIO_PIN, 0);
__wfi();
*/
}
void BrickBash::update(PicoDisplay &pico_display)
{
draw_game(pico_display);
game_status(pico_display);
collisions(pico_display);
controllers(pico_display);
//Display score
pico_display.set_pen(255, 255, 255);
pico_display.text("SCORE:"+std::to_string(score),Point(hw-50,h-15),0,fontsize);
pico_display.set_pen(0, 255, 0);
pico_display.text("HIGHSCORE:"+std::to_string(highscore),Point(0,0),0,fontsize);
//pico_display.text("ACD0:"+std::to_string(adc),Point(hw-80,h-50),0,2);
//adc_select_input(1);
//adc = adc_read();
//pico_display.text("ACD1:"+std::to_string(adc),Point(hw-80,h-30),0,2);
}
void BrickBash::draw_game(PicoDisplay &pico_display)
{
//pico_display.set_pen(0, 0, 0);
//pico_display.clear();
pico_display.gradientRect(Rect(0,0,w,h),skycols);
//Draw bat
for (int i=0; i<5; i++) {
pico_display.set_pen(bat_cols[i]);
pico_display.line(Point(bat.x, bat.y + i*2 - 1), Point(bat.x + bat.r, bat.y + i*2 - 1));
}
//Draw ball
pico_display.set_pen(128, 255, 128);
pico_display.circle(Point(ball.x>>16, ball.y>>16), ball.r);
//Draw bricks
for (int i=0; i<8; i++)
{
if (bricks[level][i] != 0) {
for (int32_t xb=0; xb<16; xb++) {
if (bricks[level][i] & (1<<xb)) {
pico_display.set_pen(brick_cols[i]);
pico_display.rectangle(Rect(brickx + xb*brickWidth, bricky+i*brickHeight, brickWidth-2, brickHeight-1));
}
}
}
}
}
void BrickBash::game_status(PicoDisplay &pico_display)
{
//Check game status
if (lives==0) {
pico_display.set_pen(255, 255, 255);
pico_display.text("GAME OVER!",Point(hw-65,hh-30),500,fontsize+1);
if (highscore < score) {
pico_display.text("YOU GOT THE",Point(hw-50,hh),500,fontsize);
pico_display.text("HIGH SCORE!",Point(hw-50,hh+30),500,fontsize);
pico_display.text("WELL DONE!!",Point(hw-50,hh+60),500,fontsize);
}
else
{
pico_display.text("YOU STILL NEED TO",Point(hw-75,hh),500,fontsize);
pico_display.text("BEAT THE HIGH SCORE",Point(hw-85,hh+30),500,fontsize);
pico_display.text("OF "+std::to_string(highscore),Point(hw-40,hh+60),500,fontsize);
}
if (pico_display.is_pressed(pico_display.X)) {
while (!pico_display.is_pressed(pico_display.X));
if (highscore < score) highscore = score;
init(pico_display);
}
}
else
{
if (start) {
if (lives==3 && level==0) {
pico_display.set_pen(255,255,255);
pico_display.text("BREAKOUT!",Point(hw-60,hh-25),500,fontsize+1);
pico_display.text("Press A to START",Point(hw-70,hh),500,fontsize);
if (pico_display.is_pressed(pico_display.X)) {
while (!pico_display.is_pressed(pico_display.X));
start = false;
}
}
else
{
if (pico_display.is_pressed(pico_display.X)) {
while (!pico_display.is_pressed(pico_display.X));
start = false;
}
}
ball.x = (bat.x + 10)<<16;
ball.y = (bat.y - 4)<<16;
}
else
{
ball.x += ball.dx * speed;
ball.y += ball.dy * speed;
}
pico_display.set_pen(128, 255, 128);
for (int i=0; i<lives-1; i++) {
pico_display.circle(Point(w-i*10-5, h-10), ball.r);
}
}
}
void BrickBash::collisions(PicoDisplay &pico_display)
{
//Ball hit walls?
int32_t bx = ball.x >> 16;
int32_t by = ball.y >> 16;
if(bx > pico_display.bounds.w || ball.x < 0) ball.dx *= -1;
if(ball.y < 0) ball.dy *= -1;
//Ball hit ground?
if (by >= pico_display.bounds.h) {
if (lives>0) lives--;
ball.dy *= -1;
start = true;
}
//Ball hit bat?
if((by >= (bat.y-3) && by <= bat.y) && (bx > bat.x && bx<(bat.x+bat.r))) {
ball.dy *= -1;
ball.dx = ((bx-(bat.x+bat.r/2))<<16) / 16;
}
//Ball hit bricks? ...
bool finished = true;
for (int i=0; i<8; i++)
{
if (bricks[level][i] != 0) {
if (by >= bricky+brickHeight*i && by < bricky+brickHeight*(i+1)) {
int32_t xb = (bx-brickx) / brickWidth; //16
if (xb>=0 && xb<16) {
if (bricks[level][i] & (1<<xb)) {
bricks[level][i] = bricks[level][i] ^ (1<<xb);
ball.dy *= -1;
score += (8-i)*20;
}
}
}
finished = false;
}
}
if (finished) {
level = (level+1) % maxlevels;
lives++;
start = true;
}
}
void BrickBash::controllers(PicoDisplay &pico_display)
{
//Check controllers
/*
adc_select_input(1);
float adc = (float)adc_read() / 4096.f - 0.5f;
float nx = btx - adc*8.f;
if (nx > 0 && nx < (PicoDisplay::WIDTH-bat.r)) { btx = nx; bat.x = btx; }
//bat.x += (adc*2.f); //(PicoDisplay::WIDTH-bat.r) * adc;
*/
if(pico_display.is_pressed(pico_display.L) && bat.x < (PicoDisplay::WIDTH-bat.r)) {
bat.x += speed;
}
if(pico_display.is_pressed(pico_display.R) && bat.x>0) {
bat.x -= speed;
}
}
| 30.41779
| 116
| 0.606646
|
timskillman
|
13571219a31c25d46c896598bd3a1081c8f966fe
| 332
|
hpp
|
C++
|
contracts/eosio.system/include/eosio.system/get_trx_id.hpp
|
eosnationftw/geojsonpoint
|
e5b38051753d760cbe2759d542e5c9b92a70c002
|
[
"MIT"
] | null | null | null |
contracts/eosio.system/include/eosio.system/get_trx_id.hpp
|
eosnationftw/geojsonpoint
|
e5b38051753d760cbe2759d542e5c9b92a70c002
|
[
"MIT"
] | null | null | null |
contracts/eosio.system/include/eosio.system/get_trx_id.hpp
|
eosnationftw/geojsonpoint
|
e5b38051753d760cbe2759d542e5c9b92a70c002
|
[
"MIT"
] | 2
|
2019-08-12T10:55:42.000Z
|
2021-04-13T14:09:39.000Z
|
#include <eosio/transaction.hpp>
#include <eosio/crypto.hpp>
namespace eosiosystem {
checksum256 get_trx_id()
{
size_t size = eosio::transaction_size();
char buf[size];
size_t read = eosio::read_transaction( buf, size );
check( size == read, "read_transaction failed");
return eosio::sha256( buf, read );
}
}
| 20.75
| 55
| 0.683735
|
eosnationftw
|
135875e079e7cce7cf5cfab249e7d6f607d47fd6
| 324
|
hpp
|
C++
|
include/IClickable.hpp
|
Zouizoui78/memory
|
2023ea9b17e676b0cdeaa37f692f50cfbda908a5
|
[
"MIT"
] | null | null | null |
include/IClickable.hpp
|
Zouizoui78/memory
|
2023ea9b17e676b0cdeaa37f692f50cfbda908a5
|
[
"MIT"
] | null | null | null |
include/IClickable.hpp
|
Zouizoui78/memory
|
2023ea9b17e676b0cdeaa37f692f50cfbda908a5
|
[
"MIT"
] | null | null | null |
#ifndef ICLICKABLE
#define ICLICKABLE
#include <functional>
template <class T>
class IClickable
{
public:
virtual void setCallback(std::function<bool (T* clicked)>) = 0;
virtual bool click() = 0;
virtual void setClickable(bool clickable) = 0;
virtual bool isClickable() = 0;
};
#endif // ICLICKABLE
| 17.052632
| 67
| 0.685185
|
Zouizoui78
|
135bc60e0e07cc17e6ca1c8ec363298aad8e9f9c
| 3,015
|
cxx
|
C++
|
Modules/Wrappers/ApplicationEngine/test/otbWrapperImageInterface.cxx
|
heralex/OTB
|
c52b504b64dc89c8fe9cac8af39b8067ca2c3a57
|
[
"Apache-2.0"
] | null | null | null |
Modules/Wrappers/ApplicationEngine/test/otbWrapperImageInterface.cxx
|
heralex/OTB
|
c52b504b64dc89c8fe9cac8af39b8067ca2c3a57
|
[
"Apache-2.0"
] | null | null | null |
Modules/Wrappers/ApplicationEngine/test/otbWrapperImageInterface.cxx
|
heralex/OTB
|
c52b504b64dc89c8fe9cac8af39b8067ca2c3a57
|
[
"Apache-2.0"
] | 1
|
2020-10-15T09:37:30.000Z
|
2020-10-15T09:37:30.000Z
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning(disable : 4786)
#endif
#include "otbWrapperApplicationRegistry.h"
int otbWrapperImageInterface(int argc, char* argv[])
{
if (argc < 4)
{
std::cerr << "Usage: " << argv[0] << " application_path input_image output_txt" << std::endl;
return EXIT_FAILURE;
}
std::string path = argv[1];
std::string input = argv[2];
std::string output = argv[3];
otb::Wrapper::ApplicationRegistry::SetApplicationPath(path);
otb::Wrapper::Application::Pointer app1 = otb::Wrapper::ApplicationRegistry::CreateApplication("Smoothing");
if (app1.IsNull())
{
std::cerr << "Failed to create application" << std::endl;
return EXIT_FAILURE;
}
std::ofstream ofs(output);
if (!ofs.is_open())
{
fprintf(stderr, "Error, can't open file");
return EXIT_FAILURE;
}
app1->SetParameterString("in", input);
app1->Execute();
ofs << "Size: " << app1->GetImageSize("out") << std::endl;
ofs << "Origin: " << app1->GetImageOrigin("out") << std::endl;
ofs << "Spacing: " << app1->GetImageSpacing("out") << std::endl;
ofs << "Keywordlist: " << std::endl;
otb::ImageKeywordlist kwl = app1->GetImageKeywordlist("out");
kwl.Print(ofs);
ofs << "ProjectionRef:" << std::endl;
ofs << app1->GetImageProjection("out") << std::endl;
itk::MetaDataDictionary dict = app1->GetImageMetaData("out");
ofs << "Dictionary keys:" << std::endl;
for (auto& key : dict.GetKeys())
{
ofs << " - " << key << std::endl;
}
otb::Wrapper::ImageBaseType::RegionType region;
region.SetIndex(0, 10);
region.SetIndex(1, 10);
region.SetSize(0, 7);
region.SetSize(1, 7);
ofs << "RAM usage (in Bytes): " << app1->PropagateRequestedRegion("out", region) << std::endl;
ofs << "Input requested: " << app1->GetImageRequestedRegion("in") << std::endl;
otb::Wrapper::Application::Pointer app2 = otb::Wrapper::ApplicationRegistry::CreateApplication("ConcatenateImages");
app2->AddParameterStringList("il", input);
app2->AddParameterStringList("il", input);
app2->Execute();
ofs << "Number of bands [il]: " << app2->GetImageNbBands("il", 0) << "+" << app2->GetImageNbBands("il", 1) << std::endl;
ofs << "Number of bands [out]: " << app2->GetImageNbBands("out") << std::endl;
ofs.close();
return EXIT_SUCCESS;
}
| 31.736842
| 122
| 0.66335
|
heralex
|
135f2a7c8306398982674a90b91a9af0bcca1b8e
| 6,409
|
cpp
|
C++
|
SourceCode/case studies/String Manipulation/Program 10-24.cpp
|
aceiro/poo2019
|
0f93d22296f43a8b024a346f510c00314817d2cf
|
[
"MIT"
] | 1
|
2019-04-09T18:29:38.000Z
|
2019-04-09T18:29:38.000Z
|
SourceCode/case studies/String Manipulation/Program 10-24.cpp
|
aceiro/poo2019
|
0f93d22296f43a8b024a346f510c00314817d2cf
|
[
"MIT"
] | null | null | null |
SourceCode/case studies/String Manipulation/Program 10-24.cpp
|
aceiro/poo2019
|
0f93d22296f43a8b024a346f510c00314817d2cf
|
[
"MIT"
] | null | null | null |
// This program prints a simple form letter reminding a customer
// of an overdue account balance.
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
// Function Prototypes
void printLetter(char *, char *, char *, char *, char *);
void getInfo(char *, char *, char *, char *, char *);
void getSal(char *);
void printline(const char *, int&);
// Strings that make up the form letter
const char part1[] = "Dear ";
const char part2[] = "Our records show that your account has a"
" balance of $";
const char part3[] = " and a past due amount of $";
const char part4[] = "Your last payment was on ";
const char part5[] = "Since we haven't heard from you in some"
" time, would you please take a moment to send"
" us a check for the past-due amount? We value"
" your business and look forward to serving you"
" in the future.\n\n";
const char part6[] = "Sincerely,\n";
const char part7[] = "The Management\n\n";
const char part8[] = "P.S. If you've already sent your payment, ignore"
" this reminder.";
int main()
{
char salutation[4]; // To hold the salutation
char lastName[16]; // Customer's last name
char lastPayment[16]; // Date of last payment
char balance[9]; // Account balace
char pastDue[9]; // Amount past due
char again; // To hold Y or N
do
{
// Call getInfo to get input from the user
getInfo(salutation, lastName, balance, pastDue,
lastPayment);
cout << "\n\n";
// Now print the form letter
printLetter(salutation, lastName, balance, pastDue,
lastPayment);
cout << "\n\nDo another letter? (Y/N) ";
cin >> again;
} while (toupper(again) == 'Y');
return 0;
}
//*****************************************************************
// Definition of function getInfo. *
// This function allows the user to enter the following items: *
// salutation, last name, account balance, past due amount, and *
// date of last payment. The function arguments are pointers to *
// strings where the input will be stored. *
//*****************************************************************
void getInfo(char *sal, char *lname, char *bal, char *due,
char *lastPay)
{
getSal(sal);
cout << "Last name: ";
cin >> lname;
lname[0] = toupper(lname[0]);
cout << "Account balance: ";
cin >> bal;
cout << "Past due Amount: ";
cin >> due;
cout << "Date of last payment (MM/DD/YYYY): ";
cin >> lastPay;
}
//****************************************************************
// Definition of function getSal. *
// This function gives the user a menu from which to pick a *
// suitable title for the letter's addressee. The choices are *
// Mr. and Ms. The choice will be copied to the address pointed *
// to by sal. *
//****************************************************************
void getSal(char *sal)
{
int choice;
do
{
cout << "salutation:\n";
cout << "\t1) Mr.\n";
cout << "\t2) Ms.\n";
cout << "Select one: ";
cin >> choice;
} while (choice != 1 && choice != 2);
if (choice == 1)
strcpy(sal, "Mr.");
else
strcpy(sal, "Ms.");
}
//*************************************************************
// Definition of function printLetter. *
// This function prints the form letter. The parameters are *
// pointers to the fields that contain user input. *
//*************************************************************
void printLetter(char *sal, char *lname, char *bal, char *due,
char *lastPay)
{
int position;
// Print the salutation part of the letter
position = 0; // Start a new line.
printline(part1, position);
cout << sal << " " << lname << ":" << endl << endl;
// Print the body of the letter
position = 0; // Start a new line.
printline(part2, position);
cout << bal; // Print account balance.
// Add length of balance to position.
position += strlen(bal);
printline(part3, position);
cout << due << ". "; // Print past due amount
position += strlen(due)+ 2;
// Add length of due and the period and space at the
// end of the sentence to position.
printline(part4, position);
cout << lastPay << ". "; // Print date of last payment.
// Now Add length of lastPay and the period and space at the
// end of the sentence to position.
position += strlen(lastPay) + 2;
printline(part5, position);
// Print the closing.
position = 0; // Start a new line.
printline(part6, position);
position = 0; // Start a new line.
printline(part7, position);
// Print the PS reminder.
position = 0; // Start a new line.
printline(part8, position);
}
//*******************************************************************
// Definition of function printline. *
// This function has two parameters: line and startCount. *
// The string pointed to by line is printed. startCount is the *
// starting position of the line in an 80 character field. There *
// are 10-character left and right margins within the 80 *
// character field. The function performs word-wrap by looking *
// for space character within the line at or after the 60th *
// character. A new line is started when a space is found, or the *
// end of the field is reached. *
//*******************************************************************
void printline(const char *line, int &startCount)
{
int charCount = 0;
if (startCount >= 70) // If the line is already at
{ // or past the right margin...
cout << "\n"; // Start a new line.
startCount = 0; // Reset startCount.
}
// The following while loop cycles through the string
// printing it one character at a time. It watches for
// spaces after the 60th position so word-wrap may be
// performed.
while (line[charCount] != '\0')
{
if (startCount >= 60 && line[charCount] == ' ')
{
cout << " \n"; // Print right margin.
charCount++; // Skip over the space.
startCount = 0;
}
if (startCount == 0)
{
cout << " "; // Print left margin.
startCount = 10;
}
cout.put(line[charCount]); // Print the character.
charCount++; // Update subscript.
startCount++; // Update position counter.
}
}
| 32.866667
| 71
| 0.561554
|
aceiro
|
1367ad766b1b8a682f2f33cf1a57bab0d8938afc
| 2,203
|
cpp
|
C++
|
src/condvartest.cpp
|
sda1969/cpptest
|
068b8401664e3c13f969abcfc93ea4f60028a73a
|
[
"Unlicense"
] | null | null | null |
src/condvartest.cpp
|
sda1969/cpptest
|
068b8401664e3c13f969abcfc93ea4f60028a73a
|
[
"Unlicense"
] | null | null | null |
src/condvartest.cpp
|
sda1969/cpptest
|
068b8401664e3c13f969abcfc93ea4f60028a73a
|
[
"Unlicense"
] | null | null | null |
/*
* condvartest.cpp
*
* Created on: 16 февр. 2017 г.
* Author: dmitry
*/
// condition_variable example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <unistd.h>
#include "condvartest.h"
namespace cvtest{
const int numThreads = 5;
static std::mutex mtx;
static std::condition_variable request, confirm;
static bool ready = false;
static uint32_t data;
// универсальный работник
static void worker (int id) {
uint32_t localData;
while(1){
// блок выполняющийся с обязательно закрытом мютексом
{
// ждем заявку мютекс закрыт
std::unique_lock<std::mutex> lck(mtx);
while (!ready){
request.wait(lck);
}
// mutex по прежнему закрыт здесь
ready = false; // обработал заявку
localData = data;
std::cout << "thread id=" << id << " local data=" << localData << '\n';
confirm.notify_one(); //заявка принята в работу
} // <--мютекс открывается здесь
// имитация длительной самостоятельной работы над локальным комплектом данных
// мютекс открыт что-бы не мешать другим в это время принимать и выполнять заявки
sleep(1);
}
}
void condvartest_run(){
std::thread threads[10];
// numThreads одинаковых исполнителей работы, мне все равно кто ее сделает
for (int i = 0; i < numThreads; ++i){
threads[i] = std::thread(worker, i);
}
std::cout << numThreads << " workers ready to serve my requests...\n";
while(1){
//lock нужен что-бы работники не могли отменить задание до его запуска
std::unique_lock<std::mutex> lck(mtx);
//std::cout << "go!" << '\n';
data++; // новые данные для очередного работника
ready = true;
request.notify_one(); //заявка работнику
//не будем посылать заявки до тех пор, пока последняя не будет принята в работу
while (ready){
confirm.wait(lck);
}
}
for (auto& th : threads) th.join();
}
}
| 27.886076
| 89
| 0.597367
|
sda1969
|
1368ef09c31178285277be45e38842472ec0401e
| 2,704
|
cc
|
C++
|
xapian-core_scws-1.2.18/api/leafpostlist.cc
|
iveteran/xapian-scws
|
670d0475f61bb4ff7cf1b1979abc4dea5d3acddf
|
[
"BSD-2-Clause"
] | null | null | null |
xapian-core_scws-1.2.18/api/leafpostlist.cc
|
iveteran/xapian-scws
|
670d0475f61bb4ff7cf1b1979abc4dea5d3acddf
|
[
"BSD-2-Clause"
] | null | null | null |
xapian-core_scws-1.2.18/api/leafpostlist.cc
|
iveteran/xapian-scws
|
670d0475f61bb4ff7cf1b1979abc4dea5d3acddf
|
[
"BSD-2-Clause"
] | null | null | null |
/** @file leafpostlist.cc
* @brief Abstract base class for leaf postlists.
*/
/* Copyright (C) 2007,2009,2014 Olly Betts
* Copyright (C) 2009 Lemur Consulting Ltd
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <config.h>
#include "xapian/weight.h"
#include "leafpostlist.h"
#include "omassert.h"
#include "debuglog.h"
using namespace std;
LeafPostList::~LeafPostList()
{
delete weight;
}
Xapian::doccount
LeafPostList::get_termfreq_min() const
{
return get_termfreq();
}
Xapian::doccount
LeafPostList::get_termfreq_max() const
{
return get_termfreq();
}
Xapian::doccount
LeafPostList::get_termfreq_est() const
{
return get_termfreq();
}
void
LeafPostList::set_termweight(const Xapian::Weight * weight_)
{
// This method shouldn't be called more than once on the same object.
Assert(!weight);
weight = weight_;
need_doclength = weight->get_sumpart_needs_doclength_();
}
Xapian::weight
LeafPostList::get_maxweight() const
{
return weight ? weight->get_maxpart() : 0;
}
Xapian::weight
LeafPostList::get_weight() const
{
if (!weight) return 0;
Xapian::termcount doclen = 0;
// Fetching the document length is work we can avoid if the weighting
// scheme doesn't use it.
if (need_doclength) doclen = get_doclength();
double sumpart = weight->get_sumpart(get_wdf(), doclen);
AssertRel(sumpart, <=, weight->get_maxpart());
return sumpart;
}
Xapian::weight
LeafPostList::recalc_maxweight()
{
return LeafPostList::get_maxweight();
}
TermFreqs
LeafPostList::get_termfreq_est_using_stats(
const Xapian::Weight::Internal & stats) const
{
LOGCALL(MATCH, TermFreqs, "LeafPostList::get_termfreq_est_using_stats", stats);
if (term.empty()) {
RETURN(TermFreqs(stats.collection_size, stats.rset_size));
}
map<string, TermFreqs>::const_iterator i = stats.termfreqs.find(term);
Assert(i != stats.termfreqs.end());
RETURN(i->second);
}
Xapian::termcount
LeafPostList::count_matching_subqs() const
{
return weight ? 1 : 0;
}
| 25.271028
| 83
| 0.723003
|
iveteran
|
136e614a75587e9782ff17aa740f653a1b73a52c
| 734
|
hpp
|
C++
|
cmdstan/stan/lib/stan_math/stan/math/fwd/arr/fun/log_sum_exp.hpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/stan/math/fwd/arr/fun/log_sum_exp.hpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/stan/math/fwd/arr/fun/log_sum_exp.hpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MATH_FWD_ARR_FUN_LOG_SUM_EXP_HPP
#define STAN_MATH_FWD_ARR_FUN_LOG_SUM_EXP_HPP
#include <stan/math/fwd/core.hpp>
#include <stan/math/prim/arr/fun/log_sum_exp.hpp>
#include <vector>
namespace stan {
namespace math {
template <typename T>
fvar<T>
log_sum_exp(const std::vector<fvar<T> >& v) {
using std::exp;
std::vector<T> vals(v.size());
for (size_t i = 0; i < v.size(); ++i)
vals[i] = v[i].val_;
T deriv(0.0);
T denominator(0.0);
for (size_t i = 0; i < v.size(); ++i) {
T exp_vi = exp(vals[i]);
denominator += exp_vi;
deriv += v[i].d_ * exp_vi;
}
return fvar<T>(log_sum_exp(vals), deriv / denominator);
}
}
}
#endif
| 23.677419
| 61
| 0.592643
|
yizhang-cae
|
13744c9a458373e2aad9e6b728cbf65601543950
| 6,311
|
inl
|
C++
|
include/vke/Core/Utils/inl/TCSmartPtr.inl
|
przemyslaw-szymanski/vke
|
1d8fb139e0e995e330db6b8873dfc49463ec312c
|
[
"MIT"
] | 1
|
2018-01-06T04:44:36.000Z
|
2018-01-06T04:44:36.000Z
|
include/vke/Core/Utils/inl/TCSmartPtr.inl
|
przemyslaw-szymanski/vke
|
1d8fb139e0e995e330db6b8873dfc49463ec312c
|
[
"MIT"
] | null | null | null |
include/vke/Core/Utils/inl/TCSmartPtr.inl
|
przemyslaw-szymanski/vke
|
1d8fb139e0e995e330db6b8873dfc49463ec312c
|
[
"MIT"
] | null | null | null |
template<typename T>
void TCWeakPtr< T >::operator=(const TCWeakPtr& o)
{
m_pPtr = o.m_pPtr;
}
template<typename T>
void TCWeakPtr< T >::operator=(TCWeakPtr&& o)
{
m_pPtr = o.Release();
}
template<typename T>
void TCWeakPtr< T >::operator=(T* pPtr)
{
m_pPtr = pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator<(const TCWeakPtr& o) const
{
return m_pPtr < o.m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator<(const T* pPtr) const
{
m_pPtr < m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator<=(const TCWeakPtr& o) const
{
return m_pPtr <= o.m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator<=(const T* pPtr) const
{
m_pPtr <= m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator>(const TCWeakPtr& o) const
{
return m_pPtr > o.m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator>(const T* pPtr) const
{
m_pPtr > m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator>=(const TCWeakPtr& o) const
{
return m_pPtr >= o.m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator>=(const T* pPtr) const
{
m_pPtr >= m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator==(const TCWeakPtr& o) const
{
return m_pPtr == o.m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator==(const T* pPtr) const
{
return m_pPtr == m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator!=(const TCWeakPtr& o) const
{
return m_pPtr != o.m_pPtr;
}
template<typename T>
bool TCWeakPtr< T >::operator!=(const T* pPtr) const
{
return m_pPtr != pPtr;
}
template<typename T>
T* TCWeakPtr< T >::Release()
{
auto pPtr = m_pPtr;
m_pPtr = nullptr;
return pPtr;
}
// TCSmartPtr
template<typename T>
void TCSmartPtr< T >::operator=(const TCSmartPtr& o)
{
this->operator=(o.m_pPtr);
}
template<typename T>
void TCSmartPtr< T >::operator=(T* pPtr)
{
if(this->m_pPtr != pPtr)
{
delete this->m_pPtr;
this->m_pPtr = pPtr;
}
}
// TCUniquePtr
template<typename T>
TCUniquePtr< T >::TCUniquePtr(TCUniquePtr& o) :
TCWeakPtr< T >(o.Release())
{
}
template<typename T>
TCUniquePtr< T >::TCUniquePtr(TCUniquePtr&& o) :
TCWeakPtr< T >(o.Release())
{
}
template<typename T>
TCUniquePtr< T >::TCUniquePtr(T* pPtr) :
TCWeakPtr< T >(pPtr)
{
pPtr = nullptr;
}
template<typename T>
void TCUniquePtr< T >::operator=(TCUniquePtr& o)
{
this->m_pPtr = o.Release();
}
template<typename T>
void TCUniquePtr< T >::operator=(TCUniquePtr&& o)
{
this->m_pPtr = o.Release();
}
template<typename T>
void TCUniquePtr< T >::operator=(T* pPtr)
{
this->m_pPtr = pPtr;
pPtr = nullptr;
}
// TRAITS
template<typename T>
void RefCountTraits< T >::AddRef(T** ppPtr)
{
(*ppPtr)->_AddRef();
}
template<typename T>
void RefCountTraits< T >::RemoveRef(T** ppPtr)
{
assert(ppPtr);
T* pTmp = *ppPtr;
if( pTmp->_RemoveRef() == 0 )
{
delete pTmp;
*ppPtr = nullptr;
}
}
template<typename T>
void RefCountTraits< T >::Assign(T** ppDst, T* pSrc)
{
if(*ppDst != pSrc)
{
if( *ppDst )
{
RemoveRef( ppDst );
}
*ppDst = pSrc;
if( *ppDst )
{
AddRef( *ppDst );
}
}
}
template<typename T>
void RefCountTraits< T >::Move(T** ppDst, T** ppSrc)
{
*ppDst = *ppSrc;
*ppSrc = nullptr;
}
template<typename T>
T* RefCountTraits< T >::Move(T** ppSrcOut)
{
T* pTmp = *ppSrcOut;
*ppSrcOut = nullptr;
return pTmp;
}
template<typename T, class MutexType, class ScopedLockType>
void ThreadSafeRefCountTraits< T, MutexType, ScopedLockType >::AddRef(T** ppPtr)
{
(*ppPtr)->_AddRefTS();
}
template<typename T, class MutexType, class ScopedLockType>
void ThreadSafeRefCountTraits< T, MutexType, ScopedLockType >::RemoveRef(T** ppPtr)
{
assert( ppPtr );
T* pTmp = *ppPtr;
if( pTmp->_RemoveRefTS() == 0 )
{
delete pTmp;
*ppPtr = nullptr;
}
}
template<typename T, class MutexType, class ScopedLockType>
void ThreadSafeRefCountTraits< T, MutexType, ScopedLockType >::Assign(T** ppDst, T* pSrc)
{
if( *ppDst != pSrc )
{
if( *ppDst )
{
RemoveRef( ppDst );
}
*ppDst = pSrc;
if( *ppDst )
{
AddRef( ppDst );
}
}
}
template<typename T, class MutexType, class ScopedLockType>
void ThreadSafeRefCountTraits< T, MutexType, ScopedLockType >::Move(T** ppLeft, T** ppRight)
{
RefCountTraits< T >::Move(ppLeft, ppRight);
}
// TCObjectSmartPtr
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >::TCObjectSmartPtr(T* pPtr)
{
Policy::Assign( &this->m_pPtr, pPtr );
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >::TCObjectSmartPtr(const TCObjectSmartPtr& o) :
TCObjectSmartPtr(o.m_pPtr)
{
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >::TCObjectSmartPtr(TCObjectSmartPtr&& o) :
TCWeakPtr< T >( o.Release() )
{
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >::TCObjectSmartPtr(TCWeakPtr< T >& o)
{
Policy::Assign( &this->m_pPtr, o.Get() );
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >::~TCObjectSmartPtr()
{
if( this->m_pPtr )
{
Policy::RemoveRef( &this->m_pPtr );
}
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >& TCObjectSmartPtr< T, Policy >::operator=(T* pPtr)
{
Policy::Assign( &this->m_pPtr, pPtr );
return *this;
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >& TCObjectSmartPtr< T, Policy >::operator=(const TCObjectSmartPtr& o)
{
this->operator=( o.m_pPtr );
return *this;
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >& TCObjectSmartPtr< T, Policy >::operator=(TCObjectSmartPtr&& o)
{
Policy::Move( &this->m_pPtr, &o.m_pPtr );
return *this;
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >& TCObjectSmartPtr< T, Policy >::operator=(TCWeakPtr< T >& o)
{
return this->operator=( o.Get() );
}
template<typename T, typename Policy>
TCObjectSmartPtr< T, Policy >& TCObjectSmartPtr< T, Policy >::operator=(TCWeakPtr< T >&& o)
{
auto pPtr = o.Release();
return this->operator=( pPtr );
}
| 19.783699
| 98
| 0.638409
|
przemyslaw-szymanski
|
1375987a353fde0ef47dae9e1c4b2925e49302d8
| 308
|
cpp
|
C++
|
src/detector.cpp
|
fntlnz/id-extractor
|
0c6ccfb2e6f16c932635a9a945d2664872906aa8
|
[
"MIT"
] | 1
|
2015-07-21T06:24:37.000Z
|
2015-07-21T06:24:37.000Z
|
src/detector.cpp
|
fntlnz/id-extractor
|
0c6ccfb2e6f16c932635a9a945d2664872906aa8
|
[
"MIT"
] | null | null | null |
src/detector.cpp
|
fntlnz/id-extractor
|
0c6ccfb2e6f16c932635a9a945d2664872906aa8
|
[
"MIT"
] | null | null | null |
#include "detector.h"
Detector::Detector(cv::Mat img, double hessianThreshold) {
this->img = img;
this->opencv_detector = cv::xfeatures2d::SURF::create(hessianThreshold);
}
void Detector::detect() {
this->opencv_detector->detectAndCompute(this->img, cv::Mat(), this->keypoints, this->descriptors);
}
| 28
| 100
| 0.724026
|
fntlnz
|
137cb6be59724ac6ca269e106e19843daa4539d5
| 1,599
|
cpp
|
C++
|
src/dockerswarm.cpp
|
MassGrid/MassGrid
|
5634dda1b9997c3d230678b1b19b6af17b590a3d
|
[
"MIT"
] | 18
|
2018-01-31T10:02:27.000Z
|
2021-04-16T14:22:31.000Z
|
src/dockerswarm.cpp
|
MassGrid/MassGrid
|
5634dda1b9997c3d230678b1b19b6af17b590a3d
|
[
"MIT"
] | null | null | null |
src/dockerswarm.cpp
|
MassGrid/MassGrid
|
5634dda1b9997c3d230678b1b19b6af17b590a3d
|
[
"MIT"
] | 14
|
2018-02-11T02:07:00.000Z
|
2022-03-18T10:28:06.000Z
|
#include "dockerswarm.h"
void Swarm::DockerSwarm(const string& swarmData,Swarm &swarms)
{
// LogPrint("docker","Swarm::DockerSwarm docker json node\n");
try{
UniValue data(UniValue::VARR);
if(!data.read(swarmData)){
LogPrint("docker","Swarm::DockerSwarm docker json error\n");
return;
}
Swarm swarm;
bool fSuccess = DockerSwarmJson(data,swarm);
if(fSuccess)
swarms=swarm;
}catch(std::exception& e){
LogPrint("docker","Swarm::DockerSwarm JSON read error,%s\n",string(e.what()).c_str());
}catch(...){
LogPrint("docker","Swarm::DockerSwarm unkonw exception\n");
}
}
bool Swarm::DockerSwarmJson(const UniValue& data, Swarm& swarm)
{
std::vector<std::string> vKeys=data.getKeys();
for(size_t i=0;i<data.size();i++){
if(data[vKeys[i]].isStr()){
if(vKeys[i]=="ID") swarm.ID=data[vKeys[i]].get_str();
else if(vKeys[i]=="CreatedAt") swarm.createdAt=getDockerTime(data[vKeys[i]].get_str());
else if(vKeys[i]=="UpdatedAt") swarm.updatedAt=getDockerTime(data[vKeys[i]].get_str());
}
if(data[vKeys[i]].isObject()){
UniValue tdata(data[vKeys[i]]);
if(vKeys[i]=="Version"){
swarm.version.index=find_value(tdata,"Index").get_int64();
}else if(vKeys[i]=="JoinTokens"){
swarm.joinWorkerTokens =find_value(tdata,"Worker").get_str();
swarm.joinManagerTokens=find_value(tdata,"Manager").get_str();
}
}
}
return true;
}
| 39
| 99
| 0.58349
|
MassGrid
|
137dc9387be538a2a7f018b2c3cdc19334e0c56c
| 11,734
|
cpp
|
C++
|
src/drivers/yiear.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 8
|
2020-05-01T15:15:16.000Z
|
2021-05-30T18:49:15.000Z
|
src/drivers/yiear.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | null | null | null |
src/drivers/yiear.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 5
|
2020-05-07T18:38:11.000Z
|
2021-08-03T12:57:41.000Z
|
#include "../vidhrdw/yiear.cpp"
/***************************************************************************
Yie Ar Kung-Fu memory map (preliminary)
enrique.sanchez@cs.us.es
CPU: Motorola 6809
Normal 6809 IRQs must be generated each video frame (60 fps).
The 6809 NMI is used for sound timing.
0000 R VLM5030 status ???
4000 W control port
bit 0 - flip screen
bit 1 - NMI enable
bit 2 - IRQ enable
bit 3 - coin counter A
bit 4 - coin counter B
4800 W sound latch write
4900 W copy sound latch to SN76496
4a00 W VLM5030 write
4b00 W VLM5030 start
4c00 R DSW #0
4d00 R DSW #1
4e00 R IN #0
4e01 R IN #1
4e02 R IN #2
4e03 R DSW #2
4f00 W watchdog
5000-502f W sprite RAM 1 (18 sprites)
byte 0 - bit 0 - sprite code MSB
bit 6 - flip X
bit 7 - flip Y
byte 1 - Y position
5030-53ff RW RAM
5400-542f W sprite RAM 2
byte 0 - X position
byte 1 - sprite code LSB
5430-57ff RW RAM
5800-5fff RW video RAM
byte 0 - bit 4 - character code MSB
bit 6 - flip Y
bit 7 - flip X
byte 1 - character code LSB
8000-ffff R ROM
***************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
#include "cpu/m6809/m6809.h"
void yiear_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void yiear_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
WRITE_HANDLER( yiear_videoram_w );
WRITE_HANDLER( yiear_control_w );
int yiear_nmi_interrupt(void);
/* in sndhrdw/trackfld.c */
WRITE_HANDLER( konami_SN76496_latch_w );
WRITE_HANDLER( konami_SN76496_0_w );
static READ_HANDLER( yiear_speech_r )
{
//return rand();
/* maybe bit 0 is VLM5030 busy pin??? */
if (VLM5030_BSY()) return 1;
else return 0;
}
static WRITE_HANDLER( yiear_VLM5030_control_w )
{
//VLM5030_ST( 1 );
//VLM5030_ST( 0 );
/* bit 0 is latch direction */
VLM5030_ST( ( data >> 1 ) & 1 );
VLM5030_RST( ( data >> 2 ) & 1 );
}
static struct MemoryReadAddress readmem[] =
{
{ 0x0000, 0x0000, yiear_speech_r },
{ 0x4c00, 0x4c00, input_port_3_r },
{ 0x4d00, 0x4d00, input_port_4_r },
{ 0x4e00, 0x4e00, input_port_0_r },
{ 0x4e01, 0x4e01, input_port_1_r },
{ 0x4e02, 0x4e02, input_port_2_r },
{ 0x4e03, 0x4e03, input_port_5_r },
{ 0x5000, 0x5fff, MRA_RAM },
{ 0x8000, 0xffff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress writemem[] =
{
{ 0x4000, 0x4000, yiear_control_w },
{ 0x4800, 0x4800, konami_SN76496_latch_w },
{ 0x4900, 0x4900, konami_SN76496_0_w },
{ 0x4a00, 0x4a00, yiear_VLM5030_control_w },
{ 0x4b00, 0x4b00, VLM5030_data_w },
{ 0x4f00, 0x4f00, watchdog_reset_w },
{ 0x5000, 0x502f, MWA_RAM, &spriteram, &spriteram_size },
{ 0x5030, 0x53ff, MWA_RAM },
{ 0x5400, 0x542f, MWA_RAM, &spriteram_2 },
{ 0x5430, 0x57ff, MWA_RAM },
{ 0x5800, 0x5fff, videoram_w, &videoram, &videoram_size },
{ 0x8000, 0xffff, MWA_ROM },
{ -1 } /* end of table */
};
INPUT_PORTS_START( yiear )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_COCKTAIL )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* DSW0 */
PORT_DIPNAME( 0x03, 0x01, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x03, "1" )
PORT_DIPSETTING( 0x02, "2" )
PORT_DIPSETTING( 0x01, "3" )
PORT_DIPSETTING( 0x00, "5" )
PORT_DIPNAME( 0x04, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x04, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x08, "30000 80000" )
PORT_DIPSETTING( 0x00, "40000 90000" )
PORT_DIPNAME( 0x10, 0x10, "Unknown DSW1 4" )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x20, "Difficulty?" )
PORT_DIPSETTING( 0x20, "Easy" )
PORT_DIPSETTING( 0x00, "Hard" )
PORT_DIPNAME( 0x40, 0x40, "Unknown DSW1 6" )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_START /* DSW1 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, "Number of Controllers" )
PORT_DIPSETTING( 0x02, "1" )
PORT_DIPSETTING( 0x00, "2" )
PORT_SERVICE( 0x04, IP_ACTIVE_LOW )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unused ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* DSW2 */
PORT_DIPNAME( 0x0f, 0x0f, DEF_STR( Coin_A ) )
PORT_DIPSETTING( 0x02, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x05, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 3C_2C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 4C_3C ) )
PORT_DIPSETTING( 0x0f, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x03, DEF_STR( 3C_4C ) )
PORT_DIPSETTING( 0x07, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x0e, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x06, DEF_STR( 2C_5C ) )
PORT_DIPSETTING( 0x0d, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0x0b, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x09, DEF_STR( 1C_7C ) )
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) )
PORT_DIPNAME( 0xf0, 0xf0, DEF_STR( Coin_B ) )
PORT_DIPSETTING( 0x20, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x50, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x80, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x40, DEF_STR( 3C_2C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 4C_3C ) )
PORT_DIPSETTING( 0xf0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x30, DEF_STR( 3C_4C ) )
PORT_DIPSETTING( 0x70, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0xe0, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x60, DEF_STR( 2C_5C ) )
PORT_DIPSETTING( 0xd0, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0xc0, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0xb0, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0xa0, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x90, DEF_STR( 1C_7C ) )
/* 0x00 gives invalid */
INPUT_PORTS_END
static struct GfxLayout charlayout =
{
8,8, /* 8x8 characters */
512, /* 512 characters */
4, /* 4 bits per pixel */
{ 4, 0, 512*16*8+4, 512*16*8+0 }, /* plane offsets */
{ 0, 1, 2, 3, 8*8+0, 8*8+1, 8*8+2, 8*8+3 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
16*8 /* each character takes 16 bytes */
};
static struct GfxLayout spritelayout =
{
16,16, /* 16x16 sprites */
512, /* 512 sprites */
4, /* 4 bits per pixel */
{ 4, 0, 512*64*8+4, 512*64*8+0 }, /* plane offsets */
{ 0*8*8+0, 0*8*8+1, 0*8*8+2, 0*8*8+3, 1*8*8+0, 1*8*8+1, 1*8*8+2, 1*8*8+3,
2*8*8+0, 2*8*8+1, 2*8*8+2, 2*8*8+3, 3*8*8+0, 3*8*8+1, 3*8*8+2, 3*8*8+3 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8 },
64*8 /* each sprite takes 64 bytes */
};
static struct GfxDecodeInfo gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &charlayout, 16, 1 },
{ REGION_GFX2, 0, &spritelayout, 0, 1 },
{ -1 } /* end of array */
};
struct SN76496interface sn76496_interface =
{
1, /* 1 chip */
{ 1536000 }, /* 1.536 MHz (hand tuned) */
{ 100 }
};
struct VLM5030interface vlm5030_interface =
{
3580000, /* master clock */
100, /* volume */
REGION_SOUND1, /* memory region */
0, /* memory size of speech rom */
0 /* VCU */
};
static struct MachineDriver machine_driver_yiear =
{
/* basic machine hardware */
{
{
CPU_M6809,
1536000, /* 1.536 Mhz */
readmem, writemem, 0, 0,
interrupt,1, /* vblank */
yiear_nmi_interrupt,500 /* music tempo (correct frequency unknown) */
}
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
0,
/* video hardware */
32*8, 32*8, { 0*8, 32*8-1, 2*8, 30*8-1 },
gfxdecodeinfo,
32, 32,
yiear_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY,
0,
generic_vh_start,
generic_vh_stop,
yiear_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_SN76496,
&sn76496_interface
},
{
SOUND_VLM5030,
&vlm5030_interface
}
}
};
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( yiear )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "i08.10d", 0x08000, 0x4000, 0xe2d7458b )
ROM_LOAD( "i07.8d", 0x0c000, 0x4000, 0x7db7442e )
ROM_REGION( 0x04000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g16_1.bin", 0x00000, 0x2000, 0xb68fd91d )
ROM_LOAD( "g15_2.bin", 0x02000, 0x2000, 0xd9b167c6 )
ROM_REGION( 0x10000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g04_5.bin", 0x00000, 0x4000, 0x45109b29 )
ROM_LOAD( "g03_6.bin", 0x04000, 0x4000, 0x1d650790 )
ROM_LOAD( "g06_3.bin", 0x08000, 0x4000, 0xe6aa945b )
ROM_LOAD( "g05_4.bin", 0x0c000, 0x4000, 0xcc187c22 )
ROM_REGION( 0x0020, REGION_PROMS )
ROM_LOAD( "yiear.clr", 0x00000, 0x0020, 0xc283d71f )
ROM_REGION( 0x2000, REGION_SOUND1 ) /* 8k for the VLM5030 data */
ROM_LOAD( "a12_9.bin", 0x00000, 0x2000, 0xf75a1539 )
ROM_END
ROM_START( yiear2 )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "d12_8.bin", 0x08000, 0x4000, 0x49ecd9dd )
ROM_LOAD( "d14_7.bin", 0x0c000, 0x4000, 0xbc2e1208 )
ROM_REGION( 0x04000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g16_1.bin", 0x00000, 0x2000, 0xb68fd91d )
ROM_LOAD( "g15_2.bin", 0x02000, 0x2000, 0xd9b167c6 )
ROM_REGION( 0x10000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g04_5.bin", 0x00000, 0x4000, 0x45109b29 )
ROM_LOAD( "g03_6.bin", 0x04000, 0x4000, 0x1d650790 )
ROM_LOAD( "g06_3.bin", 0x08000, 0x4000, 0xe6aa945b )
ROM_LOAD( "g05_4.bin", 0x0c000, 0x4000, 0xcc187c22 )
ROM_REGION( 0x0020, REGION_PROMS )
ROM_LOAD( "yiear.clr", 0x00000, 0x0020, 0xc283d71f )
ROM_REGION( 0x2000, REGION_SOUND1 ) /* 8k for the VLM5030 data */
ROM_LOAD( "a12_9.bin", 0x00000, 0x2000, 0xf75a1539 )
ROM_END
GAME( 1985, yiear, 0, yiear, yiear, 0, ROT0, "Konami", "Yie Ar Kung-Fu (set 1)" )
GAME( 1985, yiear2, yiear, yiear, yiear, 0, ROT0, "Konami", "Yie Ar Kung-Fu (set 2)" )
| 31.124668
| 117
| 0.654679
|
gameblabla
|
137df95e69ab968dd3d0dc1181671129253bb7d7
| 451
|
cpp
|
C++
|
src/tools/tools.cpp
|
InspectorSolaris/nd-engine
|
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
|
[
"WTFPL"
] | null | null | null |
src/tools/tools.cpp
|
InspectorSolaris/nd-engine
|
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
|
[
"WTFPL"
] | null | null | null |
src/tools/tools.cpp
|
InspectorSolaris/nd-engine
|
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
|
[
"WTFPL"
] | null | null | null |
#include "tools.hpp"
namespace nd::src::tools
{
f64
getDt(const f64 min) noexcept
{
using namespace std;
using namespace std::chrono;
static auto time = high_resolution_clock::now();
const auto now = high_resolution_clock::now();
const auto dt = duration_cast<seconds>(now - time).count();
time = now;
return max(min, static_cast<f64>(dt));
}
} // namespace nd::src::tools
| 21.47619
| 68
| 0.603104
|
InspectorSolaris
|
13802e4d3b9dadc78a5fca529f7b05b9e18dc077
| 658
|
cpp
|
C++
|
sample/joystick/MyApp.cpp
|
RockyRocks/glbase
|
0b03e5216e5efd3060a5ddd8cf61fb733319af17
|
[
"IJG"
] | null | null | null |
sample/joystick/MyApp.cpp
|
RockyRocks/glbase
|
0b03e5216e5efd3060a5ddd8cf61fb733319af17
|
[
"IJG"
] | null | null | null |
sample/joystick/MyApp.cpp
|
RockyRocks/glbase
|
0b03e5216e5efd3060a5ddd8cf61fb733319af17
|
[
"IJG"
] | null | null | null |
#include "MyApp.h"
// single, static instance of our application
static MyApp theApp;
void MyApp::OnCreate() {
if (!m_joystick.Open())
MsgPrintf("This sample needs a joystick!");
position[0]=position[1]=0.0f;
for (int n=0;n<MAX_BUTTON;n++) button[n]=false;
}//OnCreate
MyApp & MyApp::Get() {
return theApp;
}//Get
void MyApp::OnIdle() {
// poll the joystick
m_joystick.Update();
// get joystick position
position[0] = m_joystick.Axis(0);
position[1] = -m_joystick.Axis(1);
// get joystick buttons
for (int n=0;n<MAX_BUTTON;n++)
button[n] = m_joystick.Button(n);
}//OnIdle
void MyApp::OnDestroy() {
m_joystick.Close();
}//OnDestroy
| 19.939394
| 51
| 0.674772
|
RockyRocks
|
1385a43ee760faba8fc02144787193b5528ec1a8
| 1,323
|
hpp
|
C++
|
app/create_trading_db/include/offcenter/trading/createtradingdb/CreateTradingDBOptions.hpp
|
CodeRancher/offcenter_trading
|
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
|
[
"Apache-2.0"
] | null | null | null |
app/create_trading_db/include/offcenter/trading/createtradingdb/CreateTradingDBOptions.hpp
|
CodeRancher/offcenter_trading
|
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
|
[
"Apache-2.0"
] | 4
|
2021-12-27T17:56:21.000Z
|
2022-01-05T00:05:01.000Z
|
app/create_trading_db/include/offcenter/trading/createtradingdb/CreateTradingDBOptions.hpp
|
CodeRancher/offcenter_trading
|
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright 2021 Scott Brauer
*
* Licensed under the Apache License, Version 2.0 (the );
* 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 BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file CreateTradingDBOptions.hpp
* @author Scott Brauer
* @date 04-02-2021
*/
#ifndef OFFCENTER_TRADING_CREATETRADINGDB_CREATETRADINGDBOPTIONS_HPP_
#define OFFCENTER_TRADING_CREATETRADINGDB_CREATETRADINGDBOPTIONS_HPP_
#include <string>
namespace offcenter {
namespace trading {
namespace createtradingdb {
class CreateTradingDBOptions
{
public:
explicit CreateTradingDBOptions():
m_dropDB(false) {}
virtual ~CreateTradingDBOptions() {}
bool dropDB() const { return m_dropDB; }
friend class CreateTradingDBProgramOptions;
private:
bool m_dropDB;
};
} /* namespace createtradingdb */
} /* namespace trading */
} /* namespace offcenter */
#endif /* OFFCENTER_TRADING_CREATETRADINGDB_CREATETRADINGDBOPTIONS_HPP_ */
| 24.962264
| 75
| 0.762661
|
CodeRancher
|
1385e5cf9d2f3c4326a8a419ca0c2f77393da857
| 4,977
|
cpp
|
C++
|
src/client.cpp
|
rafaelppires/sgx_lightweight_mapreruce
|
a25b58d5ad69d61e32546a43dc604e720ef95bb8
|
[
"Apache-2.0"
] | 1
|
2020-12-11T03:15:58.000Z
|
2020-12-11T03:15:58.000Z
|
src/client.cpp
|
rafaelppires/sgx_lightweight_mapreruce
|
a25b58d5ad69d61e32546a43dc604e720ef95bb8
|
[
"Apache-2.0"
] | null | null | null |
src/client.cpp
|
rafaelppires/sgx_lightweight_mapreruce
|
a25b58d5ad69d61e32546a43dc604e720ef95bb8
|
[
"Apache-2.0"
] | 1
|
2019-09-03T02:31:08.000Z
|
2019-09-03T02:31:08.000Z
|
/**
* MapReduce client - Subscribe reducced data
* Publish code for Map, Reduce and Data
**/
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <message.h>
#include <client_protocol.h>
#include <mrprotocol.h>
#include <zhelpers.h>
#include <argp.h>
//------------------------------------------------------------------------------
static void fileerror( const std::string &fname ) {
std::cerr << "Error opening file \"" << fname << "\"\n";
exit(-2);
}
//------------------------------------------------------------------------------
static void openfiles( std::ifstream files[], std::string fnames[], int n ) {
for( int i = 0; i < n; ++i ) {
files[i].open(fnames[i].c_str());
if( !files[i].good() ) fileerror(fnames[i]);
}
}
//------------------------------------------------------------------------------
const char *argp_program_version = "SGX Lua MapReduce Client 0.9";
const char *argp_program_bug_address = "<rafael.pires@unine.ch>";
/* Program documentation. */
static char doc[] =
"SGX Lua MapReduce Client - Fire MR jobs: Wordcount or Kmeans";
static char args_doc[] = "";
static struct argp_option options[] = {
{ 0,0,0,0, "To define MR code" },
{ "mapper", 'm', "Filename", 0, "Set mapper Lua script" },
{ "reducer", 'r', "Filename", 0, "Set reducer Lua script" },
{ 0,0,0,0, "To define input data" },
{ "datafile", 'd', "Filename", 0, "Set input data file" },
{ 0,0,0,0, "To define application behavior" },
{ "kmeans", 'k', "Filename", 0, "Application is Kmeans, centers data file is Filename" },
{ "encrypt", 'e', 0, OPTION_ARG_OPTIONAL, "Encrypt messages" },
{ "pubsub", 'p', "host:port", 0, "Publish/Subscribe engine "
"runs in the provided address" },
{ 0 }
};
//------------------------------------------------------------------------------
struct Arguments {
Arguments() : encrypt(false), kmeans(false), id("Client01") {}
std::string id, address, datafile, kmeans_centers, mapscript, reducescript;
bool encrypt, kmeans;
};
//------------------------------------------------------------------------------
/* Parse a single option. */
static error_t parse_opt (int key, char *arg, struct argp_state *state) {
Arguments *args = (Arguments*)state->input;
switch(key) {
case 'm':
args->mapscript = std::string(arg);
break;
case 'r':
args->reducescript = std::string(arg);
break;
case 'd':
args->datafile = std::string(arg);
break;
case 'p':
args->address = std::string("tcp://") + arg;
break;
case 'e':
args->encrypt = true;
break;
case 'k':
args->kmeans = true;
args->kmeans_centers = std::string(arg);
break;
default:
return ARGP_ERR_UNKNOWN;
};
return 0;
}
static struct argp argp = { options, parse_opt, 0, doc };
//------------------------------------------------------------------------------
void error( const char *msg, int code ) {
printf("%s (-? or --help for info)\n", msg);
exit(code);
}
//------------------------------------------------------------------------------
int main( int argc, char **argv ) {
Arguments args;
argp_parse(&argp, argc, argv, 0, 0, &args);
if( args.address == "" ) error("Missing Pub/sub address", -1);
if( args.mapscript == "" ) error("Missing Mapper", -2);
if( args.reducescript == "" ) error("Missing Reducer", -3);
if( args.datafile == "" ) error("Missing input data file", -4);
printf("M/R encryption is turned %s\033[0m\n",
args.encrypt ? "\033[32mon" : "\033[1;31moff" );
zmq::context_t context(1);
Communication< zmq::socket_t > pipe( context,
args.address, args.id, false);
ClientProtocol protocol( args.encrypt, args.id, pipe );
if( args.kmeans ) protocol.setApp( KMEANS );
protocol.init();
// Wait for result
size_t counter = 0;
while(1) {
bool rc;
do {
zmq::message_t zmsg;
bool requires_action = false;
if( (rc = pipe.socket().recv( &zmsg, ZMQ_DONTWAIT)) ) {
// ignore 0 msg
requires_action = protocol.handle_msg( s_recv(pipe.socket()).substr(32) );
}
if( requires_action ) {
counter = 1000;
requires_action = false;
} else if( counter > 0 && --counter == 0 ) {
std::string fnames[4];
std::ifstream files[4];
fnames[0] = args.mapscript; fnames[1] = args.reducescript;
fnames[2] = args.datafile; fnames[3] = args.kmeans_centers;
openfiles( files, fnames, args.kmeans ? 4 : 3 );
protocol.fire_jobs( files, fnames );
}
} while( rc );
usleep(1000);
}
}
| 35.297872
| 94
| 0.494876
|
rafaelppires
|
138670db81488c5a39eea0295f349114ab17dfeb
| 910
|
hpp
|
C++
|
src/bqt_layer.hpp
|
JadeMatrix/BQTDraw
|
329b015c45d8f151fde09b8f26aa7e0e8151b604
|
[
"Zlib"
] | null | null | null |
src/bqt_layer.hpp
|
JadeMatrix/BQTDraw
|
329b015c45d8f151fde09b8f26aa7e0e8151b604
|
[
"Zlib"
] | null | null | null |
src/bqt_layer.hpp
|
JadeMatrix/BQTDraw
|
329b015c45d8f151fde09b8f26aa7e0e8151b604
|
[
"Zlib"
] | null | null | null |
#ifndef BQT_LAYER_HPP
#define BQT_LAYER_HPP
/*
* bqt_sketch.hpp
*
* About
*
*/
/* INCLUDES *******************************************************************//******************************************************************************/
#include "bqt_datastructures.hpp"
#include <vector>
#include "bqt_slice.hpp"
#include "bqt_imagemode.hpp"
#include "bqt_trackable.hpp"
/******************************************************************************//******************************************************************************/
namespace bqt
{
class layer
{
protected:
long docpos_x;
long docpos_y;
long width;
long height;
unsigned int DPI;
public:
};
}
/******************************************************************************//******************************************************************************/
#endif
| 21.666667
| 160
| 0.295604
|
JadeMatrix
|
138a86ccc0b99e677e84fa61c56cb460691d68a3
| 16,508
|
cpp
|
C++
|
packages/CLPBN/horus/HorusYap.cpp
|
denys-duchier/yap-6.3
|
97163fa150ba570e4ba2881646363e9877a07bcb
|
[
"Artistic-1.0-Perl",
"ClArtistic"
] | 2
|
2015-11-01T07:38:31.000Z
|
2016-03-30T18:05:28.000Z
|
packages/CLPBN/horus/HorusYap.cpp
|
denys-duchier/yap-6.3
|
97163fa150ba570e4ba2881646363e9877a07bcb
|
[
"Artistic-1.0-Perl",
"ClArtistic"
] | null | null | null |
packages/CLPBN/horus/HorusYap.cpp
|
denys-duchier/yap-6.3
|
97163fa150ba570e4ba2881646363e9877a07bcb
|
[
"Artistic-1.0-Perl",
"ClArtistic"
] | null | null | null |
#include <cstdlib>
#include <vector>
#include <iostream>
#include <sstream>
#include <YapInterface.h>
#include "ParfactorList.h"
#include "FactorGraph.h"
#include "LiftedVe.h"
#include "VarElim.h"
#include "LiftedBp.h"
#include "CountingBp.h"
#include "BeliefProp.h"
#include "ElimGraph.h"
#include "BayesBall.h"
using namespace std;
typedef std::pair<ParfactorList*, ObservedFormulas*> LiftedNetwork;
Params readParameters (YAP_Term);
vector<unsigned> readUnsignedList (YAP_Term);
void readLiftedEvidence (YAP_Term, ObservedFormulas&);
Parfactor* readParfactor (YAP_Term);
vector<unsigned>
readUnsignedList (YAP_Term list)
{
vector<unsigned> vec;
while (list != YAP_TermNil()) {
vec.push_back ((unsigned) YAP_IntOfTerm (YAP_HeadOfTerm (list)));
list = YAP_TailOfTerm (list);
}
return vec;
}
int
createLiftedNetwork (void)
{
Parfactors parfactors;
YAP_Term parfactorList = YAP_ARG1;
while (parfactorList != YAP_TermNil()) {
YAP_Term pfTerm = YAP_HeadOfTerm (parfactorList);
parfactors.push_back (readParfactor (pfTerm));
parfactorList = YAP_TailOfTerm (parfactorList);
}
// LiftedUtils::printSymbolDictionary();
if (Globals::verbosity > 2) {
Util::printHeader ("INITIAL PARFACTORS");
for (size_t i = 0; i < parfactors.size(); i++) {
parfactors[i]->print();
cout << endl;
}
}
ParfactorList* pfList = new ParfactorList (parfactors);
if (Globals::verbosity > 2) {
Util::printHeader ("SHATTERED PARFACTORS");
pfList->print();
}
// read evidence
ObservedFormulas* obsFormulas = new ObservedFormulas();
readLiftedEvidence (YAP_ARG2, *(obsFormulas));
LiftedNetwork* net = new LiftedNetwork (pfList, obsFormulas);
YAP_Int p = (YAP_Int) (net);
return YAP_Unify (YAP_MkIntTerm (p), YAP_ARG3);
}
Parfactor*
readParfactor (YAP_Term pfTerm)
{
// read dist id
unsigned distId = YAP_IntOfTerm (YAP_ArgOfTerm (1, pfTerm));
// read the ranges
Ranges ranges;
YAP_Term rangeList = YAP_ArgOfTerm (3, pfTerm);
while (rangeList != YAP_TermNil()) {
unsigned range = (unsigned) YAP_IntOfTerm (YAP_HeadOfTerm (rangeList));
ranges.push_back (range);
rangeList = YAP_TailOfTerm (rangeList);
}
// read parametric random vars
ProbFormulas formulas;
unsigned count = 0;
unordered_map<YAP_Term, LogVar> lvMap;
YAP_Term pvList = YAP_ArgOfTerm (2, pfTerm);
while (pvList != YAP_TermNil()) {
YAP_Term formulaTerm = YAP_HeadOfTerm (pvList);
if (YAP_IsAtomTerm (formulaTerm)) {
string name ((char*) YAP_AtomName (YAP_AtomOfTerm (formulaTerm)));
Symbol functor = LiftedUtils::getSymbol (name);
formulas.push_back (ProbFormula (functor, ranges[count]));
} else {
LogVars logVars;
YAP_Functor yapFunctor = YAP_FunctorOfTerm (formulaTerm);
string name ((char*) YAP_AtomName (YAP_NameOfFunctor (yapFunctor)));
Symbol functor = LiftedUtils::getSymbol (name);
unsigned arity = (unsigned) YAP_ArityOfFunctor (yapFunctor);
for (unsigned i = 1; i <= arity; i++) {
YAP_Term ti = YAP_ArgOfTerm (i, formulaTerm);
unordered_map<YAP_Term, LogVar>::iterator it = lvMap.find (ti);
if (it != lvMap.end()) {
logVars.push_back (it->second);
} else {
unsigned newLv = lvMap.size();
lvMap[ti] = newLv;
logVars.push_back (newLv);
}
}
formulas.push_back (ProbFormula (functor, logVars, ranges[count]));
}
count ++;
pvList = YAP_TailOfTerm (pvList);
}
// read the parameters
const Params& params = readParameters (YAP_ArgOfTerm (4, pfTerm));
// read the constraint
Tuples tuples;
if (lvMap.size() >= 1) {
YAP_Term tupleList = YAP_ArgOfTerm (5, pfTerm);
while (tupleList != YAP_TermNil()) {
YAP_Term term = YAP_HeadOfTerm (tupleList);
assert (YAP_IsApplTerm (term));
YAP_Functor yapFunctor = YAP_FunctorOfTerm (term);
unsigned arity = (unsigned) YAP_ArityOfFunctor (yapFunctor);
assert (lvMap.size() == arity);
Tuple tuple (arity);
for (unsigned i = 1; i <= arity; i++) {
YAP_Term ti = YAP_ArgOfTerm (i, term);
if (YAP_IsAtomTerm (ti) == false) {
cerr << "error: constraint has free variables" << endl;
abort();
}
string name ((char*) YAP_AtomName (YAP_AtomOfTerm (ti)));
tuple[i - 1] = LiftedUtils::getSymbol (name);
}
tuples.push_back (tuple);
tupleList = YAP_TailOfTerm (tupleList);
}
}
return new Parfactor (formulas, params, tuples, distId);
}
void
readLiftedEvidence (
YAP_Term observedList,
ObservedFormulas& obsFormulas)
{
while (observedList != YAP_TermNil()) {
YAP_Term pair = YAP_HeadOfTerm (observedList);
YAP_Term ground = YAP_ArgOfTerm (1, pair);
Symbol functor;
Symbols args;
if (YAP_IsAtomTerm (ground)) {
string name ((char*) YAP_AtomName (YAP_AtomOfTerm (ground)));
functor = LiftedUtils::getSymbol (name);
} else {
assert (YAP_IsApplTerm (ground));
YAP_Functor yapFunctor = YAP_FunctorOfTerm (ground);
string name ((char*) (YAP_AtomName (YAP_NameOfFunctor (yapFunctor))));
functor = LiftedUtils::getSymbol (name);
unsigned arity = (unsigned) YAP_ArityOfFunctor (yapFunctor);
for (unsigned i = 1; i <= arity; i++) {
YAP_Term ti = YAP_ArgOfTerm (i, ground);
assert (YAP_IsAtomTerm (ti));
string arg ((char *) YAP_AtomName (YAP_AtomOfTerm (ti)));
args.push_back (LiftedUtils::getSymbol (arg));
}
}
unsigned evidence = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (2, pair));
bool found = false;
for (size_t i = 0; i < obsFormulas.size(); i++) {
if (obsFormulas[i].functor() == functor &&
obsFormulas[i].arity() == args.size() &&
obsFormulas[i].evidence() == evidence) {
obsFormulas[i].addTuple (args);
found = true;
}
}
if (found == false) {
obsFormulas.push_back (ObservedFormula (functor, evidence, args));
}
observedList = YAP_TailOfTerm (observedList);
}
}
int
createGroundNetwork (void)
{
string factorsType ((char*) YAP_AtomName (YAP_AtomOfTerm (YAP_ARG1)));
FactorGraph* fg = new FactorGraph();
if (factorsType == "bayes") {
fg->setFactorsAsBayesian();
}
YAP_Term factorList = YAP_ARG2;
while (factorList != YAP_TermNil()) {
YAP_Term factor = YAP_HeadOfTerm (factorList);
// read the var ids
VarIds varIds = readUnsignedList (YAP_ArgOfTerm (1, factor));
// read the ranges
Ranges ranges = readUnsignedList (YAP_ArgOfTerm (2, factor));
// read the parameters
Params params = readParameters (YAP_ArgOfTerm (3, factor));
// read dist id
unsigned distId = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (4, factor));
fg->addFactor (Factor (varIds, ranges, params, distId));
factorList = YAP_TailOfTerm (factorList);
}
unsigned nrObservedVars = 0;
YAP_Term evidenceList = YAP_ARG3;
while (evidenceList != YAP_TermNil()) {
YAP_Term evTerm = YAP_HeadOfTerm (evidenceList);
unsigned vid = (unsigned) YAP_IntOfTerm ((YAP_ArgOfTerm (1, evTerm)));
unsigned ev = (unsigned) YAP_IntOfTerm ((YAP_ArgOfTerm (2, evTerm)));
assert (fg->getVarNode (vid));
fg->getVarNode (vid)->setEvidence (ev);
evidenceList = YAP_TailOfTerm (evidenceList);
nrObservedVars ++;
}
if (Globals::verbosity > 0) {
cout << "factor graph contains " ;
cout << fg->nrVarNodes() << " variables " ;
cout << "(" << nrObservedVars << " observed) and " ;
cout << fg->nrFacNodes() << " factors " << endl;
}
YAP_Int p = (YAP_Int) (fg);
return YAP_Unify (YAP_MkIntTerm (p), YAP_ARG4);
}
Params
readParameters (YAP_Term paramL)
{
Params params;
assert (YAP_IsPairTerm (paramL));
while (paramL != YAP_TermNil()) {
params.push_back ((double) YAP_FloatOfTerm (YAP_HeadOfTerm (paramL)));
paramL = YAP_TailOfTerm (paramL);
}
if (Globals::logDomain) {
Util::log (params);
}
return params;
}
int
runLiftedSolver (void)
{
LiftedNetwork* network = (LiftedNetwork*) YAP_IntOfTerm (YAP_ARG1);
YAP_Term taskList = YAP_ARG2;
vector<Params> results;
ParfactorList pfListCopy (*network->first);
LiftedVe::absorveEvidence (pfListCopy, *network->second);
while (taskList != YAP_TermNil()) {
Grounds queryVars;
YAP_Term jointList = YAP_HeadOfTerm (taskList);
while (jointList != YAP_TermNil()) {
YAP_Term ground = YAP_HeadOfTerm (jointList);
if (YAP_IsAtomTerm (ground)) {
string name ((char*) YAP_AtomName (YAP_AtomOfTerm (ground)));
queryVars.push_back (Ground (LiftedUtils::getSymbol (name)));
} else {
assert (YAP_IsApplTerm (ground));
YAP_Functor yapFunctor = YAP_FunctorOfTerm (ground);
string name ((char*) (YAP_AtomName (YAP_NameOfFunctor (yapFunctor))));
unsigned arity = (unsigned) YAP_ArityOfFunctor (yapFunctor);
Symbol functor = LiftedUtils::getSymbol (name);
Symbols args;
for (unsigned i = 1; i <= arity; i++) {
YAP_Term ti = YAP_ArgOfTerm (i, ground);
assert (YAP_IsAtomTerm (ti));
string arg ((char *) YAP_AtomName (YAP_AtomOfTerm (ti)));
args.push_back (LiftedUtils::getSymbol (arg));
}
queryVars.push_back (Ground (functor, args));
}
jointList = YAP_TailOfTerm (jointList);
}
if (Globals::liftedSolver == LiftedSolver::FOVE) {
LiftedVe solver (pfListCopy);
if (Globals::verbosity > 0 && taskList == YAP_ARG2) {
solver.printSolverFlags();
cout << endl;
}
results.push_back (solver.solveQuery (queryVars));
} else if (Globals::liftedSolver == LiftedSolver::LBP) {
LiftedBp solver (pfListCopy);
if (Globals::verbosity > 0 && taskList == YAP_ARG2) {
solver.printSolverFlags();
cout << endl;
}
results.push_back (solver.solveQuery (queryVars));
} else {
assert (false);
}
taskList = YAP_TailOfTerm (taskList);
}
YAP_Term list = YAP_TermNil();
for (size_t i = results.size(); i-- > 0; ) {
const Params& beliefs = results[i];
YAP_Term queryBeliefsL = YAP_TermNil();
for (size_t j = beliefs.size(); j-- > 0; ) {
YAP_Int sl1 = YAP_InitSlot (list);
YAP_Term belief = YAP_MkFloatTerm (beliefs[j]);
queryBeliefsL = YAP_MkPairTerm (belief, queryBeliefsL);
list = YAP_GetFromSlot (sl1);
YAP_RecoverSlots (1);
}
list = YAP_MkPairTerm (queryBeliefsL, list);
}
return YAP_Unify (list, YAP_ARG3);
}
int
runGroundSolver (void)
{
FactorGraph* fg = (FactorGraph*) YAP_IntOfTerm (YAP_ARG1);
vector<VarIds> tasks;
YAP_Term taskList = YAP_ARG2;
while (taskList != YAP_TermNil()) {
tasks.push_back (readUnsignedList (YAP_HeadOfTerm (taskList)));
taskList = YAP_TailOfTerm (taskList);
}
std::set<VarId> vids;
for (size_t i = 0; i < tasks.size(); i++) {
Util::addToSet (vids, tasks[i]);
}
Solver* solver = 0;
FactorGraph* mfg = fg;
if (fg->bayesianFactors()) {
mfg = BayesBall::getMinimalFactorGraph (
*fg, VarIds (vids.begin(), vids.end()));
}
if (Globals::groundSolver == GroundSolver::VE) {
solver = new VarElim (*mfg);
} else if (Globals::groundSolver == GroundSolver::BP) {
solver = new BeliefProp (*mfg);
} else if (Globals::groundSolver == GroundSolver::CBP) {
CountingBp::checkForIdenticalFactors = false;
solver = new CountingBp (*mfg);
} else {
assert (false);
}
if (Globals::verbosity > 0) {
solver->printSolverFlags();
cout << endl;
}
vector<Params> results;
results.reserve (tasks.size());
for (size_t i = 0; i < tasks.size(); i++) {
results.push_back (solver->solveQuery (tasks[i]));
}
delete solver;
if (fg->bayesianFactors()) {
delete mfg;
}
YAP_Term list = YAP_TermNil();
for (size_t i = results.size(); i-- > 0; ) {
const Params& beliefs = results[i];
YAP_Term queryBeliefsL = YAP_TermNil();
for (size_t j = beliefs.size(); j-- > 0; ) {
YAP_Int sl1 = YAP_InitSlot (list);
YAP_Term belief = YAP_MkFloatTerm (beliefs[j]);
queryBeliefsL = YAP_MkPairTerm (belief, queryBeliefsL);
list = YAP_GetFromSlot (sl1);
YAP_RecoverSlots (1);
}
list = YAP_MkPairTerm (queryBeliefsL, list);
}
return YAP_Unify (list, YAP_ARG3);
}
int
setParfactorsParams (void)
{
LiftedNetwork* network = (LiftedNetwork*) YAP_IntOfTerm (YAP_ARG1);
ParfactorList* pfList = network->first;
YAP_Term distList = YAP_ARG2;
unordered_map<unsigned, Params> paramsMap;
while (distList != YAP_TermNil()) {
YAP_Term dist = YAP_HeadOfTerm (distList);
unsigned distId = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (1, dist));
assert (Util::contains (paramsMap, distId) == false);
paramsMap[distId] = readParameters (YAP_ArgOfTerm (2, dist));
distList = YAP_TailOfTerm (distList);
}
ParfactorList::iterator it = pfList->begin();
while (it != pfList->end()) {
assert (Util::contains (paramsMap, (*it)->distId()));
// (*it)->setParams (paramsMap[(*it)->distId()]);
++ it;
}
return TRUE;
}
int
setFactorsParams (void)
{
return TRUE; // TODO
FactorGraph* fg = (FactorGraph*) YAP_IntOfTerm (YAP_ARG1);
YAP_Term distList = YAP_ARG2;
unordered_map<unsigned, Params> paramsMap;
while (distList != YAP_TermNil()) {
YAP_Term dist = YAP_HeadOfTerm (distList);
unsigned distId = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (1, dist));
assert (Util::contains (paramsMap, distId) == false);
paramsMap[distId] = readParameters (YAP_ArgOfTerm (2, dist));
distList = YAP_TailOfTerm (distList);
}
const FacNodes& facNodes = fg->facNodes();
for (size_t i = 0; i < facNodes.size(); i++) {
unsigned distId = facNodes[i]->factor().distId();
assert (Util::contains (paramsMap, distId));
facNodes[i]->factor().setParams (paramsMap[distId]);
}
return TRUE;
}
int
setVarsInformation (void)
{
Var::clearVarsInfo();
vector<string> labels;
YAP_Term labelsL = YAP_ARG1;
while (labelsL != YAP_TermNil()) {
YAP_Atom atom = YAP_AtomOfTerm (YAP_HeadOfTerm (labelsL));
labels.push_back ((char*) YAP_AtomName (atom));
labelsL = YAP_TailOfTerm (labelsL);
}
unsigned count = 0;
YAP_Term stateNamesL = YAP_ARG2;
while (stateNamesL != YAP_TermNil()) {
States states;
YAP_Term namesL = YAP_HeadOfTerm (stateNamesL);
while (namesL != YAP_TermNil()) {
YAP_Atom atom = YAP_AtomOfTerm (YAP_HeadOfTerm (namesL));
states.push_back ((char*) YAP_AtomName (atom));
namesL = YAP_TailOfTerm (namesL);
}
Var::addVarInfo (count, labels[count], states);
count ++;
stateNamesL = YAP_TailOfTerm (stateNamesL);
}
return TRUE;
}
int
setHorusFlag (void)
{
string key ((char*) YAP_AtomName (YAP_AtomOfTerm (YAP_ARG1)));
string value;
if (key == "verbosity") {
stringstream ss;
ss << (int) YAP_IntOfTerm (YAP_ARG2);
ss >> value;
} else if (key == "accuracy") {
stringstream ss;
ss << (float) YAP_FloatOfTerm (YAP_ARG2);
ss >> value;
} else if (key == "max_iter") {
stringstream ss;
ss << (int) YAP_IntOfTerm (YAP_ARG2);
ss >> value;
} else {
value = ((char*) YAP_AtomName (YAP_AtomOfTerm (YAP_ARG2)));
}
return Util::setHorusFlag (key, value);
}
int
freeGroundNetwork (void)
{
delete (FactorGraph*) YAP_IntOfTerm (YAP_ARG1);
return TRUE;
}
int
freeLiftedNetwork (void)
{
LiftedNetwork* network = (LiftedNetwork*) YAP_IntOfTerm (YAP_ARG1);
delete network->first;
delete network->second;
delete network;
return TRUE;
}
extern "C" void
init_predicates (void)
{
YAP_UserCPredicate ("cpp_create_lifted_network", createLiftedNetwork, 3);
YAP_UserCPredicate ("cpp_create_ground_network", createGroundNetwork, 4);
YAP_UserCPredicate ("cpp_run_lifted_solver", runLiftedSolver, 3);
YAP_UserCPredicate ("cpp_run_ground_solver", runGroundSolver, 3);
YAP_UserCPredicate ("cpp_set_parfactors_params", setParfactorsParams, 2);
YAP_UserCPredicate ("cpp_cpp_set_factors_params", setFactorsParams, 2);
YAP_UserCPredicate ("cpp_set_vars_information", setVarsInformation, 2);
YAP_UserCPredicate ("cpp_set_horus_flag", setHorusFlag, 2);
YAP_UserCPredicate ("cpp_free_lifted_network", freeLiftedNetwork, 1);
YAP_UserCPredicate ("cpp_free_ground_network", freeGroundNetwork, 1);
}
| 29.851718
| 78
| 0.65544
|
denys-duchier
|
138a9738117224552305d9f8005c5e6a02a06754
| 588
|
hpp
|
C++
|
MATLAB/Utilities/IO/VarianCBCT/XimPara.hpp
|
tsadakane/TIGRE
|
a853cd2d4a6bc9509c01414b85ca75b4448fd700
|
[
"BSD-3-Clause"
] | 326
|
2016-07-01T10:48:09.000Z
|
2022-03-20T07:34:52.000Z
|
MATLAB/Utilities/IO/VarianCBCT/XimPara.hpp
|
tsadakane/TIGRE
|
a853cd2d4a6bc9509c01414b85ca75b4448fd700
|
[
"BSD-3-Clause"
] | 311
|
2016-07-05T16:00:06.000Z
|
2022-03-30T12:14:55.000Z
|
MATLAB/Utilities/IO/VarianCBCT/XimPara.hpp
|
tsadakane/TIGRE
|
a853cd2d4a6bc9509c01414b85ca75b4448fd700
|
[
"BSD-3-Clause"
] | 157
|
2016-08-08T12:13:09.000Z
|
2022-03-17T00:37:45.000Z
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
//typedef struct XimPara
#ifndef STR_XIM
#define STR_XIM
//struct XimPara
typedef struct XimPara
{
char FileName[256];
int ImgWidth; // Image Width
int ImgHeight; // Image Height
int PixelNO;
int BytesPerPixel; // Determine how to read the data
int Compression_Indicator; // Data number in Rec Image Matrix
double GantryRtn; // Gantry rotation angle
}XimPara;
#endif
//#ifndef cReadXim_FUN
//#define cReadXim_FUN
// int cReadXim(char *XimFullFile, XimPara *XimStr, int *XimImg);
//#endif
| 20.275862
| 65
| 0.732993
|
tsadakane
|
138b7b6196c41532498823ac52122a6f08c69992
| 174
|
hpp
|
C++
|
headers/Simulators/ModelLoadSimulator.hpp
|
Gilqamesh/GameEngineDemo
|
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
|
[
"MIT"
] | null | null | null |
headers/Simulators/ModelLoadSimulator.hpp
|
Gilqamesh/GameEngineDemo
|
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
|
[
"MIT"
] | null | null | null |
headers/Simulators/ModelLoadSimulator.hpp
|
Gilqamesh/GameEngineDemo
|
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
|
[
"MIT"
] | null | null | null |
#ifndef MODELLOADSIMULATOR_HPP
# define MODELLOADSIMULATOR_HPP
# include "pch.hpp"
namespace NAMESPACE
{
class ModelLoadSimulator
{
public:
void main();
};
}
#endif
| 9.666667
| 31
| 0.741379
|
Gilqamesh
|
ca5e0cf257dfdc1192f76a784250ddac75476081
| 2,803
|
cpp
|
C++
|
LibAudio/WASAPIDevice.cpp
|
ebragge/LibAudio
|
7848f257ba0ab83307e0498384c99469d7dedccb
|
[
"BSD-3-Clause"
] | 2
|
2016-01-28T10:47:42.000Z
|
2016-05-10T07:45:39.000Z
|
LibAudio/WASAPIDevice.cpp
|
ebragge/LibAudio
|
7848f257ba0ab83307e0498384c99469d7dedccb
|
[
"BSD-3-Clause"
] | null | null | null |
LibAudio/WASAPIDevice.cpp
|
ebragge/LibAudio
|
7848f257ba0ab83307e0498384c99469d7dedccb
|
[
"BSD-3-Clause"
] | null | null | null |
#include "pch.h"
#include "WASAPIDevice.h"
using namespace LibAudio;
WASAPIDevice::WASAPIDevice() : m_initialized(false)
{
}
void WASAPIDevice::StopAsync()
{
if (Capture != nullptr)
{
Capture->StopCaptureAsync();
}
}
void WASAPIDevice::InitCaptureDevice(size_t id, DataCollector^ collector)
{
Number = id;
if (Capture)
{
Capture = nullptr;
}
Capture = Make<WASAPICapture>();
StateChangedEvent = Capture->GetDeviceStateEvent();
DeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);
Capture->InitializeAudioDeviceAsync(ID, Number, collector);
m_initialized = true;
}
void WASAPIDevice::InitToneDevice(size_t id, DataCollector^ collector, uint32 frequency)
{
HRESULT hr = S_OK;
if (Renderer)
{
Renderer = nullptr;
}
Renderer = Make<WASAPIRenderer>();
StateChangedEvent = Renderer->GetDeviceStateEvent();
DeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);
DEVICEPROPS props;
props.IsTonePlayback = true;
props.Frequency = (DWORD)frequency;
props.IsHWOffload = false;
props.IsBackground = false;
Renderer->SetProperties(props);
Renderer->InitializeAudioDeviceAsync(ID, Number, collector);
m_initialized = true;
}
void WASAPIDevice::OnDeviceStateChange(Object^ sender, DeviceStateChangedEventArgs^ e)
{
// Get the current time for messages
auto t = Windows::Globalization::DateTimeFormatting::DateTimeFormatter::LongTime;
Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
calendar->SetToNow();
// Handle state specific messages
switch (e->State)
{
case DeviceState::DeviceStateActivated:
{
String^ str = String::Concat(ID, "-DeviceStateActivated\n");
OutputDebugString(str->Data());
break;
}
case DeviceState::DeviceStateInitialized:
{
String^ str = String::Concat(ID, "-DeviceStateInitialized\n");
OutputDebugString(str->Data());
if (Capture != nullptr)
{
Capture->StartCaptureAsync();
}
if (Renderer != nullptr)
{
Renderer->StartPlaybackAsync();
}
break;
}
case DeviceState::DeviceStateCapturing:
{
String^ str = String::Concat(ID, "-DeviceStateCapturing\n");
OutputDebugString(str->Data());
break;
}
case DeviceState::DeviceStateDiscontinuity:
{
String^ str = String::Concat(ID, "-DeviceStateDiscontinuity\n");
OutputDebugString(str->Data());
break;
}
case DeviceState::DeviceStateInError:
{
String^ str = String::Concat(ID, "-DeviceStateInError\n");
OutputDebugString(str->Data());
break;
}
}
}
| 24.80531
| 143
| 0.693899
|
ebragge
|
ca60f968abc4cb1646b9e36b4768f1389ad4d002
| 613
|
cpp
|
C++
|
src/logging/formatting_channel_logging.cpp
|
gbellizio/poco_showcase
|
f8974002d01a89149a6a50b4f676f421605f4524
|
[
"MIT"
] | null | null | null |
src/logging/formatting_channel_logging.cpp
|
gbellizio/poco_showcase
|
f8974002d01a89149a6a50b4f676f421605f4524
|
[
"MIT"
] | null | null | null |
src/logging/formatting_channel_logging.cpp
|
gbellizio/poco_showcase
|
f8974002d01a89149a6a50b4f676f421605f4524
|
[
"MIT"
] | null | null | null |
//
// Created by gennaro on 27/11/20.
//
#include <Poco/ConsoleChannel.h>
#include <Poco/FormattingChannel.h>
#include <Poco/Logger.h>
#include <Poco/PatternFormatter.h>
int main(int argc, char **argv) {
auto &logger = Poco::Logger::get("SampleApp");
auto pattern = new Poco::PatternFormatter("%L%Y-%m-%d %H:%M:%S.%F -%q- [%s] %t");
auto formatting_channel = new Poco::FormattingChannel(pattern);
formatting_channel->setChannel(new Poco::ConsoleChannel);
logger.setChannel(formatting_channel);
logger.information("a formatted informative message");
return 0;
}
| 32.263158
| 96
| 0.672104
|
gbellizio
|
ca661eaf8e55b7f188391d1a3146e13ddfe93ccb
| 34,374
|
cpp
|
C++
|
tapi-master/unittests/libtapi/LinkerInterfaceFileTest_TBD_v1.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
tapi-master/unittests/libtapi/LinkerInterfaceFileTest_TBD_v1.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
tapi-master/unittests/libtapi/LinkerInterfaceFileTest_TBD_v1.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
//===-- LinkerInterfaceFileTest_TBD_v1.cpp - Linker Interface File Test ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include <mach/machine.h>
#include <tapi/tapi.h>
using namespace tapi;
#define DEBUG_TYPE "libtapi-test"
static const char tbd_v1_file[] =
"---\n"
"archs: [ armv7, armv7s, armv7k, arm64 ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"current-version: 2.3.4\n"
"compatibility-version: 1.0\n"
"swift-version: 1.1\n"
"exports:\n"
" - archs: [ armv7, armv7s, armv7k, arm64 ]\n"
" symbols: [ _sym1, _sym2, _sym3, _sym4, $ld$hide$os9.0$_sym1 ]\n"
" objc-classes: [ _class1, _class2 ]\n"
" objc-ivars: [ _class1._ivar1, _class1._ivar2 ]\n"
" weak-def-symbols: [ _weak1, _weak2 ]\n"
" thread-local-symbols: [ _tlv1, _tlv2 ]\n"
" - archs: [ armv7, armv7s, armv7k ]\n"
" symbols: [ _sym5 ]\n"
" objc-classes: [ _class3 ]\n"
" objc-ivars: [ _class1._ivar3 ]\n"
" weak-def-symbols: [ _weak3 ]\n"
" thread-local-symbols: [ _tlv3 ]\n"
"...\n";
static const char tbd_v1_file3[] =
"---\n"
"archs: [ i386, x86_64 ]\n"
"platform: macosx\n"
"install-name: "
"/System/Library/Frameworks/CoreImage.framework/Versions/A/CoreImage\n"
"current-version: 5.0\n"
"compatibility-version: 1.0.1\n"
"exports:\n"
" - archs: [ i386, x86_64 ]\n"
" symbols: [ "
"'$ld$install_name$os10.10$/System/Library/Frameworks/QuartzCore.framework/"
"Versions/A/QuartzCore',\n"
" "
"'$ld$install_name$os10.4$/System/Library/Frameworks/QuartzCore.framework/"
"Versions/A/QuartzCore',\n"
" "
"'$ld$install_name$os10.5$/System/Library/Frameworks/QuartzCore.framework/"
"Versions/A/QuartzCore',\n"
" "
"'$ld$install_name$os10.6$/System/Library/Frameworks/QuartzCore.framework/"
"Versions/A/QuartzCore',\n"
" "
"'$ld$install_name$os10.7$/System/Library/Frameworks/QuartzCore.framework/"
"Versions/A/QuartzCore',\n"
" "
"'$ld$install_name$os10.8$/System/Library/Frameworks/QuartzCore.framework/"
"Versions/A/QuartzCore',\n"
" "
"'$ld$install_name$os10.9$/System/Library/Frameworks/QuartzCore.framework/"
"Versions/A/QuartzCore' ]\n"
"...\n";
static const char tbd_v1_file_unknown_platform[] = "---\n"
"archs: [ i386 ]\n"
"platform: unknown\n"
"install-name: Test.dylib\n"
"...\n";
static const unsigned char unsupported_file[] = {0xcf, 0xfa, 0xed, 0xfe, 0x07,
0x00, 0x00, 0x00, 0x00, 0x00};
static const char malformed_file[] = "---\n"
"archs: [ armv7, armv7s, armv7k, arm64 ]\n"
"foobar: \"Unsupported key\"\n"
"...\n";
static const char prefer_armv7[] = "---\n"
"archs: [ armv7, armv7s, armv7k, arm64 ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ armv7 ]\n"
" symbols: [ _correct ]\n"
" - archs: [ armv7s, armv7k, arm64 ]\n"
" symbols: [ _incorrect ]\n"
"...\n";
static const char prefer_armv7s[] = "---\n"
"archs: [ armv7, armv7s, armv7k, arm64 ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ armv7s ]\n"
" symbols: [ _correct ]\n"
" - archs: [ armv7, armv7k, arm64 ]\n"
" symbols: [ _incorrect ]\n"
"...\n";
static const char prefer_armv7k[] = "---\n"
"archs: [ armv7, armv7s, armv7k, arm64 ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ armv7k ]\n"
" symbols: [ _correct ]\n"
" - archs: [ armv7, armv7s, arm64 ]\n"
" symbols: [ _incorrect ]\n"
"...\n";
static const char prefer_arm64[] = "---\n"
"archs: [ armv7, armv7s, armv7k, arm64 ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ arm64 ]\n"
" symbols: [ _correct ]\n"
" - archs: [ armv7, armv7s, armv7k ]\n"
" symbols: [ _incorrect ]\n"
"...\n";
static const char prefer_i386[] = "---\n"
"archs: [ i386, x86_64, x86_64h ]\n"
"platform: macosx\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ i386 ]\n"
" symbols: [ _correct ]\n"
" - archs: [ x86_64, x86_64h ]\n"
" symbols: [ _incorrect ]\n"
"...\n";
static const char prefer_x86_64[] = "---\n"
"archs: [ i386, x86_64, x86_64h ]\n"
"platform: macosx\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ x86_64 ]\n"
" symbols: [ _correct ]\n"
" - archs: [ i386, x86_64h ]\n"
" symbols: [ _incorrect ]\n"
"...\n";
static const char prefer_x86_64h[] = "---\n"
"archs: [ i386, x86_64, x86_64h ]\n"
"platform: macosx\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ x86_64h ]\n"
" symbols: [ _correct ]\n"
" - archs: [ i386, x86_64]\n"
" symbols: [ _incorrect ]\n"
"...\n";
static const char fallback_armv7[] = "---\n"
"archs: [ armv7 ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ armv7 ]\n"
" symbols: [ _correct ]\n"
"...\n";
static const char fallback_armv7s[] = "---\n"
"archs: [ armv7s ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ armv7s ]\n"
" symbols: [ _correct ]\n"
"...\n";
static const char fallback_armv7k[] = "---\n"
"archs: [ armv7k ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ armv7k ]\n"
" symbols: [ _correct ]\n"
"...\n";
static const char fallback_arm64[] = "---\n"
"archs: [ arm64 ]\n"
"platform: ios\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ arm64 ]\n"
" symbols: [ _correct ]\n"
"...\n";
static const char fallback_i386[] = "---\n"
"archs: [ i386 ]\n"
"platform: macosx\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ i386 ]\n"
" symbols: [ _correct ]\n"
"...\n";
static const char fallback_x86_64[] = "---\n"
"archs: [ x86_64 ]\n"
"platform: macosx\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ x86_64 ]\n"
" symbols: [ _correct ]\n"
"...\n";
static const char fallback_x86_64h[] = "---\n"
"archs: [ x86_64h ]\n"
"platform: macosx\n"
"install-name: Test.dylib\n"
"exports:\n"
" - archs: [ x86_64h ]\n"
" symbols: [ _correct ]\n"
"...\n";
using ExportedSymbol = std::tuple<std::string, bool, bool>;
using ExportedSymbolSeq = std::vector<ExportedSymbol>;
inline bool operator<(const ExportedSymbol &lhs, const ExportedSymbol &rhs) {
return std::get<0>(lhs) < std::get<0>(rhs);
}
static ExportedSymbolSeq tbd_v1_arm_exports = {
{"_OBJC_CLASS_$_class1", false, false},
{"_OBJC_CLASS_$_class2", false, false},
{"_OBJC_CLASS_$_class3", false, false},
{"_OBJC_IVAR_$_class1._ivar1", false, false},
{"_OBJC_IVAR_$_class1._ivar2", false, false},
{"_OBJC_IVAR_$_class1._ivar3", false, false},
{"_OBJC_METACLASS_$_class1", false, false},
{"_OBJC_METACLASS_$_class2", false, false},
{"_OBJC_METACLASS_$_class3", false, false},
{"_sym2", false, false},
{"_sym3", false, false},
{"_sym4", false, false},
{"_sym5", false, false},
{"_tlv1", false, true},
{"_tlv2", false, true},
{"_tlv3", false, true},
{"_weak1", true, false},
{"_weak2", true, false},
{"_weak3", true, false},
};
static ExportedSymbolSeq tbd_v1_arm64_exports = {
{"_OBJC_CLASS_$_class1", false, false},
{"_OBJC_CLASS_$_class2", false, false},
{"_OBJC_IVAR_$_class1._ivar1", false, false},
{"_OBJC_IVAR_$_class1._ivar2", false, false},
{"_OBJC_METACLASS_$_class1", false, false},
{"_OBJC_METACLASS_$_class2", false, false},
{"_sym2", false, false},
{"_sym3", false, false},
{"_sym4", false, false},
{"_tlv1", false, true},
{"_tlv2", false, true},
{"_weak1", true, false},
{"_weak2", true, false},
};
namespace TBDv1 {
TEST(libtapiTBDv1, LIF_isSupported) {
llvm::StringRef buffer(tbd_v1_file);
bool isSupported1 = LinkerInterfaceFile::isSupported(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size());
bool isSupported2 = LinkerInterfaceFile::isSupported(
"Test.tbd", reinterpret_cast<const uint8_t *>(unsupported_file),
sizeof(unsupported_file));
ASSERT_TRUE(isSupported1);
ASSERT_FALSE(isSupported2);
}
// Test parsing a .tbd file from a memory buffer/nmapped file
TEST(libtapiTBDv1, LIF_Load_ARM) {
llvm::StringRef buffer(tbd_v1_file);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ(FileType::TBD_V1, file->getFileType());
EXPECT_EQ(Platform::iOS, file->getPlatform());
EXPECT_EQ(std::string("Test.dylib"), file->getInstallName());
EXPECT_EQ(0x20304U, file->getCurrentVersion());
EXPECT_EQ(0x10000U, file->getCompatibilityVersion());
EXPECT_EQ(2U, file->getSwiftVersion());
ExportedSymbolSeq exports;
for (const auto &sym : file->exports())
exports.emplace_back(sym.getName(), sym.isWeakDefined(),
sym.isThreadLocalValue());
std::sort(exports.begin(), exports.end());
ASSERT_EQ(tbd_v1_arm_exports.size(), exports.size());
EXPECT_TRUE(
std::equal(exports.begin(), exports.end(), tbd_v1_arm_exports.begin()));
}
TEST(libtapiTBDv1, LIF_Load_ARM64) {
llvm::StringRef buffer(tbd_v1_file);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ(FileType::TBD_V1, file->getFileType());
EXPECT_EQ(Platform::iOS, file->getPlatform());
EXPECT_EQ(std::string("Test.dylib"), file->getInstallName());
EXPECT_EQ(0x20304U, file->getCurrentVersion());
EXPECT_EQ(0x10000U, file->getCompatibilityVersion());
EXPECT_EQ(2U, file->getSwiftVersion());
ExportedSymbolSeq exports;
for (const auto &sym : file->exports())
exports.emplace_back(sym.getName(), sym.isWeakDefined(),
sym.isThreadLocalValue());
std::sort(exports.begin(), exports.end());
ASSERT_EQ(tbd_v1_arm64_exports.size(), exports.size());
EXPECT_TRUE(
std::equal(exports.begin(), exports.end(), tbd_v1_arm64_exports.begin()));
}
TEST(libtapiTBDv1, LIF_Load_Install_Name) {
llvm::StringRef buffer(tbd_v1_file3);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"/System/Library/Frameworks/CoreImage.framework/Versions/A/CoreImage.tbd",
reinterpret_cast<const uint8_t *>(buffer.data()), buffer.size(),
CPU_TYPE_X86, CPU_SUBTYPE_X86_ALL, CpuSubTypeMatching::ABI_Compatible,
PackedVersion32(10, 10, 0), errorMessage));
ASSERT_TRUE(errorMessage.empty());
ASSERT_NE(nullptr, file);
ASSERT_EQ(FileType::TBD_V1, file->getFileType());
EXPECT_EQ(Platform::OSX, file->getPlatform());
EXPECT_EQ(std::string("/System/Library/Frameworks/QuartzCore.framework/"
"Versions/A/QuartzCore"),
file->getInstallName());
EXPECT_EQ(0x50000U, file->getCurrentVersion());
EXPECT_EQ(0x10001U, file->getCompatibilityVersion());
EXPECT_TRUE(file->isApplicationExtensionSafe());
EXPECT_TRUE(file->hasTwoLevelNamespace());
EXPECT_TRUE(file->isInstallNameVersionSpecific());
}
TEST(libtapiTBDv1, LIF_Load_Unknown_Platform) {
llvm::StringRef buffer(tbd_v1_file_unknown_platform);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_I386, CPU_SUBTYPE_I386_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ(FileType::TBD_V1, file->getFileType());
EXPECT_EQ(Platform::Unknown, file->getPlatform());
EXPECT_EQ(std::string("Test.dylib"), file->getInstallName());
}
// Test for invalid files.
TEST(libtapiTBDv1, LIF_UnsupportedFileType) {
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(unsupported_file),
sizeof(unsupported_file), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("unsupported file type", errorMessage);
}
TEST(libtapiTBDv1, LIF_MalformedFile) {
llvm::StringRef buffer(malformed_file);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("malformed file\nTest.tbd:2:1: error: missing required key "
"'platform'\narchs: [ armv7, armv7s, armv7k, arm64 ]\n^\n",
errorMessage);
}
TEST(libtapiTBDv1, LIF_ArchitectureNotFound) {
llvm::StringRef buffer(tbd_v1_file);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture x86_64 in file Test.tbd (4 slices)",
errorMessage);
}
TEST(libtapiTBDv1, LIF_SelectPreferedSlice_armv7) {
llvm::StringRef buffer(prefer_armv7);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_SelectPreferedSlice_armv7s) {
llvm::StringRef buffer(prefer_armv7s);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_SelectPreferedSlice_armv7k) {
llvm::StringRef buffer(prefer_armv7k);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7K,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_SelectPreferedSlice_arm64) {
llvm::StringRef buffer(prefer_arm64);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_SelectPreferedSlice_i386) {
llvm::StringRef buffer(prefer_i386);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_I386, CPU_SUBTYPE_386,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_SelectPreferedSlice_x86_64) {
llvm::StringRef buffer(prefer_x86_64);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_SelectPreferedSlice_x86_64h) {
llvm::StringRef buffer(prefer_x86_64h);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_H,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_FallBack_armv7) {
llvm::StringRef buffer(fallback_armv7);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7K,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture arm64 in file Test.tbd",
errorMessage);
}
TEST(libtapiTBDv1, LIF_FallBack_armv7s) {
llvm::StringRef buffer(fallback_armv7s);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7K,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture arm64 in file Test.tbd",
errorMessage);
}
TEST(libtapiTBDv1, LIF_FallBack_armv7k) {
llvm::StringRef buffer(fallback_armv7k);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7K,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture arm64 in file Test.tbd",
errorMessage);
}
TEST(libtapiTBDv1, LIF_FallBack_arm64) {
llvm::StringRef buffer(fallback_arm64);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture armv7 in file Test.tbd",
errorMessage);
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture armv7s in file Test.tbd",
errorMessage);
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7K,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture armv7k in file Test.tbd",
errorMessage);
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(9, 0, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_FallBack_i386) {
llvm::StringRef buffer(fallback_i386);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_I386, CPU_SUBTYPE_386,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture x86_64 in file Test.tbd",
errorMessage);
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_H,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture x86_64h in file Test.tbd",
errorMessage);
}
TEST(libtapiTBDv1, LIF_FallBack_x86_64) {
llvm::StringRef buffer(fallback_x86_64);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_I386, CPU_SUBTYPE_386,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture i386 in file Test.tbd",
errorMessage);
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_H,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_FallBack_x86_64h) {
llvm::StringRef buffer(fallback_x86_64h);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_I386, CPU_SUBTYPE_386,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture i386 in file Test.tbd",
errorMessage);
errorMessage.clear();
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_H,
CpuSubTypeMatching::ABI_Compatible, PackedVersion32(10, 11, 0),
errorMessage));
ASSERT_NE(nullptr, file);
ASSERT_TRUE(errorMessage.empty());
ASSERT_EQ("_correct", file->exports().front().getName());
}
TEST(libtapiTBDv1, LIF_No_FallBack_x86_64h) {
llvm::StringRef buffer(fallback_x86_64h);
std::string errorMessage;
auto file = std::unique_ptr<LinkerInterfaceFile>(LinkerInterfaceFile::create(
"Test.tbd", reinterpret_cast<const uint8_t *>(buffer.data()),
buffer.size(), CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL,
CpuSubTypeMatching::Exact, PackedVersion32(10, 11, 0), errorMessage));
ASSERT_EQ(nullptr, file);
ASSERT_EQ("missing required architecture x86_64 in file Test.tbd",
errorMessage);
}
} // end namespace TBDv1
| 43.732824
| 80
| 0.602141
|
JunyiXie
|
ca6840f3bfe127d7d52a92e48e146582ae9b9bf1
| 4,599
|
cpp
|
C++
|
src/Eigen-3.3/unsupported/test/cxx11_tensor_volume_patch.cpp
|
shareq2005/CarND-MPC-Project
|
f4094e8b446d2fac2ca0a4c5054d5058621595b0
|
[
"MIT"
] | 3,457
|
2018-06-09T15:36:42.000Z
|
2020-06-01T22:09:25.000Z
|
src/Eigen-3.3/unsupported/test/cxx11_tensor_volume_patch.cpp
|
shareq2005/CarND-MPC-Project
|
f4094e8b446d2fac2ca0a4c5054d5058621595b0
|
[
"MIT"
] | 1,057
|
2015-04-27T04:27:57.000Z
|
2022-03-31T13:14:59.000Z
|
src/Eigen-3.3/unsupported/test/cxx11_tensor_volume_patch.cpp
|
shareq2005/CarND-MPC-Project
|
f4094e8b446d2fac2ca0a4c5054d5058621595b0
|
[
"MIT"
] | 1,380
|
2017-06-12T23:58:23.000Z
|
2022-03-31T14:52:48.000Z
|
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
static void test_single_voxel_patch()
{
Tensor<float, 5> tensor(4,2,3,5,7);
tensor.setRandom();
Tensor<float, 5, RowMajor> tensor_row_major = tensor.swap_layout();
Tensor<float, 6> single_voxel_patch;
single_voxel_patch = tensor.extract_volume_patches(1, 1, 1);
VERIFY_IS_EQUAL(single_voxel_patch.dimension(0), 4);
VERIFY_IS_EQUAL(single_voxel_patch.dimension(1), 1);
VERIFY_IS_EQUAL(single_voxel_patch.dimension(2), 1);
VERIFY_IS_EQUAL(single_voxel_patch.dimension(3), 1);
VERIFY_IS_EQUAL(single_voxel_patch.dimension(4), 2 * 3 * 5);
VERIFY_IS_EQUAL(single_voxel_patch.dimension(5), 7);
Tensor<float, 6, RowMajor> single_voxel_patch_row_major;
single_voxel_patch_row_major = tensor_row_major.extract_volume_patches(1, 1, 1);
VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(0), 7);
VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(1), 2 * 3 * 5);
VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(2), 1);
VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(3), 1);
VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(4), 1);
VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(5), 4);
for (int i = 0; i < tensor.size(); ++i) {
VERIFY_IS_EQUAL(tensor.data()[i], single_voxel_patch.data()[i]);
VERIFY_IS_EQUAL(tensor_row_major.data()[i], single_voxel_patch_row_major.data()[i]);
VERIFY_IS_EQUAL(tensor.data()[i], tensor_row_major.data()[i]);
}
}
static void test_entire_volume_patch()
{
const int depth = 4;
const int patch_z = 2;
const int patch_y = 3;
const int patch_x = 5;
const int batch = 7;
Tensor<float, 5> tensor(depth, patch_z, patch_y, patch_x, batch);
tensor.setRandom();
Tensor<float, 5, RowMajor> tensor_row_major = tensor.swap_layout();
Tensor<float, 6> entire_volume_patch;
entire_volume_patch = tensor.extract_volume_patches(patch_z, patch_y, patch_x);
VERIFY_IS_EQUAL(entire_volume_patch.dimension(0), depth);
VERIFY_IS_EQUAL(entire_volume_patch.dimension(1), patch_z);
VERIFY_IS_EQUAL(entire_volume_patch.dimension(2), patch_y);
VERIFY_IS_EQUAL(entire_volume_patch.dimension(3), patch_x);
VERIFY_IS_EQUAL(entire_volume_patch.dimension(4), patch_z * patch_y * patch_x);
VERIFY_IS_EQUAL(entire_volume_patch.dimension(5), batch);
Tensor<float, 6, RowMajor> entire_volume_patch_row_major;
entire_volume_patch_row_major = tensor_row_major.extract_volume_patches(patch_z, patch_y, patch_x);
VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(0), batch);
VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(1), patch_z * patch_y * patch_x);
VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(2), patch_x);
VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(3), patch_y);
VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(4), patch_z);
VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(5), depth);
const int dz = patch_z - 1;
const int dy = patch_y - 1;
const int dx = patch_x - 1;
const int forward_pad_z = dz - dz / 2;
const int forward_pad_y = dy - dy / 2;
const int forward_pad_x = dx - dx / 2;
for (int pz = 0; pz < patch_z; pz++) {
for (int py = 0; py < patch_y; py++) {
for (int px = 0; px < patch_x; px++) {
const int patchId = pz + patch_z * (py + px * patch_y);
for (int z = 0; z < patch_z; z++) {
for (int y = 0; y < patch_y; y++) {
for (int x = 0; x < patch_x; x++) {
for (int b = 0; b < batch; b++) {
for (int d = 0; d < depth; d++) {
float expected = 0.0f;
float expected_row_major = 0.0f;
const int eff_z = z - forward_pad_z + pz;
const int eff_y = y - forward_pad_y + py;
const int eff_x = x - forward_pad_x + px;
if (eff_z >= 0 && eff_y >= 0 && eff_x >= 0 &&
eff_z < patch_z && eff_y < patch_y && eff_x < patch_x) {
expected = tensor(d, eff_z, eff_y, eff_x, b);
expected_row_major = tensor_row_major(b, eff_x, eff_y, eff_z, d);
}
VERIFY_IS_EQUAL(entire_volume_patch(d, z, y, x, patchId, b), expected);
VERIFY_IS_EQUAL(entire_volume_patch_row_major(b, patchId, x, y, z, d), expected_row_major);
}
}
}
}
}
}
}
}
}
void test_cxx11_tensor_volume_patch()
{
CALL_SUBTEST(test_single_voxel_patch());
CALL_SUBTEST(test_entire_volume_patch());
}
| 40.699115
| 109
| 0.676451
|
shareq2005
|
ca6a0b6d9a2e68b8167525fa71d6a140769658d1
| 424
|
cpp
|
C++
|
reversevec.cpp
|
Mohamed742/C-AIMS-SA-2018
|
a59ba718872dfae0f8ee216b10dbb66db3e8a921
|
[
"Apache-2.0"
] | null | null | null |
reversevec.cpp
|
Mohamed742/C-AIMS-SA-2018
|
a59ba718872dfae0f8ee216b10dbb66db3e8a921
|
[
"Apache-2.0"
] | null | null | null |
reversevec.cpp
|
Mohamed742/C-AIMS-SA-2018
|
a59ba718872dfae0f8ee216b10dbb66db3e8a921
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
#include <vector>
#include <algorithm>
#include<cmath>
using namespace std;
double rev1(vector<int>v)
{
vector<int> w;
{
for (int i = v.size()-1 ; 0<=i ;i--)
w.push_back(v[i]);
v = w;
}
for(auto &k : w)
cout << k << endl;
}
int main()
{
vector<int> vec14 = {123,78,15,14};
vec14.swap(vec14[0],vec14[2]);
for (auto &r : vec14){
cout<< r <<endl;
}
}
| 14.62069
| 42
| 0.528302
|
Mohamed742
|
ca77deeb672f63241c5ea023db003d8cc0a21581
| 520
|
cpp
|
C++
|
plugins/Ninjas/scratchpad/find_nearest.cpp
|
rghvdberg/ninjas
|
089b7766c3a8c0ab66421c3d6e97e0a06908e4cc
|
[
"0BSD"
] | 22
|
2017-11-11T10:29:37.000Z
|
2021-10-16T16:42:39.000Z
|
plugins/Ninjas/scratchpad/find_nearest.cpp
|
rghvdberg/ninjas
|
089b7766c3a8c0ab66421c3d6e97e0a06908e4cc
|
[
"0BSD"
] | 26
|
2017-11-11T08:52:59.000Z
|
2018-01-18T11:34:12.000Z
|
plugins/Ninjas/scratchpad/find_nearest.cpp
|
rghvdberg/ninjas
|
089b7766c3a8c0ab66421c3d6e97e0a06908e4cc
|
[
"0BSD"
] | 3
|
2017-11-30T20:30:58.000Z
|
2018-04-03T19:31:36.000Z
|
#include <iostream>
#include <vector>
#include <algorithm>
template <typename T, typename U>
auto find_nearest(T&& haystack, U&& needle)
{
auto distance_to_needle_comparator = [&](auto&& a, auto&& b) {
return abs(a - needle) < abs(b - needle);
};
return std::min_element(std::begin(haystack), std::end(haystack),
distance_to_needle_comparator);
}
int main()
{
std::vector<int> vec{10, 15, 17, 25, 21};
auto n = 20;
std::cout << *find_nearest(vec, n);
}
| 23.636364
| 69
| 0.6
|
rghvdberg
|
ca78933fd78339a655916b36910a5312220263ec
| 10,902
|
cpp
|
C++
|
gdal/frmts/pcidsk/sdk/segment/vecsegdataindex.cpp
|
cartosquare/gdal
|
c2ce185366e6276e77bbebbe9fe509055ed6d0fd
|
[
"MIT"
] | null | null | null |
gdal/frmts/pcidsk/sdk/segment/vecsegdataindex.cpp
|
cartosquare/gdal
|
c2ce185366e6276e77bbebbe9fe509055ed6d0fd
|
[
"MIT"
] | null | null | null |
gdal/frmts/pcidsk/sdk/segment/vecsegdataindex.cpp
|
cartosquare/gdal
|
c2ce185366e6276e77bbebbe9fe509055ed6d0fd
|
[
"MIT"
] | 1
|
2021-11-21T02:33:51.000Z
|
2021-11-21T02:33:51.000Z
|
/******************************************************************************
*
* Purpose: Implementation of the VecSegIndex class.
*
* This class is used to manage a vector segment data block index. There
* will be two instances created, one for the record data (sec_record) and
* one for the vertices (sec_vert). This class is exclusively a private
* helper class for VecSegHeader.
*
******************************************************************************
* Copyright (c) 2010
* PCI Geomatics, 90 Allstate Parkway, Markham, Ontario, Canada.
*
* 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 "pcidsk.h"
#include "core/pcidsk_utils.h"
#include "segment/cpcidskvectorsegment.h"
#include <cassert>
#include <cstring>
#include <cstdio>
#include <limits>
using namespace PCIDSK;
/* -------------------------------------------------------------------- */
/* Size of a block in the record/vertex block tables. This is */
/* determined by the PCIDSK format and may not be changed. */
/* -------------------------------------------------------------------- */
static const int block_page_size = 8192;
/************************************************************************/
/* VecSegDataIndex() */
/************************************************************************/
VecSegDataIndex::VecSegDataIndex()
{
block_initialized = false;
vs = nullptr;
dirty = false;
section = 0;
offset_on_disk_within_section = 0;
size_on_disk = 0;
block_count = 0;
bytes = 0;
}
/************************************************************************/
/* ~VecSegDataIndex() */
/************************************************************************/
VecSegDataIndex::~VecSegDataIndex()
{
}
/************************************************************************/
/* Initialize() */
/************************************************************************/
void VecSegDataIndex::Initialize( CPCIDSKVectorSegment *vsIn, int sectionIn )
{
this->section = sectionIn;
this->vs = vsIn;
if( section == sec_vert )
offset_on_disk_within_section = 0;
else
offset_on_disk_within_section = vs->di[sec_vert].SerializedSize();
uint32 offset = offset_on_disk_within_section
+ vs->vh.section_offsets[hsec_shape];
memcpy( &block_count, vs->GetData(sec_raw,offset,nullptr,4), 4);
memcpy( &bytes, vs->GetData(sec_raw,offset+4,nullptr,4), 4);
bool needs_swap = !BigEndianSystem();
if( needs_swap )
{
SwapData( &block_count, 4, 1 );
SwapData( &bytes, 4, 1 );
}
if( block_count > (std::numeric_limits<uint32>::max() - 8) /4 )
{
throw PCIDSKException("Invalid block_count: %u", block_count);
}
size_on_disk = block_count * 4 + 8;
}
/************************************************************************/
/* SerializedSize() */
/************************************************************************/
uint32 VecSegDataIndex::SerializedSize()
{
return 8 + 4 * block_count;
}
/************************************************************************/
/* GetBlockIndex() */
/************************************************************************/
const std::vector<uint32> *VecSegDataIndex::GetIndex()
{
/* -------------------------------------------------------------------- */
/* Load block map if needed. */
/* -------------------------------------------------------------------- */
if( !block_initialized )
{
bool needs_swap = !BigEndianSystem();
auto offset = offset_on_disk_within_section
+ vs->vh.section_offsets[hsec_shape] + 8;
vs->CheckFileBigEnough ( offset + 4 * block_count );
try
{
block_index.resize( block_count );
}
catch( const std::exception& ex )
{
throw PCIDSKException("Out of memory allocating block_index(%u): %s",
block_count, ex.what());
}
if( block_count > 0 )
{
vs->ReadFromFile( &(block_index[0]),
offset,
4 * block_count );
if( needs_swap )
SwapData( &(block_index[0]), 4, block_count );
}
block_initialized = true;
}
return &block_index;
}
/************************************************************************/
/* Flush() */
/************************************************************************/
void VecSegDataIndex::Flush()
{
if( !dirty )
return;
GetIndex(); // force loading if not already loaded!
PCIDSKBuffer wbuf( SerializedSize() );
memcpy( wbuf.buffer + 0, &block_count, 4 );
memcpy( wbuf.buffer + 4, &bytes, 4 );
memcpy( wbuf.buffer + 8, &(block_index[0]), 4*block_count );
bool needs_swap = !BigEndianSystem();
if( needs_swap )
SwapData( wbuf.buffer, 4, block_count+2 );
// Make sure this section of the header is large enough.
int32 shift = (int32) wbuf.buffer_size - (int32) size_on_disk;
if( shift != 0 )
{
uint32 old_section_size = vs->vh.section_sizes[hsec_shape];
// fprintf( stderr, "Shifting section %d by %d bytes.\n",
// section, shift );
vs->vh.GrowSection( hsec_shape, old_section_size + shift );
if( section == sec_vert )
{
// move record block index and shape index.
vs->MoveData( vs->vh.section_offsets[hsec_shape]
+ vs->di[sec_vert].size_on_disk,
vs->vh.section_offsets[hsec_shape]
+ vs->di[sec_vert].size_on_disk + shift,
old_section_size - size_on_disk );
}
else
{
// only move shape index.
vs->MoveData( vs->vh.section_offsets[hsec_shape]
+ vs->di[sec_vert].size_on_disk
+ vs->di[sec_record].size_on_disk,
vs->vh.section_offsets[hsec_shape]
+ vs->di[sec_vert].size_on_disk
+ vs->di[sec_record].size_on_disk
+ shift,
old_section_size
- vs->di[sec_vert].size_on_disk
- vs->di[sec_record].size_on_disk );
}
if( section == sec_vert )
vs->di[sec_record].offset_on_disk_within_section += shift;
}
// Actually write to disk.
vs->WriteToFile( wbuf.buffer,
offset_on_disk_within_section
+ vs->vh.section_offsets[hsec_shape],
wbuf.buffer_size );
size_on_disk = wbuf.buffer_size;
dirty = false;
}
/************************************************************************/
/* GetSectionEnd() */
/************************************************************************/
uint32 VecSegDataIndex::GetSectionEnd()
{
return bytes;
}
/************************************************************************/
/* SetSectionEnd() */
/************************************************************************/
void VecSegDataIndex::SetSectionEnd( uint32 new_end )
{
// should we keep track of the need to write this back to disk?
bytes = new_end;
}
/************************************************************************/
/* AddBlockToIndex() */
/************************************************************************/
void VecSegDataIndex::AddBlockToIndex( uint32 block )
{
GetIndex(); // force loading.
block_index.push_back( block );
block_count++;
dirty = true;
}
/************************************************************************/
/* SetDirty() */
/* */
/* This method is primarily used to mark the need to write the */
/* index when the location changes. */
/************************************************************************/
void VecSegDataIndex::SetDirty()
{
dirty = true;
}
/************************************************************************/
/* VacateBlockRange() */
/* */
/* Move any blocks in the indicated block range to the end of */
/* the segment to make space for a growing header. */
/************************************************************************/
void VecSegDataIndex::VacateBlockRange( uint32 start, uint32 count )
{
GetIndex(); // make sure loaded.
unsigned int i;
uint32 next_block = (uint32) (vs->GetContentSize() / block_page_size);
for( i = 0; i < block_count; i++ )
{
if( block_index[i] >= start && block_index[i] < start+count )
{
vs->MoveData( block_index[i] * block_page_size,
next_block * block_page_size,
block_page_size );
block_index[i] = next_block;
dirty = true;
next_block++;
}
}
}
| 34.830671
| 81
| 0.436801
|
cartosquare
|
ca7c17c03f468111787a73a6781f59c8fe223090
| 1,739
|
cpp
|
C++
|
oxygine/src/oxygine/Font.cpp
|
on-three/oxygine-framework
|
12afd02e155cfd502523bb76c9dc94ff59cafd53
|
[
"MIT"
] | null | null | null |
oxygine/src/oxygine/Font.cpp
|
on-three/oxygine-framework
|
12afd02e155cfd502523bb76c9dc94ff59cafd53
|
[
"MIT"
] | null | null | null |
oxygine/src/oxygine/Font.cpp
|
on-three/oxygine-framework
|
12afd02e155cfd502523bb76c9dc94ff59cafd53
|
[
"MIT"
] | null | null | null |
#include "Font.h"
#include "core/NativeTexture.h"
namespace oxygine
{
Font::Font() : _ignoreOptions(true), _scale(1.0f), _sdf(false), _size(0), _baselineDistance(0)
{
}
Font::~Font()
{
}
void Font::init(const char* name, int realSize, int baselineDistance, int lineHeight, bool sdf)
{
setName(name);
_sdf = sdf;
_size = realSize;
_baselineDistance = baselineDistance;
}
void Font::addGlyph(const glyph& gl)
{
_glyphs.insert(gl);
}
void Font::clear()
{
_glyphs.clear();
}
bool glyphFindPred(const glyph& g, int code)
{
return g.ch < code;
}
bool glyphsComparePred(const glyph& ob1, const glyph& ob2)
{
return ob1.ch < ob2.ch;
}
const glyph* Font::findGlyph(int code, const glyphOptions& opt) const
{
glyph g;
g.ch = code;
g.opt = _ignoreOptions ? 0 : opt;
glyphs::const_iterator it = _glyphs.find(g);
if (it != _glyphs.end())
{
return &(*it);
}
return 0;
}
const glyph* Font::getGlyph(int code, const glyphOptions& opt) const
{
const glyph* g = findGlyph(code, opt);
if (g)
return g;
glyph gl;
Font* fn = const_cast<Font*>(this);
if (fn->loadGlyph(code, gl, opt))
{
fn->_glyphs.insert(gl);
g = findGlyph(code, opt);
OX_ASSERT(g);
}
return g;
}
int Font::getBaselineDistance() const
{
return _baselineDistance;
}
int Font::getSize() const
{
return _size;
}
float Font::getScale() const
{
return _scale;
}
}
| 19.761364
| 99
| 0.525014
|
on-three
|
ca7fc3404e1bd3f3ba84676bfee89a0dc2975794
| 465
|
cpp
|
C++
|
Drakhtar/Telemetria/TrackerEvents/RoundEndEvent.cpp
|
CarlosMGM/Drakhtar_Telemetria
|
551e2e6bd1893f6d5e7d627838a71775ad0f4a41
|
[
"MIT"
] | null | null | null |
Drakhtar/Telemetria/TrackerEvents/RoundEndEvent.cpp
|
CarlosMGM/Drakhtar_Telemetria
|
551e2e6bd1893f6d5e7d627838a71775ad0f4a41
|
[
"MIT"
] | null | null | null |
Drakhtar/Telemetria/TrackerEvents/RoundEndEvent.cpp
|
CarlosMGM/Drakhtar_Telemetria
|
551e2e6bd1893f6d5e7d627838a71775ad0f4a41
|
[
"MIT"
] | null | null | null |
#include "RoundEndEvent.h"
RoundEndEvent::RoundEndEvent() : EndEvent(ROUND_END) {}
std::string RoundEndEvent::toJson() {
std::string str = ",\n";
str += " {\n";
str += R"( "Event Type": "Round End Event",)";
str += "\n" + EndEvent::toJson() + +",\n";
str += R"( "Round#": )" + std::to_string(roundNumber_) + "\n";
str += " }";
return str;
}
void RoundEndEvent::setRoundNumber(uint32_t roundNumber) {
roundNumber_ = roundNumber;
}
| 25.833333
| 69
| 0.587097
|
CarlosMGM
|
ca8b90f8ccf2d1c7e64d954811cedb4ca3b5e287
| 170
|
cpp
|
C++
|
Tests/Tests/all_tests.cpp
|
CaptainKant/RottenFish
|
32f205b3447ddc1f8f569fcf282f5123dbd0f25d
|
[
"MIT"
] | null | null | null |
Tests/Tests/all_tests.cpp
|
CaptainKant/RottenFish
|
32f205b3447ddc1f8f569fcf282f5123dbd0f25d
|
[
"MIT"
] | null | null | null |
Tests/Tests/all_tests.cpp
|
CaptainKant/RottenFish
|
32f205b3447ddc1f8f569fcf282f5123dbd0f25d
|
[
"MIT"
] | null | null | null |
//
// Created by Emmanuel Cervetti on 03/10/2016.
//
#include "loading_check.cpp"
#include "log2_check.cpp"
#include "random_check.cpp"
#include "rottenfish_check.cpp"
| 17
| 46
| 0.741176
|
CaptainKant
|
ca8fdd50fde80e3f8aa6586bcfb952c5ba5cb9e0
| 1,930
|
hpp
|
C++
|
src/RateLimiter.hpp
|
spebern/cpp-burst-pool-node
|
0cbf0759cd166ef7c3f850059180d3a8ceb158eb
|
[
"MIT"
] | null | null | null |
src/RateLimiter.hpp
|
spebern/cpp-burst-pool-node
|
0cbf0759cd166ef7c3f850059180d3a8ceb158eb
|
[
"MIT"
] | null | null | null |
src/RateLimiter.hpp
|
spebern/cpp-burst-pool-node
|
0cbf0759cd166ef7c3f850059180d3a8ceb158eb
|
[
"MIT"
] | 2
|
2018-09-20T16:11:14.000Z
|
2018-12-12T08:46:30.000Z
|
#pragma once
#include <unordered_map>
#include <string>
#include <memory>
#include <boost/thread/thread.hpp>
#include <stdint.h>
#include <atomic>
#include <chrono>
class Bucket {
private:
std::atomic<double> _zero_time;
public:
Bucket(double zero_time = 0.0) :
_zero_time(zero_time) {};
bool aquire(double now, double rate, double burst_size, double consume = 1.0) {
auto zero_time_old = _zero_time.load();
double zero_time_new;
do {
double tokens = std::min((now - zero_time_old) * rate, burst_size);
if (tokens < consume) {
return false;
} else {
tokens -= consume;
}
zero_time_new = now - tokens / rate;
} while(!_zero_time.compare_exchange_weak(zero_time_old, zero_time_new));
return true;
}
};
class RateLimiter {
private:
double _rate;
double _burst_size;
std::unordered_map<std::string, std::unique_ptr<Bucket> > _key_to_bucket;
boost::shared_mutex _key_to_bucket_mu;
static double now() {
using dur = std::chrono::duration<double>;
auto const now = std::chrono::steady_clock::now().time_since_epoch();
return std::chrono::duration_cast<dur>(now).count();
}
public:
RateLimiter(double rate, double burst_size) :
_rate(rate),
_burst_size(burst_size) {};
bool aquire(std::string &key) {
boost::upgrade_lock<boost::shared_mutex> lock(_key_to_bucket_mu);
auto bucket_it = _key_to_bucket.find(key);
if (bucket_it == _key_to_bucket.end()) {
boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(lock);
std::unique_ptr<Bucket> bucket(new Bucket());
_key_to_bucket[key] = std::move(bucket);
return true;
} else {
return bucket_it->second->aquire(now(), _rate, _burst_size);
}
};
};
| 30.15625
| 83
| 0.61658
|
spebern
|
ca926beadc631709832830a3bd0023f2b60577f2
| 51,586
|
cpp
|
C++
|
opencv/build/modules/rgbd/opencl_kernels_rgbd.cpp
|
soyyuz/opencv-contrib-ARM64
|
25386df773f88a071532ec69ff541c31e62ec8f2
|
[
"Apache-2.0"
] | null | null | null |
opencv/build/modules/rgbd/opencl_kernels_rgbd.cpp
|
soyyuz/opencv-contrib-ARM64
|
25386df773f88a071532ec69ff541c31e62ec8f2
|
[
"Apache-2.0"
] | null | null | null |
opencv/build/modules/rgbd/opencl_kernels_rgbd.cpp
|
soyyuz/opencv-contrib-ARM64
|
25386df773f88a071532ec69ff541c31e62ec8f2
|
[
"Apache-2.0"
] | 1
|
2022-03-27T03:35:07.000Z
|
2022-03-27T03:35:07.000Z
|
// This file is auto-generated. Do not edit!
#include "opencv2/core.hpp"
#include "cvconfig.h"
#include "opencl_kernels_rgbd.hpp"
#ifdef HAVE_OPENCL
namespace cv
{
namespace ocl
{
namespace rgbd
{
static const char* const moduleName = "rgbd";
struct cv::ocl::internal::ProgramEntry hash_tsdf_oclsrc={moduleName, "hash_tsdf",
"#define USE_INTERPOLATION_IN_GETNORMAL 1\n"
"#define HASH_DIVISOR 32768\n"
"typedef char int8_t;\n"
"typedef uint int32_t;\n"
"typedef int8_t TsdfType;\n"
"typedef uchar WeightType;\n"
"struct TsdfVoxel\n"
"{\n"
"TsdfType tsdf;\n"
"WeightType weight;\n"
"};\n"
"static inline TsdfType floatToTsdf(float num)\n"
"{\n"
"int8_t res = (int8_t) ( (num * (-128)) );\n"
"res = res ? res : (num < 0 ? 1 : -1);\n"
"return res;\n"
"}\n"
"static inline float tsdfToFloat(TsdfType num)\n"
"{\n"
"return ( (float) num ) / (-128);\n"
"}\n"
"static uint calc_hash(int3 x)\n"
"{\n"
"unsigned int seed = 0;\n"
"unsigned int GOLDEN_RATIO = 0x9e3779b9;\n"
"seed ^= x.s0 + GOLDEN_RATIO + (seed << 6) + (seed >> 2);\n"
"seed ^= x.s1 + GOLDEN_RATIO + (seed << 6) + (seed >> 2);\n"
"seed ^= x.s2 + GOLDEN_RATIO + (seed << 6) + (seed >> 2);\n"
"return seed;\n"
"}\n"
"static int custom_find(int3 idx, const int hashDivisor, __global const int* hashes,\n"
"__global const int4* data)\n"
"{\n"
"int hash = calc_hash(idx) % hashDivisor;\n"
"int place = hashes[hash];\n"
"while (place >= 0)\n"
"{\n"
"if (all(data[place].s012 == idx))\n"
"break;\n"
"else\n"
"place = data[place].s3;\n"
"}\n"
"return place;\n"
"}\n"
"static void integrateVolumeUnit(\n"
"int x, int y,\n"
"__global const char * depthptr,\n"
"int depth_step, int depth_offset,\n"
"int depth_rows, int depth_cols,\n"
"__global struct TsdfVoxel * volumeptr,\n"
"const __global char * pixNormsPtr,\n"
"int pixNormsStep, int pixNormsOffset,\n"
"int pixNormsRows, int pixNormsCols,\n"
"const float16 vol2camMatrix,\n"
"const float voxelSize,\n"
"const int4 volResolution4,\n"
"const int4 volStrides4,\n"
"const float2 fxy,\n"
"const float2 cxy,\n"
"const float dfac,\n"
"const float truncDist,\n"
"const int maxWeight\n"
")\n"
"{\n"
"const int3 volResolution = volResolution4.xyz;\n"
"if(x >= volResolution.x || y >= volResolution.y)\n"
"return;\n"
"const int3 volStrides = volStrides4.xyz;\n"
"const float2 limits = (float2)(depth_cols-1, depth_rows-1);\n"
"const float4 vol2cam0 = vol2camMatrix.s0123;\n"
"const float4 vol2cam1 = vol2camMatrix.s4567;\n"
"const float4 vol2cam2 = vol2camMatrix.s89ab;\n"
"const float truncDistInv = 1.f/truncDist;\n"
"float4 inPt = (float4)(x*voxelSize, y*voxelSize, 0, 1);\n"
"float3 basePt = (float3)(dot(vol2cam0, inPt),\n"
"dot(vol2cam1, inPt),\n"
"dot(vol2cam2, inPt));\n"
"float3 camSpacePt = basePt;\n"
"float3 zStep = ((float3)(vol2cam0.z, vol2cam1.z, vol2cam2.z))*voxelSize;\n"
"int volYidx = x*volStrides.x + y*volStrides.y;\n"
"int startZ, endZ;\n"
"if(fabs(zStep.z) > 1e-5f)\n"
"{\n"
"int baseZ = convert_int(-basePt.z / zStep.z);\n"
"if(zStep.z > 0)\n"
"{\n"
"startZ = baseZ;\n"
"endZ = volResolution.z;\n"
"}\n"
"else\n"
"{\n"
"startZ = 0;\n"
"endZ = baseZ;\n"
"}\n"
"}\n"
"else\n"
"{\n"
"if(basePt.z > 0)\n"
"{\n"
"startZ = 0; endZ = volResolution.z;\n"
"}\n"
"else\n"
"{\n"
"startZ = endZ = 0;\n"
"}\n"
"}\n"
"startZ = max(0, startZ);\n"
"endZ = min(volResolution.z, endZ);\n"
"for(int z = startZ; z < endZ; z++)\n"
"{\n"
"camSpacePt += zStep;\n"
"if(camSpacePt.z <= 0)\n"
"continue;\n"
"float3 camPixVec = camSpacePt / camSpacePt.z;\n"
"float2 projected = mad(camPixVec.xy, fxy, cxy);\n"
"float v;\n"
"if(all(projected >= 0) && all(projected < limits))\n"
"{\n"
"float2 ip = floor(projected);\n"
"int xi = ip.x, yi = ip.y;\n"
"__global const float* row0 = (__global const float*)(depthptr + depth_offset +\n"
"(yi+0)*depth_step);\n"
"__global const float* row1 = (__global const float*)(depthptr + depth_offset +\n"
"(yi+1)*depth_step);\n"
"float v00 = row0[xi+0];\n"
"float v01 = row0[xi+1];\n"
"float v10 = row1[xi+0];\n"
"float v11 = row1[xi+1];\n"
"float4 vv = (float4)(v00, v01, v10, v11);\n"
"if(all(vv > 0))\n"
"{\n"
"float2 t = projected - ip;\n"
"float2 vf = mix(vv.xz, vv.yw, t.x);\n"
"v = mix(vf.s0, vf.s1, t.y);\n"
"}\n"
"else\n"
"continue;\n"
"}\n"
"else\n"
"continue;\n"
"if(v == 0)\n"
"continue;\n"
"int2 projInt = convert_int2(projected);\n"
"float pixNorm = *(__global const float*)(pixNormsPtr + pixNormsOffset + projInt.y*pixNormsStep + projInt.x*sizeof(float));\n"
"float sdf = pixNorm*(v*dfac - camSpacePt.z);\n"
"if(sdf >= -truncDist)\n"
"{\n"
"float tsdf = fmin(1.0f, sdf * truncDistInv);\n"
"int volIdx = volYidx + z*volStrides.z;\n"
"struct TsdfVoxel voxel = volumeptr[volIdx];\n"
"float value = tsdfToFloat(voxel.tsdf);\n"
"int weight = voxel.weight;\n"
"value = (value*weight + tsdf) / (weight + 1);\n"
"weight = min(weight + 1, maxWeight);\n"
"voxel.tsdf = floatToTsdf(value);\n"
"voxel.weight = weight;\n"
"volumeptr[volIdx] = voxel;\n"
"}\n"
"}\n"
"}\n"
"__kernel void integrateAllVolumeUnits(\n"
"__global const char * depthptr,\n"
"int depth_step, int depth_offset,\n"
"int depth_rows, int depth_cols,\n"
"__global const int* hashes,\n"
"__global const int4* data,\n"
"__global struct TsdfVoxel * allVolumePtr,\n"
"int table_step, int table_offset,\n"
"int table_rows, int table_cols,\n"
"const __global char * pixNormsPtr,\n"
"int pixNormsStep, int pixNormsOffset,\n"
"int pixNormsRows, int pixNormsCols,\n"
"__global const uchar* isActiveFlagsPtr,\n"
"int isActiveFlagsStep, int isActiveFlagsOffset,\n"
"int isActiveFlagsRows, int isActiveFlagsCols,\n"
"const float16 vol2cam,\n"
"const float16 camInv,\n"
"const float voxelSize,\n"
"const int volUnitResolution,\n"
"const int4 volStrides4,\n"
"const float2 fxy,\n"
"const float2 cxy,\n"
"const float dfac,\n"
"const float truncDist,\n"
"const int maxWeight\n"
")\n"
"{\n"
"const int hash_divisor = HASH_DIVISOR;\n"
"int i = get_global_id(0);\n"
"int j = get_global_id(1);\n"
"int row = get_global_id(2);\n"
"int3 idx = data[row].xyz;\n"
"const int4 volResolution4 = (int4)(volUnitResolution,\n"
"volUnitResolution,\n"
"volUnitResolution,\n"
"volUnitResolution);\n"
"int isActive = *(__global const uchar*)(isActiveFlagsPtr + isActiveFlagsOffset + row);\n"
"if (isActive)\n"
"{\n"
"int volCubed = volUnitResolution * volUnitResolution * volUnitResolution;\n"
"__global struct TsdfVoxel * volumeptr = (__global struct TsdfVoxel*)\n"
"(allVolumePtr + table_offset + row * volCubed);\n"
"float3 mulIdx = convert_float3(idx * volUnitResolution) * voxelSize;\n"
"float16 volUnit2cam = vol2cam;\n"
"volUnit2cam.s37b += (float3)(dot(mulIdx, camInv.s012),\n"
"dot(mulIdx, camInv.s456),\n"
"dot(mulIdx, camInv.s89a));\n"
"integrateVolumeUnit(\n"
"i, j,\n"
"depthptr,\n"
"depth_step, depth_offset,\n"
"depth_rows, depth_cols,\n"
"volumeptr,\n"
"pixNormsPtr,\n"
"pixNormsStep, pixNormsOffset,\n"
"pixNormsRows, pixNormsCols,\n"
"volUnit2cam,\n"
"voxelSize,\n"
"volResolution4,\n"
"volStrides4,\n"
"fxy,\n"
"cxy,\n"
"dfac,\n"
"truncDist,\n"
"maxWeight\n"
");\n"
"}\n"
"}\n"
"static struct TsdfVoxel at(int3 volumeIdx, int row, int volumeUnitDegree,\n"
"int3 volStrides, __global const struct TsdfVoxel * allVolumePtr, int table_offset)\n"
"{\n"
"if (any(volumeIdx >= (1 << volumeUnitDegree)) ||\n"
"any(volumeIdx < 0))\n"
"{\n"
"struct TsdfVoxel dummy;\n"
"dummy.tsdf = floatToTsdf(1.0f);\n"
"dummy.weight = 0;\n"
"return dummy;\n"
"}\n"
"int volCubed = 1 << (volumeUnitDegree*3);\n"
"__global struct TsdfVoxel * volData = (__global struct TsdfVoxel*)\n"
"(allVolumePtr + table_offset + row * volCubed);\n"
"int3 ismul = volumeIdx * volStrides;\n"
"int coordBase = ismul.x + ismul.y + ismul.z;\n"
"return volData[coordBase];\n"
"}\n"
"static struct TsdfVoxel atVolumeUnit(int3 volumeIdx, int3 volumeUnitIdx, int row,\n"
"int volumeUnitDegree, int3 volStrides,\n"
"__global const struct TsdfVoxel * allVolumePtr, int table_offset)\n"
"{\n"
"if (row < 0)\n"
"{\n"
"struct TsdfVoxel dummy;\n"
"dummy.tsdf = floatToTsdf(1.0f);\n"
"dummy.weight = 0;\n"
"return dummy;\n"
"}\n"
"int3 volUnitLocalIdx = volumeIdx - (volumeUnitIdx << volumeUnitDegree);\n"
"int volCubed = 1 << (volumeUnitDegree*3);\n"
"__global struct TsdfVoxel * volData = (__global struct TsdfVoxel*)\n"
"(allVolumePtr + table_offset + row * volCubed);\n"
"int3 ismul = volUnitLocalIdx * volStrides;\n"
"int coordBase = ismul.x + ismul.y + ismul.z;\n"
"return volData[coordBase];\n"
"}\n"
"inline float interpolate(float3 t, float8 vz)\n"
"{\n"
"float4 vy = mix(vz.s0246, vz.s1357, t.z);\n"
"float2 vx = mix(vy.s02, vy.s13, t.y);\n"
"return mix(vx.s0, vx.s1, t.x);\n"
"}\n"
"inline float3 getNormalVoxel(float3 ptVox, __global const struct TsdfVoxel* allVolumePtr,\n"
"int volumeUnitDegree,\n"
"const int hash_divisor,\n"
"__global const int* hashes,\n"
"__global const int4* data,\n"
"int3 volStrides, int table_offset)\n"
"{\n"
"float3 normal = (float3) (0.0f, 0.0f, 0.0f);\n"
"float3 fip = floor(ptVox);\n"
"int3 iptVox = convert_int3(fip);\n"
"int iterMap[8];\n"
"for (int i = 0; i < 8; i++)\n"
"{\n"
"iterMap[i] = -2;\n"
"}\n"
"#if !USE_INTERPOLATION_IN_GETNORMAL\n"
"int4 offsets[] = { (int4)( 1, 0, 0, 0), (int4)(-1, 0, 0, 0), (int4)( 0, 1, 0, 0),\n"
"(int4)( 0, -1, 0, 0), (int4)( 0, 0, 1, 0), (int4)( 0, 0, -1, 0)\n"
"};\n"
"const int nVals = 6;\n"
"float vals[6];\n"
"#else\n"
"int4 offsets[]={(int4)( 0, 0, 0, 0), (int4)( 0, 0, 1, 0), (int4)( 0, 1, 0, 0), (int4)( 0, 1, 1, 0),\n"
"(int4)( 1, 0, 0, 0), (int4)( 1, 0, 1, 0), (int4)( 1, 1, 0, 0), (int4)( 1, 1, 1, 0),\n"
"(int4)(-1, 0, 0, 0), (int4)(-1, 0, 1, 0), (int4)(-1, 1, 0, 0), (int4)(-1, 1, 1, 0),\n"
"(int4)( 2, 0, 0, 0), (int4)( 2, 0, 1, 0), (int4)( 2, 1, 0, 0), (int4)( 2, 1, 1, 0),\n"
"(int4)( 0, -1, 0, 0), (int4)( 0, -1, 1, 0), (int4)( 1, -1, 0, 0), (int4)( 1, -1, 1, 0),\n"
"(int4)( 0, 2, 0, 0), (int4)( 0, 2, 1, 0), (int4)( 1, 2, 0, 0), (int4)( 1, 2, 1, 0),\n"
"(int4)( 0, 0, -1, 0), (int4)( 0, 1, -1, 0), (int4)( 1, 0, -1, 0), (int4)( 1, 1, -1, 0),\n"
"(int4)( 0, 0, 2, 0), (int4)( 0, 1, 2, 0), (int4)( 1, 0, 2, 0), (int4)( 1, 1, 2, 0),\n"
"};\n"
"const int nVals = 32;\n"
"float vals[32];\n"
"#endif\n"
"for (int i = 0; i < nVals; i++)\n"
"{\n"
"int3 pt = iptVox + offsets[i].s012;\n"
"int3 volumeUnitIdx = pt >> volumeUnitDegree;\n"
"int3 vand = (volumeUnitIdx & 1);\n"
"int dictIdx = vand.s0 + vand.s1 * 2 + vand.s2 * 4;\n"
"int it = iterMap[dictIdx];\n"
"if (it < -1)\n"
"{\n"
"it = custom_find(volumeUnitIdx, hash_divisor, hashes, data);\n"
"iterMap[dictIdx] = it;\n"
"}\n"
"struct TsdfVoxel tmp = atVolumeUnit(pt, volumeUnitIdx, it, volumeUnitDegree, volStrides, allVolumePtr, table_offset);\n"
"vals[i] = tsdfToFloat( tmp.tsdf );\n"
"}\n"
"#if !USE_INTERPOLATION_IN_GETNORMAL\n"
"float3 pv, nv;\n"
"pv = (float3)(vals[0*2 ], vals[1*2 ], vals[2*2 ]);\n"
"nv = (float3)(vals[0*2+1], vals[1*2+1], vals[2*2+1]);\n"
"normal = pv - nv;\n"
"#else\n"
"float cxv[8], cyv[8], czv[8];\n"
"const int idxxn[8] = { 8, 9, 10, 11, 0, 1, 2, 3 };\n"
"const int idxxp[8] = { 4, 5, 6, 7, 12, 13, 14, 15 };\n"
"const int idxyn[8] = { 16, 17, 0, 1, 18, 19, 4, 5 };\n"
"const int idxyp[8] = { 2, 3, 20, 21, 6, 7, 22, 23 };\n"
"const int idxzn[8] = { 24, 0, 25, 2, 26, 4, 27, 6 };\n"
"const int idxzp[8] = { 1, 28, 3, 29, 5, 30, 7, 31 };\n"
"float vcxp[8], vcxn[8];\n"
"float vcyp[8], vcyn[8];\n"
"float vczp[8], vczn[8];\n"
"for (int i = 0; i < 8; i++)\n"
"{\n"
"vcxp[i] = vals[idxxp[i]]; vcxn[i] = vals[idxxn[i]];\n"
"vcyp[i] = vals[idxyp[i]]; vcyn[i] = vals[idxyn[i]];\n"
"vczp[i] = vals[idxzp[i]]; vczn[i] = vals[idxzn[i]];\n"
"}\n"
"float8 cxp = vload8(0, vcxp), cxn = vload8(0, vcxn);\n"
"float8 cyp = vload8(0, vcyp), cyn = vload8(0, vcyn);\n"
"float8 czp = vload8(0, vczp), czn = vload8(0, vczn);\n"
"float8 cx = cxp - cxn;\n"
"float8 cy = cyp - cyn;\n"
"float8 cz = czp - czn;\n"
"float3 tv = ptVox - fip;\n"
"normal.x = interpolate(tv, cx);\n"
"normal.y = interpolate(tv, cy);\n"
"normal.z = interpolate(tv, cz);\n"
"#endif\n"
"float norm = sqrt(dot(normal, normal));\n"
"return norm < 0.0001f ? nan((uint)0) : normal / norm;\n"
"}\n"
"typedef float4 ptype;\n"
"__kernel void raycast(\n"
"__global const int* hashes,\n"
"__global const int4* data,\n"
"__global char * pointsptr,\n"
"int points_step, int points_offset,\n"
"__global char * normalsptr,\n"
"int normals_step, int normals_offset,\n"
"const int2 frameSize,\n"
"__global const struct TsdfVoxel * allVolumePtr,\n"
"int table_step, int table_offset,\n"
"int table_rows, int table_cols,\n"
"float16 cam2volRotGPU,\n"
"float16 vol2camRotGPU,\n"
"float truncateThreshold,\n"
"const float2 fixy, const float2 cxy,\n"
"const float4 boxDown4, const float4 boxUp4,\n"
"const float tstep,\n"
"const float voxelSize,\n"
"const float voxelSizeInv,\n"
"float volumeUnitSize,\n"
"float truncDist,\n"
"int volumeUnitDegree,\n"
"int4 volStrides4\n"
")\n"
"{\n"
"const int hash_divisor = HASH_DIVISOR;\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if(x >= frameSize.x || y >= frameSize.y)\n"
"return;\n"
"float3 point = nan((uint)0);\n"
"float3 normal = nan((uint)0);\n"
"const float3 camRot0 = cam2volRotGPU.s012;\n"
"const float3 camRot1 = cam2volRotGPU.s456;\n"
"const float3 camRot2 = cam2volRotGPU.s89a;\n"
"const float3 camTrans = cam2volRotGPU.s37b;\n"
"const float3 volRot0 = vol2camRotGPU.s012;\n"
"const float3 volRot1 = vol2camRotGPU.s456;\n"
"const float3 volRot2 = vol2camRotGPU.s89a;\n"
"const float3 volTrans = vol2camRotGPU.s37b;\n"
"float3 planed = (float3)(((float2)(x, y) - cxy)*fixy, 1.f);\n"
"planed = (float3)(dot(planed, camRot0),\n"
"dot(planed, camRot1),\n"
"dot(planed, camRot2));\n"
"float3 orig = (float3) (camTrans.s0, camTrans.s1, camTrans.s2);\n"
"float3 dir = fast_normalize(planed);\n"
"float3 origScaled = orig * voxelSizeInv;\n"
"float3 dirScaled = dir * voxelSizeInv;\n"
"float tmin = 0;\n"
"float tmax = truncateThreshold;\n"
"float tcurr = tmin;\n"
"float tprev = tcurr;\n"
"float prevTsdf = truncDist;\n"
"int3 volStrides = volStrides4.xyz;\n"
"while (tcurr < tmax)\n"
"{\n"
"float3 currRayPosVox = origScaled + tcurr * dirScaled;\n"
"int3 currVoxel = convert_int3(floor(currRayPosVox));\n"
"int3 currVolumeUnitIdx = currVoxel >> volumeUnitDegree;\n"
"int row = custom_find(currVolumeUnitIdx, hash_divisor, hashes, data);\n"
"float currTsdf = prevTsdf;\n"
"int currWeight = 0;\n"
"float stepSize = 0.5 * volumeUnitSize;\n"
"int3 volUnitLocalIdx;\n"
"if (row >= 0)\n"
"{\n"
"volUnitLocalIdx = currVoxel - (currVolumeUnitIdx << volumeUnitDegree);\n"
"struct TsdfVoxel currVoxel = at(volUnitLocalIdx, row, volumeUnitDegree, volStrides, allVolumePtr, table_offset);\n"
"currTsdf = tsdfToFloat(currVoxel.tsdf);\n"
"currWeight = currVoxel.weight;\n"
"stepSize = tstep;\n"
"}\n"
"if (prevTsdf > 0.f && currTsdf <= 0.f && currWeight > 0)\n"
"{\n"
"float tInterp = (tcurr * prevTsdf - tprev * currTsdf) / (prevTsdf - currTsdf);\n"
"if ( !isnan(tInterp) && !isinf(tInterp) )\n"
"{\n"
"float3 pvox = origScaled + tInterp * dirScaled;\n"
"float3 nv = getNormalVoxel( pvox, allVolumePtr, volumeUnitDegree,\n"
"hash_divisor, hashes, data,\n"
"volStrides, table_offset);\n"
"if(!any(isnan(nv)))\n"
"{\n"
"normal = (float3)(dot(nv, volRot0),\n"
"dot(nv, volRot1),\n"
"dot(nv, volRot2));\n"
"float3 pv = pvox * voxelSize;\n"
"point = (float3)(dot(pv, volRot0),\n"
"dot(pv, volRot1),\n"
"dot(pv, volRot2)) + volTrans;\n"
"}\n"
"}\n"
"break;\n"
"}\n"
"prevTsdf = currTsdf;\n"
"tprev = tcurr;\n"
"tcurr += stepSize;\n"
"}\n"
"__global float* pts = (__global float*)(pointsptr + points_offset + y*points_step + x*sizeof(ptype));\n"
"__global float* nrm = (__global float*)(normalsptr + normals_offset + y*normals_step + x*sizeof(ptype));\n"
"vstore4((float4)(point, 0), 0, pts);\n"
"vstore4((float4)(normal, 0), 0, nrm);\n"
"}\n"
"__kernel void markActive (\n"
"__global const int4* hashSetData,\n"
"__global char* isActiveFlagsPtr,\n"
"int isActiveFlagsStep, int isActiveFlagsOffset,\n"
"int isActiveFlagsRows, int isActiveFlagsCols,\n"
"__global char* lastVisibleIndicesPtr,\n"
"int lastVisibleIndicesStep, int lastVisibleIndicesOffset,\n"
"int lastVisibleIndicesRows, int lastVisibleIndicesCols,\n"
"const float16 vol2cam,\n"
"const float2 fxy,\n"
"const float2 cxy,\n"
"const int2 frameSz,\n"
"const float volumeUnitSize,\n"
"const int lastVolIndex,\n"
"const float truncateThreshold,\n"
"const int frameId\n"
")\n"
"{\n"
"const int hash_divisor = HASH_DIVISOR;\n"
"int row = get_global_id(0);\n"
"if (row < lastVolIndex)\n"
"{\n"
"int3 idx = hashSetData[row].xyz;\n"
"float3 volumeUnitPos = convert_float3(idx) * volumeUnitSize;\n"
"float3 volUnitInCamSpace = (float3) (dot(volumeUnitPos, vol2cam.s012),\n"
"dot(volumeUnitPos, vol2cam.s456),\n"
"dot(volumeUnitPos, vol2cam.s89a)) + vol2cam.s37b;\n"
"if (volUnitInCamSpace.z < 0 || volUnitInCamSpace.z > truncateThreshold)\n"
"{\n"
"*(isActiveFlagsPtr + isActiveFlagsOffset + row * isActiveFlagsStep) = 0;\n"
"return;\n"
"}\n"
"float2 cameraPoint;\n"
"float invz = 1.f / volUnitInCamSpace.z;\n"
"cameraPoint = fxy * volUnitInCamSpace.xy * invz + cxy;\n"
"if (all(cameraPoint >= 0) && all(cameraPoint < convert_float2(frameSz)))\n"
"{\n"
"*(__global int*)(lastVisibleIndicesPtr + lastVisibleIndicesOffset + row * lastVisibleIndicesStep) = frameId;\n"
"*(isActiveFlagsPtr + isActiveFlagsOffset + row * isActiveFlagsStep) = 1;\n"
"}\n"
"}\n"
"}\n"
, "ad8977a40f1ba1f499b05120287578a4", NULL};
struct cv::ocl::internal::ProgramEntry icp_oclsrc={moduleName, "icp",
"#define UTSIZE 27\n"
"typedef float4 ptype;\n"
"inline void calcAb7(__global const char * oldPointsptr,\n"
"int oldPoints_step, int oldPoints_offset,\n"
"__global const char * oldNormalsptr,\n"
"int oldNormals_step, int oldNormals_offset,\n"
"const int2 oldSize,\n"
"__global const char * newPointsptr,\n"
"int newPoints_step, int newPoints_offset,\n"
"__global const char * newNormalsptr,\n"
"int newNormals_step, int newNormals_offset,\n"
"const int2 newSize,\n"
"const float16 poseMatrix,\n"
"const float2 fxy,\n"
"const float2 cxy,\n"
"const float sqDistanceThresh,\n"
"const float minCos,\n"
"float* ab7\n"
")\n"
"{\n"
"const int x = get_global_id(0);\n"
"const int y = get_global_id(1);\n"
"if(x >= newSize.x || y >= newSize.y)\n"
"return;\n"
"const float3 poseRot0 = poseMatrix.s012;\n"
"const float3 poseRot1 = poseMatrix.s456;\n"
"const float3 poseRot2 = poseMatrix.s89a;\n"
"const float3 poseTrans = poseMatrix.s37b;\n"
"const float2 oldEdge = (float2)(oldSize.x - 1, oldSize.y - 1);\n"
"__global const ptype* newPtsRow = (__global const ptype*)(newPointsptr +\n"
"newPoints_offset +\n"
"y*newPoints_step);\n"
"__global const ptype* newNrmRow = (__global const ptype*)(newNormalsptr +\n"
"newNormals_offset +\n"
"y*newNormals_step);\n"
"float3 newP = newPtsRow[x].xyz;\n"
"float3 newN = newNrmRow[x].xyz;\n"
"if( any(isnan(newP)) || any(isnan(newN)) ||\n"
"any(isinf(newP)) || any(isinf(newN)) )\n"
"return;\n"
"newP = (float3)(dot(newP, poseRot0),\n"
"dot(newP, poseRot1),\n"
"dot(newP, poseRot2)) + poseTrans;\n"
"newN = (float3)(dot(newN, poseRot0),\n"
"dot(newN, poseRot1),\n"
"dot(newN, poseRot2));\n"
"float2 oldCoords = (newP.xy/newP.z)*fxy+cxy;\n"
"if(!(all(oldCoords >= 0.f) && all(oldCoords < oldEdge)))\n"
"return;\n"
"float3 oldP, oldN;\n"
"float2 ip = floor(oldCoords);\n"
"float2 t = oldCoords - ip;\n"
"int xi = ip.x, yi = ip.y;\n"
"__global const ptype* prow0 = (__global const ptype*)(oldPointsptr +\n"
"oldPoints_offset +\n"
"(yi+0)*oldPoints_step);\n"
"__global const ptype* prow1 = (__global const ptype*)(oldPointsptr +\n"
"oldPoints_offset +\n"
"(yi+1)*oldPoints_step);\n"
"float3 p00 = prow0[xi+0].xyz;\n"
"float3 p01 = prow0[xi+1].xyz;\n"
"float3 p10 = prow1[xi+0].xyz;\n"
"float3 p11 = prow1[xi+1].xyz;\n"
"__global const ptype* nrow0 = (__global const ptype*)(oldNormalsptr +\n"
"oldNormals_offset +\n"
"(yi+0)*oldNormals_step);\n"
"__global const ptype* nrow1 = (__global const ptype*)(oldNormalsptr +\n"
"oldNormals_offset +\n"
"(yi+1)*oldNormals_step);\n"
"float3 n00 = nrow0[xi+0].xyz;\n"
"float3 n01 = nrow0[xi+1].xyz;\n"
"float3 n10 = nrow1[xi+0].xyz;\n"
"float3 n11 = nrow1[xi+1].xyz;\n"
"float3 p0 = mix(p00, p01, t.x);\n"
"float3 p1 = mix(p10, p11, t.x);\n"
"oldP = mix(p0, p1, t.y);\n"
"float3 n0 = mix(n00, n01, t.x);\n"
"float3 n1 = mix(n10, n11, t.x);\n"
"oldN = mix(n0, n1, t.y);\n"
"if( any(isnan(oldP)) || any(isnan(oldN)) ||\n"
"any(isinf(oldP)) || any(isinf(oldN)) )\n"
"return;\n"
"float3 diff = newP - oldP;\n"
"if(dot(diff, diff) > sqDistanceThresh)\n"
"return;\n"
"if(fabs(dot(newN, oldN)) < minCos)\n"
"return;\n"
"float3 VxN = cross(newP, oldN);\n"
"float ab[7] = {VxN.x, VxN.y, VxN.z, oldN.x, oldN.y, oldN.z, -dot(oldN, diff)};\n"
"for(int i = 0; i < 7; i++)\n"
"ab7[i] = ab[i];\n"
"}\n"
"__kernel void getAb(__global const char * oldPointsptr,\n"
"int oldPoints_step, int oldPoints_offset,\n"
"__global const char * oldNormalsptr,\n"
"int oldNormals_step, int oldNormals_offset,\n"
"const int2 oldSize,\n"
"__global const char * newPointsptr,\n"
"int newPoints_step, int newPoints_offset,\n"
"__global const char * newNormalsptr,\n"
"int newNormals_step, int newNormals_offset,\n"
"const int2 newSize,\n"
"const float16 poseMatrix,\n"
"const float2 fxy,\n"
"const float2 cxy,\n"
"const float sqDistanceThresh,\n"
"const float minCos,\n"
"__local float * reducebuf,\n"
"__global char* groupedSumptr,\n"
"int groupedSum_step, int groupedSum_offset\n"
")\n"
"{\n"
"const int x = get_global_id(0);\n"
"const int y = get_global_id(1);\n"
"if(x >= newSize.x || y >= newSize.y)\n"
"return;\n"
"const int gx = get_group_id(0);\n"
"const int gy = get_group_id(1);\n"
"const int gw = get_num_groups(0);\n"
"const int gh = get_num_groups(1);\n"
"const int lx = get_local_id(0);\n"
"const int ly = get_local_id(1);\n"
"const int lw = get_local_size(0);\n"
"const int lh = get_local_size(1);\n"
"const int lsz = lw*lh;\n"
"const int lid = lx + ly*lw;\n"
"float ab[7];\n"
"for(int i = 0; i < 7; i++)\n"
"ab[i] = 0;\n"
"calcAb7(oldPointsptr,\n"
"oldPoints_step, oldPoints_offset,\n"
"oldNormalsptr,\n"
"oldNormals_step, oldNormals_offset,\n"
"oldSize,\n"
"newPointsptr,\n"
"newPoints_step, newPoints_offset,\n"
"newNormalsptr,\n"
"newNormals_step, newNormals_offset,\n"
"newSize,\n"
"poseMatrix,\n"
"fxy, cxy,\n"
"sqDistanceThresh,\n"
"minCos,\n"
"ab);\n"
"__local float* upperTriangle = reducebuf + lid*UTSIZE;\n"
"int pos = 0;\n"
"for(int i = 0; i < 6; i++)\n"
"{\n"
"for(int j = i; j < 7; j++)\n"
"{\n"
"upperTriangle[pos++] = ab[i]*ab[j];\n"
"}\n"
"}\n"
"const int c = clz(lsz & -lsz);\n"
"const int maxStep = c ? 31 - c : c;\n"
"for(int nstep = 1; nstep <= maxStep; nstep++)\n"
"{\n"
"if(lid % (1 << nstep) == 0)\n"
"{\n"
"__local float* rto = reducebuf + UTSIZE*lid;\n"
"__local float* rfrom = reducebuf + UTSIZE*(lid+(1 << (nstep-1)));\n"
"for(int i = 0; i < UTSIZE; i++)\n"
"rto[i] += rfrom[i];\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"}\n"
"if(lid == 0)\n"
"{\n"
"__global float* groupedRow = (__global float*)(groupedSumptr +\n"
"groupedSum_offset +\n"
"gy*groupedSum_step);\n"
"for(int i = 0; i < UTSIZE; i++)\n"
"groupedRow[gx*UTSIZE + i] = reducebuf[i];\n"
"}\n"
"}\n"
, "db7fd764b651e87bd2c879fbef42e648", NULL};
struct cv::ocl::internal::ProgramEntry kinfu_frame_oclsrc={moduleName, "kinfu_frame",
"inline float3 reproject(float3 p, float2 fxyinv, float2 cxy)\n"
"{\n"
"float2 pp = p.z*(p.xy - cxy)*fxyinv;\n"
"return (float3)(pp, p.z);\n"
"}\n"
"typedef float4 ptype;\n"
"__kernel void computePointsNormals(__global char * pointsptr,\n"
"int points_step, int points_offset,\n"
"__global char * normalsptr,\n"
"int normals_step, int normals_offset,\n"
"__global const char * depthptr,\n"
"int depth_step, int depth_offset,\n"
"int depth_rows, int depth_cols,\n"
"const float2 fxyinv,\n"
"const float2 cxy,\n"
"const float dfac\n"
")\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if(x >= depth_cols || y >= depth_rows)\n"
"return;\n"
"__global const float* row0 = (__global const float*)(depthptr + depth_offset +\n"
"(y+0)*depth_step);\n"
"__global const float* row1 = (__global const float*)(depthptr + depth_offset +\n"
"(y+1)*depth_step);\n"
"float d00 = row0[x];\n"
"float z00 = d00*dfac;\n"
"float3 p00 = (float3)(convert_float2((int2)(x, y)), z00);\n"
"float3 v00 = reproject(p00, fxyinv, cxy);\n"
"float3 p = nan((uint)0), n = nan((uint)0);\n"
"if(x < depth_cols - 1 && y < depth_rows - 1)\n"
"{\n"
"float d01 = row0[x+1];\n"
"float d10 = row1[x];\n"
"float z01 = d01*dfac;\n"
"float z10 = d10*dfac;\n"
"if(z00 != 0 && z01 != 0 && z10 != 0)\n"
"{\n"
"float3 p01 = (float3)(convert_float2((int2)(x+1, y+0)), z01);\n"
"float3 p10 = (float3)(convert_float2((int2)(x+0, y+1)), z10);\n"
"float3 v01 = reproject(p01, fxyinv, cxy);\n"
"float3 v10 = reproject(p10, fxyinv, cxy);\n"
"float3 vec = cross(v01 - v00, v10 - v00);\n"
"n = - normalize(vec);\n"
"p = v00;\n"
"}\n"
"}\n"
"__global float* pts = (__global float*)(pointsptr + points_offset + y*points_step + x*sizeof(ptype));\n"
"__global float* nrm = (__global float*)(normalsptr + normals_offset + y*normals_step + x*sizeof(ptype));\n"
"vstore4((ptype)(p, 0), 0, pts);\n"
"vstore4((ptype)(n, 0), 0, nrm);\n"
"}\n"
"__kernel void pyrDownBilateral(__global const char * depthptr,\n"
"int depth_step, int depth_offset,\n"
"int depth_rows, int depth_cols,\n"
"__global char * depthDownptr,\n"
"int depthDown_step, int depthDown_offset,\n"
"int depthDown_rows, int depthDown_cols,\n"
"const float sigma\n"
")\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if(x >= depthDown_cols || y >= depthDown_rows)\n"
"return;\n"
"const float sigma3 = sigma*3;\n"
"const int D = 5;\n"
"__global const float* srcCenterRow = (__global const float*)(depthptr + depth_offset +\n"
"(2*y)*depth_step);\n"
"float center = srcCenterRow[2*x];\n"
"int sx = max(0, 2*x - D/2), ex = min(2*x - D/2 + D, depth_cols-1);\n"
"int sy = max(0, 2*y - D/2), ey = min(2*y - D/2 + D, depth_rows-1);\n"
"float sum = 0;\n"
"int count = 0;\n"
"for(int iy = sy; iy < ey; iy++)\n"
"{\n"
"__global const float* srcRow = (__global const float*)(depthptr + depth_offset +\n"
"(iy)*depth_step);\n"
"for(int ix = sx; ix < ex; ix++)\n"
"{\n"
"float val = srcRow[ix];\n"
"if(fabs(val - center) < sigma3)\n"
"{\n"
"sum += val; count++;\n"
"}\n"
"}\n"
"}\n"
"__global float* downRow = (__global float*)(depthDownptr + depthDown_offset +\n"
"y*depthDown_step + x*sizeof(float));\n"
"*downRow = (count == 0) ? 0 : sum/convert_float(count);\n"
"}\n"
"__kernel void customBilateral(__global const char * srcptr,\n"
"int src_step, int src_offset,\n"
"__global char * dstptr,\n"
"int dst_step, int dst_offset,\n"
"const int2 frameSize,\n"
"const int kernelSize,\n"
"const float sigma_spatial2_inv_half,\n"
"const float sigma_depth2_inv_half\n"
")\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if(x >= frameSize.x || y >= frameSize.y)\n"
"return;\n"
"__global const float* srcCenterRow = (__global const float*)(srcptr + src_offset +\n"
"y*src_step);\n"
"float value = srcCenterRow[x];\n"
"int tx = min (x - kernelSize / 2 + kernelSize, frameSize.x - 1);\n"
"int ty = min (y - kernelSize / 2 + kernelSize, frameSize.y - 1);\n"
"float sum1 = 0;\n"
"float sum2 = 0;\n"
"for (int cy = max (y - kernelSize / 2, 0); cy < ty; ++cy)\n"
"{\n"
"__global const float* srcRow = (__global const float*)(srcptr + src_offset +\n"
"cy*src_step);\n"
"for (int cx = max (x - kernelSize / 2, 0); cx < tx; ++cx)\n"
"{\n"
"float depth = srcRow[cx];\n"
"float space2 = convert_float((x - cx) * (x - cx) + (y - cy) * (y - cy));\n"
"float color2 = (value - depth) * (value - depth);\n"
"float weight = native_exp (-(space2 * sigma_spatial2_inv_half +\n"
"color2 * sigma_depth2_inv_half));\n"
"sum1 += depth * weight;\n"
"sum2 += weight;\n"
"}\n"
"}\n"
"__global float* dst = (__global float*)(dstptr + dst_offset +\n"
"y*dst_step + x*sizeof(float));\n"
"*dst = sum1/sum2;\n"
"}\n"
"__kernel void pyrDownPointsNormals(__global const char * pptr,\n"
"int p_step, int p_offset,\n"
"__global const char * nptr,\n"
"int n_step, int n_offset,\n"
"__global char * pdownptr,\n"
"int pdown_step, int pdown_offset,\n"
"__global char * ndownptr,\n"
"int ndown_step, int ndown_offset,\n"
"const int2 downSize\n"
")\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if(x >= downSize.x || y >= downSize.y)\n"
"return;\n"
"float3 point = nan((uint)0), normal = nan((uint)0);\n"
"__global const ptype* pUpRow0 = (__global const ptype*)(pptr + p_offset + (2*y )*p_step);\n"
"__global const ptype* pUpRow1 = (__global const ptype*)(pptr + p_offset + (2*y+1)*p_step);\n"
"float3 d00 = pUpRow0[2*x ].xyz;\n"
"float3 d01 = pUpRow0[2*x+1].xyz;\n"
"float3 d10 = pUpRow1[2*x ].xyz;\n"
"float3 d11 = pUpRow1[2*x+1].xyz;\n"
"if(!(any(isnan(d00)) || any(isnan(d01)) ||\n"
"any(isnan(d10)) || any(isnan(d11))))\n"
"{\n"
"point = (d00 + d01 + d10 + d11)*0.25f;\n"
"__global const ptype* nUpRow0 = (__global const ptype*)(nptr + n_offset + (2*y )*n_step);\n"
"__global const ptype* nUpRow1 = (__global const ptype*)(nptr + n_offset + (2*y+1)*n_step);\n"
"float3 n00 = nUpRow0[2*x ].xyz;\n"
"float3 n01 = nUpRow0[2*x+1].xyz;\n"
"float3 n10 = nUpRow1[2*x ].xyz;\n"
"float3 n11 = nUpRow1[2*x+1].xyz;\n"
"normal = (n00 + n01 + n10 + n11)*0.25f;\n"
"}\n"
"__global ptype* pts = (__global ptype*)(pdownptr + pdown_offset + y*pdown_step);\n"
"__global ptype* nrm = (__global ptype*)(ndownptr + ndown_offset + y*ndown_step);\n"
"pts[x] = (ptype)(point, 0);\n"
"nrm[x] = (ptype)(normal, 0);\n"
"}\n"
"typedef char4 pixelType;\n"
"float specPow20(float x)\n"
"{\n"
"float x2 = x*x;\n"
"float x5 = x2*x2*x;\n"
"float x10 = x5*x5;\n"
"float x20 = x10*x10;\n"
"return x20;\n"
"}\n"
"__kernel void render(__global const char * pointsptr,\n"
"int points_step, int points_offset,\n"
"__global const char * normalsptr,\n"
"int normals_step, int normals_offset,\n"
"__global char * imgptr,\n"
"int img_step, int img_offset,\n"
"const int2 frameSize,\n"
"const float4 lightPt\n"
")\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if(x >= frameSize.x || y >= frameSize.y)\n"
"return;\n"
"__global const ptype* ptsRow = (__global const ptype*)(pointsptr + points_offset + y*points_step + x*sizeof(ptype));\n"
"__global const ptype* nrmRow = (__global const ptype*)(normalsptr + normals_offset + y*normals_step + x*sizeof(ptype));\n"
"float3 p = (*ptsRow).xyz;\n"
"float3 n = (*nrmRow).xyz;\n"
"pixelType color;\n"
"if(any(isnan(p)))\n"
"{\n"
"color = (pixelType)(0, 32, 0, 0);\n"
"}\n"
"else\n"
"{\n"
"const float Ka = 0.3f;\n"
"const float Kd = 0.5f;\n"
"const float Ks = 0.2f;\n"
"const float Ax = 1.f;\n"
"const float Dx = 1.f;\n"
"const float Sx = 1.f;\n"
"const float Lx = 1.f;\n"
"float3 l = normalize(lightPt.xyz - p);\n"
"float3 v = normalize(-p);\n"
"float3 r = normalize(2.f*n*dot(n, l) - l);\n"
"float val = (Ax*Ka*Dx + Lx*Kd*Dx*max(0.f, dot(n, l)) +\n"
"Lx*Ks*Sx*specPow20(max(0.f, dot(r, v))));\n"
"uchar ix = convert_uchar(val*255.f);\n"
"color = (pixelType)(ix, ix, ix, 0);\n"
"}\n"
"__global char* imgRow = (__global char*)(imgptr + img_offset + y*img_step + x*sizeof(pixelType));\n"
"vstore4(color, 0, imgRow);\n"
"}\n"
, "27f66c4eaad4d1a82ef9ef08a6803a08", NULL};
struct cv::ocl::internal::ProgramEntry tsdf_oclsrc={moduleName, "tsdf",
"typedef char int8_t;\n"
"typedef int8_t TsdfType;\n"
"typedef uchar WeightType;\n"
"struct TsdfVoxel\n"
"{\n"
"TsdfType tsdf;\n"
"WeightType weight;\n"
"};\n"
"static inline TsdfType floatToTsdf(float num)\n"
"{\n"
"int8_t res = (int8_t) ( (num * (-128)) );\n"
"res = res ? res : (num < 0 ? 1 : -1);\n"
"return res;\n"
"}\n"
"static inline float tsdfToFloat(TsdfType num)\n"
"{\n"
"return ( (float) num ) / (-128);\n"
"}\n"
"__kernel void integrate(__global const char * depthptr,\n"
"int depth_step, int depth_offset,\n"
"int depth_rows, int depth_cols,\n"
"__global struct TsdfVoxel * volumeptr,\n"
"const float16 vol2camMatrix,\n"
"const float voxelSize,\n"
"const int4 volResolution4,\n"
"const int4 volDims4,\n"
"const float2 fxy,\n"
"const float2 cxy,\n"
"const float dfac,\n"
"const float truncDist,\n"
"const int maxWeight,\n"
"const __global float * pixNorms)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"const int3 volResolution = volResolution4.xyz;\n"
"if(x >= volResolution.x || y >= volResolution.y)\n"
"return;\n"
"const int3 volDims = volDims4.xyz;\n"
"const float2 limits = (float2)(depth_cols-1, depth_rows-1);\n"
"const float4 vol2cam0 = vol2camMatrix.s0123;\n"
"const float4 vol2cam1 = vol2camMatrix.s4567;\n"
"const float4 vol2cam2 = vol2camMatrix.s89ab;\n"
"const float truncDistInv = 1.f/truncDist;\n"
"float4 inPt = (float4)(x*voxelSize, y*voxelSize, 0, 1);\n"
"float3 basePt = (float3)(dot(vol2cam0, inPt),\n"
"dot(vol2cam1, inPt),\n"
"dot(vol2cam2, inPt));\n"
"float3 camSpacePt = basePt;\n"
"float3 zStep = ((float3)(vol2cam0.z, vol2cam1.z, vol2cam2.z))*voxelSize;\n"
"int volYidx = x*volDims.x + y*volDims.y;\n"
"int startZ, endZ;\n"
"if(fabs(zStep.z) > 1e-5f)\n"
"{\n"
"int baseZ = convert_int(-basePt.z / zStep.z);\n"
"if(zStep.z > 0)\n"
"{\n"
"startZ = baseZ;\n"
"endZ = volResolution.z;\n"
"}\n"
"else\n"
"{\n"
"startZ = 0;\n"
"endZ = baseZ;\n"
"}\n"
"}\n"
"else\n"
"{\n"
"if(basePt.z > 0)\n"
"{\n"
"startZ = 0; endZ = volResolution.z;\n"
"}\n"
"else\n"
"{\n"
"return;\n"
"}\n"
"}\n"
"startZ = max(0, startZ);\n"
"endZ = min(volResolution.z, endZ);\n"
"for(int z = startZ; z < endZ; z++)\n"
"{\n"
"camSpacePt += zStep;\n"
"if(camSpacePt.z <= 0)\n"
"continue;\n"
"float3 camPixVec = camSpacePt / camSpacePt.z;\n"
"float2 projected = mad(camPixVec.xy, fxy, cxy);\n"
"float v;\n"
"if(all(projected >= 0) && all(projected < limits))\n"
"{\n"
"float2 ip = floor(projected);\n"
"int xi = ip.x, yi = ip.y;\n"
"__global const float* row0 = (__global const float*)(depthptr + depth_offset +\n"
"(yi+0)*depth_step);\n"
"__global const float* row1 = (__global const float*)(depthptr + depth_offset +\n"
"(yi+1)*depth_step);\n"
"float v00 = row0[xi+0];\n"
"float v01 = row0[xi+1];\n"
"float v10 = row1[xi+0];\n"
"float v11 = row1[xi+1];\n"
"float4 vv = (float4)(v00, v01, v10, v11);\n"
"if(all(vv > 0))\n"
"{\n"
"float2 t = projected - ip;\n"
"float2 vf = mix(vv.xz, vv.yw, t.x);\n"
"v = mix(vf.s0, vf.s1, t.y);\n"
"}\n"
"else\n"
"continue;\n"
"}\n"
"else\n"
"continue;\n"
"if(v == 0)\n"
"continue;\n"
"int idx = projected.y * depth_cols + projected.x;\n"
"float pixNorm = pixNorms[idx];\n"
"float sdf = pixNorm*(v*dfac - camSpacePt.z);\n"
"if(sdf >= -truncDist)\n"
"{\n"
"float tsdf = fmin(1.0f, sdf * truncDistInv);\n"
"int volIdx = volYidx + z*volDims.z;\n"
"struct TsdfVoxel voxel = volumeptr[volIdx];\n"
"float value = tsdfToFloat(voxel.tsdf);\n"
"int weight = voxel.weight;\n"
"value = (value*weight + tsdf) / (weight + 1);\n"
"weight = min(weight + 1, maxWeight);\n"
"voxel.tsdf = floatToTsdf(value);\n"
"voxel.weight = weight;\n"
"volumeptr[volIdx] = voxel;\n"
"}\n"
"}\n"
"}\n"
"inline float interpolateVoxel(float3 p, __global const struct TsdfVoxel* volumePtr,\n"
"int3 volDims, int8 neighbourCoords)\n"
"{\n"
"float3 fip = floor(p);\n"
"int3 ip = convert_int3(fip);\n"
"float3 t = p - fip;\n"
"int3 cmul = volDims*ip;\n"
"int coordBase = cmul.x + cmul.y + cmul.z;\n"
"int nco[8];\n"
"vstore8(neighbourCoords + coordBase, 0, nco);\n"
"float vaz[8];\n"
"for(int i = 0; i < 8; i++)\n"
"vaz[i] = tsdfToFloat(volumePtr[nco[i]].tsdf);\n"
"float8 vz = vload8(0, vaz);\n"
"float4 vy = mix(vz.s0246, vz.s1357, t.z);\n"
"float2 vx = mix(vy.s02, vy.s13, t.y);\n"
"return mix(vx.s0, vx.s1, t.x);\n"
"}\n"
"inline float3 getNormalVoxel(float3 p, __global const struct TsdfVoxel* volumePtr,\n"
"int3 volResolution, int3 volDims, int8 neighbourCoords)\n"
"{\n"
"if(any(p < 1) || any(p >= convert_float3(volResolution - 2)))\n"
"return nan((uint)0);\n"
"float3 fip = floor(p);\n"
"int3 ip = convert_int3(fip);\n"
"float3 t = p - fip;\n"
"int3 cmul = volDims*ip;\n"
"int coordBase = cmul.x + cmul.y + cmul.z;\n"
"int nco[8];\n"
"vstore8(neighbourCoords + coordBase, 0, nco);\n"
"int arDims[3];\n"
"vstore3(volDims, 0, arDims);\n"
"float an[3];\n"
"for(int c = 0; c < 3; c++)\n"
"{\n"
"int dim = arDims[c];\n"
"float vaz[8];\n"
"for(int i = 0; i < 8; i++)\n"
"vaz[i] = tsdfToFloat(volumePtr[nco[i] + dim].tsdf) -\n"
"tsdfToFloat(volumePtr[nco[i] - dim].tsdf);\n"
"float8 vz = vload8(0, vaz);\n"
"float4 vy = mix(vz.s0246, vz.s1357, t.z);\n"
"float2 vx = mix(vy.s02, vy.s13, t.y);\n"
"an[c] = mix(vx.s0, vx.s1, t.x);\n"
"}\n"
"float3 n = vload3(0, an);\n"
"float Norm = sqrt(n.x*n.x + n.y*n.y + n.z*n.z);\n"
"return Norm < 0.0001f ? nan((uint)0) : n / Norm;\n"
"}\n"
"typedef float4 ptype;\n"
"__kernel void raycast(__global char * pointsptr,\n"
"int points_step, int points_offset,\n"
"__global char * normalsptr,\n"
"int normals_step, int normals_offset,\n"
"const int2 frameSize,\n"
"__global const struct TsdfVoxel * volumeptr,\n"
"__global const float * vol2camptr,\n"
"__global const float * cam2volptr,\n"
"const float2 fixy,\n"
"const float2 cxy,\n"
"const float4 boxDown4,\n"
"const float4 boxUp4,\n"
"const float tstep,\n"
"const float voxelSize,\n"
"const int4 volResolution4,\n"
"const int4 volDims4,\n"
"const int8 neighbourCoords\n"
")\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if(x >= frameSize.x || y >= frameSize.y)\n"
"return;\n"
"__global const float* cm = cam2volptr;\n"
"const float3 camRot0 = vload4(0, cm).xyz;\n"
"const float3 camRot1 = vload4(1, cm).xyz;\n"
"const float3 camRot2 = vload4(2, cm).xyz;\n"
"const float3 camTrans = (float3)(cm[3], cm[7], cm[11]);\n"
"__global const float* vm = vol2camptr;\n"
"const float3 volRot0 = vload4(0, vm).xyz;\n"
"const float3 volRot1 = vload4(1, vm).xyz;\n"
"const float3 volRot2 = vload4(2, vm).xyz;\n"
"const float3 volTrans = (float3)(vm[3], vm[7], vm[11]);\n"
"const float3 boxDown = boxDown4.xyz;\n"
"const float3 boxUp = boxUp4.xyz;\n"
"const int3 volDims = volDims4.xyz;\n"
"const int3 volResolution = volResolution4.xyz;\n"
"const float invVoxelSize = native_recip(voxelSize);\n"
"float3 point = nan((uint)0);\n"
"float3 normal = nan((uint)0);\n"
"float3 orig = camTrans;\n"
"float3 planed = (float3)(((float2)(x, y) - cxy)*fixy, 1.f);\n"
"planed = (float3)(dot(planed, camRot0),\n"
"dot(planed, camRot1),\n"
"dot(planed, camRot2));\n"
"float3 dir = fast_normalize(planed);\n"
"float3 rayinv = native_recip(dir);\n"
"float3 tbottom = rayinv*(boxDown - orig);\n"
"float3 ttop = rayinv*(boxUp - orig);\n"
"float3 minAx = min(ttop, tbottom);\n"
"float3 maxAx = max(ttop, tbottom);\n"
"const float clip = 0.f;\n"
"float tmin = max(max(max(minAx.x, minAx.y), max(minAx.x, minAx.z)), clip);\n"
"float tmax = min(min(maxAx.x, maxAx.y), min(maxAx.x, maxAx.z));\n"
"tmin = tmin + tstep;\n"
"tmax = tmax - tstep;\n"
"if(tmin < tmax)\n"
"{\n"
"orig *= invVoxelSize;\n"
"dir *= invVoxelSize;\n"
"float3 rayStep = dir*tstep;\n"
"float3 next = (orig + dir*tmin);\n"
"float f = interpolateVoxel(next, volumeptr, volDims, neighbourCoords);\n"
"float fnext = f;\n"
"int steps = 0;\n"
"int nSteps = floor(native_divide(tmax - tmin, tstep));\n"
"bool stop = false;\n"
"for(int i = 0; i < nSteps; i++)\n"
"{\n"
"if(!stop)\n"
"{\n"
"next += rayStep;\n"
"int3 ip = convert_int3(round(next));\n"
"int3 cmul = ip*volDims;\n"
"int idx = cmul.x + cmul.y + cmul.z;\n"
"fnext = tsdfToFloat(volumeptr[idx].tsdf);\n"
"if(fnext != f)\n"
"{\n"
"fnext = interpolateVoxel(next, volumeptr, volDims, neighbourCoords);\n"
"if(signbit(f) != signbit(fnext))\n"
"{\n"
"stop = true; continue;\n"
"}\n"
"f = fnext;\n"
"}\n"
"steps++;\n"
"}\n"
"}\n"
"if(f > 0 && fnext < 0)\n"
"{\n"
"float3 tp = next - rayStep;\n"
"float ft = interpolateVoxel(tp, volumeptr, volDims, neighbourCoords);\n"
"float ftdt = interpolateVoxel(next, volumeptr, volDims, neighbourCoords);\n"
"float ts = tmin + tstep*(steps - native_divide(ft, ftdt - ft));\n"
"if(!isnan(ts) && !isinf(ts))\n"
"{\n"
"float3 pv = orig + dir*ts;\n"
"float3 nv = getNormalVoxel(pv, volumeptr, volResolution, volDims, neighbourCoords);\n"
"if(!any(isnan(nv)))\n"
"{\n"
"normal = (float3)(dot(nv, volRot0),\n"
"dot(nv, volRot1),\n"
"dot(nv, volRot2));\n"
"pv *= voxelSize;\n"
"point = (float3)(dot(pv, volRot0),\n"
"dot(pv, volRot1),\n"
"dot(pv, volRot2)) + volTrans;\n"
"}\n"
"}\n"
"}\n"
"}\n"
"__global float* pts = (__global float*)(pointsptr + points_offset + y*points_step + x*sizeof(ptype));\n"
"__global float* nrm = (__global float*)(normalsptr + normals_offset + y*normals_step + x*sizeof(ptype));\n"
"vstore4((float4)(point, 0), 0, pts);\n"
"vstore4((float4)(normal, 0), 0, nrm);\n"
"}\n"
"__kernel void getNormals(__global const char * pointsptr,\n"
"int points_step, int points_offset,\n"
"__global char * normalsptr,\n"
"int normals_step, int normals_offset,\n"
"const int2 frameSize,\n"
"__global const struct TsdfVoxel* volumeptr,\n"
"__global const float * volPoseptr,\n"
"__global const float * invPoseptr,\n"
"const float voxelSizeInv,\n"
"const int4 volResolution4,\n"
"const int4 volDims4,\n"
"const int8 neighbourCoords\n"
")\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if(x >= frameSize.x || y >= frameSize.y)\n"
"return;\n"
"__global const float* vp = volPoseptr;\n"
"const float3 volRot0 = vload4(0, vp).xyz;\n"
"const float3 volRot1 = vload4(1, vp).xyz;\n"
"const float3 volRot2 = vload4(2, vp).xyz;\n"
"const float3 volTrans = (float3)(vp[3], vp[7], vp[11]);\n"
"__global const float* iv = invPoseptr;\n"
"const float3 invRot0 = vload4(0, iv).xyz;\n"
"const float3 invRot1 = vload4(1, iv).xyz;\n"
"const float3 invRot2 = vload4(2, iv).xyz;\n"
"const float3 invTrans = (float3)(iv[3], iv[7], iv[11]);\n"
"const int3 volResolution = volResolution4.xyz;\n"
"const int3 volDims = volDims4.xyz;\n"
"__global const ptype* ptsRow = (__global const ptype*)(pointsptr +\n"
"points_offset +\n"
"y*points_step);\n"
"float3 p = ptsRow[x].xyz;\n"
"float3 n = nan((uint)0);\n"
"if(!any(isnan(p)))\n"
"{\n"
"float3 voxPt = (float3)(dot(p, invRot0),\n"
"dot(p, invRot1),\n"
"dot(p, invRot2)) + invTrans;\n"
"voxPt = voxPt * voxelSizeInv;\n"
"n = getNormalVoxel(voxPt, volumeptr, volResolution, volDims, neighbourCoords);\n"
"n = (float3)(dot(n, volRot0),\n"
"dot(n, volRot1),\n"
"dot(n, volRot2));\n"
"}\n"
"__global float* nrm = (__global float*)(normalsptr +\n"
"normals_offset +\n"
"y*normals_step +\n"
"x*sizeof(ptype));\n"
"vstore4((float4)(n, 0), 0, nrm);\n"
"}\n"
"#pragma OPENCL EXTENSION cl_khr_global_int32_base_atomics:enable\n"
"struct CoordReturn\n"
"{\n"
"bool result;\n"
"float3 point;\n"
"float3 normal;\n"
"};\n"
"inline struct CoordReturn coord(int x, int y, int z, float3 V, float v0, int axis,\n"
"__global const struct TsdfVoxel* volumeptr,\n"
"int3 volResolution, int3 volDims,\n"
"int8 neighbourCoords,\n"
"float voxelSize, float voxelSizeInv,\n"
"const float3 volRot0,\n"
"const float3 volRot1,\n"
"const float3 volRot2,\n"
"const float3 volTrans,\n"
"bool needNormals,\n"
"bool scan\n"
")\n"
"{\n"
"struct CoordReturn cr;\n"
"bool limits = false;\n"
"int3 shift;\n"
"float Vc = 0.f;\n"
"if(axis == 0)\n"
"{\n"
"shift = (int3)(1, 0, 0);\n"
"limits = (x + 1 < volResolution.x);\n"
"Vc = V.x;\n"
"}\n"
"if(axis == 1)\n"
"{\n"
"shift = (int3)(0, 1, 0);\n"
"limits = (y + 1 < volResolution.y);\n"
"Vc = V.y;\n"
"}\n"
"if(axis == 2)\n"
"{\n"
"shift = (int3)(0, 0, 1);\n"
"limits = (z + 1 < volResolution.z);\n"
"Vc = V.z;\n"
"}\n"
"if(limits)\n"
"{\n"
"int3 ip = ((int3)(x, y, z)) + shift;\n"
"int3 cmul = ip*volDims;\n"
"int idx = cmul.x + cmul.y + cmul.z;\n"
"struct TsdfVoxel voxel = volumeptr[idx];\n"
"float vd = tsdfToFloat(voxel.tsdf);\n"
"int weight = voxel.weight;\n"
"if(weight != 0 && vd != 1.f)\n"
"{\n"
"if((v0 > 0 && vd < 0) || (v0 < 0 && vd > 0))\n"
"{\n"
"if(!scan)\n"
"{\n"
"float Vn = Vc + voxelSize;\n"
"float dinv = 1.f/(fabs(v0)+fabs(vd));\n"
"float inter = (Vc*fabs(vd) + Vn*fabs(v0))*dinv;\n"
"float3 p = (float3)(shift.x ? inter : V.x,\n"
"shift.y ? inter : V.y,\n"
"shift.z ? inter : V.z);\n"
"cr.point = (float3)(dot(p, volRot0),\n"
"dot(p, volRot1),\n"
"dot(p, volRot2)) + volTrans;\n"
"if(needNormals)\n"
"{\n"
"float3 nv = getNormalVoxel(p * voxelSizeInv,\n"
"volumeptr, volResolution, volDims, neighbourCoords);\n"
"cr.normal = (float3)(dot(nv, volRot0),\n"
"dot(nv, volRot1),\n"
"dot(nv, volRot2));\n"
"}\n"
"}\n"
"cr.result = true;\n"
"return cr;\n"
"}\n"
"}\n"
"}\n"
"cr.result = false;\n"
"return cr;\n"
"}\n"
"__kernel void scanSize(__global const struct TsdfVoxel* volumeptr,\n"
"const int4 volResolution4,\n"
"const int4 volDims4,\n"
"const int8 neighbourCoords,\n"
"__global const float * volPoseptr,\n"
"const float voxelSize,\n"
"const float voxelSizeInv,\n"
"__local int* reducebuf,\n"
"__global char* groupedSumptr,\n"
"int groupedSum_slicestep,\n"
"int groupedSum_step, int groupedSum_offset\n"
")\n"
"{\n"
"const int3 volDims = volDims4.xyz;\n"
"const int3 volResolution = volResolution4.xyz;\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"int z = get_global_id(2);\n"
"bool validVoxel = true;\n"
"if(x >= volResolution.x || y >= volResolution.y || z >= volResolution.z)\n"
"validVoxel = false;\n"
"const int gx = get_group_id(0);\n"
"const int gy = get_group_id(1);\n"
"const int gz = get_group_id(2);\n"
"const int lx = get_local_id(0);\n"
"const int ly = get_local_id(1);\n"
"const int lz = get_local_id(2);\n"
"const int lw = get_local_size(0);\n"
"const int lh = get_local_size(1);\n"
"const int ld = get_local_size(2);\n"
"const int lsz = lw*lh*ld;\n"
"const int lid = lx + ly*lw + lz*lw*lh;\n"
"__global const float* vp = volPoseptr;\n"
"const float3 volRot0 = vload4(0, vp).xyz;\n"
"const float3 volRot1 = vload4(1, vp).xyz;\n"
"const float3 volRot2 = vload4(2, vp).xyz;\n"
"const float3 volTrans = (float3)(vp[3], vp[7], vp[11]);\n"
"int npts = 0;\n"
"if(validVoxel)\n"
"{\n"
"int3 ip = (int3)(x, y, z);\n"
"int3 cmul = ip*volDims;\n"
"int idx = cmul.x + cmul.y + cmul.z;\n"
"struct TsdfVoxel voxel = volumeptr[idx];\n"
"float value = tsdfToFloat(voxel.tsdf);\n"
"int weight = voxel.weight;\n"
"if(weight != 0 && value != 1.f)\n"
"{\n"
"float3 V = (((float3)(x, y, z)) + 0.5f)*voxelSize;\n"
"#pragma unroll\n"
"for(int i = 0; i < 3; i++)\n"
"{\n"
"struct CoordReturn cr;\n"
"cr = coord(x, y, z, V, value, i,\n"
"volumeptr, volResolution, volDims,\n"
"neighbourCoords,\n"
"voxelSize, voxelSizeInv,\n"
"volRot0, volRot1, volRot2, volTrans,\n"
"false, true);\n"
"if(cr.result)\n"
"{\n"
"npts++;\n"
"}\n"
"}\n"
"}\n"
"}\n"
"reducebuf[lid] = npts;\n"
"const int c = clz(lsz & -lsz);\n"
"const int maxStep = c ? 31 - c : c;\n"
"for(int nstep = 1; nstep <= maxStep; nstep++)\n"
"{\n"
"if(lid % (1 << nstep) == 0)\n"
"{\n"
"int rto = lid;\n"
"int rfrom = lid + (1 << (nstep-1));\n"
"reducebuf[rto] += reducebuf[rfrom];\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"}\n"
"if(lid == 0)\n"
"{\n"
"__global int* groupedRow = (__global int*)(groupedSumptr +\n"
"groupedSum_offset +\n"
"gy*groupedSum_step +\n"
"gz*groupedSum_slicestep);\n"
"groupedRow[gx] = reducebuf[0];\n"
"}\n"
"}\n"
"__kernel void fillPtsNrm(__global const struct TsdfVoxel* volumeptr,\n"
"const int4 volResolution4,\n"
"const int4 volDims4,\n"
"const int8 neighbourCoords,\n"
"__global const float * volPoseptr,\n"
"const float voxelSize,\n"
"const float voxelSizeInv,\n"
"const int needNormals,\n"
"__local float* localbuf,\n"
"volatile __global int* atomicCtr,\n"
"__global const char* groupedSumptr,\n"
"int groupedSum_slicestep,\n"
"int groupedSum_step, int groupedSum_offset,\n"
"__global char * pointsptr,\n"
"int points_step, int points_offset,\n"
"__global char * normalsptr,\n"
"int normals_step, int normals_offset\n"
")\n"
"{\n"
"const int3 volDims = volDims4.xyz;\n"
"const int3 volResolution = volResolution4.xyz;\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"int z = get_global_id(2);\n"
"bool validVoxel = true;\n"
"if(x >= volResolution.x || y >= volResolution.y || z >= volResolution.z)\n"
"validVoxel = false;\n"
"const int gx = get_group_id(0);\n"
"const int gy = get_group_id(1);\n"
"const int gz = get_group_id(2);\n"
"__global int* groupedRow = (__global int*)(groupedSumptr +\n"
"groupedSum_offset +\n"
"gy*groupedSum_step +\n"
"gz*groupedSum_slicestep);\n"
"int nptsGroup = groupedRow[gx];\n"
"if(nptsGroup == 0)\n"
"return;\n"
"const int lx = get_local_id(0);\n"
"const int ly = get_local_id(1);\n"
"const int lz = get_local_id(2);\n"
"const int lw = get_local_size(0);\n"
"const int lh = get_local_size(1);\n"
"const int ld = get_local_size(2);\n"
"const int lsz = lw*lh*ld;\n"
"const int lid = lx + ly*lw + lz*lw*lh;\n"
"__global const float* vp = volPoseptr;\n"
"const float3 volRot0 = vload4(0, vp).xyz;\n"
"const float3 volRot1 = vload4(1, vp).xyz;\n"
"const float3 volRot2 = vload4(2, vp).xyz;\n"
"const float3 volTrans = (float3)(vp[3], vp[7], vp[11]);\n"
"int npts = 0;\n"
"float3 parr[3], narr[3];\n"
"if(validVoxel)\n"
"{\n"
"int3 ip = (int3)(x, y, z);\n"
"int3 cmul = ip*volDims;\n"
"int idx = cmul.x + cmul.y + cmul.z;\n"
"struct TsdfVoxel voxel = volumeptr[idx];\n"
"float value = tsdfToFloat(voxel.tsdf);\n"
"int weight = voxel.weight;\n"
"if(weight != 0 && value != 1.f)\n"
"{\n"
"float3 V = (((float3)(x, y, z)) + 0.5f)*voxelSize;\n"
"#pragma unroll\n"
"for(int i = 0; i < 3; i++)\n"
"{\n"
"struct CoordReturn cr;\n"
"cr = coord(x, y, z, V, value, i,\n"
"volumeptr, volResolution, volDims,\n"
"neighbourCoords,\n"
"voxelSize, voxelSizeInv,\n"
"volRot0, volRot1, volRot2, volTrans,\n"
"needNormals, false);\n"
"if(cr.result)\n"
"{\n"
"parr[npts] = cr.point;\n"
"narr[npts] = cr.normal;\n"
"npts++;\n"
"}\n"
"}\n"
"}\n"
"}\n"
"const int elemStep = 4;\n"
"__local float* normAddr;\n"
"__local int localCtr;\n"
"if(lid == 0)\n"
"localCtr = 0;\n"
"int privateCtr = 0;\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"privateCtr = atomic_add(&localCtr, npts);\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"for(int i = 0; i < npts; i++)\n"
"{\n"
"__local float* addr = localbuf + (privateCtr+i)*elemStep;\n"
"vstore4((float4)(parr[i], 0), 0, addr);\n"
"}\n"
"if(needNormals)\n"
"{\n"
"normAddr = localbuf + localCtr*elemStep;\n"
"for(int i = 0; i < npts; i++)\n"
"{\n"
"__local float* addr = normAddr + (privateCtr+i)*elemStep;\n"
"vstore4((float4)(narr[i], 0), 0, addr);\n"
"}\n"
"}\n"
"if(lid == 0)\n"
"{\n"
"if(localCtr != nptsGroup)\n"
"{\n"
"printf(\"!!! fetchPointsNormals result may be incorrect, npts != localCtr at %3d %3d %3d: %3d vs %3d\\n\",\n"
"gx, gy, gz, localCtr, nptsGroup);\n"
"}\n"
"}\n"
"__local int whereToWrite;\n"
"if(lid == 0)\n"
"whereToWrite = atomic_add(atomicCtr, localCtr);\n"
"barrier(CLK_GLOBAL_MEM_FENCE);\n"
"event_t ev[2];\n"
"int evn = 0;\n"
"__global float* pts = (__global float*)(pointsptr +\n"
"points_offset +\n"
"whereToWrite*points_step);\n"
"ev[evn++] = async_work_group_copy(pts, localbuf, localCtr*elemStep, 0);\n"
"if(needNormals)\n"
"{\n"
"__global float* nrm = (__global float*)(normalsptr +\n"
"normals_offset +\n"
"whereToWrite*normals_step);\n"
"ev[evn++] = async_work_group_copy(nrm, normAddr, localCtr*elemStep, 0);\n"
"}\n"
"wait_group_events(evn, ev);\n"
"}\n"
, "5e8f0602bc335b694f2060f3c756c2b7", NULL};
struct cv::ocl::internal::ProgramEntry tsdf_functions_oclsrc={moduleName, "tsdf_functions",
"__kernel void preCalculationPixNorm (__global char * pixNormsPtr,\n"
"int pixNormsStep, int pixNormsOffset,\n"
"int pixNormsRows, int pixNormsCols,\n"
"const __global float * xx,\n"
"const __global float * yy)\n"
"{\n"
"int i = get_global_id(0);\n"
"int j = get_global_id(1);\n"
"if (i < pixNormsRows && j < pixNormsCols)\n"
"{\n"
"*(__global float*)(pixNormsPtr + pixNormsOffset + i*pixNormsStep + j*sizeof(float)) = sqrt(xx[j] * xx[j] + yy[i] * yy[i] + 1.0f);\n"
"}\n"
"}\n"
, "2c16a37c55c6c1c5edaa4e3bbecc80d8", NULL};
}}}
#endif
| 32.34232
| 133
| 0.64975
|
soyyuz
|
ca98e3df57f42bdc0418d395557fa9adc1abf9e7
| 13,242
|
hpp
|
C++
|
include/codegen/include/UnityEngine/RenderTexture.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/UnityEngine/RenderTexture.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/UnityEngine/RenderTexture.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:28 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: UnityEngine.Texture
#include "UnityEngine/Texture.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::Experimental::Rendering
namespace UnityEngine::Experimental::Rendering {
// Forward declaring type: GraphicsFormat
struct GraphicsFormat;
// Forward declaring type: DefaultFormat
struct DefaultFormat;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: VRTextureUsage
struct VRTextureUsage;
// Forward declaring type: RenderTextureFormat
struct RenderTextureFormat;
// Forward declaring type: RenderBuffer
struct RenderBuffer;
// Forward declaring type: RenderTextureDescriptor
struct RenderTextureDescriptor;
// Forward declaring type: RenderTextureReadWrite
struct RenderTextureReadWrite;
// Forward declaring type: RenderTextureMemoryless
struct RenderTextureMemoryless;
}
// Forward declaring namespace: UnityEngine::Rendering
namespace UnityEngine::Rendering {
// Forward declaring type: TextureDimension
struct TextureDimension;
}
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Autogenerated type: UnityEngine.RenderTexture
class RenderTexture : public UnityEngine::Texture {
public:
// public UnityEngine.Experimental.Rendering.GraphicsFormat get_graphicsFormat()
// Offset: 0x1409CF8
UnityEngine::Experimental::Rendering::GraphicsFormat get_graphicsFormat();
// public System.Void set_graphicsFormat(UnityEngine.Experimental.Rendering.GraphicsFormat value)
// Offset: 0x1409D38
void set_graphicsFormat(UnityEngine::Experimental::Rendering::GraphicsFormat value);
// public UnityEngine.VRTextureUsage get_vrUsage()
// Offset: 0x1409D88
UnityEngine::VRTextureUsage get_vrUsage();
// public UnityEngine.RenderTextureFormat get_format()
// Offset: 0x1409DC8
UnityEngine::RenderTextureFormat get_format();
// public System.Int32 get_antiAliasing()
// Offset: 0x1409E10
int get_antiAliasing();
// public System.Void set_antiAliasing(System.Int32 value)
// Offset: 0x1409E50
void set_antiAliasing(int value);
// static private UnityEngine.RenderTexture GetActive()
// Offset: 0x1409EA0
static UnityEngine::RenderTexture* GetActive();
// static private System.Void SetActive(UnityEngine.RenderTexture rt)
// Offset: 0x1409ED4
static void SetActive(UnityEngine::RenderTexture* rt);
// static public UnityEngine.RenderTexture get_active()
// Offset: 0x1409F14
static UnityEngine::RenderTexture* get_active();
// static public System.Void set_active(UnityEngine.RenderTexture value)
// Offset: 0x1409F48
static void set_active(UnityEngine::RenderTexture* value);
// private UnityEngine.RenderBuffer GetColorBuffer()
// Offset: 0x1409F88
UnityEngine::RenderBuffer GetColorBuffer();
// private UnityEngine.RenderBuffer GetDepthBuffer()
// Offset: 0x140A030
UnityEngine::RenderBuffer GetDepthBuffer();
// public UnityEngine.RenderBuffer get_colorBuffer()
// Offset: 0x140A0D8
UnityEngine::RenderBuffer get_colorBuffer();
// public UnityEngine.RenderBuffer get_depthBuffer()
// Offset: 0x140A0DC
UnityEngine::RenderBuffer get_depthBuffer();
// public System.Void DiscardContents(System.Boolean discardColor, System.Boolean discardDepth)
// Offset: 0x140A0E0
void DiscardContents(bool discardColor, bool discardDepth);
// public System.Void DiscardContents()
// Offset: 0x140A138
void DiscardContents();
// public System.Boolean Create()
// Offset: 0x140A180
bool Create();
// public System.Void Release()
// Offset: 0x140A1C0
void Release();
// public System.Boolean IsCreated()
// Offset: 0x140A200
bool IsCreated();
// System.Void SetSRGBReadWrite(System.Boolean srgb)
// Offset: 0x140A240
void SetSRGBReadWrite(bool srgb);
// static private System.Void Internal_Create(UnityEngine.RenderTexture rt)
// Offset: 0x140A290
static void Internal_Create(UnityEngine::RenderTexture* rt);
// private System.Void SetRenderTextureDescriptor(UnityEngine.RenderTextureDescriptor desc)
// Offset: 0x140A2D0
void SetRenderTextureDescriptor(UnityEngine::RenderTextureDescriptor desc);
// private UnityEngine.RenderTextureDescriptor GetDescriptor()
// Offset: 0x140A370
UnityEngine::RenderTextureDescriptor GetDescriptor();
// static private UnityEngine.RenderTexture GetTemporary_Internal(UnityEngine.RenderTextureDescriptor desc)
// Offset: 0x140A44C
static UnityEngine::RenderTexture* GetTemporary_Internal(UnityEngine::RenderTextureDescriptor desc);
// static public System.Void ReleaseTemporary(UnityEngine.RenderTexture temp)
// Offset: 0x140A4CC
static void ReleaseTemporary(UnityEngine::RenderTexture* temp);
// public System.Void set_depth(System.Int32 value)
// Offset: 0x140A50C
void set_depth(int value);
// public System.Void .ctor(UnityEngine.RenderTextureDescriptor desc)
// Offset: 0x140A5C4
static RenderTexture* New_ctor(UnityEngine::RenderTextureDescriptor desc);
// public System.Void .ctor(UnityEngine.RenderTexture textureToCopy)
// Offset: 0x140A900
static RenderTexture* New_ctor(UnityEngine::RenderTexture* textureToCopy);
// public System.Void .ctor(System.Int32 width, System.Int32 height, System.Int32 depth, UnityEngine.Experimental.Rendering.DefaultFormat format)
// Offset: 0x140AB18
static RenderTexture* New_ctor(int width, int height, int depth, UnityEngine::Experimental::Rendering::DefaultFormat format);
// public System.Void .ctor(System.Int32 width, System.Int32 height, System.Int32 depth, UnityEngine.Experimental.Rendering.GraphicsFormat format)
// Offset: 0x140AB68
static RenderTexture* New_ctor(int width, int height, int depth, UnityEngine::Experimental::Rendering::GraphicsFormat format);
// public System.Void .ctor(System.Int32 width, System.Int32 height, System.Int32 depth, UnityEngine.Experimental.Rendering.GraphicsFormat format, System.Int32 mipCount)
// Offset: 0x140AD24
static RenderTexture* New_ctor(int width, int height, int depth, UnityEngine::Experimental::Rendering::GraphicsFormat format, int mipCount);
// public System.Void .ctor(System.Int32 width, System.Int32 height, System.Int32 depth, UnityEngine.RenderTextureFormat format, UnityEngine.RenderTextureReadWrite readWrite)
// Offset: 0x140B088
static RenderTexture* New_ctor(int width, int height, int depth, UnityEngine::RenderTextureFormat format, UnityEngine::RenderTextureReadWrite readWrite);
// public System.Void .ctor(System.Int32 width, System.Int32 height, System.Int32 depth, UnityEngine.RenderTextureFormat format)
// Offset: 0x140B220
static RenderTexture* New_ctor(int width, int height, int depth, UnityEngine::RenderTextureFormat format);
// public System.Void .ctor(System.Int32 width, System.Int32 height, System.Int32 depth)
// Offset: 0x140B270
static RenderTexture* New_ctor(int width, int height, int depth);
// public System.Void .ctor(System.Int32 width, System.Int32 height, System.Int32 depth, UnityEngine.RenderTextureFormat format, System.Int32 mipCount)
// Offset: 0x140B2C0
static RenderTexture* New_ctor(int width, int height, int depth, UnityEngine::RenderTextureFormat format, int mipCount);
// public UnityEngine.RenderTextureDescriptor get_descriptor()
// Offset: 0x140AA68
UnityEngine::RenderTextureDescriptor get_descriptor();
// public System.Void set_descriptor(UnityEngine.RenderTextureDescriptor value)
// Offset: 0x140AFFC
void set_descriptor(UnityEngine::RenderTextureDescriptor value);
// static private System.Void ValidateRenderTextureDesc(UnityEngine.RenderTextureDescriptor desc)
// Offset: 0x140A6D0
static void ValidateRenderTextureDesc(UnityEngine::RenderTextureDescriptor desc);
// static UnityEngine.Experimental.Rendering.GraphicsFormat GetCompatibleFormat(UnityEngine.RenderTextureFormat renderTextureFormat, UnityEngine.RenderTextureReadWrite readWrite)
// Offset: 0x140B0D8
static UnityEngine::Experimental::Rendering::GraphicsFormat GetCompatibleFormat(UnityEngine::RenderTextureFormat renderTextureFormat, UnityEngine::RenderTextureReadWrite readWrite);
// static public UnityEngine.RenderTexture GetTemporary(UnityEngine.RenderTextureDescriptor desc)
// Offset: 0x140B3C0
static UnityEngine::RenderTexture* GetTemporary(UnityEngine::RenderTextureDescriptor desc);
// static private UnityEngine.RenderTexture GetTemporaryImpl(System.Int32 width, System.Int32 height, System.Int32 depthBuffer, UnityEngine.Experimental.Rendering.GraphicsFormat format, System.Int32 antiAliasing, UnityEngine.RenderTextureMemoryless memorylessMode, UnityEngine.VRTextureUsage vrUsage, System.Boolean useDynamicScale)
// Offset: 0x140B468
static UnityEngine::RenderTexture* GetTemporaryImpl(int width, int height, int depthBuffer, UnityEngine::Experimental::Rendering::GraphicsFormat format, int antiAliasing, UnityEngine::RenderTextureMemoryless memorylessMode, UnityEngine::VRTextureUsage vrUsage, bool useDynamicScale);
// static public UnityEngine.RenderTexture GetTemporary(System.Int32 width, System.Int32 height, System.Int32 depthBuffer, UnityEngine.RenderTextureFormat format, UnityEngine.RenderTextureReadWrite readWrite, System.Int32 antiAliasing)
// Offset: 0x140B5C4
static UnityEngine::RenderTexture* GetTemporary(int width, int height, int depthBuffer, UnityEngine::RenderTextureFormat format, UnityEngine::RenderTextureReadWrite readWrite, int antiAliasing);
// static public UnityEngine.RenderTexture GetTemporary(System.Int32 width, System.Int32 height, System.Int32 depthBuffer, UnityEngine.RenderTextureFormat format, UnityEngine.RenderTextureReadWrite readWrite)
// Offset: 0x140B62C
static UnityEngine::RenderTexture* GetTemporary(int width, int height, int depthBuffer, UnityEngine::RenderTextureFormat format, UnityEngine::RenderTextureReadWrite readWrite);
// static public UnityEngine.RenderTexture GetTemporary(System.Int32 width, System.Int32 height)
// Offset: 0x140B690
static UnityEngine::RenderTexture* GetTemporary(int width, int height);
// private System.Void GetColorBuffer_Injected(UnityEngine.RenderBuffer ret)
// Offset: 0x1409FE0
void GetColorBuffer_Injected(UnityEngine::RenderBuffer& ret);
// private System.Void GetDepthBuffer_Injected(UnityEngine.RenderBuffer ret)
// Offset: 0x140A088
void GetDepthBuffer_Injected(UnityEngine::RenderBuffer& ret);
// private System.Void SetRenderTextureDescriptor_Injected(UnityEngine.RenderTextureDescriptor desc)
// Offset: 0x140A320
void SetRenderTextureDescriptor_Injected(UnityEngine::RenderTextureDescriptor& desc);
// private System.Void GetDescriptor_Injected(UnityEngine.RenderTextureDescriptor ret)
// Offset: 0x140A3FC
void GetDescriptor_Injected(UnityEngine::RenderTextureDescriptor& ret);
// static private UnityEngine.RenderTexture GetTemporary_Internal_Injected(UnityEngine.RenderTextureDescriptor desc)
// Offset: 0x140A48C
static UnityEngine::RenderTexture* GetTemporary_Internal_Injected(UnityEngine::RenderTextureDescriptor& desc);
// public override System.Int32 get_width()
// Offset: 0x1409B88
// Implemented from: UnityEngine.Texture
// Base method: System.Int32 Texture::get_width()
int get_width();
// public override System.Void set_width(System.Int32 value)
// Offset: 0x1409BC8
// Implemented from: UnityEngine.Texture
// Base method: System.Void Texture::set_width(System.Int32 value)
void set_width(int value);
// public override System.Int32 get_height()
// Offset: 0x1409C18
// Implemented from: UnityEngine.Texture
// Base method: System.Int32 Texture::get_height()
int get_height();
// public override System.Void set_height(System.Int32 value)
// Offset: 0x1409C58
// Implemented from: UnityEngine.Texture
// Base method: System.Void Texture::set_height(System.Int32 value)
void set_height(int value);
// public override System.Void set_dimension(UnityEngine.Rendering.TextureDimension value)
// Offset: 0x1409CA8
// Implemented from: UnityEngine.Texture
// Base method: System.Void Texture::set_dimension(UnityEngine.Rendering.TextureDimension value)
void set_dimension(UnityEngine::Rendering::TextureDimension value);
// protected internal System.Void .ctor()
// Offset: 0x140A55C
// Implemented from: UnityEngine.Texture
// Base method: System.Void Texture::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static RenderTexture* New_ctor();
}; // UnityEngine.RenderTexture
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::RenderTexture*, "UnityEngine", "RenderTexture");
#pragma pack(pop)
| 58.078947
| 336
| 0.771485
|
Futuremappermydud
|
ca9af8873ded9de65dd6fb8ab5628b0e1d876763
| 3,489
|
cpp
|
C++
|
TensorShaderAvxBackend/Convolution/Dense/transposedense.cpp
|
tk-yoshimura/TensorShaderAVX
|
de47428efbeaa4df694e4a3584b0397162e711d9
|
[
"MIT"
] | null | null | null |
TensorShaderAvxBackend/Convolution/Dense/transposedense.cpp
|
tk-yoshimura/TensorShaderAVX
|
de47428efbeaa4df694e4a3584b0397162e711d9
|
[
"MIT"
] | null | null | null |
TensorShaderAvxBackend/Convolution/Dense/transposedense.cpp
|
tk-yoshimura/TensorShaderAVX
|
de47428efbeaa4df694e4a3584b0397162e711d9
|
[
"MIT"
] | null | null | null |
#include "../../TensorShaderAvxBackend.h"
using namespace System;
__forceinline __m128 _mm256d_sum(__m256d hi, __m256d lo) {
__m256d u = _mm256_hadd_pd(lo, hi);
__m256d v = _mm256_hadd_pd(u, _mm256_setzero_pd());
__m128d w = _mm_add_pd(_mm256_extractf128_pd(v, 1), _mm256_castpd256_pd128(v));
return _mm_cvtpd_ps(w);
}
void transposedense(unsigned int inchannels, unsigned int outchannels, unsigned int th, float* inmap_ptr, float* outmap_ptr, float* kernel_ptr) {
const unsigned int inmap_offset = inchannels * th, outmap_offset = outchannels * th;
const unsigned int inch_sep = inchannels & ~7u, inch_rem = inchannels - inch_sep;
const __m256i mask = TensorShaderAvxBackend::masktable_m256(inch_rem);
const __m128i mask1 = TensorShaderAvxBackend::masktable_m128(1);
const __m256i index = _mm256_setr_epi32(0, outchannels, outchannels * 2, outchannels * 3,
outchannels * 4, outchannels * 5, outchannels * 6, outchannels * 7);
inmap_ptr += inmap_offset;
outmap_ptr += outmap_offset;
for (unsigned int outch = 0; outch < outchannels; outch++) {
__m256d uv_hi = _mm256_setzero_pd(), uv_lo = _mm256_setzero_pd();
for (unsigned int inch = 0; inch < inch_sep; inch += 8) {
__m256 u = _mm256_loadu_ps(inmap_ptr + inch);
__m256 v = _mm256_i32gather_ps(kernel_ptr + outch + outchannels * inch, index, 4);
__m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1));
__m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u));
__m256d v_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(v, 1));
__m256d v_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(v));
uv_hi = _mm256_fmadd_pd(u_hi, v_hi, uv_hi);
uv_lo = _mm256_fmadd_pd(u_lo, v_lo, uv_lo);
}
if (inch_rem > 0) {
__m256 u = _mm256_maskload_ps(inmap_ptr + inch_sep, mask);
__m256 v = _mm256_mask_i32gather_ps(_mm256_setzero_ps(), kernel_ptr + outch + outchannels * inch_sep,
index, _mm256_castsi256_ps(mask), 4);
__m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1));
__m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u));
__m256d v_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(v, 1));
__m256d v_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(v));
uv_hi = _mm256_fmadd_pd(u_hi, v_hi, uv_hi);
uv_lo = _mm256_fmadd_pd(u_lo, v_lo, uv_lo);
}
_mm_maskstore_ps(outmap_ptr + outch, mask1, _mm256d_sum(uv_hi, uv_lo));
}
}
void TensorShaderAvxBackend::Convolution::TransposeDense(unsigned int inchannels, unsigned int outchannels, unsigned int batch, unsigned int th,
AvxArray<float>^ inmap, AvxArray<float>^ kernel, AvxArray<float>^ outmap) {
Util::CheckDuplicateArray(inmap, kernel, outmap);
if (th >= batch) {
throw gcnew System::ArgumentException();
}
Util::CheckLength(inchannels * batch, inmap);
Util::CheckLength(outchannels * batch, outmap);
Util::CheckLength(inchannels * outchannels, kernel);
float* inmap_ptr = (float*)(inmap->Ptr.ToPointer());
float* outmap_ptr = (float*)(outmap->Ptr.ToPointer());
float* kernel_ptr = (float*)(kernel->Ptr.ToPointer());
transposedense(inchannels, outchannels, th, inmap_ptr, outmap_ptr, kernel_ptr);
}
| 44.164557
| 145
| 0.658068
|
tk-yoshimura
|
ca9b0401dbb5383b690a3430e65ded8f96ca0571
| 7,562
|
cpp
|
C++
|
src/ChildProcess.Native/Exports.cpp
|
asmichi/ChildProcess
|
f40fa535dd475cf45c003265a1e428a30bf5b005
|
[
"MIT"
] | 16
|
2019-05-09T01:31:01.000Z
|
2022-02-24T12:31:50.000Z
|
src/ChildProcess.Native/Exports.cpp
|
asmichi/ChildProcess
|
f40fa535dd475cf45c003265a1e428a30bf5b005
|
[
"MIT"
] | null | null | null |
src/ChildProcess.Native/Exports.cpp
|
asmichi/ChildProcess
|
f40fa535dd475cf45c003265a1e428a30bf5b005
|
[
"MIT"
] | 2
|
2020-12-13T03:08:01.000Z
|
2021-01-30T21:54:41.000Z
|
// Copyright (c) @asmichi (https://github.com/asmichi). Licensed under the MIT License. See LICENCE in the project root for details.
// Interface for the managed implementation.
#include "AncillaryDataSocket.hpp"
#include "Base.hpp"
#include "MiscHelpers.hpp"
#include "Request.hpp"
#include "Service.hpp"
#include "SocketHelpers.hpp"
#include "UniqueResource.hpp"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <dlfcn.h>
#include <fcntl.h>
#include <memory>
#include <stdexcept>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
static_assert(sizeof(int) == 4);
namespace
{
enum FileAccess
{
FileAccessRead = 1,
FileAccessWrite = 2,
};
[[nodiscard]] bool IsWithinFdRange(std::intptr_t fd) noexcept
{
return 0 <= fd && fd <= std::numeric_limits<int>::max();
}
} // namespace
extern "C" bool ConnectToUnixSocket(const char* path, intptr_t* outSock)
{
struct sockaddr_un name;
if (std::strlen(path) > sizeof(name.sun_path) - 1)
{
errno = ENAMETOOLONG;
return false;
}
auto maybeSock = CreateUnixStreamSocket();
if (!maybeSock)
{
return false;
}
std::memset(&name, 0, sizeof(name));
name.sun_family = AF_UNIX;
std::strcpy(name.sun_path, path);
if (connect(maybeSock->Get(), reinterpret_cast<struct sockaddr*>(&name), sizeof(name)) == -1)
{
return false;
}
*outSock = maybeSock->Release();
return true;
}
extern "C" bool CreatePipe(intptr_t* readEnd, intptr_t* writeEnd)
{
auto maybePipe = CreatePipe();
if (!maybePipe)
{
return false;
}
*readEnd = maybePipe->ReadEnd.Release();
*writeEnd = maybePipe->WriteEnd.Release();
return true;
}
extern "C" bool CreateUnixStreamSocketPair(intptr_t* sock1, intptr_t* sock2)
{
auto maybeSockerPair = CreateUnixStreamSocketPair();
if (!maybeSockerPair)
{
return -1;
}
*sock1 = (*maybeSockerPair)[0].Release();
*sock2 = (*maybeSockerPair)[1].Release();
return true;
}
// Duplicate the std* handle of the current process if it will not cause SIGTTIN/SIGTTOU in the child process.
extern "C" bool DuplicateStdFileForChild(int stdFd, bool createNewProcessGroup, intptr_t* outFd)
{
if (stdFd != STDIN_FILENO && stdFd != STDOUT_FILENO && stdFd != STDERR_FILENO)
{
errno = EINVAL;
return false;
}
// First duplicate the fd since we do not own it and it can be replaced with another file description.
auto newFd = DuplicateFd(stdFd);
if (!newFd)
{
assert(errno == EBADF);
*outFd = -1;
return true;
}
if (!createNewProcessGroup)
{
// If the child process will be created within the current process group, this fd will not cause SIGTTIN/SIGTTOU.
*outFd = newFd->Release();
return true;
}
if (isatty(newFd->Get()))
{
// If the fd refers to a terminal, it will cause SIGTTIN/SIGTTOU if passed to another process group.
*outFd = -1;
return false;
}
else
{
assert(errno != EBADF);
*outFd = newFd->Release();
return true;
}
}
// Writes the path of this DLL to buf if buf has sufficient space.
// On success, returns the length of the path (including NUL).
// On error, returns -1.
extern "C" std::int32_t GetDllPath(char* buf, std::int32_t len)
{
#if defined(__linux__) || defined(__APPLE__)
Dl_info info;
if (!dladdr(reinterpret_cast<const void*>(&GetDllPath), &info))
{
return -1;
}
const size_t fnameLen = strlen(info.dli_fname);
if (fnameLen > std::numeric_limits<std::int32_t>::max() - 1)
{
assert(false);
errno = ENOMEM;
return -1;
}
const std::int32_t requiredBufLen = static_cast<std::int32_t>(fnameLen) + 1;
if (buf != nullptr && len >= requiredBufLen)
{
std::memcpy(buf, info.dli_fname, requiredBufLen);
}
return requiredBufLen;
#else
#error dladdr not available.
#endif
}
extern "C" int GetENOENT()
{
return ENOENT;
}
// Returns maximum number of bytes of a unix domain socket path (excluding the terminating NUL byte).
extern "C" std::size_t GetMaxSocketPathLength()
{
struct sockaddr_un addr;
return sizeof(addr.sun_path) - 1;
}
extern "C" int GetPid()
{
static_assert(sizeof(pid_t) == sizeof(int));
return static_cast<int>(getpid());
}
// Opens "/dev/null" with the specified nativeAccess.
extern "C" std::intptr_t OpenNullDevice(int fileAccess)
{
int nativeAccess;
if ((fileAccess & (FileAccessRead | FileAccessWrite)) == (FileAccessRead | FileAccessWrite))
{
nativeAccess = O_RDWR;
}
else if (fileAccess & FileAccessRead)
{
nativeAccess = O_RDONLY;
}
else if (fileAccess & FileAccessWrite)
{
nativeAccess = O_WRONLY;
}
else
{
errno = EINVAL;
return -1;
}
return open("/dev/null", O_CLOEXEC | nativeAccess);
}
// Creates a subchannel.
// On success, returns the subchannel fd.
// On error, sets errno and returns -1.
extern "C" std::intptr_t SubchannelCreate(std::intptr_t mainChannelFd)
{
if (!IsWithinFdRange(mainChannelFd))
{
errno = EINVAL;
return -1;
}
// Create a subchannel socket pair.
auto maybeSockerPair = CreateUnixStreamSocketPair();
if (!maybeSockerPair)
{
return -1;
}
auto localSock = std::move((*maybeSockerPair)[0]);
auto remoteSock = std::move((*maybeSockerPair)[1]);
// Send remoteSock to the helper process and request subchannel creation.
const int fds[1]{remoteSock.Get()};
const char dummyData = 0;
// We should not split this.
if (!SendExactBytesWithFd(static_cast<int>(mainChannelFd), &dummyData, 1, fds, 1))
{
return -1;
}
remoteSock.Reset();
// Receive the creation result.
std::int32_t err;
if (!RecvExactBytes(localSock.Get(), &err, sizeof(err)))
{
return -1;
}
if (err != 0)
{
errno = err;
return -1;
}
return localSock.Release();
}
// Closes a subchannel.
extern "C" bool SubchannelDestroy(std::intptr_t subchannelFd)
{
if (!IsWithinFdRange(subchannelFd))
{
errno = EINVAL;
return -1;
}
#if defined(__linux__) || defined(__APPLE__)
// On most *nix systems, even when close returns EINTR, the fd has been closed.
return close(static_cast<int>(subchannelFd)) == 0 || errno == EINTR;
#else
#error Not implemented.
#endif
}
// Receives data to entire buf
extern "C" bool SubchannelRecvExactBytes(std::intptr_t subchannelFd, void* buf, std::size_t len) noexcept
{
if (!IsWithinFdRange(subchannelFd))
{
errno = EINVAL;
return false;
}
return RecvExactBytes(static_cast<int>(subchannelFd), buf, len);
}
// Sends entire data
extern "C" bool SubchannelSendExactBytes(std::intptr_t subchannelFd, const void* buf, std::size_t len) noexcept
{
if (!IsWithinFdRange(subchannelFd))
{
errno = EINVAL;
return false;
}
return SendExactBytes(static_cast<int>(subchannelFd), buf, len);
}
// Sends entire data along with fds.
extern "C" bool SubchannelSendExactBytesAndFds(std::intptr_t subchannelFd, const void* buf, std::size_t len, const int* fds, std::size_t fdCount) noexcept
{
if (!IsWithinFdRange(subchannelFd))
{
errno = EINVAL;
return false;
}
return SendExactBytesWithFd(static_cast<int>(subchannelFd), buf, len, fds, fdCount);
}
| 24.472492
| 154
| 0.640571
|
asmichi
|
ca9bcae4b24183b5a47599116f02d13eafcca560
| 22,049
|
cpp
|
C++
|
12/moon_simulator.t.cpp
|
ComicSansMS/AdventOfCode2019
|
7ca0c57bf28ee8edab04c31a36dbd34d66d7f816
|
[
"Unlicense"
] | 3
|
2019-12-01T17:37:33.000Z
|
2021-12-14T10:12:09.000Z
|
12/moon_simulator.t.cpp
|
ComicSansMS/AdventOfCode2019
|
7ca0c57bf28ee8edab04c31a36dbd34d66d7f816
|
[
"Unlicense"
] | null | null | null |
12/moon_simulator.t.cpp
|
ComicSansMS/AdventOfCode2019
|
7ca0c57bf28ee8edab04c31a36dbd34d66d7f816
|
[
"Unlicense"
] | null | null | null |
#include <moon_simulator.hpp>
#include <catch.hpp>
#include <sstream>
#include <vector>
TEST_CASE("Moon Simulator")
{
SECTION("Vector3 Construction")
{
CHECK(Vector3().x == 0);
CHECK(Vector3().y == 0);
CHECK(Vector3().z == 0);
CHECK(Vector3(1, 2, 3).x == 1);
CHECK(Vector3(1, 2, 3).y == 2);
CHECK(Vector3(1, 2, 3).z == 3);
CHECK(Vector3(1, 2, 3) == Vector3(1, 2, 3));
CHECK_FALSE(Vector3(1, 2, 3) == Vector3(0, 2, 3));
CHECK_FALSE(Vector3(1, 2, 3) == Vector3(1, 0, 3));
CHECK_FALSE(Vector3(1, 2, 3) == Vector3(1, 2, 0));
CHECK_FALSE(Vector3(1, 2, 3) == Vector3(1, 0, 0));
CHECK_FALSE(Vector3(1, 2, 3) == Vector3(0, 2, 0));
CHECK_FALSE(Vector3(1, 2, 3) == Vector3(0, 0, 3));
CHECK_FALSE(Vector3(1, 2, 3) == Vector3(0, 0, 0));
}
SECTION("Vector3 Output")
{
std::stringstream sstr;
sstr << Vector3(1, 2, 3);
CHECK(sstr.str() == "[1,2,3]");
}
SECTION("Vector3 Addition")
{
CHECK(Vector3(1, 2, 3) + Vector3(1, 2, 3) == Vector3(2, 4, 6));
CHECK(Vector3(1, 2, 3) + Vector3(5, 9, 14) == Vector3(6, 11, 17));
CHECK(Vector3(1, 2, 3) + Vector3(-1, -2, -3) == Vector3());
}
char const sample_input[] = "<x=-1, y=0, z=2>\n"
"<x=2, y=-10, z=-7>\n"
"<x=4, y=-8, z=8>\n"
"<x=3, y=5, z=-1>\n";
SECTION("Parse Input")
{
PlanetarySystem p = parseInput(sample_input);
REQUIRE(p.size() == 4);
CHECK(p[0].position == Vector3(-1, 0, 2));
CHECK(p[1].position == Vector3(2, -10, -7));
CHECK(p[2].position == Vector3(4, -8, 8));
CHECK(p[3].position == Vector3(3, 5, -1));
CHECK(p[0].velocity == Vector3());
CHECK(p[1].velocity == Vector3());
CHECK(p[2].velocity == Vector3());
CHECK(p[3].velocity == Vector3());
}
SECTION("Gravity Between Two Moons")
{
Moon ganymede{ Vector3(3, 12, 6), Vector3() };
Moon callisto{ Vector3(5, -1, 6), Vector3() };
applyGravity(ganymede, callisto);
CHECK(ganymede.velocity == Vector3(1, -1, 0));
CHECK(callisto.velocity == Vector3(-1, 1, 0));
// position is unchanged
CHECK(ganymede.position == Vector3(3, 12, 6));
CHECK(callisto.position == Vector3(5, -1, 6));
applyGravity(ganymede, callisto);
CHECK(ganymede.velocity == Vector3(2, -2, 0));
CHECK(callisto.velocity == Vector3(-2, 2, 0));
}
SECTION("Apply Velocity")
{
Moon europa{ Vector3(1, 2, 3), Vector3(-2, 0, 3) };
applyVelocity(europa);
CHECK(europa.position == Vector3(-1, 2, 6));
// velocity is unchanges
CHECK(europa.velocity == Vector3(-2, 0, 3));
}
SECTION("Potential Energy")
{
PlanetarySystem p;
p[0] = Moon{ Vector3( 2, 1, -3), Vector3(-3, -2, 1) };
p[1] = Moon{ Vector3( 1, -8, 0), Vector3(-1, 1, 3) };
p[2] = Moon{ Vector3( 3, -6, 1), Vector3( 3, 2, -3) };
p[3] = Moon{ Vector3( 2, 0, 4), Vector3( 1, -1, -1) };
CHECK(potentialEnergy(p[0]) == 6);
CHECK(potentialEnergy(p[1]) == 9);
CHECK(potentialEnergy(p[2]) == 10);
CHECK(potentialEnergy(p[3]) == 6);
}
SECTION("Kinetic Energy")
{
PlanetarySystem p;
p[0] = Moon{ Vector3( 2, 1, -3), Vector3(-3, -2, 1) };
p[1] = Moon{ Vector3( 1, -8, 0), Vector3(-1, 1, 3) };
p[2] = Moon{ Vector3( 3, -6, 1), Vector3( 3, 2, -3) };
p[3] = Moon{ Vector3( 2, 0, 4), Vector3( 1, -1, -1) };
CHECK(kineticEnergy(p[0]) == 6);
CHECK(kineticEnergy(p[1]) == 5);
CHECK(kineticEnergy(p[2]) == 8);
CHECK(kineticEnergy(p[3]) == 3);
}
SECTION("Total Energy")
{
PlanetarySystem p;
p[0] = Moon{ Vector3( 2, 1, -3), Vector3(-3, -2, 1) };
p[1] = Moon{ Vector3( 1, -8, 0), Vector3(-1, 1, 3) };
p[2] = Moon{ Vector3( 3, -6, 1), Vector3( 3, 2, -3) };
p[3] = Moon{ Vector3( 2, 0, 4), Vector3( 1, -1, -1) };
CHECK(totalEnergy(p) == 179);
}
SECTION("Simulate")
{
PlanetarySystem p = parseInput(sample_input);
// After 0 steps:
// pos=<x=-1, y= 0, z= 2>, vel=<x= 0, y= 0, z= 0>
// pos=<x= 2, y=-10, z=-7>, vel=<x= 0, y= 0, z= 0>
// pos=<x= 4, y= -8, z= 8>, vel=<x= 0, y= 0, z= 0>
// pos=<x= 3, y= 5, z=-1>, vel=<x= 0, y= 0, z= 0>
CHECK(p[0].position == Vector3(-1, 0, 2));
CHECK(p[1].position == Vector3( 2, -10, -7));
CHECK(p[2].position == Vector3( 4, -8, 8));
CHECK(p[3].position == Vector3( 3, 5, -1));
CHECK(p[0].velocity == Vector3(0, 0, 0));
CHECK(p[1].velocity == Vector3(0, 0, 0));
CHECK(p[2].velocity == Vector3(0, 0, 0));
CHECK(p[3].velocity == Vector3(0, 0, 0));
// After 1 step:
// pos=<x= 2, y=-1, z= 1>, vel=<x= 3, y=-1, z=-1>
// pos=<x= 3, y=-7, z=-4>, vel=<x= 1, y= 3, z= 3>
// pos=<x= 1, y=-7, z= 5>, vel=<x=-3, y= 1, z=-3>
// pos=<x= 2, y= 2, z= 0>, vel=<x=-1, y=-3, z= 1>
p = simulate(p);
CHECK(p[0].position == Vector3( 2, -1, 1));
CHECK(p[1].position == Vector3( 3, -7, -4));
CHECK(p[2].position == Vector3( 1, -7, 5));
CHECK(p[3].position == Vector3( 2, 2, 0));
CHECK(p[0].velocity == Vector3( 3, -1, -1));
CHECK(p[1].velocity == Vector3( 1, 3, 3));
CHECK(p[2].velocity == Vector3(-3, 1, -3));
CHECK(p[3].velocity == Vector3(-1, -3, 1));
// After 2 steps:
// pos=<x= 5, y=-3, z=-1>, vel=<x= 3, y=-2, z=-2>
// pos=<x= 1, y=-2, z= 2>, vel=<x=-2, y= 5, z= 6>
// pos=<x= 1, y=-4, z=-1>, vel=<x= 0, y= 3, z=-6>
// pos=<x= 1, y=-4, z= 2>, vel=<x=-1, y=-6, z= 2>
p = simulate(p);
CHECK(p[0].position == Vector3( 5, -3, -1));
CHECK(p[1].position == Vector3( 1, -2, 2));
CHECK(p[2].position == Vector3( 1, -4, -1));
CHECK(p[3].position == Vector3( 1, -4, 2));
CHECK(p[0].velocity == Vector3( 3, -2, -2));
CHECK(p[1].velocity == Vector3(-2, 5, 6));
CHECK(p[2].velocity == Vector3( 0, 3, -6));
CHECK(p[3].velocity == Vector3(-1, -6, 2));
// After 3 steps:
// pos=<x= 5, y=-6, z=-1>, vel=<x= 0, y=-3, z= 0>
// pos=<x= 0, y= 0, z= 6>, vel=<x=-1, y= 2, z= 4>
// pos=<x= 2, y= 1, z=-5>, vel=<x= 1, y= 5, z=-4>
// pos=<x= 1, y=-8, z= 2>, vel=<x= 0, y=-4, z= 0>
p = simulate(p);
CHECK(p[0].position == Vector3( 5, -6, -1));
CHECK(p[1].position == Vector3( 0, 0, 6));
CHECK(p[2].position == Vector3( 2, 1, -5));
CHECK(p[3].position == Vector3( 1, -8, 2));
CHECK(p[0].velocity == Vector3( 0, -3, 0));
CHECK(p[1].velocity == Vector3(-1, 2, 4));
CHECK(p[2].velocity == Vector3( 1, 5, -4));
CHECK(p[3].velocity == Vector3( 0, -4, 0));
// After 4 steps:
// pos=<x= 2, y=-8, z= 0>, vel=<x=-3, y=-2, z= 1>
// pos=<x= 2, y= 1, z= 7>, vel=<x= 2, y= 1, z= 1>
// pos=<x= 2, y= 3, z=-6>, vel=<x= 0, y= 2, z=-1>
// pos=<x= 2, y=-9, z= 1>, vel=<x= 1, y=-1, z=-1>
p = simulate(p);
CHECK(p[0].position == Vector3( 2, -8, 0));
CHECK(p[1].position == Vector3( 2, 1, 7));
CHECK(p[2].position == Vector3( 2, 3, -6));
CHECK(p[3].position == Vector3( 2, -9, 1));
CHECK(p[0].velocity == Vector3(-3, -2, 1));
CHECK(p[1].velocity == Vector3( 2, 1, 1));
CHECK(p[2].velocity == Vector3( 0, 2, -1));
CHECK(p[3].velocity == Vector3( 1, -1, -1));
// After 5 steps:
// pos=<x=-1, y=-9, z= 2>, vel=<x=-3, y=-1, z= 2>
// pos=<x= 4, y= 1, z= 5>, vel=<x= 2, y= 0, z=-2>
// pos=<x= 2, y= 2, z=-4>, vel=<x= 0, y=-1, z= 2>
// pos=<x= 3, y=-7, z=-1>, vel=<x= 1, y= 2, z=-2>
p = simulate(p);
CHECK(p[0].position == Vector3(-1, -9, 2));
CHECK(p[1].position == Vector3( 4, 1, 5));
CHECK(p[2].position == Vector3( 2, 2, -4));
CHECK(p[3].position == Vector3( 3, -7, -1));
CHECK(p[0].velocity == Vector3(-3, -1, 2));
CHECK(p[1].velocity == Vector3( 2, 0, -2));
CHECK(p[2].velocity == Vector3( 0, -1, 2));
CHECK(p[3].velocity == Vector3( 1, 2, -2));
// After 6 steps:
// pos=<x=-1, y=-7, z= 3>, vel=<x= 0, y= 2, z= 1>
// pos=<x= 3, y= 0, z= 0>, vel=<x=-1, y=-1, z=-5>
// pos=<x= 3, y=-2, z= 1>, vel=<x= 1, y=-4, z= 5>
// pos=<x= 3, y=-4, z=-2>, vel=<x= 0, y= 3, z=-1>
p = simulate(p);
CHECK(p[0].position == Vector3(-1, -7, 3));
CHECK(p[1].position == Vector3( 3, 0, 0));
CHECK(p[2].position == Vector3( 3, -2, 1));
CHECK(p[3].position == Vector3( 3, -4, -2));
CHECK(p[0].velocity == Vector3( 0, 2, 1));
CHECK(p[1].velocity == Vector3(-1, -1, -5));
CHECK(p[2].velocity == Vector3( 1, -4, 5));
CHECK(p[3].velocity == Vector3( 0, 3, -1));
// After 7 steps:
// pos=<x= 2, y=-2, z= 1>, vel=<x= 3, y= 5, z=-2>
// pos=<x= 1, y=-4, z=-4>, vel=<x=-2, y=-4, z=-4>
// pos=<x= 3, y=-7, z= 5>, vel=<x= 0, y=-5, z= 4>
// pos=<x= 2, y= 0, z= 0>, vel=<x=-1, y= 4, z= 2>
//
p = simulate(p);
CHECK(p[0].position == Vector3(2, -2, 1));
CHECK(p[1].position == Vector3(1, -4, -4));
CHECK(p[2].position == Vector3(3, -7, 5));
CHECK(p[3].position == Vector3(2, 0, 0));
CHECK(p[0].velocity == Vector3( 3, 5, -2));
CHECK(p[1].velocity == Vector3(-2, -4, -4));
CHECK(p[2].velocity == Vector3( 0, -5, 4));
CHECK(p[3].velocity == Vector3(-1, 4, 2));
// After 8 steps:
// pos=<x= 5, y= 2, z=-2>, vel=<x= 3, y= 4, z=-3>
// pos=<x= 2, y=-7, z=-5>, vel=<x= 1, y=-3, z=-1>
// pos=<x= 0, y=-9, z= 6>, vel=<x=-3, y=-2, z= 1>
// pos=<x= 1, y= 1, z= 3>, vel=<x=-1, y= 1, z= 3>
p = simulate(p);
CHECK(p[0].position == Vector3( 5, 2, -2));
CHECK(p[1].position == Vector3( 2, -7, -5));
CHECK(p[2].position == Vector3( 0, -9, 6));
CHECK(p[3].position == Vector3( 1, 1, 3));
CHECK(p[0].velocity == Vector3( 3, 4, -3));
CHECK(p[1].velocity == Vector3( 1, -3, -1));
CHECK(p[2].velocity == Vector3(-3, -2, 1));
CHECK(p[3].velocity == Vector3(-1, 1, 3));
// After 9 steps:
// pos=<x= 5, y= 3, z=-4>, vel=<x= 0, y= 1, z=-2>
// pos=<x= 2, y=-9, z=-3>, vel=<x= 0, y=-2, z= 2>
// pos=<x= 0, y=-8, z= 4>, vel=<x= 0, y= 1, z=-2>
// pos=<x= 1, y= 1, z= 5>, vel=<x= 0, y= 0, z= 2>
p = simulate(p);
CHECK(p[0].position == Vector3( 5, 3, -4));
CHECK(p[1].position == Vector3( 2, -9, -3));
CHECK(p[2].position == Vector3( 0, -8, 4));
CHECK(p[3].position == Vector3( 1, 1, 5));
CHECK(p[0].velocity == Vector3( 0, 1, -2));
CHECK(p[1].velocity == Vector3( 0, -2, 2));
CHECK(p[2].velocity == Vector3( 0, 1, -2));
CHECK(p[3].velocity == Vector3( 0, 0, 2));
// After 10 steps:
// pos=<x= 2, y= 1, z=-3>, vel=<x=-3, y=-2, z= 1>
// pos=<x= 1, y=-8, z= 0>, vel=<x=-1, y= 1, z= 3>
// pos=<x= 3, y=-6, z= 1>, vel=<x= 3, y= 2, z=-3>
// pos=<x= 2, y= 0, z= 4>, vel=<x= 1, y=-1, z=-1>
p = simulate(p);
CHECK(p[0].position == Vector3( 2, 1, -3));
CHECK(p[1].position == Vector3( 1, -8, 0));
CHECK(p[2].position == Vector3( 3, -6, 1));
CHECK(p[3].position == Vector3( 2, 0, 4));
CHECK(p[0].velocity == Vector3(-3, -2, 1));
CHECK(p[1].velocity == Vector3(-1, 1, 3));
CHECK(p[2].velocity == Vector3( 3, 2, -3));
CHECK(p[3].velocity == Vector3( 1, -1, -1));
CHECK(totalEnergy(p) == 179);
}
char const sample_input2[] = "<x=-8, y=-10, z=0>\n"
"<x=5, y=5, z=10>\n"
"<x=2, y=-7, z=3>\n"
"<x=9, y=-8, z=-3>\n";
SECTION("Simulation #2")
{
PlanetarySystem p = parseInput(sample_input2);
// After 0 steps:
// pos=<x= -8, y=-10, z= 0>, vel=<x= 0, y= 0, z= 0>
// pos=<x= 5, y= 5, z= 10>, vel=<x= 0, y= 0, z= 0>
// pos=<x= 2, y= -7, z= 3>, vel=<x= 0, y= 0, z= 0>
// pos=<x= 9, y= -8, z= -3>, vel=<x= 0, y= 0, z= 0>
CHECK(p[0].position == Vector3( -8, -10, 0));
CHECK(p[1].position == Vector3( 5, 5, 10));
CHECK(p[2].position == Vector3( 2, -7, 3));
CHECK(p[3].position == Vector3( 9, -8, -3));
CHECK(p[0].velocity == Vector3( 0, 0, 0));
CHECK(p[1].velocity == Vector3( 0, 0, 0));
CHECK(p[2].velocity == Vector3( 0, 0, 0));
CHECK(p[3].velocity == Vector3( 0, 0, 0));
// After 10 steps:
// pos=<x= -9, y=-10, z= 1>, vel=<x= -2, y= -2, z= -1>
// pos=<x= 4, y= 10, z= 9>, vel=<x= -3, y= 7, z= -2>
// pos=<x= 8, y=-10, z= -3>, vel=<x= 5, y= -1, z= -2>
// pos=<x= 5, y=-10, z= 3>, vel=<x= 0, y= -4, z= 5>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3( -9, -10, 1));
CHECK(p[1].position == Vector3( 4, 10, 9));
CHECK(p[2].position == Vector3( 8, -10, -3));
CHECK(p[3].position == Vector3( 5, -10, 3));
CHECK(p[0].velocity == Vector3( -2, -2, -1));
CHECK(p[1].velocity == Vector3( -3, 7, -2));
CHECK(p[2].velocity == Vector3( 5, -1, -2));
CHECK(p[3].velocity == Vector3( 0, -4, 5));
// After 20 steps:
// pos=<x=-10, y= 3, z= -4>, vel=<x= -5, y= 2, z= 0>
// pos=<x= 5, y=-25, z= 6>, vel=<x= 1, y= 1, z= -4>
// pos=<x= 13, y= 1, z= 1>, vel=<x= 5, y= -2, z= 2>
// pos=<x= 0, y= 1, z= 7>, vel=<x= -1, y= -1, z= 2>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3(-10, 3, -4));
CHECK(p[1].position == Vector3( 5, -25, 6));
CHECK(p[2].position == Vector3( 13, 1, 1));
CHECK(p[3].position == Vector3( 0, 1, 7));
CHECK(p[0].velocity == Vector3( -5, 2, 0));
CHECK(p[1].velocity == Vector3( 1, 1, -4));
CHECK(p[2].velocity == Vector3( 5, -2, 2));
CHECK(p[3].velocity == Vector3( -1, -1, 2));
// After 30 steps:
// pos=<x= 15, y= -6, z= -9>, vel=<x= -5, y= 4, z= 0>
// pos=<x= -4, y=-11, z= 3>, vel=<x= -3, y=-10, z= 0>
// pos=<x= 0, y= -1, z= 11>, vel=<x= 7, y= 4, z= 3>
// pos=<x= -3, y= -2, z= 5>, vel=<x= 1, y= 2, z= -3>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3( 15, -6, -9));
CHECK(p[1].position == Vector3( -4, -11, 3));
CHECK(p[2].position == Vector3( 0, -1, 11));
CHECK(p[3].position == Vector3( -3, -2, 5));
CHECK(p[0].velocity == Vector3( -5, 4, 0));
CHECK(p[1].velocity == Vector3( -3, -10, 0));
CHECK(p[2].velocity == Vector3( 7, 4, 3));
CHECK(p[3].velocity == Vector3( 1, 2, -3));
// After 40 steps:
// pos=<x= 14, y=-12, z= -4>, vel=<x= 11, y= 3, z= 0>
// pos=<x= -1, y= 18, z= 8>, vel=<x= -5, y= 2, z= 3>
// pos=<x= -5, y=-14, z= 8>, vel=<x= 1, y= -2, z= 0>
// pos=<x= 0, y=-12, z= -2>, vel=<x= -7, y= -3, z= -3>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3( 14, -12, -4));
CHECK(p[1].position == Vector3( -1, 18, 8));
CHECK(p[2].position == Vector3( -5, -14, 8));
CHECK(p[3].position == Vector3( 0, -12, -2));
CHECK(p[0].velocity == Vector3( 11, 3, 0));
CHECK(p[1].velocity == Vector3( -5, 2, 3));
CHECK(p[2].velocity == Vector3( 1, -2, 0));
CHECK(p[3].velocity == Vector3( -7, -3, -3));
// After 50 steps:
// pos=<x=-23, y= 4, z= 1>, vel=<x= -7, y= -1, z= 2>
// pos=<x= 20, y=-31, z= 13>, vel=<x= 5, y= 3, z= 4>
// pos=<x= -4, y= 6, z= 1>, vel=<x= -1, y= 1, z= -3>
// pos=<x= 15, y= 1, z= -5>, vel=<x= 3, y= -3, z= -3>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3(-23, 4, 1));
CHECK(p[1].position == Vector3( 20, -31, 13));
CHECK(p[2].position == Vector3( -4, 6, 1));
CHECK(p[3].position == Vector3( 15, 1, -5));
CHECK(p[0].velocity == Vector3( -7, -1, 2));
CHECK(p[1].velocity == Vector3( 5, 3, 4));
CHECK(p[2].velocity == Vector3( -1, 1, -3));
CHECK(p[3].velocity == Vector3( 3, -3, -3));
// After 60 steps:
// pos=<x= 36, y=-10, z= 6>, vel=<x= 5, y= 0, z= 3>
// pos=<x=-18, y= 10, z= 9>, vel=<x= -3, y= -7, z= 5>
// pos=<x= 8, y=-12, z= -3>, vel=<x= -2, y= 1, z= -7>
// pos=<x=-18, y= -8, z= -2>, vel=<x= 0, y= 6, z= -1>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3( 36, -10, 6));
CHECK(p[1].position == Vector3(-18, 10, 9));
CHECK(p[2].position == Vector3( 8, -12, -3));
CHECK(p[3].position == Vector3(-18, -8, -2));
CHECK(p[0].velocity == Vector3( 5, 0, 3));
CHECK(p[1].velocity == Vector3( -3, -7, 5));
CHECK(p[2].velocity == Vector3( -2, 1, -7));
CHECK(p[3].velocity == Vector3( 0, 6, -1));
// After 70 steps:
// pos=<x=-33, y= -6, z= 5>, vel=<x= -5, y= -4, z= 7>
// pos=<x= 13, y= -9, z= 2>, vel=<x= -2, y= 11, z= 3>
// pos=<x= 11, y= -8, z= 2>, vel=<x= 8, y= -6, z= -7>
// pos=<x= 17, y= 3, z= 1>, vel=<x= -1, y= -1, z= -3>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3(-33, -6, 5));
CHECK(p[1].position == Vector3( 13, -9, 2));
CHECK(p[2].position == Vector3( 11, -8, 2));
CHECK(p[3].position == Vector3( 17, 3, 1));
CHECK(p[0].velocity == Vector3( -5, -4, 7));
CHECK(p[1].velocity == Vector3( -2, 11, 3));
CHECK(p[2].velocity == Vector3( 8, -6, -7));
CHECK(p[3].velocity == Vector3( -1, -1, -3));
// After 80 steps:
// pos=<x= 30, y= -8, z= 3>, vel=<x= 3, y= 3, z= 0>
// pos=<x= -2, y= -4, z= 0>, vel=<x= 4, y=-13, z= 2>
// pos=<x=-18, y= -7, z= 15>, vel=<x= -8, y= 2, z= -2>
// pos=<x= -2, y= -1, z= -8>, vel=<x= 1, y= 8, z= 0>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3( 30, -8, 3));
CHECK(p[1].position == Vector3( -2, -4, 0));
CHECK(p[2].position == Vector3(-18, -7, 15));
CHECK(p[3].position == Vector3( -2, -1, -8));
CHECK(p[0].velocity == Vector3( 3, 3, 0));
CHECK(p[1].velocity == Vector3( 4, -13, 2));
CHECK(p[2].velocity == Vector3( -8, 2, -2));
CHECK(p[3].velocity == Vector3( 1, 8, 0));
// After 90 steps:
// pos=<x=-25, y= -1, z= 4>, vel=<x= 1, y= -3, z= 4>
// pos=<x= 2, y= -9, z= 0>, vel=<x= -3, y= 13, z= -1>
// pos=<x= 32, y= -8, z= 14>, vel=<x= 5, y= -4, z= 6>
// pos=<x= -1, y= -2, z= -8>, vel=<x= -3, y= -6, z= -9>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3(-25, -1, 4));
CHECK(p[1].position == Vector3( 2, -9, 0));
CHECK(p[2].position == Vector3( 32, -8, 14));
CHECK(p[3].position == Vector3( -1, -2, -8));
CHECK(p[0].velocity == Vector3( 1, -3, 4));
CHECK(p[1].velocity == Vector3( -3, 13, -1));
CHECK(p[2].velocity == Vector3( 5, -4, 6));
CHECK(p[3].velocity == Vector3( -3, -6, -9));
// After 100 steps:
// pos=<x= 8, y=-12, z= -9>, vel=<x= -7, y= 3, z= 0>
// pos=<x= 13, y= 16, z= -3>, vel=<x= 3, y=-11, z= -5>
// pos=<x=-29, y=-11, z= -1>, vel=<x= -3, y= 7, z= 4>
// pos=<x= 16, y=-13, z= 23>, vel=<x= 7, y= 1, z= 1>
for (int i = 0; i < 10; ++i) { p = simulate(p); }
CHECK(p[0].position == Vector3( 8, -12, -9));
CHECK(p[1].position == Vector3( 13, 16, -3));
CHECK(p[2].position == Vector3(-29, -11, -1));
CHECK(p[3].position == Vector3( 16, -13, 23));
CHECK(p[0].velocity == Vector3( -7, 3, 0));
CHECK(p[1].velocity == Vector3( 3, -11, -5));
CHECK(p[2].velocity == Vector3( -3, 7, 4));
CHECK(p[3].velocity == Vector3( 7, 1, 1));
// Energy after 100 steps:
// pot: 8 + 12 + 9 = 29; kin: 7 + 3 + 0 = 10; total: 29 * 10 = 290
// pot: 13 + 16 + 3 = 32; kin: 3 + 11 + 5 = 19; total: 32 * 19 = 608
// pot: 29 + 11 + 1 = 41; kin: 3 + 7 + 4 = 14; total: 41 * 14 = 574
// pot: 16 + 13 + 23 = 52; kin: 7 + 1 + 1 = 9; total: 52 * 9 = 468
// Sum of total energy: 290 + 608 + 574 + 468 = 1940
CHECK(totalEnergy(p) == 1940);
}
SECTION("Brute Force Simulation")
{
PlanetarySystem p = parseInput(sample_input);
CHECK(findRepeatingState_brute_force(p) == 2772);
}
SECTION("Clever Simulation")
{
PlanetarySystem p = parseInput(sample_input);
CHECK(findRepeatingState_clever(p) == 2772);
}
SECTION("Clever Simulation #2")
{
PlanetarySystem p = parseInput(sample_input2);
CHECK(findRepeatingState_clever(p) == 4686774924);
}
}
| 42.813592
| 81
| 0.42655
|
ComicSansMS
|
ca9eb80224812236843df2cf2cf9f84ba3b99322
| 10,588
|
cc
|
C++
|
modules/planning/planning_base.cc
|
Ngugisenior/apollo
|
b752a7fa8d63e398cd8ab70ba12f879c11e1039d
|
[
"Apache-2.0"
] | null | null | null |
modules/planning/planning_base.cc
|
Ngugisenior/apollo
|
b752a7fa8d63e398cd8ab70ba12f879c11e1039d
|
[
"Apache-2.0"
] | null | null | null |
modules/planning/planning_base.cc
|
Ngugisenior/apollo
|
b752a7fa8d63e398cd8ab70ba12f879c11e1039d
|
[
"Apache-2.0"
] | null | null | null |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/planning_base.h"
#include <algorithm>
#include <list>
#include <vector>
#include "google/protobuf/repeated_field.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/planning_util.h"
#include "modules/planning/common/trajectory/trajectory_stitcher.h"
#include "modules/planning/planner/em/em_planner.h"
#include "modules/planning/planner/lattice/lattice_planner.h"
#include "modules/planning/planner/navi/navi_planner.h"
#include "modules/planning/planner/rtk/rtk_replay_planner.h"
#include "modules/planning/reference_line/reference_line_provider.h"
#include "modules/planning/tasks/traffic_decider/traffic_decider.h"
namespace apollo {
namespace planning {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleState;
using apollo::common::VehicleStateProvider;
using apollo::common::adapter::AdapterManager;
using apollo::common::time::Clock;
using apollo::hdmap::HDMapUtil;
PlanningBase::~PlanningBase() {}
#define CHECK_ADAPTER(NAME) \
if (AdapterManager::Get##NAME() == nullptr) { \
AERROR << #NAME << " is not registered"; \
return Status(ErrorCode::PLANNING_ERROR, #NAME " is not registered"); \
}
#define CHECK_ADAPTER_IF(CONDITION, NAME) \
if (CONDITION) CHECK_ADAPTER(NAME)
void PlanningBase::RegisterPlanners() {
planner_factory_.Register(
PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); });
planner_factory_.Register(PlanningConfig::EM,
[]() -> Planner* { return new EMPlanner(); });
planner_factory_.Register(PlanningConfig::LATTICE,
[]() -> Planner* { return new LatticePlanner(); });
planner_factory_.Register(PlanningConfig::NAVI,
[]() -> Planner* { return new NaviPlanner(); });
}
Status PlanningBase::InitFrame(const uint32_t sequence_num,
const TrajectoryPoint& planning_start_point,
const double start_time,
const VehicleState& vehicle_state) {
frame_.reset(new Frame(sequence_num, planning_start_point, start_time,
vehicle_state, reference_line_provider_.get()));
auto status = frame_->Init();
if (!status.ok()) {
AERROR << "failed to init frame:" << status.ToString();
return status;
}
return Status::OK();
}
void PlanningBase::CheckPlanningConfig() {
if (config_.has_em_planner_config() &&
config_.em_planner_config().has_dp_st_speed_config()) {
const auto& dp_st_speed_config =
config_.em_planner_config().dp_st_speed_config();
CHECK(dp_st_speed_config.has_matrix_dimension_s());
CHECK_GT(dp_st_speed_config.matrix_dimension_s(), 3);
CHECK_LT(dp_st_speed_config.matrix_dimension_s(), 10000);
CHECK(dp_st_speed_config.has_matrix_dimension_t());
CHECK_GT(dp_st_speed_config.matrix_dimension_t(), 3);
CHECK_LT(dp_st_speed_config.matrix_dimension_t(), 10000);
}
// TODO(All): check other config params
}
bool PlanningBase::IsVehicleStateValid(const VehicleState& vehicle_state) {
if (std::isnan(vehicle_state.x()) || std::isnan(vehicle_state.y()) ||
std::isnan(vehicle_state.z()) || std::isnan(vehicle_state.heading()) ||
std::isnan(vehicle_state.kappa()) ||
std::isnan(vehicle_state.linear_velocity()) ||
std::isnan(vehicle_state.linear_acceleration())) {
return false;
}
return true;
}
void PlanningBase::PublishPlanningPb(ADCTrajectory* trajectory_pb,
double timestamp) {
trajectory_pb->mutable_header()->set_timestamp_sec(timestamp);
// TODO(all): integrate reverse gear
trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE);
if (AdapterManager::GetRoutingResponse() &&
!AdapterManager::GetRoutingResponse()->Empty()) {
trajectory_pb->mutable_routing_header()->CopyFrom(
AdapterManager::GetRoutingResponse()->GetLatestObserved().header());
}
if (FLAGS_use_planning_fallback &&
trajectory_pb->trajectory_point_size() == 0) {
SetFallbackTrajectory(trajectory_pb);
}
// NOTICE:
// Since we are using the time at each cycle beginning as timestamp, the
// relative time of each trajectory point should be modified so that we can
// use the current timestamp in header.
// auto* trajectory_points = trajectory_pb.mutable_trajectory_point();
if (!FLAGS_planning_test_mode) {
const double dt = timestamp - Clock::NowInSeconds();
for (auto& p : *trajectory_pb->mutable_trajectory_point()) {
p.set_relative_time(p.relative_time() + dt);
}
}
Publish(trajectory_pb);
}
void PlanningBase::SetFallbackTrajectory(ADCTrajectory* trajectory_pb) {
CHECK_NOTNULL(trajectory_pb);
// use planning trajecotry from last cycle
auto* last_planning = AdapterManager::GetPlanning();
if (last_planning != nullptr && !last_planning->Empty()) {
const auto& traj = last_planning->GetLatestObserved();
const double current_time_stamp = trajectory_pb->header().timestamp_sec();
const double pre_time_stamp = traj.header().timestamp_sec();
for (int i = 0; i < traj.trajectory_point_size(); ++i) {
const double t = traj.trajectory_point(i).relative_time() +
pre_time_stamp - current_time_stamp;
auto* p = trajectory_pb->add_trajectory_point();
p->CopyFrom(traj.trajectory_point(i));
p->set_relative_time(t);
}
}
}
void PlanningBase::ExportReferenceLineDebug(planning_internal::Debug* debug) {
if (!FLAGS_enable_record_debug) {
return;
}
for (auto& reference_line_info : frame_->reference_line_info()) {
auto rl_debug = debug->mutable_planning_data()->add_reference_line();
rl_debug->set_id(reference_line_info.Lanes().Id());
rl_debug->set_length(reference_line_info.reference_line().Length());
rl_debug->set_cost(reference_line_info.Cost());
rl_debug->set_is_change_lane_path(reference_line_info.IsChangeLanePath());
rl_debug->set_is_drivable(reference_line_info.IsDrivable());
rl_debug->set_is_protected(reference_line_info.GetRightOfWayStatus() ==
ADCTrajectory::PROTECTED);
}
}
Status PlanningBase::Plan(
const double current_time_stamp,
const std::vector<TrajectoryPoint>& stitching_trajectory,
ADCTrajectory* trajectory_pb) {
auto* ptr_debug = trajectory_pb->mutable_debug();
if (FLAGS_enable_record_debug) {
ptr_debug->mutable_planning_data()->mutable_init_point()->CopyFrom(
stitching_trajectory.back());
}
auto status = planner_->Plan(stitching_trajectory.back(), frame_.get());
ExportReferenceLineDebug(ptr_debug);
const auto* best_ref_info = frame_->FindDriveReferenceLineInfo();
if (!best_ref_info) {
std::string msg("planner failed to make a driving plan");
AERROR << msg;
if (last_publishable_trajectory_) {
last_publishable_trajectory_->Clear();
}
return Status(ErrorCode::PLANNING_ERROR, msg);
}
ptr_debug->MergeFrom(best_ref_info->debug());
trajectory_pb->mutable_latency_stats()->MergeFrom(
best_ref_info->latency_stats());
// set right of way status
trajectory_pb->set_right_of_way_status(best_ref_info->GetRightOfWayStatus());
for (const auto& id : best_ref_info->TargetLaneId()) {
trajectory_pb->add_lane_id()->CopyFrom(id);
}
best_ref_info->ExportDecision(trajectory_pb->mutable_decision());
// Add debug information.
if (FLAGS_enable_record_debug) {
auto* reference_line = ptr_debug->mutable_planning_data()->add_path();
reference_line->set_name("planning_reference_line");
const auto& reference_points =
best_ref_info->reference_line().reference_points();
double s = 0.0;
double prev_x = 0.0;
double prev_y = 0.0;
bool empty_path = true;
for (const auto& reference_point : reference_points) {
auto* path_point = reference_line->add_path_point();
path_point->set_x(reference_point.x());
path_point->set_y(reference_point.y());
path_point->set_theta(reference_point.heading());
path_point->set_kappa(reference_point.kappa());
path_point->set_dkappa(reference_point.dkappa());
if (empty_path) {
path_point->set_s(0.0);
empty_path = false;
} else {
double dx = reference_point.x() - prev_x;
double dy = reference_point.y() - prev_y;
s += std::hypot(dx, dy);
path_point->set_s(s);
}
prev_x = reference_point.x();
prev_y = reference_point.y();
}
}
last_publishable_trajectory_.reset(new PublishableTrajectory(
current_time_stamp, best_ref_info->trajectory()));
ADEBUG << "current_time_stamp: " << std::to_string(current_time_stamp);
last_publishable_trajectory_->PrependTrajectoryPoints(
stitching_trajectory.begin(), stitching_trajectory.end() - 1);
for (size_t i = 0; i < last_publishable_trajectory_->NumOfPoints(); ++i) {
if (last_publishable_trajectory_->TrajectoryPointAt(i).relative_time() >
FLAGS_trajectory_time_high_density_period) {
break;
}
ADEBUG << last_publishable_trajectory_->TrajectoryPointAt(i)
.ShortDebugString();
}
last_publishable_trajectory_->PopulateTrajectoryProtobuf(trajectory_pb);
best_ref_info->ExportEngageAdvice(trajectory_pb->mutable_engage_advice());
return status;
}
} // namespace planning
} // namespace apollo
| 38.926471
| 80
| 0.694277
|
Ngugisenior
|
ca9fbff61a38c4235ec462243c039a6f5a9d092a
| 1,224
|
cpp
|
C++
|
src/hssh/global_topological/global_place.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 3
|
2020-03-05T23:56:14.000Z
|
2021-02-17T19:06:50.000Z
|
src/hssh/global_topological/global_place.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 1
|
2021-03-07T01:23:47.000Z
|
2021-03-07T01:23:47.000Z
|
src/hssh/global_topological/global_place.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 1
|
2021-03-03T07:54:16.000Z
|
2021-03-03T07:54:16.000Z
|
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file global_place.cpp
* \author Collin Johnson
*
* Definition of GlobalPlace.
*/
#include "hssh/global_topological/global_place.h"
#include <algorithm>
namespace vulcan
{
namespace hssh
{
GlobalPlace::GlobalPlace(Id id, AreaType type, Id metricId, const GlobalTransitionCycle& cycle)
: id_(id)
, type_(type)
, cycle_(cycle)
{
metricPlaceIds_.push_back(metricId);
}
bool GlobalPlace::replaceTransition(const GlobalTransition& oldTrans, const GlobalTransition& newTrans)
{
return cycle_.replaceTransition(oldTrans, newTrans);
}
bool GlobalPlace::changeMetricId(Id oldId, Id newId)
{
auto idIt = std::find(metricPlaceIds_.begin(), metricPlaceIds_.end(), oldId);
if (idIt != metricPlaceIds_.end()) {
*idIt = newId;
}
return idIt != metricPlaceIds_.end();
}
} // namespace hssh
} // namespace vulcan
| 23.09434
| 103
| 0.72549
|
anuranbaka
|
caa0a1713e1b14054ef2f12045dde429df23fb45
| 8,647
|
cc
|
C++
|
example/http_c++/http_server.cc
|
flare-rpc/flare-cpp
|
c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950
|
[
"Apache-2.0"
] | 3
|
2022-01-23T17:55:24.000Z
|
2022-03-23T12:55:18.000Z
|
example/http_c++/http_server.cc
|
flare-rpc/flare-cpp
|
c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950
|
[
"Apache-2.0"
] | null | null | null |
example/http_c++/http_server.cc
|
flare-rpc/flare-cpp
|
c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950
|
[
"Apache-2.0"
] | null | null | null |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// A server to receive HttpRequest and send back HttpResponse.
#include <gflags/gflags.h>
#include "flare/log/logging.h"
#include "flare/bootstrap/bootstrap.h"
#include <flare/rpc/server.h>
#include <flare/rpc/restful.h>
#include "http.pb.h"
DEFINE_int32(port, 8010, "TCP Port of this server");
DEFINE_int32(idle_timeout_s, -1, "Connection will be closed if there is no "
"read/write operations during the last `idle_timeout_s'");
DEFINE_int32(logoff_ms, 2000, "Maximum duration of server's LOGOFF state "
"(waiting for client to close connection before server stops)");
DEFINE_string(certificate, "cert.pem", "Certificate file path to enable SSL");
DEFINE_string(private_key, "key.pem", "Private key file path to enable SSL");
DEFINE_string(ciphers, "", "Cipher suite used for SSL connections");
namespace example {
// Service with static path.
class HttpServiceImpl : public HttpService {
public:
HttpServiceImpl() {};
virtual ~HttpServiceImpl() {};
void Echo(google::protobuf::RpcController *cntl_base,
const HttpRequest *,
HttpResponse *,
google::protobuf::Closure *done) {
// This object helps you to call done->Run() in RAII style. If you need
// to process the request asynchronously, pass done_guard.release().
flare::rpc::ClosureGuard done_guard(done);
flare::rpc::Controller *cntl =
static_cast<flare::rpc::Controller *>(cntl_base);
// Fill response.
cntl->http_response().set_content_type("text/plain");
flare::cord_buf_builder os;
os << "queries:";
for (flare::rpc::URI::QueryIterator it = cntl->http_request().uri().QueryBegin();
it != cntl->http_request().uri().QueryEnd(); ++it) {
os << ' ' << it->first << '=' << it->second;
}
os << "\nbody: " << cntl->request_attachment() << '\n';
os.move_to(cntl->response_attachment());
}
};
// Service with dynamic path.
class FileServiceImpl : public FileService {
public:
FileServiceImpl() {};
virtual ~FileServiceImpl() {};
struct Args {
flare::container::intrusive_ptr<flare::rpc::ProgressiveAttachment> pa;
};
static void *SendLargeFile(void *raw_args) {
std::unique_ptr<Args> args(static_cast<Args *>(raw_args));
if (args->pa == NULL) {
LOG(ERROR) << "ProgressiveAttachment is NULL";
return NULL;
}
for (int i = 0; i < 100; ++i) {
char buf[16];
int len = snprintf(buf, sizeof(buf), "part_%d ", i);
args->pa->Write(buf, len);
// sleep a while to send another part.
flare::fiber_sleep_for(10000);
}
return NULL;
}
void default_method(google::protobuf::RpcController *cntl_base,
const HttpRequest *,
HttpResponse *,
google::protobuf::Closure *done) {
flare::rpc::ClosureGuard done_guard(done);
flare::rpc::Controller *cntl =
static_cast<flare::rpc::Controller *>(cntl_base);
const std::string &filename = cntl->http_request().unresolved_path();
if (filename == "largefile") {
// Send the "largefile" with ProgressiveAttachment.
std::unique_ptr<Args> args(new Args);
args->pa = cntl->CreateProgressiveAttachment();
fiber_id_t th;
fiber_start_background(&th, NULL, SendLargeFile, args.release());
} else {
cntl->response_attachment().append("Getting file: ");
cntl->response_attachment().append(filename);
}
}
};
// Restful service. (The service implementation is exactly same with regular
// services, the difference is that you need to pass a `restful_mappings'
// when adding the service into server).
class QueueServiceImpl : public example::QueueService {
public:
QueueServiceImpl() {};
virtual ~QueueServiceImpl() {};
void start(google::protobuf::RpcController *cntl_base,
const HttpRequest *,
HttpResponse *,
google::protobuf::Closure *done) {
flare::rpc::ClosureGuard done_guard(done);
flare::rpc::Controller *cntl =
static_cast<flare::rpc::Controller *>(cntl_base);
cntl->response_attachment().append("queue started");
}
void stop(google::protobuf::RpcController *cntl_base,
const HttpRequest *,
HttpResponse *,
google::protobuf::Closure *done) {
flare::rpc::ClosureGuard done_guard(done);
flare::rpc::Controller *cntl =
static_cast<flare::rpc::Controller *>(cntl_base);
cntl->response_attachment().append("queue stopped");
}
void getstats(google::protobuf::RpcController *cntl_base,
const HttpRequest *,
HttpResponse *,
google::protobuf::Closure *done) {
flare::rpc::ClosureGuard done_guard(done);
flare::rpc::Controller *cntl =
static_cast<flare::rpc::Controller *>(cntl_base);
const std::string &unresolved_path = cntl->http_request().unresolved_path();
if (unresolved_path.empty()) {
cntl->response_attachment().append("Require a name after /stats");
} else {
cntl->response_attachment().append("Get stats: ");
cntl->response_attachment().append(unresolved_path);
}
}
};
} // namespace example
int main(int argc, char *argv[]) {
flare::bootstrap_init(argc, argv);
flare::run_bootstrap();
// Generally you only need one Server.
flare::rpc::Server server;
example::HttpServiceImpl http_svc;
example::FileServiceImpl file_svc;
example::QueueServiceImpl queue_svc;
// Add services into server. Notice the second parameter, because the
// service is put on stack, we don't want server to delete it, otherwise
// use flare::rpc::SERVER_OWNS_SERVICE.
if (server.AddService(&http_svc,
flare::rpc::SERVER_DOESNT_OWN_SERVICE) != 0) {
LOG(ERROR) << "Fail to add http_svc";
return -1;
}
if (server.AddService(&file_svc,
flare::rpc::SERVER_DOESNT_OWN_SERVICE) != 0) {
LOG(ERROR) << "Fail to add file_svc";
return -1;
}
if (server.AddService(&queue_svc,
flare::rpc::SERVER_DOESNT_OWN_SERVICE,
"/v1/queue/start => start,"
"/v1/queue/stop => stop,"
"/v1/queue/stats/* => getstats") != 0) {
LOG(ERROR) << "Fail to add queue_svc";
return -1;
}
// Start the server.
flare::rpc::ServerOptions options;
options.idle_timeout_sec = FLAGS_idle_timeout_s;
options.mutable_ssl_options()->default_cert.certificate = FLAGS_certificate;
options.mutable_ssl_options()->default_cert.private_key = FLAGS_private_key;
options.mutable_ssl_options()->ciphers = FLAGS_ciphers;
if (server.Start(FLAGS_port, &options) != 0) {
LOG(ERROR) << "Fail to start HttpServer";
return -1;
}
// Wait until Ctrl-C is pressed, then Stop() and Join() the server.
server.RunUntilAskedToQuit();
flare::run_finalizers();
return 0;
}
| 40.218605
| 94
| 0.588412
|
flare-rpc
|
caa511c164e2846dfa02c78c7cdaa3d3c69cd6a1
| 1,648
|
hpp
|
C++
|
Sources/inc/Boss.hpp
|
Tifox/Grog-Knight
|
377a661286cda7ee3b2b2d0099641897938c2f8f
|
[
"Apache-2.0"
] | null | null | null |
Sources/inc/Boss.hpp
|
Tifox/Grog-Knight
|
377a661286cda7ee3b2b2d0099641897938c2f8f
|
[
"Apache-2.0"
] | null | null | null |
Sources/inc/Boss.hpp
|
Tifox/Grog-Knight
|
377a661286cda7ee3b2b2d0099641897938c2f8f
|
[
"Apache-2.0"
] | null | null | null |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* File: Boss.hpp
* Creation: 2015-09-29 18:09
* Louis Solofrizzo <louis@ne02ptzero.me>
*/
#ifndef __BOSS__
# define __BOSS__
class Characters;
class HUDWindow;
# include "Characters.hpp"
# include "Projectile.hpp"
# define ORIENT 0.1f
class Boss : public Characters {
public:
Boss(std::string name, int x, int y);
~Boss(void);
virtual void ReceiveMessage(Message *m);
virtual void AnimCallback(String s);
virtual void BeginContact(Elements *elem, b2Contact *contact);
virtual void EndContact(Elements *elem, b2Contact *contact);
void lifeBar(void);
void createProjectile(Vector2 force, Vector2 init);
private:
HUDWindow *_h;
std::list<HUDActor *> _lifeList;
int _lastHitID;
int _inactive;
float _x;
float _y;
int _stade;
};
# include "HUDWindow.hpp"
#endif
| 27.932203
| 64
| 0.716626
|
Tifox
|
caa7720cf58d7a104c82067b4594b30a42332992
| 3,750
|
cpp
|
C++
|
src/Window/Mouse.cpp
|
razerx100/Gaia
|
4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b
|
[
"MIT"
] | null | null | null |
src/Window/Mouse.cpp
|
razerx100/Gaia
|
4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b
|
[
"MIT"
] | null | null | null |
src/Window/Mouse.cpp
|
razerx100/Gaia
|
4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b
|
[
"MIT"
] | null | null | null |
#include <Mouse.hpp>
Mouse::Mouse()
: m_x(0),
m_y(0),
m_inWindow(false),
m_leftPressed(false),
m_middlePressed(false),
m_rightPressed(false),
m_wheelDeltaCarry(0),
m_rawEnabled(false) {}
std::pair<int, int> Mouse::GetPos() const noexcept {
return { m_x, m_y };
}
int Mouse::GetPosX() const noexcept {
return m_x;
}
int Mouse::GetPosY() const noexcept {
return m_y;
}
bool Mouse::IsInWindow() const noexcept {
return m_inWindow;
}
bool Mouse::IsLeftPressed() const noexcept {
return m_leftPressed;
}
bool Mouse::IsMiddlePressed() const noexcept {
return m_middlePressed;
}
bool Mouse::IsRightPressed() const noexcept {
return m_rightPressed;
}
bool Mouse::IsRawEnabled() const noexcept {
return m_rawEnabled;
}
std::optional<Mouse::Event> Mouse::Read() noexcept {
if (!m_buffer.empty()) {
Mouse::Event e = m_buffer.front();
m_buffer.pop();
return e;
}
else
return std::nullopt;
}
bool Mouse::IsBufferEmpty() const noexcept {
return m_buffer.empty();
}
void Mouse::Flush() noexcept {
m_buffer = std::queue<Event>();
}
void Mouse::EnableRaw() noexcept {
m_rawEnabled = true;
}
void Mouse::DisableRaw() noexcept {
m_rawEnabled = false;
}
void Mouse::OnMouseMove(int x, int y) noexcept {
m_x = x;
m_y = y;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::Move, *this));
TrimBuffer();
}
void Mouse::OnMouseEnter() noexcept {
m_inWindow = true;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::Enter, *this));
TrimBuffer();
}
void Mouse::OnMouseLeave() noexcept {
m_inWindow = false;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::Leave, *this));
TrimBuffer();
}
void Mouse::OnLeftPress() noexcept {
m_leftPressed = true;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::LPress, *this));
TrimBuffer();
}
void Mouse::OnMiddlePress() noexcept {
m_middlePressed = true;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::MPress, *this));
TrimBuffer();
}
void Mouse::OnRightPress() noexcept {
m_rightPressed = true;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::RPress, *this));
TrimBuffer();
}
void Mouse::OnLeftRelease() noexcept {
m_leftPressed = false;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::LRelease, *this));
TrimBuffer();
}
void Mouse::OnMiddleRelease() noexcept {
m_middlePressed = false;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::MRelease, *this));
TrimBuffer();
}
void Mouse::OnRightRelease() noexcept {
m_rightPressed = false;
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::RRelease, *this));
TrimBuffer();
}
void Mouse::OnWheelUp() noexcept {
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::WheelUp, *this));
TrimBuffer();
}
void Mouse::OnWheelDown() noexcept {
m_buffer.emplace(Mouse::Event(Mouse::Event::Type::WheelDown, *this));
TrimBuffer();
}
void Mouse::TrimBuffer() noexcept {
while (m_buffer.size() > s_bufferSize)
m_buffer.pop();
}
void Mouse::OnWheelDelta(int delta) noexcept {
m_wheelDeltaCarry += delta;
while (m_wheelDeltaCarry >= 120) {
m_wheelDeltaCarry -= 120;
OnWheelUp();
}
while (m_wheelDeltaCarry <= -120) {
m_wheelDeltaCarry += 120;
OnWheelDown();
}
}
void Mouse::OnMouseRawDelta(int dx, int dy) noexcept {
m_rawDeltaBuffer.emplace(RawDelta{dx, dy});
TrimRawDeltaBuffer();
}
void Mouse::TrimRawDeltaBuffer() noexcept {
while (m_rawDeltaBuffer.size() > s_bufferSize)
m_rawDeltaBuffer.pop();
}
std::optional<Mouse::RawDelta> Mouse::ReadRawDelta() noexcept {
if (m_rawDeltaBuffer.empty())
return std::nullopt;
RawDelta d = m_rawDeltaBuffer.front();
m_rawDeltaBuffer.pop();
return d;
}
| 20.604396
| 71
| 0.6736
|
razerx100
|
caaa38fe5b8afff309e02056ead5e2c6d1ca38eb
| 574
|
cpp
|
C++
|
code/save_before/13.cpp
|
EGyeom/BlogMaker
|
7b319a19bb23786c55a0539be86e1c3246e62240
|
[
"MIT"
] | 1
|
2021-06-03T13:44:27.000Z
|
2021-06-03T13:44:27.000Z
|
code/save_before/13.cpp
|
EGyeom/BlogMaker
|
7b319a19bb23786c55a0539be86e1c3246e62240
|
[
"MIT"
] | null | null | null |
code/save_before/13.cpp
|
EGyeom/BlogMaker
|
7b319a19bb23786c55a0539be86e1c3246e62240
|
[
"MIT"
] | null | null | null |
// 두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
// 예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.
// 제한 조건
// a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.
// a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.
// a와 b의 대소관계는 정해져있지 않습니다.
// 입출력 예
// a b return
// 3 5 12
// 3 3 3
// 5 3 12
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
long long solution(int a, int b) {
long long answer = 0;
if(a > b)
{
a ^= b;
b ^= a;
a ^= b;
}
for(int i = a; i <=b; i++)
{
answer += i;
}
return answer;
}
| 18.516129
| 68
| 0.503484
|
EGyeom
|
caab14b7f57a17bd957577fe5e79794b26f09e20
| 1,668
|
cpp
|
C++
|
ysu/lib/rate_limiting.cpp
|
lik2129/ysu_coin
|
47e40ed5d4000fc59566099929bd08a9ae16a4c1
|
[
"BSD-3-Clause"
] | null | null | null |
ysu/lib/rate_limiting.cpp
|
lik2129/ysu_coin
|
47e40ed5d4000fc59566099929bd08a9ae16a4c1
|
[
"BSD-3-Clause"
] | null | null | null |
ysu/lib/rate_limiting.cpp
|
lik2129/ysu_coin
|
47e40ed5d4000fc59566099929bd08a9ae16a4c1
|
[
"BSD-3-Clause"
] | null | null | null |
#include <ysu/lib/locks.hpp>
#include <ysu/lib/rate_limiting.hpp>
#include <ysu/lib/utility.hpp>
#include <limits>
ysu::rate::token_bucket::token_bucket (size_t max_token_count_a, size_t refill_rate_a)
{
// A token count of 0 indicates unlimited capacity. We use 1e9 as
// a sentinel, allowing largest burst to still be computed.
if (max_token_count_a == 0 || refill_rate_a == 0)
{
refill_rate_a = max_token_count_a = static_cast<size_t> (1e9);
}
max_token_count = smallest_size = current_size = max_token_count_a;
refill_rate = refill_rate_a;
last_refill = std::chrono::steady_clock::now ();
}
bool ysu::rate::token_bucket::try_consume (unsigned tokens_required_a)
{
debug_assert (tokens_required_a <= 1e9);
ysu::lock_guard<std::mutex> lk (bucket_mutex);
refill ();
bool possible = current_size >= tokens_required_a;
if (possible)
{
current_size -= tokens_required_a;
}
else if (tokens_required_a == 1e9)
{
current_size = 0;
}
// Keep track of smallest observed bucket size so burst size can be computed (for tests and stats)
smallest_size = std::min (smallest_size, current_size);
return possible || refill_rate == 1e9;
}
void ysu::rate::token_bucket::refill ()
{
auto now (std::chrono::steady_clock::now ());
auto tokens_to_add = static_cast<size_t> (std::chrono::duration_cast<std::chrono::nanoseconds> (now - last_refill).count () / 1e9 * refill_rate);
current_size = std::min (current_size + tokens_to_add, max_token_count);
last_refill = std::chrono::steady_clock::now ();
}
size_t ysu::rate::token_bucket::largest_burst () const
{
ysu::lock_guard<std::mutex> lk (bucket_mutex);
return max_token_count - smallest_size;
}
| 30.888889
| 146
| 0.736811
|
lik2129
|
caaeda5398432aa0d6b25f1e45394e0dc2a92fd0
| 44,238
|
cpp
|
C++
|
third_party/houdini/gusd/GT_Utils.cpp
|
mistafunk/USD
|
be1a80f8cb91133ac75e1fc2a2e1832cd10d91c8
|
[
"BSD-2-Clause"
] | 2
|
2020-02-17T11:13:02.000Z
|
2020-02-17T14:51:01.000Z
|
third_party/houdini/gusd/GT_Utils.cpp
|
mistafunk/USD
|
be1a80f8cb91133ac75e1fc2a2e1832cd10d91c8
|
[
"BSD-2-Clause"
] | null | null | null |
third_party/houdini/gusd/GT_Utils.cpp
|
mistafunk/USD
|
be1a80f8cb91133ac75e1fc2a2e1832cd10d91c8
|
[
"BSD-2-Clause"
] | null | null | null |
//
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "GT_Utils.h"
#include "UT_Gf.h"
#include "UT_Version.h"
#include <GA/GA_ATIGroupBool.h>
#include <GT/GT_DANumeric.h>
#include <GT/GT_GEOPrimPacked.h>
#include <GT/GT_PrimInstance.h>
#include <GT/GT_Util.h>
#include <SYS/SYS_Version.h>
#include "pxr/base/gf/vec3h.h"
#include "pxr/base/gf/vec4h.h"
#include "pxr/base/tf/span.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/usd/usd/attribute.h"
#include "pxr/usd/usd/timeCode.h"
#include "pxr/usd/usdGeom/boundable.h"
#include "pxr/usd/usdGeom/xformable.h"
#include <boost/tuple/tuple.hpp>
#include <iostream>
PXR_NAMESPACE_OPEN_SCOPE
using std::cout;
using std::cerr;
using std::endl;
using std::set;
using std::string;
#ifdef DEBUG
#define DBG(x) x
#else
#define DBG(x)
#endif
namespace {
//#############################################################################
// struct GtDataToUsdTypename
//#############################################################################
struct GtDataToUsdTypename
{
typedef boost::tuple<GT_Storage,
GT_Type,
int /*tupleSize*/,
bool /*isArray*/> KeyType;
struct equal_func : std::binary_function<KeyType, KeyType, bool>
{
bool operator()(const KeyType& lhs, const KeyType& rhs) const
{
return lhs.get<0>() == rhs.get<0>()
&& lhs.get<1>() == rhs.get<1>()
&& lhs.get<2>() == rhs.get<2>()
&& lhs.get<3>() == rhs.get<3>();
}
};
struct hash_func : std::unary_function<KeyType, std::size_t>
{
std::size_t operator()(const KeyType& k) const
{
std::size_t seed = 0;
boost::hash_combine(seed, k.get<0>());
boost::hash_combine(seed, k.get<1>());
boost::hash_combine(seed, k.get<2>());
boost::hash_combine(seed, k.get<3>());
return seed;
}
};
typedef UT_Map<KeyType, SdfValueTypeName, hash_func, equal_func> MapType;
MapType m_typeLookup;
GtDataToUsdTypename()
{
// Integral types
DefineTypeLookup(GT_STORE_INT32, GT_TYPE_NONE, -1,
SdfValueTypeNames->Int);
DefineTypeLookup(GT_STORE_INT64, GT_TYPE_NONE, -1,
SdfValueTypeNames->Int64);
DefineTypeLookup(GT_STORE_UINT8, GT_TYPE_NONE, -1,
SdfValueTypeNames->UChar);
#if SYS_VERSION_FULL_INT >= 0x11000000
// Up-cast int8/int16 to avoid precision loss.
DefineTypeLookup(GT_STORE_INT8, GT_TYPE_NONE, -1,
SdfValueTypeNames->Int);
DefineTypeLookup(GT_STORE_INT16, GT_TYPE_NONE, -1,
SdfValueTypeNames->Int);
#endif
// Integral vectors.
// USD only supports a single precision for vectors of integers.
#if SYS_VERSION_FULL_INT >= 0x11000000
for (auto storage : {GT_STORE_UINT8, GT_STORE_INT8, GT_STORE_INT16,
GT_STORE_INT32, GT_STORE_INT64})
#else
for (auto storage : {GT_STORE_UINT8, GT_STORE_INT32, GT_STORE_INT64})
#endif
{
DefineTypeLookup(storage, GT_TYPE_NONE, 2,
SdfValueTypeNames->Int2);
DefineTypeLookup(storage, GT_TYPE_NONE, 3,
SdfValueTypeNames->Int3);
DefineTypeLookup(storage, GT_TYPE_NONE, 4,
SdfValueTypeNames->Int4);
}
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_NONE, -1,
SdfValueTypeNames->Half);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_NONE, -1,
SdfValueTypeNames->Float);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_NONE, -1,
SdfValueTypeNames->Double);
// Vec2
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_NONE, 2,
SdfValueTypeNames->Half2);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_NONE, 2,
SdfValueTypeNames->Float2);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_NONE, 2,
SdfValueTypeNames->Double2);
// GT_TYPE_TEXTURE
#if SYS_VERSION_FULL_INT >= 0x10050000
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_TEXTURE, 2,
SdfValueTypeNames->TexCoord2h);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_TEXTURE, 2,
SdfValueTypeNames->TexCoord2f);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_TEXTURE, 2,
SdfValueTypeNames->TexCoord2d);
#endif
// GT_TYPE_ST
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_ST, 2,
SdfValueTypeNames->TexCoord2h);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_ST, 2,
SdfValueTypeNames->TexCoord2f);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_ST, 2,
SdfValueTypeNames->TexCoord2d);
// Vec3
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_NONE, 3,
SdfValueTypeNames->Half3);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_NONE, 3,
SdfValueTypeNames->Float3);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_NONE, 3,
SdfValueTypeNames->Double3);
// GT_TYPE_VECTOR 3
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_VECTOR, 3,
SdfValueTypeNames->Vector3h);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_VECTOR, 3,
SdfValueTypeNames->Vector3f);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_VECTOR, 3,
SdfValueTypeNames->Vector3d);
// GT_TYPE_NORMAL 3
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_NORMAL, 3,
SdfValueTypeNames->Normal3h);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_NORMAL, 3,
SdfValueTypeNames->Normal3f);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_NORMAL, 3,
SdfValueTypeNames->Normal3d);
// GT_TYPE_COLOR 3
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_COLOR, 3,
SdfValueTypeNames->Color3h);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_COLOR, 3,
SdfValueTypeNames->Color3f);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_COLOR, 3,
SdfValueTypeNames->Color3d);
// GT_TYPE_POINT 3
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_POINT, 3,
SdfValueTypeNames->Point3h);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_POINT, 3,
SdfValueTypeNames->Point3f);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_POINT, 3,
SdfValueTypeNames->Point3d);
// GT_TYPE_TEXTURE 3
#if SYS_VERSION_FULL_INT >= 0x10050000
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_TEXTURE, 3,
SdfValueTypeNames->TexCoord3h);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_TEXTURE, 3,
SdfValueTypeNames->TexCoord3f);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_TEXTURE, 3,
SdfValueTypeNames->TexCoord3d);
#endif
// Vec4
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_NONE, 4,
SdfValueTypeNames->Half4);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_NONE, 4,
SdfValueTypeNames->Float4);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_NONE, 4,
SdfValueTypeNames->Double4);
// GT_TYPE_COLOR 4
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_COLOR, 4,
SdfValueTypeNames->Color4h);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_COLOR, 4,
SdfValueTypeNames->Color4f);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_COLOR, 4,
SdfValueTypeNames->Color4d);
// GT_TYPE_QUATERNION
DefineTypeLookup(GT_STORE_REAL16, GT_TYPE_QUATERNION, 4,
SdfValueTypeNames->Quath);
DefineTypeLookup(GT_STORE_REAL32, GT_TYPE_QUATERNION, 4,
SdfValueTypeNames->Quatf);
DefineTypeLookup(GT_STORE_REAL64, GT_TYPE_QUATERNION, 4,
SdfValueTypeNames->Quatd);
// Matrices.
// USD only supports a single precision type for matrices.
for (auto storage : {GT_STORE_REAL16,
GT_STORE_REAL32,
GT_STORE_REAL64}) {
DefineTypeLookup(storage, GT_TYPE_MATRIX3, 9,
SdfValueTypeNames->Matrix3d);
DefineTypeLookup(storage, GT_TYPE_MATRIX, 16,
SdfValueTypeNames->Matrix4d);
}
// String
DefineTypeLookup(GT_STORE_STRING, GT_TYPE_NONE, -1,
SdfValueTypeNames->String);
}
SdfValueTypeName operator()(const GT_DataArrayHandle& gtData, bool isArray) const
{
GT_Size tupleSize = gtData->getTupleSize();
// Types may be specialized for vectors of size 2,3,4 and matrices.
// -1 means "any size"
if(tupleSize != 2 && tupleSize != 3 && tupleSize != 4
&& tupleSize != 9 && tupleSize != 16) {
tupleSize = -1;
}
KeyType key(gtData->getStorage(),
gtData->getTypeInfo(),
tupleSize,
isArray);
MapType::const_iterator it = m_typeLookup.find(key);
if(it != m_typeLookup.end()) {
return it->second;
}
return SdfValueTypeName();
}
void
DefineTypeLookup(GT_Storage storage, GT_Type type, int tupleSize,
const SdfValueTypeName& typeName)
{
// Scalar type
m_typeLookup[KeyType(storage, type, tupleSize, /*array*/ false)] =
typeName.GetScalarType();
// Array type
m_typeLookup[KeyType(storage, type, tupleSize, /*array*/ true)] =
typeName.GetArrayType();
}
};
//#############################################################################
//#############################################################################
// Converters
//#############################################################################
/// Copy \p count elements from \p src to \p dst.
template <typename FROM, typename TO>
void
_CopyArray(TO* dst, const FROM* src, GT_Size count)
{
for (GT_Size i = 0; i < count; ++i) {
dst[i] = static_cast<TO>(src[i]);
}
}
bool _IsNumeric(GT_Storage storage)
{
return GTisInteger(storage) || GTisFloat(storage);
}
/// Convert numeric GT types to USD.
/// This converter can only be used on types supported directly by the
/// GT_DataArray interface.
template <class UsdType>
struct _ConvertNumericToUsd
{
using ScalarType = typename GusdPodTupleTraits<UsdType>::ValueType;
static const int tupleSize = GusdGetTupleSize<UsdType>();
static bool fillValue(UsdType& usdValue, const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (_IsNumeric(gtData->getStorage()) && gtData->entries() > 0 &&
gtData->getTupleSize() == tupleSize) {
auto* dst = reinterpret_cast<ScalarType*>(&usdValue);
gtData->import(0, dst, tupleSize);
return true;
}
return false;
}
static bool fillArray(VtArray<UsdType>& usdArray,
const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (_IsNumeric(gtData->getStorage()) &&
gtData->getTupleSize() == tupleSize) {
usdArray.resize(gtData->entries());
auto* dst = reinterpret_cast<ScalarType*>(usdArray.data());
gtData->fillArray(dst, 0, gtData->entries(), tupleSize);
return true;
}
return false;
}
};
/// Convert numeric GT types to USD.
/// This can be used on types that are not directly supported by GT_DataArray,
/// and which require a static_cast to copy into the output.
template <class UsdType>
struct _ConvertNumericWithCastToUsd
{
using ScalarType = typename GusdPodTupleTraits<UsdType>::ValueType;
static const int tupleSize = GusdGetTupleSize<UsdType>();
static bool fillValue(UsdType& usdValue, const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (gtData->entries() > 0 && gtData->getTupleSize() == tupleSize) {
const GT_Storage storage = gtData->getStorage();
if (storage == GT_STORE_UINT8) {
return _fillValue<uint8>(usdValue, gtData);
}
#if SYS_VERSION_FULL_INT >= 0x11000000
else if (storage == GT_STORE_INT8) {
return _fillValue<int8>(usdValue, gtData);
} else if (storage == GT_STORE_INT16) {
return _fillValue<int16>(usdValue, gtData);
}
#endif
else if (storage == GT_STORE_INT32) {
return _fillValue<int32>(usdValue, gtData);
} else if (storage == GT_STORE_INT64) {
return _fillValue<int64>(usdValue, gtData);
} else if (storage == GT_STORE_REAL16) {
return _fillValue<fpreal16>(usdValue, gtData);
} else if (storage == GT_STORE_REAL32) {
return _fillValue<fpreal32>(usdValue, gtData);
} else if (storage == GT_STORE_REAL64) {
return _fillValue<fpreal64>(usdValue, gtData);
}
}
return false;
}
static bool fillArray(VtArray<UsdType>& usdArray,
const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (gtData->getTupleSize() == tupleSize) {
const GT_Storage storage = gtData->getStorage();
if (storage == GT_STORE_UINT8) {
return _fillArray<uint8>(usdArray, gtData);
}
#if SYS_VERSION_FULL_INT >= 0x11000000
else if (storage == GT_STORE_INT8) {
return _fillArray<int8>(usdArray, gtData);
} else if (storage == GT_STORE_INT16) {
return _fillArray<int16>(usdArray, gtData);
}
#endif
else if (storage == GT_STORE_INT32) {
return _fillArray<int32>(usdArray, gtData);
} else if (storage == GT_STORE_INT64) {
return _fillArray<int64>(usdArray, gtData);
} else if (storage == GT_STORE_REAL16) {
return _fillArray<fpreal16>(usdArray, gtData);
} else if (storage == GT_STORE_REAL32) {
return _fillArray<fpreal32>(usdArray, gtData);
} else if (storage == GT_STORE_REAL64) {
return _fillArray<fpreal64>(usdArray, gtData);
}
}
return false;
}
private:
template <typename GtType>
static bool _fillValue(UsdType& usdValue,
const GT_DataArrayHandle& gtData,
GT_Offset offset=0)
{
GtType src[tupleSize];
gtData->import(offset, src, tupleSize);
_CopyArray(reinterpret_cast<ScalarType*>(&usdValue), src, tupleSize);
return true;
}
template <typename GtType>
static bool _fillArray(VtArray<UsdType>& usdArray,
const GT_DataArrayHandle& gtData)
{
const GT_Size numElems = gtData->entries();
usdArray.resize(numElems);
auto dst = TfMakeSpan(usdArray);
for (GT_Offset i = 0; i < numElems; ++i) {
_fillValue<GtType>(dst[i], gtData, i);
}
return true;
}
};
/// Converter specialized for converting GT data to GfQuat types.
template <class UsdType>
struct _ConvertQuatToUsd
{
using GtScalarType = typename GusdPodTupleTraits<UsdType>::ValueType;
static bool fillValue(UsdType& usdValue, const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (GTisFloat(gtData->getStorage()) &&
gtData->entries() > 0 &&
gtData->getTupleSize() == 4) {
_fillValue(usdValue, gtData, 0);
return true;
}
return false;
}
static bool fillArray(VtArray<UsdType>& usdArray,
const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (GTisFloat(gtData->getStorage()) && gtData->getTupleSize() == 4) {
usdArray.resize(gtData->entries());
auto dst = TfMakeSpan(usdArray);
for (GT_Offset i = 0; i < gtData->entries(); ++i) {
_fillValue(dst[i], gtData, i);
}
return true;
}
return false;
}
private:
static void _fillValue(UsdType& usdValue,
const GT_DataArrayHandle& gtData,
GT_Offset offset=0)
{
GtScalarType src[4];
gtData->import(offset, src, 4);
// Houdini quaternions are stored as i,j,k,w
using UsdScalarType = typename UsdType::ScalarType;
usdValue.SetReal(static_cast<UsdScalarType>(src[3]));
usdValue.SetImaginary(static_cast<UsdScalarType>(src[0]),
static_cast<UsdScalarType>(src[1]),
static_cast<UsdScalarType>(src[2]));
}
};
void _ConvertString(const GT_String& src, std::string* dst)
{
*dst = std::string(src ? src : "");
}
void _ConvertString(const GT_String& src, TfToken* dst)
{
*dst = TfToken(src ? src : "");
}
void _ConvertString(const GT_String& src, SdfAssetPath* dst)
{
*dst = SdfAssetPath(src ? src : "");
}
/// Convert a GT type to a USD string value.
struct _ConvertStringToUsd
{
static bool fillValue(std::string& usdValue, const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (GTisString(gtData->getStorage()) &&
gtData->entries() > 0 &&
gtData->getTupleSize() == 1) {
_ConvertString(gtData->getS(0), &usdValue);
return true;
}
return false;
}
static bool fillArray(VtStringArray& usdArray,
const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (GTisString(gtData->getStorage()) &&
gtData->getTupleSize() == 1) {
// XXX tuples of strings not supported
usdArray.resize(gtData->entries());
gtData->fillStrings(usdArray.data());
return true;
}
return false;
}
};
/// Convert a GT type to string-like types (eg., TfToken)
struct _ConvertStringLikeToUsd
{
template <class UsdType>
static bool fillValue(UsdType& usdValue, const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (GTisString(gtData->getStorage()) &&
gtData->entries() > 0 &&
gtData->getTupleSize() == 1) {
_ConvertString(gtData->getS(0), &usdValue);
return true;
}
return false;
}
template <class UsdType>
static bool fillArray(VtArray<UsdType>& usdArray,
const GT_DataArrayHandle& gtData)
{
UT_ASSERT_P(gtData);
if (GTisString(gtData->getStorage()) &&
gtData->getTupleSize() == 1) {
// XXX tuples of strings not supported
const GT_Size numElems = gtData->entries();
usdArray.resize(numElems);
auto dst = TfMakeSpan(usdArray);
for (GT_Size i = 0; i < numElems; ++i) {
_ConvertString(gtData->getS(i), &dst[i]);
}
return true;
}
return false;
}
};
template <class UsdType> struct _ConvertToUsd {};
#define _GUSD_DEFINE_CONVERTER(type, base) \
template <> struct _ConvertToUsd<type> : public base {};
// Scalars
_GUSD_DEFINE_CONVERTER(double, _ConvertNumericToUsd<double>);
_GUSD_DEFINE_CONVERTER(float, _ConvertNumericToUsd<float>);
_GUSD_DEFINE_CONVERTER(GfHalf, _ConvertNumericWithCastToUsd<GfHalf>);
_GUSD_DEFINE_CONVERTER(bool, _ConvertNumericWithCastToUsd<bool>);
_GUSD_DEFINE_CONVERTER(int, _ConvertNumericToUsd<int>);
_GUSD_DEFINE_CONVERTER(uint8, _ConvertNumericToUsd<uint8>);
_GUSD_DEFINE_CONVERTER(int64, _ConvertNumericToUsd<int64>);
_GUSD_DEFINE_CONVERTER(uint32, _ConvertNumericWithCastToUsd<uint32>);
_GUSD_DEFINE_CONVERTER(uint64, _ConvertNumericWithCastToUsd<uint64>);
// Vectors
_GUSD_DEFINE_CONVERTER(GfVec2d, _ConvertNumericToUsd<GfVec2d>);
_GUSD_DEFINE_CONVERTER(GfVec2f, _ConvertNumericToUsd<GfVec2f>);
_GUSD_DEFINE_CONVERTER(GfVec2h, _ConvertNumericToUsd<GfVec2h>);
_GUSD_DEFINE_CONVERTER(GfVec2i, _ConvertNumericToUsd<GfVec2i>);
_GUSD_DEFINE_CONVERTER(GfVec3d, _ConvertNumericToUsd<GfVec3d>);
_GUSD_DEFINE_CONVERTER(GfVec3f, _ConvertNumericToUsd<GfVec3f>);
_GUSD_DEFINE_CONVERTER(GfVec3h, _ConvertNumericToUsd<GfVec3h>);
_GUSD_DEFINE_CONVERTER(GfVec3i, _ConvertNumericToUsd<GfVec3i>);
_GUSD_DEFINE_CONVERTER(GfVec4d, _ConvertNumericToUsd<GfVec4d>);
_GUSD_DEFINE_CONVERTER(GfVec4f, _ConvertNumericToUsd<GfVec4f>);
_GUSD_DEFINE_CONVERTER(GfVec4h, _ConvertNumericToUsd<GfVec4h>);
_GUSD_DEFINE_CONVERTER(GfVec4i, _ConvertNumericToUsd<GfVec4i>);
// Quat types
_GUSD_DEFINE_CONVERTER(GfQuatd, _ConvertQuatToUsd<GfQuatd>);
_GUSD_DEFINE_CONVERTER(GfQuatf, _ConvertQuatToUsd<GfQuatf>);
_GUSD_DEFINE_CONVERTER(GfQuath, _ConvertQuatToUsd<GfQuath>);
// Matrices
_GUSD_DEFINE_CONVERTER(GfMatrix2d, _ConvertNumericToUsd<GfMatrix2d>);
_GUSD_DEFINE_CONVERTER(GfMatrix3d, _ConvertNumericToUsd<GfMatrix3d>);
_GUSD_DEFINE_CONVERTER(GfMatrix4d, _ConvertNumericToUsd<GfMatrix4d>);
// Strings a string-like types.
_GUSD_DEFINE_CONVERTER(std::string, _ConvertStringToUsd);
_GUSD_DEFINE_CONVERTER(SdfAssetPath, _ConvertStringLikeToUsd);
_GUSD_DEFINE_CONVERTER(TfToken, _ConvertStringLikeToUsd);
template <class UsdType>
bool _SetUsdAttributeT(const UsdAttribute& destAttr,
const GT_DataArrayHandle& sourceAttr,
const SdfValueTypeName& usdType,
UsdTimeCode time)
{
UT_ASSERT(usdType);
if (usdType.IsArray()) {
VtArray<UsdType> usdArray;
if (_ConvertToUsd<UsdType>::fillArray(usdArray, sourceAttr)) {
return destAttr.Set(usdArray, time);
}
} else {
UsdType usdValue;
if (_ConvertToUsd<UsdType>::fillValue(usdValue, sourceAttr)) {
return destAttr.Set(usdValue, time);
}
}
return false;
}
bool
_SetUsdAttribute(const UsdAttribute& destAttr,
const GT_DataArrayHandle& sourceAttr,
const SdfValueTypeName& usdType,
UsdTimeCode time)
{
if (!sourceAttr || !destAttr) {
return false;
}
const SdfValueTypeName scalarType = usdType.GetScalarType();
// GfVec3
// GfVec3f is the most common type
// XXX: We compare using the TfType rather than the Sdf type name so that
// the same converters are employed regardless of the Sdf role.
if (scalarType.GetType() == SdfValueTypeNames->Float3.GetType()) {
return _SetUsdAttributeT<GfVec3f>(destAttr, sourceAttr, usdType, time);
}
if (scalarType.GetType() == SdfValueTypeNames->Double3.GetType()) {
return _SetUsdAttributeT<GfVec3d>(destAttr, sourceAttr, usdType, time);
}
if (scalarType.GetType() == SdfValueTypeNames->Half3.GetType()) {
return _SetUsdAttributeT<GfVec3h>(destAttr, sourceAttr, usdType, time);
}
// GfVec2
if (scalarType.GetType() == SdfValueTypeNames->Double2.GetType()) {
return _SetUsdAttributeT<GfVec2d>(destAttr, sourceAttr, usdType, time);
}
if (scalarType.GetType() == SdfValueTypeNames->Float2.GetType()) {
return _SetUsdAttributeT<GfVec2f>(destAttr, sourceAttr, usdType, time);
}
if (scalarType.GetType() == SdfValueTypeNames->Half2.GetType()) {
return _SetUsdAttributeT<GfVec2h>(destAttr, sourceAttr, usdType, time);
}
// GfVec4
if (scalarType.GetType() == SdfValueTypeNames->Double4.GetType()) {
return _SetUsdAttributeT<GfVec4d>(destAttr, sourceAttr, usdType, time);
}
if (scalarType.GetType() == SdfValueTypeNames->Float4.GetType()) {
return _SetUsdAttributeT<GfVec4f>(destAttr, sourceAttr, usdType, time);
}
if (scalarType.GetType() == SdfValueTypeNames->Half4.GetType()) {
return _SetUsdAttributeT<GfVec4h>(destAttr, sourceAttr, usdType, time);
}
// Quaternions
if (scalarType == SdfValueTypeNames->Quatd) {
return _SetUsdAttributeT<GfQuatd>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->Quatf) {
return _SetUsdAttributeT<GfQuatf>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->Quath) {
return _SetUsdAttributeT<GfQuath>(destAttr, sourceAttr, usdType, time);
}
// Scalars.
if (scalarType == SdfValueTypeNames->Float) {
return _SetUsdAttributeT<float>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->Double) {
return _SetUsdAttributeT<double>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->Half) {
return _SetUsdAttributeT<GfHalf>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->Int) {
return _SetUsdAttributeT<int>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->Int64) {
return _SetUsdAttributeT<int64>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->UChar) {
return _SetUsdAttributeT<uint8>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->UInt) {
return _SetUsdAttributeT<uint32>(destAttr, sourceAttr, usdType, time);
}
if (scalarType == SdfValueTypeNames->UInt64) {
return _SetUsdAttributeT<uint64>(destAttr, sourceAttr, usdType, time);
}
// Matrices
if (scalarType.GetType() == SdfValueTypeNames->Matrix2d.GetType()) {
return _SetUsdAttributeT<GfMatrix2d>(destAttr, sourceAttr,
usdType, time);
}
if (scalarType.GetType() == SdfValueTypeNames->Matrix3d.GetType()) {
return _SetUsdAttributeT<GfMatrix3d>(destAttr, sourceAttr,
usdType, time);
}
if (scalarType.GetType() == SdfValueTypeNames->Matrix4d.GetType()) {
return _SetUsdAttributeT<GfMatrix4d>(destAttr, sourceAttr,
usdType, time);
}
// Strings
if (scalarType == SdfValueTypeNames->String) {
return _SetUsdAttributeT<std::string>(destAttr, sourceAttr,
usdType, time);
}
if (scalarType == SdfValueTypeNames->Token) {
return _SetUsdAttributeT<TfToken>(destAttr, sourceAttr,
usdType, time);
}
if (scalarType == SdfValueTypeNames->Asset) {
return _SetUsdAttributeT<SdfAssetPath>(destAttr, sourceAttr,
usdType, time);
}
TF_WARN("setUsdAttribute: type not implemented: %s",
usdType.GetAsToken().GetText());
return false;
}
//#############################################################################
bool
setPvSample(const UsdGeomImageable& usdPrim,
const TfToken& name,
const GT_DataArrayHandle& gtData,
const TfToken& interpolationIn,
UsdTimeCode time)
{
static const GtDataToUsdTypename usdTypename;
TfToken interpolation = interpolationIn;
//bool isArrayType = (interpolation != UsdGeomTokens->constant);
SdfValueTypeName typeName = usdTypename( gtData, true );
if( !typeName ) {
TF_WARN( "Unsupported primvar type %s, %s, tupleSize = %zd",
name.GetText(), GTstorage(gtData->getStorage()),
gtData->getTupleSize() );
return false;
}
const UsdGeomPrimvar existingPrimvar = usdPrim.GetPrimvar( name );
if( existingPrimvar && typeName != existingPrimvar.GetTypeName() ) {
// If this primvar already exists, we can't change its type. Most notably,
// we change change a scalar to an array type.
typeName = existingPrimvar.GetTypeName();
if( !typeName.IsArray() ) {
interpolation = UsdGeomTokens->constant;
}
}
UsdGeomPrimvar primvar = usdPrim.CreatePrimvar( name, typeName, interpolation );
if(!primvar)
return false;
return _SetUsdAttribute(primvar.GetAttr(), gtData, typeName, time);
}
} // anon namespace
//#############################################################################
// class GusdGT_AttrFilter
//#############################################################################
GusdGT_AttrFilter::
GusdGT_AttrFilter(const std::string& pattern)
{
// always override these
m_overridePattern =
" ^__point_id"
" ^__vertex_id"
" ^__primitive_id"
" ^__topology"
" ^__primitivelist"
" ^usdMeta_*"
" ^usdvisible"
" ^usdactive";
setPattern(GT_OWNER_POINT, pattern);
setPattern(GT_OWNER_VERTEX, pattern);
setPattern(GT_OWNER_UNIFORM, pattern);
setPattern(GT_OWNER_CONSTANT, pattern);
}
GusdGT_AttrFilter::
GusdGT_AttrFilter(const GusdGT_AttrFilter &rhs)
: m_patterns( rhs.m_patterns )
, m_activeOwners( rhs.m_activeOwners )
{
m_overridePattern =
" ^__point_id"
" ^__vertex_id"
" ^__primitive_id"
" ^__topology"
" ^usdMeta_*"
" ^usdvisible"
" ^usdactive";
}
void GusdGT_AttrFilter::
setPattern(GT_Owner owner, const std::string& pattern)
{
m_patterns[owner] = " " + pattern + m_overridePattern;
}
void GusdGT_AttrFilter::
appendPattern(GT_Owner owner, const std::string& pattern)
{
m_patterns[owner] += " " + pattern;
}
void GusdGT_AttrFilter::
setActiveOwners(const OwnerArgs& owners) const
{
m_activeOwners = owners;
}
bool GusdGT_AttrFilter::
matches(const std::string& attrName) const
{
for(int i=0; i<m_activeOwners.entries(); ++i) {
UT_Map<GT_Owner, std::string>::const_iterator mapIt =
m_patterns.find(m_activeOwners.item(i));
if(mapIt == m_patterns.end()) continue;
UT_String str(attrName);
if(str.multiMatch(mapIt->second.c_str()) != 0) {
return true;
}
}
return false;
}
//#############################################################################
// GusdGT_Utils implementation
//#############################################################################
GT_Type
GusdGT_Utils::getType(const SdfValueTypeName& typeName)
{
const TfToken& role = typeName.GetRole();
if (role == SdfValueRoleNames->Point) {
return GT_TYPE_POINT;
} else if (role == SdfValueRoleNames->Normal) {
return GT_TYPE_NORMAL;
} else if (role == SdfValueRoleNames->Vector) {
return GT_TYPE_VECTOR;
} else if (role == SdfValueRoleNames->Color) {
return GT_TYPE_COLOR;
} else if (role == SdfValueRoleNames->TextureCoordinate) {
#if SYS_VERSION_FULL_INT >= 0x10050000
return GT_TYPE_TEXTURE;
#endif
} else if (typeName == SdfValueTypeNames->Matrix4d) {
return GT_TYPE_MATRIX;
} else if (typeName == SdfValueTypeNames->Matrix3d) {
return GT_TYPE_MATRIX3;
}
return GT_TYPE_NONE;
}
TfToken
GusdGT_Utils::getRole(GT_Type type)
{
switch (type)
{
case GT_TYPE_POINT: return SdfValueRoleNames->Point;
case GT_TYPE_VECTOR: return SdfValueRoleNames->Vector;
case GT_TYPE_NORMAL: return SdfValueRoleNames->Normal;
case GT_TYPE_COLOR: return SdfValueRoleNames->Color;
case GT_TYPE_ST:
#if SYS_VERSION_FULL_INT >= 0x10050000
case GT_TYPE_TEXTURE:
return SdfValueRoleNames->TextureCoordinate;
#endif
default:
return TfToken();
};
}
bool GusdGT_Utils::
setUsdAttribute(const UsdAttribute& destAttr,
const GT_DataArrayHandle& sourceAttr,
UsdTimeCode time)
{
return _SetUsdAttribute(destAttr, sourceAttr, destAttr.GetTypeName(), time);
}
GT_DataArrayHandle GusdGT_Utils::
getExtentsArray(const GT_PrimitiveHandle& gtPrim)
{
GT_DataArrayHandle ret;
if(gtPrim) {
UT_BoundingBox houBoundsArray[]
= {UT_BoundingBox(SYS_FP32_MAX, SYS_FP32_MAX, SYS_FP32_MAX,
SYS_FP32_MIN, SYS_FP32_MIN, SYS_FP32_MIN)};
houBoundsArray[0].initBounds();
gtPrim->enlargeRenderBounds(houBoundsArray, 1);
GT_Real32Array* gtExtents = new GT_Real32Array(2, 3);
gtExtents->setTupleBlock(houBoundsArray[0].minvec().data(), 1, 0);
gtExtents->setTupleBlock(houBoundsArray[0].maxvec().data(), 1, 1);
ret = gtExtents;
}
return ret;
}
#if (GUSD_VER_CMP_1(>=,15))
typedef GT_AttributeMap::const_names_iterator AttrMapIterator;
#else
typedef UT_SymbolTable::traverser AttrMapIterator;
#endif
bool
GusdGT_Utils::setPrimvarSample(
const UsdGeomImageable& usdPrim,
const TfToken &name,
const GT_DataArrayHandle& data,
const TfToken& interpolation,
UsdTimeCode time )
{
DBG(cerr << "GusdGT_Utils::setPrimvarSample: " << name
<< ", " << GTstorage( data->getStorage() ) << ", "
<< data->getTupleSize() << ", " << interpolation << endl);
return setPvSample(usdPrim, name, data, interpolation, time);
}
template <typename T> bool
isDataConst( const T* p, GT_Size entries, GT_Size tupleSize ) {
if( tupleSize == 1 ) {
T first = *p++;
for( GT_Size i = 1; i < entries; ++i ) {
if( *p++ != first ) {
return false;
}
}
return true;
}
else if ( tupleSize == 3 ) {
T first_0 = *(p+0);
T first_1 = *(p+1);
T first_2 = *(p+2);
p += 3;
for( GT_Size i = 1; i < entries; ++i ) {
if( *(p+0) != first_0 ||
*(p+1) != first_1 ||
*(p+2) != first_2 ) {
return false;
}
p += 3;
}
return true;
}
else {
const T* firstP = p;
p += tupleSize;
for( GT_Size i = 1; i < entries; ++i ) {
for( GT_Size j = 0; j < tupleSize; ++ j ) {
if( *(p + j) != *(firstP + j) ) {
return false;
}
}
p += tupleSize;
}
return true;
}
}
bool
GusdGT_Utils::
isDataConstant( const GT_DataArrayHandle& data )
{
const GT_Storage storage = data->getStorage();
const GT_Size tupleSize = data->getTupleSize();
const GT_Size entries = data->entries();
if (entries == 0) {
return true;
}
if (storage == GT_STORE_UINT8) {
GT_DataArrayHandle buffer;
return isDataConst<uint8>(data->getU8Array(buffer),
entries, tupleSize);
}
#if SYS_VERSION_FULL_INT >= 0x11000000
else if (storage == GT_STORE_INT8) {
GT_DataArrayHandle buffer;
return isDataConst<int8>(data->getI8Array(buffer),
entries, tupleSize);
} else if (storage == GT_STORE_INT16) {
GT_DataArrayHandle buffer;
return isDataConst<int16>(data->getI16Array(buffer),
entries, tupleSize);
}
#endif
else if (storage == GT_STORE_INT32) {
GT_DataArrayHandle buffer;
return isDataConst<int32>(data->getI32Array(buffer),
entries, tupleSize);
} else if (storage == GT_STORE_INT64) {
GT_DataArrayHandle buffer;
return isDataConst<int64>(data->getI64Array(buffer),
entries, tupleSize);
} else if (storage == GT_STORE_REAL16) {
GT_DataArrayHandle buffer;
return isDataConst<fpreal16>(data->getF16Array(buffer),
entries, tupleSize);
} else if (storage == GT_STORE_REAL32) {
GT_DataArrayHandle buffer;
return isDataConst<fpreal32>(data->getF32Array(buffer),
entries, tupleSize);
} else if (storage == GT_STORE_REAL64) {
GT_DataArrayHandle buffer;
return isDataConst<fpreal64>(data->getF64Array(buffer),
entries, tupleSize);
} else if (storage == GT_STORE_STRING) {
if (data->getStringIndexCount() >= 0) {
// If this is an indexed string array, we can just compare the indices.
// One would think that getIndexedStrings would return indices,
// but it doesn't. If we look at the header file for GT_DAIndexedString,
// we can deduce that getI32Array gets you the indices.
GT_DataArrayHandle buffer;
const int32* indices = data->getI32Array(buffer);
if (indices ) {
int32 first = indices[0];
for (GT_Size i = 1; i < entries; ++i) {
if (indices[i] != first) {
return false;
}
}
return true;
}
}
UT_StringArray strings;
data->getStrings(strings);
// beware of arrays of strings, I don't how to compare these.
if (strings.entries() == 0) {
return false;
}
const UT_StringHolder &first = strings(0);
for (GT_Size i = 1, end = std::min( entries, strings.entries() ); i < end; ++i) {
if (strings(i) != first) {
return false;
}
}
return true;
}
TF_WARN("Unsupported primvar type: %s, tupleSize = %zd",
GTstorage(storage), tupleSize);
return false;
}
void GusdGT_Utils::
setCustomAttributesFromGTPrim(
const UsdGeomImageable &usdGeomPrim,
const GT_AttributeListHandle& gtAttrs,
set<string>& excludeSet,
UsdTimeCode time )
{
//TODO: The exclude set should be a GT_GEOAttributeFilter
static const GtDataToUsdTypename usdTypename;
UsdPrim prim = usdGeomPrim.GetPrim();
if( !gtAttrs )
return;
const GT_AttributeMapHandle attrMapHandle = gtAttrs->getMap();
for(AttrMapIterator mapIt=attrMapHandle->begin(); !mapIt.atEnd(); ++mapIt) {
#if SYS_VERSION_FULL_INT < 0x11000000
string name = mapIt.name();
#else
string name = mapIt->first.toStdString();
#endif
#if (GUSD_VER_CMP_1(>=,15))
const int attrIndex = attrMapHandle->get(name);
#else
const int attrIndex = attrMapHandle->getMapIndex(mapIt.thing());
#endif
const GT_DataArrayHandle& gtData = gtAttrs->get(attrIndex);
if( TfStringStartsWith( name, "__" ) ||
excludeSet.find( name ) != excludeSet.end() ) {
continue;
}
const SdfValueTypeName typeName = usdTypename( gtData, false );
UsdAttribute attr =
prim.CreateAttribute( TfToken( name ), typeName );
setUsdAttribute( attr, gtData, time );
}
}
GT_DataArrayHandle GusdGT_Utils::
getTransformArray(const GT_PrimitiveHandle& gtPrim)
{
GT_DataArrayHandle ret;
if(gtPrim) {
UT_Matrix4D houXform;
gtPrim->getPrimitiveTransform()->getMatrix(houXform);
GT_Real64Array* gtData = new GT_Real64Array(houXform.data(), 1, 16);
ret = gtData;
}
return ret;
}
GT_DataArrayHandle GusdGT_Utils::
getPackedTransformArray(const GT_PrimitiveHandle& gtPrim)
{
GT_DataArrayHandle ret;
if(gtPrim) {
const GT_GEOPrimPacked* gtPacked
= dynamic_cast<const GT_GEOPrimPacked*>(gtPrim.get());
if(gtPacked) {
UT_Matrix4D houXform;
gtPacked->getPrim()->getFullTransform4(houXform);
GT_Real64Array* gtData = new GT_Real64Array(houXform.data(), 1, 16);
ret = gtData;
}
}
return ret;
}
bool GusdGT_Utils::
setTransformFromGTArray(const UsdGeomXformable& usdGeom,
const GT_DataArrayHandle& xform,
const TransformLevel transformLevel,
UsdTimeCode time)
{
if(!usdGeom || !xform) return false;
bool resetsXformStack=false;
std::vector<UsdGeomXformOp> xformOps = usdGeom.GetOrderedXformOps(
&resetsXformStack);
if(xformOps.size() <= transformLevel) return false;
GfMatrix4d mat4;
if (_ConvertToUsd<GfMatrix4d>::fillValue(mat4, xform)) {
return xformOps[transformLevel].Set(mat4, time);
}
return false;
}
GfMatrix4d GusdGT_Utils::
getMatrixFromGTArray(const GT_DataArrayHandle& xform)
{
GfMatrix4d mat4;
if (!_ConvertToUsd<GfMatrix4d>::fillValue(mat4, xform)) {
mat4.SetIdentity();
}
return mat4;
}
GT_DataArrayHandle GusdGT_Utils::
transformPoints(
GT_DataArrayHandle pts,
const UT_Matrix4D& objXform )
{
GT_Real32Array *newPts =
new GT_Real32Array( pts->entries(), 3, pts->getTypeInfo() );
UT_Vector3F* dstP = reinterpret_cast<UT_Vector3F*>(newPts->data());
GT_DataArrayHandle buffer;
const UT_Vector3F* srcP =
reinterpret_cast<const UT_Vector3F *>(pts->getF32Array( buffer ));
for( GT_Size i = 0; i < pts->entries(); ++i ) {
*dstP++ = *srcP++ * objXform;
}
return newPts;
}
GT_DataArrayHandle GusdGT_Utils::
transformPoints(
GT_DataArrayHandle pts,
const GfMatrix4d& objXform )
{
return transformPoints( pts, GusdUT_Gf::Cast( objXform ) );
}
//#############################################################################
GT_AttributeListHandle GusdGT_Utils::
getAttributesFromPrim( const GEO_Primitive *prim )
{
const GA_Detail& detail = prim->getDetail();
GA_Offset offset = prim->getMapOffset();
GA_Range range = GA_Range( detail.getPrimitiveMap(), offset, offset + 1 );
const GA_AttributeDict& attrDict = detail.getAttributeDict(GA_ATTRIB_PRIMITIVE);
if( attrDict.entries() == 0 )
return GT_AttributeListHandle();
GT_AttributeListHandle attrList = new GT_AttributeList(new GT_AttributeMap());
for( GA_AttributeDict::iterator it=attrDict.begin(); !it.atEnd(); ++it)
{
GA_Attribute *attr = it.attrib();
// Ignore any attributes which define groups.
if( attr && !GA_ATIGroupBool::isType( attr ))
{
GT_DataArrayHandle array = GT_Util::extractAttribute( *attr, range );
attrList = attrList->addAttribute( attr->getName(), array, true );
}
}
return attrList;
}
std::string GusdGT_Utils::
makeValidIdentifier(const TfToken& usdFilePath, const SdfPath& nodePath)
{
return TfMakeValidIdentifier(usdFilePath)
+ "__" + TfMakeValidIdentifier(nodePath.GetString());
}
PXR_NAMESPACE_CLOSE_SCOPE
| 33.615502
| 89
| 0.602988
|
mistafunk
|
cab07ed8404b350afd07da4e95586d614cdaa107
| 870
|
hpp
|
C++
|
include/miok/package.hpp
|
michaelbrockus/bunny-package-cpp
|
50774a65dad10dda3e61f803898659a6eca5ec58
|
[
"Apache-2.0"
] | null | null | null |
include/miok/package.hpp
|
michaelbrockus/bunny-package-cpp
|
50774a65dad10dda3e61f803898659a6eca5ec58
|
[
"Apache-2.0"
] | null | null | null |
include/miok/package.hpp
|
michaelbrockus/bunny-package-cpp
|
50774a65dad10dda3e61f803898659a6eca5ec58
|
[
"Apache-2.0"
] | null | null | null |
//
// file: package.hpp
// author: Michael Brockus
// gmail: <michaelbrockus@gmail.com>
#ifndef MIOK_PACKAGE_HPP
#define MIOK_PACKAGE_HPP
//
// Macros to control the visibility of functions provided by this package
//
#ifdef BUILDING_MIOK_PACKAGE
#define MIOK_PUBLIC __attribute__((visibility("default")))
#else
#define MIOK_PUBLIC
#endif
//
// PUBLIC APPLICATION INTERFACE
// --------------------------------
//
// Published package with provided public application interface for
// use in the users application. Please note that we are internationally
// targeting c23 standard. If you wish to use a version of this library
// that targets an older version of C append "-support" at the end of the
// package name and everything should just work.
//
namespace miok
{
MIOK_PUBLIC const char *greet(void);
} // namespace bunny
#endif // end of MIOK_PACKAGE_H
| 24.857143
| 73
| 0.726437
|
michaelbrockus
|
cab2eadca09249fd737bc573bef98b810765ddec
| 164,513
|
cxx
|
C++
|
PWGCF/FEMTOSCOPY/PLamAnalysisPP/AliAnalysisTaskPLFemto.cxx
|
wiechula/AliPhysics
|
6c5c45a5c985747ee82328d8fd59222b34529895
|
[
"BSD-3-Clause"
] | null | null | null |
PWGCF/FEMTOSCOPY/PLamAnalysisPP/AliAnalysisTaskPLFemto.cxx
|
wiechula/AliPhysics
|
6c5c45a5c985747ee82328d8fd59222b34529895
|
[
"BSD-3-Clause"
] | null | null | null |
PWGCF/FEMTOSCOPY/PLamAnalysisPP/AliAnalysisTaskPLFemto.cxx
|
wiechula/AliPhysics
|
6c5c45a5c985747ee82328d8fd59222b34529895
|
[
"BSD-3-Clause"
] | null | null | null |
/*
**************************************************************************
* Copyright(c) 1998-2009, 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 *
* appeuear 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. *
**************************************************************************/
/* $Id$ */
// Class to calculate P-V0 (especially P-Lambda) correlation functions
// Author: O. Arnold
// inherited a lot from other analyses, especially from H. Beck (thanks!)
//
//-----------------------------------------------------------------------
#include <TSystem.h>
#include <TParticle.h>
#include "TROOT.h"
#include <TDatabasePDG.h>
#include <AliAnalysisDataSlot.h>
#include <AliAnalysisDataContainer.h>
#include "AliStack.h"
#include "AliMCEvent.h"
#include "AliAnalysisManager.h"
#include "AliAODMCHeader.h"
#include "AliAODHandler.h"
#include "AliLog.h"
#include "AliAODVertex.h"
#include "AliAODRecoDecay.h"
#include "AliESDtrack.h"
#include "AliAODMCParticle.h"
//#include "AliNormalizationCounter.h"
#include "AliAODEvent.h"
#include "AliAnalysisTaskPLFemto.h"
#include "AliInputEventHandler.h"
#include "AliFemtoLambdaEventCollection2.h"
#include "AliFemtoLambdaEvent.h"
#include "AliFemtoLambdaParticle.h"
#include "AliFemtoProtonParticle.h"
#include "AliPPVsMultUtils.h"
//#include "AliAODv0.h"
#ifdef __ROOT__
ClassImp(AliAnalysisTaskPLFemto)
#endif
Double_t TPCradii[9] = {85.,105.,125.,145.,165.,185.,205.,225.,245.};//must be global to be used on grid
//__________________________________________________________________________
AliAnalysisTaskPLFemto::AliAnalysisTaskPLFemto():
AliAnalysisTaskSE(),
fEvents(0),
fUseMCInfo(kFALSE),
fOnlineV0(kTRUE),
fOutput(0),
fOutputSP(0),
fOutputTP(0),
fOutputPID(0),
fAODMCEvent(0),
fCEvents(0),
fSphericityvalue(-9999.),
fTPCradii(0),
fV0Counter(0),
fAntiV0Counter(0),
fProtonCounter(0),
fAntiProtonCounter(0),
fXiCounter(0),
fEventNumber(0),
fWhichfilterbit(128),
fwhichV0("Lambda"),
fwhichAntiV0("Anti-"+fwhichV0),
fwhichV0region("signal"),
fPIDResponse(0),
fGTI(0),
fTrackBuffSize(1000),
fEC(new AliFemtoLambdaEventCollection2 **[kZVertexBins]),
fEvt(0),
fV0cand(new AliFemtoLambdaParticle[kV0TrackLimit]),
fAntiV0cand(new AliFemtoLambdaParticle[kV0TrackLimit]),
fProtoncand(new AliFemtoProtonParticle[kProtonTrackLimit]),
fAntiProtoncand(new AliFemtoProtonParticle[kProtonTrackLimit]),
fXicand(new AliFemtoXiParticle[kXiTrackLimit]),
fCuts(new AliFemtoCutValues()),
fAnaUtils(new AliAnalysisUtils())
{
//
// Constructor. Initialization of Inputs and Outputs
//
fTPCradii = TPCradii;
for(Int_t i=0; i<3;i++) fPrimVertex[i] = -9999.;
Info("AliAnalysisTaskPLFemto","Calling default Constructor");
for(UChar_t iZBin=0;iZBin<kZVertexBins;iZBin++)
{
fEC[iZBin] = new AliFemtoLambdaEventCollection2 *[kMultiplicityBins];
// Bins in Multiplicity
for (UChar_t iMultBin=0;iMultBin<kMultiplicityBins;iMultBin++)
{
fEC[iZBin][iMultBin] = new AliFemtoLambdaEventCollection2(kEventsToMix+1,kV0TrackLimit);
}
}
fAnaUtils->SetMinPlpContribSPD(3);
}
//___________________________________________________________________________
AliAnalysisTaskPLFemto::AliAnalysisTaskPLFemto(const Char_t* name,Bool_t OnlineCase,TString whichV0,TString whichV0region,const int whichfilterbit) :
AliAnalysisTaskSE(name),
fEvents(0),
fUseMCInfo(kFALSE),
fOnlineV0(OnlineCase),
fOutput(0),
fOutputSP(0),
fOutputTP(0),
fOutputPID(0),
fAODMCEvent(0),
fCEvents(0),
fSphericityvalue(-9999.),
fTPCradii(0),
fwhichV0(whichV0),
fwhichAntiV0("Anti-"+whichV0),
fwhichV0region(whichV0region),
fV0Counter(0),
fAntiV0Counter(0),
fProtonCounter(0),
fAntiProtonCounter(0),
fXiCounter(0),
fEventNumber(0),
fWhichfilterbit(whichfilterbit),
fPIDResponse(0),
fGTI(0),
fTrackBuffSize(1000),
fEC(new AliFemtoLambdaEventCollection2 **[kZVertexBins]),
fEvt(0),
fV0cand(new AliFemtoLambdaParticle[kV0TrackLimit]),
fAntiV0cand(new AliFemtoLambdaParticle[kV0TrackLimit]),
fProtoncand(new AliFemtoProtonParticle[kProtonTrackLimit]),
fAntiProtoncand(new AliFemtoProtonParticle[kProtonTrackLimit]),
fXicand(new AliFemtoXiParticle[kXiTrackLimit]),
fCuts(new AliFemtoCutValues()),
fAnaUtils(new AliAnalysisUtils())
{
Info("AliAnalysisTaskPLFemto","Calling extended Constructor");
fTPCradii = TPCradii;
for(Int_t i=0; i<3;i++) fPrimVertex[i] = -9999.;
for(UChar_t iZBin=0;iZBin<kZVertexBins;iZBin++)
{
fEC[iZBin] = new AliFemtoLambdaEventCollection2 *[kMultiplicityBins];
// Bins in Multiplicity
for (UChar_t iMultBin=0;iMultBin<kMultiplicityBins;iMultBin++)
{
fEC[iZBin][iMultBin] = new AliFemtoLambdaEventCollection2(kEventsToMix+1,kV0TrackLimit);
}
}
DefineOutput(1,TList::Class()); //conters
DefineOutput(2,TList::Class());
DefineOutput(3,TList::Class());
DefineOutput(4,TList::Class());
fAnaUtils->SetMinPlpContribSPD(3);
}
//___________________________________________________________________________
AliAnalysisTaskPLFemto::~AliAnalysisTaskPLFemto() {
//
// destructor
//
Info("~AliAnalysisTaskPLFemto","Calling Destructor");
delete fOutput;
delete fOutputSP;
delete fOutputTP;
delete fOutputPID;
delete fCEvents;
if (fGTI)
delete[] fGTI;
fGTI=0;
if(fEC)
{
for(unsigned short i=0; i<kZVertexBins; i++)
{
for(unsigned short j=0; j<kMultiplicityBins; j++)
{
fEC[i][j]->~AliFemtoLambdaEventCollection2();
fEC[i][j] = NULL;
delete [] fEC[i][j]; fEC[i][j] = NULL;
}
delete[] fEC[i]; fEC[i] = NULL;
}
delete[] fEC; fEC = NULL;
}
if(fEC){ delete fEC; fEC = NULL;}
if(fV0cand) delete[] fV0cand;
if(fAntiV0cand) delete[] fAntiV0cand;
if(fProtoncand) delete[] fProtoncand;
if(fAntiProtoncand) delete[] fAntiProtoncand;
if(fXicand) delete[] fXicand;
if(fCuts) delete fCuts;
if(fPIDResponse) delete fPIDResponse;
// TODO: Uncomment this line when the AliAnalysisUtils destructor is fixed
// if(fAnaUtils) delete fAnaUtils;
}
//_________________________________________________
void AliAnalysisTaskPLFemto::Init()
{
//
// Initialization
//
return;
}
Bool_t AliAnalysisTaskPLFemto::GoodTPCFitMapSharedMap(const AliAODTrack *pTrack, const AliAODTrack *nTrack)
{
//This method was inherited form H. Beck analysis
// Rejects tracks with shared clusters
// This overload is used for positive and negative daughters from V0s
// Get the shared maps
const TBits posSharedMap = pTrack->GetTPCSharedMap();
const TBits negSharedMap = nTrack->GetTPCSharedMap();
if( ((posSharedMap.CountBits()) >= 1) || ((negSharedMap.CountBits()) >= 1))
{
// Bad tracks, have too many shared clusters!
return kFALSE;
}
return kTRUE;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::GoodTPCFitMapSharedMap(const AliAODTrack *track)
{
//This method was inherited form H. Beck analysis
// Rejects tracks with shared clusters
// This overload is used for primaries
// Get the shared maps
const TBits sharedMap = track->GetTPCSharedMap();
if((sharedMap.CountBits()) >= 1)
{
// Bad track, has too many shared clusters!
return kFALSE;
}
return kTRUE;
}
//________________________________________________________________________
Double_t AliAnalysisTaskPLFemto::LpCorrfunc(Double_t relk,Double_t source)
{
//Dummy Lambda-p correlation function for a simple MC study
const Double_t hbarc = 0.197;
Double_t qinv = 2. * relk;
return 1. + TMath::Exp(-pow(qinv*source,2.)/pow(hbarc,2.));
}
//________________________________________________________________________
Double_t AliAnalysisTaskPLFemto::ppCorrfunc(Double_t relk,Double_t source)
{
//Dummy p-p correlation function for a simple MC study
const Double_t hbarc = 0.197;
Double_t qinv = 2. * relk;
Double_t rectang = 0.;
if(relk > 0.4 && relk < 0.6) rectang = 2.; //artificial rectangular weighting
return 1. + TMath::Exp(-qinv*source/hbarc) + rectang; // in this momentum region the first part is zero and the rectang part survives
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::AcceptTrack(const AliAODTrack *track,int type)
{
//This method was inherited from H. Beck analysis
// Apply additional track cuts
// In the documents
// https://alisoft.cern.ch/AliRoot/trunk/TPC/doc/Definitions/Definitions.pdf
// TPC people describe the cut strategy for the TPC. It is explicitly
// stated that a cut on the number of crossed rows and a cut on the
// number of crossed rows over findable clusters is recommended to
// remove fakes. In the pdf a cut value of .83 on the ratio
// is stated, no value for the number of crossed rows. Looking at the
// AliESDtrackCuts.cxx one sees that exactly this cut is used with
// 0.8 on the ratio and 70 on the crossed rows.
// Checked the filter task and AliAODTrack and AliESDtrack and
// AliESDtrackCuts and the Definitions.pdf:
// The function to get the findable clusters is GetTPCNclsF()
// For the number fo crossed rows for ESD tracks, the function
// GetTPCCrossedRows() usually is used. Looking at the AliESDtrack.cxx
// one sees that it's just an alias (with additional caching) for
// GetTPCClusterInfo(2, 1); The identical function exists in the
// AliAODTrack.cxx
TString fillthis = "";
Float_t nCrossed = track->GetTPCClusterInfo(2,1);
UShort_t nFindableCluster = track->GetTPCNclsF();
Float_t ratio = nCrossed / Float_t(nFindableCluster);
if(type == 4)
{
fillthis = "fFindableClusterProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(nFindableCluster);
fillthis = "fNCrossedRowsProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(nCrossed);
fillthis = "fRatioFindableCrossedProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(ratio);
}
else if(type == -4)
{
fillthis = "fFindableClusterAntiProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(nFindableCluster);
fillthis = "fNCrossedRowsAntiProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(nCrossed);
fillthis = "fRatioFindableCrossedAntiProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(ratio);
}
if(nCrossed<70)
return kFALSE;
if(!track->GetTPCNclsF())
return kFALSE; // Note that the AliESDtrackCuts would here return kTRUE
if((nCrossed/track->GetTPCNclsF()) < .83)
return kFALSE;
return kTRUE;
}
//_________________________________________________
void AliAnalysisTaskPLFemto::ResetGlobalTrackReference()
{
//This method was inherited form H. Beck analysis
// Sets all the pointers to zero. To be called at
// the beginning or end of an event
for(UShort_t i=0;i<fTrackBuffSize;i++)
{
fGTI[i]=0;
}
}
//_________________________________________________
void AliAnalysisTaskPLFemto::StoreGlobalTrackReference(AliAODTrack *track)
{
//This method was inherited form H. Beck analysis
// Stores the pointer to the global track
// This was AOD073
// // Don't use the filter bits 2 (ITS standalone) and 128 TPC only
// // Remove this return statement and you'll see they don't have
// // any TPC signal
// if(track->TestFilterBit(128) || track->TestFilterBit(2))
// return;
// This is AOD086
// Another set of tracks was introduced: Global constrained.
// We only want filter bit 1 <-- NO! we also want no
// filter bit at all, which are the v0 tracks
// if(!track->TestFilterBit(1))
// return;
// There are also tracks without any filter bit, i.e. filter map 0,
// at the beginning of the event: they have ~id 1 to 5, 1 to 12
// This are tracks that didn't survive the primary track filter but
// got written cause they are V0 daughters
// Check whether the track has some info
// I don't know: there are tracks with filter bit 0
// and no TPC signal. ITS standalone V0 daughters?
// if(!track->GetTPCsignal()){
// printf("Warning: track has no TPC signal, "
// // "not adding it's info! "
// "ID: %d FilterMap: %d\n"
// ,track->GetID(),track->GetFilterMap());
// // return;
// }
// Check that the id is positive
if(track->GetID()<0)
{
// printf("Warning: track has negative ID: %d\n",track->GetID());
return;
}
// Check id is not too big for buffer
if(track->GetID()>=fTrackBuffSize)
{
printf("Warning: track ID too big for buffer: ID: %d, buffer %d\n"
,track->GetID(),fTrackBuffSize);
return;
}
// Warn if we overwrite a track
if(fGTI[track->GetID()])
{
// Seems like there are FilterMap 0 tracks
// that have zero TPCNcls, don't store these!
if( (!track->GetFilterMap()) &&
(!track->GetTPCNcls()) )
return;
// Imagine the other way around,
// the zero map zero clusters track
// is stored and the good one wants
// to be added. We ommit the warning
// and just overwrite the 'bad' track
if( fGTI[track->GetID()]->GetFilterMap() ||
fGTI[track->GetID()]->GetTPCNcls() )
{
// If we come here, there's a problem
printf("Warning! global track info already there!");
printf(" TPCNcls track1 %u track2 %u",
(fGTI[track->GetID()])->GetTPCNcls(),track->GetTPCNcls());
printf(" FilterMap track1 %u track2 %u\n",
(fGTI[track->GetID()])->GetFilterMap(),track->GetFilterMap());
}
} // Two tracks same id
// // There are tracks with filter bit 0,
// // do they have TPCNcls stored?
// if(!track->GetFilterMap()){
// printf("Filter map is zero, TPCNcls: %u\n"
// ,track->GetTPCNcls());
// }
// Assign the pointer
(fGTI[track->GetID()]) = track;
}
//_________________________________________________________________
Double_t *AliAnalysisTaskPLFemto::DCAxy(const AliAODTrack *track, const AliVEvent *evt)
{
Double_t *DCAVals = new Double_t[2];
Double_t *errorVals = new Double_t[2];
errorVals[0] = -9999.;
errorVals[1] = -9999.;
if(!track)
{
printf("Pointer to track is zero!\n");
return errorVals;
}
// Create an external parameter from the AODtrack
AliExternalTrackParam etp;
etp.CopyFromVTrack(track);
Double_t covar[3]={0.,0.,0.};
if(!etp.PropagateToDCA(evt->GetPrimaryVertex(),evt->GetMagneticField(),10.,DCAVals,covar)) return errorVals;
// return the DCAxy
delete[] errorVals;
return DCAVals;
}
//_________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::GoodDCA(const AliAODTrack *AODtrack,const AliAODEvent *aodEvent,Int_t type)
{
TString fillthis = "";
Double_t *xyz = new Double_t[2];
if(fWhichfilterbit == 128) xyz = DCAxy(fGTI[-AODtrack->GetID()-1],fInputEvent);
else xyz = DCAxy(AODtrack,fInputEvent);
if(type == 4) //proton
{
fillthis = "fProtonDCAxyDCAz";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0],xyz[1]);
fillthis = "fProtonDCAxy";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0]);
if(fabs(xyz[1])<fCuts->GetProtonDCAzCut())//check the influence of z cut on DCAxy
{
fillthis = "fProtonDCAxyCutz";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0]);
}
fillthis = "fProtonDCAz";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[1]);
//Find the pt bin for pt dependent DCA analysis:
int ptbin = fCuts->FindProtonPtBinDCA(AODtrack->Pt());
if(!fUseMCInfo && ptbin != -9999)
{
fillthis = "fProtonDCAxyDCAzPt";
fillthis += ptbin;
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0],xyz[1]);//total amount of protons in exp.
}
else if(fUseMCInfo && ptbin != -9999)
{
TClonesArray *mcarray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if(!mcarray) return kFALSE;
AliAODMCParticle* mcproton = 0;
if(AODtrack->GetLabel() >=0) mcproton = (AliAODMCParticle*)mcarray->At(AODtrack->GetLabel());
else return kFALSE;
fillthis = "fProtonDCAxyDCAzMCCase";
fillthis += 0;
fillthis += "PtBin";
fillthis += ptbin;
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0],xyz[1]);//total amount of protons
//check the DCA of the proton in Monte Carlo
if(mcproton->GetPdgCode() == 2212) //be shure it is a proton
{
if(mcproton->IsPhysicalPrimary() && !mcproton->IsSecondaryFromWeakDecay())
{
fillthis = "fProtonDCAxyDCAzMCCase";
fillthis += 1;
fillthis += "PtBin";
fillthis += ptbin;
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0],xyz[1]);//primary protons
}
else if(mcproton->IsSecondaryFromWeakDecay() && !mcproton->IsSecondaryFromMaterial())
{
fillthis = "fProtonDCAxyDCAzMCCase";
fillthis += 2;
fillthis += "PtBin";
fillthis += ptbin;
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0],xyz[1]);//secondary protons
}
else if(mcproton->IsSecondaryFromMaterial())
{
fillthis = "fProtonDCAxyDCAzMCCase";
fillthis += 3;
fillthis += "PtBin";
fillthis += ptbin;
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0],xyz[1]);//material protons
}
}
else //background
{
fillthis = "fProtonDCAxyDCAzMCCase";
fillthis += 4;
fillthis += "PtBin";
fillthis += ptbin;
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0],xyz[1]);//total amount of protons
}
}
}
else if(type == -4) //antiproton
{
fillthis = "fAntiProtonDCAxyDCAz";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0],xyz[1]);
fillthis = "fAntiProtonDCAxy";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0]);
if(fabs(xyz[1])<fCuts->GetProtonDCAzCut())//check the influence of z cut on DCAxy
{
fillthis = "fAntiProtonDCAxyCutz";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[0]);
}
fillthis = "fAntiProtonDCAz";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(xyz[1]);
}
if(fabs(xyz[0]) < fCuts->GetProtonDCAxyCut())//first cut on xy-value
{
if(fabs(xyz[1]) < fCuts->GetProtonDCAzCut())//then on z-value
{
delete[] xyz;
return kTRUE;
}
else
{
delete[] xyz;
return kFALSE;
}
}
else
{
delete[] xyz;
return kFALSE;
}
}
//________________________________________________________________________________________________
Int_t AliAnalysisTaskPLFemto::GetNumberOfTrackletsInEtaRange(AliAODEvent* ev,Double_t mineta,Double_t maxeta)
{
// counts tracklets in given eta range
AliAODTracklets* tracklets=ev->GetTracklets();
Int_t nTr=tracklets->GetNumberOfTracklets();
Int_t count=0;
for(Int_t iTr=0; iTr<nTr; iTr++)
{
Double_t theta=tracklets->GetTheta(iTr);
Double_t eta=-TMath::Log(TMath::Tan(theta/2.));
if(eta>mineta && eta<maxeta) count++;
}
TString fillthis = "fNTracklets";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(count);
return count;
}
//________________________________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::PileUpRejection(AliAODEvent* ev)
{
Bool_t isPileUp = kFALSE;
Int_t fNofTracklets = ev->GetMultiplicity()->GetNumberOfTracklets();
Int_t NofITSClusters1 = ev->GetNumberOfITSClusters(1);
TString fillthis = "fEventSPDClusterNTracklets";
((TH2F*)(fOutput->FindObject(fillthis)))->Fill(fNofTracklets,NofITSClusters1);
if(!fAnaUtils->IsPileUpEvent(ev))
{
fillthis = "fEventSPDClusterNTrackletsPileUpCut";
((TH2F*)(fOutput->FindObject(fillthis)))->Fill(fNofTracklets,NofITSClusters1);
}
return isPileUp;
}
//________________________________________________________________________________________________
Int_t *AliAnalysisTaskPLFemto::MultiplicityBinFinderzVertexBinFinder(AliAODEvent *aodEvent,Double_t zVertex)
{
Int_t *MixingBins = new Int_t[2];
Float_t multipl = GetNumberOfTrackletsInEtaRange(aodEvent,-0.8,0.8);//this is the multiplicty calculated with tracklets
if(multipl <= 0.) //multiplicity estimation fails
{
MixingBins[0] = -9999;
MixingBins[1] = -9999;
return MixingBins;
}
Int_t multBin = 0;
if(multipl <= 4) multBin = 0;
else if(multipl <= 8) multBin = 1;
else if(multipl <= 12) multBin = 2;
else if(multipl <= 16) multBin = 3;
else if(multipl <= 20) multBin = 4;
else if(multipl <= 24) multBin = 5;
else if(multipl <= 28) multBin = 6;
else if(multipl <= 32) multBin = 7;
else if(multipl <= 36) multBin = 8;
else if(multipl <= 40) multBin = 9;
else if(multipl <= 60) multBin = 10;
else if(multipl <= 80) multBin = 11;
else multBin = 12;
if(multBin+1 > kMultiplicityBins) std::cout << "Change the Multiplicity maximum" << std::endl;
Double_t deltaZ = (kZVertexStop - kZVertexStart)/(Double_t)kZVertexBins;
Int_t zVertexBin = 0;
for(Int_t i=0;i<kZVertexBins;i++)
{
if((kZVertexStart + i*deltaZ)<zVertex && zVertex<(kZVertexStart + (i+1)*deltaZ))
{
zVertexBin = i;
break;
}
}
MixingBins[0] = zVertexBin;
MixingBins[1] = multBin;
return MixingBins;
}
//_________________________________________________________________
Double_t AliAnalysisTaskPLFemto::CalcSphericityEvent(AliAODEvent *aodEvent)
{
Double_t ptTot = 0.; //total Pt of all protons and v0s in the event
Double_t s00 = 0.; //Elements of the sphericity matrix
Double_t s11 = 0.;
Double_t s10 = 0.;
Int_t numOfTracks = aodEvent->GetNumberOfTracks();
if(numOfTracks<3) return -9999.;//if already at this point not enough tracks are in the event -> return
Int_t nTracks = 0;
for(Int_t iTrack=0;iTrack<numOfTracks;iTrack++)
{
AliAODTrack *aodtrack = dynamic_cast<AliAODTrack*>(aodEvent->GetTrack(iTrack));
if(!aodtrack->TestFilterBit(fWhichfilterbit)) continue;
Double_t pt = aodtrack->Pt();
//Double_t Phi = aodtrack->Phi();
Double_t px = aodtrack->Px();
Double_t py = aodtrack->Py();
Double_t eta = aodtrack->Eta();
if(!(eta>-0.8 && eta<0.8)) continue;
if(pt<0.5) continue;
ptTot += pt;
s00 += px*px/pt;
s11 += py*py/pt;
s10 += px*py/pt;
nTracks++;
}
if(nTracks<3) return -9999.;//new flag: check
//normalize to total Pt to obtain a linear form:
if(ptTot == 0.) return -9999.;
s00 /= ptTot;
s11 /= ptTot;
s10 /= ptTot;
//Calculate the trace of the sphericity matrix:
Double_t T = s00+s11;
//Calculate the determinant of the sphericity matrix:
Double_t D = s00*s11 - s10*s10;//S10 = S01
//Calculate the eigenvalues of the sphericity matrix:
Double_t lambda1 = 0.5*(T + TMath::Sqrt(T*T - 4.*D));
Double_t lambda2 = 0.5*(T - TMath::Sqrt(T*T - 4.*D));
if((lambda1 + lambda2) == 0.) return -9999.;
Double_t ST = -1.;
if(lambda2>lambda1)
{
ST = 2.*lambda1/(lambda1+lambda2);
}
else
{
ST = 2.*lambda2/(lambda1+lambda2);
}
return ST;
}
//_________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::CheckGlobalTrack(const AliAODTrack *track)
{
//Checks if to the corresponding track a global track exists
//This is especially useful if one has TPC only tracks and needs the PID information
Bool_t isGlobal = kTRUE;
if(!(fGTI[-track->GetID()-1])) isGlobal = kFALSE;
return isGlobal;
}
//_________________________________________________________________
Float_t AliAnalysisTaskPLFemto::GetCorrectedTOFSignal(const AliVTrack *track,const AliAODEvent *aodevent)
{
// Return the corrected TOF signal, see https://twiki.cern.ch/twiki/bin/viewauth/ALICE/TOF
// Check for the global track
/*
if(fWhichfilterbit == 128 && !(fGTI[-track->GetID()-1]))
{
printf("Warning: no corresponding global track found!\n");
return -9999.;
}
*/
// Request the TOFpid bit
//AliPIDResponse::EDetPidStatus statusTOF = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF,fGTI[-track->GetID()-1]);
AliPIDResponse::EDetPidStatus statusTOF = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF,track);
if(statusTOF != AliPIDResponse::kDetPidOk) return -9999.;
// The expected time
Double_t expectedTimes[AliPID::kSPECIES];
//Double_t expectedTimes[AliPID::kProton];
//(fGTI[-track->GetID()-1])->GetIntegratedTimes(expectedTimes);
// Check for TOF header
if(aodevent->GetTOFHeader())
{
// New AODs without start time subtraction
//return ((fGTI[-track->GetID()-1])->GetTOFsignal() - expectedTimes[AliPID::kProton] - fPIDResponse->GetTOFResponse().GetStartTime(track->P()));
return (track->GetTOFsignal() - expectedTimes[AliPID::kProton] - fPIDResponse->GetTOFResponse().GetStartTime(track->P()));
}
// Old AODs with start time already subtracted
//return ((fGTI[-track->GetID()-1])->GetTOFsignal() - expectedTimes[AliPID::kProton]);
return (track->GetTOFsignal() - expectedTimes[AliPID::kProton]);
}
//_________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::SingleParticleQualityCuts(const AliAODTrack *aodtrack,const AliAODEvent *aodEvent)
{
Double_t eta = aodtrack->Eta();
Double_t pt = aodtrack->Pt();
Double_t ch = aodtrack->Charge();
if(ch>0)//protons
{
if(fabs(eta) > fCuts->GetProtonEtaRange()) return kFALSE; //should lie within the ALICE acceptance
if(pt < fCuts->GetProtonPIDthrPtLow()) return kFALSE;
if(pt > fCuts->GetProtonPIDthrPtUp()) return kFALSE;
if(!GoodTPCFitMapSharedMap(aodtrack)) return kFALSE;// Reject tracks with shared clusters
if(aodtrack->GetTPCNcls()<fCuts->GetProtonTPCCluster()) return kFALSE;
//Accept track should be here
if(!AcceptTrack(aodtrack,4)) return kFALSE;//reject tracks with row crossing
if(!(SelectPID(aodtrack,aodEvent,4))) return kFALSE; //select protons
if(!GoodDCA(aodtrack,aodEvent,4)) return kFALSE; //to increase the probability for primaries
}
else
{
if(fabs(eta) > fCuts->GetProtonEtaRange()) return kFALSE; //should lie within the ALICE acceptance
if(pt < fCuts->GetProtonPIDthrPtLow()) return kFALSE;
if(pt > fCuts->GetProtonPIDthrPtUp()) return kFALSE;;
if(!GoodTPCFitMapSharedMap(aodtrack)) return kFALSE;// Reject tracks with shared clusters
if(aodtrack->GetTPCNcls()<fCuts->GetProtonTPCCluster()) return kFALSE;
//Accept track should be here
if(!AcceptTrack(aodtrack,-4)) return kFALSE;//reject tracks with row crossing
if(!(SelectPID(aodtrack,aodEvent,-4))) return kFALSE; //select protons
if(!GoodDCA(aodtrack,aodEvent,-4)) return kFALSE; //to increase the probability for primaries
}
return kTRUE;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::SingleParticleQualityCuts(const AliAODv0 *v0)
{
AliAODTrack *posTrack = fGTI[v0->GetPosID()];
AliAODTrack *negTrack = fGTI[v0->GetNegID()];
Double_t poseta = posTrack->Eta();
Double_t negeta = negTrack->Eta();
Double_t posTPCcls = posTrack->GetTPCNcls();
Double_t negTPCcls = negTrack->GetTPCNcls();
if(v0->GetNDaughters() != 2) return kFALSE;
if(v0->GetNProngs() != 2) return kFALSE;
if(v0->GetCharge() != 0) return kFALSE;
if(posTPCcls < fCuts->GetV0TPCCluster()) return kFALSE;
if(negTPCcls < fCuts->GetV0TPCCluster()) return kFALSE;
if(fabs(poseta) > fCuts->GetV0EtaRange()) return kFALSE;
if(fabs(negeta) > fCuts->GetV0EtaRange()) return kFALSE;
if(v0->Pt() < fCuts->GetV0PIDthrPtLow()) return kFALSE; //below it just enhances background
return kTRUE;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::ProtonSelector(AliAODEvent *aodEvent)
{
fProtonCounter = 0;
fAntiProtonCounter = 0;
for(Int_t iTrack=0;iTrack<aodEvent->GetNumberOfTracks();iTrack++)
{
AliAODTrack *track = dynamic_cast<AliAODTrack*>(aodEvent->GetTrack(iTrack));
if(!track)
{
AliFatal("Not a standard AOD");
continue;
}
TString fillthis = "";
//Several selections
//if(!(track->GetType() == AliAODTrack::kPrimary)) continue; //should select primary tracks (effect?)
if(fWhichfilterbit == 128 && (-track->GetID()-1 >= fTrackBuffSize)) continue; //check if the fGTI array is not too small
if(!track->TestFilterBit(fWhichfilterbit)) continue;
if(fWhichfilterbit == 128 && !CheckGlobalTrack(track)) continue; //Does a global track exist for the TPC only track?
//to select only good track conditions (very strict):
//does only work with filterbit(128) commented out?
//if((!(track->GetStatus() & AliESDtrack::kITSrefit) || (!(track->GetStatus() & AliESDtrack::kTPCrefit)))) continue;
//if(!(track->GetStatus()&AliESDtrack::kTPCrefit)) continue;
Double_t charge = track->Charge();
if(charge>0.)
{
if(fProtonCounter > kProtonTrackLimit) continue;
if(!SingleParticleQualityCuts(track,aodEvent)) continue;//Define additional quality criteria
//fill proton parameters:
//____________________________________________
fProtoncand[fProtonCounter].fPt = track->Pt();
fProtoncand[fProtonCounter].fMomentum.SetXYZ(track->Px(),track->Py(),track->Pz());
if(fWhichfilterbit == 128) fProtoncand[fProtonCounter].fID = (fGTI[-track->GetID()-1])->GetID();
else fProtoncand[fProtonCounter].fID = track->GetID();
fProtoncand[fProtonCounter].fEta = track->Eta();
GetGlobalPositionAtGlobalRadiiThroughTPC(track,aodEvent->GetMagneticField(),fProtoncand[fProtonCounter].fPrimPosTPC,fPrimVertex);
//calculate phi* to check for possible merging/splitting effects:
for(int radius=0;radius<9;radius++)
{
fProtoncand[fProtonCounter].fPhistar[radius] = PhiS(track,aodEvent->GetMagneticField(),fTPCradii[radius]);
}
fillthis = "fNProtonsTot";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1);
fillthis = "fProtonPt";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(track->Pt());
fillthis = "fProtonPhi";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(track->Phi());
fillthis = "fProtonEta";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(track->Eta());
//Monte Carlo
if(fUseMCInfo)
{
if(CheckMCPID(aodEvent,track,2212)) fProtoncand[fProtonCounter].fReal = kTRUE;
else fProtoncand[fProtonCounter].fReal = kFALSE;
//Monte Carlo functions:
GetProtonOrigin(track,aodEvent,4);//evaluated with all the cuts applied
double protontruth[3] = {-9999,-9999.,-9999.};
double protontruth_mother[3] = {-9999,-9999.,-9999.};
double protontruth_motherParton[3] = {-9999,-9999.,-9999.};
int PDGcodes[3] = {-9999,-9999,-9999};
GetMCMomentum(track,protontruth,protontruth_mother,protontruth_motherParton,PDGcodes,aodEvent,4);
fProtoncand[fProtonCounter].fMomentumMC.SetXYZ(protontruth[0],protontruth[1],protontruth[2]);
fProtoncand[fProtonCounter].fMomentumMCMother.SetXYZ(protontruth_mother[0],protontruth_mother[1],protontruth_mother[2]);
fProtoncand[fProtonCounter].fMomentumMCMotherParton.SetXYZ(protontruth_motherParton[0],protontruth_motherParton[1],protontruth_motherParton[2]);
if(PDGcodes[0] != -9999) fProtoncand[fProtonCounter].fPDGCodeMother = PDGcodes[0];
else fProtoncand[fProtonCounter].fPDGCodeMother = 0;
if(PDGcodes[1] != -9999 && PDGcodes[2] != -9999)
{
fProtoncand[fProtonCounter].fPDGCodePartonMother = PDGcodes[1];
fProtoncand[fProtonCounter].fPartonMotherLabel = PDGcodes[2];
}
else
{
fProtoncand[fProtonCounter].fPDGCodePartonMother = 0;
fProtoncand[fProtonCounter].fPartonMotherLabel = 0;
}
}
else
{
fProtoncand[fProtonCounter].fMomentumMC.SetXYZ(-9999.,-9999.,-9999.);
fProtoncand[fProtonCounter].fMomentumMCMother.SetXYZ(-9999.,-9999.,-9999.);
fProtoncand[fProtonCounter].fPDGCodePartonMother = -9999;
fProtoncand[fProtonCounter].fPartonMotherLabel = -9999;
}
fProtonCounter++;
}
else // Antiprotons
{
if(fAntiProtonCounter > kProtonTrackLimit) continue;
if(!SingleParticleQualityCuts(track,aodEvent)) continue;//Define additional quality criteria
//fill Anti-proton parameters:
//____________________________________________
fAntiProtoncand[fAntiProtonCounter].fPt = track->Pt();
fAntiProtoncand[fAntiProtonCounter].fMomentum.SetXYZ(track->Px(),track->Py(),track->Pz());
if(fWhichfilterbit == 128) fAntiProtoncand[fAntiProtonCounter].fID = (fGTI[-track->GetID()-1])->GetID();
else fAntiProtoncand[fAntiProtonCounter].fID = track->GetID();
fAntiProtoncand[fAntiProtonCounter].fEta = track->Eta();
if(fUseMCInfo)
{
//Monte Carlo functions:
GetProtonOrigin(track,aodEvent,-4);//evaluated with all the cuts applied
double antiprotontruth[3] = {-9999,-9999.,-9999.};
double antiprotontruth_mother[3] = {-9999,-9999.,-9999.};
double antiprotontruth_motherParton[3] = {-9999,-9999.,-9999.};
int PDGcodes[3] = {-9999,-9999,-9999};
GetMCMomentum(track,antiprotontruth,antiprotontruth_mother,antiprotontruth_motherParton,PDGcodes,aodEvent,-4);
fAntiProtoncand[fAntiProtonCounter].fMomentumMC.SetXYZ(antiprotontruth[0],antiprotontruth[1],antiprotontruth[2]);
fAntiProtoncand[fAntiProtonCounter].fMomentumMCMother.SetXYZ(antiprotontruth_mother[0],antiprotontruth_mother[1],antiprotontruth_mother[2]);
fAntiProtoncand[fAntiProtonCounter].fMomentumMCMotherParton.SetXYZ(antiprotontruth_motherParton[0],antiprotontruth_motherParton[1],antiprotontruth_motherParton[2]);
if(PDGcodes[0] != -9999) fAntiProtoncand[fAntiProtonCounter].fPDGCodeMother = PDGcodes[0];
else fProtoncand[fAntiProtonCounter].fPDGCodeMother = 0;
if(PDGcodes[1] != -9999 && PDGcodes[2] != -9999)
{
fAntiProtoncand[fAntiProtonCounter].fPDGCodePartonMother = PDGcodes[1];
fAntiProtoncand[fAntiProtonCounter].fPartonMotherLabel = PDGcodes[2];
}
else
{
fAntiProtoncand[fAntiProtonCounter].fPDGCodePartonMother = 0;
fAntiProtoncand[fAntiProtonCounter].fPartonMotherLabel = 0;
}
}
else
{
fAntiProtoncand[fAntiProtonCounter].fMomentumMC.SetXYZ(-9999.,-9999.,-9999.);
fAntiProtoncand[fAntiProtonCounter].fMomentumMCMother.SetXYZ(-9999.,-9999.,-9999.);
fAntiProtoncand[fAntiProtonCounter].fPDGCodePartonMother = -9999;
fAntiProtoncand[fAntiProtonCounter].fPartonMotherLabel = -9999;
}
//GetGlobalPositionAtGlobalRadiiThroughTPC(track,aodEvent->GetMagneticField(),fAntiProtoncand[fAntiProtonCounter].fPrimPosTPC,fPrimVertex);
fAntiProtonCounter++;
fillthis = "fNAntiProtonsTot";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1);
fillthis = "fAntiProtonPt";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(track->Pt());
}
}
//LOOP END (PRIMARY) PROTONS_____________________________________________________________
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::V0Selector(AliAODEvent *aodEvent)
{
TString fillthis = "";
fV0Counter = 0;//how many V0 candidates do we have in this event?
fAntiV0Counter = 0;//how many Anti-V0 candidates do we have in this event?
//Get a V0 from the event:
TClonesArray *v01 = (TClonesArray*)aodEvent->GetV0s();
//number of V0s:
Int_t entriesV0= v01->GetEntriesFast();
for(Int_t i=0; i<entriesV0; i++)
{
AliAODv0 *v0 = aodEvent->GetV0(i);
if(!v0) continue;
if(v0->GetNProngs()>2) continue;
if(fOnlineV0)
{
if(!(v0->GetOnFlyStatus())) continue; //online v0
}
else
{
if((v0->GetOnFlyStatus())) continue; //offline v0
}
// Check that the array fGTI isn't too small
// for the track ids
if(v0->GetPosID() >= fTrackBuffSize || v0->GetNegID() >= fTrackBuffSize) continue;
// This is AODs: find the track for given id:
AliAODTrack *pTrack = fGTI[v0->GetPosID()];
AliAODTrack *nTrack = fGTI[v0->GetNegID()];
if((!pTrack) || (!nTrack)) continue;
if(!SingleParticleQualityCuts(v0)) continue;
if(SelectV0PID(v0,fwhichV0))//V0 selection
{
FillV0Selection(v0,aodEvent,fwhichV0);
}
else if(SelectV0PID(v0,fwhichAntiV0))//Anti-V0 selection
{
FillV0Selection(v0,aodEvent,fwhichAntiV0);
}
}
}
//_______________________________________________________________________
void AliAnalysisTaskPLFemto::XiSelector(AliAODEvent *aodEvent)
{
TString fillthis = "";
//fV0Counter = 0;//how many V0 candidates do we have in this event?
//fAntiV0Counter = 0;//how many Anti-V0 candidates do we have in this event?
//Get a V0 from the event:
TClonesArray *Xicand = (TClonesArray*)aodEvent->GetCascades();
//number of V0s:
Int_t entriesXi= Xicand->GetEntriesFast();
Double_t xvP = aodEvent->GetPrimaryVertex()->GetX();
Double_t yvP = aodEvent->GetPrimaryVertex()->GetY();
Double_t zvP = aodEvent->GetPrimaryVertex()->GetZ();
fXiCounter = 0;
for (Int_t i=0; i<entriesXi; i++)
{
AliAODcascade *Xi = aodEvent->GetCascade(i);
Double_t pointXi = Xi->CosPointingAngleXi(xvP,yvP,zvP);
if(!Xi) continue;
if(Xi->ChargeXi() > 0)
{
}
else if(Xi->ChargeXi() < 0)
{
Double_t massXi = Xi->MassXi();
AliAODTrack* pTrack = fGTI[Xi->GetPosID()];
AliAODTrack* nTrack1 = fGTI[Xi->GetBachID()];
AliAODTrack* nTrack2 = fGTI[Xi->GetNegID()];
if((pTrack->GetID() == nTrack1->GetID()) || (pTrack->GetID() == nTrack2->GetID()) || (nTrack1->GetID() == nTrack2->GetID())) continue;
Int_t posTPCcluster = pTrack->GetTPCNcls();
Int_t negTPCcluster1 = nTrack1->GetTPCNcls();
Int_t negTPCcluster2 = nTrack2->GetTPCNcls();
if(posTPCcluster < 70) continue;
if(negTPCcluster1 < 70) continue;
if(negTPCcluster2 < 70) continue;
fillthis = "fXiInvMasswoCuts";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(massXi);
//Do a rough PID for all daughter tracks:
AliPIDResponse::EDetPidStatus statusPosTPC = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTPC,pTrack);
if(statusPosTPC != AliPIDResponse::kDetPidOk) continue;
AliPIDResponse::EDetPidStatus statusNegTPC1 = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTPC,nTrack1);
if(statusNegTPC1 != AliPIDResponse::kDetPidOk) continue;
AliPIDResponse::EDetPidStatus statusNegTPC2 = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTPC,nTrack2);
if(statusNegTPC2 != AliPIDResponse::kDetPidOk) continue;
Double_t nSigmaProtonTPC = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(pTrack,(AliPID::kProton)));
Double_t nSigmaPionTPC1 = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(nTrack1,(AliPID::kPion)));
Double_t nSigmaPionTPC2 = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(nTrack2,(AliPID::kPion)));
if(nSigmaProtonTPC > 5.) continue;
if(nSigmaPionTPC1 > 5.) continue;
if(nSigmaPionTPC2 > 5.) continue;
if(pointXi<0.98) continue;
Double_t MassV0 = Xi->MassLambda();
fillthis = "fXiInvMassLambda";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassV0);
if(!(MassV0>(fCuts->GetHadronMasses(3122)-fCuts->GetV0PID_width()) && MassV0<(fCuts->GetHadronMasses(3122)+fCuts->GetV0PID_width()))) continue;
fillthis = "fXiInvMasswCuts";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(massXi);
if(massXi>(fCuts->GetHadronMasses(3312)-0.005) && massXi<(fCuts->GetHadronMasses(3312)+0.005))
{
fXicand[fXiCounter].fPt = Xi->Pt();
fXicand[fXiCounter].fMass = massXi;
fXicand[fXiCounter].fDaughterID1 = Xi->GetPosID();
fXicand[fXiCounter].fDaughterID2 = Xi->GetNegID();
fXicand[fXiCounter].fBachID = Xi->GetBachID();
fXicand[fXiCounter].fXitag = kTRUE;//considered as a good Xi candidate
fXicand[fXiCounter].fPointing = pointXi;
fXicand[fXiCounter].fMomentum.SetXYZ(Xi->Px(),Xi->Py(),Xi->Pz());
fXiCounter++;
}
}
}
}
//_______________________________________________________________________
void AliAnalysisTaskPLFemto::FIFOShifter(Int_t zBin,Int_t MultBin)
{
//Load the stuff into the buffer:
//be careful we load only the tracks from this event in the buffer but
//the objects fV0cand and fProtoncand are not deleted: they may have information from the last event for i>fV0Counter stored
fEC[zBin][MultBin]->FIFOShift();
(fEvt) = fEC[zBin][MultBin]->fEvt;
(fEvt)->fFillStatus = 1;
(fEvt)->fMultBin = MultBin;
(fEvt)->fSphericity = fSphericityvalue;
(fEvt)->fEventNumber = fEventNumber;
fEC[zBin][MultBin]->fNumEvents++;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::TrackCleaner()
{
TString fillthis = "";
//Cleaning for V0: There is a probability that two V0s in an event share the same tracks
Int_t nDoubleShare = 0;
if(fV0Counter>1)
{
//A procedure that controls that we have different V0s:
for(Int_t i=0;i<fV0Counter;i++)
{
if(!fV0cand[i].fV0tag) continue; //already tagged as bad, must not be tested
for(Int_t j=i+1;j<fV0Counter;j++)
{
if(!fV0cand[j].fV0tag) continue; //already tagged as bad, must not be tested
if((fV0cand[i].fDaughterID1 == fV0cand[j].fDaughterID2) || (fV0cand[i].fDaughterID2 == fV0cand[j].fDaughterID1) //crossing, should be excluded already at PID level
|| (fV0cand[i].fDaughterID1 == fV0cand[j].fDaughterID1) || (fV0cand[i].fDaughterID2 == fV0cand[j].fDaughterID2))//same
{
nDoubleShare++;
if(fV0cand[i].fPointing > fV0cand[j].fPointing) fV0cand[j].fV0tag = kFALSE;//V0_i is "more primary" than V0_j
else fV0cand[i].fV0tag = kFALSE;
}
}
}
}
if(nDoubleShare>0)
{
fillthis = "fNV0TrackSharing";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(nDoubleShare);
}
nDoubleShare = 0;
//Same for Anti V0
if(fAntiV0Counter>1)
{
//A procedure that controls that we have different Anti-V0s:
for(Int_t i=0;i<fAntiV0Counter;i++)
{
if(!fAntiV0cand[i].fV0tag) continue; //already tagged as bad, must not be tested
for(Int_t j=i+1;j<fAntiV0Counter;j++)
{
if(!fAntiV0cand[j].fV0tag) continue; //already tagged as bad, must not be tested
if((fAntiV0cand[i].fDaughterID1 == fAntiV0cand[j].fDaughterID2) || (fAntiV0cand[i].fDaughterID2 == fAntiV0cand[j].fDaughterID1) //crossing, should be excluded already at PID level
|| (fAntiV0cand[i].fDaughterID1 == fAntiV0cand[j].fDaughterID1) || (fAntiV0cand[i].fDaughterID2 == fAntiV0cand[j].fDaughterID2))//same
{
nDoubleShare++;
if(fAntiV0cand[i].fPointing > fAntiV0cand[j].fPointing) fAntiV0cand[j].fV0tag = kFALSE;
else fAntiV0cand[i].fV0tag = kFALSE;
}
}
}
}
if(nDoubleShare>0)
{
fillthis = "fNAntiV0TrackSharing";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(nDoubleShare);
}
//Now check that the proton from V0 and the primary proton are not the same
for(int i=0; i<fV0Counter;i++)
{
if(!fV0cand[i].fV0tag) continue; //already tagged as bad, must not be tested
for(int j=0; j<fProtonCounter;j++)
{
if((fV0cand[i].fDaughterID1 == fProtoncand[j].fID) || (fV0cand[i].fDaughterID2 == fProtoncand[j].fID))
{
//Then mark the V0 as bad because the probability is larger that it was a primary proton wrongly paired to a V0
fV0cand[i].fV0tag = kFALSE;
fillthis = "fNV0protonSharedTracks";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1);
}
}
}
//Check that Anti-V0 and proton don't share tracks
for(int i=0; i<fAntiV0Counter;i++)
{
if(!fAntiV0cand[i].fV0tag) continue; //already tagged as bad, must not be tested
for(int j=0; j<fProtonCounter;j++)
{
if((fAntiV0cand[i].fDaughterID1 == fProtoncand[j].fID) || (fAntiV0cand[i].fDaughterID2 == fProtoncand[j].fID))
{
//Then mark the Anti-V0 as bad because the probability is larger that it was a primary proton wrongly paired to a V0
fAntiV0cand[i].fV0tag = kFALSE;
fillthis = "fNAntiV0protonSharedTracks";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1);
}
}
}
//Check that Anti-Proton and Anti-V0 don't share tracks
for(int i=0; i<fAntiV0Counter;i++)
{
if(!fAntiV0cand[i].fV0tag) continue; //already tagged as bad, must not be tested
for(int j=0; j<fAntiProtonCounter;j++)
{
if((fAntiV0cand[i].fDaughterID1 == fAntiProtoncand[j].fID) || (fAntiV0cand[i].fDaughterID2 == fAntiProtoncand[j].fID))
{
//Then mark the Anti-V0 as bad because the probability is larger that it was a primary proton wrongly paired to a V0
fAntiV0cand[i].fV0tag = kFALSE;
fillthis = "fNAntiV0AntiprotonSharedTracks";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1);
}
}
}
//Check that Xi and proton don't share tracks
for(int i=0; i<fXiCounter;i++)
{
if(!fXicand[i].fXitag) continue; //already tagged as bad, must not be tested
for(int j=0; j<fProtonCounter;j++)
{
if((fXicand[i].fDaughterID1 == fProtoncand[j].fID) || (fXicand[i].fDaughterID2 == fProtoncand[j].fID) || (fXicand[i].fBachID == fProtoncand[j].fID))
{
fXicand[i].fXitag = kFALSE;
}
}
}
}
//________________________________________________________________________
Int_t *AliAnalysisTaskPLFemto::BufferFiller()
{
TString fillthis = "";
Int_t *NumberOfParticles = new Int_t[2];
//Fill V0 candidates in EventCollection:
Int_t tempV0Counter = 0;
for(int i=0;i<fV0Counter;i++)
{
//one can include additional cuts for V0s at this position
if(fV0cand[i].fV0tag) //use only V0s which have a good tag (unique V0s without track sharing with other V0s in the sample)
{
fillthis = "fNLambdasTot";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(2); //fill only unique candidates
(fEvt)->fLambdaParticle[tempV0Counter] = fV0cand[i];
if(fProtonCounter>0)
{
fillthis = "fNLambdasTot";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(3); //fill only unique candidates
}
tempV0Counter++;
}
}
Int_t tempAntiV0Counter = 0;
for(int i=0;i<fAntiV0Counter;i++)
{
//one can include additional cuts for V0s at this position
if(fAntiV0cand[i].fV0tag) //use only V0s which have a good tag (unique V0s without track sharing with other V0s in the sample)
{
(fEvt)->fAntiLambdaParticle[tempAntiV0Counter] = fAntiV0cand[i];
fillthis = "fNAntiLambdasTot";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(2); //fill only unique candidates
if(fAntiProtonCounter>0)
{
fillthis = "fNAntiLambdasTot";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(3); //fill only unique candidates
}
tempAntiV0Counter++;
}
}
//Fill Proton candidates in EventCollection:
Int_t tempProtonCounter = 0;
for(Int_t i=0;i<fProtonCounter;i++)
{
//at this point you can include some cuts
(fEvt)->fProtonParticle[i] = fProtoncand[i];
tempProtonCounter++;
}
//Fill Anti-Proton candidates in EventCollection:
Int_t tempAntiProtonCounter = 0;
for(Int_t i=0;i<fAntiProtonCounter;i++)
{
(fEvt)->fAntiProtonParticle[i] = fAntiProtoncand[i];
tempAntiProtonCounter++;
}
Int_t tempXiCounter = 0;
for(int i=0;i<fXiCounter;i++)
{
if(fXicand[i].fXitag)
{
(fEvt)->fXiParticle[tempXiCounter] = fXicand[i];
tempXiCounter++;
}
}
(fEvt)->fNumV0s = tempV0Counter;
(fEvt)->fNumAntiV0s = tempAntiV0Counter;
(fEvt)->fNumProtons = tempProtonCounter;
(fEvt)->fNumAntiProtons = tempAntiProtonCounter;
(fEvt)->fNumXis = tempXiCounter;
NumberOfParticles[0] = tempV0Counter;
NumberOfParticles[1] = tempProtonCounter;
return NumberOfParticles;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::ParticlePairer()
{
Int_t NPairs = 0;
//Loop for p-V0:
for(int i=0; i<(fEvt)->fNumV0s;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
for(int j=0; j<(fEvt+evnum)->fNumProtons;j++)
{
if(evnum == 0) NPairs++;
PairAnalysis((fEvt)->fLambdaParticle[i],(fEvt+evnum)->fProtonParticle[j],evnum,kProtonV0);
}//Proton Loop
}//event Loop
}//V0 Loop
TString fillthis = "fNProtonLambdaPairs";
if(NPairs !=0) ((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(NPairs);
//Loop for p-AntiV0
for(int i=0; i<(fEvt)->fNumAntiV0s;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
for(int j=0; j<(fEvt+evnum)->fNumProtons;j++)
{
PairAnalysis((fEvt)->fAntiLambdaParticle[i],(fEvt+evnum)->fProtonParticle[j],evnum,kProtonAntiV0);
}//Proton Loop
}//event Loop
}//V0 Loop
//Loop for Antip-V0
for(int i=0; i<(fEvt)->fNumV0s;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
for(int j=0; j<(fEvt+evnum)->fNumAntiProtons;j++)
{
PairAnalysis((fEvt)->fLambdaParticle[i],(fEvt+evnum)->fAntiProtonParticle[j],evnum,kAntiProtonV0);
}//AntiProton Loop
}//event Loop
}//V0 Loop
//Loop for Antip-AntiV0
for(int i=0; i<(fEvt)->fNumAntiV0s;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
for(int j=0; j<(fEvt+evnum)->fNumAntiProtons;j++)
{
PairAnalysis((fEvt)->fAntiLambdaParticle[i],(fEvt+evnum)->fAntiProtonParticle[j],evnum,kAntiProtonAntiV0);
}//Proton Loop
}//event Loop
}//V0 Loop
/*
for(int i=0; i<(fEvt)->fNumV0s;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
int secevent = 0;
if(evnum>0) secevent=evnum+1;//for mixed event take always different events and avoid combinations like 1-2-3, 1-3-2, which leads to double counting
for(int evnum2 = secevent; evnum2<kEventsToMix+1; evnum2++)
{
for(int j=0; j<(fEvt+evnum)->fNumProtons;j++)
{
int startevent = 0;
if(evnum==0 && evnum2 == 0) startevent = j+1;
for(int k=startevent; k<(fEvt+evnum2)->fNumProtons;k++)
{
TripleAnalysis((fEvt)->fLambdaParticle[i],(fEvt+evnum)->fProtonParticle[j],(fEvt+evnum2)->fProtonParticle[k],evnum+evnum2,kProtonProtonV0);
}
}
}
}
}
*/
//Loop for p-p
for(int i=0; i<(fEvt)->fNumProtons;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
int startbin = 0;
if(evnum==0)
{
startbin=i+1;
if((fEvt)->fProtonParticle[i].fID == (fEvt+evnum)->fProtonParticle[startbin].fID) continue;
}
for(int j=startbin;j<(fEvt+evnum)->fNumProtons;j++)
{
PairAnalysis((fEvt)->fProtonParticle[i],(fEvt+evnum)->fProtonParticle[j],evnum,kProtonProton);
}//ProtonA Loop
}//event Loop
}//ProtonB Loop
//Loop for Antip-Antip
for(int i=0; i<(fEvt)->fNumAntiProtons;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
int startbin = 0;
if(evnum==0)
{
startbin=i+1;
if((fEvt)->fAntiProtonParticle[i].fID == (fEvt+evnum)->fAntiProtonParticle[startbin].fID) continue;
}
for(int j=startbin; j<(fEvt+evnum)->fNumAntiProtons;j++)
{
PairAnalysis((fEvt)->fAntiProtonParticle[i],(fEvt+evnum)->fAntiProtonParticle[j],evnum,kAntiProtonAntiProton);
}//AntiProtonA Loop
}//event Loop
}//AntiProtonB Loop
//Loop for Antip-p
for(int i=0; i<(fEvt)->fNumProtons;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
for(int j=0; j<(fEvt+evnum)->fNumAntiProtons;j++)
{
if(evnum==0)
{
if((fEvt)->fProtonParticle[i].fID == (fEvt+evnum)->fAntiProtonParticle[j].fID) continue; //should only be set for same events
}
PairAnalysis((fEvt)->fProtonParticle[i],(fEvt+evnum)->fAntiProtonParticle[j],evnum,kAntiProtonProton);
}//AntiProton Loop
}//event Loop
}//Proton Loop
//Loop for p-Xi
for(int i=0; i<(fEvt)->fNumXis;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
for(int j=0; j<(fEvt+evnum)->fNumProtons;j++)
{
PairAnalysis((fEvt)->fXiParticle[i],(fEvt+evnum)->fProtonParticle[j],evnum,kProtonXi);
}//Proton Loop
}//event Loop
}//Xi Loop
//Loop for Antip-Xi
for(int i=0; i<(fEvt)->fNumXis;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
for(int j=0; j<(fEvt+evnum)->fNumAntiProtons;j++)
{
PairAnalysis((fEvt)->fXiParticle[i],(fEvt+evnum)->fAntiProtonParticle[j],evnum,kAntiProtonXi);
}//AntiProton Loop
}//event Loop
}//Xi Loop
/*
for(int i=0; i<(fEvt)->fNumProtons;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
int secevent = 0;
if(evnum>0) secevent=evnum+1;//for mixed event take always different events and avoid combinations like 1-2-3, 1-3-2, which leads to double counting
for(int evnum2 = secevent; evnum2<kEventsToMix+1; evnum2++)
{
int startparticle1 = 0;
if(evnum==0 && evnum2 == 0) startparticle1 = i+1;
for(int j=startparticle1; j<(fEvt+evnum)->fNumProtons;j++)
{
int startparticle2 = 0;
if(evnum==0 && evnum2 == 0) startparticle2 = j+1;
for(int k=startparticle2; k<(fEvt+evnum2)->fNumProtons;k++)
{
TripleAnalysis((fEvt)->fProtonParticle[i],(fEvt+evnum)->fProtonParticle[j],(fEvt+evnum2)->fProtonParticle[k],evnum+evnum2,kProtonProtonProton);
}
}
}
}
}
*/
//Loop for V0-V0
for(int i=0; i<(fEvt)->fNumV0s;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
int startbin = 0;
if(evnum==0) startbin=i+1;
for(int j=startbin; j<(fEvt+evnum)->fNumV0s;j++)
{
PairAnalysis((fEvt)->fLambdaParticle[i],(fEvt+evnum)->fLambdaParticle[j],evnum,kV0V0);
}//Proton Loop
}//event Loop
}//V0 Loop
//Loop for AntiV0-AntiV0
for(int i=0; i<(fEvt)->fNumAntiV0s;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
int startbin = 0;
if(evnum==0) startbin=i+1;
for(int j=startbin; j<(fEvt+evnum)->fNumAntiV0s;j++)
{
PairAnalysis((fEvt)->fAntiLambdaParticle[i],(fEvt+evnum)->fAntiLambdaParticle[j],evnum,kAntiV0AntiV0);
}//Proton Loop
}//event Loop
}//V0 Loop
//Loop for AntiV0-V0
for(int i=0; i<(fEvt)->fNumAntiV0s;i++)
{
for(int evnum=0; evnum<kEventsToMix+1; evnum++)
{
for(int j=0; j<(fEvt+evnum)->fNumV0s;j++)
{
PairAnalysis((fEvt)->fAntiLambdaParticle[i],(fEvt+evnum)->fLambdaParticle[j],evnum,kAntiV0V0);
}//Proton Loop
}//event Loop
}//V0 Loop
//calculate decay matrix for residual correlations:
//we take it from another model
//CalculateDecayMatrix();
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::CalculateDecayMatrix()
{
//Calculate decay matrices from monte carlo:
if(fUseMCInfo)
{
Bool_t proton_from_weak = kFALSE;
Bool_t lambda_from_weak = kFALSE;
//This vectors are needed to obtain the matrix:
std::vector<AliFemtoProtonParticle> proton_vec;
std::vector<AliFemtoProtonParticle> proton_from_weak_vec;
std::vector<AliFemtoLambdaParticle> lambda_from_weak_vec;
//Protons feed down correlations:
if((fEvt)->fNumProtons>1)
{
for(int i=0;i<(fEvt)->fNumProtons;i++)
{
if((fEvt)->fProtonParticle[i].fPDGCodeMother>0)
{
proton_from_weak = kTRUE;
proton_from_weak_vec.push_back((fEvt)->fProtonParticle[i]);
}
else
{
proton_vec.push_back((fEvt)->fProtonParticle[i]);
}
}
if(proton_from_weak && proton_from_weak_vec.size() == 1) //Only one feed down proton
{
for(std::vector<AliFemtoProtonParticle>::iterator protonA = proton_vec.begin(); protonA != proton_vec.end(); protonA++)
{
for(std::vector<AliFemtoProtonParticle>::iterator protonB = proton_from_weak_vec.begin(); protonB != proton_from_weak_vec.end(); protonB++)//treat this proton as a "weak resonance"
{
//GetDecayMatrix(*protonA,*protonB);
}
}
}
}
proton_vec.clear();
proton_from_weak_vec.clear();
//Lambdas feed down correlations:
if((fEvt)->fNumProtons>0 && (fEvt)->fNumV0s>0)
{
for(int i=0;i<(fEvt)->fNumV0s;i++)
{
if((fEvt)->fLambdaParticle[i].fPDGCodeMother>0)
{
lambda_from_weak = kTRUE;
lambda_from_weak_vec.push_back((fEvt)->fLambdaParticle[i]);
}
}
for(int i=0;i<(fEvt)->fNumProtons;i++)
{
if((fEvt)->fProtonParticle[i].fPDGCodeMother == 0)
{
proton_vec.push_back((fEvt)->fProtonParticle[i]);
}
}
if(lambda_from_weak && lambda_from_weak_vec.size() == 1) //Only one feed down V0
{
for(std::vector<AliFemtoProtonParticle>::iterator Proton = proton_vec.begin(); Proton != proton_vec.end(); Proton++)
{
for(std::vector<AliFemtoLambdaParticle>::iterator V0 = lambda_from_weak_vec.begin(); V0 != lambda_from_weak_vec.end(); V0++)//treat this V0 as a "weak resonance"
{
//GetDecayMatrix(*Proton,*V0);
}
}
}
}
proton_vec.clear();
lambda_from_weak_vec.clear();
}
}
//________________________________________________________________________
Float_t AliAnalysisTaskPLFemto::PhiS(AliAODTrack *track,const Float_t bfield,const Float_t Radius,const Float_t DecVtx[2])
{
const Float_t chg = track->Charge();
const Float_t Pt = track->Pt();
const Float_t phi0 = track->Phi();
const Float_t magCurv = Pt/(chg*0.1*0.3*bfield);
const Float_t xD = DecVtx[0];
const Float_t yD = DecVtx[1];
//now the ugly solution of the system of equations:
Float_t firstTerm = (magCurv + xD)*(Radius*Radius + 2*magCurv*xD + xD*xD + yD*yD);
Float_t secondTerm = -yD*yD*((2*magCurv-Radius+xD)*(Radius+xD) + yD*yD)*((xD-Radius)*(2*magCurv+Radius + xD)+yD*yD);
if(secondTerm<0) return -9999.;
Float_t nominator = firstTerm - TMath::Sqrt(secondTerm);
Float_t denominator = 2*((magCurv+xD)*(magCurv+xD) + yD*yD);
//intersection point:
Float_t interX = nominator/denominator;
Float_t phis = phi0 + TMath::ASin(interX/Radius);
return phis;
}
//________________________________________________________________________
Float_t AliAnalysisTaskPLFemto::PhiS(AliAODTrack *track,const Float_t bfield,const Float_t Radius)
{
const Float_t phi0 = track->Phi();//angle at primary vertex
const Float_t pt = track->Pt();
const Float_t chg = track->Charge();
//To use the following equation:
//pt must be given in GeV/c
//bfield in T
//chg in units of electric charge
//radius in m
//0.3 is a conversion factor for pt and bfield can be plugged in in terms of GeV/c and electric charge, 0.1 converts the magnetic field to Tesla, 0.01 transforms the radius from cm to m
Float_t phis = phi0 + TMath::ASin(0.1*chg*bfield*0.3*Radius*0.01/(2.*pt));
return phis;
}
//________________________________________________________________________
Float_t AliAnalysisTaskPLFemto::EtaS(const Float_t zVertex, const Float_t Radius)
{
Float_t thetaS = TMath::Pi()/2. - TMath::ATan(zVertex/Radius);
return -TMath::Log( TMath::Tan(thetaS/2.) );
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::ClosePairRejecter(Float_t deltaPhiS,Float_t deltaEta)
{
Bool_t isTooClose = kFALSE;
if(fabs(deltaPhiS)<0.045 && fabs(deltaEta)<0.01) isTooClose = kTRUE;
return isTooClose;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::UserExec(Option_t *)
{
// user exec
if (!fInputEvent) {
Error("UserExec","NO EVENT FOUND!");
return;
}
fEvents++;
TString fillthis = "";
AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(fInputEvent);
fAODMCEvent = MCEvent(); //return NULL pointer in case of exp event, no problem
fCEvents->Fill(1);
// the AODs with null vertex pointer didn't pass the PhysSel
if(!aodEvent->GetPrimaryVertex() || TMath::Abs(aodEvent->GetMagneticField())<0.001) return;
fCEvents->Fill(2);
// AOD primary vertex
AliAODVertex *vtx1 = (AliAODVertex*)aodEvent->GetPrimaryVertex();
if(!vtx1) return;
if(vtx1->GetNContributors()<2) return;
fCEvents->Fill(3);
fPrimVertex[0] = vtx1->GetX();
fPrimVertex[1] = vtx1->GetY();
fPrimVertex[2] = vtx1->GetZ();
fillthis = "fVtxX";
((TH1F*)(fOutput->FindObject(fillthis)))->Fill(fPrimVertex[0]);
fillthis = "fVtxY";
((TH1F*)(fOutput->FindObject(fillthis)))->Fill(fPrimVertex[1]);
fillthis = "fVtxZ";
((TH1F*)(fOutput->FindObject(fillthis)))->Fill(fPrimVertex[2]);
if(fPrimVertex[2] < fCuts->GetEvtzVertexLow() || fPrimVertex[2] > fCuts->GetEvtzVertexUp()) return;
fCEvents->Fill(4);
//find the centrality and zBin for mixed event: 0=zBin, 1=MultBin
Int_t *MixingBins = MultiplicityBinFinderzVertexBinFinder(aodEvent,fPrimVertex[2]);
if(MixingBins[0]==-9999 || MixingBins[1]==-9999) return;//Multiplicity estimation fails
fCEvents->Fill(5);
Int_t zBin = MixingBins[0];
Int_t MultBin = MixingBins[1];
fillthis = "fNBinsMultmixing";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MultBin);
fillthis = "fNBinsVertexmixing";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(zBin);
Bool_t isPileUp = PileUpRejection(aodEvent);
if(!aodEvent->IsPileupFromSPD(3,0.8,3.,2.,5.)) fCEvents->Fill(7);
if(fAnaUtils->IsPileUpEvent(aodEvent)) return;//pile up rejection
fCEvents->Fill(6);
//*******************************(O.Arnold)
//Set the private pointer array which contains information from global tracks
ResetGlobalTrackReference();
for(Int_t iTrack=0;iTrack<aodEvent->GetNumberOfTracks();iTrack++)
{
AliAODTrack *track = dynamic_cast<AliAODTrack*>(aodEvent->GetTrack(iTrack));
if(!track) AliFatal("Not a standard AOD");
if(!track) continue;
// Store the reference of the global tracks
StoreGlobalTrackReference(track);
}
//*******************************
fEventNumber++;
//Calculate event shape (sphericity):
fSphericityvalue = CalcSphericityEvent(aodEvent);
FIFOShifter(zBin,MultBin);//Put the information into the FIFO
ProtonSelector(aodEvent); //Select primary protons
V0Selector(aodEvent); //Select V0s
XiSelector(aodEvent); //Select Xis
if(fProtonCounter>0 && fV0Counter>0) {fCEvents->Fill(8);}
if(fAntiProtonCounter>0 && fAntiV0Counter>0) {fCEvents->Fill(9);}
TrackCleaner(); //Check for unique V0s and no track sharing between V0 daughter tracks and primary tracks
Int_t *NumberOfParticles = new Int_t[2];
NumberOfParticles = BufferFiller();//Fill the candidates to the buffer: 0=V0,1=Proton
ParticlePairer(); //at this point the relevant distributions for the CF are built and mixing takes place
fillthis = "fNProtonsPerevent";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(NumberOfParticles[1]);
fillthis = "fNLambdasPerevent";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(NumberOfParticles[0]); //fill only unique candidates
PostData(1,fOutput);
PostData(2,fOutputSP);
PostData(3,fOutputPID);
PostData(4,fOutputTP);
}
//________________________________________________________________________
Double_t AliAnalysisTaskPLFemto::Qinv(TLorentzVector trackV0,TLorentzVector trackProton)
{
// Copied from Hans Beck analysis who copied it from NA49:
// Copied from NA49. See http://na49info.web.cern.ch/na49info/na49/Software/minidst/ana/html/src/T49Tool.cxx.html#T49Tool:Qinv
// Always using lambda mass (no mass difference found yet for lam <-> alam (see PDG))
TLorentzVector trackQ, trackP;
trackQ = trackV0 - trackProton;
trackP = trackV0 + trackProton;
Double_t qinvL = trackQ.Mag2();
Double_t qP = trackQ.Dot(trackP);
Double_t pinv = trackP.Mag2();
Double_t QinvLP = TMath::Sqrt(qP*qP/pinv - qinvL);
return QinvLP;
}
//________________________________________________________________________
Double_t AliAnalysisTaskPLFemto::relKcalc(TLorentzVector track1,TLorentzVector track2)
{
//This function calculates the relative momentum k* between any particle pair
TLorentzVector trackSum, track1cms, track2cms;
trackSum = track1 + track2;
Double_t beta = trackSum.Beta();
Double_t betax = beta*cos(trackSum.Phi())*sin(trackSum.Theta());
Double_t betay = beta*sin(trackSum.Phi())*sin(trackSum.Theta());
Double_t betaz = beta*cos(trackSum.Theta());
track1cms = track1;
track2cms = track2;
track1cms.Boost(-betax,-betay,-betaz);
track2cms.Boost(-betax,-betay,-betaz);
TLorentzVector trackRelK;
trackRelK = track1cms - track2cms;
Double_t relK = 0.5*trackRelK.P();
return relK;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::PairAnalysis(const AliFemtoLambdaParticle &v0,const AliFemtoProtonParticle &proton,Int_t REorME,pairType inputPair)
{
//This function analyses p-V0 correlations
TLorentzVector trackV0,trackProton,trackSum,trackV0posdaughter;
trackV0.SetXYZM(v0.fMomentum.X(),v0.fMomentum.Y(),v0.fMomentum.Z(),fCuts->GetHadronMasses(3122));
trackV0posdaughter.SetXYZM(v0.fMomentumPosDaughter.X(),v0.fMomentumPosDaughter.Y(),v0.fMomentumPosDaughter.Z(),fCuts->GetHadronMasses(2212));
trackProton.SetXYZM(proton.fMomentum.X(),proton.fMomentum.Y(),proton.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackSum = trackV0 + trackProton;
Double_t relK = relKcalc(trackV0,trackProton);
Double_t relKPPdaughter = relKcalc(trackProton,trackV0posdaughter);
Double_t pairKT = 0.5*trackSum.Pt();
double averageMass = 0.5*(fCuts->GetHadronMasses(3122) + fCuts->GetHadronMasses(2212));
double pairMT = TMath::Sqrt(pow(pairKT,2.) + pow(averageMass,2.));
if(REorME == 0 && inputPair == kProtonV0)//real event
{
TString fillthis = "fPairkTLp";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(pairKT);
fillthis = "fProtonLambdaMT";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(pairMT);
fillthis = "fProtonLambdaRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
fillthis = "fProtonLambdaPosDaughterRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relKPPdaughter);
fillthis = "fNPairStatistics";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(1);
if(relK<0.15)
{
fillthis = "fNPairStatistics";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(2);
fillthis = "fProtonLambdaMTrelKcut";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(pairMT);
}
}
else if(REorME!=0 && inputPair == kProtonV0)//mixed event
{
TString fillthis = "fProtonLambdaRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
fillthis = "fProtonLambdaPosDaughterRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relKPPdaughter);
if(fUseMCInfo) GetMomentumMatrix(v0,proton);//determines the amount of momentum resolution (from mixed event to enlarge statistics)
}
else if(REorME == 0 && inputPair == kAntiProtonV0)//real event
{
TString fillthis = "fAntiProtonLambdaRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
fillthis = "fAntiProtonAntiLambdaPosDaughterRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relKPPdaughter);
}
//else if(REorME != 0 && whichpair_combi=="AntiProton-V0")//mixed event
else if(REorME != 0 && inputPair == kAntiProtonV0)//mixed event
{
TString fillthis = "fAntiProtonLambdaRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
fillthis = "fAntiProtonAntiLambdaPosDaughterRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relKPPdaughter);
}
else if(REorME == 0 && inputPair == kProtonAntiV0)//real event
{
TString fillthis = "fProtonAntiLambdaRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME != 0 && inputPair == kProtonAntiV0)//mixed event
{
TString fillthis = "fProtonAntiLambdaRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME == 0 && inputPair == kAntiProtonAntiV0)//real event
{
TString fillthis = "fAntiProtonAntiLambdaRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
fillthis = "fNPairStatistics";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(3);
if(relK<0.15)
{
fillthis = "fNPairStatistics";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(4);
}
}
else if(REorME != 0 && inputPair == kAntiProtonAntiV0)//mixed event
{
TString fillthis = "fAntiProtonAntiLambdaRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::PairAnalysis(const AliFemtoXiParticle &xi,const AliFemtoProtonParticle &proton,Int_t REorME,pairType inputPair)
{
//This method analyses p-Xi correlations
TLorentzVector trackXi,trackProton;
trackXi.SetXYZM(xi.fMomentum.X(),xi.fMomentum.Y(),xi.fMomentum.Z(),fCuts->GetHadronMasses(3312));
trackProton.SetXYZM(proton.fMomentum.X(),proton.fMomentum.Y(),proton.fMomentum.Z(),fCuts->GetHadronMasses(2212));
Double_t relK = relKcalc(trackXi,trackProton);
if(REorME == 0 && inputPair == kProtonXi)//real event
{
TString fillthis = "fProtonXiRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME!=0 && inputPair == kProtonXi)//mixed event
{
TString fillthis = "fProtonXiRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME == 0 && inputPair == kAntiProtonXi)
{
TString fillthis = "fAntiProtonXiRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME != 0 && inputPair == kAntiProtonXi)
{
TString fillthis = "fAntiProtonXiRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::PairAnalysis(const AliFemtoLambdaParticle &v01,const AliFemtoLambdaParticle &v02,Int_t REorME,pairType inputPair)
{
TLorentzVector trackV01,trackV02;
trackV01.SetXYZM(v01.fMomentum.X(),v01.fMomentum.Y(),v01.fMomentum.Z(),fCuts->GetHadronMasses(3122));
trackV02.SetXYZM(v02.fMomentum.X(),v02.fMomentum.Y(),v02.fMomentum.Z(),fCuts->GetHadronMasses(3122));
Double_t relK = relKcalc(trackV01,trackV02);
if(REorME == 0 && inputPair == kV0V0)//real event
{
TString fillthis = "fLambdaLambdaRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME != 0 && inputPair == kV0V0)//mixed event
{
TString fillthis = "fLambdaLambdaRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME == 0 && inputPair == kAntiV0AntiV0)//real event
{
TString fillthis = "fAntiLambdaAntiLambdaRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME != 0 && inputPair == kAntiV0AntiV0)//mixed event
{
TString fillthis = "fAntiLambdaAntiLambdaRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME == 0 && inputPair == kAntiV0V0)//real event
{
TString fillthis = "fAntiLambdaLambdaRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME != 0 && inputPair == kAntiV0V0)//mixed event
{
TString fillthis = "fAntiLambdaLambdaRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::PairAnalysis(const AliFemtoProtonParticle &protonA,const AliFemtoProtonParticle &protonB,Int_t REorME,pairType inputPair)
{
//This method analyses p-p correlations
TLorentzVector trackProtonA,trackProtonB,trackSum;
TString fillthis = "";
trackProtonA.SetXYZM(protonA.fMomentum.X(),protonA.fMomentum.Y(),protonA.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackProtonB.SetXYZM(protonB.fMomentum.X(),protonB.fMomentum.Y(),protonB.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackSum = trackProtonA + trackProtonB;
Double_t relK = relKcalc(trackProtonA,trackProtonB);
Double_t pairKT = 0.5*trackSum.Pt();
Double_t pairMT = TMath::Sqrt(pow(pairKT,2.) + pow(fCuts->GetHadronMasses(2212),2.));
if(REorME == 0 && inputPair == kProtonProton)//real event
{
fillthis = "fProtonProtonRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
fillthis = "fPairkTpp";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(pairKT);
fillthis = "fProtonProtonMT";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(pairMT);
fillthis = "fNPairStatistics";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(6);
if(relK < 0.15)
{
fillthis = "fProtonProtonMTrelKcut";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(pairMT);
fillthis = "fNPairStatistics";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(7);
}
//check for splitting/merging in angle space
for(int radius=0; radius<9; radius++)
{
Double_t deltaEta = protonA.fEta - protonB.fEta;
Double_t deltaPhistar = protonA.fPhistar[radius] - protonB.fPhistar[radius];
fillthis = "fDeltaEtaDeltaPhiTPCradpp";
fillthis += radius;
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(TMath::Abs(deltaEta),TMath::Abs(deltaPhistar));
}
}
else if(REorME!=0 && inputPair == kProtonProton)//mixed event
{
fillthis = "fProtonProtonRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
if(fUseMCInfo) GetMomentumMatrix(protonA,protonB);//Determine the momentum resolution (from mixed event to enlarge statistics)
//check for splitting/merging in angle space
for(int radius=0; radius<9; radius++)
{
Double_t deltaEta = protonA.fEta - protonB.fEta;
Double_t deltaPhistar = protonA.fPhistar[radius] - protonB.fPhistar[radius];
fillthis = "fDeltaEtaDeltaPhiTPCradppME";
fillthis += radius;
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(TMath::Abs(deltaEta),TMath::Abs(deltaPhistar));
}
}
else if(REorME==0 && inputPair == kAntiProtonAntiProton)//same event
{
fillthis = "fAntiProtonAntiProtonRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
fillthis = "fPairkTApAp";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(pairKT);
fillthis = "fNPairStatistics";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(8);
if(relK < 0.15)
{
fillthis = "fNPairStatistics";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(9);
}
}
else if(REorME!=0 && inputPair == kAntiProtonAntiProton)//mixed event
{
fillthis = "fAntiProtonAntiProtonRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
else if(REorME==0 && inputPair == kAntiProtonProton)//same event
{
fillthis = "fAntiProtonProtonRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
fillthis = "fPairkTApp";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(pairKT);
}
else if(REorME!=0 && inputPair == kAntiProtonProton)//mixed event
{
fillthis = "fAntiProtonProtonRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK);
}
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::TripleAnalysis(const AliFemtoLambdaParticle &v0,const AliFemtoProtonParticle &proton1,const AliFemtoProtonParticle &proton2,Int_t REorME,pairType inputPair)
{
TLorentzVector trackV0;
TLorentzVector trackProton1;
TLorentzVector trackProton2;
trackProton1.SetXYZM(proton1.fMomentum.X(),proton1.fMomentum.Y(),proton1.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackProton2.SetXYZM(proton2.fMomentum.X(),proton2.fMomentum.Y(),proton2.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackV0.SetXYZM(v0.fMomentum.X(),v0.fMomentum.Y(),v0.fMomentum.Z(),fCuts->GetHadronMasses(3122));
Double_t relK12 = relKcalc(trackProton1,trackProton2);
Double_t relK13 = relKcalc(trackProton1,trackV0);
Double_t relK23 = relKcalc(trackProton2,trackV0);
Double_t relK123 = TMath::Sqrt(pow(relK12,2.) + pow(relK13,2.) + pow(relK23,2.));
TString fillthis = "";
if(REorME == 0 && inputPair == kProtonProtonV0)//real event
{
fillthis = "fProtonProtonLambdaRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK123);
}
else if(REorME != 0 && inputPair == kProtonProtonV0)
{
fillthis = "fProtonProtonLambdaRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK123);
}
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::TripleAnalysis(const AliFemtoProtonParticle &proton1,const AliFemtoProtonParticle &proton2,const AliFemtoProtonParticle &proton3,Int_t REorME,pairType inputPair)
{
//This method analyses p-p-p correlations
TLorentzVector trackProton1;
TLorentzVector trackProton2;
TLorentzVector trackProton3;
trackProton1.SetXYZM(proton1.fMomentum.X(),proton1.fMomentum.Y(),proton1.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackProton2.SetXYZM(proton2.fMomentum.X(),proton2.fMomentum.Y(),proton2.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackProton3.SetXYZM(proton3.fMomentum.X(),proton3.fMomentum.Y(),proton3.fMomentum.Z(),fCuts->GetHadronMasses(2212));
Double_t relK12 = relKcalc(trackProton1,trackProton2);
Double_t relK13 = relKcalc(trackProton1,trackProton3);
Double_t relK23 = relKcalc(trackProton2,trackProton3);
Double_t relK123 = TMath::Sqrt(pow(relK12,2.) + pow(relK13,2.) + pow(relK23,2.));
TString fillthis = "";
if(REorME == 0 && inputPair == kProtonProtonProton)//real event
{
fillthis = "fProtonProtonProtonRelK";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK123);
}
else if(REorME != 0 && inputPair == kProtonProtonProton)
{
fillthis = "fProtonProtonProtonRelKME";
((TH1F*)(fOutputTP->FindObject(fillthis)))->Fill(relK123);
}
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::V0TopologicalSelection(AliAODv0 *v0,AliAODEvent *aodEvent,TString ParOrAPar)
{
//This function selects the V0s according to given criteria which were studied with Monte Carlo
TString fillthis = "";
// Get the coordinates of the primary vertex
Double_t xvP = aodEvent->GetPrimaryVertex()->GetX();
Double_t yvP = aodEvent->GetPrimaryVertex()->GetY();
Double_t zvP = aodEvent->GetPrimaryVertex()->GetZ();
Double_t vecTarget[3]={xvP,yvP,zvP};
Double_t vV0[3];
v0->GetXYZ(vV0);
Double_t V0pt = v0->Pt();
//Calculate vertex variables:
Double_t dcaV0Dau = v0->DcaV0Daughters();
Double_t dcaPrim = v0->DcaV0ToPrimVertex();
Double_t dcaPrimPos = v0->DcaPosToPrimVertex();
Double_t dcaPrimNeg = v0->DcaNegToPrimVertex();
Double_t lenDecay = v0->DecayLengthV0(vecTarget);
Double_t point = v0->CosPointingAngle(vecTarget);
Double_t transverseRadius = v0->DecayLengthXY(vecTarget);
if(ParOrAPar == fwhichV0)
{
fillthis = "fLambdaDCADaughterTracks";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(dcaV0Dau);
fillthis = "fLambdaDCAPrimVertex";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(dcaPrim);
fillthis = "fLambdaDCAPosdaughPrimVertex";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(dcaPrimPos);
fillthis = "fLambdaDCANegdaughPrimVertex";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(dcaPrimNeg);
fillthis = "fLambdaDecaylength";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(lenDecay);
fillthis = "fLambdaCosPointingAngle";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(point);
fillthis = "fLambdaTransverseRadius";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(transverseRadius);
}
else if(ParOrAPar == fwhichAntiV0)
{
//conditions for AntiV0 must be implemented!
}
if(fUseMCInfo && ParOrAPar == fwhichV0)
{
Bool_t realV0 = CheckIfRealV0(v0,aodEvent,3122,2212,211);
if(realV0)
{
fillthis = "fDCAV0PosdaughMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(dcaPrimPos,V0pt);
fillthis = "fDCAV0NegdaughMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(dcaPrimNeg,V0pt);
fillthis = "fTrRadiusV0MC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(transverseRadius,V0pt);
fillthis = "fPoinAngleV0MC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(point,V0pt);
fillthis = "fLambdaV0vertexXMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(vV0[0],V0pt);
fillthis = "fLambdaV0vertexYMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(vV0[1],V0pt);
fillthis = "fLambdaV0vertexZMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(vV0[2],V0pt);
fillthis = "fDecayLengthV0MC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(lenDecay,V0pt);
}
else
{
fillthis = "fDCAbkgPosdaughMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(dcaPrimPos,V0pt);
fillthis = "fDCAbkgNegdaughMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(dcaPrimNeg,V0pt);
fillthis = "fTrRadiusbkgMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(transverseRadius,V0pt);
fillthis = "fPoinAnglebkgMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(point,V0pt);
fillthis = "fLambdabkgvertexXMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(vV0[0],V0pt);
fillthis = "fLambdabkgvertexYMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(vV0[1],V0pt);
fillthis = "fLambdabkgvertexZMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(vV0[2],V0pt);
fillthis = "fDecayLengthbkgMC";
((TH2F*)(fOutputSP->FindObject(fillthis)))->Fill(lenDecay,V0pt);
}
}
//Check if the V0 fulfills the topological cut criteria:
if(fabs(vV0[0]) > fCuts->GetV0decayvtxcut()) return kFALSE;
if(fabs(vV0[1]) > fCuts->GetV0decayvtxcut()) return kFALSE;
if(fabs(vV0[2]) > fCuts->GetV0decayvtxcut()) return kFALSE;
if(transverseRadius < fCuts->GetV0rxylow()) return kFALSE;
if(transverseRadius > fCuts->GetV0rxyup()) return kFALSE;
if(dcaPrimPos < fCuts->GetV0DCAtrPV()) return kFALSE;
if(dcaPrimNeg < fCuts->GetV0DCAtrPV()) return kFALSE;
if(dcaV0Dau > fCuts->GetV0DCAtracksV0decay()) return kFALSE;
//Fill the pointing angle as a function of pt
int ptbin = fCuts->FindV0PtBinCPA(V0pt);
if(ParOrAPar == fwhichV0 && ptbin != -9999)
{
Double_t MassV0 = v0->MassLambda();
fillthis = "fLambdaCPAPtBin";
fillthis += ptbin;
if(MassV0>(fCuts->GetHadronMasses(3122)-fCuts->GetV0PID_width()) && MassV0<(fCuts->GetHadronMasses(3122)+fCuts->GetV0PID_width()) && ParOrAPar == fwhichV0)
{
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(point);//Fill pointing angle only for Lambda candidates
}
if(fUseMCInfo)
{
Bool_t realV0 = CheckIfRealV0(v0,aodEvent,3122,2212,211);
if(realV0)//these are true MC V0s
{
TClonesArray *mcarray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcarray) return kFALSE;
Int_t daugh[2] = {2212,211};//daughter IDs of Lambda
Int_t label = v0->MatchToMC(3122,mcarray,2,daugh);
AliAODMCParticle *MCv0 = (AliAODMCParticle*)mcarray->At(label);
if(!MCv0) return kFALSE;;
fillthis = "fLambdaCPAAllPtBin";
fillthis += ptbin;
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(point);
if(MCv0->IsPhysicalPrimary() && !MCv0->IsSecondaryFromWeakDecay())
{
fillthis = "fLambdaCPAPrimaryPtBin";
fillthis += ptbin;
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(point);
}
else if(MCv0->IsSecondaryFromWeakDecay())
{
fillthis = "fLambdaCPASecondaryPtBin";
fillthis += ptbin;
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(point);
}
else if(MCv0->IsSecondaryFromMaterial())
{
fillthis = "fLambdaCPAMaterialPtBin";
fillthis += ptbin;
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(point);
}
}
else
{
fillthis = "fLambdaCPABkgPtBin";
fillthis += ptbin;
//background in the mass range of the lambda is interesting for us:
if(MassV0>(fCuts->GetHadronMasses(3122)-fCuts->GetV0PID_width()) && MassV0<(fCuts->GetHadronMasses(3122)+fCuts->GetV0PID_width()) && ParOrAPar == fwhichV0)
{
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(point);//Fill background only in the selection region
}
}
}
}
if(point < fCuts->GetV0pointing()) return kFALSE;
return kTRUE;
}
//________________________________________________________________________
inline void AliAnalysisTaskPLFemto::FillV0Selection(AliAODv0 *v0,AliAODEvent* aodEvent,TString ParOrAPar)
{
Double_t MassV0 = 0.;
TString fillthis = "";
if(ParOrAPar == fwhichV0)
{
Double_t MassK0 = v0->MassK0Short();
MassV0 = v0->MassLambda();
fillthis = "fInvMassMissIDK0s";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassK0);
if(MassK0 < fCuts->GetK0sAntiCutLow() || fCuts->GetK0sAntiCutUp() < MassK0)
{
//This cuts out the peak of the K0s
fillthis = "fInvMassMissIDK0swCuts";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassK0);
}
else return;
}
else if(ParOrAPar == fwhichAntiV0)
{
MassV0 = v0->MassAntiLambda();
Double_t MassK0 = v0->MassK0Short();
fillthis = "fInvMassMissIDK0s";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassK0);
if(MassK0 < fCuts->GetK0sAntiCutLow() || fCuts->GetK0sAntiCutUp() < MassK0)
{
fillthis = "fInvMassMissIDK0swCuts";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassK0);
}
else return;
}
else if(ParOrAPar == "Kaon" || ParOrAPar == "Anti-Kaon") MassV0 = v0->MassK0Short();
Bool_t V0Cuts = V0TopologicalSelection(v0,aodEvent,ParOrAPar);//calculates the topological cut conditions
Double_t xvP = aodEvent->GetPrimaryVertex()->GetX();
Double_t yvP = aodEvent->GetPrimaryVertex()->GetY();
Double_t zvP = aodEvent->GetPrimaryVertex()->GetZ();
Double_t vecTarget[3]={xvP,yvP,zvP};
Double_t point = v0->CosPointingAngle(vecTarget);
if(ParOrAPar == fwhichV0)
{
fillthis = "fInvMassLambdawoCuts";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassV0);
}
else if(ParOrAPar == fwhichAntiV0)
{
fillthis = "fInvMassAntiLambdawoCuts";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassV0);
}
else
{
std::cout << "Specify which V0 you want to analyse" << std::endl;
return;
}
if(V0Cuts)// apply vertex cuts
{
AliAODTrack* pTrack = fGTI[v0->GetPosID()];
AliAODTrack* nTrack = fGTI[v0->GetNegID()];
if(!pTrack || !nTrack) return;
Double_t charge1 = pTrack->Charge();
Double_t charge2 = nTrack->Charge();
if(charge1 < 0. && charge2 > 0. && ParOrAPar == fwhichV0)//assign correct charge to tracks from V0
{
pTrack = fGTI[v0->GetNegID()];//proton as positive particle
nTrack = fGTI[v0->GetPosID()];//pion as negative particle
}
else if(charge1 > 0. && charge2 <0. && ParOrAPar == fwhichAntiV0)//assign correct charge to tracks from Anti-V0
{
pTrack = fGTI[v0->GetNegID()];//anti-proton as negative particle
nTrack = fGTI[v0->GetPosID()];//anti-pion as positive particle
}
// Lambda or AntiLambda
if(ParOrAPar == fwhichV0)
{
fillthis = "fInvMassLambdawCuts";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassV0);
if(fProtonCounter>0)
{
fillthis = "fInvMassLambdawCutsAfterSelection";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassV0);
}
Int_t ptbin = fCuts->FindV0PtBinInvMass(v0->Pt());
if(ParOrAPar == fwhichV0 && ptbin != -9999)
{
fillthis = "fInvMassLambdawCutsPtBin";
fillthis += ptbin;
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassV0);
}
}
else if(ParOrAPar == fwhichAntiV0)
{
fillthis = "fInvMassAntiLambdawCuts";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassV0);
}
//Save all the information of the V0
//_____________________________________________________
Bool_t which_V0_region = kFALSE;
Bool_t which_AntiV0_region = kFALSE;
if(fwhichV0region == "left")
{
if(MassV0<1.105 && ParOrAPar == fwhichV0) which_V0_region = kTRUE;
else if(MassV0<1.105 && ParOrAPar == fwhichAntiV0) which_AntiV0_region = kTRUE;
}
else if(fwhichV0region == "right")
{
if(MassV0>1.13 && MassV0<1.18 && ParOrAPar == fwhichV0) which_V0_region = kTRUE;
else if(MassV0>1.13 && MassV0<1.18 && ParOrAPar == fwhichAntiV0) which_AntiV0_region = kTRUE;
}
else if(fwhichV0region == "signal")
{
if(MassV0>(fCuts->GetHadronMasses(3122)-fCuts->GetV0PID_width()) && MassV0<(fCuts->GetHadronMasses(3122)+fCuts->GetV0PID_width()) && ParOrAPar == fwhichV0) which_V0_region = kTRUE;
else if(MassV0>(fCuts->GetHadronMasses(3122)-fCuts->GetV0PID_width()) && MassV0<(fCuts->GetHadronMasses(3122)+fCuts->GetV0PID_width()) && ParOrAPar == fwhichAntiV0) which_AntiV0_region = kTRUE;
}
if(which_V0_region && ParOrAPar == fwhichV0)
{
fillthis = "fLambdaPt";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(v0->Pt());
fillthis = "fLambdaPhi";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(v0->Phi());
fillthis = "fLambdaEta";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(v0->Eta());
fillthis = "fInvMassLambdawCutsAfterMassCut";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MassV0);
if(fV0Counter > kV0TrackLimit) return;
if(pTrack->GetID() == nTrack->GetID()) return; //should never happen
fV0cand[fV0Counter].fPt = v0->Pt();
fV0cand[fV0Counter].fMomentum.SetXYZ(v0->Px(),v0->Py(),v0->Pz());
fV0cand[fV0Counter].fMass = MassV0;
fV0cand[fV0Counter].fPointing = point;
fV0cand[fV0Counter].fEtaPosdaughter = pTrack->Eta();//eta should be translational invariant due to magnetic field along z (?)
fV0cand[fV0Counter].fV0tag = kTRUE;//should be by true by initialization but do it again (however i had problems with this flag, maybe order of initialization went sometimes wrong)
fV0cand[fV0Counter].fDaughterID1 = pTrack->GetID();
fV0cand[fV0Counter].fDaughterID2 = nTrack->GetID();
fV0cand[fV0Counter].fMomentumPosDaughter.SetXYZ(pTrack->Px(),pTrack->Py(),pTrack->Pz());
fV0cand[fV0Counter].fMomentumNegDaughter.SetXYZ(nTrack->Px(),nTrack->Py(),nTrack->Pz());
GetGlobalPositionAtGlobalRadiiThroughTPC(pTrack,aodEvent->GetMagneticField(),fV0cand[fV0Counter].fPosDaughPosTPC,fPrimVertex);
GetGlobalPositionAtGlobalRadiiThroughTPC(nTrack,aodEvent->GetMagneticField(),fV0cand[fV0Counter].fNegDaughPosTPC,fPrimVertex);
if(fUseMCInfo)// if monte carlo
{
if(CheckMCPID(v0,aodEvent,3122)) fV0cand[fV0Counter].fReal = kTRUE;
else fV0cand[fV0Counter].fReal = kFALSE;
GetV0Origin(v0,aodEvent);//evaluated with all the cuts applied
double v0MCmom[3] = {-9999.,-9999.,-9999.};
double v0MCmom_mother[4] = {-9999.,-9999.,-9999.,-9999.};
GetMCMomentum(v0,v0MCmom,v0MCmom_mother,aodEvent);
fV0cand[fV0Counter].fMomentumMC.SetXYZ(v0MCmom[0],v0MCmom[1],v0MCmom[2]);
fV0cand[fV0Counter].fMomentumMCMother.SetXYZ(v0MCmom_mother[0],v0MCmom_mother[1],v0MCmom_mother[2]);
if(v0MCmom_mother[3]>0) fV0cand[fV0Counter].fPDGCodeMother = (int)v0MCmom_mother[3];//it stems coming from a weak decay
else fV0cand[fV0Counter].fPDGCodeMother = 0;
}
else
{
fV0cand[fV0Counter].fMomentumMC.SetXYZ(-9999.,-9999.,-9999.);
fV0cand[fV0Counter].fMomentumMCMother.SetXYZ(-9999.,-9999.,-9999.);
}
if(!fV0cand[fV0Counter].fV0tag) std::cout << "something is wrong with the V0 tag" << std::endl;
fillthis = "fNLambdasTot";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1); //fill only unique candidates
fV0Counter++;//This is a V0 (Lambda) candidate
}
else if(which_AntiV0_region && ParOrAPar == fwhichAntiV0)//fill only in a certain mass range
{
fillthis = "fAntiLambdaPt";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(v0->Pt());
if(fAntiV0Counter > kV0TrackLimit) return;
if(pTrack->GetID() == nTrack->GetID()) return; //should never happen
fAntiV0cand[fAntiV0Counter].fPt = v0->Pt();
fAntiV0cand[fAntiV0Counter].fMomentum.SetXYZ(v0->Px(),v0->Py(),v0->Pz());
fAntiV0cand[fAntiV0Counter].fMass = MassV0;
fAntiV0cand[fAntiV0Counter].fPointing = point;
fAntiV0cand[fAntiV0Counter].fV0tag = kTRUE;
fAntiV0cand[fAntiV0Counter].fDaughterID1 = pTrack->GetID();
fAntiV0cand[fAntiV0Counter].fDaughterID2 = nTrack->GetID();
fAntiV0cand[fAntiV0Counter].fMomentumPosDaughter.SetXYZ(pTrack->Px(),pTrack->Py(),pTrack->Pz());
fAntiV0cand[fAntiV0Counter].fMomentumNegDaughter.SetXYZ(nTrack->Px(),nTrack->Py(),nTrack->Pz());
fillthis = "fNAntiLambdasTot";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1); //fill only unique candidates
fAntiV0Counter++;//This is a Anti-V0 (Anti-Lambda) candidate
}
//_____________________________________________________
}
}
//________________________________________ terminate ___________________________
void AliAnalysisTaskPLFemto::Terminate(Option_t*)
{
// The Terminate() function is the last function to be called during
// a query. It always runs on the client, it can be used to present
// the results graphically or save the results to file.
//Info("Terminate","");
AliAnalysisTaskSE::Terminate();
fOutput = dynamic_cast<TList*> (GetOutputData(1));
if (!fOutput) {
printf("ERROR: fOutput not available\n");
return;
}
//fCEvents = dynamic_cast<TH1F*>(fOutput->FindObject("fCEvents"));
fOutputSP = dynamic_cast<TList*> (GetOutputData(2)); //1
if (!fOutputSP) {
printf("ERROR: fOutputAll not available\n");
return;
}
fOutputPID = dynamic_cast<TList*> (GetOutputData(3));//2
if (!fOutputPID) {
printf("ERROR: fOutputPID not available\n");
return;
}
fOutputTP = dynamic_cast<TList*> (GetOutputData(4));//3
if (!fOutputTP) {
printf("ERROR: fOutputTP not available\n");
return;
}
return;
}
//___________________________________________________________________________
void AliAnalysisTaskPLFemto::UserCreateOutputObjects()
{
std::cout << "Create Output Objects" << std::endl;
// output
Info("UserCreateOutputObjects","CreateOutputObjects of task %s\n", GetName());
//slot #1
//OpenFile(1);
fOutput = new TList();
fOutput->SetOwner();
fOutput->SetName("listEvt");
fOutputPID = new TList();
fOutputPID->SetOwner();
fOutputPID->SetName("listPID");
fOutputSP = new TList();
fOutputSP->SetOwner();
fOutputSP->SetName("listSP");
fOutputTP = new TList();
fOutputTP->SetOwner();
fOutputTP->SetName("listTP");
// define histograms
DefineHistograms(fwhichV0);
fGTI = new AliAODTrack *[fTrackBuffSize]; // Array of pointers
//for particle identification
AliAnalysisManager *man=AliAnalysisManager::GetAnalysisManager();
if(!man){AliError("Couldn't get the analysis manager!");}
AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler());
if(!inputHandler){AliError("Couldn't get the input handler!");}
fPIDResponse = inputHandler->GetPIDResponse();
if(!fPIDResponse){AliError("Couldn't get the PID response task!");}
PostData(1,fOutput);
PostData(2,fOutputSP);
PostData(3,fOutputPID);
PostData(4,fOutputTP);
return;
}
//___________________________________ hiostograms _______________________________________
void AliAnalysisTaskPLFemto::DefineHistograms(TString whichV0)
{
// Create histograms
//Define event related histograms:
fCEvents = new TH1F("fCEvents","conter",11,0,11);
fCEvents->SetStats(kTRUE);
fCEvents->GetXaxis()->SetTitle("1");
fCEvents->GetYaxis()->SetTitle("counts");
//***************************************************************************
//Global event histograms
//***************************************************************************
TH1F* fVtxX = new TH1F("fVtxX","Primary X vertex",600,-1.,1.);
TH1F* fVtxY = new TH1F("fVtxY","Primary Y vertex",600,-1.,1.);
TH1F* fVtxZ = new TH1F("fVtxZ","Primary Z vertex",600,-15.,15.);
TH1F* fProtonPIDthresholdTPCLow = new TH1F("fProtonPIDthresholdTPCLow","lower momentum threshold which was chosen for PID selection of protons",10,0,10);
fProtonPIDthresholdTPCLow->SetBinContent(1,fCuts->GetProtonPIDthrPtLow());
TH1F* fProtonPIDthresholdTPCUp = new TH1F("fProtonPIDthresholdTPCUp","upper momentum threshold which was chosen for PID selection of protons",10,0,10);
fProtonPIDthresholdTPCUp->SetBinContent(1,fCuts->GetProtonPIDthrPtUp());
TH1F* fProtonPIDTPCTOFSwitch = new TH1F("fProtonPIDTPCTOFSwitc","Switch between TOF and TPC for proton PID",10,0,10);
fProtonPIDTPCTOFSwitch->SetBinContent(1,fCuts->GetProtonPIDTOFTPCSwitch());
TH1F* fLambdaPIDthresholdTPCLow = new TH1F("fLambdaPIDthresholdTPCLow","lower momentum threshold which was chosen for PID selection of Lambdas",10,0,10);
fLambdaPIDthresholdTPCLow->SetBinContent(1,fCuts->GetV0PIDthrPtLow());
TH1F* fLambdaPIDthresholdTPCUp = new TH1F("fLambdaPIDthresholdTPCUp","upper momentum threshold which was chosen for PID selection of Lambdas",10,0,10);
fLambdaPIDthresholdTPCUp->SetBinContent(1,fCuts->GetProtonPIDthrPtUp());
TH1F* fProtonDCAxyValue = new TH1F("fProtonDCAxyValue","DCAxy value for protons",10,0,10);
fProtonDCAxyValue->SetBinContent(1,fCuts->GetProtonDCAxyCut());
TH1F* fProtonDCAzValue = new TH1F("fProtonDCAzValue","DCAxy value for protons",10,0,10);
fProtonDCAzValue->SetBinContent(1,fCuts->GetProtonDCAzCut());
TH1F* fTrackselection = new TH1F("fTrackselection","which filterbit was used to select the tracks",10,0,10);
fTrackselection->SetBinContent(1,fWhichfilterbit);
//Define single particle histograms event related:
TH1F* fWhichAnalysis = new TH1F("fWhichAnalysis","Which V0 is correlated, 1:Lambda,2:KOshort",10,0,10);
TH1F* fWhichV0region = new TH1F("fWhichV0region","Sideband or signal: 1:left sideband,2:signal,3:right sideband",10,0,10);
TH1F* fOnlineOrOffline = new TH1F("fOnlineOrOffline","Histogram that displays if V0 selection was online or on-the-fly, 1:online, 2:offline",10,0,10);
TH1F* fMCorExp = new TH1F("fMCorExp","Monte Carlo or experimental data, 1: Exp, 2: MC",10,0,10);
TH2F* fEventSPDClusterNTracklets = new TH2F("fEventSPDClusterNTracklets","SPDCluster vs Tracklets: Is pile-up seen",200,0,200,200,0,200);
TH2F* fEventSPDClusterNTrackletsPileUpCut = new TH2F("fEventSPDClusterNTrackletsPileUpCut","SPDCluster vs Tracklets: Is pile-up seen",200,0,200,200,0,200);
if(fOnlineV0) fOnlineOrOffline->Fill(1);
else if(!fOnlineV0) fOnlineOrOffline->Fill(3);
if(whichV0=="Lambda") fWhichAnalysis->Fill(1);
else if(whichV0=="Kaon") fWhichAnalysis->Fill(3);
if(fwhichV0region == "left") fWhichV0region->Fill(1);
else if(fwhichV0region == "signal") fWhichV0region->Fill(2);
else if(fwhichV0region == "right") fWhichV0region->Fill(3);
if(fUseMCInfo) fMCorExp->Fill(1);
else fMCorExp->Fill(2);
fOutput->Add(fCEvents);
fOutput->Add(fVtxX);
fOutput->Add(fVtxY);
fOutput->Add(fVtxZ);
fOutput->Add(fProtonPIDthresholdTPCLow);
fOutput->Add(fProtonPIDthresholdTPCUp);
fOutput->Add(fProtonPIDTPCTOFSwitch);
fOutput->Add(fLambdaPIDthresholdTPCLow);
fOutput->Add(fLambdaPIDthresholdTPCUp);
fOutput->Add(fWhichAnalysis);
fOutput->Add(fWhichV0region);
fOutput->Add(fOnlineOrOffline);
fOutput->Add(fEventSPDClusterNTracklets);
fOutput->Add(fEventSPDClusterNTrackletsPileUpCut);
fOutput->Add(fProtonDCAxyValue);
fOutput->Add(fProtonDCAzValue);
fOutput->Add(fTrackselection);
fOutput->Add(fMCorExp);
//***************************************************************************
//***************************************************************************
//***************************************************************************
//Single particle histograms
//***************************************************************************
Float_t invMassLow = 0.;
Float_t invMassUp = 0.;
if(whichV0=="Lambda")
{
invMassLow = 1.;
invMassUp = 1.2;
}
else if(whichV0=="Kaon")
{
invMassLow = 0.4;
invMassUp = 0.6;
}
TH1F* fInvMassLambdawCuts = new TH1F("fInvMassLambdawCuts","Invariant mass of Lambda(p #pi) (GeV/c) with topological cuts",400,invMassLow,invMassUp);
TH1F* fInvMassLambdawoCuts = new TH1F("fInvMassLambdawoCuts","Invariant mass of Lambda(p #pi) (GeV/c) without topological cuts",400,invMassLow,invMassUp);
TH1F* fInvMassLambdawCutsAfterSelection = new TH1F("fInvMassLambdawCutsAfterSelection","Invariant mass of Lambda(p #pi) (GeV/c) with topological cuts and after proton selection",400,invMassLow,invMassUp);
TH1F* fInvMassLambdawCutsAfterMassCut = new TH1F("fInvMassLambdawCutsAfterMassCut","Invariant mass of Lambda(p #pi) (GeV/c) with vertex cuts and Mass cut of 4 MeV/c²",400,invMassLow,invMassUp);
//Differential Analysis in Pt:
TH1F* fInvMassLambdawCutsPtBin[fCuts->GetV0PtBinsInvMass()];
for(Int_t i=0; i<fCuts->GetV0PtBinsInvMass(); i++)
{
TString HistName = "fInvMassLambdawCutsPtBin";
HistName += i;
fInvMassLambdawCutsPtBin[i] = new TH1F(HistName.Data(),HistName.Data(),200,1.,1.2);
fOutputSP->Add(fInvMassLambdawCutsPtBin[i]);
}
TH1F* fInvMassAntiLambdawCuts = new TH1F("fInvMassAntiLambdawCuts","Invariant mass of AntiLambda(a-p a-#pi) (GeV/c) with vertex cuts",400,invMassLow,invMassUp);
TH1F* fInvMassAntiLambdawoCuts = new TH1F("fInvMassAntiLambdawoCuts","Invariant mass of AntiLambda(a-p a-#pi) (GeV/c) without topological cuts",400,invMassLow,invMassUp);
TH1F* fInvMassMissIDK0s = new TH1F("fInvMassMissIDK0s","Invariant mass of K0s under the hypothesis we have a lambda",400,0.4,0.6);
TH1F* fInvMassMissIDK0swCuts = new TH1F("fInvMassMissIDK0swCuts","Invariant mass of K0s after mass cut applied",400,0.4,0.6);
TH1F* fXiInvMasswoCuts = new TH1F("fXiInvMasswoCuts","Invariant mass of Xi candidate",300,1.2,1.5);
TH1F* fXiInvMasswCuts = new TH1F("fXiInvMasswCuts","Invariant mass of Xi candidate with topological cuts",300,1.2,1.5);
TH1F* fXiInvMassLambda = new TH1F("fXiInvMassLambda","Invariant mass of p-pi stemming from Xi",400,invMassLow,invMassUp);
TH1F* fLambdaDCADaughterTracks = new TH1F("fLambdaDCADaughterTracks","Distance of closest approach of p and #pi track",400,0.,2.);
TH1F* fLambdaDCAPrimVertex = new TH1F("fLambdaDCAPrimVertex","Distance of closest approach of V0 track to primary vertex",500,0.,10.);
TH1F* fLambdaDCAPosdaughPrimVertex = new TH1F("fLambdaDCAPosdaughPrimVertex","Distance of closest approach of V0 positive daughter track to primary vertex",500,0.,10.);
TH1F* fLambdaDCANegdaughPrimVertex = new TH1F("fLambdaDCANegdaughPrimVertex","Distance of closest approach of V0 negative daughter track to primary vertex",500,0.,10.);
TH1F* fLambdaTransverseRadius = new TH1F("fLambdaTransverseRadius","Transverse distance between primary vertex and V0 decay vertex",400,0,60.);
TH1F* fLambdaDecaylength = new TH1F("fLambdaDecaylength","Distance between primary and secondary vertex",500,0.,100.);
TH1F* fLambdaCosPointingAngle = new TH1F("fLambdaCosPointingAngle","Cosinuns of Pointing angle",800,0.8,1.);
TH1F* fProtonDCAxy = new TH1F("fProtonDCAxy","Distance of closest approach of primary proton to primary vertex in xy",1000,-5.,5.);
TH1F* fProtonDCAxyCutz = new TH1F("fProtonDCAxyCutz","Distance of closest approach of primary proton to primary vertex in xy with DCAz Cut",1000,-5.,5.);
TH1F* fProtonDCAz = new TH1F("fProtonDCAz","Distance of closest approach of primary proton to primary vertex in z",1000,-20.,20.);
TH2F* fProtonDCAxyDCAz = new TH2F("fProtonDCAxyDCAz","Distribution of DCAz vs DCAxy",500,-5,5,1000,-20,20);
TH1F* fAntiProtonDCAxy = new TH1F("fAntiProtonDCAxy","Distance of closest approach of primary proton to primary vertex in xy",1000,-5.,5.);
TH1F* fAntiProtonDCAxyCutz = new TH1F("fAntiProtonDCAxyCutz","Distance of closest approach of primary proton to primary vertex in xy with DCAz Cut",1000,-5.,5.);
TH1F* fAntiProtonDCAz = new TH1F("fAntiProtonDCAz","Distance of closest approach of primary proton to primary vertex in z",1000,-20.,20.);
TH2F* fAntiProtonDCAxyDCAz = new TH2F("fAntiProtonDCAxyDCAz","Distribution of DCAz vs DCAxy",500,-5,5,1000,-20,20);
TH2F* fProtonDCAxyDCAzMCPtBin[5][fCuts->GetPtBinsDCA()];
TH2F* fProtonDCAxyDCAzPt[fCuts->GetPtBinsDCA()];
for(int ProtonCases = 0; ProtonCases < 5; ProtonCases++)//primary, secondary, ....
{
for(int ptbins = 0; ptbins < fCuts->GetPtBinsDCA(); ptbins++)
{
TString HistName = "fProtonDCAxyDCAzMCCase";
HistName += ProtonCases;
HistName += "PtBin";
HistName += ptbins;
fProtonDCAxyDCAzMCPtBin[ProtonCases][ptbins] = new TH2F(HistName.Data(),"DCAz vs DCAxy for different pt Bins",500,-5,5,500,-5,5);
fProtonDCAxyDCAzMCPtBin[ProtonCases][ptbins]->Sumw2();
if(fUseMCInfo) fOutputSP->Add(fProtonDCAxyDCAzMCPtBin[ProtonCases][ptbins]);
else if(!fUseMCInfo)
{
if(ProtonCases == 0)
{
HistName = "fProtonDCAxyDCAzPt";
HistName += ptbins;
fProtonDCAxyDCAzPt[ptbins] = new TH2F(HistName.Data(),"DCAz vs DCAxy for different pt Bins",500,-5,5,500,-5,5);
fProtonDCAxyDCAzPt[ptbins]->Sumw2();
fOutputSP->Add(fProtonDCAxyDCAzPt[ptbins]);
}
}
}
}
TH1F* fLambdaCPAPtBin[fCuts->GetV0PtBinsCPA()];
TH1F* fLambdaCPAAllPtBin[fCuts->GetV0PtBinsCPA()];
TH1F* fLambdaCPAPrimaryPtBin[fCuts->GetV0PtBinsCPA()];
TH1F* fLambdaCPASecondaryPtBin[fCuts->GetV0PtBinsCPA()];
TH1F* fLambdaCPAMaterialPtBin[fCuts->GetV0PtBinsCPA()];
TH1F* fLambdaCPABkgPtBin[fCuts->GetV0PtBinsCPA()];
for(int ptbins = 0; ptbins < fCuts->GetV0PtBinsCPA(); ptbins++)
{
TString HistName = "fLambdaCPAPtBin";
HistName += ptbins;
fLambdaCPAPtBin[ptbins] = new TH1F(HistName.Data(),"Cosine of pointing angle as function of pt for all V0s",100,0.99,1);
fOutputSP->Add(fLambdaCPAPtBin[ptbins]);
if(fUseMCInfo)
{
HistName = "fLambdaCPAAllPtBin";
HistName += ptbins;
fLambdaCPAAllPtBin[ptbins] = new TH1F(HistName.Data(),"Cosine of pointing angle as function of pt for all real V0s",100,0.99,1);
fOutputSP->Add(fLambdaCPAAllPtBin[ptbins]);
HistName = "fLambdaCPAPrimaryPtBin";
HistName += ptbins;
fLambdaCPAPrimaryPtBin[ptbins] = new TH1F(HistName.Data(),"Cosine of pointing angle as function of pt for primary real V0s",100,0.99,1);
fOutputSP->Add(fLambdaCPAPrimaryPtBin[ptbins]);
HistName = "fLambdaCPASecondaryPtBin";
HistName += ptbins;
fLambdaCPASecondaryPtBin[ptbins] = new TH1F(HistName.Data(),"Cosine of pointing angle as function of pt for secondary real V0s",100,0.99,1);
fOutputSP->Add(fLambdaCPASecondaryPtBin[ptbins]);
HistName = "fLambdaCPAMaterialPtBin";
HistName += ptbins;
fLambdaCPAMaterialPtBin[ptbins] = new TH1F(HistName.Data(),"Cosine of pointing angle as function of pt for material real V0s",100,0.99,1);
fOutputSP->Add(fLambdaCPAMaterialPtBin[ptbins]);
HistName = "fLambdaCPABkgPtBin";
HistName += ptbins;
fLambdaCPABkgPtBin[ptbins] = new TH1F(HistName.Data(),"Cosine of pointing angle as function of pt for background V0s",100,0.99,1);
fOutputSP->Add(fLambdaCPABkgPtBin[ptbins]);
}
}
TH1F* fLambdaPt = new TH1F("fLambdaPt","Transverse momentum spectrum of V0s",50,0.,10.);
TH1F* fLambdaPhi = new TH1F("fLambdaPhi","Phi angle spectrum of V0s",300,-1,2.*TMath::Pi());
TH1F* fLambdaEta = new TH1F("fLambdaEta","Eta spectrum of V0s",400,-2,2);
TH1F* fAntiLambdaPt = new TH1F("fAntiLambdaPt","Transverse momentum spectrum of Anti-V0s",50,0.,10.);
TH1F* fProtonPt = new TH1F("fProtonPt","Transverse momentum spectrum of protons",50,0.,10.);
TH1F* fProtonPhi = new TH1F("fProtonPhi","Phi angle spectrum of protons",300,-1,2.*TMath::Pi());
TH1F* fProtonEta = new TH1F("fProtonEta","Pseudorapidity spectrum of protons",400,-2,2);
TH1F* fAntiProtonPt = new TH1F("fAntiProtonPt","Transverse momentum spectrum of Anti-protons",50,0.,10.);
TH2F* fLambdaV0vertexXMC = new TH2F("fLambdaV0vertexXMC","Vertex X of V0 decay vertex",800,-300,300,100,0,10);
TH2F* fLambdaV0vertexYMC = new TH2F("fLambdaV0vertexYMC","Vertex Y of V0 decay vertex",800,-300,300,100,0,10);
TH2F* fLambdaV0vertexZMC = new TH2F("fLambdaV0vertexZMC","Vertex Z of V0 decay vertex",800,-300,300,100,0,10);
TH2F* fLambdabkgvertexXMC = new TH2F("fLambdabkgvertexXMC","Vertex X of V0 decay vertex",800,-300,300,100,0,10);
TH2F* fLambdabkgvertexYMC = new TH2F("fLambdabkgvertexYMC","Vertex Y of V0 decay vertex",800,-300,300,100,0,10);
TH2F* fLambdabkgvertexZMC = new TH2F("fLambdabkgvertexZMC","Vertex Z of V0 decay vertex",800,-300,300,100,0,10);
TH2F* fDCAV0PosdaughMC = new TH2F("fDCAV0PosdaughMC","DCA of positive daughter track from V0 to primary vertex in MC as a function of V0 pt",400,0,2,100,0,10);
TH2F* fDCAbkgPosdaughMC = new TH2F("fDCAbkgPosdaughMC","DCA of positive daughter track from bkg to primary vertex in MC as a function of bkg pt",400,0,2,100,0,10);
TH2F* fDCAV0NegdaughMC = new TH2F("fDCAV0NegdaughMC","DCA of negative daughter track from V0 to primary vertex in MC as a function of V0 pt",400,0,2,100,0,10);
TH2F* fDCAbkgNegdaughMC = new TH2F("fDCAbkgNegdaughMC","DCA of negative daughter track from background to primary vertex in MC as a function of bkg pt",400,0,2,100,0,10);
TH2F* fTrRadiusV0MC = new TH2F("fTrRadiusV0MC","Transverse distance of V0 between primary and secondary vertex MC as a function of V0 pt",3000,0,300,100,0,10);
TH2F* fTrRadiusbkgMC = new TH2F("fTrRadiusbkgMC","Transverse distance of bkg between primary and secondary vertex MC as a function of bkg pt",3000,0,300,100,0,10);
TH2F* fDecayLengthV0MC = new TH2F("fDecayLengthV0MC","Transverse distance of V0 between primary and secondary vertex MC as a function of V0 pt",600,0,60,100,0,10);
TH2F* fDecayLengthbkgMC = new TH2F("fDecayLengthbkgMC","Transverse distance of bkg between primary and secondary vertex MC as a function of bkg pt",600,0,60,100,0,10);
TH2F* fPoinAngleV0MC = new TH2F("fPoinAngleV0MC","Pointing angle of V0 as a function of V0 pt",500,0.97,1,100,0,10);
TH2F* fPoinAnglebkgMC = new TH2F("fPoinAnglebkgMC","Pointing angle of bkg as a function of bkg pt",500,0.97,1,100,0,10);
TH1F* fNBinsMultmixing = new TH1F("fNBinsMultmixing","Bins in multiplicity that are used for event mixing, which bin is often occupied etc.",kMultiplicityBins,0,kMultiplicityBins);
TH1F* fNBinsVertexmixing = new TH1F("fNBinsVertexmixing","Bins in z-Vertex that are used for event mixing, which bin is often occupied etc.",kZVertexBins,0,kZVertexBins);
TH1F* fNTracklets = new TH1F("fNTracklets","Number of Tracklets",200,0,200);
TH1F* fNProtonsPerevent = new TH1F("fNProtonsPerevent","Number of protons in an event",200,1,100);
TH1F* fNLambdasPerevent = new TH1F("fNLambdasPerevent","Number of V0s in an event",20,1,10);
TH1F* fNProtonsTot = new TH1F("fNProtonsTot","Total number of protons",10,1,10);
TH1F* fNAntiProtonsTot = new TH1F("fNAntiProtonsTot","Total number of anti-protons",10,1,10);
TH1F* fNLambdasTot = new TH1F("fNLambdasTot","Total number of V0s under certain conditions",10,1,10);
TH1F* fNAntiLambdasTot = new TH1F("fNAntiLambdasTot","Total number of Anti-V0s under certain conditions",10,1,10);
TH1F* fNV0TrackSharing = new TH1F("fNV0TrackSharing","Number of V0s which shared tracks in an event",20,0,10);
TH1F* fNAntiV0TrackSharing = new TH1F("fNAntiV0TrackSharing","Number of Anti-V0s which shared tracks in an event",20,0,10);
TH1F* fNV0protonSharedTracks = new TH1F("fNV0protonSharedTracks","How often share a V0 and a proton the same track?",10,0,10);
TH1F* fNAntiV0protonSharedTracks = new TH1F("fNAntiV0protonSharedTracks","How often share a Anti-V0 and a proton the same track?",10,0,10);
TH1F* fNAntiV0AntiprotonSharedTracks = new TH1F("fNAntiV0AntiprotonSharedTracks","How often share a Anti-V0 and a Anti-proton the same track?",10,0,10);
TH1F* fFeeddownProton = new TH1F("fFeeddownProton","1: total number of protons, 2: Primary, 3: from weak decays, 4: from material",10,0,10);
TH1F* fFeeddownProtonFromWeakPDG = new TH1F("fFeeddownProtonFromWeakPDG","Protons stemming from weak decays",213,3121,3334);
TH1F* fFeeddownV0 = new TH1F("fFeeddownV0","1: total number of protons, 2: Primary, 3: from weak decays, 4: from material",10,0,10);
TH1F* fFeeddownV0FromWeakPDG = new TH1F("fFeeddownV0FromWeakPDG","V0s stemming from weak decays",213,3121,3334);
TH1F* fFindableClusterProton = new TH1F("fFindableClusterProton","Number of findable cluster for protons",200,0,200);
TH1F* fNCrossedRowsProton = new TH1F("fNCrossedRowsProton","Number of crossed rows for protons",200,0,200);
TH1F* fRatioFindableCrossedProton = new TH1F("fRatioFindableCrossedProton","Number of crossed rows over findable cluster for protons",200,0,1.5);
TH1F* fFindableClusterAntiProton = new TH1F("fFindableClusterAntiProton","Number of findable cluster for protons",200,0,200);
TH1F* fNCrossedRowsAntiProton = new TH1F("fNCrossedRowsAntiProton","Number of crossed rows for protons",200,0,200);
TH1F* fRatioFindableCrossedAntiProton = new TH1F("fRatioFindableCrossedAntiProton","Number of crossed rows over findable cluster for protons",200,0,1.5);
fInvMassLambdawCuts->Sumw2();
fInvMassAntiLambdawCuts->Sumw2();
fInvMassLambdawoCuts->Sumw2();
fInvMassAntiLambdawoCuts->Sumw2();
fInvMassLambdawCutsAfterMassCut->Sumw2();
fInvMassLambdawCutsAfterSelection->Sumw2();
fInvMassMissIDK0s->Sumw2();
fInvMassMissIDK0swCuts->Sumw2();
fXiInvMasswoCuts->Sumw2();
fXiInvMasswCuts->Sumw2();
fProtonDCAxy->Sumw2();
fProtonDCAxyCutz->Sumw2();
fProtonDCAz->Sumw2();
fProtonDCAxyDCAz->Sumw2();
fAntiProtonDCAxy->Sumw2();
fAntiProtonDCAxyCutz->Sumw2();
fAntiProtonDCAz->Sumw2();
fAntiProtonDCAxyDCAz->Sumw2();
fOutputSP->Add(fNBinsMultmixing);
fOutputSP->Add(fNBinsVertexmixing);
fOutputSP->Add(fNTracklets);
fOutputSP->Add(fInvMassLambdawCuts);
fOutputSP->Add(fInvMassLambdawoCuts);
fOutputSP->Add(fInvMassLambdawCutsAfterSelection);
fOutputSP->Add(fInvMassLambdawCutsAfterMassCut);
fOutputSP->Add(fInvMassAntiLambdawCuts);
fOutputSP->Add(fInvMassAntiLambdawoCuts);
fOutputSP->Add(fInvMassMissIDK0s);
fOutputSP->Add(fInvMassMissIDK0swCuts);
fOutputSP->Add(fXiInvMasswoCuts);
fOutputSP->Add(fXiInvMasswCuts);
fOutputSP->Add(fXiInvMassLambda);
fOutputSP->Add(fLambdaPt);
fOutputSP->Add(fLambdaPhi);
fOutputSP->Add(fLambdaEta);
fOutputSP->Add(fAntiLambdaPt);
fOutputSP->Add(fProtonPt);
fOutputSP->Add(fProtonPhi);
fOutputSP->Add(fProtonEta);
fOutputSP->Add(fAntiProtonPt);
fOutputSP->Add(fNLambdasTot);
fOutputSP->Add(fNAntiLambdasTot);
fOutputSP->Add(fNLambdasPerevent);
fOutputSP->Add(fNProtonsTot);
fOutputSP->Add(fNAntiProtonsTot);
fOutputSP->Add(fNProtonsPerevent);
fOutputSP->Add(fNV0TrackSharing);
fOutputSP->Add(fNAntiV0TrackSharing);
fOutputSP->Add(fNV0protonSharedTracks);
fOutputSP->Add(fNAntiV0protonSharedTracks);
fOutputSP->Add(fNAntiV0AntiprotonSharedTracks);
if(fUseMCInfo)
{
fOutputSP->Add(fLambdaV0vertexXMC);
fOutputSP->Add(fLambdabkgvertexXMC);
fOutputSP->Add(fLambdaV0vertexYMC);
fOutputSP->Add(fLambdabkgvertexYMC);
fOutputSP->Add(fLambdaV0vertexZMC);
fOutputSP->Add(fLambdabkgvertexZMC);
fOutputSP->Add(fDCAV0PosdaughMC);
fOutputSP->Add(fDCAbkgPosdaughMC);
fOutputSP->Add(fDCAV0NegdaughMC);
fOutputSP->Add(fDCAbkgNegdaughMC);
fOutputSP->Add(fTrRadiusV0MC);
fOutputSP->Add(fTrRadiusbkgMC);
fOutputSP->Add(fPoinAngleV0MC);
fOutputSP->Add(fPoinAnglebkgMC);
fOutputSP->Add(fDecayLengthV0MC);
fOutputSP->Add(fDecayLengthbkgMC);
}
fOutputSP->Add(fLambdaDCADaughterTracks);
fOutputSP->Add(fLambdaDCAPrimVertex);
fOutputSP->Add(fLambdaDCAPosdaughPrimVertex);
fOutputSP->Add(fLambdaDCANegdaughPrimVertex);
fOutputSP->Add(fLambdaDecaylength);
fOutputSP->Add(fLambdaCosPointingAngle);
fOutputSP->Add(fLambdaTransverseRadius);
fOutputSP->Add(fProtonDCAxy);
fOutputSP->Add(fProtonDCAxyCutz);
fOutputSP->Add(fProtonDCAz);
fOutputSP->Add(fProtonDCAxyDCAz);
fOutputSP->Add(fAntiProtonDCAxy);
fOutputSP->Add(fAntiProtonDCAxyCutz);
fOutputSP->Add(fAntiProtonDCAz);
fOutputSP->Add(fAntiProtonDCAxyDCAz);
if(fUseMCInfo)
{
fOutputSP->Add(fFeeddownProton);
fOutputSP->Add(fFeeddownProtonFromWeakPDG);
fOutputSP->Add(fFeeddownV0);
fOutputSP->Add(fFeeddownV0FromWeakPDG);
}
fOutputSP->Add(fFindableClusterProton);
fOutputSP->Add(fNCrossedRowsProton);
fOutputSP->Add(fRatioFindableCrossedProton);
fOutputSP->Add(fFindableClusterAntiProton);
fOutputSP->Add(fNCrossedRowsAntiProton);
fOutputSP->Add(fRatioFindableCrossedAntiProton);
//Define two particle histograms:
//p-lambda
TH1F* fProtonLambdaRelK = new TH1F("fProtonLambdaRelK","Relative momentum of V0-p RE",150,0.,3.); //first choice was 300 bins
TH1F* fProtonLambdaRelKME = new TH1F("fProtonLambdaRelKME","Relative momentum of V0-p ME",150,0.,3.);
TH1F* fProtonLambdaPosDaughterRelK = new TH1F("fProtonLambdaPosDaughterRelK","Relative momentum of daughter proton and primary proton RE",150,0.,3.); //first choice was 300 bins
TH1F* fProtonLambdaPosDaughterRelKME = new TH1F("fProtonLambdaPosDaughterRelKME","Relative momentum of daughter proton and primary proton ME",150,0.,3.);
TH1F* fAntiProtonAntiLambdaPosDaughterRelK = new TH1F("fAntiProtonAntiLambdaPosDaughterRelK","Relative momentum of daughter anti-proton and primary anti-proton RE",150,0.,3.); //first choice was 300 bins
TH1F* fAntiProtonAntiLambdaPosDaughterRelKME = new TH1F("fAntiProtonAntiLambdaPosDaughterRelKME","Relative momentum of daughter anti-proton and primary anti-proton ME",150,0.,3.);
//Antip-Antilambda
TH1F* fAntiProtonAntiLambdaRelK = new TH1F("fAntiProtonAntiLambdaRelK","Relative momentum of Anti-V0-Antip RE",500,0.,3.); //first choice was 300 bins
TH1F* fAntiProtonAntiLambdaRelKME = new TH1F("fAntiProtonAntiLambdaRelKME","Relative momentum of Anti-V0-Antip ME",500,0.,3.);
TH1F* fProtonLambdaMT = new TH1F("fProtonLambdaMT","Transverse mass of pL",1000,0.,10.);
TH1F* fProtonLambdaMTrelKcut = new TH1F("fProtonLambdaMTrelKcut","Transverse mass of pL",1000,0.,10.);
//p-Antilambda
TH1F* fAntiProtonLambdaRelK = new TH1F("fAntiProtonLambdaRelK","Relative momentum of V0-Anti-p RE",150,0.,3.); //first choice was 300 bins
TH1F* fAntiProtonLambdaRelKME = new TH1F("fAntiProtonLambdaRelKME","Relative momentum of V0-Anti-p ME",150,0.,3.);
TH1F* fProtonAntiLambdaRelK = new TH1F("fProtonAntiLambdaRelK","Relative momentum of Anti-V0-p RE",150,0.,3.);
TH1F* fProtonAntiLambdaRelKME = new TH1F("fProtonAntiLambdaRelKME","Relative momentum of Anti-V0-p ME",150,0.,3.);
//p-Xi
TH1F* fProtonXiRelK = new TH1F("fProtonXiRelK","Relative momentum of Xi-p RE",150,0.,3.);
TH1F* fProtonXiRelKME = new TH1F("fProtonXiRelKME","Relative momentum of Xi-p ME",150,0.,3.);
TH1F* fAntiProtonXiRelK = new TH1F("fAntiProtonXiRelK","Relative momentum of Xi-Antip RE",150,0.,3.);
TH1F* fAntiProtonXiRelKME = new TH1F("fAntiProtonXiRelKME","Relative momentum of Xi-Antip ME",150,0.,3.);
//p-p
TH1F* fProtonProtonRelK = new TH1F("fProtonProtonRelK","Relative momentum of pp RE",750,0.,3.);
TH1F* fProtonProtonRelKME = new TH1F("fProtonProtonRelKME","Relative momentum of pp ME",750,0.,3.);
TH1F* fProtonProtonMT = new TH1F("fProtonProtonMT","Transverse mass of pp",1000,0.,10.);
TH1F* fProtonProtonMTrelKcut = new TH1F("fProtonProtonMTrelKcut","Transverse mass of pp with relative momentum cut",1000,0.,10.);
//p-p-p
TH1F* fProtonProtonProtonRelK = new TH1F("fProtonProtonProtonRelK","Relative momentum of ppp RE",150,0.,3.);
TH1F* fProtonProtonProtonRelKME = new TH1F("fProtonProtonProtonRelKME","Relative momentum of ppp ME",150,0.,3.);
//p-p-V0
TH1F* fProtonProtonLambdaRelK = new TH1F("fProtonProtonLambdaRelK","Relative momentum of p-p-Lambda RE",300,0.,6.);
TH1F* fProtonProtonLambdaRelKME = new TH1F("fProtonProtonLambdaRelKME","Relative momentum of p-p-Lambda ME",300,0.,6.);
//Antip-Antip
TH1F* fAntiProtonAntiProtonRelK = new TH1F("fAntiProtonAntiProtonRelK","Relative momentum of antip-antip RE",750,0.,3.);
TH1F* fAntiProtonAntiProtonRelKME = new TH1F("fAntiProtonAntiProtonRelKME","Relative momentum of antip-antip ME",750,0.,3.);
//Antip-p
TH1F* fAntiProtonProtonRelK = new TH1F("fAntiProtonProtonRelK","Relative momentum of antip-p RE",300,0.,3.);
TH1F* fAntiProtonProtonRelKME = new TH1F("fAntiProtonProtonRelKME","Relative momentum of p-antip ME",300,0.,3.);
//Lambda-Lambda
TH1F* fLambdaLambdaRelK = new TH1F("fLambdaLambdaRelK","Relative momentum of V0-V0 RE",150,0.,3.);
TH1F* fLambdaLambdaRelKME = new TH1F("fLambdaLambdaRelKME","Relative momentum of V0-V0 ME",150,0.,3.);
//AntiLambda-Lambda
TH1F* fAntiLambdaLambdaRelK = new TH1F("fAntiLambdaLambdaRelK","Relative momentum of AntiV0-V0 RE",150,0.,3.);
TH1F* fAntiLambdaLambdaRelKME = new TH1F("fAntiLambdaLambdaRelKME","Relative momentum of V0-V0 ME",150,0.,3.);
//AntiLambda-AntiLambda
TH1F* fAntiLambdaAntiLambdaRelK = new TH1F("fAntiLambdaAntiLambdaRelK","Relative momentum of AntiV0-AntiV0 RE",150,0.,3.);
TH1F* fAntiLambdaAntiLambdaRelKME = new TH1F("fAntiLambdaAntiLambdaRelKME","Relative momentum of AntiV0-AntiV0 ME",150,0.,3.);
TH1F* fNProtonLambdaPairs = new TH1F("fNProtonLambdaPairs","Number of V0-p pairs in an event",200,0,100);
TH1F* fNPairStatistics = new TH1F("fNPairStatistics","Number of pairs under certain condition",40,0,10);
TH1F* fPairkTLp = new TH1F("fPairkTLp","total transverse momentum of V0-p pair",1000,0.,10.);
TH1F* fPairkTpp = new TH1F("fPairkTpp","total transverse momentum of p-p pair",1000,0.,10.);
TH1F* fPairkTApAp = new TH1F("fPairkTApAp","total transverse momentum of Ap-Ap pair",1000,0.,10.);
TH1F* fPairkTApp = new TH1F("fPairkTApp","total transverse momentum of Ap-p pair",1000,0.,10.);
const Int_t NumberTPCrad = 9;
TH2F* fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProton[NumberTPCrad];
TH2F* fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProtonME[NumberTPCrad];
TH2F* fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPion[NumberTPCrad];
TH2F* fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPionME[NumberTPCrad];
TH2F* fDeltaEtaDeltaPhiTPCradpp[NumberTPCrad];
TH2F* fDeltaEtaDeltaPhiTPCradppME[NumberTPCrad];
for(Int_t i=0;i<NumberTPCrad;i++) //close track eff. as a function of the TPC radius
{
TString HistDesc = "#Delta #eta vs. #Delta #phi for primary proton and decay proton evaluated at TPCradnum = ";
HistDesc += i;
TString HistName = "fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProton";
HistName += i;
fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProton[i] = new TH2F(HistName.Data(),HistDesc.Data(),400,0,4,400,0,1.);
fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProton[i]->Sumw2();
fOutputTP->Add(fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProton[i]);
HistDesc = "#Delta #eta vs. #Delta #phi for primary proton and decay pion evaluated at TPCradnum = ";
HistDesc += i;
HistName = "fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPion";
HistName += i;
fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPion[i] = new TH2F(HistName.Data(),HistDesc.Data(),400,0,4,400,0,1.);
fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPion[i]->Sumw2();
fOutputTP->Add(fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPion[i]);
HistDesc = "#Delta #eta vs. #Delta #phi for primary proton and decay proton in mixed event evaluated at TPCradnum = ";
HistDesc += i;
HistName = "fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProtonME";
HistName += i;
fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProtonME[i] = new TH2F(HistName.Data(),HistDesc.Data(),400,0,4,400,0,1.);
fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProtonME[i]->Sumw2();
fOutputTP->Add(fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProtonME[i]);
HistDesc = "#Delta #eta vs. #Delta #phi for primary proton and decay pion in mixed event evaluated at TPCradnum = ";
HistDesc += i;
HistName = "fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPionME";
HistName += i;
fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPionME[i] = new TH2F(HistName.Data(),HistDesc.Data(),400,0,4,400,0,1.);
fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPionME[i]->Sumw2();
fOutputTP->Add(fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPionME[i]);
HistDesc = "#Delta #eta vs. #Delta #phi for proton-proton pairs evaluated at TPCradnum = ";
HistDesc += i;
HistName = "fDeltaEtaDeltaPhiTPCradpp";
HistName += i;
fDeltaEtaDeltaPhiTPCradpp[i] = new TH2F(HistName.Data(),HistDesc.Data(),400,0,4,400,0,1.);
fDeltaEtaDeltaPhiTPCradpp[i]->Sumw2();
fOutputTP->Add(fDeltaEtaDeltaPhiTPCradpp[i]);
HistDesc = "#Delta #eta vs. #Delta #phi for proton-proton pairs evaluated at TPCradnum = ";
HistDesc += i;
HistName = "fDeltaEtaDeltaPhiTPCradppME";
HistName += i;
fDeltaEtaDeltaPhiTPCradppME[i] = new TH2F(HistName.Data(),HistDesc.Data(),400,0,4,400,0,1.);
fDeltaEtaDeltaPhiTPCradppME[i]->Sumw2();
fOutputTP->Add(fDeltaEtaDeltaPhiTPCradppME[i]);
}
TH2F* fV0PtTrueReco = new TH2F("fV0PtTrueReco","V0: true transverse momentum vs. reconstructed momentum pt",200,0,10,200,0,10);
TH2F* fV0PtResoRecoRotated = new TH2F("fV0PtResoRecoRotated","V0: true transverse momentum vs. reconstructed momentum pt",200,0,10,1000,-1,1);
TH2F* fV0PhiResoRecoRotated = new TH2F("fV0PhiResoRecoRotated","V0: true phi vs. reconstructed momentum pt",200,0,10,3000,-1,1);
TH2F* fV0ThetaResoRecoRotated = new TH2F("fV0ThetaResoRecoRotated","V0: true theta vs. reconstructed momentum pt",200,0,10,3000,-1,1);
TH2F* fProtonPtTrueReco = new TH2F("fProtonPtTrueReco","Proton: true transverse momentum vs. reconstructed momentum pt",600,0,3,600,0,10);
TH2F* fProtonPtResoRecoRotated = new TH2F("fProtonPtResoRecoRotated","Proton: true momentum vs. reconstructed momentum pt in rotated coordinate system",200,0,10,1000,-1,1);
TH2F* fProtonPhiResoRecoRotated = new TH2F("fProtonPhiResoRecoRotated","Proton: true phi vs. reconstructed momentum pt",200,0,10,3000,-1,1);
TH2F* fProtonThetaResoRecoRotated = new TH2F("fProtonThetaResoRecoRotated","Proton: true theta vs. reconstructed momentum pt",200,0,10,3000,-1,1);
TH2F* fV0pRelKTrueReco = new TH2F("fV0pRelKTrueReco","V0p: true momentum vs. reconstructed momentum relK",600,0.,3.,600,0.,3.);
TH2F* fV0pRelKTrueRecoRotated = new TH2F("fV0pRelKTrueRecoRotated","V0p: true momentum vs. reconstructed momentum relK",600,0.,3.,1000,-1.,1.);
TH2F* fPpRelKTrueReco = new TH2F("fPpRelKTrueReco","pp: true momentum vs. reconstructed momentum relK",750,0.,3.,750,0.,3.);
TH2F* fPpRelKTrueRecoFB = new TH2F("fPpRelKTrueRecoFB","pp: true momentum vs. reconstructed momentum relK",1500,0.,3.,1500,0.,3.);
TH2F* fPpRelKTrueRecoRotated = new TH2F("fPpRelKTrueRecoRotated","pp: true momentum vs. reconstructed momentum relK in rotated coordinate system",750,0.,3.,1000,-1.,1.);
TH2F* fPpPV0RelKRelK = new TH2F("fPpPV0RelKRelK","relative momentum transformation from pV0 -> pp",600,0.,3.,600,0.,3.);
fProtonLambdaMT->Sumw2();
fProtonLambdaMTrelKcut->Sumw2();
fProtonLambdaRelK->Sumw2();
fProtonLambdaRelKME->Sumw2();
fProtonLambdaPosDaughterRelK->Sumw2();
fProtonLambdaPosDaughterRelKME->Sumw2();
fAntiProtonAntiLambdaPosDaughterRelK->Sumw2();
fAntiProtonAntiLambdaPosDaughterRelKME->Sumw2();
fAntiProtonLambdaRelK->Sumw2();
fAntiProtonLambdaRelKME->Sumw2();
fProtonAntiLambdaRelK->Sumw2();
fProtonAntiLambdaRelKME->Sumw2();
fAntiProtonAntiLambdaRelK->Sumw2();
fAntiProtonAntiLambdaRelKME->Sumw2();
fProtonXiRelK->Sumw2();
fProtonXiRelKME->Sumw2();
fAntiProtonXiRelK->Sumw2();
fAntiProtonXiRelKME->Sumw2();
fProtonProtonMT->Sumw2();
fProtonProtonMTrelKcut->Sumw2();
fProtonProtonRelK->Sumw2();
fProtonProtonRelKME->Sumw2();
fProtonProtonLambdaRelK->Sumw2();
fProtonProtonLambdaRelKME->Sumw2();
fProtonProtonProtonRelK->Sumw2();
fProtonProtonProtonRelKME->Sumw2();
fAntiProtonAntiProtonRelK->Sumw2();
fAntiProtonAntiProtonRelKME->Sumw2();
fAntiProtonProtonRelK->Sumw2();
fAntiProtonProtonRelKME->Sumw2();
fLambdaLambdaRelK->Sumw2();
fLambdaLambdaRelKME->Sumw2();
fAntiLambdaAntiLambdaRelK->Sumw2();
fAntiLambdaAntiLambdaRelKME->Sumw2();
fAntiLambdaLambdaRelK->Sumw2();
fAntiLambdaLambdaRelKME->Sumw2();
fOutputTP->Add(fProtonLambdaMT);
fOutputTP->Add(fProtonLambdaMTrelKcut);
fOutputTP->Add(fProtonLambdaRelK);
fOutputTP->Add(fProtonLambdaRelKME);
fOutputTP->Add(fProtonLambdaPosDaughterRelK);
fOutputTP->Add(fProtonLambdaPosDaughterRelKME);
fOutputTP->Add(fAntiProtonAntiLambdaPosDaughterRelK);
fOutputTP->Add(fAntiProtonAntiLambdaPosDaughterRelKME);
fOutputTP->Add(fAntiProtonAntiLambdaRelK);
fOutputTP->Add(fAntiProtonAntiLambdaRelKME);
fOutputTP->Add(fProtonAntiLambdaRelK);
fOutputTP->Add(fProtonAntiLambdaRelKME);
fOutputTP->Add(fAntiProtonLambdaRelK);
fOutputTP->Add(fAntiProtonLambdaRelKME);
fOutputTP->Add(fProtonXiRelK);
fOutputTP->Add(fProtonXiRelKME);
fOutputTP->Add(fAntiProtonXiRelK);
fOutputTP->Add(fAntiProtonXiRelKME);
fOutputTP->Add(fProtonProtonLambdaRelK);
fOutputTP->Add(fProtonProtonLambdaRelKME);
fOutputTP->Add(fProtonProtonProtonRelK);
fOutputTP->Add(fProtonProtonProtonRelKME);
fOutputTP->Add(fProtonProtonRelK);
fOutputTP->Add(fProtonProtonRelKME);
fOutputTP->Add(fProtonProtonMT);
fOutputTP->Add(fProtonProtonMTrelKcut);
fOutputTP->Add(fAntiProtonAntiProtonRelK);
fOutputTP->Add(fAntiProtonAntiProtonRelKME);
fOutputTP->Add(fAntiProtonProtonRelK);
fOutputTP->Add(fAntiProtonProtonRelKME);
fOutputTP->Add(fLambdaLambdaRelK);
fOutputTP->Add(fLambdaLambdaRelKME);
fOutputTP->Add(fAntiLambdaAntiLambdaRelK);
fOutputTP->Add(fAntiLambdaAntiLambdaRelKME);
fOutputTP->Add(fAntiLambdaLambdaRelK);
fOutputTP->Add(fAntiLambdaLambdaRelKME);
fOutputTP->Add(fNProtonLambdaPairs);
fOutputTP->Add(fNPairStatistics);
fOutputTP->Add(fPairkTLp);
fOutputTP->Add(fPairkTpp);
fOutputTP->Add(fPairkTApAp);
fOutputTP->Add(fPairkTApp);
if(fUseMCInfo)
{
fOutputTP->Add(fV0PtTrueReco);
fOutputTP->Add(fV0PtResoRecoRotated);
fOutputTP->Add(fV0PhiResoRecoRotated);
fOutputTP->Add(fV0ThetaResoRecoRotated);
fOutputTP->Add(fProtonPtTrueReco);
fOutputTP->Add(fProtonPtResoRecoRotated);
fOutputTP->Add(fProtonPhiResoRecoRotated);
fOutputTP->Add(fProtonThetaResoRecoRotated);
fOutputTP->Add(fV0pRelKTrueReco);
fOutputTP->Add(fV0pRelKTrueRecoRotated);
fOutputTP->Add(fPpRelKTrueReco);
fOutputTP->Add(fPpRelKTrueRecoFB);
fOutputTP->Add(fPpRelKTrueRecoRotated);
fOutputTP->Add(fPpPV0RelKRelK);
}
//Define PID related histograms:
TH2F* fdEdxVsP = new TH2F("fdEdxVsP","dE/dx of all particles vs momentum",1000,0,7,400,-10,200);
TH2F* fTOFSignalVsP = new TH2F ("fTOFSignalVsP","tof signal vs p (positives);p [GeV/c];t_{meas} - t_{0} - t_{expected} [ps]",20,0.0,5.0,120,-10000.0,5000.0);
TH2F* fProtonNSigmaTPC = new TH2F("fProtonNSigmaTPC","nsigma_TPC of protons for P<0.75 GeV/c without TOF signal",100,0,1,100,-1.,5.);
TH2F* fProtonNSigmaCombined = new TH2F("fProtonNSigmaCombined","nsigma_combined of protons for P>0.75 GeV/c",500,0.5,7,100,-1.,5.);
TH2F* fNsigmaTOFTPCPtBin[fCuts->GetPtBinsPurity()];
TH2F* fNsigmaTOFTPCHypothesisIncludedPtBin[fCuts->GetPtBinsPurity()];
TH1F* fProtonPurityTOFTPCcombinedMCPtBin[fCuts->GetPtBinsPurity()];
for(Int_t i=0;i<fCuts->GetPtBinsPurity();i++)
{
TString HistName = "fNsigmaTOFTPCPtBin";
HistName += i;
TString Description = "nsigma of TPC vs nsigma of TOF for momentum bin ";
Description += i;
fNsigmaTOFTPCPtBin[i] = new TH2F(HistName.Data(),Description.Data(),200,-10,10,200,-10,10);
fOutputPID->Add(fNsigmaTOFTPCPtBin[i]);
HistName = "fNsigmaTOFTPCHypothesisIncludedPtBin";
HistName += i;
Description = "nsigma of TPC vs nsigma of TOF for momentum bin ";
Description += i;
fNsigmaTOFTPCHypothesisIncludedPtBin[i] = new TH2F(HistName.Data(),Description.Data(),200,-10,10,200,-10,10);
fOutputPID->Add(fNsigmaTOFTPCHypothesisIncludedPtBin[i]);
if(fUseMCInfo)
{
HistName = "fProtonPurityTOFTPCcombinedMCPtBin";
HistName += i;
Description = "Total: 1, Signal: 2, Background: 3, purity for protons with kaon rejection and n#sigma_{combined}<3 in momentum bin ";
Description += i;
fProtonPurityTOFTPCcombinedMCPtBin[i] = new TH1F(HistName.Data(),Description.Data(),4,0,4);
fOutputPID->Add(fProtonPurityTOFTPCcombinedMCPtBin[i]);
}
}
fOutputPID->Add(fdEdxVsP);
fOutputPID->Add(fTOFSignalVsP);
fOutputPID->Add(fProtonNSigmaTPC);
fOutputPID->Add(fProtonNSigmaCombined);
return;
}
Bool_t AliAnalysisTaskPLFemto::SelectPID(const AliAODTrack *track,const AliAODEvent *aodevent,Int_t type)
{
//Comment: In the SingleParticleQA function goodDCA is called after SelectPID. To have plots which include already
//the goodDCA decision it was partly included in the SelectPID function even if the clarity gets a bit lost
Double_t charge = track->Charge();
if(type == 4 && charge<0.) return kFALSE;
else if(type == -4 && charge>0.) return kFALSE;
const AliAODTrack *globaltrack;
if(fWhichfilterbit == 128) globaltrack = fGTI[-track->GetID()-1];
else globaltrack = track;
Bool_t isparticle = kFALSE;
TClonesArray *mcarray = 0;
AliAODMCParticle* mcproton = 0;
if(fUseMCInfo)
{
mcarray = dynamic_cast<TClonesArray*>(aodevent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcarray) return kFALSE;
if(track->GetLabel() >=0) mcproton = (AliAODMCParticle*)mcarray->At(track->GetLabel());
else return kFALSE;//check this flag out! it rejects in principle all fake tracks in the analysis
}
//there must be TPC & TOF signal (TOF for P>0.75 GeV/c)
Bool_t TPCisthere = kFALSE;
Bool_t TOFisthere = kFALSE;
AliPIDResponse::EDetPidStatus statusTPC = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTPC,globaltrack);
if(statusTPC == AliPIDResponse::kDetPidOk) TPCisthere = kTRUE;
AliPIDResponse::EDetPidStatus statusTOF = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF,globaltrack);
if(statusTOF == AliPIDResponse::kDetPidOk) TOFisthere = kTRUE;
if(!TPCisthere) return kFALSE; //TPC signal must be there
TString fillthis = "fdEdxVsP";
((TH2F*)(fOutputPID->FindObject(fillthis)))->Fill(globaltrack->GetTPCmomentum(),globaltrack->GetTPCsignal());
//Now do particle identification:
if(globaltrack->GetTPCmomentum() <= fCuts->GetProtonPIDTOFTPCSwitch())//for P<0.75 use TPC
{
Double_t nSigmaProtonTPConly = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(globaltrack,(AliPID::kProton)));
fillthis = "fProtonNSigmaTPC";
if(type == 4)((TH2F*)(fOutputPID->FindObject(fillthis)))->Fill(globaltrack->GetTPCmomentum(),nSigmaProtonTPConly);
if(nSigmaProtonTPConly < fCuts->GetProtonnsigma()) isparticle = kTRUE;
}
else if(globaltrack->GetTPCmomentum() > fCuts->GetProtonPIDTOFTPCSwitch())//for P>0.75 GeV/c use TPC&TOF
{
if(!TOFisthere) return kFALSE;//makes only sense if TOF PID is available (TPC signal was checked already at the beginning)
Double_t corrTOFsignal = GetCorrectedTOFSignal(globaltrack,aodevent);
Double_t nSigmaTPCproton = fPIDResponse->NumberOfSigmasTPC(globaltrack,(AliPID::kProton));
Double_t nSigmaTOFproton = fPIDResponse->NumberOfSigmasTOF(globaltrack,(AliPID::kProton));
Double_t nSigmaTPCTOFcombined = TMath::Sqrt(pow(nSigmaTPCproton,2.) + pow(nSigmaTOFproton,2.));
//if(type == 4 && GoodDCA(track,aodevent,kTRUE,type))
if(type == 4)
{
fillthis = "fProtonNSigmaCombined";
((TH2F*)(fOutputPID->FindObject(fillthis)))->Fill(globaltrack->P(),nSigmaTPCTOFcombined);
fillthis = "fTOFSignalVsP";
((TH2F*)(fOutputPID->FindObject(fillthis)))->Fill(globaltrack->GetTPCmomentum(),corrTOFsignal);
}
if(nSigmaTPCTOFcombined < fCuts->GetProtonnsigma() && TestPIDHypothesis(globaltrack,type)) isparticle = kTRUE;//full PID for high momentum region
//QA the PID differentially as a function of pt
Int_t ptbin = fCuts->FindProtonPtBinPurity(globaltrack->GetTPCmomentum());
//if(ptbin != -9999 && GoodDCA(track,aodevent,kTRUE,type))
if(ptbin != -9999)
{
//investigate this as a function of momentum slices:
if(type == 4)
{
fillthis = "fNsigmaTOFTPCPtBin";
fillthis += ptbin;
((TH2F*)(fOutputPID->FindObject(fillthis)))->Fill(nSigmaTPCproton,nSigmaTOFproton);
if(TestPIDHypothesis(globaltrack,type))
{
fillthis = "fNsigmaTOFTPCHypothesisIncludedPtBin";
fillthis += ptbin;
((TH2F*)(fOutputPID->FindObject(fillthis)))->Fill(nSigmaTPCproton,nSigmaTOFproton);
}
}
//Investigate the purity for the selected particles (in Monte Carlo):
if(isparticle)
{
if(fUseMCInfo)
{
//check with monte carlo the purity:
if(type == 4)
{
fillthis = "fProtonPurityTOFTPCcombinedMCPtBin";
fillthis += ptbin;
((TH1F*)(fOutputPID->FindObject(fillthis)))->Fill(1);
}
if(type == 4 && mcproton->GetPdgCode() == 2212)
{
fillthis = "fProtonPurityTOFTPCcombinedMCPtBin";
fillthis += ptbin;
((TH1F*)(fOutputPID->FindObject(fillthis)))->Fill(2);
}
else if(type == 4 && mcproton->GetPdgCode() != 2212)
{
fillthis = "fProtonPurityTOFTPCcombinedMCPtBin";
fillthis += ptbin;
((TH1F*)(fOutputPID->FindObject(fillthis)))->Fill(3);
}
}
}
}
}
return isparticle;
}
Bool_t AliAnalysisTaskPLFemto::TestPIDHypothesis(const AliAODTrack *track,Int_t type)
{
//For P>0.75 GeV/c the TPC dE/dx bands start to merge, we apply an additional test to the PID of the particle (proton)
//const AliAODTrack *globaltrack;
//if(fWhichfilterbit == 128) globaltrack = fGTI[-track->GetID()-1];
//else globaltrack = track;
Double_t charge = track->Charge();
if(type == 4 && charge<0.) return kFALSE;
else if(type == -4 && charge>0.) return kFALSE;
Bool_t keepParticle = kTRUE;
if(track->GetTPCmomentum() <= fCuts->GetProtonPIDTOFTPCSwitch()) return kTRUE;//don't check for low momentum tracks
else
{
AliPIDResponse::EDetPidStatus statusTPC = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTPC,track);
AliPIDResponse::EDetPidStatus statusTOF = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF,track);
if(!statusTPC) return kTRUE; //TPC signal must be present
if(!statusTOF) return kTRUE; //TOF signal must be present
Double_t nSigmaProtonTPC = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(track,(AliPID::kProton)));
Double_t nSigmaKaonTPC = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(track,(AliPID::kKaon)));
Double_t nSigmaPionTPC = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(track,(AliPID::kPion)));
Double_t nSigmaElectronTPC = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(track,(AliPID::kElectron)));
Double_t nSigmaProtonTOF = TMath::Abs(fPIDResponse->NumberOfSigmasTOF(track,(AliPID::kProton)));
Double_t nSigmaKaonTOF = TMath::Abs(fPIDResponse->NumberOfSigmasTOF(track,(AliPID::kKaon)));
Double_t nSigmaPionTOF = TMath::Abs(fPIDResponse->NumberOfSigmasTOF(track,(AliPID::kPion)));
Double_t nSigmaElectronTOF = TMath::Abs(fPIDResponse->NumberOfSigmasTOF(track,(AliPID::kElectron)));
//Form the combination:
Double_t nSigmaProtonCombined = TMath::Sqrt(pow(nSigmaProtonTPC,2.) + pow(nSigmaProtonTOF,2.));
Double_t nSigmaKaonCombined = TMath::Sqrt(pow(nSigmaKaonTPC,2.) + pow(nSigmaKaonTOF,2.));
Double_t nSigmaPionCombined = TMath::Sqrt(pow(nSigmaPionTPC,2.) + pow(nSigmaPionTOF,2.));
Double_t nSigmaElectronCombined = TMath::Sqrt(pow(nSigmaElectronTPC,2.) + pow(nSigmaElectronTOF,2.));
//The other hypothesis fits better:
if((nSigmaKaonCombined < nSigmaProtonCombined) || (nSigmaPionCombined < nSigmaProtonCombined) || (nSigmaElectronCombined < nSigmaProtonCombined)) keepParticle = kFALSE;
}
return keepParticle;
}
Bool_t AliAnalysisTaskPLFemto::SelectV0PID(const AliAODv0 *v0,TString ParOrAPar)
{
AliAODTrack* pTrack = fGTI[v0->GetPosID()];
AliAODTrack* nTrack = fGTI[v0->GetNegID()];
Double_t charge1 = pTrack->Charge();
Double_t charge2 = nTrack->Charge();
if(charge1 < 0. && charge2 > 0. && ParOrAPar == fwhichV0)//assign correct charge to tracks from V0
{
pTrack = fGTI[v0->GetNegID()];//proton as positive particle
nTrack = fGTI[v0->GetPosID()];//pion as negative particle
}
else if(charge1 > 0. && charge2 <0. && ParOrAPar == fwhichAntiV0)//assign correct charge to tracks from Anti-V0
{
pTrack = fGTI[v0->GetNegID()];//anti-proton as negative particle
nTrack = fGTI[v0->GetPosID()];//anti-pion as positive particle
}
else if((charge1>0. && charge2>0.) || (charge1<0. && charge2<0.))
{
return kFALSE;
}
//new method for checking detector status:
AliPIDResponse::EDetPidStatus statusPosTPC = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTPC,pTrack);
if(statusPosTPC != AliPIDResponse::kDetPidOk) return kFALSE;
AliPIDResponse::EDetPidStatus statusNegTPC = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTPC,nTrack);
if(statusNegTPC != AliPIDResponse::kDetPidOk) return kFALSE;
Bool_t isV0 = kFALSE;
Bool_t isProton = kFALSE;
Bool_t isPion = kFALSE;
Double_t nSigmaProtonTPC = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(pTrack,(AliPID::kProton)));
if(nSigmaProtonTPC < fCuts->GetV0nsigma()) isProton = kTRUE;
Double_t nSigmaPionTPC = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(nTrack,(AliPID::kPion)));
if(nSigmaPionTPC < fCuts->GetV0nsigma()) isPion = kTRUE;
if(isProton && isPion) isV0 = kTRUE;
return isV0;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::GetGlobalPositionAtGlobalRadiiThroughTPC(const AliAODTrack *track, const Float_t bfield,double globalPositionsAtRadii[9][3], double PrimaryVertex[3])
{
// Gets the global position of the track at nine different radii in the TPC
// track is the track you want to propagate
// bfield is the magnetic field of your event
// globalPositionsAtRadii is the array of global positions in the radii and xyz
// Initialize the array to something indicating there was no propagation
for(Int_t i=0;i<9;i++)
{
for(Int_t j=0;j<3;j++)
{
globalPositionsAtRadii[i][j]=-9999.;
}
}
// Make a copy of the track to not change parameters of the track
AliExternalTrackParam etp; etp.CopyFromVTrack(track);
//printf("\nAfter CopyFromVTrack\n");
//etp.Print();
// The global position of the the track
Double_t xyz[3]={-9999.,-9999.,-9999.};
// Counter for which radius we want
Int_t iR=0;
// The radii at which we get the global positions
// IROC (OROC) from 84.1 cm to 132.1 cm (134.6 cm to 246.6 cm)
//Float_t Rwanted[9]={85.,105.,125.,145.,165.,185.,205.,225.,245.};
// The global radius we are at
Float_t globalRadius=0;
// Propagation is done in local x of the track
for (Float_t x = etp.GetX();x<247.;x+=1.)
{
// GetX returns local coordinates
// Starts at the tracks fX and goes outwards. x = 245 is the outer radial limit
// of the TPC when the track is straight, i.e. has inifinite pt and doesn't get bent.
// If the track's momentum is smaller than infinite, it will develop a y-component, which
// adds to the global radius
// Stop if the propagation was not succesful. This can happen for low pt tracks
// that don't reach outer radii
if(!etp.PropagateTo(x,bfield)) break;
etp.GetXYZ(xyz); // GetXYZ returns global coordinates
globalRadius = TMath::Sqrt(xyz[0]*xyz[0]+xyz[1]*xyz[1]); //Idea to speed up: compare squared radii
// Roughly reached the radius we want
if(globalRadius > fTPCradii[iR])
{
// Bigger loop has bad precision, we're nearly one centimeter too far, go back in small steps.
while (globalRadius>fTPCradii[iR])
{
x-=.1;
//printf("propagating to x %5.2f\n",x);
if(!etp.PropagateTo(x,bfield)) break;
etp.GetXYZ(xyz); // GetXYZ returns global coordinates
globalRadius = TMath::Sqrt(xyz[0]*xyz[0]+xyz[1]*xyz[1]); //Idea to speed up: compare squared radii
}
//printf("At Radius:%05.2f (local x %5.2f). Setting position to x %4.1f y %4.1f z %4.1f\n",globalRadius,x,xyz[0],xyz[1],xyz[2]);
globalPositionsAtRadii[iR][0]=xyz[0];
globalPositionsAtRadii[iR][1]=xyz[1];
globalPositionsAtRadii[iR][2]=xyz[2];
//subtract primary vertex, "zero" track for correct mixed-event comparison
globalPositionsAtRadii[iR][0] -= PrimaryVertex[0];
globalPositionsAtRadii[iR][1] -= PrimaryVertex[1];
globalPositionsAtRadii[iR][2] -= PrimaryVertex[2];
// Indicate we want the next radius
iR+=1;
}
if(iR>8) return; //TPC edge reached
}
}
//________________________________________________________________________
Double_t AliAnalysisTaskPLFemto::DEtacalc(const double zprime1, const double zprime2, const double radius)
{
double thetaS1 = TMath::Pi()/2. - TMath::ATan(zprime1/radius);
double thetaS2 = TMath::Pi()/2. - TMath::ATan(zprime2/radius);
double etaS1 = -TMath::Log(TMath::Tan(thetaS1/2.));
double etaS2 = -TMath::Log(TMath::Tan(thetaS2/2.));
double detaS = etaS1 - etaS2;
return detaS;
}
//________________________________________________________________________
Double_t AliAnalysisTaskPLFemto::DPhicalc(const double dxprime, const double dyprime, const double radius)
{
double dist = TMath::Sqrt(pow(dxprime,2.) + pow(dyprime,2.));
double dphi = 2.*TMath::ATan(dist/(2.*radius));
return dphi;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::GetAverageSeparation(const double globalPositions1st[9][3],const double globalPositions2nd[9][3],Int_t REorME,TString whichpair,double *average_separation)
{
int numPoints = 0;
TString fillthis = "";
//Compute the separation of two daughter tracks, averaged over 9 different positions
double avgSeparationTotal = 0.;
double avgSeparationTransverse = 0.;
double avgSeparationZ = 0.;
for(int RadiusNumber = 0; RadiusNumber <9; RadiusNumber++)
{
double sumsquareTotal = 0.;
double sumsquareTransverse = 0.;
double sumsquareZ = 0.;
//Calculate different separations:
for(int Component = 0; Component <3; Component++)
{
//Check first if all components were calculated properly:
if(globalPositions1st[RadiusNumber][Component] == -9999. || globalPositions2nd[RadiusNumber][Component] == -9999.) continue;
sumsquareTotal += pow(globalPositions1st[RadiusNumber][Component] - globalPositions2nd[RadiusNumber][Component],2);
if(Component<2) sumsquareTransverse += pow(globalPositions1st[RadiusNumber][Component] - globalPositions2nd[RadiusNumber][Component],2);
else sumsquareZ += pow(globalPositions1st[RadiusNumber][Component] - globalPositions2nd[RadiusNumber][Component],2);
numPoints++;
}
double dxprime = globalPositions1st[RadiusNumber][0] - globalPositions2nd[RadiusNumber][0];
double dyprime = globalPositions1st[RadiusNumber][1] - globalPositions2nd[RadiusNumber][1];
//Calculate Angle observables:
double detaS = DEtacalc(globalPositions1st[RadiusNumber][2],globalPositions2nd[RadiusNumber][2],fTPCradii[RadiusNumber]);
double dphiS = DPhicalc(dxprime,dyprime,fTPCradii[RadiusNumber]);
detaS = TMath::Abs(detaS);
dphiS = TMath::Abs(dphiS);
if(REorME == 0 && whichpair=="Proton-V0,pp")
{
fillthis = "fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProton";
fillthis += RadiusNumber;
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(detaS,dphiS);
}
else if(REorME != 0 && whichpair=="Proton-V0,pp")
{
fillthis = "fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughProtonME";
fillthis += RadiusNumber;
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(detaS,dphiS);
}
else if(REorME == 0 && whichpair=="Proton-V0,ppim")
{
fillthis = "fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPion";
fillthis += RadiusNumber;
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(detaS,dphiS);
}
else if(REorME != 0 && whichpair=="Proton-V0,ppim")
{
fillthis = "fDeltaEtaDeltaPhiTPCradLpPrimProtonDaughPionME";
fillthis += RadiusNumber;
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(detaS,dphiS);
}
avgSeparationTotal += sqrt(sumsquareTotal);
avgSeparationTransverse += sqrt(sumsquareTransverse);
avgSeparationZ += sqrt(sumsquareZ);
}
if(numPoints != 0)
{
avgSeparationTotal /= (Double_t)numPoints;
avgSeparationTransverse /= (Double_t)numPoints;
avgSeparationZ /= (Double_t)numPoints;
}
else
{
avgSeparationTotal = -9999.;
avgSeparationTransverse = -9999.;
avgSeparationZ = -9999.;
}
average_separation[0] = avgSeparationTotal;
average_separation[1] = avgSeparationTransverse;
average_separation[2] = avgSeparationZ;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::CheckIfRealV0(AliAODv0 *v0,AliAODEvent *aodEvent,Int_t PDGmother,Int_t PDGdaugh1, Int_t PDGdaugh2)
{
//Checks according to daughter tracks and mother PDG if the V0 is real or fake
Bool_t realV0 = kFALSE;
TClonesArray *mcarray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if(!mcarray) return kFALSE;
//Int_t daugh[2] = {2212,211};//daughter IDs of Lambda
Int_t daugh[2];
daugh[0] = PDGdaugh1;
daugh[1] = PDGdaugh2;
Int_t label = v0->MatchToMC(PDGmother,mcarray,2,daugh);
//Int_t label = v0->MatchToMC(PDGmother,mcarray);
if(label >= 0) realV0 = kTRUE;
return realV0;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::GetV0Origin(AliAODv0 *v0,AliAODEvent *aodEvent)
{
//Checks where the V0 comes from, e.g. feed-down or primary
TString fillthis = "";
TClonesArray *mcarray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcarray) return;
Int_t daugh[2] = {2212,211};//daughter IDs of Lambda
Int_t label = v0->MatchToMC(3122,mcarray,2,daugh);
if(label<0) return;// only "true" if it is a real v0
AliAODMCParticle *MCv0 = (AliAODMCParticle*)mcarray->At(label);
if(!MCv0) return;
fillthis = "fFeeddownV0";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1);
if(MCv0->IsPhysicalPrimary() && !MCv0->IsSecondaryFromWeakDecay())
{
fillthis = "fFeeddownV0";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(2);
}
else if(MCv0->IsSecondaryFromWeakDecay())
{
AliAODMCParticle* MCv0Mother = (AliAODMCParticle*)mcarray->At(MCv0->GetMother());
fillthis = "fFeeddownV0";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(3);
fillthis = "fFeeddownV0FromWeakPDG";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(MCv0Mother->PdgCode());
}
else if(MCv0->IsSecondaryFromMaterial())
{
fillthis = "fFeeddownV0";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(4);
}
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::GetProtonOrigin(AliAODTrack *AODtrack,AliAODEvent *aodEvent,Int_t type)
{
//Checks where the proton comes from, e.g. feed-down or primary
Int_t desiredPDGcode = 0;
if(type == 4) desiredPDGcode = 2212;
else if(type == -4) desiredPDGcode = -2212;
else std::cout << "type is wrong" << std::endl;
//Momentum Matrix for single particle
TString fillthis = "";
TClonesArray *mcarray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcarray) return;
if(AODtrack->GetLabel() < 0) return;
AliAODMCParticle* mcproton = (AliAODMCParticle*)mcarray->At(AODtrack->GetLabel());
if(!mcproton) return;
if(mcproton->GetPdgCode() != desiredPDGcode) return; //be shure it is a proton/antiproton
//check where the proton comes from in Monte Carlo:
if(type == 4)
{
fillthis = "fFeeddownProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(1);//total amount of protons
if(mcproton->IsPhysicalPrimary() && !mcproton->IsSecondaryFromWeakDecay())
{
fillthis = "fFeeddownProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(2);//primary and not from weak decay
}
else if(mcproton->IsSecondaryFromWeakDecay() && !mcproton->IsSecondaryFromMaterial())
{
AliAODMCParticle* mcprotonMother = (AliAODMCParticle*)mcarray->At(mcproton->GetMother());
fillthis = "fFeeddownProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(3);//from weak decay
fillthis = "fFeeddownProtonFromWeakPDG";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(mcprotonMother->PdgCode());
}
else if(mcproton->IsSecondaryFromMaterial())
{
fillthis = "fFeeddownProton";
((TH1F*)(fOutputSP->FindObject(fillthis)))->Fill(4);//from material
}
}
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::GetMomentumMatrix(const AliFemtoLambdaParticle &v0,const AliFemtoProtonParticle &proton)
{
//This function calculates the effect of the finite momentum resolution of ALICE for v0s
TLorentzVector trackV0,trackProton,trackV0MC,trackProtonMC;
trackV0.SetXYZM(v0.fMomentum.X(),v0.fMomentum.Y(),v0.fMomentum.Z(),fCuts->GetHadronMasses(3122));
trackProton.SetXYZM(proton.fMomentum.X(),proton.fMomentum.Y(),proton.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackV0MC.SetXYZM(v0.fMomentumMC.X(),v0.fMomentumMC.Y(),v0.fMomentumMC.Z(),fCuts->GetHadronMasses(3122));
trackProtonMC.SetXYZM(proton.fMomentumMC.X(),proton.fMomentumMC.Y(),proton.fMomentumMC.Z(),fCuts->GetHadronMasses(2212));
if(trackV0MC.X() == -9999. || trackProtonMC.X() == -9999.) return;
if(trackV0MC.Y() == -9999. || trackProtonMC.Y() == -9999.) return;
if(trackV0MC.Z() == -9999. || trackProtonMC.Z() == -9999.) return;
Double_t relK = relKcalc(trackV0,trackProton);
Double_t relKMC = relKcalc(trackV0MC,trackProtonMC);
TString fillthis = "fV0pRelKTrueReco";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(relKMC,relK);
Double_t relKTruePrime = 1./TMath::Sqrt(2.)*(relKMC - relK);
Double_t relKRecoPrime = 1./TMath::Sqrt(2.)*(relKMC + relK);
fillthis = "fV0pRelKTrueRecoRotated";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(relKRecoPrime,relKTruePrime);
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::GetMomentumMatrix(const AliFemtoProtonParticle &proton1,const AliFemtoProtonParticle &proton2)
{
//This function calculates the effect of the finite momentum resolution of ALICE for protons
//It takes the input of the proton momentum and the reconstructed momentum
TLorentzVector trackProton1,trackProton2,trackProton1MC,trackProton2MC;
trackProton1.SetXYZM(proton1.fMomentum.X(),proton1.fMomentum.Y(),proton1.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackProton2.SetXYZM(proton2.fMomentum.X(),proton2.fMomentum.Y(),proton2.fMomentum.Z(),fCuts->GetHadronMasses(2212));
trackProton1MC.SetXYZM(proton1.fMomentumMC.X(),proton1.fMomentumMC.Y(),proton1.fMomentumMC.Z(),fCuts->GetHadronMasses(2212));
trackProton2MC.SetXYZM(proton2.fMomentumMC.X(),proton2.fMomentumMC.Y(),proton2.fMomentumMC.Z(),fCuts->GetHadronMasses(2212));
if(trackProton1MC.X() == -9999. || trackProton2MC.X() == -9999.) return;
if(trackProton1MC.Y() == -9999. || trackProton2MC.Y() == -9999.) return;
if(trackProton1MC.Z() == -9999. || trackProton2MC.Z() == -9999.) return;
Double_t relK = relKcalc(trackProton1,trackProton2);
Double_t relKMC = relKcalc(trackProton1MC,trackProton2MC);
TString fillthis = "fPpRelKTrueReco";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(relKMC,relK);
fillthis = "fPpRelKTrueRecoFB";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(relKMC,relK);
Double_t relKTruePrime = 1./TMath::Sqrt(2.)*(relKMC - relK);
Double_t relKRecoPrime = 1./TMath::Sqrt(2.)*(relKMC + relK);
fillthis = "fPpRelKTrueRecoRotated";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(relKRecoPrime,relKTruePrime);
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::CheckMCPID(AliAODEvent *aodEvent, AliAODTrack* aodtrack,int pdg)
{
//Checks the input track according to given PDG value
TClonesArray *mcarray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if(!mcarray) return kFALSE;
if(aodtrack->GetLabel() < 0) return kFALSE;
AliAODMCParticle* mcPart = (AliAODMCParticle*)mcarray->At(aodtrack->GetLabel());
if(!mcPart) return kFALSE;
if(mcPart->GetPdgCode() == pdg) return kTRUE;
else return kFALSE;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskPLFemto::CheckMCPID(AliAODv0 *v0,AliAODEvent* aodEvent,int pdg)
{
//Checks if the input v0 is a real V0
TClonesArray *mcarray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if(!mcarray) return kFALSE;
Int_t daugh[2] = {2212,211};//daughter IDs of Lambda
Int_t label = v0->MatchToMC(3122,mcarray,2,daugh);
if(label<0) return kFALSE;// only "true" if it is a real v0
AliAODMCParticle* mcPart = (AliAODMCParticle*)mcarray->At(label);
if(!mcPart) return kFALSE;
if(mcPart->GetPdgCode() == pdg) return kTRUE;
else return kFALSE;
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::GetMCMomentum(AliAODTrack *aodtrack,double *Protontruth,double *ProtontruthMother,double *ProtontruthMotherParton,int *PDGcodes,AliAODEvent *aodEvent, Int_t type)
{
TString fillthis = "";
if(aodtrack->GetLabel() < 0) return; //reject fakes
AliAODMCParticle *mcproton = (AliAODMCParticle*)fAODMCEvent->GetTrack(aodtrack->GetLabel());
if(!mcproton) return;
if(type == 4 && mcproton->GetPdgCode() != 2212) return;
else if(type == -4 && mcproton->GetPdgCode() != -2212) return;
if(!mcproton->PxPyPz(Protontruth)) std::cout << "Err copying true momentum" << std::endl;
fillthis = "fProtonPtTrueReco";
if(mcproton->Pt() && aodtrack->Pt())((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(mcproton->Pt(),aodtrack->Pt());
if(Protontruth[0] != -9999.)
{
TLorentzVector protonVec;//needed if mass is involved
protonVec.SetXYZM(aodtrack->Px(),aodtrack->Py(),aodtrack->Pz(),fCuts->GetHadronMasses(2212));
Double_t ptTrue = mcproton->Pt();
Double_t ptReco = aodtrack->Pt();
Double_t ptTruePrime = 1./TMath::Sqrt(2.)*(ptTrue - ptReco);
Double_t ptRecoPrime = 1./TMath::Sqrt(2.)*(ptTrue + ptReco);
Double_t phiTrue = mcproton->Phi();
Double_t phiReco = aodtrack->Phi();
Double_t phiTruePrime = phiTrue - phiReco;
Double_t thetaTrue = mcproton->Theta();
Double_t thetaReco = aodtrack->Theta();
Double_t thetaTruePrime = thetaTrue - thetaReco;
fillthis = "fProtonPtResoRecoRotated";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(ptReco,ptTruePrime);
fillthis = "fProtonPhiResoRecoRotated";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(ptReco,phiTruePrime);
fillthis = "fProtonThetaResoRecoRotated";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(ptReco,thetaTruePrime);
}
//check if proton is from feed-down
if(mcproton->IsSecondaryFromWeakDecay())
{
//AliAODMCParticle* mcproton_motherWeak = (AliAODMCParticle*)mcarray->At(mcproton->GetMother());
AliAODMCParticle* mcprotonMotherWeak = (AliAODMCParticle*)fAODMCEvent->GetTrack(mcproton->GetMother());
if(!mcprotonMotherWeak->PxPyPz(ProtontruthMother)) std::cout << "Err copying true momentum" << std::endl;
PDGcodes[0] = mcprotonMotherWeak->PdgCode();
}
}
//________________________________________________________________________
void AliAnalysisTaskPLFemto::GetMCMomentum(AliAODv0 *v0,double *V0momtruth,double *V0momtruthMother,AliAODEvent *aodEvent)
{
TString fillthis = "";
//Momentum Matrix for single-particle quantities
//MCv0 is the v0 from MC (checked for correct daughter tracks and if its not a fake)
//v0 is the reconstructed v0
TClonesArray *mcarray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcarray) return;
Int_t daugh[2] = {2212,211};//daughter IDs of Lambda
Int_t label = v0->MatchToMC(3122,mcarray,2,daugh);
if(label<0) return;// only "true" if it is a real v0
AliAODMCParticle *MCv0 = (AliAODMCParticle*)mcarray->At(label);
if(!MCv0) return;
if(!MCv0->PxPyPz(V0momtruth)) std::cout << "Err copying true momentum" << std::endl;
fillthis = "fV0PtTrueReco";
if(MCv0->Pt() && v0->Pt())((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(MCv0->Pt(),v0->Pt());
if(V0momtruth[0] != -9999.)
{
Double_t ptTrue = MCv0->Pt();
Double_t ptReco = v0->Pt();
Double_t ptTruePrime = 1./TMath::Sqrt(2.)*(ptTrue - ptReco);
Double_t ptRecoPrime = 1./TMath::Sqrt(2.)*(ptTrue + ptReco);
Double_t phiTrue = MCv0->Phi();
Double_t phiReco = v0->Phi();
Double_t phiTruePrime = phiTrue - phiReco;
Double_t thetaTrue = MCv0->Theta();
Double_t thetaReco = v0->Theta();
Double_t thetaTruePrime = thetaTrue - thetaReco;
fillthis = "fV0PtResoRecoRotated";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(ptReco,ptTruePrime);
fillthis = "fV0PhiResoRecoRotated";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(ptReco,phiTruePrime);
fillthis = "fV0ThetaResoRecoRotated";
((TH2F*)(fOutputTP->FindObject(fillthis)))->Fill(ptReco,thetaTruePrime);
}
//check if V0 is from feed-down:
if(MCv0->IsSecondaryFromWeakDecay())
{
AliAODMCParticle* MCv0Mother = (AliAODMCParticle*)mcarray->At(MCv0->GetMother());
if(!MCv0Mother->PxPyPz(V0momtruthMother)) std::cout << "Err copying true momentum" << std::endl;
V0momtruthMother[3] = MCv0Mother->PdgCode();
}
}
| 39.470489
| 206
| 0.699015
|
wiechula
|
cabe427a88dc37e6fb397f850445d187c81bc709
| 2,578
|
hpp
|
C++
|
src/mlpack/methods/ann/activation_functions/tanh_exponential_function.hpp
|
laszlzso/mlpack
|
52e123e56792638c957d0229b001ae14a9e94a75
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4
|
2019-07-09T21:52:01.000Z
|
2020-07-29T19:14:33.000Z
|
src/mlpack/methods/ann/activation_functions/tanh_exponential_function.hpp
|
laszlzso/mlpack
|
52e123e56792638c957d0229b001ae14a9e94a75
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4
|
2020-06-21T17:36:46.000Z
|
2020-08-07T07:16:01.000Z
|
src/mlpack/methods/ann/activation_functions/tanh_exponential_function.hpp
|
laszlzso/mlpack
|
52e123e56792638c957d0229b001ae14a9e94a75
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
/**
* @file methods/ann/activation_functions/tanh_exponential_function.hpp
* @author Mayank Raj
*
* Definition and implementation of the Tanh exponential function.
*
* For more information see the following paper
*
* @code
* @misc{The Institution of Engineering and Technology 2015 ,
* title = {TanhExp: A Smooth Activation Function with High Convergence Speed for Lightweight Neural Networks},
* author = {Xinyu Liu and Xiaoguang Di},
* year = {2020},
* url = {https://arxiv.org/pdf/2003.09855v2.pdf},
* eprint = {2003.09855v2},
* archivePrefix = {arXiv},
* primaryClass = {cs.LG} }
* @endcode
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_TANH_EXPONENTIAL_FUNCTION_HPP
#define MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_TANH_EXPONENTIAL_FUNCTION_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* The TanhExp function, defined by
*
* @f{eqnarray*}{
* f(x) = x * tanh(e^x)\\
* f'(x) = tanh(e^x) - x*e^x*(tanh(e^x)^2 - 1)\\
* @f}
*/
class TanhExpFunction
{
public:
/**
* Computes the TanhExp function.
*
* @param x Input data.
* @return f(x).
*/
static double Fn(const double x)
{
return x * std::tanh(std::exp(x));
}
/**
* Computes the TanhExp function.
*
* @param x Input data.
* @param y The resulting output activation.
*/
template<typename InputVecType, typename OutputVecType>
static void Fn(const InputVecType& x, OutputVecType& y)
{
y = x % arma::tanh(arma::exp(x));
}
/**
* Computes the first derivative of the TanhExp function.
*
* @param y Input activation.
* @return f'(x)
*/
static double Deriv(const double y)
{
return std::tanh(std::exp(y)) - y * std::exp(y) *
(std::pow(std::tanh(std::exp(y)), 2) - 1);
}
/**
* Computes the first derivatives of the tanh function.
*
* @param y Input activations.
* @param x The resulting derivatives.
*/
template<typename InputVecType, typename OutputVecType>
static void Deriv(const InputVecType& y, OutputVecType& x)
{
x = arma::tanh(arma::exp(y)) - y % arma::exp(y) %
(arma::pow(arma::tanh(arma::exp(y)), 2) - 1);
}
}; // class TanhExpFunction
} // namespace ann
} // namespace mlpack
#endif
| 26.57732
| 114
| 0.658262
|
laszlzso
|
cabfa7f78fc24b397244116e491be2fb8227f008
| 5,127
|
cc
|
C++
|
design_patterns/algorithms/algorithm.cc
|
fetaxyu/design-patterns
|
4e1a4d07ab928ca72ec370608cadf0824c41915e
|
[
"Apache-2.0"
] | null | null | null |
design_patterns/algorithms/algorithm.cc
|
fetaxyu/design-patterns
|
4e1a4d07ab928ca72ec370608cadf0824c41915e
|
[
"Apache-2.0"
] | null | null | null |
design_patterns/algorithms/algorithm.cc
|
fetaxyu/design-patterns
|
4e1a4d07ab928ca72ec370608cadf0824c41915e
|
[
"Apache-2.0"
] | null | null | null |
/* Copyleft 2018 The design-patterns Authors. Some Rights Reserved.
@Author: fetaxyu
@Date: 2018-11-14
Email: fetaxyu@gmail.com
===============================================================*/
#include <iostream>
#include "design_patterns/algorithms/algorithm.h"
namespace solution {
bool Find(int target, std::vector<std::vector<int>> array) {
bool found = false;
int rows = array.size();
int columns = array.at(0).size();
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
if (array[row][column] == target) {
found = true;
break;
}
if (array[row][column] > target) {
--column;
}
else {
++row;
}
}
return found;
}
void ReplaceSpace(char * str, int length) {
if (!str) {
return;
}
int spaceCount = 0;
for (int i = 0; i < length - 1; ++i) {
if (str[i] == ' ') {
++spaceCount;
}
}
if (spaceCount > 0) {
int newLength = length + spaceCount * 2;
int newIndex = newLength;
int oldIndex = length;
while (oldIndex >= 0 && newIndex > oldIndex && spaceCount > 0) {
if (str[oldIndex] == ' ') {
str[newIndex--] = '0';
str[newIndex--] = '2';
str[newIndex--] = '%';
--spaceCount;
} else {
str[newIndex--] = str[oldIndex];
}
--oldIndex;
}
}
std::cout << str << std::endl;
}
std::vector<int> PrintListFromTailToHead(ListNode * head) {
std::vector<int> rs;
if (head) {
while (head->next) {
rs.push_back(head->val);
head = head->next;
}
rs.push_back(head->val);
}
std::reverse(rs.begin(), rs.end());
return rs;
}
TreeNode* ReConstructBinaryTree(std::vector<int> pre, std::vector<int> vin) {
if (pre.empty() || vin.empty()) { return NULL; }
int rootValue = pre.at(0);
int index = 0;
for (int e : vin) {
if (e == rootValue) {
break;
}
++index;
}
std::vector<int> leftPre, leftVin, rightPre, rightVin;
for (int i = 0; i < index; ++i) {
leftPre.push_back(pre[i + 1]);
leftVin.push_back(vin[i]);
}
for (int i = index + 1; i < vin.size(); ++i) {
rightPre.push_back(pre[i]);
rightVin.push_back(vin[i]);
}
TreeNode* node = new TreeNode(rootValue);
node->left = ReConstructBinaryTree(leftPre, leftVin);
node->right = ReConstructBinaryTree(rightPre, rightVin);
return node;
}
void CQueue::push(int node) {
stack1.push(node);
}
int CQueue::pop() {
if (stack2.empty()) {
while (stack1.size() > 0) {
int n = stack1.top();
stack1.pop();
stack2.push(n);
}
}
if (stack2.empty()) {
throw new std::runtime_error("Queue is empty!");
}
int n = stack2.top();
stack2.pop();
return n;
}
void CStack::push(int node) {
if (!queue1.empty()) {
queue1.push(node);
} else {
queue2.push(node);
}
}
int CStack::swap(std::queue<int>& q1, std::queue<int>& q2) {
while (q1.size() > 1) {
int n = q1.front();
q1.pop();
q2.push(n);
}
int n = q1.front();
q1.pop();
return n;
}
int CStack::pop() {
if (!queue1.empty()) {
return swap(queue1, queue2);
}
if (!queue2.empty()) {
return swap(queue2, queue1);
}
throw new std::runtime_error("Stack is empty!");
}
int MinNumberInRotateArray(std::vector<int> arr) {
if (arr.empty()) {
return 0;
}
int index1 = 0;
int index2 = arr.size() - 1;
int indexMid = index1;
while (arr[index1] >= arr[index2]) {
if (index2 - index1 == 1) {
indexMid = index2;
break;
}
indexMid = (index1 + index2) / 2;
if (arr[indexMid] >= arr[index1]) {
index1 = indexMid;
} else if (arr[indexMid] <= arr[index2]) {
index2 = indexMid;
}
}
return arr[indexMid];
}
int Fibonacci(int n) {
if (n > 39) {
throw new std::runtime_error("n <= 39!");
}
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
int i = 2;
int n1 = 0, n2 = 1;
while (i <= n) {
int n3 = n1 + n2;
n1 = n2;
n2 = n3;
++i;
}
return n2;
}
int JumpFloor(int n) {
if (n < 0) {
throw new std::runtime_error("n >= 0!");
}
if (n == 0) return 0;
int arr[2] = { 1, 2 };
if (n < 2) {
return arr[n-1];
}
int i = 2;
while (i < n) {
int count = arr[1] + arr[0];
arr[0] = arr[1];
arr[1] = count;
++i;
}
return arr[1];
}
int JumpFloorII(int n) {
if (n <= 0) {
throw new std::runtime_error("n > 0!");
}
return n == 1 ? 1 : 2 * JumpFloorII(n - 1);
}
int NumberOf1(int n) {
int count = 0;
while (n) {
++count;
n = (n - 1) & n;
}
return count;
}
double Power(double base, int exponent) {
if (exponent == 0) {
return 1;
}
if (exponent == 1) {
return base;
}
if (exponent == -1) {
return 1 / base;
}
double rs = base;
int n = exponent > 0 ? exponent : -exponent;
while (n > 1) {
rs *= rs;
if (n & 0x01 == 1) {
rs *= base;
}
n = n >> 1;
}
return exponent > 0 ? rs : 1 / rs;
}
int RectCover(int number) {
return JumpFloor(number);
}
void ReOrderArray(std::vector<int>& array) {
int index = -1, count = 0, i = 0;
while (i < array.size()) {
if (array[i] & 0x1) {
if (index > 0) {
for (int j = 1; j <= count; ++j) {
int temp = array[i];
array[i] = array[i - 1];
array[i - 1] = temp;
i = i - 1;
}
count = 0;
index = -1;
} else {
++i;
}
} else {
index = index > 0 ? index : i;
++count;
++i;
}
}
}
}
| 17.989474
| 77
| 0.55237
|
fetaxyu
|
cac1147091236a13651345a043bd327a58d9b656
| 488
|
cpp
|
C++
|
problems/codeforces/1260/c-infinite-fence/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | 7
|
2020-10-15T22:37:10.000Z
|
2022-02-26T17:23:49.000Z
|
problems/codeforces/1260/c-infinite-fence/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | null | null | null |
problems/codeforces/1260/c-infinite-fence/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define long int64_t
// *****
auto solve() {
long r, b, k;
cin >> r >> b >> k;
long g = gcd(r, b);
if (r > (k - 1) * b + g || b > (k - 1) * r + g) {
return false;
} else {
return true;
}
}
// *****
int main() {
ios::sync_with_stdio(false);
unsigned T;
cin >> T >> ws;
for (unsigned t = 1; t <= T; ++t) {
cout << (solve() ? "OBEY" : "REBEL") << endl;
}
return 0;
}
| 15.741935
| 53
| 0.428279
|
brunodccarvalho
|
cac29ccbd066c0503ed280bd4b47577e260c6605
| 6,422
|
cpp
|
C++
|
src/TextField.cpp
|
moebiussurfing/ofxSimpleFloatingGui
|
67777c46c9aea920a81bc7510be69b1865adb390
|
[
"MIT"
] | 4
|
2019-08-21T05:01:51.000Z
|
2020-05-10T21:50:32.000Z
|
src/TextField.cpp
|
moebiussurfing/ofxSimpleFloatingGui
|
67777c46c9aea920a81bc7510be69b1865adb390
|
[
"MIT"
] | null | null | null |
src/TextField.cpp
|
moebiussurfing/ofxSimpleFloatingGui
|
67777c46c9aea920a81bc7510be69b1865adb390
|
[
"MIT"
] | 1
|
2020-05-08T19:49:45.000Z
|
2020-05-08T19:49:45.000Z
|
#include "TextField.h"
TextField::TextField()
{
}
/// setup methods
void TextField::setup(ofTrueTypeFont _stringFont){
setup(10, _stringFont);
}
void TextField::setup(int _maxChar, ofTrueTypeFont _stringFont){
setup(" ", _maxChar, _stringFont);
}
void TextField::setup(string _displayedString, int _maxChar, ofTrueTypeFont _stringFont)
{
setup(_displayedString, _maxChar, _stringFont, ofColor::black, ofColor(230));
}
void TextField::setup(string _displayedString, int _maxChar, ofTrueTypeFont _stringFont, ofColor _stringColor, ofColor _backgroundColor)
{
ofAddListener(ofEvents().keyPressed, this, &TextField::keyPressed);
displayedString = _displayedString.substr(0, _maxChar);
stringFont = _stringFont;
stringColor = _stringColor;
backgroundColor = _backgroundColor;
maxChar = _maxChar;
// set up background rectangle size
padX = ofMap(_stringFont.getSize(), 5, 11, 5, 15);
padY = 15;
lineHeight = stringFont.stringHeight(displayedString);
float rectW = stringFont.stringWidth(displayedString) + 2 * padX;
float rectH = lineHeight + 2 * padY;
// init other variables
maxSize = getMaxSize(_stringFont, _maxChar) + 2 * padX;
backgroundRect = ofRectangle(0, 0, rectW, rectH);
animTime = (int) (ofGetFrameRate() * 0.2);
deltaT = 1 / (float) animTime;
nChar = displayedString.size();
blinkThresh = (int) (ofGetFrameRate() * 0.6); // we want the blink to be 0.6 seconds long
}
string TextField::draw(float posX, float posY, ofMatrix4x4 transMatrix){
// get absolute position of hover rectangle
ofPoint backgroundRectPosAbs = ofPoint(posX, posY) * transMatrix;
// check if string is hovered
hovered = (ofGetMouseX() < backgroundRectPosAbs.x + backgroundRect.width) &&
(ofGetMouseX() > backgroundRectPosAbs.x) &&
(ofGetMouseY() < backgroundRectPosAbs.y + backgroundRect.height) &&
(ofGetMouseY() > backgroundRectPosAbs.y);
// if we click while hovered we enter edit mode
if(ofGetMousePressed() && !mousePressedPrev)
{
editMode = hovered;
}
// if we just entered edit mode
if(editMode && !editModePrev)
{
// we update editString with displayedString
editString = displayedString;
// backgroundRect.width is gonna be animated to its maxSize
targetWidth = maxSize;
deltaWidth = (targetWidth - backgroundRect.getWidth()) / animTime;
animCounter = 0;
// init blinking of cursor
blinkTime = 0;
blink = true;
}
// if we just quit edit mode
if(!editMode && editModePrev)
{
// we save change into displayedString
displayedString = editString;
// backgroundRect.width is gonna be animated to the width of current string
targetWidth = cursorX + 2 * padX;
deltaWidth = (targetWidth - backgroundRect.getWidth()) / animTime;
animCounter = 0;
}
// if we are currently in edit mode
if(editMode)
{
// get string rect
cursorX = stringFont.stringWidth(editString);
// handle blinking
blinkTime++;
if(blinkTime >= blinkThresh) {
blink = !blink;
blinkTime = 0;
}
}
// update animation counter and bool
animCounter += deltaT;
animRunning = (animCounter <= 1);
// animate backgroundRect.width when animation is running
if(animRunning) {
backgroundRect.setWidth(backgroundRect.getWidth()+ deltaWidth) ;
}
ofPushStyle();
ofSetLineWidth(1);
ofPushMatrix();
ofTranslate(posX, posY);
// debug
//ofDrawCircle(0, 0, 2);
// draw background rectangle
ofFill();
ofSetColor(backgroundColor);
ofDrawRectRounded(backgroundRect, backgroundRect.height / 2);
// display a boundary rectangle when text field is hovered, being edited or animation is running
if(hovered || editMode || animRunning) {
ofNoFill();
ofSetColor(ofColor::gray);
ofDrawRectRounded(backgroundRect, backgroundRect.height / 2);
}
// draw string
ofSetColor(stringColor);
stringFont.drawString(editMode ? editString : displayedString, padX, padY + lineHeight);
// draw line
if(editMode && blink){
ofSetLineWidth(2);
ofSetColor(ofColor::black);
ofDrawLine(cursorX + padX + 3, 0, cursorX + padX + 3, backgroundRect.height);
}
/*
// debug stuff
ofNoFill();
ofSetLineWidth(1);
ofSetColor(ofColor::black);
ofDrawRectangle(padX, padY, stringFont.stringWidth(editMode ? editString : displayedString), stringFont.getLineHeight());
ofSetColor(ofColor::black);
ofDrawLine(0, rectH / 2, rectW, rectH / 2);
ofDrawLine(rectW / 2, 0, rectW / 2, rectH);
*/
ofPopMatrix();
ofPopStyle();
// update states
mousePressedPrev = ofGetMousePressed();
editModePrev = editMode;
// we return displayedString, this means that this value changed when we leave edit mode
return displayedString;
}
// getter
string TextField::getValue(){
return displayedString;
}
float TextField::getMaxSize(ofTrueTypeFont _font, int _sz) {
std::stringstream ss;
for(int i = 0; i < _sz; i++) {
ss << 'w';
}
return _font.stringWidth(ss.str());
}
void TextField::keyPressed(ofKeyEventArgs& eventArgs) {
// debug
//ofLog() << eventArgs.key;
if(editMode) {
// delete if backspace
if(eventArgs.key == 8) {
// remove last char
if(editString.size() > 0) {
editString = editString.substr(0, editString.size()-1);
nChar -= 1;
}
}
// only consider a-z or 0-9 or spacebar
if((nChar < maxChar) && ((eventArgs.key >= 97 && eventArgs.key <= 122) || (eventArgs.key >= 48 && eventArgs.key <= 57) || eventArgs.key == 32)) {
editString += ofToString((char) eventArgs.key);
nChar += 1;
}
// if enter, exit edit mode
if(eventArgs.key == 13){
editMode = !editMode;
}
}
}
| 30.436019
| 153
| 0.605263
|
moebiussurfing
|
cac3badb523262663820b93e2527588f49be4923
| 5,311
|
cc
|
C++
|
mace/ops/arm/fp32/activation.cc
|
WeipengChan/mace
|
a610d506592892007be538e71ca1daef07c7857b
|
[
"Apache-2.0"
] | 1
|
2018-12-19T02:48:20.000Z
|
2018-12-19T02:48:20.000Z
|
mace/ops/arm/fp32/activation.cc
|
WeipengChan/mace
|
a610d506592892007be538e71ca1daef07c7857b
|
[
"Apache-2.0"
] | null | null | null |
mace/ops/arm/fp32/activation.cc
|
WeipengChan/mace
|
a610d506592892007be538e71ca1daef07c7857b
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2019 The MACE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mace/ops/arm/fp32/activation.h"
#include <arm_neon.h>
#include <algorithm>
namespace mace {
namespace ops {
namespace arm {
namespace fp32 {
Activation::Activation(ActivationType type,
const float limit,
const float leakyrelu_coefficient)
: type_(type),
limit_(limit),
leakyrelu_coefficient_(leakyrelu_coefficient) {}
MaceStatus Activation::Compute(const OpContext *context,
const Tensor *input,
Tensor *output) {
Tensor::MappingGuard input_guard(input);
if (input != output) {
MACE_RETURN_IF_ERROR(output->ResizeLike(input));
Tensor::MappingGuard output_guard(output);
DoActivation(context, input, output);
} else {
DoActivation(context, input, output);
}
return MaceStatus::MACE_SUCCESS;
}
void Activation::DoActivation(const OpContext *context,
const Tensor *input,
Tensor *output) {
auto input_data = input->data<float>();
auto output_data = output->mutable_data<float>();
const index_t size = input->size();
utils::ThreadPool &thread_pool =
context->device()->cpu_runtime()->thread_pool();
switch (type_) {
case RELU: {
const float32x4_t vzero = vdupq_n_f32(0.f);
const index_t block_count = size / 4;
thread_pool.Compute1D(
[=](index_t start, index_t end, index_t step) {
auto input_ptr = input_data + start * 4;
auto output_ptr = output_data + start * 4;
for (index_t i = start; i < end; i += step) {
float32x4_t v = vld1q_f32(input_ptr);
v = vmaxq_f32(v, vzero);
vst1q_f32(output_ptr, v);
input_ptr += 4;
output_ptr += 4;
}
},
0, block_count, 1);
// remain
for (index_t i = block_count * 4; i < size; ++i) {
output_data[i] = std::max(0.f, input_data[i]);
}
break;
}
case RELUX: {
const float32x4_t vzero = vdupq_n_f32(0.f);
const float32x4_t vlimit = vdupq_n_f32(limit_);
const index_t block_count = size / 4;
thread_pool.Compute1D(
[=](index_t start, index_t end, index_t step) {
auto input_ptr = input_data + start * 4;
auto output_ptr = output_data + start * 4;
for (index_t i = start; i < end; i += step) {
float32x4_t v = vld1q_f32(input_ptr);
v = vmaxq_f32(v, vzero);
v = vminq_f32(v, vlimit);
vst1q_f32(output_ptr, v);
input_ptr += 4;
output_ptr += 4;
}
},
0, block_count, 1);
// remain
for (index_t i = block_count * 4; i < size; ++i) {
output_data[i] = std::max(0.f, std::min(limit_, input_data[i]));
}
break;
}
case LEAKYRELU: {
const float32x4_t vzero = vdupq_n_f32(0.f);
const float32x4_t valpha = vdupq_n_f32(leakyrelu_coefficient_);
const index_t block_count = size / 4;
thread_pool.Compute1D(
[=](index_t start, index_t end, index_t step) {
auto input_ptr = input_data + start * 4;
auto output_ptr = output_data + start * 4;
for (index_t i = start; i < end; i += step) {
float32x4_t v = vld1q_f32(input_ptr);
float32x4_t u = vminq_f32(v, vzero);
v = vmaxq_f32(v, vzero);
v = vmlaq_f32(v, valpha, u);
vst1q_f32(output_ptr, v);
input_ptr += 4;
output_ptr += 4;
}
},
0, block_count, 1);
// remain
for (index_t i = block_count * 4; i < size; ++i) {
output_data[i] = std::max(input_data[i], 0.f) +
std::min(input_data[i], 0.f) * leakyrelu_coefficient_;
}
break;
}
case TANH: {
thread_pool.Compute1D(
[=](index_t start, index_t end, index_t step) {
for (index_t i = start; i < end; i += step) {
output_data[i] = std::tanh(input_data[i]);
}
},
0, size, 1);
break;
}
case SIGMOID: {
thread_pool.Compute1D(
[=](index_t start, index_t end, index_t step) {
for (index_t i = start; i < end; i += step) {
output_data[i] = 1 / (1 + std::exp(-(input_data[i])));
}
},
0, size, 1);
break;
}
case NOOP:
break;
default:
MACE_NOT_IMPLEMENTED;
}
}
} // namespace fp32
} // namespace arm
} // namespace ops
} // namespace mace
| 28.86413
| 79
| 0.555639
|
WeipengChan
|
cac3c63af218479a2bac860d436966698c990997
| 5,114
|
cpp
|
C++
|
EOSAI/EOSAIDesire2.cpp
|
BritClousing/EOSAI
|
c147500d223c361dce2e32d6547aaa234c07d472
|
[
"MIT"
] | 1
|
2019-05-22T12:41:38.000Z
|
2019-05-22T12:41:38.000Z
|
EOSAI/EOSAIDesire2.cpp
|
BritClousing/EOSAI
|
c147500d223c361dce2e32d6547aaa234c07d472
|
[
"MIT"
] | null | null | null |
EOSAI/EOSAIDesire2.cpp
|
BritClousing/EOSAI
|
c147500d223c361dce2e32d6547aaa234c07d472
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "EOSAIDesire2.h"
#include "EOSAIUnitTemplate.h"
//#include "WorldDescPlayer.h"
//#include "WorldDescServer.h"
//#include "WorldDescPlayerProxy.h"
#include "EOSAIBrain.h"
#include "EOSAICommonData.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
CEOSAIDesire2::CEOSAIDesire2()
{
m_pAIBrain = NULL;
//m_pTacticalProject = NULL;
SetTimeValueFunction_PlanLongterm();
m_iAggressiveTowardsPlayer = 0;
// Scoring
m_eScoringLevel = EnumUndefined;
m_fScore = 0.0f;
}
CEOSAIThoughtDatabase* CEOSAIDesire2::GetAIThoughtDatabase()
{
return m_pAIBrain->GetAIThoughtDatabase();
}
bool CEOSAIDesire2::IsAPrimaryGoalOfTacticalProject( CAITacticalProject* p )
{
POSITION pos = m_TacticalProjectsIAmAPrimaryMemberOf.GetHeadPosition();
while( pos )
{
CAITacticalProject* pTacProject = m_TacticalProjectsIAmAPrimaryMemberOf.GetNext( pos );
if( pTacProject == p ) return true;
}
return false;
}
bool CEOSAIDesire2::IsAPrimaryGoalOfOneOrMoreTacticalProjects()
{
return ( m_TacticalProjectsIAmAPrimaryMemberOf.IsEmpty() == FALSE );
}
void CEOSAIDesire2::AddAsPrimaryGoalOfTacticalProject( CAITacticalProject* p )
{
ASSERT( IsAPrimaryGoalOfTacticalProject( p ) == false );
m_TacticalProjectsIAmAPrimaryMemberOf.AddTail( p );
}
/*
void CEOSAIDesire2::RemoveAsPrimaryGoalOfTacticalProject( CAITacticalProject* p )
{
ASSERT( IsAPrimaryGoalOfTacticalProject( p ) );
//
POSITION pos = m_TacticalProjectsIAmAPrimaryMemberOf.GetHeadPosition();
while( pos )
{
POSITION PrevPos = pos;
CAITacticalProject* pTacProjectInList = m_TacticalProjectsIAmAPrimaryMemberOf.GetNext( PrevPos );
if( pTacProjectInList == p )
{
m_TacticalProjectsIAmAPrimaryMemberOf.RemoveAt( PrevPos );
break;
}
}
}
*/
bool CEOSAIDesire2::IsAPrimaryGoalOfTacticalProject2( CEOSAITacticalProject2* p )
{
POSITION pos = m_TacticalProjectsIAmAPrimaryMemberOf.GetHeadPosition();
while( pos )
{
CEOSAITacticalProject2* pTacProject = m_TacticalProjects2IAmAPrimaryMemberOf.GetNext( pos );
if( pTacProject == p ) return true;
}
return false;
}
bool CEOSAIDesire2::IsAPrimaryGoalOfOneOrMoreTacticalProjects2()
{
return ( m_TacticalProjects2IAmAPrimaryMemberOf.IsEmpty() == FALSE );
}
void CEOSAIDesire2::AddAsPrimaryGoalOfTacticalProject2( CEOSAITacticalProject2* p )
{
ASSERT( IsAPrimaryGoalOfTacticalProject2( p ) == false );
m_TacticalProjects2IAmAPrimaryMemberOf.AddTail( p );
}
//
// Time-Value functions
//
bool CEOSAIDesire2::CurrentForeignRelationsPreventsPersuingThisDesire()
{
if( m_iAggressiveTowardsPlayer == 0 ) return false;
//EOSAIEnumForeignRelations eRel = m_pAIBrain->GetWorldDescPlayer()->GetForeignRelations( m_iAggressiveTowardsPlayer );
//if( eRel.IsEnemy() ) return false;
//CWorldDescServer* pWorldDescServer = GetAIBrain()->GetWorldDescServer();
//CWorldDescPlayerProxy* pWorldDescPlayerProxy = GetAIBrain()->GetWorldDescPlayerProxy();
if( g_pEOSAICommonData->GetForeignRelations( m_pAIBrain->GetAIPlayerNumber(), m_iAggressiveTowardsPlayer ).IsEnemy() ) return false;
//if( pWorldDescPlayerProxy->GetSneakAttack( m_iAggressiveTowardsPlayer ) ) return false;
if( g_pEOSAICommonData->HasSetSneakAttack( m_pAIBrain->GetAIPlayerNumber(), m_iAggressiveTowardsPlayer ) ) return false;
return true;
}
//
// Time-Value functions
//
void CEOSAIDesire2::SetTimeValueFunction_OnlyAvailableNow()
{
m_TimeValueFunction.Clear();
m_TimeValueFunction.SetInputOutput( 0.0f, 1.0f );
m_TimeValueFunction.SetInputOutput( 1.0f, 0.9f );
m_TimeValueFunction.SetInputOutput( 2.0f, 0.5f );
m_TimeValueFunction.SetInputOutput( 3.0f, 0.2f );
m_TimeValueFunction.SetInputOutput( 4.0f, 0.0f );
}
void CEOSAIDesire2::SetTimeValueFunction_PlanForNext10Turns()
{
m_TimeValueFunction.Clear();
m_TimeValueFunction.SetInputOutput( 0.0f, 1.0f );
m_TimeValueFunction.SetInputOutput( 4.0f, 0.9f );
m_TimeValueFunction.SetInputOutput( 6.0f, 0.8f );
m_TimeValueFunction.SetInputOutput( 8.0f, 0.5f );
m_TimeValueFunction.SetInputOutput(10.0f, 0.0f );
}
void CEOSAIDesire2::SetTimeValueFunction_PlanLongterm()
{
m_TimeValueFunction.Clear();
m_TimeValueFunction.SetInputOutput( 0.0f, 1.0f );
m_TimeValueFunction.SetInputOutput( 50.0f, 0.5f );
}
bool CEOSAIDesire2::ActionInvolvesCapturingAndOccupyingGroundTerritory()
{
return m_JobsToDo.m_fGroundCitResHunter > 0.0f;
}
// Score
void CEOSAIDesire2::CalculateScore( EnumScoringLevel eScoringLevel )
{
if( eScoringLevel == EnumInitialScoring )
{
m_eScoringLevel = eScoringLevel;
//m_fScore = GetAccessibility01() * GetAreaSimpleInterest();
m_fScore = GetAccessibility01() * (0.7f*GetSimpleInterest() + 0.3f*GetAreaSimpleInterest());
int g=0;
/*
if( fValue > fBestValue )
{
fBestValue = fValue;
pBestDesire = pDesire;
}
*/
}
else
{
ASSERT( false );
}
}
/*
//float CEOSAIDesire2::GetBestMovementRateSimpleTaskForce()
float CEOSAIDesire2::GetBestMovementRateForUnitsCompletingAllTheJobs()
{
return m_Jobs.GetBestMovementRateForUnitsCompletingAllTheJobs(
GetAIThoughtDatabase(), GetAIThoughtDatabase()->GetUnitsICanBuildOrHave() );
}
*/
| 27.945355
| 133
| 0.779625
|
BritClousing
|
cac62a1d81e44e4996699a7abf2c890e742df79b
| 6,100
|
cpp
|
C++
|
utilities/msmonitor/gui/QMSMFormMeasurementAbstract.cpp
|
akiml/ampehre
|
383a863442574ea2e6a6ac853a9b99e153daeccf
|
[
"BSD-2-Clause"
] | 3
|
2016-01-20T13:41:52.000Z
|
2018-04-10T17:50:49.000Z
|
utilities/msmonitor/gui/QMSMFormMeasurementAbstract.cpp
|
akiml/ampehre
|
383a863442574ea2e6a6ac853a9b99e153daeccf
|
[
"BSD-2-Clause"
] | null | null | null |
utilities/msmonitor/gui/QMSMFormMeasurementAbstract.cpp
|
akiml/ampehre
|
383a863442574ea2e6a6ac853a9b99e153daeccf
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* QMSMFormMeasurementAbstract.cpp
*
* Copyright (C) 2015, Achim Lösch <achim.loesch@upb.de>, Christoph Knorr <cknorr@mail.uni-paderborn.de>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*
* encoding: UTF-8
* tab size: 4
*
* author: Achim Lösch (achim.loesch@upb.de)
* created: 1/28/14
* version: 0.3.0 - extend libmeasure and add application for online monitoring
* 0.3.2 - add a networking component to show influence of a task to measurements in GUI
* 0.4.1 - add MIC support to msmonitor
* 0.5.11 - add option to control the output to csv file and new RingBuffer to store results to msmonitor
*/
#include "QMSMFormMeasurementAbstract.hpp"
#include "../data/CDataHandler.cpp"
#include <iostream>
namespace Ui {
uint32_t QMSMFormMeasurementAbstract::sNumberOfImages = 0;
QMSMFormMeasurementAbstract::QMSMFormMeasurementAbstract(QWidget *pParent, NData::CDataHandler* pDataHandler) :
QMdiSubWindow(pParent),
FormMeasurement(),
mpFormMeasurementAbstract(new QWidget(pParent)),
mpDataHandler(pDataHandler),
mTimer(mpDataHandler->getSettings().mGUIRefreshRate, this),
mColorCpu(0, 0, 255),
mColorCpuAlternative(0, 128, 255),
mColorGpu(255, 0, 0),
mColorGpuAlternative(153, 0, 0),
mColorFpga(0, 153, 0),
mColorFpgaAlternative(0, 255, 0),
mColorMic(153, 0, 255),
mColorMicAlternative(255, 0, 255),
mColorSystem(255, 128, 0),
mColorSystemAlternative(255, 255, 0),
mVerticalLine(QwtSymbol::VLine, QBrush(Qt::black), QPen(Qt::black), QSize(1, 300)),
mMarker(),
mMarkerLabel(""),
mMarkerTime(0),
mpLegend(new QwtLegend()),
mpPanner(0),
mpMagnifier(0),
mpGrid(new QwtPlotGrid())
{
//setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint);
setupUi(mpFormMeasurementAbstract);
setWidget(mpFormMeasurementAbstract);
qwtPlot->setAxisTitle(QwtPlot::xBottom, createTitle(QString::fromUtf8("Time [s]")));
mpLegend->setFrameStyle(QFrame::Box | QFrame::Sunken);
mpPanner = new QwtPlotPanner(qwtPlot->canvas());
mpMagnifier = new QwtPlotMagnifier(qwtPlot->canvas());
mpGrid->enableXMin(true);
mpGrid->enableYMin(true);
mpGrid->setMajorPen(QPen(Qt::black, 0, Qt::DotLine));
mpGrid->setMinorPen(QPen(Qt::gray, 0, Qt::DotLine));
mpGrid->attach(qwtPlot);
createActions();
}
QMSMFormMeasurementAbstract::~QMSMFormMeasurementAbstract(void) {
delete mpLegend;
delete mpPanner;
delete mpMagnifier;
delete mpGrid;
delete mpFormMeasurementAbstract;
}
void QMSMFormMeasurementAbstract::createActions(void) {
connect(pushButtonOK, SIGNAL(clicked(bool)), this, SLOT(close()));
connect(pushButtonSave, SIGNAL(clicked(bool)), this, SLOT(saveImage()));
connect(this, SIGNAL(signalRefreshGui(void)), this, SLOT(slotRefreshGui()));
connect(this, SIGNAL(signalAddMarker(void)), this, SLOT(addMarker()));
}
QwtText QMSMFormMeasurementAbstract::createTitle(QString title) {
QwtText qTitle(title);
qTitle.setFont(QFont("Helvetica", 12));
return qTitle;
}
void QMSMFormMeasurementAbstract::close(void) {
hide();
}
void QMSMFormMeasurementAbstract::closeEvent(QCloseEvent *pEvent) {
hide();
}
bool QMSMFormMeasurementAbstract::event(QEvent *pEvent) {
if (pEvent->type() == QEvent::ToolTip) {
return true;
}
return QMdiSubWindow::event(pEvent);
}
void QMSMFormMeasurementAbstract::refreshGui(void) {
emit signalRefreshGui();
}
void QMSMFormMeasurementAbstract::slotRefreshGui(void) {
setupCurves();
qwtPlot->replot();
}
void QMSMFormMeasurementAbstract::saveImage(void) {
const char *home_directory = getenv("HOME");
QString filename(home_directory);
filename += "/plot_";
filename += QString::number(sNumberOfImages++);
filename += ".png";
QPixmap pixmap(mpDataHandler->getSettings().mImageSizeX, mpDataHandler->getSettings().mImageSizeY);
/*
QwtPlotPrintFilter filter;
//filter.color(Qt::white, QwtPlotPrintFilter::CanvasBackground);
//filter.setOptions(QwtPlotPrintFilter::PrintBackground);
filter.setOptions(QwtPlotPrintFilter::PrintAll);
qwtPlot->print(pixmap, filter);
*/
if (pixmap.save(filename, "png")) {
std::cout << "INFO : Image stored as '" << qPrintable(filename) << "'." << std::endl;
} else {
std::cerr << "ERROR: Could not store '" << qPrintable(filename) << "'!" << std::endl;
}
}
void QMSMFormMeasurementAbstract::scaleAxis(double xValue, double yValueMin, double yValueMax) {
int32_t first_tick = 0;
int32_t second_tick = 0;
double time_show_data = 0.0;
time_show_data = mpDataHandler->getSettings().mTimeToShowData/1000.0;
first_tick = ((int)(xValue-time_show_data)/10)*10;
first_tick = (first_tick >= 0 && (xValue-time_show_data) > 0) ? first_tick+10 : first_tick;
second_tick = ((int)(xValue)/10)*10+10;
qwtPlot->setAxisScale(QwtPlot::xBottom, first_tick, second_tick);
qwtPlot->setAxisScale(QwtPlot::yLeft, yValueMin, yValueMax);
}
void QMSMFormMeasurementAbstract::startTimer(void) {
mTimer.startTimer();
}
void QMSMFormMeasurementAbstract::stopTimer(void) {
mTimer.stopTimer();
}
void QMSMFormMeasurementAbstract::joinTimer(void) {
mTimer.joinTimer();
}
void QMSMFormMeasurementAbstract::addMarker(void) {
QwtPlotMarker *marker = new QwtPlotMarker();
marker->setSymbol(&mVerticalLine);
marker->setLabel(QwtText(mMarkerLabel));
marker->setLabelAlignment(Qt::AlignTop);
marker->setValue(mMarkerTime, getMiddleOfYAxis());
marker->attach(qwtPlot);
mMarker.push_back(marker);
}
void QMSMFormMeasurementAbstract::triggerMarkerSignal(QString &rLabel) {
mMarkerTime = mpDataHandler->getMeasurement().getTime();
mMarkerLabel = rLabel;
emit signalAddMarker();
}
void QMSMFormMeasurementAbstract::resetMarker(void) {
for(std::vector<QwtPlotMarker *>::iterator it = mMarker.begin(); it != mMarker.end(); ++it) {
(*it)->setVisible(false);
}
}
}
| 29.61165
| 114
| 0.715902
|
akiml
|
cac72302c62640db650770ad51b5ea40af7e9a44
| 11,092
|
hpp
|
C++
|
agency/cuda/execution/detail/kernel/bulk_then_execute_kernel.hpp
|
ccecka/agency
|
729f5346e842c9cef3ad6f34d18d17a96a001a75
|
[
"BSD-3-Clause"
] | null | null | null |
agency/cuda/execution/detail/kernel/bulk_then_execute_kernel.hpp
|
ccecka/agency
|
729f5346e842c9cef3ad6f34d18d17a96a001a75
|
[
"BSD-3-Clause"
] | null | null | null |
agency/cuda/execution/detail/kernel/bulk_then_execute_kernel.hpp
|
ccecka/agency
|
729f5346e842c9cef3ad6f34d18d17a96a001a75
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <agency/detail/config.hpp>
#include <agency/cuda/execution/detail/kernel/launch_kernel.hpp>
#include <agency/cuda/execution/detail/kernel/on_chip_shared_parameter.hpp>
#include <agency/cuda/device.hpp>
#include <agency/cuda/detail/future/async_future.hpp>
#include <memory>
namespace agency
{
namespace cuda
{
namespace detail
{
// XXX consider moving the stuff related to bulk_then_execute_closure into its own header
// as bulk_then_execution_concurrent_grid.hpp also depends on it
template<size_t block_dimension, class Function, class PredecessorPointer, class ResultPointer, class OuterParameterPointer, class InnerFactory>
struct bulk_then_execute_closure
{
Function f_;
PredecessorPointer predecessor_ptr_;
ResultPointer result_ptr_;
OuterParameterPointer outer_parameter_ptr_;
InnerFactory inner_factory_;
// this is the implementation for non-void predecessor
template<class F, class T1, class T2, class T3, class T4>
__device__ static inline void impl(F f, T1& predecessor, T2& result, T3& outer_param, T4& inner_param)
{
f(predecessor, result, outer_param, inner_param);
}
// this is the implementation for void predecessor
template<class F, class T2, class T3, class T4>
__device__ static inline void impl(F f, agency::detail::unit, T2& result, T3& outer_param, T4& inner_param)
{
f(result, outer_param, inner_param);
}
template<size_t dimension = block_dimension, __AGENCY_REQUIRES(dimension == 1)>
__device__ static inline bool is_first_thread_of_block()
{
#ifdef __CUDA_ARCH__
return threadIdx.x == 0;
#else
return false;
#endif
}
template<size_t dimension = block_dimension, __AGENCY_REQUIRES(dimension > 1)>
__device__ static inline bool is_first_thread_of_block()
{
#ifdef __CUDA_ARCH__
agency::int3 idx{threadIdx.x, threadIdx.y, threadIdx.z};
#else
agency::int3 idx{};
#endif
// XXX this is actually the correct comparison
// but this comparison explodes the kernel resource requirements of programs like
// testing/unorganized/transpose which launch multidimensional thread blocks.
// Those large resource requirements lead to significantly degraded performance.
// We should investigate ways to mitigate those requirements and use the correct
// comparison. One idea is to teach on_chip_shared_parameter to avoid calling
// trivial constructors and destructors.
//return idx == agency::int3{0,0,0};
// XXX note that this comparison always fails -- it is incorrect
return false;
}
__device__ inline void operator()()
{
// we need to cast each dereference below to convert proxy references to ensure that f() only sees raw references
// XXX isn't there a more elegant way to deal with this?
using predecessor_reference = typename std::pointer_traits<PredecessorPointer>::element_type &;
using result_reference = typename std::pointer_traits<ResultPointer>::element_type &;
using outer_param_reference = typename std::pointer_traits<OuterParameterPointer>::element_type &;
on_chip_shared_parameter<InnerFactory> inner_parameter(is_first_thread_of_block(), inner_factory_);
impl(
f_,
static_cast<predecessor_reference>(*predecessor_ptr_),
static_cast<result_reference>(*result_ptr_),
static_cast<outer_param_reference>(*outer_parameter_ptr_),
inner_parameter.get()
);
}
};
template<size_t block_dimension, class Function, class PredecessorPointer, class ResultPointer, class OuterParameterPointer, class InnerFactory>
__host__ __device__
bulk_then_execute_closure<block_dimension,Function,PredecessorPointer,ResultPointer,OuterParameterPointer,InnerFactory>
make_bulk_then_execute_closure(Function f, PredecessorPointer predecessor_ptr, ResultPointer result_ptr, OuterParameterPointer outer_parameter_ptr, InnerFactory inner_factory)
{
return bulk_then_execute_closure<block_dimension,Function,PredecessorPointer,ResultPointer,OuterParameterPointer,InnerFactory>{f, predecessor_ptr, result_ptr, outer_parameter_ptr, inner_factory};
}
template<size_t block_dimension, class Function, class T, class ResultFactory, class OuterFactory, class InnerFactory>
struct bulk_then_execute_kernel
{
using result_type = agency::detail::result_of_t<ResultFactory()>;
using outer_arg_type = agency::detail::result_of_t<OuterFactory()>;
using predecessor_pointer_type = decltype(std::declval<agency::detail::asynchronous_state<T>&>().data());
using result_pointer_type = decltype(std::declval<agency::detail::asynchronous_state<result_type>&>().data());
using outer_parameter_pointer_type = decltype(std::declval<agency::detail::asynchronous_state<outer_arg_type>&>().data());
using closure_type = bulk_then_execute_closure<block_dimension, Function, predecessor_pointer_type, result_pointer_type, outer_parameter_pointer_type, InnerFactory>;
using type = decltype(&cuda_kernel<closure_type>);
constexpr static const type value = &cuda_kernel<closure_type>;
};
template<size_t block_dimension, class Function, class T, class ResultFactory, class OuterFactory, class InnerFactory>
using bulk_then_execute_kernel_t = typename bulk_then_execute_kernel<block_dimension,Function,T,ResultFactory,OuterFactory,InnerFactory>::type;
// this helper function returns a pointer to the kernel launched within launch_bulk_then_execute_kernel_impl()
template<size_t block_dimension, class Function, class T, class ResultFactory, class OuterFactory, class InnerFactory>
__host__ __device__
bulk_then_execute_kernel_t<block_dimension,Function,T,ResultFactory,OuterFactory,InnerFactory> make_bulk_then_execute_kernel(const Function& f, const asynchronous_state<T>&, const ResultFactory&, const OuterFactory&, const InnerFactory&)
{
return bulk_then_execute_kernel<block_dimension,Function,T,ResultFactory,OuterFactory,InnerFactory>::value;
}
template<class Shape>
__host__ __device__
::dim3 make_dim3(const Shape& shape)
{
agency::uint3 temp = agency::detail::shape_cast<uint3>(shape);
return ::dim3(temp.x, temp.y, temp.z);
}
// this is the main implementation of the other two launch_bulk_then_execute_kernel() functions
template<class Function, class Shape, class T, class ResultFactory, class OuterFactory, class InnerFactory>
__host__ __device__
async_future<agency::detail::result_of_t<ResultFactory()>>
launch_bulk_then_execute_kernel_impl(device_id device, detail::stream&& stream, Function f, ::dim3 grid_dim, Shape block_dim, const asynchronous_state<T>& predecessor_state, ResultFactory result_factory, OuterFactory outer_factory, InnerFactory inner_factory)
{
// create the asynchronous state to store the result
using result_type = agency::detail::result_of_t<ResultFactory()>;
detail::asynchronous_state<result_type> result_state = detail::make_asynchronous_state(result_factory);
// create the asynchronous state to store the outer shared argument
using outer_arg_type = agency::detail::result_of_t<OuterFactory()>;
detail::asynchronous_state<outer_arg_type> outer_arg_state = detail::make_asynchronous_state(outer_factory);
// wrap up f and its arguments into a closure to execute in a kernel
const size_t block_dimension = agency::detail::shape_size<Shape>::value;
auto closure = make_bulk_then_execute_closure<block_dimension>(f, predecessor_state.data(), result_state.data(), outer_arg_state.data(), inner_factory);
// make the kernel to launch
auto kernel = make_cuda_kernel(closure);
// launch the kernel
detail::try_launch_kernel_on_device(kernel, grid_dim, detail::make_dim3(block_dim), 0, stream.native_handle(), device.native_handle(), closure);
// create the next event
detail::event next_event(std::move(stream));
// schedule the outer arg's state for destruction when the next event is complete
detail::invalidate_and_destroy_when(outer_arg_state, next_event);
// return a new async_future corresponding to the next event & result state
return make_async_future(std::move(next_event), std::move(result_state));
}
template<class Function, class Shape, class T, class ResultFactory, class OuterFactory, class InnerFactory>
__host__ __device__
async_future<agency::detail::result_of_t<ResultFactory()>>
launch_bulk_then_execute_kernel(device_id device, Function f, ::dim3 grid_dim, Shape block_dim, async_future<T>& predecessor, ResultFactory result_factory, OuterFactory outer_factory, InnerFactory inner_factory)
{
// since we're going to leave the predecessor future valid, we make a new dependent stream before calling launch_bulk_then_execute_kernel_impl()
return detail::launch_bulk_then_execute_kernel_impl(device, detail::async_future_event(predecessor).make_dependent_stream(device), f, grid_dim, block_dim, detail::async_future_state(predecessor), result_factory, outer_factory, inner_factory);
}
template<class Function, class Shape, class T, class ResultFactory, class OuterFactory, class InnerFactory>
__host__ __device__
async_future<agency::detail::result_of_t<ResultFactory()>>
launch_bulk_then_execute_kernel_and_invalidate_predecessor(device_id device, Function f, ::dim3 grid_dim, Shape block_dim, async_future<T>& predecessor, ResultFactory result_factory, OuterFactory outer_factory, InnerFactory inner_factory)
{
// invalidate the future by splitting it into its event and state
detail::event predecessor_event;
detail::asynchronous_state<T> predecessor_state;
agency::tie(predecessor_event, predecessor_state) = detail::invalidate_async_future(predecessor);
// launch the kernel
auto result = detail::launch_bulk_then_execute_kernel_impl(device, predecessor_event.make_dependent_stream_and_invalidate(device), f, grid_dim, block_dim, predecessor_state, result_factory, outer_factory, inner_factory);
// schedule the predecessor's state for destruction when the result future's event is complete
detail::invalidate_and_destroy_when(predecessor_state, detail::async_future_event(result));
return result;
}
template<size_t block_dimension, class Function, class T, class ResultFactory, class OuterFactory, class InnerFactory>
__host__ __device__
int max_block_size_of_bulk_then_execute_kernel(const device_id& device, const Function& f, const async_future<T>& predecessor, const ResultFactory& result_factory, const OuterFactory& outer_factory, const InnerFactory& inner_factory)
{
// temporarily switch the CUDA runtime's current device to the given device
detail::scoped_current_device scope(device);
// get a pointer to the kernel launched by launch_bulk_then_execute_kernel()
constexpr auto kernel = bulk_then_execute_kernel<block_dimension,Function,T,ResultFactory,OuterFactory,InnerFactory>::value;
// get the kernel's attributes
cudaFuncAttributes attr;
detail::throw_on_error(cudaFuncGetAttributes(&attr, kernel), "cuda::detail::max_block_size_of_bulk_then_execute_grid(): CUDA error after cudaFuncGetAttributes()");
// return the attribute of interest
return attr.maxThreadsPerBlock;
}
} // end detail
} // end cuda
} // end agency
| 48.017316
| 261
| 0.79625
|
ccecka
|
cac731ec9bad23c1f9d2a6d5ce9afce112c96f03
| 1,602
|
cpp
|
C++
|
src/blocks/shovel.cpp
|
ondralukes/OpenGLCraft
|
8384fc70c02dddcf593a2e6aab6c1cd7d0ba38a3
|
[
"MIT"
] | 1
|
2020-01-27T18:11:13.000Z
|
2020-01-27T18:11:13.000Z
|
src/blocks/shovel.cpp
|
ondralukes/OpenGLCraft
|
8384fc70c02dddcf593a2e6aab6c1cd7d0ba38a3
|
[
"MIT"
] | 12
|
2020-01-22T09:16:29.000Z
|
2020-02-10T21:37:50.000Z
|
src/blocks/shovel.cpp
|
ondralukes/OpenGLCraft
|
8384fc70c02dddcf593a2e6aab6c1cd7d0ba38a3
|
[
"MIT"
] | null | null | null |
#include "shovel.hpp"
using namespace Blocks;
WoodenShovel::WoodenShovel() : Block("textures/woodenShovel.dds"){
data.type = WOODEN_SHOVEL;
toolType = SHOVEL;
toolLevel = 1.0f;
hp = 50;
maxStack = 1;
drawFlat = true;
fuelValue = 0.15f;
}
void
WoodenShovel::save(){
if(data.dataPos == 0){
data.dataPos = SaveManager::main->allocateBlockData(sizeof(int));
}
FILE * fp = SaveManager::main->getBlockDatafp();
fseek(fp, data.dataPos, SEEK_SET);
fwrite(&hp, sizeof(int), 1, fp);
}
void
WoodenShovel::load(){
if(data.dataPos == 0) return;
FILE * fp = SaveManager::main->getBlockDatafp();
fseek(fp, data.dataPos, SEEK_SET);
fread(&hp, sizeof(int), 1, fp);
}
bool
WoodenShovel::usedAsTool(){
hp--;
if(hp == 0) return true;
save();
return false;
}
float
WoodenShovel::getHP(){
return hp/50.0f;
}
StoneShovel::StoneShovel() : Block("textures/stoneShovel.dds"){
data.type = STONE_SHOVEL;
toolType = SHOVEL;
toolLevel = 2.0f;
hp = 150;
maxStack = 1;
drawFlat = true;
}
void
StoneShovel::save(){
if(data.dataPos == 0){
data.dataPos = SaveManager::main->allocateBlockData(sizeof(int));
}
FILE * fp = SaveManager::main->getBlockDatafp();
fseek(fp, data.dataPos, SEEK_SET);
fwrite(&hp, sizeof(int), 1, fp);
}
void
StoneShovel::load(){
if(data.dataPos == 0) return;
FILE * fp = SaveManager::main->getBlockDatafp();
fseek(fp, data.dataPos, SEEK_SET);
fread(&hp, sizeof(int), 1, fp);
}
bool
StoneShovel::usedAsTool(){
hp--;
if(hp == 0) return true;
save();
return false;
}
float
StoneShovel::getHP(){
return hp/150.0f;
}
| 18.847059
| 69
| 0.654806
|
ondralukes
|
cac85812ef474b9f1ddf4c50d8e5d72e6462bd81
| 2,860
|
cpp
|
C++
|
graph-source-code/225-D/12319993.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/225-D/12319993.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/225-D/12319993.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: GNU C++
#include <stdio.h>
#include <set>
#include <queue>
#include <algorithm>
using namespace std;
int n,m,res=-1;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
set<int> v;
struct State{
int steps;
char a[15][15];
int hash(){
int res=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
res=171*res+a[i][j];
}
}
return res;
}
void takeout(char c){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(a[i][j]==c){
a[i][j]='.';
return;
}
}
}
return;
}
void increase(){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(a[i][j]>='0' && a[i][j]<='9')a[i][j]++;
}
}
}
};
queue<State> q;
bool inside(int x,int y){
return x>=0 && x<n && y>=0 && y<m;
}
void move(State& state){
int x,y,h;
state.steps++;
for(int i=0;i<n;i++)for(int j=0;j<m;j++)if(state.a[i][j]=='2'){
for(int f=0;f<4;f++){
x=i+dx[f];y=j+dy[f];
if(inside(x,y)){
if(state.a[x][y]=='@'){
res=state.steps;
return;
}
if(state.a[x][y]=='.'){
state.a[x][y]='1';
h=state.hash();
if(v.find(h)==v.end()){
q.push(state);
v.insert(h);
}
state.a[x][y]='.';
}
}
}
return;
}
return;
}
int main(){
//freopen("D:\\input.txt","r",stdin);
bool f=false;
int len=0;
State init,p;
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){
scanf("%s",init.a[i]);
for(int j=0;j<m;j++){
//printf("%c",init.a[i][j]);
if(init.a[i][j]>='0' && init.a[i][j]<='9'){
len=max(len,init.a[i][j]-'0');
}
}
//printf("\n");
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(init.a[i][j]=='@'){
if(inside(i-1,j) && init.a[i-1][j]!='#')f=true;
if(inside(i+1,j) && init.a[i+1][j]!='#')f=true;
if(inside(i,j-1) && init.a[i][j-1]!='#')f=true;
if(inside(i,j+1) && init.a[i][j+1]!='#')f=true;
}
}
}
if(!f){
printf("-1");
return 0;
}
init.steps=0;
q.push(init);
v.insert(init.hash());
while(!q.empty() && res==-1){
p=q.front();q.pop();
p.takeout(len+'0');
p.increase();
move(p);
}
printf("%d",res);
return 0;
}
| 23.636364
| 68
| 0.334965
|
AmrARaouf
|
cacb1e31443fab418f88f96d7d86e355005af0be
| 579
|
cpp
|
C++
|
src/page_02/task076.cpp
|
berlios/pe
|
5edd686481666c86a14804cfeae354a267d468be
|
[
"MIT"
] | null | null | null |
src/page_02/task076.cpp
|
berlios/pe
|
5edd686481666c86a14804cfeae354a267d468be
|
[
"MIT"
] | null | null | null |
src/page_02/task076.cpp
|
berlios/pe
|
5edd686481666c86a14804cfeae354a267d468be
|
[
"MIT"
] | null | null | null |
#include <vector>
#include "base/task.h"
int CountNumberOfPartitions(int remaining, std::vector<int>* sequence) {
if (remaining == 0) {
return 1;
}
int sum = 0;
int max = sequence->back();
for (int i = 1; i <= max && i <= remaining; ++i) {
sequence->push_back(i);
sum += CountNumberOfPartitions(remaining - i, sequence);
sequence->pop_back();
}
return sum;
}
TASK(76) {
int counter = 0;
for (int i = 1; i < 100; ++i) {
std::vector<int> sequence = {i};
counter += CountNumberOfPartitions(100 - i, &sequence);
}
return counter;
}
| 19.965517
| 72
| 0.599309
|
berlios
|
cace21609f44f0cb375f10b09fdf0a83c31efd60
| 107
|
cpp
|
C++
|
src/server.cpp
|
MlsDmitry/RakNet-samples
|
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
|
[
"MIT"
] | null | null | null |
src/server.cpp
|
MlsDmitry/RakNet-samples
|
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
|
[
"MIT"
] | null | null | null |
src/server.cpp
|
MlsDmitry/RakNet-samples
|
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
|
[
"MIT"
] | null | null | null |
//
// server.cpp
// cserver
//
// Created by Dmitry Molokovich on 02/04/2021.
//
#include "server.hpp"
| 11.888889
| 47
| 0.626168
|
MlsDmitry
|
caceeab17b19fa90797e3aba166b0bb867d0c05e
| 35,618
|
cpp
|
C++
|
LGTV Companion Service/Service.cpp
|
dechamps/LGTVCompanion
|
9c68d79c3a1314c7064bcebb712684dbd1a305c7
|
[
"MIT"
] | null | null | null |
LGTV Companion Service/Service.cpp
|
dechamps/LGTVCompanion
|
9c68d79c3a1314c7064bcebb712684dbd1a305c7
|
[
"MIT"
] | null | null | null |
LGTV Companion Service/Service.cpp
|
dechamps/LGTVCompanion
|
9c68d79c3a1314c7064bcebb712684dbd1a305c7
|
[
"MIT"
] | null | null | null |
// See LGTV Companion UI.cpp for additional details
#include "Service.h"
using namespace std;
using json = nlohmann::json;
//globals
SERVICE_STATUS gSvcStatus;
SERVICE_STATUS_HANDLE gSvcStatusHandle;
HANDLE ghSvcStopEvent = NULL;
HPOWERNOTIFY gPs1;
json jsonPrefs; //contains the user preferences in json
PREFS Prefs; //App preferences
vector <CSession> DeviceCtrlSessions; //CSession objects manage network connections with Display
DWORD EventCallbackStatus = NULL;
WSADATA WSAData;
//mutex g_mutex;
wstring DataPath;
vector<string> HostIPs;
wchar_t sddl[] = L"D:"
L"(A;;CCLCSWRPWPDTLOCRRC;;;SY)" // default permissions for local system
L"(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)" // default permissions for administrators
L"(A;;CCLCSWLOCRRC;;;AU)" // default permissions for authenticated users
L"(A;;CCLCSWRPWPDTLOCRRC;;;PU)" // default permissions for power users
L"(A;;RPWP;;;IU)" // added permission: start/stop service for interactive users
;
// Application entrypoint
int wmain(int argc, wchar_t* argv[])
{
if (lstrcmpi(argv[1], L"-install") == 0)
{
SvcInstall();
return 0;
}
if (lstrcmpi(argv[1], L"-uninstall") == 0)
{
SvcUninstall();
return 0;
}
SERVICE_TABLE_ENTRY DispatchTable[] =
{
{ (LPWSTR)SVCNAME, (LPSERVICE_MAIN_FUNCTION)SvcMain },
{ NULL, NULL }
};
// This call returns when the service has stopped.
if (!StartServiceCtrlDispatcher(DispatchTable))
SvcReportEvent(EVENTLOG_ERROR_TYPE, L"StartServiceCtrlDispatcher");
return 0;
}
// Install service in the SCM database
VOID SvcInstall()
{
SC_HANDLE schSCManager;
SC_HANDLE schService;
WCHAR szPath[MAX_PATH];
if (!GetModuleFileNameW(NULL, szPath, MAX_PATH))
{
printf("Failed to install service (%d).\n", GetLastError());
return;
}
schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (!schSCManager)
{
printf("Failed to install service. Please run again as ADMIN. OpenSCManager failed (%d).\n", GetLastError());
return;
}
// Create the service
schService = CreateService(
schSCManager, // SCM database
SVCNAME, // name of service
SVCDISPLAYNAME, // service name to display
SERVICE_ALL_ACCESS|WRITE_DAC, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_AUTO_START, // start type
SERVICE_ERROR_NORMAL, // error control type
szPath, // path to service's binary
NULL, // no load ordering group
NULL, // no tag identifier
SERVICE_DEPENDENCIES, // dependencies
SERVICE_ACCOUNT, // LocalSystem account
NULL); // no password
if (schService == NULL)
{
printf("Failed to install service. CreateService failed (%d).\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
}
else
{
PSECURITY_DESCRIPTOR sd;
if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, SDDL_REVISION_1, &sd, NULL))
{
printf("Failed to set security descriptor (%d).\n", GetLastError());
}
if (!SetServiceObjectSecurity(schService, DACL_SECURITY_INFORMATION, sd))
{
printf("Failed to set security descriptor(%d).\n", GetLastError());
}
if (!StartService(
schService, // handle to service
0, // number of arguments
NULL)) // no arguments
{
printf("Installation of service was successful but the service failed to start (%d).\n", GetLastError());
}
else
printf("Service successfully installed and started.\n");
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}
// Uninstall service in the SCM database
VOID SvcUninstall()
{
SC_HANDLE schSCManager;
SC_HANDLE schService;
SERVICE_STATUS_PROCESS ssp;
DWORD dwStartTime = (DWORD)GetTickCount64();
DWORD dwBytesNeeded;
DWORD dwTimeout = 15000; // 15-second time-out
// Get a handle to the SCM database.
schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == schSCManager)
{
printf("Failed to uninstall service. Please run again as ADMIN. OpenSCManager failed (%d).\n", GetLastError());
return;
}
// Get a handle to the service.
schService = OpenService(
schSCManager, // SCM database
SVCNAME, // name of service
SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE);
if (!schService)
{
printf("Failed to uninstall service. OpenService failed (%d).\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
}
if (!QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded))
{
printf("QueryServiceStatusEx failed (%d).\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
ControlService(
schService,
SERVICE_CONTROL_STOP,
(LPSERVICE_STATUS)&ssp);
// Wait for the service to stop.
while (ssp.dwCurrentState != SERVICE_STOPPED)
{
Sleep(ssp.dwWaitHint);
if (QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded))
{
if (ssp.dwCurrentState == SERVICE_STOPPED)
break;
if ((DWORD)GetTickCount64() - dwStartTime > dwTimeout)
{
printf("Failed to uninstall service. Timed out when stoppping service.\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
}
else
{
printf("Failed to uninstall service. Unable to query service status.\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
}
if (!DeleteService(schService))
{
printf("Failed to uninstall service. DeleteService failed (%d)\n", GetLastError());
}
else printf("Service uninstalled successfully\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}
// Service entrypoint
VOID WINAPI SvcMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
gSvcStatusHandle = RegisterServiceCtrlHandlerExW(SVCNAME,SvcCtrlHandler, NULL);
if (!gSvcStatusHandle)
{
SvcReportEvent(EVENTLOG_ERROR_TYPE, L"RegisterServiceCtrlHandler");
return;
}
// These SERVICE_STATUS members remain as set here
gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
gSvcStatus.dwServiceSpecificExitCode = 0;
// Report SERVICE_START_PENDING status to the SCM
ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);
ghSvcStopEvent = CreateEvent( NULL, TRUE, FALSE, NULL);
if (!ghSvcStopEvent)
{
SvcReportEvent(EVENTLOG_ERROR_TYPE, L"CreateEvent");
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
return;
}
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
{
SvcReportEvent(EVENTLOG_ERROR_TYPE, L"WSAStartup");
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
return;
}
//load the config file into json::Prefs and initiate the device control sessions
try {
if (ReadConfigFile())
InitDeviceSessions();
}
catch(std::exception const& e)
{
wstring s = L"ERROR! Failed to read the configuration file. LGTV service is terminating. Error: ";
s += widen(e.what());
SvcReportEvent(EVENTLOG_ERROR_TYPE, s);
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
UnregisterPowerSettingNotification(gPs1);
WSACleanup();
return;
}
//get local host IPs, if possible at this time
HostIPs = GetOwnIP();
if (HostIPs.size() > 0)
{
string logmsg;
if (HostIPs.size() == 1)
logmsg = "Host IP detected: ";
else
logmsg = "Host IPs detected: ";
for (int index = 0; index < HostIPs.size(); index++)
{
logmsg += HostIPs[index];
if (index != HostIPs.size() - 1)
logmsg += ", ";
}
Log(logmsg);
}
//subscribe to EventID 1074, which contain information about whether user/system triggered restart or shutdown
EVT_HANDLE hSub = NULL;
hSub = EvtSubscribe(NULL, //local computer
NULL, // no signalevent
L"System", //channel path
L"Event/System[EventID=1074]", //query
NULL, //bookmark
NULL, //Context
(EVT_SUBSCRIBE_CALLBACK)SubCallback, //callback
EvtSubscribeToFutureEvents);
thread thread_obj(IPCThread);
thread_obj.detach();
if (SetProcessShutdownParameters(0x1E1, 0))
Log("Setting shutdown parameter level 0x1E1");
// else if (SetProcessShutdownParameters(0x3ff, 0))
// Log("Setting shutdown parameter level 0x3FF");
else
Log("Could not set shutdown parameter level");
SetProcessShutdownParameters(0x3FF,0);
ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
//register to receive power notifications
gPs1 = RegisterPowerSettingNotification(gSvcStatusHandle, &(GUID_CONSOLE_DISPLAY_STATE), DEVICE_NOTIFY_SERVICE_HANDLE);
SvcReportEvent(EVENTLOG_INFORMATION_TYPE, L"The service has started.");
// Wait until service stops
WaitForSingleObject(ghSvcStopEvent, INFINITE);
//terminate the device control sessions
DeviceCtrlSessions.clear();
UnregisterPowerSettingNotification(gPs1);
WSACleanup();
EvtClose(hSub);
Log("The service terminated.\n");
SvcReportEvent(EVENTLOG_INFORMATION_TYPE, L"The service has ended.");
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
return;
}
// Sets the current service status and reports it to the SCM.
VOID ReportSvcStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint)
{
static DWORD dwCheckPoint = 1;
// Fill in the SERVICE_STATUS structure.
gSvcStatus.dwCurrentState = dwCurrentState;
gSvcStatus.dwWin32ExitCode = dwWin32ExitCode;
gSvcStatus.dwWaitHint = dwWaitHint;
if (dwCurrentState == SERVICE_START_PENDING)
gSvcStatus.dwControlsAccepted = 0;
else gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PRESHUTDOWN | SERVICE_ACCEPT_POWEREVENT; //SERVICE_ACCEPT_PRESHUTDOWN | // | SERVICE_ACCEPT_USERMODEREBOOT; //does not work
if ((dwCurrentState == SERVICE_RUNNING) ||
(dwCurrentState == SERVICE_STOPPED))
gSvcStatus.dwCheckPoint = 0;
else gSvcStatus.dwCheckPoint = dwCheckPoint++;
// Report the status of the service to the SCM.
SetServiceStatus(gSvcStatusHandle, &gSvcStatus);
}
// Called by SCM whenever a control code is sent to the service using the ControlService function. dwCtrl - control code
DWORD SvcCtrlHandler(DWORD dwCtrl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext)
{
bool bThreadNotFinished;
switch (dwCtrl)
{
case SERVICE_CONTROL_STOP:
ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 20000);
do
{
bThreadNotFinished = false;
for (auto& dev : DeviceCtrlSessions)
{
if (dev.IsBusy())
bThreadNotFinished = true;
}
if (bThreadNotFinished)
Sleep(100);
} while (bThreadNotFinished);
// Signal the service to stop.
SetEvent(ghSvcStopEvent);
ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);
break;
// case SERVICE_CONTROL_USERMODEREBOOT: // does not seem to work. Unfortunate! Need to investigate alternative means of detecting a system restart then.
// break;
case SERVICE_CONTROL_POWEREVENT:
switch (dwEventType)
{
case PBT_APMRESUMEAUTOMATIC:
EventCallbackStatus = NULL;;
Log("** System resumed from low power state (Automatic).");
DispatchSystemPowerEvent(SYSTEM_EVENT_RESUMEAUTO);
break;
case PBT_APMRESUMESUSPEND:
EventCallbackStatus = NULL;;
Log("** System resumed from low power state.");
DispatchSystemPowerEvent(SYSTEM_EVENT_RESUME);
break;
case PBT_APMSUSPEND:
if (EventCallbackStatus == SYSTEM_EVENT_REBOOT)
{
Log("** System is restarting.");
DispatchSystemPowerEvent(SYSTEM_EVENT_REBOOT);
}
else if (EventCallbackStatus == SYSTEM_EVENT_SHUTDOWN)
{
Log("** System is shutting down (low power mode).");
DispatchSystemPowerEvent(SYSTEM_EVENT_SUSPEND);
}
else if (EventCallbackStatus == SYSTEM_EVENT_UNSURE)
{
Log("WARNING! Unable to determine if system is shutting down or restarting. Please check 'additional settings' in the UI.");
DispatchSystemPowerEvent(SYSTEM_EVENT_UNSURE);
}
else
{
Log("** System is suspending to a low power state.");
DispatchSystemPowerEvent(SYSTEM_EVENT_SUSPEND);
}
break;
case PBT_POWERSETTINGCHANGE:
if (lpEventData)
{
POWERBROADCAST_SETTING* PBS = NULL;
string text;
PBS = (POWERBROADCAST_SETTING*)lpEventData;
if (PBS->PowerSetting == GUID_CONSOLE_DISPLAY_STATE)
{
text = (DWORD)PBS->Data[0] == 0 ? "** System requests displays OFF." : "** System requests displays ON.";
Log(text);
DispatchSystemPowerEvent(PBS->Data[0] == 0 ? SYSTEM_EVENT_DISPLAYOFF : SYSTEM_EVENT_DISPLAYON);
}
else
{
char guid_cstr[39];
GUID guid = PBS->PowerSetting;
snprintf(guid_cstr, sizeof(guid_cstr),
"PBT_POWERSETTINGCHANGE unknown GUID:: {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
text = guid_cstr;
Log(text);
}
}
break;
default:break;
}
break;
case SERVICE_CONTROL_PRESHUTDOWN:
if (EventCallbackStatus == SYSTEM_EVENT_REBOOT)
{
Log("** System is restarting.");
DispatchSystemPowerEvent(SYSTEM_EVENT_REBOOT);
}
else if (EventCallbackStatus == SYSTEM_EVENT_SHUTDOWN)
{
Log("** System is shutting down.");
DispatchSystemPowerEvent(SYSTEM_EVENT_SHUTDOWN);
}
else if (EventCallbackStatus == SYSTEM_EVENT_UNSURE)
{
Log("WARNING! Unable to determine if system is shutting down or restarting. Please check 'additional settings in the UI.");
DispatchSystemPowerEvent(SYSTEM_EVENT_UNSURE);
}
else
{
//This does happen sometimes, probably for timing reasons when shutting down the system.
Log("WARNING! The application did not receive an Event Subscription Callback prior to system shutting down. Unable to determine if system is shutting down or restarting.");
DispatchSystemPowerEvent(SYSTEM_EVENT_UNSURE);
}
//copy paste from the STOP event below
ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 20000);
do
{
bThreadNotFinished = false;
for (auto& dev : DeviceCtrlSessions)
{
if (dev.IsBusy())
bThreadNotFinished = true;
}
if(bThreadNotFinished)
Sleep(100);
} while (bThreadNotFinished);
// Signal the service to stop.
SetEvent(ghSvcStopEvent);
ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);
break;
case SERVICE_CONTROL_INTERROGATE:
Log("SERVICE_CONTROL_INTERROGATE");
break;
default:
break;
}
return NO_ERROR;
}
// Add an event in the event log. Type can be: EVENTLOG_SUCCESS, EVENTLOG_ERROR_TYPE, EVENTLOG_INFORMATION_TYPE
VOID SvcReportEvent(WORD Type, wstring string)
{
HANDLE hEventSource;
LPCTSTR lpszStrings[2];
hEventSource = RegisterEventSource(NULL, SVCNAME);
if (hEventSource)
{
wstring s;
switch (Type)
{
case EVENTLOG_ERROR_TYPE:
s = string;
s += L" failed with error: ";
s += GetErrorMessage(GetLastError());
break;
case EVENTLOG_SUCCESS:
s = string;
s += L" succeeded.";
break;
case EVENTLOG_INFORMATION_TYPE:
default:
s = string;
break;
}
lpszStrings[0] = SVCNAME;
lpszStrings[1] = s.c_str();
ReportEvent(hEventSource, // event log handle
Type, // event type
0, // event category
0, // event identifier
NULL, // no security identifier
2, // size of lpszStrings array
0, // no binary data
lpszStrings, // array of strings
NULL); // no binary data
DeregisterEventSource(hEventSource);
}
}
// Format the error message to readable form
wstring GetErrorMessage(DWORD dwErrorCode)
{
if (dwErrorCode)
{
WCHAR* lpMsgBuf = NULL;
DWORD bufLen = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
lpMsgBuf,
0, NULL);
if (bufLen)
{
LPCSTR lpMsgStr = (LPCSTR)lpMsgBuf;
wstring result(lpMsgStr, lpMsgStr + bufLen);
LocalFree(lpMsgBuf);
return result;
}
}
return L"";
}
// Write key to configuration file when a thread has received a pairing key. Should be called in thread safe manner
bool SetSessionKey(string Key, string deviceid)
{
if (Key.size() > 0 && deviceid.size() > 0)
{
wstring path = DataPath;
path += L"config.json";
ofstream i(path.c_str());
if (i.is_open())
{
jsonPrefs[deviceid]["SessionKey"] = Key;
i << setw(4) << jsonPrefs << endl;
i.close();
// return true;
}
}
string s = deviceid;
s += ", pairing key received: ";
s += Key;
Log(s);
return true;
}
// Read the configuration file into a json object and populate the preferences struct
bool ReadConfigFile()
{
WCHAR szPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath)))
{
string st = "LGTV Companion Service started (v ";
st += narrow(APPVERSION);
st += ") ---------------------------";
string ty = "Data path: ";
wstring path = szPath;
path += L"\\";
path += APPNAME;
path += L"\\";
CreateDirectory(path.c_str(), NULL);
ty += narrow(path);
Log(ty);
DataPath = path;
path += L"config.json";
ifstream i(path.c_str());
if (i.is_open())
{
json j;
i >> jsonPrefs;
i.close();
j = jsonPrefs[JSON_PREFS_NODE][JSON_EVENT_RESTART_STRINGS];
if (!j.empty() && j.size() > 0)
{
Prefs.EventLogRestartString.clear();
for (auto& elem : j.items())
Prefs.EventLogRestartString.push_back(elem.value().get<string>());
}
j = jsonPrefs[JSON_PREFS_NODE][JSON_EVENT_SHUTDOWN_STRINGS];
if (!j.empty() && j.size() > 0)
{
Prefs.EventLogShutdownString.clear();
for (auto& elem : j.items())
Prefs.EventLogShutdownString.push_back(elem.value().get<string>());
}
j = jsonPrefs[JSON_PREFS_NODE][JSON_VERSION];
if (!j.empty() && j.is_number())
Prefs.version = j.get<int>();
j = jsonPrefs[JSON_PREFS_NODE][JSON_PWRONTIMEOUT];
if (!j.empty() && j.is_number())
Prefs.PowerOnTimeout =j.get<int>();
j = jsonPrefs[JSON_PREFS_NODE][JSON_LOGGING];
if (!j.empty() && j.is_boolean())
Prefs.Logging = j.get<bool>();
Log(st);
Log("Configuration file successfully read");
Log(ty);
return true;
}
}
return false;
}
// Create and init device objects
void InitDeviceSessions()
{
if (jsonPrefs.empty())
return;
//Clear current sessions.
DeviceCtrlSessions.clear();
//Iterate nodes
for (const auto& item : jsonPrefs.items())
{
json j;
if (item.key() == JSON_PREFS_NODE)
break;
stringstream s;
SESSIONPARAMETERS params;
params.DeviceId = item.key();
s << params.DeviceId << ", ";
if (item.value()["Name"].is_string())
params.Name = item.value()["Name"].get<string>();
s << params.Name << ", with IP ";
if(item.value()["IP"].is_string())
params.IP = item.value()["IP"].get<string>();
s << params.IP << " initiated (";
if (item.value()["Enabled"].is_boolean())
params.Enabled = item.value()["Enabled"].get<bool>();
s << "Enabled:" << (params.Enabled?"yes":"no") << ", ";
if (item.value()["Subnet"].is_string())
params.Subnet = item.value()["Subnet"].get<string>();
if (item.value()["WOL"].is_number())
params.WOLtype = item.value()["WOL"].get<int>();
s << "WOL:" << params.WOLtype << ", ";
if (params.WOLtype == WOL_SUBNETBROADCAST && params.Subnet != "")
s << "SubnetMask:" << params.Subnet << ", ";
if(item.value()["SessionKey"].is_string())
params.SessionKey = item.value()["SessionKey"].get<string>();
s << "Pairing key:" << (params.SessionKey =="" ? "n/a" : params.SessionKey) << ", MAC: ";
j = item.value()["MAC"];
if (!j.empty() && j.size() > 0)
{
for (auto& m : j.items())
{
params.MAC.push_back(m.value().get<string>());
s << m.value().get<string>()<< " ";
}
s << ")";
}
else
s << "n/a )";
params.PowerOnTimeout = Prefs.PowerOnTimeout;
CSession S(¶ms);
DeviceCtrlSessions.push_back(S);
Log(s.str());
}
return;
}
// Broadcast power events (display on/off, resuming, rebooting etc) to the device objects
bool DispatchSystemPowerEvent(DWORD dwMsg)
{
if (DeviceCtrlSessions.size() == 0)
{
Log("WARNING! No Devices in DispatchSystemPowerEvent().");
return false;
}
for (auto& value : DeviceCtrlSessions)
value.SystemEvent(dwMsg);
//get local host IPs, if possible at this time
if (HostIPs.size() == 0)
{
HostIPs = GetOwnIP();
if (HostIPs.size() != 0)
{
string logmsg;
if(HostIPs.size() == 1)
logmsg = "Host IP detected: ";
else
logmsg = "Host IPs detected: ";
for (int index = 0; index < HostIPs.size(); index++)
{
logmsg += HostIPs[index];
if (index != HostIPs.size() - 1)
logmsg += ", ";
}
Log(logmsg);
}
}
return true;
}
// Write to log file
void Log(string ss)
{
if (!Prefs.Logging)
return;
ofstream m;
time_t rawtime;
struct tm timeinfo;
char buffer[80];
wstring path = DataPath;
time(&rawtime);
localtime_s(&timeinfo,&rawtime);
strftime(buffer, 80, "%a %H:%M:%S > ", &timeinfo);
puts(buffer);
string s = buffer;
s += ss;
s += "\n";
path += L"Log.txt";
m.open(path.c_str(), ios::out | ios::app);
if (m.is_open())
{
m << s.c_str();
m.close();
}
}
// Callback function for the event log to determine restart or power off, by asking for Events with EventID 1074 to be pushed to the application. Localisation is an issue though....
DWORD WINAPI SubCallback(EVT_SUBSCRIBE_NOTIFY_ACTION Action, PVOID UserContext, EVT_HANDLE hEvent)
{
UNREFERENCED_PARAMETER(UserContext);
wstring s;
EventCallbackStatus = NULL;
if (Action == EvtSubscribeActionDeliver)
{
DWORD dwBufferSize = 0;
DWORD dwBufferUsed = 0;
DWORD dwPropertyCount = 0;
LPWSTR pRenderedContent = NULL;
if (!EvtRender(NULL, hEvent, EvtRenderEventXml, dwBufferSize, pRenderedContent, &dwBufferUsed, &dwPropertyCount))
{
if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
{
dwBufferSize = dwBufferUsed;
pRenderedContent = (LPWSTR)malloc(dwBufferSize);
if (pRenderedContent)
{
EvtRender(NULL, hEvent, EvtRenderEventXml, dwBufferSize, pRenderedContent, &dwBufferUsed, &dwPropertyCount);
}
}
}
if (pRenderedContent)
{
s = pRenderedContent;
free(pRenderedContent);
}
}
for (auto& str : Prefs.EventLogShutdownString)
{
wstring w = L">";
w += widen(str);
w += L"<";
if (s.find(w) != wstring::npos)
{
EventCallbackStatus = SYSTEM_EVENT_SHUTDOWN;
Log("Event subscription callback: system shut down detected.");
}
}
for (auto & str : Prefs.EventLogRestartString)
{
wstring w = L">";
w += widen(str);
w += L"<";
if (s.find(w) != wstring::npos)
{
EventCallbackStatus = SYSTEM_EVENT_REBOOT;
Log("Event subscription callback: System restart detected.");
}
}
if (EventCallbackStatus == NULL)
{
EventCallbackStatus = SYSTEM_EVENT_UNSURE;
Log("WARNING! Event subscription callback: Could not detect whether system is shutting down or restarting. Please check 'additional settings' in the UI.");
}
return 0;
}
// Convert UTF-8 to wide
wstring widen(string sInput) {
if (sInput == "")
return L"";
// Calculate target buffer size
long len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, sInput.c_str(), (int)sInput.size(), NULL, 0);
if (len == 0)
return L"";
// Convert character sequence
wstring out(len, 0);
if (len != MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, sInput.c_str(), (int)sInput.size(), &out[0], (int)out.size()))
return L"";
return out;
}
// Convert wide to UTF-8
string narrow(wstring sInput) {
// Calculate target buffer size
long len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, sInput.c_str(), (int)sInput.size(),
NULL, 0, NULL, NULL);
if (len == 0)
return "";
// Convert character sequence
string out(len, 0);
if (len != WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, sInput.c_str(), (int)sInput.size(), &out[0], (int)out.size(), NULL, NULL))
return "";
return out;
}
// THREAD: The intra process communications (named pipe) thread. Runs for the duration of the service
void IPCThread(void)
{
HANDLE hPipe;
char buffer[1024];
DWORD dwRead;
PSECURITY_DESCRIPTOR psd = NULL;
BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
psd = (PSECURITY_DESCRIPTOR)sd;
InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(psd, TRUE, (PACL)NULL, FALSE);
SECURITY_ATTRIBUTES sa = { sizeof(sa), psd, FALSE };
// Log("Creating named pipe");
hPipe = CreateNamedPipe(PIPENAME,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
1,
1024 * 16,
1024 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
&sa);
while (hPipe != INVALID_HANDLE_VALUE )
{
if (ConnectNamedPipe(hPipe, NULL) != FALSE) // wait for someone to connect to the pipe
{
while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
{
/* add terminating zero */
buffer[dwRead] = '\0';
string s = "IPC command received: ";
string t = buffer;
s += t;
Log(s);
transform(t.begin(), t.end(), t.begin(), ::tolower);
vector <string> cmd = stringsplit(t, " ");
if (cmd.size() > 1)
{
int param1 = 0;
for (auto& param : cmd)
{
if (param == "-poweron")
param1 = APP_CMDLINE_ON;
else if (param == "-poweroff")
param1 = APP_CMDLINE_OFF;
else if (param == "-autoenable")
param1 = APP_CMDLINE_AUTOENABLE;
else if (param == "-autodisable")
param1 = APP_CMDLINE_AUTODISABLE;
else if (param1 > 0)
{
for (auto& device : DeviceCtrlSessions)
{
SESSIONPARAMETERS s = device.GetParams();
string id = s.DeviceId;
string name = s.Name;
transform(id.begin(), id.end(), id.begin(), ::tolower);
transform(name.begin(), name.end(), name.begin(), ::tolower);
if (param1 == APP_CMDLINE_ON && (id == param || name == param))
{
device.SystemEvent(SYSTEM_EVENT_FORCEON);
}
else if (param1 == APP_CMDLINE_OFF && (id == param || name == param))
{
device.SystemEvent(SYSTEM_EVENT_FORCEOFF);
}
else if (param1 == APP_CMDLINE_AUTOENABLE && (id == param || name == param))
{
device.Run();
string temp = s.DeviceId;
temp +=", automatic management is temporarily enabled (effective until restart of service).";
Log(temp);
}
else if (param1 == APP_CMDLINE_AUTODISABLE && (id == param || name == param))
{
device.Stop();
string temp = s.DeviceId;
temp += ", automatic management is temporarily disabled (effective until restart of service).";
Log(temp);
}
}
}
}
}
}
}
DisconnectNamedPipe(hPipe);
}
return;
}
// Split a string into a vector of strings, modified to accept quotation marks
vector<string> stringsplit(string str, string token) {
vector<string>res;
while (str.size() > 0)
{
size_t index;
if (str[0] == '\"') // quotation marks
{
index = str.find("\"", 1);
if (index != string::npos)
{
if (index - 2 > 0)
{
string temp = str.substr(1, index - 1);
res.push_back(temp);
}
size_t next = str.find_first_not_of(token, index + token.size());
if (next != string::npos)
str = str.substr(next); // str.substr(index + token.size());
else
str = "";
}
else
{
res.push_back(str);
str = "";
}
}
else // not quotation marks
{
index = str.find(token);
if (index != string::npos)
{
res.push_back(str.substr(0, index));
size_t next = str.find_first_not_of(token, index + token.size());
if (next != string::npos)
str = str.substr(next); // str.substr(index + token.size());
else
str = "";
}
else {
res.push_back(str);
str = "";
}
}
}
return res;
}
// Get the local host ip, e.g 192.168.1.x
vector <string> GetOwnIP(void)
{
vector <string> IPs;
char host[256];
if (gethostname(host, sizeof(host)) != SOCKET_ERROR)
{
struct hostent* phent = gethostbyname(host);
if (phent != 0)
{
for (int i = 0; phent->h_addr_list[i] != 0; ++i)
{
string ip;
struct in_addr addr;
memcpy(&addr, phent->h_addr_list[i], sizeof(struct in_addr));
ip = inet_ntoa(addr);
if (ip != "127.0.0.1")
IPs.push_back(ip);
}
}
}
return IPs;
}
| 32.707071
| 201
| 0.539952
|
dechamps
|
cad5b9bee2ed5bd54759e2842da259afa0d13d30
| 648
|
cpp
|
C++
|
src/display_diff_example.cpp
|
meconlen/stringAlgorithms
|
102357edc78845a361b8420791b353699acdd4fb
|
[
"BSD-2-Clause"
] | 1
|
2018-01-21T13:36:49.000Z
|
2018-01-21T13:36:49.000Z
|
src/display_diff_example.cpp
|
meconlen/stringAlgorithms
|
102357edc78845a361b8420791b353699acdd4fb
|
[
"BSD-2-Clause"
] | null | null | null |
src/display_diff_example.cpp
|
meconlen/stringAlgorithms
|
102357edc78845a361b8420791b353699acdd4fb
|
[
"BSD-2-Clause"
] | null | null | null |
#include <config.h>
#include <string>
#include <vector>
#include "needlemanwunsch.hpp"
#include "stringoutput.hpp"
using stringAlgorithms::NeedlemanWunsch;
using stringAlgorithms::display_diff;
using stringAlgorithms::scoring::plus_minus_one;
int main(int argc, char *argv[])
{
std::vector<uint64_t> x = { 1, 2, 3, 4, 5 };
std::vector<uint64_t> y = { 1, 2, 0, 5};
std::vector<uint64_t> s, t;
uint64_t delIndicator = -1;
// lambda
NeedlemanWunsch(x.begin(), x.end(), y.begin(), y.end(), std::back_inserter(s), std::back_inserter(t), plus_minus_one, -1, delIndicator);
display_diff(s, t, delIndicator);
return 0;
}
| 24
| 139
| 0.679012
|
meconlen
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.