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
sequencelengths 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
sequencelengths 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
88272ef7427fbb6c6403d5ae5bcaea95374d8bb7 | 6,023 | hh | C++ | src/include/cpu.hh | tomblackwhite/alpha-emu | a371f7d094acbf02c83aa3940ff043f033b7cfe8 | [
"BSD-2-Clause"
] | null | null | null | src/include/cpu.hh | tomblackwhite/alpha-emu | a371f7d094acbf02c83aa3940ff043f033b7cfe8 | [
"BSD-2-Clause"
] | null | null | null | src/include/cpu.hh | tomblackwhite/alpha-emu | a371f7d094acbf02c83aa3940ff043f033b7cfe8 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <bitset>
#include <cstdint>
#include <functional>
#include <unordered_map>
#include <vector>
using std::uint16_t;
using std::uint8_t;
using std::int8_t;
using std::int16_t;
/* 寻址方式 6502为小端 */
enum class AddressMode {
// accumulator impiled single byte instruction
// operand is AC (implied single byte instruction)
accumulator,
// operand is address $HHLL
absolute,
// OPC $LLHH,X operand is address;
// effective address is address incremented by X with carry
absolute_x,
// OPC $LLHH,Y operand is address;
// effective address is address incremented by Y with carry **
absolute_y,
// OPC #$BB operand is byte BB
immediate,
// OPC operand implied
implied,
// OPC ($LLHH) operand is address;
// effective address is contents of word at address: C.w($HHLL)
indirect,
// OPC ($LL,X) operand is zeropage address;
// effective address is word in (LL + X, LL + X + 1), inc. without carry:
// C.w($00LL + X)
// An 8-bit zero-page address and the X register are added, without carry
//(if the addition overflows, the address wraps around within page 0).
x_indirect,
// OPC ($LL),Y operand is zeropage address;
// effective address is word in (LL, LL + 1) incremented by Y with carry:
// C.w($00LL) + Y
indirect_y,
// OPC $BB branch target is PC + signed offset BB ***
relative,
// OPC $LL operand is zeropage address (hi-byte is zero, address = $00LL)
zeropage,
// OPC $LL,X operand is zeropage address;
// effective address is address incremented by X without carry **
zeropage_x,
// OPC $LL,Y operand is zeropage address;
// effective address is address incremented by Y without carry **
zeropage_y
/*
* 所以不带进位的加法,不会影响到地址位的高位。
* 通常来说, increments of 16-bit addresses include a carry,
* increments of zeropage addresses don't.
* 这个和累加器的carry bit 无关
*/
};
enum class InstructionType {
ADC,AND,ASL,BCC,BCS,BEQ,BIT,BMI,BNE,BPL,BRK,BVC,BVS,CLC,CLD,CLI,CLV,CMP,
CPX,CPY,DEC,DEX,DEY,EOR,INC,INX,INY,JMP,JSR,LDA,LDX,LDY,LSR,NOP,ORA,PHA,
PHP,PLA,PLP,ROL,ROR,RTI,RTS,SBC,SEC,SED,SEI,STA,STX,STY,TAX,TAY,TSX,TXA,
TXS,TYA
};
//指令
struct Instruction {
//周期数
int m_cycleCount;
//指令的值
uint8_t m_operatorCode;
AddressMode m_addressMode;
InstructionType m_instructionType;
//执行实际的命令并设置相关寄存器
//在初始化时自动捕获当前上下文变量
std::function<void(uint16_t &memoryValue)> m_executor;
};
/*
** CPU负责读取内存中的命令
** 依次读取命令并执行命令并且设置相应
** 的寄存器,状态之类的。
** 需要根据命令读取内存中的数据,根据寻址方式,获取操作数,设置对应
** 的pc count
*/
class CPU {
private:
// memory instructions
/*
* status register
* N V - B D I Z C from bit 7 to bit 0
* N ... Negative
* V ... Overflow
* - ...ignored
* B ...Break
* D ... Decimal (use BCD for arithmetics)
* I ... Interrupt (IRQ disable)
* Z ... Zero
* C ... Carry
*/
std::bitset<8> m_SR = 0;
// accumulator register
uint8_t m_AC = 0;
// X register
uint8_t m_X = 0;
// Y register
uint8_t m_Y = 0;
// stack pointer
uint8_t m_statckPointer = 0;
// program counter
uint16_t m_PC = 0;
/*
* 内存
*/
std::vector<uint8_t> m_memory;
/*指令集*/
std::unordered_map<uint8_t, Instruction> m_instructionMap;
public:
//初始化指令集设置相关参数
void InitInstructionSet();
//开始执行内存中的代码
void Run();
/*
* 需要根据寻址模式获取值并且递增当前的program counter
* 首先获取opertor code 然后根据operator code 判断
* 寻址方式,获取实际的值
*/
uint8_t GetValue() { return 0; }
public:
CPU() { InitInstructionSet(); };
void test() {}
private:
auto NegativeFlag() { return m_SR[7]; }
auto OverflowFlag() { return m_SR[6]; }
auto BreakFlag() { return m_SR[4]; }
auto DecimalFlag() { return m_SR[3]; }
auto InterruptFlag() { return m_SR[2]; }
auto ZeroFlag() { return m_SR[1]; }
auto CarryFlag() { return m_SR[0]; }
/*寻址方式*/
/*获取指令使用的有效地址或者能直接使用的值*/
uint16_t GetAddressOrMemoryValue(AddressMode mode) {
uint16_t result = 0;
switch (mode) {
case AddressMode::accumulator: {
//取累加器中的值
result = m_X;
break;
}
case AddressMode::absolute: {
//取有效地址
result = m_memory[m_PC] + (m_memory[m_PC + 1] << 4);
m_PC += 2;
break;
}
case AddressMode::absolute_x: {
//取有效地址
result = m_memory[m_PC] + (m_memory[m_PC + 1] << 4) + m_X;
m_PC += 2;
break;
}
case AddressMode::absolute_y: {
//取有效地址
result = m_memory[m_PC] + (m_memory[m_PC + 1] << 4) + m_Y;
m_PC += 2;
break;
}
case AddressMode::immediate: {
//直接取值
result = m_memory[m_PC];
m_PC += 1;
break;
}
case AddressMode::implied: {
//直接返回
break;
}
case AddressMode::indirect: {
//取有效地址
uint16_t middleAddress = m_memory[m_PC] + (m_memory[m_PC + 1] << 4);
result = m_memory[middleAddress] + (m_memory[middleAddress + 1] << 4);
m_PC += 2;
break;
}
case AddressMode::x_indirect: {
//取有效地址
uint16_t middleAddress = m_memory[m_PC] + m_X;
middleAddress &= 0xFF;
result = m_memory[middleAddress] + (m_memory[middleAddress + 1] << 4);
m_PC += 1;
break;
}
case AddressMode::indirect_y: {
//取有效地址
uint16_t middleAddress = m_memory[m_PC] + (m_memory[m_PC + 1] << 4);
result = middleAddress + m_Y;
m_PC += 1;
break;
}
case AddressMode::relative: {
//取偏移量
result = m_memory[m_PC];
m_PC += 1;
break;
}
case AddressMode::zeropage: {
//取地址
result = m_memory[m_PC];
m_PC += 1;
break;
}
case AddressMode::zeropage_x: {
//取地址
result = m_memory[m_PC] + m_X;
result &= 0xFF;
m_PC += 1;
break;
}
case AddressMode::zeropage_y: {
//取地址
result = m_memory[m_PC] + m_Y;
result &= 0xFF;
m_PC += 1;
break;
}
default: {
static_assert(true, "未知的寻址类型");
}
}
return result;
}
/*获取根据寻址模式获取的值,获取指令执行时需要传的参数。*/
uint16_t GetInstructionParameter(uint16_t addressModeValue) { return 0;}
};
| 22.307407 | 76 | 0.618297 | tomblackwhite |
88279010049a442451ff74bcd4820086458b91df | 7,105 | hpp | C++ | bits.hpp | YagoMello/bits | 0d82845930ee71b78a995eca59d470ae29f58f02 | [
"Apache-2.0"
] | null | null | null | bits.hpp | YagoMello/bits | 0d82845930ee71b78a995eca59d470ae29f58f02 | [
"Apache-2.0"
] | null | null | null | bits.hpp | YagoMello/bits | 0d82845930ee71b78a995eca59d470ae29f58f02 | [
"Apache-2.0"
] | null | null | null | #ifndef BIT_HPP
#define BIT_HPP
/* Bit abstraction library
* Author: Yago T. de Mello
* e-mail: [email protected]
* Version: 2.6.0 2021-11-24
* License: Apache 2.0
* C++20
*/
/*
Copyright 2021 Yago Teodoro de Mello
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 <type_traits>
namespace bits {
// Used by bits::make_bit to select the correct template
// when reg_type is a pointer
template <typename T>
concept is_not_pointer = !std::is_pointer<typename std::remove_reference<T>::type>::value;
template <typename T>
concept is_const = std::is_const<typename std::remove_pointer<typename std::remove_reference<T>::type>::type>::value;
template <typename T>
concept is_not_const = !is_const<T>;
class bit {
public:
// The mutator and accessor function-pointers
using func_write_type = void (*)(const bool value);
using func_read_type = bool (*)();
// Allows the creation of uninitialized instances
bit() = default;
// Used by bits::make_bit
bit(
func_write_type func_write,
func_read_type func_read
) noexcept {
func_write_ = func_write;
func_read_ = func_read;
}
// Copy constructor
// Copies the value but not the function pointers
bit(const bit & obj) {
this->write(obj.read());
}
// Move constructor
// Makes no sense
bit(bit && obj) = delete;
// Sets the bit value
constexpr bit & operator =(const bool value) {
this->func_write_(value);
return *this;
}
// Forbid copy assignment
// forcing conversion to bool
bit & operator =(const bit &) = delete;
// Forces this object to use the other object's
// function pointers
constexpr void same_as(const bit & obj) noexcept {
this->func_write_ = obj.func_write_;
this->func_read_ = obj.func_read_;
}
// Gets the bit value
constexpr operator bool() const {
return this->func_read_();
}
// Explicit way to set the value to true
constexpr void set() {
this->func_write_(true);
}
// Explicit way to set the value to false
constexpr void clr() {
this->func_write_(false);
}
// Explicit way to set the value
constexpr void write(const bool value) {
this->func_write_(value);
}
// Explicit way to read the value
[[nodiscard]] constexpr bool read() const {
return this->func_read_();
}
// Template polymorphism generator
// Writes the value to a compile-time known variable
// If the variable is not const
template <auto & reg, auto offset>
static constexpr void default_write_static(const bool value)
requires is_not_const<decltype(reg)> {
using reg_type = std::remove_reference<decltype(reg)>::type;
using value_type = std::remove_volatile<reg_type>::type;
// Bit masks to select/clear the bit
constexpr value_type mask_bit = value_type(1) << offset;
constexpr value_type mask_clear = ~mask_bit;
// The clear result is stored in a temporary
// to prevent unnecessary writes/reads to reg
// when reg is volatile
const value_type reg_clr = reg & mask_clear;
reg = reg_clr | value_type(value_type(value) * mask_bit);
}
// Template polymorphism generator
// If the variable is const, do not write to it
template <auto & reg, auto offset>
static constexpr void default_write_static(const bool)
requires is_const<decltype(reg)> { }
// Template polymorphism generator
// Reads the value of a compile-time known variable
template <auto & reg, auto offset>
static constexpr bool default_read_static() {
using reg_type = std::remove_reference<decltype(reg)>::type;
using value_type = std::remove_volatile<reg_type>::type;
// Bit mask to select the bit
constexpr value_type mask_bit = value_type(1) << offset;
return (reg & mask_bit) != value_type(0);
}
// Template polymorphism generator
// Writes the value to a variable in a compile-time known pointer
template <auto * & reg_ptr, auto offset>
static constexpr void default_write_dynamic(const bool value)
requires is_not_const<decltype(reg_ptr)> {
using ptr_type = std::remove_reference<decltype(reg_ptr)>::type;
using reg_type = std::remove_pointer<ptr_type>::type;
using value_type = std::remove_volatile<reg_type>::type;
// Bit masks to select/clear the bit
constexpr value_type mask_bit = value_type(1) << offset;
constexpr value_type mask_clear = ~mask_bit;
// The clear result is stored in a temporary
// to prevent unnecessary writes/reads to reg
// when reg is volatile
const value_type reg_clr = *reg_ptr & mask_clear;
*reg_ptr = reg_clr | value_type(value_type(value) * mask_bit);
}
template <auto & reg, auto offset>
static constexpr void default_write_dynamic(const bool)
requires is_const<decltype(reg)> { }
// Template polymorphism generator
// Reads the value of a variable in a compile-time known pointer
template <auto * & reg_ptr, auto offset>
static constexpr bool default_read_dynamic() {
using ptr_type = std::remove_reference<decltype(reg_ptr)>::type;
using reg_type = std::remove_pointer<ptr_type>::type;
using value_type = std::remove_volatile<reg_type>::type;
// Bit mask to select the bit
constexpr value_type mask_bit = value_type(1) << offset;
return (*reg_ptr & mask_bit) != value_type(0);
}
private:
// The function pointers
func_write_type func_write_;
func_read_type func_read_;
};
// Creates a bit object to access a compile-time known variable
template <auto & reg, auto offset>
bits::bit make_bit(
bit::func_write_type func_write = &bit::default_write_static<reg, offset>,
bit::func_read_type func_read = &bit::default_read_static<reg, offset>
) requires is_not_pointer<decltype(reg)> {
return bits::bit(func_write, func_read);
}
// Creates a bit object to access a variable in a compile-time known pointer
template <auto * & reg_ptr, auto offset>
bits::bit make_bit(
bit::func_write_type func_write = &bit::default_write_dynamic<reg_ptr, offset>,
bit::func_read_type func_read = &bit::default_read_dynamic<reg_ptr, offset>
) {
return bits::bit(func_write, func_read);
}
} // namespace bits
#endif // BIT_HPP
| 32.741935 | 117 | 0.666854 | YagoMello |
882c699df89729f87108858b2ed7f0db4c1a6597 | 3,098 | hpp | C++ | include/ghost/connection/Reader.hpp | mathieunassar/ghostmodule | 8e9a9e958ec3cfa3494b49211920e3f669a9c8bd | [
"Apache-2.0"
] | 2 | 2019-10-05T06:51:49.000Z | 2020-10-11T11:20:59.000Z | include/ghost/connection/Reader.hpp | mathieunassar/ghostmodule | 8e9a9e958ec3cfa3494b49211920e3f669a9c8bd | [
"Apache-2.0"
] | 24 | 2019-06-19T21:33:23.000Z | 2020-10-04T11:36:41.000Z | include/ghost/connection/Reader.hpp | mathieunassar/ghostmodule | 8e9a9e958ec3cfa3494b49211920e3f669a9c8bd | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Mathieu Nassar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GHOST_READER_HPP
#define GHOST_READER_HPP
#include <ghost/connection/ReaderSink.hpp>
#include <memory>
namespace ghost
{
/**
* @brief Interface for reading through a connection.
*
* Reader objects are obtained from connection objects.
*
* The type of message being read by the Reader is provided
* by the template parameter "MessageType", which can be one of
* the following:
* - a Google Protobuf message type (including google.protobuf.Any)
* - A user-defined object type derived from the Message class.
*
* @tparam MessageType the type of messages that will be read
* by the Reader.
*/
template <typename MessageType>
class Reader
{
public:
virtual ~Reader() = default;
/**
* Creates a ghost::Reader bound to the provided connection.
* @return a ghost::Reader object that can read from the provided connection.
*/
static std::shared_ptr<ghost::Reader<MessageType>> create(const std::shared_ptr<ghost::ReaderSink>& sink,
bool blocking);
/**
* @brief Reads a message from the reader.
*
* If a message handler was added to the connection bound to this reader,
* then calling read will always return false.
* Read will also return false if the connection was set to not block during
* I/O calls.
* Finally, the method will return false if the incoming message does not match
* the expected type MessageType.
* In all the other cases, this method returns true.
*
* @param message the message to read (input)
* @return true if a message of the given type was actually read
* @return false if no message was read during this call.
*/
virtual bool read(MessageType& message) = 0;
/**
* @brief Gets the last read message.
*
* @param message the message to read (input)
* @return true if a message of the given type was actually read
* @return false if no message could be returned
*/
virtual bool lastRead(MessageType& message) = 0;
};
template <>
std::shared_ptr<ghost::Reader<google::protobuf::Any>> ghost::Reader<google::protobuf::Any>::create(
const std::shared_ptr<ghost::ReaderSink>& sink, bool blocking);
} // namespace ghost
#include <ghost/connection/internal/GenericReader.hpp>
// Template definition //
template <typename MessageType>
std::shared_ptr<ghost::Reader<MessageType>> ghost::Reader<MessageType>::create(
const std::shared_ptr<ghost::ReaderSink>& sink, bool blocking)
{
return std::make_shared<ghost::internal::GenericReader<MessageType>>(sink, blocking);
}
#endif // GHOST_WRITER_HPP
| 32.610526 | 106 | 0.732085 | mathieunassar |
8830fb955023a846e2bba1fe3f46edf3e85ebf78 | 1,796 | hpp | C++ | src/cc/Books/ElementsOfProgrammingInterviews/reference/ch16.hpp | nuggetwheat/study | 1e438a995c3c6ce783af9ae6a537c349afeedbb8 | [
"MIT"
] | null | null | null | src/cc/Books/ElementsOfProgrammingInterviews/reference/ch16.hpp | nuggetwheat/study | 1e438a995c3c6ce783af9ae6a537c349afeedbb8 | [
"MIT"
] | null | null | null | src/cc/Books/ElementsOfProgrammingInterviews/reference/ch16.hpp | nuggetwheat/study | 1e438a995c3c6ce783af9ae6a537c349afeedbb8 | [
"MIT"
] | null | null | null |
#ifndef Books_ElementsOfProgrammingInterviews_reference_ch16_hpp
#define Books_ElementsOfProgrammingInterviews_reference_ch16_hpp
#include "Common/Tree.hpp"
#include <array>
#include <cstdlib>
#include <memory>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
namespace reference {
extern void MoveTowerOfHanoi(std::vector<std::stack<int>> &pegs, int to_peg);
extern void MoveTowerOfHanoiIterative(std::vector<std::stack<int>> &pegs, int to_peg);
extern std::vector<std::vector<int>> NQueens(int n);
extern std::vector<std::vector<int>> NQueensIterative(int n);
extern std::vector<std::vector<int>> Permutations(std::vector<int> A);
extern std::vector<std::vector<int>> PermutationsIterative(std::vector<int> A);
extern std::vector<std::vector<int>> GeneratePowerSet(const std::vector<int> &input);
extern std::vector<std::vector<int>> GeneratePowerSetIterative(const std::vector<int> &input);
extern std::vector<std::vector<int>> Combinations(int n, int k);
extern std::vector<std::vector<int>> CombinationsIterative(int n, int k);
extern std::vector<std::string> GenerateBalancedParenthesis(int num_pairs);
extern std::vector<std::string> GenerateBalancedParenthesisIterative(int num_pairs);
extern std::vector<std::vector<std::string>> PalindromePartitioning(const std::string &input);
extern std::vector<std::unique_ptr<study::BSTNode<int>>> GenerateAllBinaryTrees(int num_nodes);
extern bool SolveSudoku(std::vector<std::vector<int>> *partial_assignment);
extern std::vector<int> GrayCode(int num_bits);
extern std::vector<int> GrayCodeIterative(int num_bits);
extern int ComputeDiameter(const std::unique_ptr<study::BSTNode<int>> &tree);
}
#endif // Books_ElementsOfProgrammingInterviews_reference_ch16_hpp
| 32.071429 | 97 | 0.763363 | nuggetwheat |
883143a10ab0b7c390135c75b87f00ae8742b0ce | 1,504 | cpp | C++ | src/Zelta/Concurrency/Worker.cpp | RafaelGC/ese | 95868d2f7221334271d4a74ef38b2ed3478a8b91 | [
"MIT"
] | 1 | 2018-01-28T21:35:14.000Z | 2018-01-28T21:35:14.000Z | src/Zelta/Concurrency/Worker.cpp | RafaelGC/ese | 95868d2f7221334271d4a74ef38b2ed3478a8b91 | [
"MIT"
] | 1 | 2017-04-05T00:41:53.000Z | 2017-04-05T00:41:53.000Z | src/Zelta/Concurrency/Worker.cpp | rafaelgc/ESE | 95868d2f7221334271d4a74ef38b2ed3478a8b91 | [
"MIT"
] | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Worker.cpp
* Author: rafa
*
* Created on January 14, 2018, 3:42 PM
*/
#include <thread>
#include <Zelta/Concurrency/Worker.hpp>
#include <Zelta/Concurrency/Task.hpp>
namespace zt {
Worker::Worker(std::condition_variable& poolCv) : uniqueLock(mtx) {
task = nullptr;
this->poolCv = &poolCv;
thread = std::thread(&Worker::work, this);
stopped = false;
}
Worker::~Worker() {
}
bool Worker::setTask(Task& task) {
if (isFree()) {
this->task = &task;
cv.notify_all();
return true;
}
return false;
}
bool Worker::isFree() const {
return !task;
}
void Worker::work() {
while (!stopped) {
if (!isFree()) {
if (this->task->work()) {
task = nullptr;
// When the task is done (it returns true) we notify
// the pool so that it knows there is a free worker.
if (poolCv) {
poolCv->notify_all();
cv.wait(uniqueLock);
}
}
}
}
}
void Worker::join() {
thread.join();
}
void Worker::stop() {
stopped = true;
}
} | 20.888889 | 79 | 0.490691 | RafaelGC |
88337aa39dc78f9e6d0ab600afd2499272c41cf2 | 1,265 | cpp | C++ | benchmarks/Matmul/matmul_cpp.cpp | Cwc-Lib/Cello | 139e04c3b2cc2c6a68f96637e0c53286ca5792c0 | [
"BSD-2-Clause-FreeBSD"
] | 4,067 | 2015-05-16T22:57:52.000Z | 2022-03-30T05:40:04.000Z | benchmarks/Matmul/matmul_cpp.cpp | Cwc-Lib/Cello | 139e04c3b2cc2c6a68f96637e0c53286ca5792c0 | [
"BSD-2-Clause-FreeBSD"
] | 59 | 2015-06-17T09:51:27.000Z | 2021-09-24T20:15:21.000Z | benchmarks/Matmul/matmul_cpp.cpp | Cwc-Lib/Cello | 139e04c3b2cc2c6a68f96637e0c53286ca5792c0 | [
"BSD-2-Clause-FreeBSD"
] | 308 | 2015-05-16T11:33:08.000Z | 2022-03-18T00:26:28.000Z | #include <stdlib.h>
class Matrix {
public:
size_t n;
double** d;
Matrix(int n);
~Matrix();
};
Matrix::Matrix(int n) {
n = n;
d = (double**)malloc(n * sizeof(double*));
for (int i = 0; i < n; ++i) {
d[i] = (double*)calloc(n, sizeof(double));
}
}
Matrix::~Matrix() {
for (int i = 0; i < n; ++i) free(d[i]);
free(d);
}
static Matrix* Matrix_Gen(int n) {
Matrix* m = new Matrix(n);
double tmp = 1.0 / n / n;
for (int i = 0; i < m->n; ++i) {
for (int j = 0; j < m->n; ++j) {
m->d[i][j] = tmp * (i - j) * (i + j);
}
}
return m;
}
static Matrix* Matrix_Mul(Matrix* m0, Matrix* m1) {
Matrix* a = m0;
Matrix* b = m1;
Matrix* m = new Matrix(a->n);
Matrix* c = new Matrix(a->n);
for (int i = 0; i < m->n; ++i) {
for (int j = 0; j < m->n; ++j) {
c->d[i][j] = b->d[j][i];
}
}
for (int i = 0; i < m->n; ++i) {
double *p = a->d[i], *q = m->d[i];
for (int j = 0; j < m->n; ++j) {
double t = 0.0, *r = c->d[j];
for (int k = 0; k < m->n; ++k) {
t += p[k] * r[k];
}
q[j] = t;
}
}
delete c;
return m;
}
int main(int argc, char *argv[]) {
int n = 300;
n = (n/2) * 2;
Matrix* a = Matrix_Gen(n);
Matrix* b = Matrix_Gen(n);
Matrix* m = Matrix_Mul(a, b);
delete a; delete b; delete m;
return 0;
}
| 17.569444 | 51 | 0.474308 | Cwc-Lib |
883bbec44358e50add87f47786eea94f72a5f192 | 4,353 | hh | C++ | hackt_docker/hackt/src/sim/prsim/Cause.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/sim/prsim/Cause.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/sim/prsim/Cause.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | /**
\file "sim/prsim/Cause.hh"
Structure of basic node event.
$Id: Cause.hh,v 1.5 2009/02/01 07:21:35 fang Exp $
*/
#ifndef __HAC_SIM_PRSIM_CAUSE_H__
#define __HAC_SIM_PRSIM_CAUSE_H__
#include <iosfwd>
#include "sim/common.hh"
#include "sim/prsim/enums.hh"
#include "util/utypes.h"
#include "sim/prsim/devel_switches.hh" // for PRSIM_TRACK_CAUSE_TIME
#if PRSIM_TRACK_CAUSE_TIME || PRSIM_TRACK_LAST_EDGE_TIME
#include "sim/time.hh"
#endif
namespace HAC {
namespace SIM {
namespace PRSIM {
using std::ostream;
using std::istream;
#if PRSIM_TRACK_CAUSE_TIME || PRSIM_TRACK_LAST_EDGE_TIME
typedef real_time event_time_type;
#endif
//=============================================================================
/**
(node, value) pair representing a past event.
With a time stamp, does this struct become large enough to
warrant using pointers to Cause objects?
Said Cause objects would need to expire over time,
perhaps via reference count...
*/
struct EventCause {
node_index_type node;
value_enum val;
#if PRSIM_TRACK_CAUSE_TIME
event_time_type time;
#endif
EventCause() : node(INVALID_NODE_INDEX), val(LOGIC_LOW)
#if PRSIM_TRACK_CAUSE_TIME
, time(-1.0)
#endif
{ }
// initial value doesn't matter, could be LOGIC_OTHER
#if PRSIM_TRACK_CAUSE_TIME
EventCause(const node_index_type n, const value_enum v,
const event_time_type& t) :
node(n), val(v), time(t) { }
#else
EventCause(const node_index_type n, const value_enum v) :
node(n), val(v) { }
#endif
/**
For set-ordering relation.
*/
bool
operator < (const EventCause& e) const {
// really, shouldn't be inserting events with same id,val...
return (node < e.node) ||
((node == e.node) && (
(val < e.val)
#if 0 && PRSIM_TRACK_CAUSE_TIME
|| ((val == e.val) && (time < e.time))
#endif
));
}
ostream&
dump_raw(ostream&) const;
void
save_state(ostream&) const;
void
load_state(istream&);
}; // end struct EventCause
//-----------------------------------------------------------------------------
/**
Structure for tracking event causality in greater detail.
Members kept in separate arrays for better alignment.
Note: don't want to trace critical trace index here, costs memory.
*/
struct LastCause {
typedef EventCause event_cause_type;
/**
The causing node.
Indexed by node's current value.
*/
node_index_type caused_by_node[3];
/**
The value of the causing node.
3 of 4 slots used for better padding.
Indexed by node's current value.
*/
value_enum caused_by_value[4];
#if PRSIM_TRACK_CAUSE_TIME
event_time_type cause_time[3];
#endif
void
initialize(void) {
// caused_by_node({0}),
// caused_by_value({0})
// caused_by_node = {0};
// caused_by_value = {0};
// *this = {{0,0,0}, {0,0,0}};
caused_by_node[0] = INVALID_NODE_INDEX;
caused_by_node[1] = INVALID_NODE_INDEX;
caused_by_node[2] = INVALID_NODE_INDEX;
caused_by_value[0] = LOGIC_LOW; // don't care
caused_by_value[1] = LOGIC_LOW; // don't care
caused_by_value[2] = LOGIC_LOW; // don't care
caused_by_value[3] = LOGIC_LOW; // really don't care
// but needs to be initialized else binary will be
// non-deterministic
#if PRSIM_TRACK_CAUSE_TIME
cause_time[0] = cause_time[1] = cause_time[2] = -1.0;
#endif
}
/**
How the f-- do you initialize aggregate members?
*/
LastCause() {
initialize();
}
/**
\param the value with which to lookup the last cause.
\return the index of the last node to cause this change.
*/
node_index_type
get_cause_node(const value_enum v) const {
return caused_by_node[size_t(v)];
}
event_cause_type
get_cause(const value_enum v) const {
const size_t i(v);
return event_cause_type(caused_by_node[i], caused_by_value[i]
#if PRSIM_TRACK_CAUSE_TIME
, cause_time[i]
#endif
);
}
void
set_cause(const value_enum v, const event_cause_type& e) {
const size_t i(v);
caused_by_node[i] = e.node;
caused_by_value[i] = e.val;
#if PRSIM_TRACK_CAUSE_TIME
cause_time[i] = e.time;
#endif
}
void
save_state(ostream&) const;
void
load_state(istream&);
ostream&
dump_checkpoint_state(ostream&) const;
}; // end struct LastCause
//=============================================================================
} // end namespace PRSIM
} // end namespace SIM
} // end namespace HAC
#endif // __HAC_SIM_PRSIM_CAUSE_H__
| 23.657609 | 79 | 0.666667 | broken-wheel |
883e5f28b3e8dd39ce48699669e91cddc117a46a | 1,547 | hpp | C++ | include/gogh/disassembler.hpp | braedinski/gogh | 28f5be6b075fc549dd9d8d6fb1708176b1892c03 | [
"MIT"
] | null | null | null | include/gogh/disassembler.hpp | braedinski/gogh | 28f5be6b075fc549dd9d8d6fb1708176b1892c03 | [
"MIT"
] | null | null | null | include/gogh/disassembler.hpp | braedinski/gogh | 28f5be6b075fc549dd9d8d6fb1708176b1892c03 | [
"MIT"
] | null | null | null | /*
* gogh::disassembler
*
* The class is just a wrapper for capstone disassembler.
* `gogh` will use its own instruction decoder/disassembler.
*
*/
#include <capstone/capstone.h>
namespace gogh {
class disassembler {
public:
disassembler() {
if (cs_open(
CS_ARCH_MIPS,
(cs_mode)(CS_MODE_MIPS32 + CS_MODE_BIG_ENDIAN),
&_handle) != CS_ERR_OK) {
}
}
~disassembler() {
if (_handle) {
cs_close(&_handle);
}
}
bool disassemble(const uint8_t *code, const size_t length) {
std::size_t count = cs_disasm(
_handle,
code,
length,
0x1000,
0,
&_instruction
);
if (count > 0) {
for (std::size_t j = 0; j < count; j++) {
/*
std::cout
<< "0x" << std::hex << _instruction[j].address << ' '
<< _instruction[j].mnemonic << ' '
<< _instruction[j].op_str << '\n';
*/
}
cs_free(_instruction, count);
}
return true;
}
protected:
cs_insn *_instruction;
csh _handle;
};
} | 26.672414 | 81 | 0.372334 | braedinski |
883f7d3ccf35c53eb89b1db830f34c5e76883615 | 5,220 | cpp | C++ | tests/CoreTests/RandomOuts.cpp | JacopoDT/numerare-core | a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f | [
"MIT-0"
] | null | null | null | tests/CoreTests/RandomOuts.cpp | JacopoDT/numerare-core | a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f | [
"MIT-0"
] | null | null | null | tests/CoreTests/RandomOuts.cpp | JacopoDT/numerare-core | a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f | [
"MIT-0"
] | null | null | null | /***
MIT License
Copyright (c) 2018 NUMERARE
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.
Parts of this file are originally Copyright (c) 2012-2017 The CryptoNote developers, The Bytecoin developers
***/
#include "RandomOuts.h"
#include "TestGenerator.h"
#include "Rpc/CoreRpcServerCommandsDefinitions.h"
GetRandomOutputs::GetRandomOutputs() {
REGISTER_CALLBACK_METHOD(GetRandomOutputs, checkHalfUnlocked);
REGISTER_CALLBACK_METHOD(GetRandomOutputs, checkFullyUnlocked);
}
bool GetRandomOutputs::generate(std::vector<test_event_entry>& events) const {
TestGenerator generator(*m_currency, events);
generator.generateBlocks();
uint64_t sendAmount = MK_COINS(1);
for (int i = 0; i < 10; ++i) {
auto builder =
generator.createTxBuilder(generator.minerAccount, generator.minerAccount, sendAmount, m_currency->minimumFee());
auto tx = builder.build();
generator.addEvent(tx);
generator.makeNextBlock(tx);
}
// unlock half of the money
generator.generateBlocks(m_currency->minedMoneyUnlockWindow() / 2 + 1);
generator.addCallback("checkHalfUnlocked");
// unlock the remaining part
generator.generateBlocks(m_currency->minedMoneyUnlockWindow() / 2);
generator.addCallback("checkFullyUnlocked");
return true;
}
bool GetRandomOutputs::request(CryptoNote::Core& c, uint64_t ramount, size_t mixin,
CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response& resp) {
resp.outs.clear();
CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_request req;
req.amounts.push_back(ramount);
req.outs_count = static_cast<uint16_t>(mixin);
for (auto amount : req.amounts) {
std::vector<uint32_t> globalIndexes;
std::vector<Crypto::PublicKey> publicKeys;
if (!c.getRandomOutputs(amount, static_cast<uint16_t>(req.outs_count), globalIndexes, publicKeys)) {
return false;
}
assert(globalIndexes.size() == publicKeys.size());
resp.outs.emplace_back(CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_outs_for_amount{amount, {}});
for (size_t i = 0; i < globalIndexes.size(); ++i) {
resp.outs.back().outs.push_back({globalIndexes[i], publicKeys[i]});
}
}
return true;
}
#define CHECK(cond) \
if ((cond) == false) { \
LOG_ERROR("Condition " #cond " failed"); \
return false; \
}
bool GetRandomOutputs::checkHalfUnlocked(CryptoNote::Core& c, size_t ev_index,
const std::vector<test_event_entry>& events) {
CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response resp;
auto amount = MK_COINS(1);
auto unlocked = m_currency->minedMoneyUnlockWindow() / 2 + 1;
CHECK(request(c, amount, 0, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == 0);
CHECK(request(c, amount, unlocked, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == unlocked);
CHECK(request(c, amount, unlocked * 2, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == unlocked);
return true;
}
bool GetRandomOutputs::checkFullyUnlocked(CryptoNote::Core& c, size_t ev_index,
const std::vector<test_event_entry>& events) {
CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response resp;
auto amount = MK_COINS(1);
auto unlocked = m_currency->minedMoneyUnlockWindow() + 1;
CHECK(request(c, amount, unlocked, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == unlocked);
CHECK(request(c, amount, unlocked * 2, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == unlocked);
return true;
}
| 37.826087 | 120 | 0.66705 | JacopoDT |
8842930a3f2c988927dcdc7a2bca9a2f05163bc8 | 11,159 | cpp | C++ | src/gpu/ocl/gemm/gen12lp_gemm.cpp | IvanNovoselov/oneDNN | aa47fcd2a03ee5caac119b6417bc66abe3154aab | [
"Apache-2.0"
] | null | null | null | src/gpu/ocl/gemm/gen12lp_gemm.cpp | IvanNovoselov/oneDNN | aa47fcd2a03ee5caac119b6417bc66abe3154aab | [
"Apache-2.0"
] | 1 | 2020-04-17T22:23:01.000Z | 2020-04-23T21:11:41.000Z | src/gpu/ocl/gemm/gen12lp_gemm.cpp | IvanNovoselov/oneDNN | aa47fcd2a03ee5caac119b6417bc66abe3154aab | [
"Apache-2.0"
] | 3 | 2021-07-20T07:40:15.000Z | 2021-08-03T08:39:17.000Z | /*******************************************************************************
* Copyright 2019-2020 Intel Corporation
*
* 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 "gpu/ocl/gemm/gen12lp_gemm.hpp"
#include "common/c_types_map.hpp"
#include "common/dnnl_traits.hpp"
#include "common/type_helpers.hpp"
namespace dnnl {
namespace impl {
namespace gpu {
namespace ocl {
struct gen12lp_gemm_driver_params_t {
static constexpr auto block_m = 2048;
static constexpr auto block_n = 2048;
static constexpr auto block_k = 1024;
};
status_t gen12lp_gemm_t::launch_x8x8s32(gemm_exec_ctx_t ctx,
compute::compute_stream_t *compute_stream, const memory_storage_t &a,
const memory_storage_t &b, const memory_storage_t &c, int offset_a,
int offset_b, int offset_c, int lda, int ldb, int ldc, int m, int n,
int k, int beta, int ao, int bo, const memory_storage_t &co,
int offset_co, bool apply_co, bool apply_eltwise, float eltwise_alpha,
float eltwise_beta, float eltwise_scale, bool aligned) const {
auto &kernel = compute_x8x8s32_kernel_[aligned];
assert(kernel);
int unroll_m, unroll_n, block_m, block_n;
gen12lp_gemm_x8x8s32_kernel_t::get_unrolls(unroll_m, unroll_n);
block_m = gen12lp_gemm_driver_params_t::block_m;
block_n = gen12lp_gemm_driver_params_t::block_n;
int kk = ((k + 3) & ~3);
int sizea = block_m * (kk + sizeof(int));
int sizeb = block_n * (kk + sizeof(int));
compute::kernel_arg_list_t arg_list;
arg_list.set(0, a);
arg_list.set(1, b);
arg_list.set(2, c);
arg_list.set(3, (int)offset_a);
arg_list.set(4, (int)offset_b);
arg_list.set(5, (int)offset_c);
arg_list.set(6, (int)lda);
arg_list.set(7, (int)ldb);
arg_list.set(8, (int)ldc);
arg_list.set(9, (int)m);
arg_list.set(10, (int)n);
arg_list.set(11, (int)k);
arg_list.set(12, (int)beta);
arg_list.set(13, (int)ao);
arg_list.set(14, (int)bo);
arg_list.set(15, co);
arg_list.set(16, (int)offset_co);
arg_list.set(17, (int)apply_co);
arg_list.set(18, sizea, nullptr);
arg_list.set(19, sizeb, nullptr);
arg_list.set(20, (int)apply_eltwise);
arg_list.set(21, eltwise_alpha);
arg_list.set(22, eltwise_beta);
arg_list.set(23, eltwise_scale);
size_t nthreads_x = (m + unroll_m - 1) / unroll_m;
size_t nthreads_y = (n + unroll_n - 1) / unroll_n;
size_t lthreads_x = 2;
size_t lthreads_y = 8;
#ifndef CL_VERSION_2_0
while (nthreads_x % lthreads_x)
lthreads_x--;
while (nthreads_y % lthreads_y)
lthreads_y--;
#endif
static constexpr size_t subgroup_size = 16;
size_t gws[3] = {nthreads_x * subgroup_size, nthreads_y, 1};
size_t lws[3] = {lthreads_x * subgroup_size, lthreads_y, 1};
auto nd_range = compute::nd_range_t(gws, lws);
return parallel_for(ctx, nd_range, kernel, arg_list);
}
status_t gen12lp_gemm_t::launch_scale_x8x8s32(gemm_exec_ctx_t ctx,
compute::compute_stream_t *compute_stream,
const memory_storage_t &c_temp, const memory_storage_t &c, char offsetc,
int offset_c, int m, int n, int ldc, float alpha, float beta,
const memory_storage_t &co, int offset_co, bool alpha_is_zero,
bool apply_eltwise, float eltwise_alpha, float eltwise_beta,
float eltwise_scale) const {
auto &kernel = scale_x8x8s32_kernel_;
assert(kernel);
compute::kernel_arg_list_t arg_list;
arg_list.set(0, c_temp);
arg_list.set(1, c);
arg_list.set(2, (int)offsetc);
arg_list.set(3, (int)offset_c);
arg_list.set(4, (int)m);
arg_list.set(5, (int)n);
arg_list.set(6, (int)ldc);
arg_list.set(7, alpha);
arg_list.set(8, beta);
arg_list.set(9, co);
arg_list.set(10, (int)offset_co);
arg_list.set(11, (int)alpha_is_zero);
arg_list.set(12, (int)apply_eltwise);
arg_list.set(13, eltwise_alpha);
arg_list.set(14, eltwise_beta);
arg_list.set(15, eltwise_scale);
int unroll_m, unroll_n;
gen12lp_gemm_scale_x8x8s32_kernel_t::get_unrolls(unroll_m, unroll_n);
size_t nthreads_x = (m + unroll_m - 1) / unroll_m;
size_t nthreads_y = (n + unroll_n - 1) / unroll_n;
size_t lthreads_x = 16;
size_t lthreads_y = 1;
size_t gws[3] = {nthreads_x * lthreads_x, nthreads_y, 1};
size_t lws[3] = {lthreads_x, lthreads_y, 1};
auto nd_range = compute::nd_range_t(gws, lws);
return parallel_for(ctx, nd_range, kernel, arg_list);
}
status_t gen12lp_gemm_t::execute(const gemm_exec_ctx_t &ctx) const {
return execute_standard(ctx);
}
status_t gen12lp_gemm_t::execute_standard(const gemm_exec_ctx_t &ctx) const {
auto a_type = pd()->desc()->a_type;
auto b_type = pd()->desc()->b_type;
auto c_type = pd()->desc()->c_type;
auto *compute_stream
= utils::downcast<compute::compute_stream_t *>(ctx.stream());
auto m = pd()->desc()->m;
auto n = pd()->desc()->n;
auto k = pd()->desc()->k;
bool transa = (pd()->desc()->transa == dnnl_trans);
bool transb = (pd()->desc()->transb == dnnl_trans);
int cmask = 0;
pd()->attr()->zero_points_.get(DNNL_ARG_DST, nullptr, &cmask, nullptr);
char offsetc_char;
if (1 << 1 == cmask)
offsetc_char = 'C';
else if (1 << 0 == cmask)
offsetc_char = 'R';
else
offsetc_char = 'F';
auto lda = pd()->desc()->lda;
auto ldb = pd()->desc()->ldb;
auto ldc = pd()->desc()->ldc;
const int *ao_i32 = nullptr;
const int *bo_i32 = nullptr;
pd()->attr()->zero_points_.get(DNNL_ARG_SRC, nullptr, nullptr, &ao_i32);
pd()->attr()->zero_points_.get(DNNL_ARG_WEIGHTS, nullptr, nullptr, &bo_i32);
auto ao = *ao_i32;
auto bo = *bo_i32;
auto alpha = pd()->alpha();
auto beta = pd()->beta();
auto eltwise_alpha = pd()->eltwise_alpha();
auto eltwise_beta = pd()->eltwise_beta();
auto eltwise_scale = pd()->eltwise_scale();
auto &a = GEMM_CTX_ARG_STORAGE(a);
auto &b = GEMM_CTX_ARG_STORAGE(b);
auto &co = GEMM_CTX_ARG_STORAGE(c_zero_point);
auto &c = GEMM_CTX_ARG_STORAGE(c);
auto temp_buf = ctx.get_scratchpad_grantor().get_memory_storage(
memory_tracking::names::key_gemm_tmp_buffer);
int64_t off_a0
= a.offset() / types::data_type_size(a_type) + pd()->dyn_offset_a;
int64_t off_b0
= b.offset() / types::data_type_size(b_type) + pd()->dyn_offset_b;
int64_t off_c0
= c.offset() / types::data_type_size(c_type) + pd()->dyn_offset_c;
int64_t offset_co
= co.offset() / types::data_type_size(c_type) + pd()->dyn_offset_co;
bool do_compute = pd()->do_compute();
bool do_scale = pd()->do_scale();
status_t status;
int unroll_m, unroll_n;
int block_m, block_n, block_k;
gen12lp_gemm_x8x8s32_kernel_t::get_unrolls(unroll_m, unroll_n);
block_m = gen12lp_gemm_driver_params_t::block_m;
block_n = gen12lp_gemm_driver_params_t::block_n;
block_k = gen12lp_gemm_driver_params_t::block_k;
bool apply_co = true;
bool aligned = false;
int64_t size_k, size_m, size_n;
if (do_compute) {
for (int64_t Bk = 0; Bk < k; Bk += size_k) {
size_k = k - Bk;
bool apply_eltwise = (size_k <= block_k);
if (size_k > block_k) size_k = block_k;
for (int64_t Bm = 0; Bm < m; Bm += size_m) {
size_m = m - Bm;
if (size_m > block_m) size_m = block_m;
auto off_a_src = off_a0
+ (!transa ? (Bm + Bk * lda) : (Bk + Bm * lda));
for (int64_t Bn = 0; Bn < n; Bn += size_n) {
size_n = n - Bn;
if (size_n > block_n) size_n = block_n;
auto off_b_src = off_b0
+ (!transb ? (Bk + Bn * ldb) : (Bn + Bk * ldb));
apply_co = !co.is_null() && !(do_scale || (Bk > 0));
auto offset_co_src = offset_co
+ ((offsetc_char == 'C') ? Bm : 0)
+ ((offsetc_char == 'R') ? Bn : 0);
int eff_beta = ((Bk > 0) || (!do_scale && (beta == 1.0f)))
? 1
: 0;
if (!do_scale) {
auto off_c = off_c0 + Bm + Bn * ldc;
if ((lda & 3) || (ldb & 3) || (ldc & 3)
|| (off_a_src & 3) || (off_b_src & 3)
|| (off_c & 3))
aligned = false;
else
aligned = true;
status = launch_x8x8s32(ctx, compute_stream, a, b, c,
off_a_src, off_b_src, off_c, lda, ldb, ldc,
size_m, size_n, size_k, eff_beta, ao, bo, co,
offset_co_src, apply_co, apply_eltwise,
eltwise_alpha, eltwise_beta, eltwise_scale,
aligned);
if (status) return status;
} else if (do_scale) {
auto off_c = 0 + Bm + Bn * m;
if ((lda & 3) || (ldb & 3) || (ldc & 3)
|| (off_a_src & 3) || (off_b_src & 3)
|| (off_c & 3))
aligned = false;
else
aligned = true;
status = launch_x8x8s32(ctx, compute_stream, a, b,
*temp_buf, off_a_src, off_b_src, off_c, lda,
ldb, m, size_m, size_n, size_k, eff_beta, ao,
bo, co, offset_co_src, apply_co, false,
eltwise_alpha, eltwise_beta, eltwise_scale,
aligned);
if (status) return status;
}
}
}
}
}
bool alpha_is_zero = false;
if (do_scale) {
status = launch_scale_x8x8s32(ctx, compute_stream, *temp_buf, c,
offsetc_char, off_c0, m, n, ldc, alpha, beta, co, offset_co,
(int)alpha_is_zero, true, eltwise_alpha, eltwise_beta,
eltwise_scale);
if (status) return status;
}
return status::success;
}
} // namespace ocl
} // namespace gpu
} // namespace impl
} // namespace dnnl
// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
| 36.113269 | 80 | 0.570123 | IvanNovoselov |
8847f3406218db6478b2dd223dca1bda84814406 | 1,718 | hpp | C++ | kernel/memory_map.hpp | mox692/mos | 211b36dade615cfd43d3bb077703b82b638eec10 | [
"Apache-2.0"
] | null | null | null | kernel/memory_map.hpp | mox692/mos | 211b36dade615cfd43d3bb077703b82b638eec10 | [
"Apache-2.0"
] | null | null | null | kernel/memory_map.hpp | mox692/mos | 211b36dade615cfd43d3bb077703b82b638eec10 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <stdint.h>
// 構造体定義はUEFI specificな部分. UEFI規格で定められてる定義を独自に構造体定義とした.
// ref: edk2/MdePkg/Include/Uefi/UefiSpec.h
// ref: p57
struct MemoryMap {
unsigned long long buffer_size;
// memory mapの中身の先頭アドレス.
// 内部的にはEFI_MEMORY_DESCRIPTORの配列になっている(ref:edk2/MdePkg/Include/Uefi/UefiSpec.h)
void* buffer;
// MemoryMap全体のsizeを表す(EFI_MEMORY_DESCRIPTORエントリのサイズではない!)
unsigned long long map_size;
unsigned long long map_key;
// EFI_MEMORY_DESCRIPTORのサイズ.(UEFIがupdateされるにつれ、ここが変動しうる)
unsigned long long descriptor_size;
// EFI_MEMORY_DESCRIPTORのサイズ.(上とも関連し、恐らくupdateされることを見越してこのfieldを入れた?)
uint32_t descriptor_version;
};
// MEMO: EFI_MEMORY_DESCRIPTORの定義を独自構造体として再定義したもの
struct MemoryDescriptor {
uint32_t type;
uintptr_t physical_start;
uintptr_t virtual_start;
uint64_t number_of_pages;
uint64_t attribute;
};
#ifdef __cplusplus
enum class MemoryType {
kEfiReservedMemoryType,
kEfiLoaderCode,
kEfiLoaderData,
kEfiBootServicesCode,
kEfiBootServicesData,
kEfiRuntimeServicesCode,
kEfiRuntimeServicesData,
kEfiConventionalMemory,
kEfiUnusableMemory,
kEfiACPIReclaimMemory,
kEfiACPIMemoryNVS,
kEfiMemoryMappedIO,
kEfiMemoryMappedIOPortSpace,
kEfiPalCode,
kEfiPersistentMemory,
kEfiMaxMemoryType
};
inline bool operator==(uint32_t lhs, MemoryType rhs) {
return lhs == static_cast<uint32_t>(rhs);
}
inline bool operator==(MemoryType lhs, uint32_t rhs) {
return rhs == lhs;
}
inline bool IsAvailable(MemoryType memory_type) {
return
memory_type == MemoryType::kEfiBootServicesCode ||
memory_type == MemoryType::kEfiBootServicesData ||
memory_type == MemoryType::kEfiConventionalMemory;
}
const int kUEFIPageSize = 4096;
#endif
| 25.264706 | 81 | 0.786962 | mox692 |
88491b236a93fd2f6d9cfcd0b3b86a55d38fea6c | 1,016 | cpp | C++ | src/brokerlib/message/payload/src/BrokerRegistryQueryResponsePayload.cpp | chrissmith-mcafee/opendxl-broker | a3f985fc19699ab8fcff726bbd1974290eb6e044 | [
"Apache-2.0",
"MIT"
] | 13 | 2017-10-15T14:32:34.000Z | 2022-02-17T08:25:26.000Z | src/brokerlib/message/payload/src/BrokerRegistryQueryResponsePayload.cpp | vkrish-mcafee/opendxl-broker | 39c5d06c233dbe01146f0db781eccfd67bbaafbf | [
"Apache-2.0",
"MIT"
] | 14 | 2017-10-17T18:23:50.000Z | 2021-12-10T22:05:25.000Z | src/brokerlib/message/payload/src/BrokerRegistryQueryResponsePayload.cpp | vkrish-mcafee/opendxl-broker | 39c5d06c233dbe01146f0db781eccfd67bbaafbf | [
"Apache-2.0",
"MIT"
] | 26 | 2017-10-27T00:27:29.000Z | 2021-09-02T16:57:55.000Z | /******************************************************************************
* Copyright (c) 2018 McAfee, LLC - All Rights Reserved.
*****************************************************************************/
#include "include/BrokerSettings.h"
#include "message/include/DxlMessageConstants.h"
#include "message/payload/include/BrokerStateEventPayload.h"
#include "message/payload/include/BrokerRegistryQueryResponsePayload.h"
using namespace dxl::broker;
using namespace dxl::broker::message;
using namespace dxl::broker::message::payload;
using namespace Json;
/** {@inheritDoc} */
void BrokerRegistryQueryResponsePayload::write( Json::Value& out ) const
{
Value brokers( Json::objectValue );
for( auto it = m_states.begin(); it != m_states.end(); it++ )
{
Value jsonObject( Json::objectValue );
BrokerStateEventPayload( *(*it) ).write( jsonObject );
brokers[ (*it)->getBroker().getId() ] = jsonObject;
}
out[ DxlMessageConstants::PROP_BROKERS ] = brokers;
}
| 37.62963 | 79 | 0.601378 | chrissmith-mcafee |
884bcdf60400ceca8e082489717b4773b8b35acc | 1,059 | cpp | C++ | PaintlLess/Assets/components/Ability_Priest.cpp | rubenglezortiz/Proyectos2-2020-21 | 74b52b8ec4c60717292f8287fa05c00a3748b0d4 | [
"CC0-1.0"
] | null | null | null | PaintlLess/Assets/components/Ability_Priest.cpp | rubenglezortiz/Proyectos2-2020-21 | 74b52b8ec4c60717292f8287fa05c00a3748b0d4 | [
"CC0-1.0"
] | null | null | null | PaintlLess/Assets/components/Ability_Priest.cpp | rubenglezortiz/Proyectos2-2020-21 | 74b52b8ec4c60717292f8287fa05c00a3748b0d4 | [
"CC0-1.0"
] | null | null | null | #include "Ability_Priest.h"
Ability_Priest::Ability_Priest() : AbilityStruct(selectorH, ShaderForm::TxT, ShaderType::nullSh) {}
bool Ability_Priest::AbilityExecute(int x, int y)
{
bool hasCured = false;
GameMap* map = this->getAbility()->getMap();
Entity* entity_ = this->getAbility()->getEntity();
std::vector<Vector2D> abilityCells = this->getAbility()->getCells();
if (abilityCells.empty()) {
this->getAbility()->Shade();
abilityCells = this->getAbility()->getCells();
}
for (int i = 0; i < abilityCells.size(); i++) {
if (map->getCharacter(abilityCells[i]) != nullptr) {
if ((map->getCharacter(abilityCells[i])->hasGroup<Equipo_Azul>() && entity_->hasGroup<Equipo_Azul>()) || (map->getCharacter(abilityCells[i])->hasGroup<Equipo_Rojo>() && entity_->hasGroup<Equipo_Rojo>())) {
map->getCharacter(abilityCells[i])->getComponent<Health>()->healMonaguillo(1);
entity_->getComponent<FramedImage>()->setAnim(A_A_A);
sdlutils().soundEffects().at("monaguilloSound").play();
hasCured = true;
}
}
}
return hasCured;
}
| 39.222222 | 209 | 0.687441 | rubenglezortiz |
884bd6f3ee6572e5aaa93f8e2e7cd4b0c97193b3 | 21,491 | cpp | C++ | 20/jurassic_jigsaw.cpp | ComicSansMS/AdventOfCode2020 | a46b49f5c566cabbea0e61e24f6238e4caf7470c | [
"Unlicense"
] | null | null | null | 20/jurassic_jigsaw.cpp | ComicSansMS/AdventOfCode2020 | a46b49f5c566cabbea0e61e24f6238e4caf7470c | [
"Unlicense"
] | null | null | null | 20/jurassic_jigsaw.cpp | ComicSansMS/AdventOfCode2020 | a46b49f5c566cabbea0e61e24f6238e4caf7470c | [
"Unlicense"
] | null | null | null | #include <jurassic_jigsaw.hpp>
#include <fmt/printf.h>
#include <range/v3/view/cartesian_product.hpp>
#include <range/v3/range/conversion.hpp>
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <charconv>
#include <iterator>
#include <limits>
#include <numeric>
#include <regex>
#include <sstream>
#include <string>
std::vector<RawTile> parseInput(std::string_view input)
{
std::vector<RawTile> ret;
std::stringstream sstr{std::string{input}};
int line_count = 0;
std::string line;
RawTile t;
while (std::getline(sstr, line)) {
if (line_count == 0) {
assert(line.starts_with("Tile "));
assert(line[9] == ':');
t.id = std::stoi(line.substr(5, 4));
} else if (line_count == 11) {
assert(line == "");
ret.push_back(t);
line_count = 0;
continue;
} else {
assert(line.size() == 10);
int start_index = (line_count - 1) * 10;
for (int i = 0; i < 10; ++i) {
assert((line[i] == '.') || (line[i] == '#'));
t.field[start_index + i] = (line[i] == '.') ? 0 : 1;
}
}
++line_count;
}
assert(line_count == 0);
return ret;
}
CompressedTile compressTile(RawTile const& t)
{
CompressedTile ret;
for (int i = 0; i < 10; ++i) { ret.top[9 - i] = t.field[i]; }
for (int i = 0; i < 10; ++i) { ret.bottom[9 - i] = t.field[i + 90]; }
for (int i = 0; i < 10; ++i) { ret.left[9 - i] = t.field[i * 10]; }
for (int i = 0; i < 10; ++i) { ret.right[9 - i] = t.field[(i * 10) + 9]; }
ret.id = t.id;
ret.transform = TransformState::Straight;
return ret;
}
template<std::size_t N>
std::bitset<N> reverse(std::bitset<N> const& b)
{
std::bitset<N> ret;
for(std::size_t i = 0; i < N; ++i) { ret[i] = b[N - i - 1]; }
return ret;
}
bool hasMatchingSide(CompressedTile const& candidate, CompressedTile const& match, std::bitset<10> CompressedTile::* side_to_check)
{
std::bitset<10> const& s = candidate.*side_to_check;
return ((match.top == s) || (reverse(match.top) == s) ||
(match.bottom == s) || (reverse(match.bottom) == s) ||
(match.left == s) || (reverse(match.left) == s) ||
(match.right == s) || (reverse(match.right) == s));
}
SortedTiles findCorners(std::vector<RawTile> const& t)
{
std::vector<CompressedTile> ctiles;
ctiles.reserve(t.size());
std::transform(begin(t), end(t), std::back_inserter(ctiles), compressTile);
auto const check_side = [&ctiles](std::size_t candidate_index, std::bitset<10> CompressedTile::* side_to_check) -> bool {
CompressedTile const& candidate = ctiles[candidate_index];
bool found_match = false;
for (std::size_t ii = 0; ii < ctiles.size(); ++ii) {
if (ii != candidate_index) {
if(hasMatchingSide(candidate, ctiles[ii], side_to_check)) { found_match = true; break; }
}
}
return found_match;
};
SortedTiles ret;
for (std::size_t i = 0; i < t.size(); ++i) {
int unmatched_sides = 0;
if (!check_side(i, &CompressedTile::top)) { ++unmatched_sides; }
if (!check_side(i, &CompressedTile::bottom)) { ++unmatched_sides; }
if (!check_side(i, &CompressedTile::left)) { ++unmatched_sides; }
if (!check_side(i, &CompressedTile::right)) { ++unmatched_sides; }
assert(unmatched_sides < 3);
if (unmatched_sides == 2) {
ret.corner.push_back(t[i]);
} else if(unmatched_sides == 1) {
ret.edge.push_back(t[i]);
} else {
assert(unmatched_sides == 0);
ret.middle.push_back(t[i]);
}
}
return ret;
}
int64_t solve1(std::vector<RawTile> const& t)
{
auto const corners = findCorners(t).corner;
assert(corners.size() == 4);
return std::accumulate(begin(corners), end(corners), int64_t{1},
[](int64_t acc, RawTile const& t) { return acc * t.id; });
}
[[nodiscard]] CompressedTile transformCompressed(CompressedTile ct)
{
auto rot90 = [](CompressedTile const& ct) -> CompressedTile {
CompressedTile ret = ct;
ret.right = ct.top;
ret.bottom = reverse(ct.right);
ret.left = ct.bottom;
ret.top = reverse(ct.left);
return ret;
};
auto flip = [](CompressedTile const& ct) -> CompressedTile {
CompressedTile ret = ct;
ret.right = reverse(ct.right);
ret.bottom = ct.top;
ret.top = ct.bottom;
ret.left = reverse(ct.left);
return ret;
};
switch (ct.transform)
{
default: assert(false);
case TransformState::Straight:
ct.transform = TransformState::Rot90;
return rot90(ct);
case TransformState::Rot90:
ct.transform = TransformState::Rot180;
return rot90(ct);
case TransformState::Rot180:
ct.transform = TransformState::Rot270;
return rot90(ct);
case TransformState::Rot270:
ct.transform = TransformState::Flip;
return flip(rot90(ct));
case TransformState::Flip:
ct.transform = TransformState::Flip90;
return rot90(ct);
case TransformState::Flip90:
ct.transform = TransformState::Flip180;
return rot90(ct);
case TransformState::Flip180:
ct.transform = TransformState::Flip270;
return rot90(ct);
case TransformState::Flip270:
ct.transform = TransformState::Straight;
return flip(rot90(ct));
}
}
[[nodiscard]] RawTile rot90(RawTile const& t)
{
RawTile ret;
ret.id = t.id;
for (int j = 0; j < 10; ++j) {
for (int i = 0; i < 10; ++i) {
ret.field[i*10 + j] = t.field[(10 - j - 1)*10 + i];
}
}
return ret;
}
[[nodiscard]] RawTile flip(RawTile const& t)
{
RawTile ret;
ret.id = t.id;
for (int j = 0; j < 10; ++j) {
for (int i = 0; i < 10; ++i) {
ret.field[i*10 + j] = t.field[(10 - i - 1)*10 + j];
}
}
return ret;
}
[[nodiscard]] RawTile transformTo(RawTile const& t, TransformState target_state)
{
switch (target_state)
{
default: assert(false);
case TransformState::Straight:
return t;
case TransformState::Rot90:
return rot90(t);
case TransformState::Rot180:
return rot90(rot90(t));
case TransformState::Rot270:
return rot90(rot90(rot90(t)));
case TransformState::Flip:
return flip(t);
case TransformState::Flip90:
return rot90(flip(t));
break;
case TransformState::Flip180:
return rot90(rot90(flip(t)));
break;
case TransformState::Flip270:
return flip(rot90(t));
break;
}
}
bool hasAnyMatch(CompressedTile const& source_tile, std::vector<CompressedTile> const& haystack, std::bitset<10> CompressedTile::* source_edge)
{
return std::any_of(begin(haystack), end(haystack),
[&source_tile, source_edge](CompressedTile const& m) { return (&m != &source_tile) && hasMatchingSide(source_tile, m, source_edge); });
}
std::vector<std::vector<CompressedTile>::iterator> findMatchesFor(CompressedTile const& source_tile, std::vector<CompressedTile>& haystack, std::bitset<10> CompressedTile::* source_edge)
{
std::vector<std::vector<CompressedTile>::iterator> ret;
for (auto it = haystack.begin(), it_end = haystack.end(); it != it_end; ++it) {
if (hasMatchingSide(source_tile, *it, source_edge)) {
ret.push_back(it);
}
}
return ret;
}
std::vector<RawTile> solvePuzzle(SortedTiles const& sorted_tiles)
{
assert(sorted_tiles.corner.size() == 4);
assert(sorted_tiles.edge.size() % 4 == 0);
int const dimension = static_cast<int>(sorted_tiles.edge.size() / 4) + 2;
assert(sorted_tiles.middle.size() == (dimension - 2) * (dimension - 2));
std::vector<CompressedTile> corner;
std::transform(begin(sorted_tiles.corner), end(sorted_tiles.corner), std::back_inserter(corner), compressTile);
std::vector<CompressedTile> edge;
std::transform(begin(sorted_tiles.edge), end(sorted_tiles.edge), std::back_inserter(edge), compressTile);
std::vector<CompressedTile> middle;
std::transform(begin(sorted_tiles.middle), end(sorted_tiles.middle), std::back_inserter(middle), compressTile);
std::vector<CompressedTile> solution;
solution.reserve(dimension * dimension);
// orient first corner correctly
solution.push_back(corner.back());
corner.pop_back();
CompressedTile& corner_ul = solution.front();
while (!(hasAnyMatch(corner_ul, edge, &CompressedTile::right) &&
hasAnyMatch(corner_ul, edge, &CompressedTile::bottom)))
{
corner_ul = transformCompressed(corner_ul);
}
// solve top edge
for (int i = 0; i < dimension - 2; ++i) {
CompressedTile const& left_neighbour = solution.back();
auto matches = findMatchesFor(left_neighbour, edge, &CompressedTile::right);
assert(matches.size() == 1);
auto it_next = matches.back();
assert(it_next != end(edge));
CompressedTile edge_piece = *it_next;
edge.erase(it_next);
// find correct orientation
while (! ((left_neighbour.right == edge_piece.left) &&
(hasAnyMatch(edge_piece, (i == (dimension - 3) ? corner : edge), &CompressedTile::right)) &&
(hasAnyMatch(edge_piece, middle, &CompressedTile::bottom))) )
{
edge_piece = transformCompressed(edge_piece);
assert(edge_piece.transform != TransformState::Straight);
}
solution.push_back(edge_piece);
}
// solve top-left corner
{
CompressedTile const& left_neighbour = solution.back();
auto matches = findMatchesFor(left_neighbour, corner, &CompressedTile::right);
assert(matches.size() == 1);
auto it_next = matches.back();
CompressedTile next_piece = *it_next;
corner.erase(it_next);
// find correct orientation
while (! ((left_neighbour.right == next_piece.left) &&
(hasAnyMatch(next_piece, edge, &CompressedTile::bottom))) )
{
next_piece = transformCompressed(next_piece);
assert(next_piece.transform != TransformState::Straight);
}
solution.push_back(next_piece);
}
// solve center pieces
for (int i_row = 0; i_row < dimension - 2; ++i_row) {
// left edge
{
CompressedTile const& top_neighbour = solution[i_row * dimension];
auto matches = findMatchesFor(top_neighbour, edge, &CompressedTile::bottom);
assert(matches.size() == 1);
auto it_next = matches.back();
CompressedTile next_piece = *it_next;
edge.erase(it_next);
// find correct orientation
while (! ((top_neighbour.bottom == next_piece.top) &&
(hasAnyMatch(next_piece, middle, &CompressedTile::right))) )
{
next_piece = transformCompressed(next_piece);
assert(next_piece.transform != TransformState::Straight);
}
solution.push_back(next_piece);
}
// middle
for (int i_col = 0; i_col < dimension - 2; ++i_col) {
CompressedTile const& top_neighbour = solution[(i_row * dimension) + i_col + 1];
CompressedTile const& left_neighbour = solution.back();
auto matches = findMatchesFor(top_neighbour, middle, &CompressedTile::bottom);
assert(matches.size() == 1);
auto it_next = matches.back();
CompressedTile next_piece = *it_next;
middle.erase(it_next);
// find correct orientation
while (! ((top_neighbour.bottom == next_piece.top) &&
(left_neighbour.right == next_piece.left) &&
(hasAnyMatch(next_piece, ((i_col == dimension - 3) ? edge : middle), &CompressedTile::right))) )
{
next_piece = transformCompressed(next_piece);
assert(next_piece.transform != TransformState::Straight);
}
solution.push_back(next_piece);
}
// right edge
{
CompressedTile const& top_neighbour = solution[(i_row + 1) * dimension - 1];
CompressedTile const& left_neighbour = solution.back();
auto matches = findMatchesFor(top_neighbour, edge, &CompressedTile::bottom);
assert(matches.size() == 1);
auto it_next = matches.back();
CompressedTile next_piece = *it_next;
edge.erase(it_next);
// find correct orientation
while (! ((top_neighbour.bottom == next_piece.top) &&
(left_neighbour.right == next_piece.left)) )
{
next_piece = transformCompressed(next_piece);
assert(next_piece.transform != TransformState::Straight);
}
solution.push_back(next_piece);
}
}
assert(middle.empty());
// solve bottom-left corner
{
CompressedTile const& top_neighbour = solution[(dimension - 2) * dimension];
auto matches = findMatchesFor(top_neighbour, corner, &CompressedTile::bottom);
assert(matches.size() == 1);
auto it_next = matches.back();
CompressedTile next_piece = *it_next;
corner.erase(it_next);
// find correct orientation
while (! ((top_neighbour.bottom == next_piece.top) &&
(hasAnyMatch(next_piece, edge, &CompressedTile::right))) )
{
next_piece = transformCompressed(next_piece);
assert(next_piece.transform != TransformState::Straight);
}
solution.push_back(next_piece);
}
// solve bottom edge
for (int i = 0; i < dimension - 2; ++i) {
CompressedTile const& top_neighbour = solution[(dimension - 2) * dimension + i + 1];
CompressedTile const& left_neighbour = solution.back();
auto matches = findMatchesFor(left_neighbour, edge, &CompressedTile::right);
assert(matches.size() == 1);
auto it_next = matches.back();
assert(it_next != end(edge));
CompressedTile edge_piece = *it_next;
edge.erase(it_next);
// find correct orientation
while (! ((left_neighbour.right == edge_piece.left) &&
(top_neighbour.bottom == edge_piece.top) &&
(hasAnyMatch(edge_piece, (i == (dimension - 3) ? corner : edge), &CompressedTile::right))) )
{
edge_piece = transformCompressed(edge_piece);
assert(edge_piece.transform != TransformState::Straight);
}
solution.push_back(edge_piece);
}
assert(edge.empty());
// place final corner
{
assert(corner.size() == 1);
CompressedTile final_corner = corner.back();
corner.pop_back();
CompressedTile const& top_neighbour = solution[(dimension - 1) * dimension - 1];
CompressedTile const& left_neighbour = solution.back();
// find correct orientation
while (! ((left_neighbour.right == final_corner.left) &&
(top_neighbour.bottom == final_corner.top)) )
{
final_corner = transformCompressed(final_corner);
assert(final_corner.transform != TransformState::Straight);
}
solution.push_back(final_corner);
}
assert(corner.empty());
// assemble raw tile solution
std::vector<RawTile> all_tiles;
all_tiles.reserve(dimension * dimension);
all_tiles = sorted_tiles.corner;
all_tiles.insert(end(all_tiles), begin(sorted_tiles.edge), end(sorted_tiles.edge));
all_tiles.insert(end(all_tiles), begin(sorted_tiles.middle), end(sorted_tiles.middle));
std::vector<RawTile> ret;
ret.reserve(dimension * dimension);
for (auto const& cs : solution) {
auto it = std::find_if(begin(all_tiles), end(all_tiles), [id = cs.id](auto const& t) { return t.id == id; });
assert(it != end(all_tiles));
ret.push_back(transformTo(*it, cs.transform));
}
return ret;
}
std::vector<RawTile> transformSolution(std::vector<RawTile> const& in, TransformState target_state)
{
int const dimension = static_cast<int>(std::sqrt(in.size()));
assert(dimension * dimension == in.size());
auto const rot90 = [dimension](std::vector<RawTile> const& in) {
std::vector<RawTile> ret;
ret.resize(dimension * dimension);
for (int iy = 0; iy < dimension; ++iy) {
for (int ix = 0; ix < dimension; ++ix) {
ret[ix*dimension + iy] = transformTo(in[(dimension - iy - 1)*dimension + ix], TransformState::Rot90);
}
}
return ret;
};
auto const flip = [dimension](std::vector<RawTile> const& in) {
std::vector<RawTile> ret;
ret.resize(dimension * dimension);
for (int iy = 0; iy < dimension; ++iy) {
for (int ix = 0; ix < dimension; ++ix) {
ret[ix*dimension + iy] = transformTo(in[(dimension - ix - 1)*dimension + iy], TransformState::Flip);
}
}
return ret;
};
switch (target_state)
{
case TransformState::Rot90:
return rot90(in);
case TransformState::Rot180:
return rot90(rot90(in));
case TransformState::Rot270:
return rot90(rot90(rot90(in)));
case TransformState::Flip:
return flip(in);
case TransformState::Flip90:
return rot90(flip(in));
case TransformState::Flip180:
return rot90(rot90(flip(in)));
case TransformState::Flip270:
return rot90(rot90(rot90(flip(in))));
case TransformState::Straight:
break;
}
return in;
}
GaplessField makeGapless(std::vector<RawTile> const& tiles)
{
int const dimension = static_cast<int>(std::sqrt(tiles.size()));
assert(dimension * dimension == tiles.size());
GaplessField ret;
ret.dimension = dimension * 8;
ret.field.resize(ret.dimension * ret.dimension);
for (int ity = 0; ity < dimension; ++ity) {
for (int itx = 0; itx < dimension; ++itx) {
RawTile const& t = tiles[ity * dimension + itx];
for (int iy = 1; iy < 9; ++iy) {
int const target_y = (ity * 8) + iy - 1;
for (int ix = 1; ix < 9; ++ix) {
int const target_x = (itx * 8) + ix - 1;
ret.field[target_y * ret.dimension + target_x] = t.field[iy * 10 + ix];
}
}
}
}
return ret;
}
Pattern getDragonPattern()
{
char const pattern[] = " # \n"
"# ## ## ###\n"
" # # # # # # \n";
Pattern p;
p.height = 3;
p.width = 20;
p.data.reserve(p.width * p.height);
for (auto const c : pattern) {
if ((c == '\n') || (c == '\0')) {
assert(p.data.size() % p.width == 0);
} else {
p.data.push_back((c == '#') ? 1 : 0);
}
}
assert(p.data.size() == p.width * p.height);
return p;
}
std::vector<Vec2> findInField(std::vector<RawTile> const& field, Pattern const& p)
{
TransformState const transforms[] = { TransformState::Straight, TransformState::Rot90, TransformState::Rot180,
TransformState::Rot270, TransformState::Flip, TransformState::Flip90,
TransformState::Flip180, TransformState::Flip270 };
for (auto const transform : transforms) {
GaplessField gf = makeGapless(transformSolution(field, transform));
std::vector<Vec2> ret;
for (int iy = 0; iy < gf.dimension; ++iy) {
for (int ix = 0; ix < gf.dimension; ++ix) {
bool found_pattern = true;
for(int py = 0; py < p.height; ++py) {
for(int px = 0; px < p.width; ++px) {
int const fy = iy + py;
int const fx = ix + px;
if ((fy >= gf.dimension) || (fx >= gf.dimension)) { found_pattern = false; break; }
if (p.data[py * p.width + px]) {
if (!gf.field[fy * gf.dimension + fx]) {
found_pattern = false;
break;
}
}
}
if (!found_pattern) { break; }
}
if (found_pattern) {
ret.push_back(Vec2{ ix, iy });
}
}
}
if (!ret.empty()) {
return ret;
}
}
return {};
}
int64_t solve2(std::vector<RawTile> const& tiles)
{
auto const sorted_tiles = findCorners(tiles);
auto const solved_puzzle = solvePuzzle(sorted_tiles);
auto const findings = findInField(solved_puzzle, getDragonPattern());
GaplessField gf = makeGapless(solved_puzzle);
auto const fields_total = std::count(begin(gf.field), end(gf.field), 1);
auto const dragon_pattern = getDragonPattern();
auto const fields_dragon = std::count(begin(dragon_pattern.data), end(dragon_pattern.data), 1);
return fields_total - (fields_dragon * findings.size());
}
| 37.375652 | 186 | 0.574566 | ComicSansMS |
9c008761a4ea0029f4ed43ab696820a5ad4c27d8 | 5,671 | cpp | C++ | Game/Source/Graphics/TextureUtils.cpp | JanVijfhuizen/Data-Oriented-Engine | cf0af33249a5b81a28adb8e3502e426d112934ba | [
"MIT"
] | null | null | null | Game/Source/Graphics/TextureUtils.cpp | JanVijfhuizen/Data-Oriented-Engine | cf0af33249a5b81a28adb8e3502e426d112934ba | [
"MIT"
] | null | null | null | Game/Source/Graphics/TextureUtils.cpp | JanVijfhuizen/Data-Oriented-Engine | cf0af33249a5b81a28adb8e3502e426d112934ba | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Graphics/TextureUtils.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "StringView.h"
#include "VkRenderer/VkApp.h"
#include "VkRenderer/VkStackAllocator.h"
#include "VkRenderer/VkCommandBufferUtils.h"
#include "VkRenderer/VkSyncUtils.h"
#include "VkRenderer/VkImageUtils.h"
namespace game::texture
{
VkFormat GetFormat()
{
return VK_FORMAT_R8G8B8A8_SRGB;
}
VkImageLayout GetImageLayout()
{
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
Texture Load(const EngineOutData& outData, const jlb::StringView path)
{
auto& app = *outData.app;
auto& logicalDevice = app.logicalDevice;
auto& vkAllocator = *outData.vkAllocator;
// Load pixels.
int texWidth, texHeight, texChannels;
stbi_uc* pixels = stbi_load(path, &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
const VkDeviceSize imageSize = texWidth * texHeight * 4;
assert(pixels);
// Create staging buffer.
VkBuffer stagingBuffer;
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = imageSize;
bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
auto result = vkCreateBuffer(logicalDevice, &bufferInfo, nullptr, &stagingBuffer);
assert(!result);
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(logicalDevice, stagingBuffer, &memRequirements);
const auto stagingPoolId = vkAllocator.GetPoolId(app, memRequirements.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
const auto stagingMemBlock = vkAllocator.AllocateBlock(app, memRequirements.size, memRequirements.alignment, stagingPoolId);
result = vkBindBufferMemory(logicalDevice, stagingBuffer, stagingMemBlock.memory, stagingMemBlock.offset);
assert(!result);
// Copy pixels to staging buffer.
void* data;
vkMapMemory(logicalDevice, stagingMemBlock.memory, stagingMemBlock.offset, imageSize, 0, &data);
memcpy(data, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(logicalDevice, stagingMemBlock.memory);
// Free pixels.
stbi_image_free(pixels);
// Create image.
auto imageInfo = vk::image::CreateDefaultInfo({texWidth, texHeight}, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
VkImage image;
result = vkCreateImage(logicalDevice, &imageInfo, nullptr, &image);
assert(!result);
vkGetImageMemoryRequirements(logicalDevice, image, &memRequirements);
const auto poolId = vkAllocator.GetPoolId(app, memRequirements.memoryTypeBits,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
const auto memBlock = vkAllocator.AllocateBlock(app, memRequirements.size, memRequirements.alignment, poolId);
result = vkBindImageMemory(logicalDevice, image, memBlock.memory, memBlock.offset);
assert(!result);
// Start transfer.
VkCommandBuffer cmdBuffer;
auto cmdBufferAllocInfo = vk::cmdBuffer::CreateDefaultInfo(app);
result = vkAllocateCommandBuffers(app.logicalDevice, &cmdBufferAllocInfo, &cmdBuffer);
assert(!result);
VkFence fence;
auto fenceInfo = vk::sync::CreateFenceDefaultInfo();
result = vkCreateFence(app.logicalDevice, &fenceInfo, nullptr, &fence);
assert(!result);
result = vkResetFences(app.logicalDevice, 1, &fence);
assert(!result);
// Begin recording.
auto cmdBeginInfo = vk::cmdBuffer::CreateBeginDefaultInfo();
vkBeginCommandBuffer(cmdBuffer, &cmdBeginInfo);
vk::image::TransitionLayout(image, cmdBuffer, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
vk::image::CopyBufferToImage(stagingBuffer, image, cmdBuffer, { texWidth, texHeight });
vk::image::TransitionLayout(image, cmdBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
// End recording.
result = vkEndCommandBuffer(cmdBuffer);
assert(!result);
// Submit.
auto cmdSubmitInfo = vk::cmdBuffer::CreateSubmitDefaultInfo(cmdBuffer);
result = vkQueueSubmit(app.queues.graphics, 1, &cmdSubmitInfo, fence);
assert(!result);
result = vkWaitForFences(logicalDevice, 1, &fence, VK_TRUE, UINT64_MAX);
assert(!result);
vkDestroyFence(logicalDevice, fence, nullptr);
// Destroy staging buffer.
vkDestroyBuffer(logicalDevice, stagingBuffer, nullptr);
vkAllocator.FreeBlock(stagingMemBlock);
Texture texture{};
texture.image = image;
texture.memBlock = memBlock;
texture.resolution = { texWidth, texHeight };
return texture;
}
SubTexture GenerateSubTexture(const Texture& texture, const size_t chunkSize,
const glm::ivec2 lTop, const glm::ivec2 rBot)
{
const float xMul = static_cast<float>(chunkSize) / texture.resolution.x;
const float yMul = static_cast<float>(chunkSize) / texture.resolution.y;
SubTexture sub{};
sub.leftTop.x = xMul * lTop.x;
sub.leftTop.y = yMul * lTop.y;
sub.rightBot.x = xMul * rBot.x;
sub.rightBot.y = yMul * rBot.y;
return sub;
}
SubTexture GenerateSubTexture(const Texture& texture, const size_t chunkSize,
const size_t index)
{
const glm::ivec2 lTop = IndexToCoordinates(texture, chunkSize, index);
return GenerateSubTexture(texture, chunkSize, lTop, lTop + glm::ivec2{1, 1});
}
glm::ivec2 IndexToCoordinates(const Texture& texture, const size_t chunkSize, const size_t index)
{
const glm::ivec2 resolution = texture.resolution / glm::ivec2{chunkSize, chunkSize};
return { index % resolution.x, index / resolution.x };
}
void Free(const EngineOutData& outData, Texture& texture)
{
vkDestroyImage(outData.app->logicalDevice, texture.image, nullptr);
outData.vkAllocator->FreeBlock(texture.memBlock);
}
}
| 35.892405 | 155 | 0.771822 | JanVijfhuizen |
9c07441de55c192415887232cde2f678a892a56a | 17,859 | cc | C++ | src/runtime/runtime-test-wasm.cc | marsonya/v8 | aa13c15f19cdb57643e02b5a2def80162c2200f9 | [
"BSD-3-Clause"
] | 2 | 2021-04-19T00:22:26.000Z | 2021-04-19T00:23:56.000Z | src/runtime/runtime-test-wasm.cc | marsonya/v8 | aa13c15f19cdb57643e02b5a2def80162c2200f9 | [
"BSD-3-Clause"
] | 5 | 2021-04-19T10:15:18.000Z | 2021-04-28T19:02:36.000Z | src/runtime/runtime-test-wasm.cc | marsonya/v8 | aa13c15f19cdb57643e02b5a2def80162c2200f9 | [
"BSD-3-Clause"
] | 1 | 2021-03-08T00:27:33.000Z | 2021-03-08T00:27:33.000Z | // Copyright 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/base/memory.h"
#include "src/base/platform/mutex.h"
#include "src/execution/arguments-inl.h"
#include "src/execution/frames-inl.h"
#include "src/logging/counters.h"
#include "src/objects/smi.h"
#include "src/runtime/runtime-utils.h"
#include "src/trap-handler/trap-handler.h"
#include "src/utils/ostreams.h"
#include "src/wasm/memory-tracing.h"
#include "src/wasm/module-compiler.h"
#include "src/wasm/wasm-code-manager.h"
#include "src/wasm/wasm-engine.h"
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-objects-inl.h"
#include "src/wasm/wasm-serialization.h"
namespace v8 {
namespace internal {
namespace {
struct WasmCompileControls {
uint32_t MaxWasmBufferSize = std::numeric_limits<uint32_t>::max();
bool AllowAnySizeForAsync = true;
};
using WasmCompileControlsMap = std::map<v8::Isolate*, WasmCompileControls>;
// We need per-isolate controls, because we sometimes run tests in multiple
// isolates concurrently. Methods need to hold the accompanying mutex on access.
// To avoid upsetting the static initializer count, we lazy initialize this.
DEFINE_LAZY_LEAKY_OBJECT_GETTER(WasmCompileControlsMap,
GetPerIsolateWasmControls)
base::LazyMutex g_PerIsolateWasmControlsMutex = LAZY_MUTEX_INITIALIZER;
bool IsWasmCompileAllowed(v8::Isolate* isolate, v8::Local<v8::Value> value,
bool is_async) {
base::MutexGuard guard(g_PerIsolateWasmControlsMutex.Pointer());
DCHECK_GT(GetPerIsolateWasmControls()->count(isolate), 0);
const WasmCompileControls& ctrls = GetPerIsolateWasmControls()->at(isolate);
return (is_async && ctrls.AllowAnySizeForAsync) ||
(value->IsArrayBuffer() && value.As<v8::ArrayBuffer>()->ByteLength() <=
ctrls.MaxWasmBufferSize) ||
(value->IsArrayBufferView() &&
value.As<v8::ArrayBufferView>()->ByteLength() <=
ctrls.MaxWasmBufferSize);
}
// Use the compile controls for instantiation, too
bool IsWasmInstantiateAllowed(v8::Isolate* isolate,
v8::Local<v8::Value> module_or_bytes,
bool is_async) {
base::MutexGuard guard(g_PerIsolateWasmControlsMutex.Pointer());
DCHECK_GT(GetPerIsolateWasmControls()->count(isolate), 0);
const WasmCompileControls& ctrls = GetPerIsolateWasmControls()->at(isolate);
if (is_async && ctrls.AllowAnySizeForAsync) return true;
if (!module_or_bytes->IsWasmModuleObject()) {
return IsWasmCompileAllowed(isolate, module_or_bytes, is_async);
}
v8::Local<v8::WasmModuleObject> module =
v8::Local<v8::WasmModuleObject>::Cast(module_or_bytes);
return static_cast<uint32_t>(
module->GetCompiledModule().GetWireBytesRef().size()) <=
ctrls.MaxWasmBufferSize;
}
v8::Local<v8::Value> NewRangeException(v8::Isolate* isolate,
const char* message) {
return v8::Exception::RangeError(
v8::String::NewFromOneByte(isolate,
reinterpret_cast<const uint8_t*>(message))
.ToLocalChecked());
}
void ThrowRangeException(v8::Isolate* isolate, const char* message) {
isolate->ThrowException(NewRangeException(isolate, message));
}
bool WasmModuleOverride(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (IsWasmCompileAllowed(args.GetIsolate(), args[0], false)) return false;
ThrowRangeException(args.GetIsolate(), "Sync compile not allowed");
return true;
}
bool WasmInstanceOverride(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (IsWasmInstantiateAllowed(args.GetIsolate(), args[0], false)) return false;
ThrowRangeException(args.GetIsolate(), "Sync instantiate not allowed");
return true;
}
} // namespace
// Returns a callable object. The object returns the difference of its two
// parameters when it is called.
RUNTIME_FUNCTION(Runtime_SetWasmCompileControls) {
HandleScope scope(isolate);
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
CHECK_EQ(args.length(), 2);
CONVERT_ARG_HANDLE_CHECKED(Smi, block_size, 0);
CONVERT_BOOLEAN_ARG_CHECKED(allow_async, 1);
base::MutexGuard guard(g_PerIsolateWasmControlsMutex.Pointer());
WasmCompileControls& ctrl = (*GetPerIsolateWasmControls())[v8_isolate];
ctrl.AllowAnySizeForAsync = allow_async;
ctrl.MaxWasmBufferSize = static_cast<uint32_t>(block_size->value());
v8_isolate->SetWasmModuleCallback(WasmModuleOverride);
return ReadOnlyRoots(isolate).undefined_value();
}
RUNTIME_FUNCTION(Runtime_SetWasmInstantiateControls) {
HandleScope scope(isolate);
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
CHECK_EQ(args.length(), 0);
v8_isolate->SetWasmInstanceCallback(WasmInstanceOverride);
return ReadOnlyRoots(isolate).undefined_value();
}
namespace {
void PrintIndentation(int stack_size) {
const int max_display = 80;
if (stack_size <= max_display) {
PrintF("%4d:%*s", stack_size, stack_size, "");
} else {
PrintF("%4d:%*s", stack_size, max_display, "...");
}
}
int WasmStackSize(Isolate* isolate) {
// TODO(wasm): Fix this for mixed JS/Wasm stacks with both --trace and
// --trace-wasm.
int n = 0;
for (StackTraceFrameIterator it(isolate); !it.done(); it.Advance()) {
if (it.is_wasm()) n++;
}
return n;
}
} // namespace
RUNTIME_FUNCTION(Runtime_WasmTraceEnter) {
HandleScope shs(isolate);
DCHECK_EQ(0, args.length());
PrintIndentation(WasmStackSize(isolate));
// Find the caller wasm frame.
wasm::WasmCodeRefScope wasm_code_ref_scope;
StackTraceFrameIterator it(isolate);
DCHECK(!it.done());
DCHECK(it.is_wasm());
WasmFrame* frame = WasmFrame::cast(it.frame());
// Find the function name.
int func_index = frame->function_index();
const wasm::WasmModule* module = frame->wasm_instance().module();
wasm::ModuleWireBytes wire_bytes =
wasm::ModuleWireBytes(frame->native_module()->wire_bytes());
wasm::WireBytesRef name_ref =
module->lazily_generated_names.LookupFunctionName(
wire_bytes, func_index, VectorOf(module->export_table));
wasm::WasmName name = wire_bytes.GetNameOrNull(name_ref);
wasm::WasmCode* code = frame->wasm_code();
PrintF(code->is_liftoff() ? "~" : "*");
if (name.empty()) {
PrintF("wasm-function[%d] {\n", func_index);
} else {
PrintF("wasm-function[%d] \"%.*s\" {\n", func_index, name.length(),
name.begin());
}
return ReadOnlyRoots(isolate).undefined_value();
}
RUNTIME_FUNCTION(Runtime_WasmTraceExit) {
HandleScope shs(isolate);
DCHECK_EQ(1, args.length());
CONVERT_ARG_CHECKED(Smi, value_addr_smi, 0);
PrintIndentation(WasmStackSize(isolate));
PrintF("}");
// Find the caller wasm frame.
wasm::WasmCodeRefScope wasm_code_ref_scope;
StackTraceFrameIterator it(isolate);
DCHECK(!it.done());
DCHECK(it.is_wasm());
WasmFrame* frame = WasmFrame::cast(it.frame());
int func_index = frame->function_index();
const wasm::FunctionSig* sig =
frame->wasm_instance().module()->functions[func_index].sig;
size_t num_returns = sig->return_count();
if (num_returns == 1) {
wasm::ValueType return_type = sig->GetReturn(0);
switch (return_type.kind()) {
case wasm::kI32: {
int32_t value = base::ReadUnalignedValue<int32_t>(value_addr_smi.ptr());
PrintF(" -> %d\n", value);
break;
}
case wasm::kI64: {
int64_t value = base::ReadUnalignedValue<int64_t>(value_addr_smi.ptr());
PrintF(" -> %" PRId64 "\n", value);
break;
}
case wasm::kF32: {
float_t value = base::ReadUnalignedValue<float_t>(value_addr_smi.ptr());
PrintF(" -> %f\n", value);
break;
}
case wasm::kF64: {
double_t value =
base::ReadUnalignedValue<double_t>(value_addr_smi.ptr());
PrintF(" -> %f\n", value);
break;
}
default:
PrintF(" -> Unsupported type\n");
break;
}
} else {
// TODO(wasm) Handle multiple return values.
PrintF("\n");
}
return ReadOnlyRoots(isolate).undefined_value();
}
RUNTIME_FUNCTION(Runtime_IsAsmWasmCode) {
SealHandleScope shs(isolate);
DCHECK_EQ(1, args.length());
CONVERT_ARG_CHECKED(JSFunction, function, 0);
if (!function.shared().HasAsmWasmData()) {
return ReadOnlyRoots(isolate).false_value();
}
if (function.shared().HasBuiltinId() &&
function.shared().builtin_id() == Builtins::kInstantiateAsmJs) {
// Hasn't been compiled yet.
return ReadOnlyRoots(isolate).false_value();
}
return ReadOnlyRoots(isolate).true_value();
}
namespace {
bool DisallowWasmCodegenFromStringsCallback(v8::Local<v8::Context> context,
v8::Local<v8::String> source) {
return false;
}
} // namespace
RUNTIME_FUNCTION(Runtime_DisallowWasmCodegen) {
SealHandleScope shs(isolate);
DCHECK_EQ(1, args.length());
CONVERT_BOOLEAN_ARG_CHECKED(flag, 0);
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
v8_isolate->SetAllowWasmCodeGenerationCallback(
flag ? DisallowWasmCodegenFromStringsCallback : nullptr);
return ReadOnlyRoots(isolate).undefined_value();
}
RUNTIME_FUNCTION(Runtime_IsWasmCode) {
SealHandleScope shs(isolate);
DCHECK_EQ(1, args.length());
CONVERT_ARG_CHECKED(JSFunction, function, 0);
bool is_js_to_wasm =
function.code().kind() == CodeKind::JS_TO_WASM_FUNCTION ||
(function.code().is_builtin() &&
function.code().builtin_index() == Builtins::kGenericJSToWasmWrapper);
return isolate->heap()->ToBoolean(is_js_to_wasm);
}
RUNTIME_FUNCTION(Runtime_IsWasmTrapHandlerEnabled) {
DisallowGarbageCollection no_gc;
DCHECK_EQ(0, args.length());
return isolate->heap()->ToBoolean(trap_handler::IsTrapHandlerEnabled());
}
RUNTIME_FUNCTION(Runtime_IsThreadInWasm) {
DisallowGarbageCollection no_gc;
DCHECK_EQ(0, args.length());
return isolate->heap()->ToBoolean(trap_handler::IsThreadInWasm());
}
RUNTIME_FUNCTION(Runtime_GetWasmRecoveredTrapCount) {
HandleScope scope(isolate);
DCHECK_EQ(0, args.length());
size_t trap_count = trap_handler::GetRecoveredTrapCount();
return *isolate->factory()->NewNumberFromSize(trap_count);
}
RUNTIME_FUNCTION(Runtime_GetWasmExceptionId) {
HandleScope scope(isolate);
DCHECK_EQ(2, args.length());
CONVERT_ARG_HANDLE_CHECKED(WasmExceptionPackage, exception, 0);
CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 1);
Handle<Object> tag =
WasmExceptionPackage::GetExceptionTag(isolate, exception);
CHECK(tag->IsWasmExceptionTag());
Handle<FixedArray> exceptions_table(instance->exceptions_table(), isolate);
for (int index = 0; index < exceptions_table->length(); ++index) {
if (exceptions_table->get(index) == *tag) return Smi::FromInt(index);
}
UNREACHABLE();
}
RUNTIME_FUNCTION(Runtime_GetWasmExceptionValues) {
HandleScope scope(isolate);
DCHECK_EQ(1, args.length());
CONVERT_ARG_HANDLE_CHECKED(WasmExceptionPackage, exception, 0);
Handle<Object> values_obj =
WasmExceptionPackage::GetExceptionValues(isolate, exception);
CHECK(values_obj->IsFixedArray()); // Only called with correct input.
Handle<FixedArray> values = Handle<FixedArray>::cast(values_obj);
return *isolate->factory()->NewJSArrayWithElements(values);
}
// Wait until the given module is fully tiered up, then serialize it into an
// array buffer.
RUNTIME_FUNCTION(Runtime_SerializeWasmModule) {
HandleScope scope(isolate);
DCHECK_EQ(1, args.length());
CONVERT_ARG_HANDLE_CHECKED(WasmModuleObject, module_obj, 0);
wasm::NativeModule* native_module = module_obj->native_module();
native_module->compilation_state()->WaitForTopTierFinished();
DCHECK(!native_module->compilation_state()->failed());
wasm::WasmSerializer wasm_serializer(native_module);
size_t byte_length = wasm_serializer.GetSerializedNativeModuleSize();
Handle<JSArrayBuffer> array_buffer =
isolate->factory()
->NewJSArrayBufferAndBackingStore(byte_length,
InitializedFlag::kUninitialized)
.ToHandleChecked();
CHECK(wasm_serializer.SerializeNativeModule(
{static_cast<uint8_t*>(array_buffer->backing_store()), byte_length}));
return *array_buffer;
}
// Take an array buffer and attempt to reconstruct a compiled wasm module.
// Return undefined if unsuccessful.
RUNTIME_FUNCTION(Runtime_DeserializeWasmModule) {
HandleScope scope(isolate);
DCHECK_EQ(2, args.length());
CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 0);
CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, wire_bytes, 1);
CHECK(!buffer->was_detached());
CHECK(!wire_bytes->WasDetached());
Handle<JSArrayBuffer> wire_bytes_buffer = wire_bytes->GetBuffer();
Vector<const uint8_t> wire_bytes_vec{
reinterpret_cast<const uint8_t*>(wire_bytes_buffer->backing_store()) +
wire_bytes->byte_offset(),
wire_bytes->byte_length()};
Vector<uint8_t> buffer_vec{
reinterpret_cast<uint8_t*>(buffer->backing_store()),
buffer->byte_length()};
// Note that {wasm::DeserializeNativeModule} will allocate. We assume the
// JSArrayBuffer backing store doesn't get relocated.
MaybeHandle<WasmModuleObject> maybe_module_object =
wasm::DeserializeNativeModule(isolate, buffer_vec, wire_bytes_vec, {});
Handle<WasmModuleObject> module_object;
if (!maybe_module_object.ToHandle(&module_object)) {
return ReadOnlyRoots(isolate).undefined_value();
}
return *module_object;
}
RUNTIME_FUNCTION(Runtime_WasmGetNumberOfInstances) {
SealHandleScope shs(isolate);
DCHECK_EQ(1, args.length());
CONVERT_ARG_HANDLE_CHECKED(WasmModuleObject, module_obj, 0);
int instance_count = 0;
WeakArrayList weak_instance_list =
module_obj->script().wasm_weak_instance_list();
for (int i = 0; i < weak_instance_list.length(); ++i) {
if (weak_instance_list.Get(i)->IsWeak()) instance_count++;
}
return Smi::FromInt(instance_count);
}
RUNTIME_FUNCTION(Runtime_WasmNumCodeSpaces) {
DCHECK_EQ(1, args.length());
HandleScope scope(isolate);
CONVERT_ARG_HANDLE_CHECKED(JSObject, argument, 0);
Handle<WasmModuleObject> module;
if (argument->IsWasmInstanceObject()) {
module = handle(Handle<WasmInstanceObject>::cast(argument)->module_object(),
isolate);
} else if (argument->IsWasmModuleObject()) {
module = Handle<WasmModuleObject>::cast(argument);
}
size_t num_spaces =
module->native_module()->GetNumberOfCodeSpacesForTesting();
return *isolate->factory()->NewNumberFromSize(num_spaces);
}
RUNTIME_FUNCTION(Runtime_WasmTraceMemory) {
HandleScope scope(isolate);
DCHECK_EQ(1, args.length());
CONVERT_ARG_CHECKED(Smi, info_addr, 0);
wasm::MemoryTracingInfo* info =
reinterpret_cast<wasm::MemoryTracingInfo*>(info_addr.ptr());
// Find the caller wasm frame.
wasm::WasmCodeRefScope wasm_code_ref_scope;
StackTraceFrameIterator it(isolate);
DCHECK(!it.done());
DCHECK(it.is_wasm());
WasmFrame* frame = WasmFrame::cast(it.frame());
uint8_t* mem_start = reinterpret_cast<uint8_t*>(
frame->wasm_instance().memory_object().array_buffer().backing_store());
int func_index = frame->function_index();
int pos = frame->position();
// TODO(titzer): eliminate dependency on WasmModule definition here.
int func_start =
frame->wasm_instance().module()->functions[func_index].code.offset();
wasm::ExecutionTier tier = frame->wasm_code()->is_liftoff()
? wasm::ExecutionTier::kLiftoff
: wasm::ExecutionTier::kTurbofan;
wasm::TraceMemoryOperation(tier, info, func_index, pos - func_start,
mem_start);
return ReadOnlyRoots(isolate).undefined_value();
}
RUNTIME_FUNCTION(Runtime_WasmTierUpFunction) {
HandleScope scope(isolate);
DCHECK_EQ(2, args.length());
CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0);
CONVERT_SMI_ARG_CHECKED(function_index, 1);
auto* native_module = instance->module_object().native_module();
isolate->wasm_engine()->CompileFunction(
isolate, native_module, function_index, wasm::ExecutionTier::kTurbofan);
CHECK(!native_module->compilation_state()->failed());
return ReadOnlyRoots(isolate).undefined_value();
}
RUNTIME_FUNCTION(Runtime_WasmTierDown) {
HandleScope scope(isolate);
DCHECK_EQ(0, args.length());
isolate->wasm_engine()->TierDownAllModulesPerIsolate(isolate);
return ReadOnlyRoots(isolate).undefined_value();
}
RUNTIME_FUNCTION(Runtime_WasmTierUp) {
HandleScope scope(isolate);
DCHECK_EQ(0, args.length());
isolate->wasm_engine()->TierUpAllModulesPerIsolate(isolate);
return ReadOnlyRoots(isolate).undefined_value();
}
RUNTIME_FUNCTION(Runtime_IsLiftoffFunction) {
HandleScope scope(isolate);
DCHECK_EQ(1, args.length());
CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
CHECK(WasmExportedFunction::IsWasmExportedFunction(*function));
Handle<WasmExportedFunction> exp_fun =
Handle<WasmExportedFunction>::cast(function);
wasm::NativeModule* native_module =
exp_fun->instance().module_object().native_module();
uint32_t func_index = exp_fun->function_index();
wasm::WasmCodeRefScope code_ref_scope;
wasm::WasmCode* code = native_module->GetCode(func_index);
return isolate->heap()->ToBoolean(code && code->is_liftoff());
}
RUNTIME_FUNCTION(Runtime_FreezeWasmLazyCompilation) {
DCHECK_EQ(1, args.length());
DisallowGarbageCollection no_gc;
CONVERT_ARG_CHECKED(WasmInstanceObject, instance, 0);
instance.module_object().native_module()->set_lazy_compile_frozen(true);
return ReadOnlyRoots(isolate).undefined_value();
}
} // namespace internal
} // namespace v8
| 36.521472 | 80 | 0.718293 | marsonya |
9c0ada9cd56768f5143633c87da83d0f3f61dd4b | 1,382 | hpp | C++ | include/boost/simd/arch/x86/sse1/simd/function/load.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | include/boost/simd/arch/x86/sse1/simd/function/load.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | include/boost/simd/arch/x86/sse1/simd/function/load.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | //==================================================================================================
/*!
@file
@copyright 2015 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_X86_SSE1_SIMD_FUNCTION_LOAD_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_SSE1_SIMD_FUNCTION_LOAD_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>
#include <boost/dispatch/adapted/common/pointer.hpp>
namespace boost { namespace simd { namespace ext
{
namespace bd = ::boost::dispatch;
namespace bs = ::boost::simd;
//------------------------------------------------------------------------------------------------
// load from a pointer of single
BOOST_DISPATCH_OVERLOAD ( load_
, (typename Target, typename Pointer)
, bs::sse_
, bd::pointer_<bd::scalar_<bd::single_<Pointer>>,1u>
, bd::target_<bs::pack_<bd::single_<Target>,bs::sse_>>
)
{
using target_t = typename Target::type;
BOOST_FORCEINLINE target_t operator()(Pointer p, Target const&) const
{
return _mm_loadu_ps(p);
}
};
} } }
#endif
| 33.707317 | 100 | 0.502171 | yaeldarmon |
9c0f5c5de6bfe5889e0e7a9c7aaab616d590b5ce | 661 | cxx | C++ | src/test/dblclient/test_version.cxx | mcptr/dbl-service | 9af5aee06be0a4b909782b251bf6078513399d33 | [
"MIT"
] | null | null | null | src/test/dblclient/test_version.cxx | mcptr/dbl-service | 9af5aee06be0a4b909782b251bf6078513399d33 | [
"MIT"
] | null | null | null | src/test/dblclient/test_version.cxx | mcptr/dbl-service | 9af5aee06be0a4b909782b251bf6078513399d33 | [
"MIT"
] | 1 | 2018-10-09T06:30:03.000Z | 2018-10-09T06:30:03.000Z | #include "utils/test.hxx"
#include <string>
#include <memory>
#include <iostream>
int main(int argc, char** argv)
{
using namespace test;
using dblclient::Session;
UnitTest unit_test;
std::unique_ptr<Server> server(new Server());
std::string address = server->get_address();
int port = server->get_port();
unit_test.test_case(
"Test version",
[&address, &port](TestCase& test)
{
Session session;
session.open(address, port);
std::string version = session.get_server_version();
test.assert_true(version.length() > 0, "Got version");
}
);
ProcessTest proc_test(std::move(server), unit_test);
return proc_test.run(argc, argv);
}
| 21.322581 | 57 | 0.698941 | mcptr |
9c10af8e01ebf7237c8d5fac4e991053993dc9ec | 8,144 | cpp | C++ | rviz_default_plugins/src/rviz_default_plugins/displays/image/image_display.cpp | miraiworks/rviz | c53e307332a62805bf4b4ee275c008011b51a970 | [
"BSD-3-Clause-Clear"
] | null | null | null | rviz_default_plugins/src/rviz_default_plugins/displays/image/image_display.cpp | miraiworks/rviz | c53e307332a62805bf4b4ee275c008011b51a970 | [
"BSD-3-Clause-Clear"
] | null | null | null | rviz_default_plugins/src/rviz_default_plugins/displays/image/image_display.cpp | miraiworks/rviz | c53e307332a62805bf4b4ee275c008011b51a970 | [
"BSD-3-Clause-Clear"
] | null | null | null | /*
* Copyright (c) 2012, Willow Garage, Inc.
* Copyright (c) 2017, Bosch Software Innovations GmbH.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <memory>
#include <string>
#include <utility>
#include <OgreCamera.h>
#include <OgreManualObject.h>
#include <OgreMaterialManager.h>
#include <OgreRectangle2D.h>
#include <OgreRenderSystem.h>
#include <OgreRenderWindow.h>
#include <OgreRoot.h>
#include <OgreSceneNode.h>
#include <OgreTechnique.h>
#include <OgreTextureManager.h>
#include <OgreViewport.h>
#include "sensor_msgs/image_encodings.hpp"
#include "rviz_common/display_context.hpp"
#include "rviz_common/frame_manager_iface.hpp"
#include "rviz_common/render_panel.hpp"
#include "rviz_common/validate_floats.hpp"
#include "rviz_common/uniform_string_stream.hpp"
#include "rviz_rendering/material_manager.hpp"
#include "rviz_rendering/render_window.hpp"
#include "rviz_default_plugins/displays/image/ros_image_texture.hpp"
#include "rviz_default_plugins/displays/image/image_display.hpp"
#include "rviz_default_plugins/displays/image/ros_image_texture_iface.hpp"
namespace rviz_default_plugins
{
namespace displays
{
ImageDisplay::ImageDisplay()
: ImageDisplay(std::make_unique<ROSImageTexture>()) {}
ImageDisplay::ImageDisplay(std::unique_ptr<ROSImageTextureIface> texture)
: queue_size_property_(std::make_unique<rviz_common::QueueSizeProperty>(this, 10)),
texture_(std::move(texture))
{
normalize_property_ = new rviz_common::properties::BoolProperty(
"Normalize Range",
true,
"If set to true, will try to estimate the range of possible values from the received images.",
this,
SLOT(updateNormalizeOptions()));
min_property_ = new rviz_common::properties::FloatProperty(
"Min Value",
0.0,
"Value which will be displayed as black.",
this,
SLOT(updateNormalizeOptions()));
max_property_ = new rviz_common::properties::FloatProperty(
"Max Value",
1.0,
"Value which will be displayed as white.",
this,
SLOT(updateNormalizeOptions()));
median_buffer_size_property_ = new rviz_common::properties::IntProperty(
"Median window",
5,
"Window size for median filter used for computing min/max.",
this,
SLOT(updateNormalizeOptions()));
got_float_image_ = false;
}
void ImageDisplay::onInitialize()
{
MFDClass::onInitialize();
updateNormalizeOptions();
setupScreenRectangle();
setupRenderPanel();
render_panel_->getRenderWindow()->setupSceneAfterInit(
[this](Ogre::SceneNode * scene_node) {
scene_node->attachObject(screen_rect_.get());
});
}
ImageDisplay::~ImageDisplay() = default;
void ImageDisplay::onEnable()
{
MFDClass::subscribe();
}
void ImageDisplay::onDisable()
{
MFDClass::unsubscribe();
clear();
}
void ImageDisplay::updateNormalizeOptions()
{
if (got_float_image_) {
bool normalize = normalize_property_->getBool();
normalize_property_->setHidden(false);
min_property_->setHidden(normalize);
max_property_->setHidden(normalize);
median_buffer_size_property_->setHidden(!normalize);
texture_->setNormalizeFloatImage(
normalize, min_property_->getFloat(), max_property_->getFloat());
texture_->setMedianFrames(median_buffer_size_property_->getInt());
} else {
normalize_property_->setHidden(true);
min_property_->setHidden(true);
max_property_->setHidden(true);
median_buffer_size_property_->setHidden(true);
}
}
void ImageDisplay::clear()
{
texture_->clear();
}
void ImageDisplay::update(float wall_dt, float ros_dt)
{
(void) wall_dt;
(void) ros_dt;
try {
texture_->update();
// make sure the aspect ratio of the image is preserved
float win_width = render_panel_->width();
float win_height = render_panel_->height();
float img_width = texture_->getWidth();
float img_height = texture_->getHeight();
if (img_width != 0 && img_height != 0 && win_width != 0 && win_height != 0) {
float img_aspect = img_width / img_height;
float win_aspect = win_width / win_height;
if (img_aspect > win_aspect) {
screen_rect_->setCorners(
-1.0f, 1.0f * win_aspect / img_aspect, 1.0f, -1.0f * win_aspect / img_aspect, false);
} else {
screen_rect_->setCorners(
-1.0f * img_aspect / win_aspect, 1.0f, 1.0f * img_aspect / win_aspect, -1.0f, false);
}
}
} catch (UnsupportedImageEncoding & e) {
setStatus(rviz_common::properties::StatusProperty::Error, "Image", e.what());
}
}
void ImageDisplay::reset()
{
MFDClass::reset();
clear();
}
/* This is called by incomingMessage(). */
void ImageDisplay::processMessage(sensor_msgs::msg::Image::ConstSharedPtr msg)
{
bool got_float_image = msg->encoding == sensor_msgs::image_encodings::TYPE_32FC1 ||
msg->encoding == sensor_msgs::image_encodings::TYPE_16UC1 ||
msg->encoding == sensor_msgs::image_encodings::TYPE_16SC1 ||
msg->encoding == sensor_msgs::image_encodings::MONO16;
if (got_float_image != got_float_image_) {
got_float_image_ = got_float_image;
updateNormalizeOptions();
}
texture_->addMessage(msg);
}
void ImageDisplay::setupScreenRectangle()
{
static int count = 0;
rviz_common::UniformStringStream ss;
ss << "ImageDisplayObject" << count++;
screen_rect_ = std::make_unique<Ogre::Rectangle2D>(true);
screen_rect_->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1);
screen_rect_->setCorners(-1.0f, 1.0f, 1.0f, -1.0f);
ss << "Material";
material_ = rviz_rendering::MaterialManager::createMaterialWithNoLighting(ss.str());
material_->setSceneBlending(Ogre::SBT_REPLACE);
material_->setDepthWriteEnabled(false);
material_->setDepthCheckEnabled(false);
Ogre::TextureUnitState * tu =
material_->getTechnique(0)->getPass(0)->createTextureUnitState();
tu->setTextureName(texture_->getName());
tu->setTextureFiltering(Ogre::TFO_NONE);
material_->setCullingMode(Ogre::CULL_NONE);
Ogre::AxisAlignedBox aabInf;
aabInf.setInfinite();
screen_rect_->setBoundingBox(aabInf);
screen_rect_->setMaterial(material_);
}
void ImageDisplay::setupRenderPanel()
{
render_panel_ = std::make_unique<rviz_common::RenderPanel>();
render_panel_->resize(640, 480);
render_panel_->initialize(context_);
setAssociatedWidget(render_panel_.get());
static int count = 0;
render_panel_->getRenderWindow()->setObjectName(
"ImageDisplayRenderWindow" + QString::number(count++));
}
} // namespace displays
} // namespace rviz_default_plugins
#include <pluginlib/class_list_macros.hpp> // NOLINT
PLUGINLIB_EXPORT_CLASS(rviz_default_plugins::displays::ImageDisplay, rviz_common::Display)
| 31.937255 | 98 | 0.73502 | miraiworks |
9c15e855d38d2e17cd8eec66d4d57842d0d686c4 | 1,758 | hpp | C++ | rosbag2_transport/src/rosbag2_transport/formatter.hpp | albtam/rosbag2 | e4ce24cdfa7e24c6d2c025ecc38ab1157a0eecc8 | [
"Apache-2.0"
] | 1 | 2020-05-22T13:40:13.000Z | 2020-05-22T13:40:13.000Z | rosbag2_transport/src/rosbag2_transport/formatter.hpp | albtam/rosbag2 | e4ce24cdfa7e24c6d2c025ecc38ab1157a0eecc8 | [
"Apache-2.0"
] | 7 | 2019-10-22T17:24:35.000Z | 2020-01-03T16:28:36.000Z | rosbag2_transport/src/rosbag2_transport/formatter.hpp | albtam/rosbag2 | e4ce24cdfa7e24c6d2c025ecc38ab1157a0eecc8 | [
"Apache-2.0"
] | 8 | 2020-04-08T11:11:25.000Z | 2020-11-16T15:55:24.000Z | // Copyright 2018, Bosch Software Innovations GmbH.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROSBAG2_TRANSPORT__FORMATTER_HPP_
#define ROSBAG2_TRANSPORT__FORMATTER_HPP_
#include <chrono>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include "rosbag2_storage/bag_metadata.hpp"
namespace rosbag2_transport
{
class Formatter
{
public:
static void format_bag_meta_data(const rosbag2_storage::BagMetadata & metadata);
static std::unordered_map<std::string, std::string> format_duration(
std::chrono::high_resolution_clock::duration duration);
static std::string format_time_point(std::chrono::high_resolution_clock::duration time_point);
static std::string format_file_size(uint64_t file_size);
static void format_file_paths(
const std::vector<std::string> & paths,
std::stringstream & info_stream,
int indentation_spaces);
static void format_topics_with_type(
const std::vector<rosbag2_storage::TopicInformation> & topics,
std::stringstream & info_stream,
int indentation_spaces);
private:
static void indent(std::stringstream & info_stream, int number_of_spaces);
};
} // namespace rosbag2_transport
#endif // ROSBAG2_TRANSPORT__FORMATTER_HPP_
| 30.310345 | 96 | 0.770193 | albtam |
9c1611b336777d85b788ac690f91083e28d56834 | 776 | hpp | C++ | src/stan/math/prim/mat/meta/is_constant.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | src/stan/math/prim/mat/meta/is_constant.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | src/stan/math/prim/mat/meta/is_constant.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_PRIM_MAT_META_IS_CONSTANT_HPP
#define STAN_MATH_PRIM_MAT_META_IS_CONSTANT_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/meta/is_eigen.hpp>
#include <stan/math/prim/scal/meta/bool_constant.hpp>
#include <stan/math/prim/scal/meta/is_constant.hpp>
#include <type_traits>
namespace stan {
/**
* Defines a public enum named value and sets it to true
* if the type of the elements in the provided Eigen Matrix
* is constant, false otherwise. This is used in
* the is_constant_all metaprogram.
*
* @tparam T type of the Eigen Matrix
*/
template <typename T>
struct is_constant<T, std::enable_if_t<is_eigen<T>::value>>
: bool_constant<is_constant<typename std::decay_t<T>::Scalar>::value> {};
} // namespace stan
#endif
| 31.04 | 77 | 0.761598 | alashworth |
9c171112ed84d97e7e7cef4373009c84055eb7b0 | 4,613 | hpp | C++ | external/boost_1_60_0/qsboost/phoenix/core/expression.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | 1 | 2019-06-27T17:54:13.000Z | 2019-06-27T17:54:13.000Z | external/boost_1_60_0/qsboost/phoenix/core/expression.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | external/boost_1_60_0/qsboost/phoenix/core/expression.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null |
#if !QSBOOST_PHOENIX_IS_ITERATING
#ifndef QSBOOST_PHOENIX_CORE_EXPRESSION_HPP
#define QSBOOST_PHOENIX_CORE_EXPRESSION_HPP
#include <qsboost/phoenix/core/limits.hpp>
#include <qsboost/call_traits.hpp>
#include <qsboost/fusion/sequence/intrinsic/at.hpp>
#include <qsboost/phoenix/core/as_actor.hpp>
#include <qsboost/phoenix/core/detail/expression.hpp>
#include <qsboost/phoenix/core/domain.hpp>
#include <qsboost/phoenix/support/iterate.hpp>
#include <qsboost/preprocessor/comparison/equal.hpp>
#include <qsboost/proto/domain.hpp>
#include <qsboost/proto/make_expr.hpp>
#include <qsboost/proto/transform/pass_through.hpp>
#if !defined(QSBOOST_PHOENIX_DONT_USE_PREPROCESSED_FILES)
#include <qsboost/phoenix/core/preprocessed/expression.hpp>
#else
#if defined(__WAVE__) && defined(QSBOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/expression_" QSBOOST_PHOENIX_LIMIT_STR ".hpp")
#endif
/*=============================================================================
Copyright (c) 2005-2010 Joel de Guzman
Copyright (c) 2010 Eric Niebler
Copyright (c) 2010 Thomas Heller
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if defined(__WAVE__) && defined(QSBOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif
namespace qsboost { namespace phoenix
{
template <typename Expr> struct actor;
template <
template <typename> class Actor
, typename Tag
, QSBOOST_PHOENIX_typename_A_void(QSBOOST_PHOENIX_COMPOSITE_LIMIT)
, typename Dummy = void>
struct expr_ext;
template <
typename Tag
, QSBOOST_PHOENIX_typename_A_void(QSBOOST_PHOENIX_COMPOSITE_LIMIT)
, typename Dummy = void
>
struct expr : expr_ext<actor, Tag, QSBOOST_PHOENIX_A(QSBOOST_PHOENIX_COMPOSITE_LIMIT)> {};
#define M0(Z, N, D) \
QSBOOST_PP_COMMA_IF(N) \
typename proto::detail::uncvref<typename call_traits<QSBOOST_PP_CAT(A, N)>::value_type>::type
#define M1(Z, N, D) \
QSBOOST_PP_COMMA_IF(N) typename call_traits<QSBOOST_PP_CAT(A, N)>::param_type QSBOOST_PP_CAT(a, N)
#define QSBOOST_PHOENIX_ITERATION_PARAMS \
(3, (1, QSBOOST_PHOENIX_COMPOSITE_LIMIT, \
<qsboost/phoenix/core/expression.hpp>)) \
/**/
#include QSBOOST_PHOENIX_ITERATE()
#undef M0
#undef M1
}}
#if defined(__WAVE__) && defined(QSBOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#endif // PHOENIX_DONT_USE_PREPROCESSED_FILES
#endif
#else
template <template <typename> class Actor, typename Tag, QSBOOST_PHOENIX_typename_A>
struct expr_ext<Actor, Tag, QSBOOST_PHOENIX_A>
: proto::transform<expr_ext<Actor, Tag, QSBOOST_PHOENIX_A>, int>
{
typedef
typename proto::result_of::make_expr<
Tag
, phoenix_default_domain //proto::basic_default_domain
, QSBOOST_PP_REPEAT(QSBOOST_PHOENIX_ITERATION, M0, _)
>::type
base_type;
typedef Actor<base_type> type;
typedef
typename proto::nary_expr<Tag, QSBOOST_PHOENIX_A>::proto_grammar
proto_grammar;
static type make(QSBOOST_PP_REPEAT(QSBOOST_PHOENIX_ITERATION, M1, _))
{ //?? actor or Actor??
//Actor<base_type> const e =
actor<base_type> const e =
{
proto::make_expr<
Tag
, phoenix_default_domain // proto::basic_default_domain
>(QSBOOST_PHOENIX_a)
};
return e;
}
template<typename Expr, typename State, typename Data>
struct impl
: proto::pass_through<expr_ext>::template impl<Expr, State, Data>
{};
typedef Tag proto_tag;
#define QSBOOST_PHOENIX_ENUM_CHILDREN(_, N, __) \
typedef QSBOOST_PP_CAT(A, N) QSBOOST_PP_CAT(proto_child, N); \
/**/
QSBOOST_PP_REPEAT(QSBOOST_PHOENIX_ITERATION, QSBOOST_PHOENIX_ENUM_CHILDREN, _)
#undef QSBOOST_PHOENIX_ENUM_CHILDREN
};
#endif
| 34.94697 | 110 | 0.620204 | wouterboomsma |
9c19f5efe66502016882f3258595b5af6719725e | 102 | hpp | C++ | contracts/eosiolib/stdlib.hpp | celes-dev/celesos | b2877d64915bb027b9d86a7a692c6e91f23328b0 | [
"MIT"
] | null | null | null | contracts/eosiolib/stdlib.hpp | celes-dev/celesos | b2877d64915bb027b9d86a7a692c6e91f23328b0 | [
"MIT"
] | null | null | null | contracts/eosiolib/stdlib.hpp | celes-dev/celesos | b2877d64915bb027b9d86a7a692c6e91f23328b0 | [
"MIT"
] | null | null | null | #pragma once
#include <initializer_list>
#include <iterator>
#include <memory>
#define DEBUG 1
| 14.571429 | 28 | 0.715686 | celes-dev |
9c1cfcdcce7dcc27a9170dafc83d0afa6e118049 | 2,044 | cpp | C++ | Luogu/P1619.cpp | Insouciant21/solution | 8f241ec2076c9c29c0d39c2c285ee12eac1dee9e | [
"Apache-2.0"
] | 1 | 2020-09-11T13:17:28.000Z | 2020-09-11T13:17:28.000Z | Luogu/P1619.cpp | Insouciant21/solution | 8f241ec2076c9c29c0d39c2c285ee12eac1dee9e | [
"Apache-2.0"
] | 1 | 2020-10-22T13:36:23.000Z | 2020-10-22T13:36:23.000Z | Luogu/P1619.cpp | Insouciant21/solution | 8f241ec2076c9c29c0d39c2c285ee12eac1dee9e | [
"Apache-2.0"
] | 1 | 2020-10-22T13:33:11.000Z | 2020-10-22T13:33:11.000Z | /*
Problem: P1619
Time: 2020/10/14 20:35:55
Author: Insouciant21
Status: Accepted
*/
#include <bits/stdc++.h>
using namespace std;
const int maxn = int(1e7) * 4 + 1;
bitset<maxn> numList;
map<int, int> q;
int prime[2433655];
int cnt;
void prepare() {
numList[0] = numList[1] = 1;
for (int i = 2; i < maxn; i++) {
if (!numList[i]) {
prime[++cnt] = i;
for (int j = 2; i * j < maxn; j++)
numList[i * j] = 1;
}
}
}
long long get() {
string in;
long long num = 0;
int cnt = 0;
getline(cin, in);
for (int i = 0; i < in.length() && num < maxn; i++) {
if (in[i] >= '0' && in[i] <= '9') {
num = num * 10 + (in[i] - '0');
cnt++;
}
}
if (cnt == 0) exit(0);
return num;
}
int main() {
prepare();
ios::sync_with_stdio(false);
while (true) {
long long num;
cout << "Enter the number=";
num = get();
long long re = num;
cout << endl << "Prime? ";
if (num >= maxn) {
cout << "No!\n";
cout << "The number is too large!\n" << endl;
continue;
}
else if (!numList[num]) {
cout << "Yes!" << endl << endl;
continue;
}
else if (num < 2) {
cout << "No!\n" << endl;
continue;
}
else
cout << "No!" << endl;
for (int i = 1; prime[i] <= num / 2; i++) {
while (num >= prime[i]) {
if (num % prime[i] == 0) {
q[prime[i]]++;
num /= prime[i];
}
else
break;
}
}
if (num != 1) q[num]++;
string ans;
for (auto iter = q.begin(); iter != q.end(); iter++)
ans += to_string(iter->first) + "^" + to_string(iter->second) + "*";
ans.pop_back();
cout << re << "=" << ans << endl << endl;
q.clear();
}
return 0;
} | 22.966292 | 80 | 0.395793 | Insouciant21 |
9c1e2865c00182de878ee3f78dcc572f223b33ce | 33,768 | cpp | C++ | src/Bindings/LuaState.cpp | p-mcgowan/MCServer | 46bdc6c2c621a27c40e11c7af701f3ce50148e01 | [
"Apache-2.0"
] | null | null | null | src/Bindings/LuaState.cpp | p-mcgowan/MCServer | 46bdc6c2c621a27c40e11c7af701f3ce50148e01 | [
"Apache-2.0"
] | null | null | null | src/Bindings/LuaState.cpp | p-mcgowan/MCServer | 46bdc6c2c621a27c40e11c7af701f3ce50148e01 | [
"Apache-2.0"
] | null | null | null |
// LuaState.cpp
// Implements the cLuaState class representing the wrapper over lua_State *, provides associated helper functions
#include "Globals.h"
#include "LuaState.h"
extern "C"
{
#include "lua/src/lualib.h"
}
#undef TOLUA_TEMPLATE_BIND
#include "tolua++/include/tolua++.h"
#include "Bindings.h"
#include "ManualBindings.h"
#include "DeprecatedBindings.h"
#include "../Entities/Entity.h"
#include "../BlockEntities/BlockEntity.h"
// fwd: SQLite/lsqlite3.c
extern "C"
{
int luaopen_lsqlite3(lua_State * L);
}
// fwd: LuaExpat/lxplib.c:
extern "C"
{
int luaopen_lxp(lua_State * L);
}
const cLuaState::cRet cLuaState::Return = {};
////////////////////////////////////////////////////////////////////////////////
// cLuaState:
cLuaState::cLuaState(const AString & a_SubsystemName) :
m_LuaState(nullptr),
m_IsOwned(false),
m_SubsystemName(a_SubsystemName),
m_NumCurrentFunctionArgs(-1)
{
}
cLuaState::cLuaState(lua_State * a_AttachState) :
m_LuaState(a_AttachState),
m_IsOwned(false),
m_SubsystemName("<attached>"),
m_NumCurrentFunctionArgs(-1)
{
}
cLuaState::~cLuaState()
{
if (IsValid())
{
if (m_IsOwned)
{
Close();
}
else
{
Detach();
}
}
}
void cLuaState::Create(void)
{
if (m_LuaState != nullptr)
{
LOGWARNING("%s: Trying to create an already-existing LuaState, ignoring.", __FUNCTION__);
return;
}
m_LuaState = lua_open();
luaL_openlibs(m_LuaState);
m_IsOwned = true;
}
void cLuaState::RegisterAPILibs(void)
{
tolua_AllToLua_open(m_LuaState);
ManualBindings::Bind(m_LuaState);
DeprecatedBindings::Bind(m_LuaState);
luaopen_lsqlite3(m_LuaState);
luaopen_lxp(m_LuaState);
}
void cLuaState::Close(void)
{
if (m_LuaState == nullptr)
{
LOGWARNING("%s: Trying to close an invalid LuaState, ignoring.", __FUNCTION__);
return;
}
if (!m_IsOwned)
{
LOGWARNING(
"%s: Detected mis-use, calling Close() on an attached state (0x%p). Detaching instead.",
__FUNCTION__, m_LuaState
);
Detach();
return;
}
lua_close(m_LuaState);
m_LuaState = nullptr;
m_IsOwned = false;
}
void cLuaState::Attach(lua_State * a_State)
{
if (m_LuaState != nullptr)
{
LOGINFO("%s: Already contains a LuaState (0x%p), will be closed / detached.", __FUNCTION__, m_LuaState);
if (m_IsOwned)
{
Close();
}
else
{
Detach();
}
}
m_LuaState = a_State;
m_IsOwned = false;
}
void cLuaState::Detach(void)
{
if (m_LuaState == nullptr)
{
return;
}
if (m_IsOwned)
{
LOGWARNING(
"%s: Detected a mis-use, calling Detach() when the state is owned. Closing the owned state (0x%p).",
__FUNCTION__, m_LuaState
);
Close();
return;
}
m_LuaState = nullptr;
}
void cLuaState::AddPackagePath(const AString & a_PathVariable, const AString & a_Path)
{
// Get the current path:
lua_getfield(m_LuaState, LUA_GLOBALSINDEX, "package"); // Stk: <package>
lua_getfield(m_LuaState, -1, a_PathVariable.c_str()); // Stk: <package> <package.path>
size_t len = 0;
const char * PackagePath = lua_tolstring(m_LuaState, -1, &len);
// Append the new path:
AString NewPackagePath(PackagePath, len);
NewPackagePath.append(LUA_PATHSEP);
NewPackagePath.append(a_Path);
// Set the new path to the environment:
lua_pop(m_LuaState, 1); // Stk: <package>
lua_pushlstring(m_LuaState, NewPackagePath.c_str(), NewPackagePath.length()); // Stk: <package> <NewPackagePath>
lua_setfield(m_LuaState, -2, a_PathVariable.c_str()); // Stk: <package>
lua_pop(m_LuaState, 1);
lua_pop(m_LuaState, 1); // Stk: -
}
bool cLuaState::LoadFile(const AString & a_FileName)
{
ASSERT(IsValid());
// Load the file:
int s = luaL_loadfile(m_LuaState, a_FileName.c_str());
if (ReportErrors(s))
{
LOGWARNING("Can't load %s because of an error in file %s", m_SubsystemName.c_str(), a_FileName.c_str());
return false;
}
// Execute the globals:
s = lua_pcall(m_LuaState, 0, LUA_MULTRET, 0);
if (ReportErrors(s))
{
LOGWARNING("Error in %s in file %s", m_SubsystemName.c_str(), a_FileName.c_str());
return false;
}
return true;
}
bool cLuaState::HasFunction(const char * a_FunctionName)
{
if (!IsValid())
{
// This happens if cPlugin::Initialize() fails with an error
return false;
}
lua_getglobal(m_LuaState, a_FunctionName);
bool res = (!lua_isnil(m_LuaState, -1) && lua_isfunction(m_LuaState, -1));
lua_pop(m_LuaState, 1);
return res;
}
bool cLuaState::PushFunction(const char * a_FunctionName)
{
ASSERT(m_NumCurrentFunctionArgs == -1); // If not, there's already something pushed onto the stack
if (!IsValid())
{
// This happens if cPlugin::Initialize() fails with an error
return false;
}
// Push the error handler for lua_pcall()
lua_pushcfunction(m_LuaState, &ReportFnCallErrors);
lua_getglobal(m_LuaState, a_FunctionName);
if (!lua_isfunction(m_LuaState, -1))
{
LOGWARNING("Error in %s: Could not find function %s()", m_SubsystemName.c_str(), a_FunctionName);
lua_pop(m_LuaState, 2);
return false;
}
m_CurrentFunctionName.assign(a_FunctionName);
m_NumCurrentFunctionArgs = 0;
return true;
}
bool cLuaState::PushFunction(int a_FnRef)
{
ASSERT(IsValid());
ASSERT(m_NumCurrentFunctionArgs == -1); // If not, there's already something pushed onto the stack
// Push the error handler for lua_pcall()
lua_pushcfunction(m_LuaState, &ReportFnCallErrors);
lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, a_FnRef); // same as lua_getref()
if (!lua_isfunction(m_LuaState, -1))
{
lua_pop(m_LuaState, 2);
return false;
}
m_CurrentFunctionName = "<callback>";
m_NumCurrentFunctionArgs = 0;
return true;
}
bool cLuaState::PushFunction(const cTableRef & a_TableRef)
{
ASSERT(IsValid());
ASSERT(m_NumCurrentFunctionArgs == -1); // If not, there's already something pushed onto the stack
// Push the error handler for lua_pcall()
lua_pushcfunction(m_LuaState, &ReportFnCallErrors);
lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, a_TableRef.GetTableRef()); // Get the table ref
if (!lua_istable(m_LuaState, -1))
{
// Not a table, bail out
lua_pop(m_LuaState, 2);
return false;
}
lua_getfield(m_LuaState, -1, a_TableRef.GetFnName());
if (lua_isnil(m_LuaState, -1) || !lua_isfunction(m_LuaState, -1))
{
// Not a valid function, bail out
lua_pop(m_LuaState, 3);
return false;
}
// Pop the table off the stack:
lua_remove(m_LuaState, -2);
Printf(m_CurrentFunctionName, "<table-callback %s>", a_TableRef.GetFnName());
m_NumCurrentFunctionArgs = 0;
return true;
}
void cLuaState::PushNil(void)
{
ASSERT(IsValid());
lua_pushnil(m_LuaState);
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const AString & a_String)
{
ASSERT(IsValid());
lua_pushlstring(m_LuaState, a_String.data(), a_String.size());
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const AStringVector & a_Vector)
{
ASSERT(IsValid());
lua_createtable(m_LuaState, (int)a_Vector.size(), 0);
int newTable = lua_gettop(m_LuaState);
int index = 1;
for (AStringVector::const_iterator itr = a_Vector.begin(), end = a_Vector.end(); itr != end; ++itr, ++index)
{
tolua_pushstring(m_LuaState, itr->c_str());
lua_rawseti(m_LuaState, newTable, index);
}
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const cCraftingGrid * a_Grid)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)a_Grid, "cCraftingGrid");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const cCraftingRecipe * a_Recipe)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)a_Recipe, "cCraftingRecipe");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const char * a_Value)
{
ASSERT(IsValid());
tolua_pushstring(m_LuaState, a_Value);
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const cItems & a_Items)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)&a_Items, "cItems");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const cPlayer * a_Player)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)a_Player, "cPlayer");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const HTTPRequest * a_Request)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)a_Request, "HTTPRequest");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const HTTPTemplateRequest * a_Request)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)a_Request, "HTTPTemplateRequest");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const Vector3d & a_Vector)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)&a_Vector, "Vector3<double>");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const Vector3d * a_Vector)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)a_Vector, "Vector3<double>");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const Vector3i & a_Vector)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)&a_Vector, "Vector3<int>");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(const Vector3i * a_Vector)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, (void *)a_Vector, "Vector3<int>");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(bool a_Value)
{
ASSERT(IsValid());
tolua_pushboolean(m_LuaState, a_Value ? 1 : 0);
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cBlockEntity * a_BlockEntity)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_BlockEntity, (a_BlockEntity == nullptr) ? "cBlockEntity" : a_BlockEntity->GetClass());
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cChunkDesc * a_ChunkDesc)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_ChunkDesc, "cChunkDesc");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cClientHandle * a_Client)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Client, "cClientHandle");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cEntity * a_Entity)
{
ASSERT(IsValid());
if (a_Entity == nullptr)
{
lua_pushnil(m_LuaState);
}
else
{
switch (a_Entity->GetEntityType())
{
case cEntity::etMonster:
{
// Don't push specific mob types, as those are not exported in the API:
tolua_pushusertype(m_LuaState, a_Entity, "cMonster");
break;
}
case cEntity::etPlayer:
{
tolua_pushusertype(m_LuaState, a_Entity, "cPlayer");
break;
}
case cEntity::etPickup:
{
tolua_pushusertype(m_LuaState, a_Entity, "cPickup");
break;
}
case cEntity::etTNT:
{
tolua_pushusertype(m_LuaState, a_Entity, "cTNTEntity");
break;
}
case cEntity::etProjectile:
{
tolua_pushusertype(m_LuaState, a_Entity, a_Entity->GetClass());
break;
}
case cEntity::etFloater:
{
tolua_pushusertype(m_LuaState, a_Entity, "cFloater");
break;
}
case cEntity::etEntity:
case cEntity::etEnderCrystal:
case cEntity::etFallingBlock:
case cEntity::etMinecart:
case cEntity::etBoat:
case cEntity::etExpOrb:
case cEntity::etItemFrame:
case cEntity::etPainting:
{
// Push the generic entity class type:
tolua_pushusertype(m_LuaState, a_Entity, "cEntity");
}
} // switch (EntityType)
}
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cHopperEntity * a_Hopper)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Hopper, "cHopperEntity");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cItem * a_Item)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Item, "cItem");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cItems * a_Items)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Items, "cItems");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cLuaServerHandle * a_ServerHandle)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_ServerHandle, "cServerHandle");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cLuaTCPLink * a_TCPLink)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_TCPLink, "cTCPLink");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cLuaUDPEndpoint * a_UDPEndpoint)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_UDPEndpoint, "cUDPEndpoint");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cMonster * a_Monster)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Monster, "cMonster");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cPickup * a_Pickup)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Pickup, "cPickup");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cPlayer * a_Player)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Player, "cPlayer");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cPlugin * a_Plugin)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Plugin, "cPlugin");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cPluginLua * a_Plugin)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Plugin, "cPluginLua");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cProjectileEntity * a_ProjectileEntity)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_ProjectileEntity, "cProjectileEntity");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cTNTEntity * a_TNTEntity)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_TNTEntity, "cTNTEntity");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cWebAdmin * a_WebAdmin)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_WebAdmin, "cWebAdmin");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cWindow * a_Window)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Window, "cWindow");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cWorld * a_World)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_World, "cWorld");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(double a_Value)
{
ASSERT(IsValid());
tolua_pushnumber(m_LuaState, a_Value);
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(int a_Value)
{
ASSERT(IsValid());
tolua_pushnumber(m_LuaState, a_Value);
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(TakeDamageInfo * a_TDI)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_TDI, "TakeDamageInfo");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(Vector3d * a_Vector)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Vector, "Vector3<double>");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(Vector3i * a_Vector)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Vector, "Vector3<int>");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(void * a_Ptr)
{
UNUSED(a_Ptr);
ASSERT(IsValid());
// Investigate the cause of this - what is the callstack?
// One code path leading here is the OnHookExploding / OnHookExploded with exotic parameters. Need to decide what to do with them
LOGWARNING("Lua engine: attempting to push a plain pointer, pushing nil instead.");
LOGWARNING("This indicates an unimplemented part of MCS bindings");
LogStackTrace();
lua_pushnil(m_LuaState);
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(std::chrono::milliseconds a_Value)
{
ASSERT(IsValid());
tolua_pushnumber(m_LuaState, static_cast<lua_Number>(a_Value.count()));
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::PushUserType(void * a_Object, const char * a_Type)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Object, a_Type);
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::GetStackValue(int a_StackPos, AString & a_Value)
{
size_t len = 0;
const char * data = lua_tolstring(m_LuaState, a_StackPos, &len);
if (data != nullptr)
{
a_Value.assign(data, len);
}
}
void cLuaState::GetStackValue(int a_StackPos, BLOCKTYPE & a_ReturnedVal)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_ReturnedVal = static_cast<BLOCKTYPE>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal));
}
}
void cLuaState::GetStackValue(int a_StackPos, bool & a_ReturnedVal)
{
a_ReturnedVal = (tolua_toboolean(m_LuaState, a_StackPos, a_ReturnedVal ? 1 : 0) > 0);
}
void cLuaState::GetStackValue(int a_StackPos, cRef & a_Ref)
{
a_Ref.RefStack(*this, a_StackPos);
}
void cLuaState::GetStackValue(int a_StackPos, double & a_ReturnedVal)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_ReturnedVal = tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal);
}
}
void cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal)
{
if (!lua_isnumber(m_LuaState, a_StackPos))
{
return;
}
a_ReturnedVal = static_cast<eWeather>(Clamp(
static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)),
static_cast<int>(wSunny), static_cast<int>(wThunderstorm))
);
}
void cLuaState::GetStackValue(int a_StackPos, int & a_ReturnedVal)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_ReturnedVal = static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal));
}
}
void cLuaState::GetStackValue(int a_StackPos, pBlockArea & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cBlockArea", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cBlockArea **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cBoundingBox", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cBoundingBox **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pMapManager & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cMapManager", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cMapManager **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pPluginManager & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cPluginManager", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cPluginManager **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pRoot & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cRoot", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cRoot **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pScoreboard & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cScoreboard", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cScoreboard **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pWorld & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cWorld", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cWorld **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pClientHandle & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cClientHandle", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cClientHandle **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
bool cLuaState::CallFunction(int a_NumResults)
{
ASSERT (m_NumCurrentFunctionArgs >= 0); // A function must be pushed to stack first
ASSERT(lua_isfunction(m_LuaState, -m_NumCurrentFunctionArgs - 1)); // The function to call
ASSERT(lua_isfunction(m_LuaState, -m_NumCurrentFunctionArgs - 2)); // The error handler
// Save the current "stack" state and reset, in case the callback calls another function:
AString CurrentFunctionName;
std::swap(m_CurrentFunctionName, CurrentFunctionName);
int NumArgs = m_NumCurrentFunctionArgs;
m_NumCurrentFunctionArgs = -1;
// Call the function:
int s = lua_pcall(m_LuaState, NumArgs, a_NumResults, -NumArgs - 2);
if (s != 0)
{
// The error has already been printed together with the stacktrace
LOGWARNING("Error in %s calling function %s()", m_SubsystemName.c_str(), CurrentFunctionName.c_str());
return false;
}
// Remove the error handler from the stack:
lua_remove(m_LuaState, -a_NumResults - 1);
return true;
}
bool cLuaState::CheckParamUserTable(int a_StartParam, const char * a_UserTable, int a_EndParam)
{
ASSERT(IsValid());
if (a_EndParam < 0)
{
a_EndParam = a_StartParam;
}
tolua_Error tolua_err;
for (int i = a_StartParam; i <= a_EndParam; i++)
{
if (tolua_isusertable(m_LuaState, i, a_UserTable, 0, &tolua_err))
{
continue;
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
// All params checked ok
return true;
}
bool cLuaState::CheckParamUserType(int a_StartParam, const char * a_UserType, int a_EndParam)
{
ASSERT(IsValid());
if (a_EndParam < 0)
{
a_EndParam = a_StartParam;
}
tolua_Error tolua_err;
for (int i = a_StartParam; i <= a_EndParam; i++)
{
if (tolua_isusertype(m_LuaState, i, a_UserType, 0, &tolua_err))
{
continue;
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
// All params checked ok
return true;
}
bool cLuaState::CheckParamTable(int a_StartParam, int a_EndParam)
{
ASSERT(IsValid());
if (a_EndParam < 0)
{
a_EndParam = a_StartParam;
}
tolua_Error tolua_err;
for (int i = a_StartParam; i <= a_EndParam; i++)
{
if (tolua_istable(m_LuaState, i, 0, &tolua_err))
{
continue;
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
// All params checked ok
return true;
}
bool cLuaState::CheckParamNumber(int a_StartParam, int a_EndParam)
{
ASSERT(IsValid());
if (a_EndParam < 0)
{
a_EndParam = a_StartParam;
}
tolua_Error tolua_err;
for (int i = a_StartParam; i <= a_EndParam; i++)
{
if (tolua_isnumber(m_LuaState, i, 0, &tolua_err))
{
continue;
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
// All params checked ok
return true;
}
bool cLuaState::CheckParamString(int a_StartParam, int a_EndParam)
{
ASSERT(IsValid());
if (a_EndParam < 0)
{
a_EndParam = a_StartParam;
}
tolua_Error tolua_err;
for (int i = a_StartParam; i <= a_EndParam; i++)
{
if (tolua_isstring(m_LuaState, i, 0, &tolua_err))
{
continue;
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
// All params checked ok
return true;
}
bool cLuaState::CheckParamFunction(int a_StartParam, int a_EndParam)
{
ASSERT(IsValid());
if (a_EndParam < 0)
{
a_EndParam = a_StartParam;
}
for (int i = a_StartParam; i <= a_EndParam; i++)
{
if (lua_isfunction(m_LuaState, i))
{
continue;
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s",
(entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str()
);
return false;
} // for i - Param
// All params checked ok
return true;
}
bool cLuaState::CheckParamFunctionOrNil(int a_StartParam, int a_EndParam)
{
ASSERT(IsValid());
if (a_EndParam < 0)
{
a_EndParam = a_StartParam;
}
for (int i = a_StartParam; i <= a_EndParam; i++)
{
if (lua_isfunction(m_LuaState, i) || lua_isnil(m_LuaState, i))
{
continue;
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s",
(entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str()
);
return false;
} // for i - Param
// All params checked ok
return true;
}
bool cLuaState::CheckParamEnd(int a_Param)
{
tolua_Error tolua_err;
if (tolua_isnoobj(m_LuaState, a_Param, &tolua_err))
{
return true;
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = Printf("#ferror in function '%s': Too many arguments.", (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
}
bool cLuaState::IsParamUserType(int a_Param, AString a_UserType)
{
ASSERT(IsValid());
tolua_Error tolua_err;
return tolua_isusertype(m_LuaState, a_Param, a_UserType.c_str(), 0, &tolua_err);
}
bool cLuaState::IsParamNumber(int a_Param)
{
ASSERT(IsValid());
tolua_Error tolua_err;
return tolua_isnumber(m_LuaState, a_Param, 0, &tolua_err);
}
bool cLuaState::ReportErrors(int a_Status)
{
return ReportErrors(m_LuaState, a_Status);
}
bool cLuaState::ReportErrors(lua_State * a_LuaState, int a_Status)
{
if (a_Status == 0)
{
// No error to report
return false;
}
LOGWARNING("LUA: %d - %s", a_Status, lua_tostring(a_LuaState, -1));
lua_pop(a_LuaState, 1);
return true;
}
void cLuaState::LogStackTrace(int a_StartingDepth)
{
LogStackTrace(m_LuaState, a_StartingDepth);
}
void cLuaState::LogStackTrace(lua_State * a_LuaState, int a_StartingDepth)
{
LOGWARNING("Stack trace:");
lua_Debug entry;
int depth = a_StartingDepth;
while (lua_getstack(a_LuaState, depth, &entry))
{
lua_getinfo(a_LuaState, "Sln", &entry);
LOGWARNING(" %s(%d): %s", entry.short_src, entry.currentline, entry.name ? entry.name : "(no name)");
depth++;
}
LOGWARNING("Stack trace end");
}
AString cLuaState::GetTypeText(int a_StackPos)
{
return lua_typename(m_LuaState, lua_type(m_LuaState, a_StackPos));
}
int cLuaState::CallFunctionWithForeignParams(
const AString & a_FunctionName,
cLuaState & a_SrcLuaState,
int a_SrcParamStart,
int a_SrcParamEnd
)
{
ASSERT(IsValid());
ASSERT(a_SrcLuaState.IsValid());
// Store the stack position before any changes
int OldTop = lua_gettop(m_LuaState);
// Push the function to call, including the error handler:
if (!PushFunction(a_FunctionName.c_str()))
{
LOGWARNING("Function '%s' not found", a_FunctionName.c_str());
lua_settop(m_LuaState, OldTop);
return -1;
}
// Copy the function parameters to the target state
if (CopyStackFrom(a_SrcLuaState, a_SrcParamStart, a_SrcParamEnd) < 0)
{
// Something went wrong, fix the stack and exit
lua_settop(m_LuaState, OldTop);
m_NumCurrentFunctionArgs = -1;
m_CurrentFunctionName.clear();
return -1;
}
// Call the function, with an error handler:
int s = lua_pcall(m_LuaState, a_SrcParamEnd - a_SrcParamStart + 1, LUA_MULTRET, OldTop + 1);
if (ReportErrors(s))
{
LOGWARN("Error while calling function '%s' in '%s'", a_FunctionName.c_str(), m_SubsystemName.c_str());
// Reset the stack:
lua_settop(m_LuaState, OldTop);
// Reset the internal checking mechanisms:
m_NumCurrentFunctionArgs = -1;
m_CurrentFunctionName.clear();
// Make Lua think everything is okay and return 0 values, so that plugins continue executing.
// The failure is indicated by the zero return values.
return 0;
}
// Reset the internal checking mechanisms:
m_NumCurrentFunctionArgs = -1;
m_CurrentFunctionName.clear();
// Remove the error handler from the stack:
lua_remove(m_LuaState, OldTop + 1);
// Return the number of return values:
return lua_gettop(m_LuaState) - OldTop;
}
int cLuaState::CopyStackFrom(cLuaState & a_SrcLuaState, int a_SrcStart, int a_SrcEnd)
{
/*
// DEBUG:
LOGD("Copying stack values from %d to %d", a_SrcStart, a_SrcEnd);
a_SrcLuaState.LogStack("Src stack before copying:");
LogStack("Dst stack before copying:");
*/
for (int i = a_SrcStart; i <= a_SrcEnd; ++i)
{
int t = lua_type(a_SrcLuaState, i);
switch (t)
{
case LUA_TNIL:
{
lua_pushnil(m_LuaState);
break;
}
case LUA_TSTRING:
{
AString s;
a_SrcLuaState.ToString(i, s);
Push(s);
break;
}
case LUA_TBOOLEAN:
{
bool b = (tolua_toboolean(a_SrcLuaState, i, false) != 0);
Push(b);
break;
}
case LUA_TNUMBER:
{
lua_Number d = tolua_tonumber(a_SrcLuaState, i, 0);
Push(d);
break;
}
case LUA_TUSERDATA:
{
// Get the class name:
const char * type = nullptr;
if (lua_getmetatable(a_SrcLuaState, i) == 0)
{
LOGWARNING("%s: Unknown class in pos %d, cannot copy.", __FUNCTION__, i);
lua_pop(m_LuaState, i - a_SrcStart);
return -1;
}
lua_rawget(a_SrcLuaState, LUA_REGISTRYINDEX); // Stack +1
type = lua_tostring(a_SrcLuaState, -1);
lua_pop(a_SrcLuaState, 1); // Stack -1
// Copy the value:
void * ud = tolua_touserdata(a_SrcLuaState, i, nullptr);
tolua_pushusertype(m_LuaState, ud, type);
break;
}
default:
{
LOGWARNING("%s: Unsupported value: '%s' at stack position %d. Can only copy numbers, strings, bools and classes!",
__FUNCTION__, lua_typename(a_SrcLuaState, t), i
);
a_SrcLuaState.LogStack("Stack where copying failed:");
lua_pop(m_LuaState, i - a_SrcStart);
return -1;
}
}
}
return a_SrcEnd - a_SrcStart + 1;
}
void cLuaState::ToString(int a_StackPos, AString & a_String)
{
size_t len;
const char * s = lua_tolstring(m_LuaState, a_StackPos, &len);
if (s != nullptr)
{
a_String.assign(s, len);
}
}
void cLuaState::LogStack(const char * a_Header)
{
LogStack(m_LuaState, a_Header);
}
void cLuaState::LogStack(lua_State * a_LuaState, const char * a_Header)
{
// Format string consisting only of %s is used to appease the compiler
LOG("%s", (a_Header != nullptr) ? a_Header : "Lua C API Stack contents:");
for (int i = lua_gettop(a_LuaState); i > 0; i--)
{
AString Value;
int Type = lua_type(a_LuaState, i);
switch (Type)
{
case LUA_TBOOLEAN: Value.assign((lua_toboolean(a_LuaState, i) != 0) ? "true" : "false"); break;
case LUA_TLIGHTUSERDATA: Printf(Value, "%p", lua_touserdata(a_LuaState, i)); break;
case LUA_TNUMBER: Printf(Value, "%f", (double)lua_tonumber(a_LuaState, i)); break;
case LUA_TSTRING: Printf(Value, "%s", lua_tostring(a_LuaState, i)); break;
case LUA_TTABLE: Printf(Value, "%p", lua_topointer(a_LuaState, i)); break;
default: break;
}
LOGD(" Idx %d: type %d (%s) %s", i, Type, lua_typename(a_LuaState, Type), Value.c_str());
} // for i - stack idx
}
int cLuaState::ReportFnCallErrors(lua_State * a_LuaState)
{
LOGWARNING("LUA: %s", lua_tostring(a_LuaState, -1));
LogStackTrace(a_LuaState, 1);
return 1; // We left the error message on the stack as the return value
}
////////////////////////////////////////////////////////////////////////////////
// cLuaState::cRef:
cLuaState::cRef::cRef(void) :
m_LuaState(nullptr),
m_Ref(LUA_REFNIL)
{
}
cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) :
m_LuaState(nullptr),
m_Ref(LUA_REFNIL)
{
RefStack(a_LuaState, a_StackPos);
}
cLuaState::cRef::cRef(cRef && a_FromRef):
m_LuaState(a_FromRef.m_LuaState),
m_Ref(a_FromRef.m_Ref)
{
a_FromRef.m_LuaState = nullptr;
a_FromRef.m_Ref = LUA_REFNIL;
}
cLuaState::cRef::~cRef()
{
if (m_LuaState != nullptr)
{
UnRef();
}
}
void cLuaState::cRef::RefStack(cLuaState & a_LuaState, int a_StackPos)
{
ASSERT(a_LuaState.IsValid());
if (m_LuaState != nullptr)
{
UnRef();
}
m_LuaState = &a_LuaState;
lua_pushvalue(a_LuaState, a_StackPos); // Push a copy of the value at a_StackPos onto the stack
m_Ref = luaL_ref(a_LuaState, LUA_REGISTRYINDEX);
}
void cLuaState::cRef::UnRef(void)
{
ASSERT(m_LuaState->IsValid()); // The reference should be destroyed before destroying the LuaState
if (IsValid())
{
luaL_unref(*m_LuaState, LUA_REGISTRYINDEX, m_Ref);
}
m_LuaState = nullptr;
m_Ref = LUA_REFNIL;
}
| 18.801782 | 130 | 0.695037 | p-mcgowan |
9c2484d3538e728431aad1d2f8712e14ce7f3d27 | 1,412 | hh | C++ | src/pks/PK_BDF.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/pks/PK_BDF.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/pks/PK_BDF.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
Process Kernels
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Authors: Konstantin Lipnikov, Ethan Coon
This is a purely virtual base class for process kernels which use
(implicit) time integrators.
*/
#ifndef AMANZI_PK_BDF_HH_
#define AMANZI_PK_BDF_HH_
#include "Teuchos_RCP.hpp"
#include "BDFFnBase.hh"
#include "Key.hh"
#include "Operator.hh"
#include "OperatorDefs.hh"
#include "PDE_HelperDiscretization.hh"
#include "primary_variable_field_evaluator.hh"
#include "PK.hh"
namespace Amanzi {
class PK_BDF : virtual public PK,
public BDFFnBase<TreeVector> {
public:
PK_BDF()
: PK(),
BDFFnBase<TreeVector>() {};
PK_BDF(Teuchos::ParameterList& pk_tree,
const Teuchos::RCP<Teuchos::ParameterList>& glist,
const Teuchos::RCP<State>& S,
const Teuchos::RCP<TreeVector>& soln)
: PK(pk_tree, glist, S, soln),
BDFFnBase<TreeVector>() {};
// access to operators and PDEs in sub-PKs
virtual Teuchos::RCP<Operators::Operator>
my_operator(const Operators::OperatorType& type) { return Teuchos::null; }
virtual Teuchos::RCP<Operators::PDE_HelperDiscretization>
my_pde(const Operators::PDEType& type) { return Teuchos::null; }
};
} // namespace Amanzi
#endif
| 24.77193 | 80 | 0.723796 | fmyuan |
9c2567c22c33c731fc0e23733c13d9a9191fdef5 | 14,586 | cpp | C++ | Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/directTidalDissipationAccelerationPartial.cpp | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/directTidalDissipationAccelerationPartial.cpp | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/directTidalDissipationAccelerationPartial.cpp | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#include "Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/directTidalDissipationAccelerationPartial.h"
#include "Tudat/Astrodynamics/OrbitDetermination/EstimatableParameters/directTidalTimeLag.h"
#include "Tudat/Mathematics/BasicMathematics/linearAlgebra.h"
namespace tudat
{
namespace acceleration_partials
{
//! Function to compute partial derivative of direct tidal acceleration due to tide on planet w.r.t. position of satellite
Eigen::Matrix3d computeDirectTidalAccelerationDueToTideOnPlanetWrtPosition(
const Eigen::Vector6d relativeStateOfBodyExertingTide, const Eigen::Vector3d planetAngularVelocityVector,
const double currentTidalAccelerationMultiplier, const double timeLag, const bool includeDirectRadialComponent )
{
Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 );
Eigen::Vector3d relativePositionUnitVector = relativePosition.normalized( );
Eigen::Vector3d relativeVelocity = relativeStateOfBodyExertingTide.segment( 3, 3 );
double positionVelocityInnerProduct = relativePosition.dot( relativeVelocity );
double distance = relativePosition.norm( );
double distanceSquared = distance * distance;
double radialComponentMultiplier = ( includeDirectRadialComponent == true ) ? 1.0 : 0.0;
return currentTidalAccelerationMultiplier * (
radialComponentMultiplier * ( Eigen::Matrix3d::Identity( )
- 8.0 * relativePositionUnitVector * relativePositionUnitVector.transpose( ) ) +
timeLag * ( -20.0 * positionVelocityInnerProduct *
relativePositionUnitVector * relativePositionUnitVector.transpose( ) /
distanceSquared + 2.0 / distanceSquared * (
Eigen::Matrix3d::Identity( ) * positionVelocityInnerProduct +
relativePosition * relativeVelocity.transpose( ) ) -
8.0 / distance * ( relativePosition.cross( planetAngularVelocityVector) + relativeVelocity ) *
relativePositionUnitVector.transpose( ) -
linear_algebra::getCrossProductMatrix( planetAngularVelocityVector ) ) );
}
//! Function to compute partial derivative of direct tidal acceleration due to tide on planet w.r.t. velocity of satellite/
Eigen::Matrix3d computeDirectTidalAccelerationDueToTideOnPlanetWrtVelocity(
const Eigen::Vector6d relativeStateOfBodyExertingTide, const double currentTidalAccelerationMultiplier,
const double timeLag )
{
Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 );
Eigen::Vector3d relativePositionUnitVector = relativePosition.normalized( );
return currentTidalAccelerationMultiplier * timeLag *
( 2.0 * relativePositionUnitVector * relativePositionUnitVector.transpose( ) +
Eigen::Matrix3d::Identity( ) );
}
//! Function to compute partial derivative of direct tidal acceleration due to tide on satellite w.r.t. position of satellite
Eigen::Matrix3d computeDirectTidalAccelerationDueToTideOnSatelliteWrtPosition(
const Eigen::Vector6d relativeStateOfBodyExertingTide,
const double currentTidalAccelerationMultiplier, const double timeLag, const bool includeDirectRadialComponent )
{
Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 );
Eigen::Vector3d relativePositionUnitVector = relativePosition.normalized( );
Eigen::Vector3d relativeVelocity = relativeStateOfBodyExertingTide.segment( 3, 3 );
double positionVelocityInnerProduct = relativePosition.dot( relativeVelocity );
double distance = relativePosition.norm( );
double distanceSquared = distance * distance;
double radialComponentMultiplier = ( includeDirectRadialComponent == true ) ? 1.0 : 0.0;
return currentTidalAccelerationMultiplier * (
2.0 * radialComponentMultiplier * (
Eigen::Matrix3d::Identity( ) - 8.0 * relativePositionUnitVector * relativePositionUnitVector.transpose( ) ) +
timeLag * 3.5 * ( -20.0 * positionVelocityInnerProduct *
relativePositionUnitVector * relativePositionUnitVector.transpose( ) / distanceSquared +
2.0 / distanceSquared * ( Eigen::Matrix3d::Identity( ) * positionVelocityInnerProduct +
relativePosition * relativeVelocity.transpose( ) ) ) );
}
//! Function to compute partial derivative of direct tidal acceleration due to tide on satellite w.r.t. velocity of satellite
Eigen::Matrix3d computeDirectTidalAccelerationDueToTideOnSatelliteWrtVelocity(
const Eigen::Vector6d relativeStateOfBodyExertingTide, const double currentTidalAccelerationMultiplier,
const double timeLag )
{
Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 );
Eigen::Vector3d relativePositionUnitVector = relativePosition.normalized( );
return currentTidalAccelerationMultiplier * timeLag * 3.5 *
( 2.0 * relativePositionUnitVector * relativePositionUnitVector.transpose( ) );
}
//! Function for setting up and retrieving a function returning a partial w.r.t. a double parameter.
std::pair< std::function< void( Eigen::MatrixXd& ) >, int >
DirectTidalDissipationAccelerationPartial::getParameterPartialFunction(
std::shared_ptr< estimatable_parameters::EstimatableParameter< double > > parameter )
{
std::pair< std::function< void( Eigen::MatrixXd& ) >, int > partialFunctionPair;
// Check dependencies.
if( parameter->getParameterName( ).first == estimatable_parameters::gravitational_parameter )
{
// If parameter is gravitational parameter, check and create dependency function .
partialFunctionPair = this->getGravitationalParameterPartialFunction( parameter->getParameterName( ) );
}
else if( parameter->getParameterName( ).first == estimatable_parameters::direct_dissipation_tidal_time_lag )
{
if( ( parameter->getParameterName( ).second.first == acceleratingBody_ ) &&
tidalAcceleration_->getModelTideOnPlanet( ) )
{
std::shared_ptr< estimatable_parameters::DirectTidalTimeLag > timeLagParameter =
std::dynamic_pointer_cast< estimatable_parameters::DirectTidalTimeLag >( parameter );
if( timeLagParameter == nullptr )
{
throw std::runtime_error( "Error when getting partial of DirectTidalDissipationAcceleration w.r.t. DirectTidalTimeLag, models are inconsistent" );
}
else
{
std::vector< std::string > bodiesCausingDeformation = timeLagParameter->getBodiesCausingDeformation( );
if( bodiesCausingDeformation.size( ) == 0 || (
std::find( bodiesCausingDeformation.begin( ), bodiesCausingDeformation.end( ), acceleratedBody_ ) !=
bodiesCausingDeformation.end( ) ) )
{
partialFunctionPair = std::make_pair(
std::bind( &DirectTidalDissipationAccelerationPartial::wrtTidalTimeLag, this, std::placeholders::_1 ), 1 );
}
}
}
else if( ( parameter->getParameterName( ).second.first == acceleratedBody_ ) &&
!tidalAcceleration_->getModelTideOnPlanet( ) )
{
std::shared_ptr< estimatable_parameters::DirectTidalTimeLag > timeLagParameter =
std::dynamic_pointer_cast< estimatable_parameters::DirectTidalTimeLag >( parameter );
if( timeLagParameter == nullptr )
{
throw std::runtime_error( "Error when getting partial of DirectTidalDissipationAcceleration w.r.t. DirectTidalTimeLag, models are inconsistent" );
}
else
{
std::vector< std::string > bodiesCausingDeformation = timeLagParameter->getBodiesCausingDeformation( );
if( bodiesCausingDeformation.size( ) == 0 || (
std::find( bodiesCausingDeformation.begin( ), bodiesCausingDeformation.end( ), acceleratingBody_ ) !=
bodiesCausingDeformation.end( ) ) )
{
partialFunctionPair = std::make_pair(
std::bind( &DirectTidalDissipationAccelerationPartial::wrtTidalTimeLag, this, std::placeholders::_1 ), 1 );
}
}
}
}
else
{
partialFunctionPair = std::make_pair( std::function< void( Eigen::MatrixXd& ) >( ), 0 );
}
return partialFunctionPair;
}
void DirectTidalDissipationAccelerationPartial::update( const double currentTime )
{
tidalAcceleration_->updateMembers( currentTime );
if( !( currentTime_ == currentTime ) )
{
currentRelativeBodyState_ = tidalAcceleration_->getCurrentRelativeState( );
if( tidalAcceleration_->getModelTideOnPlanet( ) )
{
currentPartialWrtPosition_ = computeDirectTidalAccelerationDueToTideOnPlanetWrtPosition(
currentRelativeBodyState_,
tidalAcceleration_->getCurrentAngularVelocityVectorOfBodyUndergoingTide( ),
tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ),
tidalAcceleration_->getTimeLag( ), tidalAcceleration_->getIncludeDirectRadialComponent( ) );
currentPartialWrtVelocity_ = computeDirectTidalAccelerationDueToTideOnPlanetWrtVelocity(
currentRelativeBodyState_, tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ),
tidalAcceleration_->getTimeLag( ) );
}
else
{
currentPartialWrtPosition_ = computeDirectTidalAccelerationDueToTideOnSatelliteWrtPosition(
currentRelativeBodyState_, tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ),
tidalAcceleration_->getTimeLag( ), tidalAcceleration_->getIncludeDirectRadialComponent( ) );
currentPartialWrtVelocity_ = computeDirectTidalAccelerationDueToTideOnSatelliteWrtVelocity(
currentRelativeBodyState_, tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ),
tidalAcceleration_->getTimeLag( ) );
}
currentTime_ = currentTime;
}
}
//! Function to create a function returning the current partial w.r.t. a gravitational parameter.
std::pair< std::function< void( Eigen::MatrixXd& ) >, int >
DirectTidalDissipationAccelerationPartial::getGravitationalParameterPartialFunction(
const estimatable_parameters::EstimatebleParameterIdentifier& parameterId )
{
std::function< void( Eigen::MatrixXd& ) > partialFunction;
int numberOfColumns = 0;
// Check if parameter is gravitational parameter.
if( parameterId.first == estimatable_parameters::gravitational_parameter )
{
// Check if parameter body is central body.
if( parameterId.second.first == acceleratingBody_ )
{
if( !tidalAcceleration_->getModelTideOnPlanet( ) )
{
partialFunction = std::bind( &DirectTidalDissipationAccelerationPartial::wrtGravitationalParameterOfPlanet,
this, std::placeholders::_1 );
numberOfColumns = 1;
}
}
// Check if parameter body is accelerated body, and if the mutual acceleration is used.
if( parameterId.second.first == acceleratedBody_ )
{
partialFunction = std::bind( &DirectTidalDissipationAccelerationPartial::wrtGravitationalParameterOfSatellite,
this, std::placeholders::_1 );
numberOfColumns = 1;
}
}
return std::make_pair( partialFunction, numberOfColumns );
}
//! Function to calculate central gravity partial w.r.t. central body gravitational parameter
void DirectTidalDissipationAccelerationPartial::wrtGravitationalParameterOfPlanet( Eigen::MatrixXd& gravitationalParameterPartial )
{
gravitationalParameterPartial.block( 0, 0, 3, 1 ) = tidalAcceleration_->getAcceleration( ) *
2.0 / tidalAcceleration_->getGravitationalParameterFunctionOfBodyExertingTide( )( );
}
//! Function to compute derivative w.r.t. gravitational parameter of satellite
void DirectTidalDissipationAccelerationPartial::wrtGravitationalParameterOfSatellite( Eigen::MatrixXd& gravitationalParameterPartial )
{
gravitationalParameterPartial.block( 0, 0, 3, 1 ) = -tidalAcceleration_->getAcceleration( ) /
tidalAcceleration_->getGravitationalParameterFunctionOfBodyUndergoingTide( )( );
if( tidalAcceleration_->getModelTideOnPlanet( ) )
{
gravitationalParameterPartial *= -1.0;
}
}
//! Function to compute derivative w.r.t. tidal time lag parameter.
void DirectTidalDissipationAccelerationPartial::wrtTidalTimeLag( Eigen::MatrixXd& timeLagPartial )
{
if( !tidalAcceleration_->getModelTideOnPlanet( ) )
{
timeLagPartial = gravitation::computeDirectTidalAccelerationDueToTideOnSatellite(
tidalAcceleration_->getCurrentRelativeState( ),
tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ), 1.0, false );
}
else
{
timeLagPartial = gravitation::computeDirectTidalAccelerationDueToTideOnPlanet(
tidalAcceleration_->getCurrentRelativeState( ), tidalAcceleration_->getCurrentAngularVelocityVectorOfBodyUndergoingTide( ),
tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ), 1.0, false );
}
}
}
}
| 53.04 | 163 | 0.67222 | sebranchett |
9c2633e8271987c1198734d2c376e5426524abb9 | 1,648 | cpp | C++ | code/texturanalysis.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 8 | 2020-02-21T22:21:01.000Z | 2022-02-16T05:30:54.000Z | code/texturanalysis.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | null | null | null | code/texturanalysis.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 3 | 2020-08-05T05:42:35.000Z | 2021-08-30T05:39:51.000Z | #define _USE_MATH_DEFINES
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <unordered_map>
#define EPSILON 0.00001
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll i, j, k;
ll whiteSpace;
ll stepper;
ll caseNum = 1;
string texture;
bool even;
while(cin >> texture && texture != "END")
{
even = true;
if(texture.size() == 1)
{
cout << caseNum << " EVEN\n";
caseNum++;
continue;
}
else
{
stepper = 1;
while(texture[stepper] != '*')
{
stepper++;
}
whiteSpace = stepper;
}
for(i = 0; i < texture.size(); i++)
{
if(whiteSpace != 0 && i % whiteSpace != 0)
{
if (texture[i] != '.')
{
even = false;
}
}
else
{
if (texture[i] != '*')
{
even = false;
}
}
}
cout << caseNum << " ";
if(even)
{
cout << "EVEN\n";
}
else
{
cout << "NOT EVEN\n";
}
caseNum++;
}
return 0;
}
| 18.942529 | 54 | 0.418689 | matthewReff |
9c26a39d5606a2d8fc0213a969ff68daa4b1dacf | 2,121 | hpp | C++ | cppcache/src/TimeoutTimer.hpp | vaijira/geode-native | 5a46b659b86ecc4890df59c1b7abe727192e5d06 | [
"Apache-2.0"
] | null | null | null | cppcache/src/TimeoutTimer.hpp | vaijira/geode-native | 5a46b659b86ecc4890df59c1b7abe727192e5d06 | [
"Apache-2.0"
] | null | null | null | cppcache/src/TimeoutTimer.hpp | vaijira/geode-native | 5a46b659b86ecc4890df59c1b7abe727192e5d06 | [
"Apache-2.0"
] | null | null | null | #pragma once
#ifndef GEODE_TIMEOUTTIMER_H_
#define GEODE_TIMEOUTTIMER_H_
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <geode/internal/geode_globals.hpp>
#include <ace/Condition_Recursive_Thread_Mutex.h>
#include <ace/Condition_T.h>
#include <ace/Guard_T.h>
#include <ace/Time_Value.h>
#include <ace/OS_NS_sys_time.h>
namespace apache {
namespace geode {
namespace client {
class APACHE_GEODE_EXPORT TimeoutTimer {
private:
ACE_Recursive_Thread_Mutex m_mutex;
ACE_Condition<ACE_Recursive_Thread_Mutex> m_cond;
volatile bool m_reset;
public:
TimeoutTimer() : m_mutex(), m_cond(m_mutex), m_reset(false) {}
/**
* Return only after seconds have passed without receiving a reset.
*/
void untilTimeout(int seconds) {
ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);
ACE_OS::last_error(0);
while ((ACE_OS::last_error() != ETIME) || m_reset) {
m_reset = false;
ACE_Time_Value stopTime = ACE_OS::gettimeofday();
stopTime += seconds;
ACE_OS::last_error(0);
m_cond.wait(&stopTime);
}
}
/**
* Reset the timeout interval so that it restarts now.
*/
void reset() {
ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);
// m_cond.signal();
m_reset = true;
}
};
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_TIMEOUTTIMER_H_
| 28.662162 | 75 | 0.726073 | vaijira |
9c2b25a05445cbd4fb817c64503b949df9959a2e | 17,176 | cpp | C++ | protoc_plugin/main.cpp | FrancoisChabot/easy_grpc | d811e63fa022e1030a086e38945f4000b947d9af | [
"Apache-2.0"
] | 26 | 2019-06-09T02:00:00.000Z | 2022-02-16T08:08:58.000Z | protoc_plugin/main.cpp | FrancoisChabot/easy_grpc | d811e63fa022e1030a086e38945f4000b947d9af | [
"Apache-2.0"
] | 13 | 2019-05-28T02:05:23.000Z | 2019-07-10T20:21:12.000Z | protoc_plugin/main.cpp | FrancoisChabot/easy_grpc | d811e63fa022e1030a086e38945f4000b947d9af | [
"Apache-2.0"
] | 4 | 2019-06-08T11:30:38.000Z | 2020-05-17T04:45:37.000Z | #include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <filesystem>
#include <functional>
using google::protobuf::Descriptor;
using google::protobuf::FileDescriptor;
using google::protobuf::MethodDescriptor;
using google::protobuf::ServiceDescriptor;
using google::protobuf::compiler::CodeGenerator;
using google::protobuf::compiler::GeneratorContext;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using std::filesystem::path;
const char* header_extension = ".egrpc.pb.h";
const char* source_extension = ".egrpc.pb.cc";
const char* pb_header_extension = ".pb.h";
enum class Method_mode {
UNARY,
CLIENT_STREAM,
SERVER_STREAM,
BIDIR_STREAM
};
Method_mode get_mode(const MethodDescriptor* method) {
bool c_stream = method->client_streaming();
bool s_stream = method->server_streaming();
if(c_stream && s_stream) {
return Method_mode::BIDIR_STREAM;
}
if(c_stream) {
return Method_mode::CLIENT_STREAM;
}
if(s_stream) {
return Method_mode::SERVER_STREAM;
}
return Method_mode::UNARY;
}
// Obtain the fully-qualified type name for a given descriptor.
std::string class_name(const Descriptor* desc) {
auto outer = desc;
while (outer->containing_type()) {
outer = outer->containing_type();
}
auto outer_name = outer->full_name();
auto inner_name = desc->full_name().substr(outer_name.size());
std::ostringstream result;
result << "::";
for (auto& c : outer_name) {
if (c == '.') {
result << "::";
} else {
result << c;
}
}
for (auto& c : inner_name) {
if (c == '.') {
result << "_";
} else {
result << c;
}
}
return result.str();
}
std::string header_guard(std::string_view file_name) {
std::ostringstream result;
for (auto c : file_name) {
if (std::isalnum(c)) {
result << c;
} else {
result << std::hex << int(c);
}
}
return result.str();
}
std::vector<std::string> tokenize(const std::string& str, char c) {
std::vector<std::string> result;
if (!str.empty()) {
auto current = 0;
auto next = str.find(c);
while (next != std::string::npos) {
result.push_back(str.substr(current, next-current));
current = next + 1;
next = str.find(c, current);
}
if (current != next) {
result.push_back(str.substr(current, next));
}
}
return result;
}
std::vector<std::string> package_parts(const FileDescriptor* file) {
return tokenize(file->package(), '.');
}
void generate_service_header(const ServiceDescriptor* service,
std::ostream& dst) {
auto name = service->name();
auto full_name = service->full_name();
auto method_name_cste = [&](auto method) {
return std::string("k") + name + "_" + method->name() + "_name";
};
dst << "class " << service->name() << " {\n"
<< "public:\n"
<< " using service_type = " << name << ";\n\n"
<< " virtual ~" << name << "() {}\n\n";
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
dst << " static const char * " << method_name_cste(method) << ";\n";
}
dst << "\n";
// Print out the compile-time helper functions
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
auto input = method->input_type();
auto output = method->output_type();
switch(get_mode(method)) {
case Method_mode::UNARY:
dst << " virtual ::easy_grpc::Future<" << class_name(output) << "> "
<< method->name() << "(" << class_name(input) << ") = 0;\n";
break;
case Method_mode::CLIENT_STREAM:
dst << " virtual ::easy_grpc::Future<" << class_name(output) << "> "
<< method->name() << "(::easy_grpc::Stream_future<" << class_name(input) << ">) = 0;\n";
break;
case Method_mode::SERVER_STREAM:
dst << " virtual ::easy_grpc::Stream_future<" << class_name(output) << "> " << method->name() << "(" << class_name(input) << ") = 0;\n";
break;
case Method_mode::BIDIR_STREAM:
dst << " virtual ::easy_grpc::Stream_future<" << class_name(output) << "> " << method->name() << "(::easy_grpc::Stream_future<" << class_name(input) << ">) = 0;\n";
break;
}
}
dst << "\n";
dst << " class Stub_interface {\n"
<< " public:\n"
<< " virtual ~Stub_interface() {}\n\n";
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
auto input = method->input_type();
auto output = method->output_type();
switch(get_mode(method)) {
case Method_mode::UNARY:
dst << " virtual ::easy_grpc::Future<" << class_name(output) << "> "
<< method->name() << "(" << class_name(input)
<< ", ::easy_grpc::client::Call_options={}) = 0;\n";
break;
case Method_mode::CLIENT_STREAM:
dst << " virtual std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Future<" << class_name(output) << ">> "
<< method->name() << "(::easy_grpc::client::Call_options={}) = 0;\n";
break;
case Method_mode::SERVER_STREAM:
dst << " virtual ::easy_grpc::Stream_future<" << class_name(output) << "> "
<< method->name() << "(" << class_name(input)
<< ", ::easy_grpc::client::Call_options={}) = 0;\n";
break;
case Method_mode::BIDIR_STREAM:
dst << " virtual std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Stream_future<" << class_name(output) << ">> "
<< method->name() << "(::easy_grpc::client::Call_options={}) = 0;\n";
break;
}
}
dst << " };\n\n";
dst << " class Stub final : public Stub_interface {\n"
<< " public:\n"
<< " Stub(::easy_grpc::client::Channel*, "
"::easy_grpc::Completion_queue* = nullptr);\n\n";
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
auto input = method->input_type();
auto output = method->output_type();
switch(get_mode(method)) {
case Method_mode::UNARY:
dst << " ::easy_grpc::Future<" << class_name(output) << "> "
<< method->name() << "(" << class_name(input)
<< ", ::easy_grpc::client::Call_options={}) override;\n";
break;
case Method_mode::CLIENT_STREAM:
dst << " std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Future<" << class_name(output) << ">> "
<< method->name() << "(::easy_grpc::client::Call_options={}) override;\n";
break;
case Method_mode::SERVER_STREAM:
dst << " ::easy_grpc::Stream_future<" << class_name(output) << "> "
<< method->name() << "(" << class_name(input)
<< ", ::easy_grpc::client::Call_options={}) override;\n";
break;
case Method_mode::BIDIR_STREAM:
dst << " std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Stream_future<" << class_name(output) << ">> "
<< method->name() << "(::easy_grpc::client::Call_options={}) override;\n";
break;
}
}
dst << "\n"
<< " private:\n"
<< " ::easy_grpc::client::Channel* channel_;\n"
<< " ::easy_grpc::Completion_queue* default_queue_;\n\n";
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
dst << " void* " << method->name() << "_tag_;\n";
}
dst << " };\n\n";
dst << " template<typename ImplT>\n"
<< " static ::easy_grpc::server::Service_config get_config(ImplT& impl) {\n"
<< " ::easy_grpc::server::Service_config result(\""<< full_name <<"\");\n\n";
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
auto input = method->input_type();
auto output = method->output_type();
switch(get_mode(method)) {
case Method_mode::UNARY:
dst << " result.add_method("
<< method_name_cste(method) << ", [&impl](" << class_name(input) << " req){return impl." << method->name() << "(std::move(req));});\n";
break;
case Method_mode::CLIENT_STREAM:
dst << " result.add_method("
<< method_name_cste(method) << ", [&impl](::easy_grpc::Stream_future<" << class_name(input) << "> req){return impl." << method->name() << "(std::move(req));});\n";
break;
case Method_mode::SERVER_STREAM:
dst << " result.add_method("
<< method_name_cste(method) << ", [&impl](" << class_name(input) << " req){return impl." << method->name() << "(std::move(req));});\n";
break;
case Method_mode::BIDIR_STREAM:
dst << " result.add_method("
<< method_name_cste(method) << ", [&impl](::easy_grpc::Stream_future<" << class_name(input) << "> req){return impl." << method->name() << "(std::move(req));});\n";
break;
}
}
dst << "\n return result;\n";
dst << " }\n";
dst << "};\n\n";
}
void generate_service_source(const ServiceDescriptor* service,
std::ostream& dst) {
auto name = service->name();
dst << "// ********** " << name << " ********** //\n\n";
auto method_name_cste = [&](auto method) {
return std::string("k") + name + "_" + method->name() + "_name";
};
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
dst << "const char* " << name << "::" << method_name_cste(method) << " = \"/"
<< service->file()->package() << "." << name << "/" << method->name()
<< "\";\n";
}
dst << "\n";
dst << name
<< "::Stub::Stub(::easy_grpc::client::Channel* c, "
"::easy_grpc::Completion_queue* default_queue)\n"
<< " : channel_(c), default_queue_(default_queue ? default_queue : "
"c->default_queue())";
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
dst << "\n , " << method->name() << "_tag_(c->register_method("
<< method_name_cste(method) << "))";
}
dst << " {}\n\n";
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
auto input = method->input_type();
auto output = method->output_type();
dst << "// " << method->name() << "\n";
switch(get_mode(method)) {
case Method_mode::UNARY:
dst << "::easy_grpc::Future<" << class_name(output) << "> " << name
<< "::Stub::" << method->name() << "(" << class_name(input)
<< " req, ::easy_grpc::client::Call_options options) {\n"
<< " if(!options.completion_queue) { options.completion_queue = "
"default_queue_; }\n"
<< " return ::easy_grpc::client::start_unary_call<"
<< class_name(output) << ">(channel_, " << method->name()
<< "_tag_, std::move(req), std::move(options));\n"
<< "}\n\n";
break;
case Method_mode::CLIENT_STREAM:
dst << "std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Future<" << class_name(output) << ">> "
<< name << "::Stub::" << method->name() << "(::easy_grpc::client::Call_options options) {\n";
dst << " if(!options.completion_queue) { options.completion_queue = "
"default_queue_; }\n"
<< " return ::easy_grpc::client::start_client_streaming_call<" << class_name(output) << ", "
<< class_name(input) << ">(channel_, " << method->name()
<< "_tag_, std::move(options));\n"
<< "}\n\n";
break;
case Method_mode::SERVER_STREAM:
dst << "::easy_grpc::Stream_future<" << class_name(output) << "> " << name
<< "::Stub::" << method->name() << "(" << class_name(input)
<< " req, ::easy_grpc::client::Call_options options) {\n"
<< " if(!options.completion_queue) { options.completion_queue = "
"default_queue_; }\n"
<< " return ::easy_grpc::client::start_server_streaming_call<"
<< class_name(output) << ">(channel_, " << method->name()
<< "_tag_, std::move(req), std::move(options));\n"
<< "}\n\n";
break;
case Method_mode::BIDIR_STREAM:
dst << "std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Stream_future<" << class_name(output) << ">> " << name
<< "::Stub::" << method->name() << "(::easy_grpc::client::Call_options options) {\n"
<< " if(!options.completion_queue) { options.completion_queue = "
"default_queue_; }\n"
<< " return ::easy_grpc::client::start_bidir_streaming_call<"
<< class_name(output) << ", " << class_name(input) << ">(channel_, " << method->name()
<< "_tag_, std::move(options));\n"
<< "}\n\n";
break;
}
}
}
std::string generate_header(const FileDescriptor* file) {
std::ostringstream result;
auto file_name = path(file->name()).stem().string();
// Prologue
result << "// This code was generated by the easy_grpc protoc plugin.\n"
<< "#ifndef EASY_GRPC_" << header_guard(file_name) << "_INCLUDED_H\n"
<< "#define EASY_GRPC_" << header_guard(file_name) << "_INCLUDED_H\n"
<< "\n";
// Headers
result << "#include \"" << file_name << pb_header_extension << "\""
<< "\n\n";
result << "#include \"easy_grpc/ext_protobuf/gen_support.h\""
<< "\n\n";
result << "#include <memory>\n\n";
// namespace
auto package = package_parts(file);
if (!package.empty()) {
for (const auto& p : package) {
result << "namespace " << p << " {\n";
}
result << "\n";
}
// Services
for (int i = 0; i < file->service_count(); ++i) {
generate_service_header(file->service(i), result);
}
// Epilogue
if (!package.empty()) {
for (const auto& p : package) {
result << "} // namespace" << p << "\n";
}
result << "\n";
}
result << "#endif\n";
return result.str();
}
std::string generate_source(const FileDescriptor* file) {
std::ostringstream result;
auto file_name = path(file->name()).stem().string();
// Prologue
result << "// This code was generated by the easy_grpc protoc plugin.\n\n";
// Headers
result << "#include \"" << file_name << header_extension << "\""
<< "\n\n";
// namespace
auto package = package_parts(file);
if (!package.empty()) {
for (const auto& p : package) {
result << "namespace " << p << " {\n";
}
result << "\n";
}
// Services
for (int i = 0; i < file->service_count(); ++i) {
generate_service_source(file->service(i), result);
}
// Epilogue
if (!package.empty()) {
for (const auto& p : package) {
result << "} // namespace" << p << "\n";
}
result << "\n";
}
return result.str();
}
class Generator : public CodeGenerator {
public:
// Generates code for the given proto file, generating one or more files in
// the given output directory.
//
// A parameter to be passed to the generator can be specified on the command
// line. This is intended to be used to pass generator specific parameters.
// It is empty if no parameter was given. ParseGeneratorParameter (below),
// can be used to accept multiple parameters within the single parameter
// command line flag.
//
// Returns true if successful. Otherwise, sets *error to a description of
// the problem (e.g. "invalid parameter") and returns false.
bool Generate(const FileDescriptor* file, const std::string& parameter,
GeneratorContext* context, std::string* error) const override {
try {
auto file_name = path(file->name()).stem().string();
{
auto header_data = generate_header(file);
std::unique_ptr<ZeroCopyOutputStream> header_dst{
context->Open(file_name + header_extension)};
CodedOutputStream header_out(header_dst.get());
header_out.WriteRaw(header_data.data(), header_data.size());
}
{
auto src_data = generate_source(file);
std::unique_ptr<ZeroCopyOutputStream> src_dst{
context->Open(file_name + source_extension)};
CodedOutputStream src_out(src_dst.get());
src_out.WriteRaw(src_data.data(), src_data.size());
}
} catch (std::exception& e) {
*error = e.what();
return false;
}
return true;
}
};
int main(int argc, char* argv[]) {
Generator generator;
::google::protobuf::compiler::PluginMain(argc, argv, &generator);
} | 34.629032 | 174 | 0.55694 | FrancoisChabot |
9c2ba419c96951cf61cbd815930d9c9460333a1c | 6,838 | cpp | C++ | src/common/meta/GflagsManager.cpp | wenhaocs/nebula | 326b856cdf44fcaf67d3883073dc9412a9e3eebd | [
"Apache-2.0"
] | null | null | null | src/common/meta/GflagsManager.cpp | wenhaocs/nebula | 326b856cdf44fcaf67d3883073dc9412a9e3eebd | [
"Apache-2.0"
] | null | null | null | src/common/meta/GflagsManager.cpp | wenhaocs/nebula | 326b856cdf44fcaf67d3883073dc9412a9e3eebd | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2019 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include "common/meta/GflagsManager.h"
#include "common/conf/Configuration.h"
#include "common/fs/FileUtils.h"
DEFINE_string(gflags_mode_json, "share/resources/gflags.json", "gflags mode json for service");
namespace nebula {
namespace meta {
Value GflagsManager::gflagsValueToValue(const std::string& type, const std::string& flagValue) {
// all int32/uint32/uint64 gflags are converted to int64 for now
folly::StringPiece view(type);
if (view.startsWith("int") || view.startsWith("uint")) {
return Value(folly::to<int64_t>(flagValue));
} else if (type == "double") {
return Value(folly::to<double>(flagValue));
} else if (type == "bool") {
return Value(folly::to<bool>(flagValue));
} else if (type == "string") {
return Value(folly::to<std::string>(flagValue));
} else if (type == "map") {
auto value = Value(folly::to<std::string>(flagValue));
VLOG(1) << "Nested value: " << value;
// transform to map value
conf::Configuration conf;
auto status = conf.parseFromString(value.getStr());
if (!status.ok()) {
LOG(ERROR) << "Parse value: " << value << " failed: " << status;
return Value::kNullValue;
}
Map map;
conf.forEachItem([&map](const std::string& key, const folly::dynamic& val) {
map.kvs.emplace(key, val.asString());
});
value.setMap(std::move(map));
return value;
}
LOG(WARNING) << "Unknown type: " << type;
return Value::kEmpty;
}
std::unordered_map<std::string, std::pair<cpp2::ConfigMode, bool>> GflagsManager::parseConfigJson(
const std::string& path) {
// The default conf for gflags flags mode
std::unordered_map<std::string, std::pair<cpp2::ConfigMode, bool>> configModeMap{
{"max_edge_returned_per_vertex", {cpp2::ConfigMode::MUTABLE, false}},
{"minloglevel", {cpp2::ConfigMode::MUTABLE, false}},
{"v", {cpp2::ConfigMode::MUTABLE, false}},
{"heartbeat_interval_secs", {cpp2::ConfigMode::MUTABLE, false}},
{"agent_heartbeat_interval_secs", {cpp2::ConfigMode::MUTABLE, false}},
{"meta_client_retry_times", {cpp2::ConfigMode::MUTABLE, false}},
{"wal_ttl", {cpp2::ConfigMode::MUTABLE, false}},
{"clean_wal_interval_secs", {cpp2::ConfigMode::MUTABLE, false}},
{"custom_filter_interval_secs", {cpp2::ConfigMode::MUTABLE, false}},
{"accept_partial_success", {cpp2::ConfigMode::MUTABLE, false}},
{"rocksdb_db_options", {cpp2::ConfigMode::MUTABLE, true}},
{"rocksdb_column_family_options", {cpp2::ConfigMode::MUTABLE, true}},
{"rocksdb_block_based_table_options", {cpp2::ConfigMode::MUTABLE, true}},
};
conf::Configuration conf;
if (!conf.parseFromFile(path).ok()) {
LOG(ERROR) << "Load gflags json failed";
return configModeMap;
}
static std::vector<std::string> keys = {"MUTABLE"};
static std::vector<cpp2::ConfigMode> modes = {cpp2::ConfigMode::MUTABLE};
for (size_t i = 0; i < keys.size(); i++) {
std::vector<std::string> values;
if (!conf.fetchAsStringArray(keys[i].c_str(), values).ok()) {
continue;
}
cpp2::ConfigMode mode = modes[i];
for (const auto& name : values) {
configModeMap[name] = {mode, false};
}
}
static std::string nested = "NESTED";
std::vector<std::string> values;
if (conf.fetchAsStringArray(nested.c_str(), values).ok()) {
for (const auto& name : values) {
// all nested gflags regard as mutable ones
configModeMap[name] = {cpp2::ConfigMode::MUTABLE, true};
}
}
return configModeMap;
}
std::vector<cpp2::ConfigItem> GflagsManager::declareGflags(const cpp2::ConfigModule& module) {
std::vector<cpp2::ConfigItem> configItems;
if (module == cpp2::ConfigModule::UNKNOWN) {
return configItems;
}
auto mutableConfig = parseConfigJson(FLAGS_gflags_mode_json);
// Get all flags by listing all defined gflags
std::vector<gflags::CommandLineFlagInfo> flags;
gflags::GetAllFlags(&flags);
for (auto& flag : flags) {
auto& name = flag.name;
auto type = flag.type;
// We only register mutable configs to meta
cpp2::ConfigMode mode = cpp2::ConfigMode::MUTABLE;
auto iter = mutableConfig.find(name);
if (iter != mutableConfig.end()) {
// isNested
if (iter->second.second) {
type = "map";
}
} else {
continue;
}
Value value = gflagsValueToValue(type, flag.current_value);
if (value.empty()) {
LOG(INFO) << "Not able to declare " << name << " of " << flag.type;
continue;
}
if (value.isNull()) {
LOG(ERROR) << "Parse gflags: " << name << ", value: " << flag.current_value << " failed.";
continue;
}
cpp2::ConfigItem item;
item.name_ref() = name;
item.module_ref() = module;
item.mode_ref() = mode;
item.value_ref() = std::move(value);
configItems.emplace_back(std::move(item));
}
LOG(INFO) << "Prepare to register " << configItems.size() << " gflags to meta";
return configItems;
}
void GflagsManager::getGflagsModule(cpp2::ConfigModule& gflagsModule) {
// get current process according to gflags pid_file
gflags::CommandLineFlagInfo pid;
if (gflags::GetCommandLineFlagInfo("pid_file", &pid)) {
auto defaultPid = pid.default_value;
if (defaultPid.find("nebula-graphd") != std::string::npos) {
gflagsModule = cpp2::ConfigModule::GRAPH;
} else if (defaultPid.find("nebula-storaged") != std::string::npos) {
gflagsModule = cpp2::ConfigModule::STORAGE;
} else if (defaultPid.find("nebula-metad") != std::string::npos) {
gflagsModule = cpp2::ConfigModule::META;
} else {
LOG(ERROR) << "Should not reach here";
}
} else {
LOG(INFO) << "Unknown config module";
}
}
std::string GflagsManager::ValueToGflagString(const Value& val) {
switch (val.type()) {
case Value::Type::BOOL: {
return val.getBool() ? "true" : "false";
}
case Value::Type::INT: {
return folly::to<std::string>(val.getInt());
}
case Value::Type::FLOAT: {
return folly::to<std::string>(val.getFloat());
}
case Value::Type::STRING: {
return val.getStr();
}
case Value::Type::MAP: {
auto& kvs = val.getMap().kvs;
std::vector<std::string> values(kvs.size());
std::transform(kvs.begin(), kvs.end(), values.begin(), [](const auto& iter) -> std::string {
std::stringstream out;
out << "\"" << iter.first << "\""
<< ":"
<< "\"" << iter.second << "\"";
return out.str();
});
std::stringstream os;
os << "{" << folly::join(",", values) << "}";
return os.str();
}
default: {
LOG(FATAL) << "Unsupported type for gflags";
}
}
}
} // namespace meta
} // namespace nebula
| 34.887755 | 98 | 0.630301 | wenhaocs |
9c2c0ff0cc5390f799834059af174f87aa59e277 | 3,288 | cpp | C++ | src/qt/veil/veilstatusbar.cpp | Oilplik/veil-1 | 852b05b255b464201de53fe7afdf7c696ed50724 | [
"MIT"
] | null | null | null | src/qt/veil/veilstatusbar.cpp | Oilplik/veil-1 | 852b05b255b464201de53fe7afdf7c696ed50724 | [
"MIT"
] | null | null | null | src/qt/veil/veilstatusbar.cpp | Oilplik/veil-1 | 852b05b255b464201de53fe7afdf7c696ed50724 | [
"MIT"
] | null | null | null | #include <qt/veil/veilstatusbar.h>
#include <qt/veil/forms/ui_veilstatusbar.h>
#include <qt/bitcoingui.h>
#include <qt/walletmodel.h>
#include <qt/veil/qtutils.h>
#include <iostream>
VeilStatusBar::VeilStatusBar(QWidget *parent, BitcoinGUI* gui) :
QWidget(parent),
mainWindow(gui),
ui(new Ui::VeilStatusBar)
{
ui->setupUi(this);
ui->checkStacking->setProperty("cssClass" , "switch");
connect(ui->btnLock, SIGNAL(clicked()), this, SLOT(onBtnLockClicked()));
connect(ui->btnSync, SIGNAL(clicked()), this, SLOT(onBtnSyncClicked()));
connect(ui->checkStacking, SIGNAL(toggled(bool)), this, SLOT(onCheckStakingClicked(bool)));
}
bool VeilStatusBar::getSyncStatusVisible() {
return ui->btnSync->isVisible();
}
void VeilStatusBar::updateSyncStatus(QString status){
ui->btnSync->setText(status);
}
void VeilStatusBar::setSyncStatusVisible(bool fVisible) {
ui->btnSync->setVisible(fVisible);
}
void VeilStatusBar::onBtnSyncClicked(){
mainWindow->showModalOverlay();
}
bool fBlockNextStakeCheckSignal = false;
void VeilStatusBar::onCheckStakingClicked(bool res) {
// When our own dialog internally changes the checkstate, block signal from executing
if (fBlockNextStakeCheckSignal) {
fBlockNextStakeCheckSignal = false;
return;
}
// Miner thread starts in init.cpp, but staking enabled flag is checked each iteration of the miner, so can be enabled or disabled here
WalletModel::EncryptionStatus lockState = walletModel->getEncryptionStatus();
if (res){
if (gArgs.GetBoolArg("-exchangesandservicesmode", false) || lockState == WalletModel::Locked) {
QString dialogMsg = gArgs.GetBoolArg("-exchangesandservicesmode", false) ? "Staking is disabled in exchange mode" : "Must unlock wallet before staking can be enabled";
openToastDialog(dialogMsg, mainWindow);
fBlockNextStakeCheckSignal = true;
ui->checkStacking->setCheckState(Qt::CheckState::Unchecked);
}
} else {
openToastDialog("Miner stopped", mainWindow);
}
if (!gArgs.GetBoolArg("-exchangesandservicesmode", false) && lockState != WalletModel::Locked)
this->walletModel->setStakingEnabled(res);
}
bool fBlockNextBtnLockSignal = false;
void VeilStatusBar::onBtnLockClicked()
{
// When our own dialog internally changes the checkstate, block signal from executing
if (fBlockNextBtnLockSignal) {
fBlockNextBtnLockSignal = false;
return;
}
mainWindow->encryptWallet(walletModel->getEncryptionStatus() != WalletModel::Locked);
fBlockNextBtnLockSignal = true;
updateStakingCheckbox();
}
void VeilStatusBar::setWalletModel(WalletModel *model)
{
this->preparingFlag = false;
this->walletModel = model;
updateStakingCheckbox();
this->preparingFlag = true;
}
void VeilStatusBar::updateStakingCheckbox()
{
WalletModel::EncryptionStatus lockState = walletModel->getEncryptionStatus();
ui->btnLock->setChecked(lockState == WalletModel::Locked || lockState == WalletModel::UnlockedForStakingOnly);
if(this->preparingFlag) {
ui->checkStacking->setChecked(walletModel->isStakingEnabled() && lockState != WalletModel::Locked);
}
}
VeilStatusBar::~VeilStatusBar()
{
delete ui;
}
| 32.88 | 179 | 0.716241 | Oilplik |
9c2e210c0eef0fa2784d7abf75641799a36d804f | 4,156 | cpp | C++ | DT3Core/Resources/Importers/ImporterFontTTF.cpp | 9heart/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 3 | 2018-10-05T15:03:27.000Z | 2019-03-19T11:01:56.000Z | DT3Core/Resources/Importers/ImporterFontTTF.cpp | pakoito/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 1 | 2016-01-28T14:39:49.000Z | 2016-01-28T22:12:07.000Z | DT3Core/Resources/Importers/ImporterFontTTF.cpp | adderly/DT3 | e2605be091ec903d3582e182313837cbaf790857 | [
"MIT"
] | 3 | 2016-01-25T16:44:51.000Z | 2021-01-29T19:59:45.000Z | //==============================================================================
///
/// File: ImporterFontTTF.cpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/Resources/Importers/ImporterFontTTF.hpp"
#include "DT3Core/Resources/ResourceTypes/FontResource.hpp"
#include "DT3Core/Types/FileBuffer/BinaryFileStream.hpp"
#include "DT3Core/Types/Utility/ConsoleStream.hpp"
#include "DT3Core/System/Factory.hpp"
#include "DT3Core/System/FileManager.hpp"
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
/// Register with object factory
//==============================================================================
IMPLEMENT_FACTORY_IMPORTER(ImporterFontTTF,ttf)
IMPLEMENT_FACTORY_IMPORTER(ImporterFontTTF,ttc)
IMPLEMENT_FACTORY_IMPORTER(ImporterFontTTF,otf)
//==============================================================================
/// Standard class constructors/destructors
//==============================================================================
ImporterFontTTF::ImporterFontTTF (void)
{
}
ImporterFontTTF::~ImporterFontTTF (void)
{
}
//==============================================================================
//==============================================================================
unsigned long ImporterFontTTF::ft_io_func ( FT_Stream stream,
unsigned long offset,
unsigned char* buffer,
unsigned long count)
{
BinaryFileStream *read_ptr = reinterpret_cast<BinaryFileStream*>(stream->descriptor.pointer);
read_ptr->seek_g(offset, Stream::FROM_BEGINNING);
if (count == 0)
return 0;
return (unsigned long) read_ptr->read_raw(buffer,count);
}
void ImporterFontTTF::ft_close_func( FT_Stream stream)
{
BinaryFileStream *read_ptr = reinterpret_cast<BinaryFileStream*>(stream->descriptor.pointer);
delete read_ptr;
}
//==============================================================================
//==============================================================================
DTerr ImporterFontTTF::import(FontResource *target, std::string args)
{
// Open up the stream for the font file
BinaryFileStream *file = new BinaryFileStream(); // This pointer has to go through a C-API so no shared_ptr
DTerr err = FileManager::open(*file, target->path(), true);
if (err != DT3_ERR_NONE) {
LOG_MESSAGE << "Unable to open font " << target->path().full_path();
delete file;
return DT3_ERR_FILE_OPEN_FAILED;
}
// Send the stream to freetype
FT_Open_Args ftargs;
::memset((void *)&ftargs,0,sizeof(ftargs));
ftargs.flags = FT_OPEN_STREAM;
ftargs.stream=(FT_Stream)malloc(sizeof *(ftargs.stream));
ftargs.stream->base = NULL;
ftargs.stream->size = static_cast<DTuint>(file->length());
ftargs.stream->pos = 0;
ftargs.stream->descriptor.pointer = (void*) (file);
ftargs.stream->pathname.pointer = NULL;
ftargs.stream->read = &ImporterFontTTF::ft_io_func;
ftargs.stream->close = &ImporterFontTTF::ft_close_func;
FT_Error error = ::FT_Open_Face(FontResource::library(),
&ftargs,
0,
&(target->typeface()));
::FT_Select_Charmap(target->typeface(),FT_ENCODING_UNICODE);
return error == 0 ? DT3_ERR_NONE : DT3_ERR_FILE_OPEN_FAILED;
}
//==============================================================================
//==============================================================================
} // DT3
| 36.778761 | 111 | 0.478104 | 9heart |
9c2e5f56b26e34245f54665bec514f35e3fed30d | 5,272 | cpp | C++ | tests/Util/Time.cpp | DiantArts/xrnEcs | 821ad9504dc022972f499721a8f494ab78d4d2d8 | [
"MIT"
] | null | null | null | tests/Util/Time.cpp | DiantArts/xrnEcs | 821ad9504dc022972f499721a8f494ab78d4d2d8 | [
"MIT"
] | 13 | 2022-03-18T00:36:09.000Z | 2022-03-28T14:14:26.000Z | tests/Util/Time.cpp | DiantArts/xrnEcs | 821ad9504dc022972f499721a8f494ab78d4d2d8 | [
"MIT"
] | null | null | null | #include <pch.hpp>
#include <xrn/Util/Time.hpp>
template class ::xrn::util::BasicTime<double>;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#include <boost/test/unit_test.hpp>
#pragma GCC diagnostic pop
BOOST_AUTO_TEST_SUITE(test)
BOOST_AUTO_TEST_SUITE(xrn)
BOOST_AUTO_TEST_SUITE(util)
BOOST_AUTO_TEST_SUITE(Time)
BOOST_AUTO_TEST_CASE(Basic)
{
using ::xrn::util::literal::operator""_ns;
auto t1{ ::xrn::Time::createAsSeconds(0.1) };
auto t2{ t1.getAsMilliseconds() }; // 100ms
::xrn::Time t3{ 30 };
auto t4{ t3.getAsMicroseconds() }; // 30000ms
auto t5{ ::xrn::Time::createAsNanoseconds(-800000) }; // -0.8
auto t6{ t5.getAsSeconds() }; // -0.0008ms
auto t7{ t1 + ::xrn::Time::createAsSeconds(t6) }; // 99.2ms
auto t8{ t1 + -800000_ns }; // 99.2ms
auto t9{ t1 + t5 }; // 99.2ms
auto t10{ t1 + 55 }; // 155ms
auto t11{ 55 + t1 }; // 155ms
BOOST_TEST((t1 == 100));
BOOST_TEST((t2 == 100));
BOOST_TEST((t3 == 30));
BOOST_TEST((t4 == 30000));
BOOST_TEST((t5 == -0.8));
BOOST_TEST((t6 == -0.0008));
BOOST_TEST((t7 == 99.2));
BOOST_TEST((t8 == 99.2));
BOOST_TEST((t9 == 99.2));
BOOST_TEST((t10 == 155));
BOOST_TEST((t11 == 155));
}
BOOST_AUTO_TEST_CASE(Creates)
{
auto t1{ ::xrn::Time::createAsSeconds(30) };
auto t2{ ::xrn::Time::createAsMilliseconds(30) };
auto t3{ ::xrn::Time::createAsMicroseconds(30) };
auto t4{ ::xrn::Time::createAsNanoseconds(30) };
BOOST_TEST((t1 == 30000));
BOOST_TEST((t2 == 30));
BOOST_TEST((t3 == 0.03));
BOOST_TEST((t4 == 0.00003));
}
BOOST_AUTO_TEST_CASE(Compares)
{
auto t1{ ::xrn::Time::createAsSeconds(30) };
auto t2{ ::xrn::Time::createAsMilliseconds(30000) };
auto t3{ ::xrn::Time::createAsMicroseconds(30000000) };
auto t4{ ::xrn::Time::createAsNanoseconds(30000000000) };
auto t5{ ::xrn::Time::createAsNanoseconds(20000000000) };
auto t6{ 30000 };
BOOST_TEST((t1 == t2));
BOOST_TEST((t1 == t3));
BOOST_TEST((t1 == t4));
BOOST_TEST((t4 == t1));
BOOST_TEST((t1 >= t5));
BOOST_TEST((t1 > t5));
BOOST_TEST((t5 <= t1));
BOOST_TEST((t5 < t1));
BOOST_TEST((t5 != t1));
BOOST_TEST((t1 != t5));
BOOST_TEST((t1 == t6));
BOOST_TEST((t6 == t1));
BOOST_TEST((t6 >= t5));
BOOST_TEST((t6 > t5));
BOOST_TEST((t5 <= t6));
BOOST_TEST((t5 < t6));
BOOST_TEST((t5 != t6));
BOOST_TEST((t6 != t5));
}
BOOST_AUTO_TEST_CASE(GettersSetters)
{
auto t1{ ::xrn::Time::createAsSeconds(30) };
BOOST_TEST((t1 == 30000));
BOOST_TEST((t1.get() == 30000));
BOOST_TEST((static_cast<double>(t1) == 30000));
BOOST_TEST((t1.getAsSeconds() == 30));
BOOST_TEST((t1.getAsMilliseconds() == 30000));
BOOST_TEST((t1.getAsMicroseconds() == 30000000));
BOOST_TEST((t1.getAsNanoseconds() == 30000000000));
t1 = ::xrn::Time::createAsSeconds(40);
BOOST_TEST((t1.get() == 40000));
BOOST_TEST((static_cast<double>(t1) == 40000));
BOOST_TEST((t1.getAsSeconds() == 40));
BOOST_TEST((t1.getAsMilliseconds() == 40000));
BOOST_TEST((t1.getAsMicroseconds() == 40000000));
BOOST_TEST((t1.getAsNanoseconds() == 40000000000));
t1.set(::xrn::Time::createAsSeconds(50));
BOOST_TEST((t1.get() == 50000));
BOOST_TEST((static_cast<double>(t1) == 50000));
BOOST_TEST((t1.getAsSeconds() == 50));
BOOST_TEST((t1.getAsMilliseconds() == 50000));
BOOST_TEST((t1.getAsMicroseconds() == 50000000));
BOOST_TEST((t1.getAsNanoseconds() == 50000000000));
t1.set(60000);
BOOST_TEST((t1.get() == 60000));
BOOST_TEST((static_cast<double>(t1) == 60000));
BOOST_TEST((t1.getAsSeconds() == 60));
BOOST_TEST((t1.getAsMilliseconds() == 60000));
BOOST_TEST((t1.getAsMicroseconds() == 60000000));
BOOST_TEST((t1.getAsNanoseconds() == 60000000000));
}
BOOST_AUTO_TEST_CASE(Add)
{
auto t1{ ::xrn::Time::createAsSeconds(3) };
auto t2{ ::xrn::Time::createAsSeconds(3) };
t1 += t2;
BOOST_TEST((t1 == 6000));
t1 = t1 + t2;
BOOST_TEST((t1 == 9000));
t1 += 3000;
BOOST_TEST((t1 == 12000));
t1 = t2 + 3000;
BOOST_TEST((t1 == 6000));
t1.add(t2);
BOOST_TEST((t1 == 9000));
t1.add(3000);
BOOST_TEST((t1 == 12000));
}
BOOST_AUTO_TEST_CASE(Sub)
{
auto t1{ ::xrn::Time::createAsSeconds(3) };
auto t2{ ::xrn::Time::createAsSeconds(3) };
t1 -= t2;
BOOST_TEST((t1 == 0));
t1 = t1 - t2;
BOOST_TEST((t1 == -3000));
t1 -= 3000;
BOOST_TEST((t1 == -6000));
t1 = t2 - 3000;
BOOST_TEST((t1 == 0));
t1.sub(t2);
BOOST_TEST((t1 == -3000));
t1.sub(3000);
BOOST_TEST((t1 == -6000));
}
BOOST_AUTO_TEST_CASE(MulDiv)
{
auto t1{ ::xrn::Time::createAsSeconds(3) };
t1 *= 3;
BOOST_TEST((t1 == 9000));
t1 /= 3;
BOOST_TEST((t1 == 3000));
t1 = t1 * 3;
BOOST_TEST((t1 == 9000));
t1 = t1 / 3;
BOOST_TEST((t1 == 3000));
}
BOOST_AUTO_TEST_CASE(Mod)
{
auto t1{ ::xrn::Time::createAsSeconds(3) };
t1 %= 3;
BOOST_TEST((t1 == 0));
t1 = ::xrn::Time::createAsSeconds(3);
t1 = t1 % 3;
BOOST_TEST((t1 == 0));
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 27.89418 | 65 | 0.600341 | DiantArts |
9c3062e925d921e9a97c72c056b1e17c1b853826 | 14,587 | cpp | C++ | whip/VFSBackend.cpp | IlyaFinkelshteyn/whip-server-1 | d6055f523950f5f05cb164cc7ad79a5a9424809f | [
"Apache-2.0"
] | 2 | 2018-08-16T02:00:55.000Z | 2018-08-19T06:27:00.000Z | whip/VFSBackend.cpp | IlyaFinkelshteyn/whip-server-1 | d6055f523950f5f05cb164cc7ad79a5a9424809f | [
"Apache-2.0"
] | 2 | 2018-08-19T17:49:15.000Z | 2019-04-24T16:58:32.000Z | whip/VFSBackend.cpp | IlyaFinkelshteyn/whip-server-1 | d6055f523950f5f05cb164cc7ad79a5a9424809f | [
"Apache-2.0"
] | 5 | 2016-12-18T08:16:04.000Z | 2017-06-04T22:59:41.000Z | #include "StdAfx.h"
#include "VFSBackend.h"
#include "AppLog.h"
#include "AssetStorageError.h"
#include "Settings.h"
#include "DatabaseSet.h"
#include "IndexFile.h"
#include "SQLiteIndexFileManager.h"
#include "IIndexFileManager.h"
#include "kashmir/uuid.h"
#include "SQLiteError.h"
#include <boost/filesystem/fstream.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/shared_array.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/foreach.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <stdexcept>
#include <sstream>
#include <vector>
#include <boost/cstdlib.hpp>
namespace fs = boost::filesystem;
using namespace boost::posix_time;
namespace iwvfs
{
VFSBackend::VFSBackend(const std::string& storageRoot, bool enablePurge, boost::asio::io_service& ioService,
PushReplicationService::ptr pushRepl)
: _storageRoot(storageRoot), _enablePurge(enablePurge), _stop(false), _ioService(ioService), _purgeLocalsTimer(ioService),
_isPurgingLocals(false), _currentLocalsPurgeIndex(0), _diskLatencyAvg(DISK_LATENCY_SAMPLE_SIZE),
_diskOpAvg(DISK_LATENCY_SAMPLE_SIZE), _pushRepl(pushRepl)
{
SAFELOG(AppLog::instance().out() << "[IWVFS] Starting storage backend" << std::endl);
//make sure the storage root exists
if (! fs::exists(_storageRoot)) {
throw std::runtime_error("Unable to start storage backend, the storage root '"
+ storageRoot + "' was not found");
}
SAFELOG(AppLog::instance().out() << "[IWVFS] Root: " << storageRoot << ", Purge: " << (_enablePurge ? "enabled" : "disabled") << std::endl);
_debugging = whip::Settings::instance().get("debug").as<bool>();
SAFELOG(AppLog::instance().out() << "[IWVFS] SQLite Index Backend: SQLite v" << sqlite3_libversion() << std::endl);
//TODO: Should be deleted on shutdown
IIndexFileManager::ptr indexFileManager(new SQLiteIndexFileManager());
IndexFile::SetIndexFileManager(indexFileManager);
SAFELOG(AppLog::instance().out() << "[IWVFS] Generating asset existence index" << std::endl);
_existenceIndex.reset(new ExistenceIndex(storageRoot));
SAFELOG(AppLog::instance().out() << "[IWVFS] Starting disk I/O worker thread" << std::endl);
_workerThread.reset(new boost::thread(boost::bind(&VFSBackend::workLoop, this)));
}
VFSBackend::~VFSBackend()
{
}
void VFSBackend::workLoop()
{
while( !_stop )
{
try {
AssetRequest::ptr req;
{
boost::mutex::scoped_lock lock(_workMutex);
while(_workQueue.empty() && !_stop) {
_workArrived.wait(lock);
}
if (_stop) break;
req = _workQueue.front();
_workQueue.pop_front();
}
_diskLatencyAvg.addSample(req->queueDuration());
ptime opStart = microsec_clock::universal_time();
req->processRequest(*this);
time_duration diff = microsec_clock::universal_time() - opStart;
_diskOpAvg.addSample((int) diff.total_milliseconds());
} catch (const std::exception& e) {
_ioService.post(boost::bind(&VFSBackend::ioLoopFailed, this, std::string(e.what())));
} catch (...) {
_ioService.post(boost::bind(&VFSBackend::ioLoopFailed, this, "Unknown error"));
}
}
}
void VFSBackend::performDiskWrite(Asset::ptr asset, AsyncStoreAssetCallback callback)
{
try {
this->storeAsset(asset);
_ioService.post(boost::bind(callback, true, AssetStorageError::ptr()));
_pushRepl->queueAssetForPush(asset);
} catch (const AssetStorageError& storageError) {
AssetStorageError::ptr error(new AssetStorageError(storageError));
_ioService.post(boost::bind(callback, false, error));
} catch (const std::exception& storageError) {
AssetStorageError::ptr error(new AssetStorageError(storageError.what()));
_ioService.post(boost::bind(&VFSBackend::assetWriteFailed, this, asset->getUUID(), storageError.what()));
_ioService.post(boost::bind(callback, false, error));
}
}
void VFSBackend::assetWriteFailed(std::string assetId, std::string reason)
{
SAFELOG(AppLog::instance().error() << "[IWVFS] Asset write failed for " << assetId << ": " << reason << std::endl);
_existenceIndex->removeId(kashmir::uuid::uuid_t(assetId.c_str()));
}
void VFSBackend::ioLoopFailed(std::string reason)
{
SAFELOG(AppLog::instance().error() << "[IWVFS] Critical warning: ioWorker caught exception: " << reason << std::endl);
}
void VFSBackend::performDiskRead(const std::string& assetId, AsyncGetAssetCallback callback)
{
try {
Asset::ptr asset = this->getAsset(assetId);
if (asset) {
_ioService.post(boost::bind(callback, asset, true, AssetStorageError::ptr()));
} else {
AssetStorageError::ptr error(new AssetStorageError("Asset " + assetId + " not found"));
_ioService.post(boost::bind(callback, Asset::ptr(), false, error));
}
} catch (const AssetStorageError& storageError) {
AssetStorageError::ptr error(new AssetStorageError(storageError));
_ioService.post(boost::bind(callback, Asset::ptr(), false, error));
} catch (const std::exception& storageError) {
AssetStorageError::ptr error(new AssetStorageError(storageError.what()));
_ioService.post(boost::bind(callback, Asset::ptr(), false, error));
}
}
void VFSBackend::performDiskPurge(const std::string& assetId, AsyncAssetPurgeCallback callback)
{
}
void VFSBackend::performDiskPurgeLocals(const std::string& uuidHead)
{
//purging locals has three steps which starts here
// 1) The first step is to look up the asset ids that are contained in the specified index/locals file
// 2) Those local ids are passed to the existence index for deletion
// 3) When that process completes a full deletion is scheduled for the locals data file and index
fs::path indexPath(fs::path(_storageRoot) / uuidHead / "locals.idx");
UuidListPtr containedIds;
if (fs::exists(indexPath)) {
//open the index file and get a list of asset ids contained within
IndexFile::ptr indexFile(new IndexFile(indexPath));
containedIds = indexFile->getContainedAssetIds();
}
//schedule a deletion of the returned uuids to happen on the ASIO thread
_ioService.post(boost::bind(&VFSBackend::unindexLocals, this, containedIds, uuidHead));
}
void VFSBackend::unindexLocals(UuidListPtr uuidList, std::string uuidHead)
{
if (uuidList) {
UuidList::iterator end = uuidList->end();
for (UuidList::iterator i = uuidList->begin(); i != end; ++i)
{
_existenceIndex->removeId(*i);
}
}
//schedule physical deletion of the index and data files
AssetRequest::ptr req(new DeleteLocalStorageRequest(uuidHead));
boost::mutex::scoped_lock lock(_workMutex);
_workQueue.push_back(req);
_workArrived.notify_one();
}
void VFSBackend::performLocalsPhysicalDeletion(const std::string& uuidHead)
{
fs::path indexPath(fs::path(_storageRoot) / uuidHead / "locals.idx");
IndexFile::GetIndexFileManager()->forceCloseIndexFile(indexPath);
//the index file is guaranteed to not be in use, delete the index file and the data file
fs::path dataPath(fs::path(_storageRoot) / uuidHead / "locals.data");
fs::remove(indexPath);
fs::remove(dataPath);
}
bool VFSBackend::isLittleEndian()
{
union {
boost::uint32_t i;
char c[4];
} bint = {0x01020304};
return bint.c[0] != 1;
}
fs::path VFSBackend::getFullPathForUUID(const std::string& uuid)
{
fs::path subdir(fs::path(_storageRoot) / fs::path(uuid.substr(0, whip::Settings::UUID_PATH_CHARS)));
return subdir;
}
void VFSBackend::verifyDatabaseDirectory(const std::string& uuid)
{
fs::path subdir(this->getFullPathForUUID(uuid));
if (! fs::exists(subdir)) {
if (! fs::create_directory(subdir)) {
throw AssetStorageError("Could not create directory for database storage " + subdir.string(), true);
}
}
}
DatabaseSet::ptr VFSBackend::verifyAndopenSetForUUID(const std::string& uuid)
{
try {
this->verifyDatabaseDirectory(uuid);
DatabaseSet::ptr dbset(new DatabaseSet(this->getFullPathForUUID(uuid)));
return dbset;
} catch (const SQLiteError& e) {
throw AssetStorageError(std::string("Index file error: ") + e.what(), true);
}
}
Asset::ptr VFSBackend::getAsset(const std::string& uuid)
{
DatabaseSet::ptr dbset(this->verifyAndopenSetForUUID(uuid));
Asset::ptr localAsset(dbset->getAsset(uuid));
return localAsset;
}
void VFSBackend::storeAsset(Asset::ptr asset)
{
DatabaseSet::ptr dbset(this->verifyAndopenSetForUUID(asset->getUUID()));
dbset->storeAsset(asset);
}
bool VFSBackend::assetExists(const std::string& uuid)
{
return _existenceIndex->assetExists(uuid);
}
void VFSBackend::purgeAsset(const std::string& uuid)
{
//TODO: Not implemented
}
void VFSBackend::getAsset(const std::string& uuid, unsigned int flags, AsyncGetAssetCallback callBack)
{
//flags are not used here yet
this->getAsset(uuid, callBack);
}
void VFSBackend::getAsset(const std::string& uuid, AsyncGetAssetCallback callBack)
{
//use the cache to shortcut the situation where the asset doesnt exist
if (! _existenceIndex->assetExists(uuid)) {
AssetStorageError::ptr error(new AssetStorageError("Could not retrieve asset " + uuid + ", asset not found"));
_ioService.post(boost::bind(callBack, Asset::ptr(), false, error));
return;
}
AssetRequest::ptr req(new AssetGetRequest(uuid, callBack));
boost::mutex::scoped_lock lock(_workMutex);
_workQueue.push_back(req);
_workArrived.notify_one();
}
void VFSBackend::storeAsset(Asset::ptr asset, AsyncStoreAssetCallback callBack)
{
//use the cache to shortcut the situation where the asset already exists
if (_existenceIndex->assetExists(asset->getUUID())) {
AssetStorageError::ptr error(new AssetStorageError("Unable to store asset " + asset->getUUID() + ", asset already exists"));
_ioService.post(boost::bind(callBack, false, error));
return;
}
//we put the asset into the existance index now to be sure there are no race conditions
//between storage and subsequent retrieval
// remember the queue will process all
// requests in order so getting a successful response for a read here is ok since
// the write will always happen first
_existenceIndex->addNewId(asset->getUUID());
AssetRequest::ptr req(new AssetPutRequest(asset, callBack));
boost::mutex::scoped_lock lock(_workMutex);
_workQueue.push_back(req);
_workArrived.notify_one();
}
void VFSBackend::purgeAsset(const std::string& uuid, AsyncAssetPurgeCallback callBack)
{
AssetRequest::ptr req(new AssetPurgeRequest(uuid, false, callBack));
boost::mutex::scoped_lock lock(_workMutex);
_workQueue.push_back(req);
_workArrived.notify_one();
}
void VFSBackend::beginPurgeLocals()
{
if (! _isPurgingLocals) {
SAFELOG(AppLog::instance().out() << "[IWVFS] PurgeLocals command received, beginning purge" << std::endl);
_isPurgingLocals = true;
_currentLocalsPurgeIndex = 0;
_purgeLocalsTimer.expires_from_now(boost::posix_time::seconds(1));
_purgeLocalsTimer.async_wait(boost::bind(&VFSBackend::onPurgeTimer, this, boost::asio::placeholders::error));
}
}
void VFSBackend::onPurgeTimer(const boost::system::error_code& error)
{
if (!error) {
std::stringstream hexNum;
hexNum << std::setfill('0') << std::setw(whip::Settings::UUID_PATH_CHARS) << std::hex << _currentLocalsPurgeIndex++;
std::string assetId(hexNum.str());
AssetRequest::ptr req(new AssetPurgeRequest(assetId, true));
SAFELOG(AppLog::instance().out() << "[IWVFS] Queueing purge of: " << assetId << std::endl);
boost::mutex::scoped_lock lock(_workMutex);
_workQueue.push_back(req);
_workArrived.notify_one();
if (_currentLocalsPurgeIndex <= 0xFFF) {
_purgeLocalsTimer.expires_from_now(boost::posix_time::seconds(1));
_purgeLocalsTimer.async_wait(boost::bind(&VFSBackend::onPurgeTimer, this, boost::asio::placeholders::error));
} else {
_isPurgingLocals = false;
}
} else {
SAFELOG(AppLog::instance().out() << "[IWVFS] PurgeLocals timer execution error: " << error.message() << std::endl);
}
}
void VFSBackend::getStatus(boost::shared_ptr<std::ostream> journal, boost::function<void()> completedCallback)
{
AssetRequest::ptr req(new CollectStatusRequest(journal, completedCallback));
boost::mutex::scoped_lock lock(_workMutex);
_workQueue.push_back(req);
_workArrived.notify_one();
}
void VFSBackend::performGetStatus(boost::shared_ptr<std::ostream> journal, boost::function<void()> completedCallback)
{
(*journal) << "-VFS Backend" << std::endl;
{
boost::mutex::scoped_lock lock(_workMutex);
(*journal) << " Disk queue size: " << _workQueue.size() << std::endl;
(*journal) << " Avg Disk Queue Wait: " << _diskLatencyAvg.getAverage() << " ms" << std::endl;
(*journal) << " Avg Disk Op Latency: " << _diskOpAvg.getAverage() << " ms" << std::endl;
(*journal) << "-VFS Queue Items" << std::endl;
BOOST_FOREACH(AssetRequest::ptr req, _workQueue)
{
(*journal) << " " << req->getDescription() << std::endl;
}
}
_ioService.post(completedCallback);
}
void VFSBackend::getStoredAssetIDsWithPrefix(std::string prefix, boost::shared_ptr<std::ostream> journal, boost::function<void()> completedCallback)
{
AssetRequest::ptr req(new GetStoredAssetIdsRequest(prefix, journal, completedCallback));
boost::mutex::scoped_lock lock(_workMutex);
_workQueue.push_back(req);
_workArrived.notify_one();
}
void VFSBackend::performGetStoredAssetIds(std::string prefix, boost::shared_ptr<std::ostream> journal, boost::function<void()> completedCallback)
{
fs::path indexPath(fs::path(_storageRoot) / prefix / "globals.idx");
if (fs::exists(indexPath)) {
//open the index file and get a list of asset ids contained within
IndexFile::ptr indexFile(new IndexFile(indexPath));
StringUuidListPtr containedIds = indexFile->getContainedAssetIdStrings();
StringUuidList& containedIdsRef = *containedIds;
BOOST_FOREACH(const std::string& assetId, containedIdsRef)
{
(*journal) << assetId << ",";
}
}
_ioService.post(completedCallback);
}
void VFSBackend::shutdown()
{
SAFELOG(AppLog::instance().out() << "[IWVFS] Performing clean shutdown" << std::endl);
_stop = true;
{
boost::mutex::scoped_lock lock(_workMutex);
_workArrived.notify_one();
}
if (_workerThread->joinable()) {
_workerThread->join();
}
SAFELOG(AppLog::instance().out() << "[IWVFS] Closing indexes" << std::endl);
IndexFile::GetIndexFileManager()->shutdown();
SAFELOG(AppLog::instance().out() << "[IWVFS] Shutdown complete" << std::endl);
}
ExistenceIndex::ptr VFSBackend::getIndex()
{
return _existenceIndex;
}
} | 31.989035 | 149 | 0.710838 | IlyaFinkelshteyn |
9c30b76ccf7ff6426b05eb259bf7db7ef015b39b | 4,019 | hpp | C++ | Source/AMRInterpolator/AMRInterpolator.hpp | GeraintPratten/GRChombo | ab6c9d5bd2267215a8f199f3df1ea9dcf4b5abe6 | [
"BSD-3-Clause"
] | null | null | null | Source/AMRInterpolator/AMRInterpolator.hpp | GeraintPratten/GRChombo | ab6c9d5bd2267215a8f199f3df1ea9dcf4b5abe6 | [
"BSD-3-Clause"
] | null | null | null | Source/AMRInterpolator/AMRInterpolator.hpp | GeraintPratten/GRChombo | ab6c9d5bd2267215a8f199f3df1ea9dcf4b5abe6 | [
"BSD-3-Clause"
] | null | null | null | /* GRChombo
* Copyright 2012 The GRChombo collaboration.
* Please refer to LICENSE in GRChombo's root directory.
*/
#ifndef AMRINTERPOLATOR_HPP_
#define AMRINTERPOLATOR_HPP_
// Chombo includes
#include "AMR.H"
#include "AMRLevel.H"
#include "UsingNamespace.H"
// Our includes
#include "BoundaryConditions.hpp"
#include "InterpSource.hpp"
#include "InterpolationAlgorithm.hpp"
#include "InterpolationLayout.hpp"
#include "InterpolationQuery.hpp"
#include "MPIContext.hpp"
#include "UserVariables.hpp"
// End include
template <typename InterpAlgo> class AMRInterpolator
{
public:
// constructor for backward compatibility
// (adds an artificial BC with only periodic BC)
AMRInterpolator(const AMR &amr,
const std::array<double, CH_SPACEDIM> &coarsest_origin,
const std::array<double, CH_SPACEDIM> &coarsest_dx,
int verbosity = 0);
AMRInterpolator(const AMR &amr,
const std::array<double, CH_SPACEDIM> &coarsest_origin,
const std::array<double, CH_SPACEDIM> &coarsest_dx,
const BoundaryConditions::params_t &a_bc_params,
int verbosity = 0);
void refresh();
void limit_num_levels(unsigned int num_levels);
void interp(InterpolationQuery &query);
const AMR &getAMR() const;
const std::array<double, CH_SPACEDIM> &get_coarsest_dx();
const std::array<double, CH_SPACEDIM> &get_coarsest_origin();
private:
void computeLevelLayouts();
InterpolationLayout findBoxes(InterpolationQuery &query);
void prepareMPI(InterpolationQuery &query,
const InterpolationLayout layout);
void exchangeMPIQuery();
void calculateAnswers(InterpolationQuery &query);
void exchangeMPIAnswer();
/// set values of member 'm_lo_boundary_reflective' and
/// 'm_hi_boundary_reflective'
void set_reflective_BC();
int get_var_parity(int comp, const VariableType type, int point_idx,
const InterpolationQuery &query,
const Derivative &deriv) const;
/// reflect coordinates if BC set to reflective in that direction
double apply_reflective_BC_on_coord(const InterpolationQuery &query,
double dir, int point_idx) const;
const AMR &m_amr;
// Coordinates of the point represented by IntVect::Zero in coarsest grid
const std::array<double, CH_SPACEDIM> m_coarsest_origin;
// Grid spacing in each direction
const std::array<double, CH_SPACEDIM> m_coarsest_dx;
int m_num_levels;
const int m_verbosity;
std::vector<std::array<double, CH_SPACEDIM>> m_origin;
std::vector<std::array<double, CH_SPACEDIM>> m_dx;
MPIContext m_mpi;
std::vector<int> m_mpi_mapping;
// Memoisation of boxes previously found
std::vector<int> m_mem_level;
std::vector<int> m_mem_box;
std::vector<int> m_query_level;
std::vector<int> m_query_box;
std::vector<double> m_query_coords[CH_SPACEDIM];
std::vector<std::vector<double>> m_query_data;
std::vector<int> m_answer_level;
std::vector<int> m_answer_box;
std::vector<double> m_answer_coords[CH_SPACEDIM];
std::vector<std::vector<double>> m_answer_data;
// A bit of Android-ism here, but it's really useful!
// Identifies the printout as originating from this class.
const static string TAG;
// Variables for reflective BC
// m_bc_params can't be a 'const' reference as we need a
// constructor with backward compatibility that builds an artificial
// 'BoundaryConditions::params_t'
BoundaryConditions::params_t m_bc_params;
/// simplified bools saying whether or not boundary has
/// a reflective condition in a given direction
std::array<bool, CH_SPACEDIM> m_lo_boundary_reflective,
m_hi_boundary_reflective;
std::array<double, CH_SPACEDIM> m_upper_corner;
};
#include "AMRInterpolator.impl.hpp"
#endif /* AMRINTERPOLATOR_HPP_ */
| 33.491667 | 77 | 0.696193 | GeraintPratten |
9c3199d0fe9f3ea30e284f29e8059b00b560cb84 | 1,088 | cpp | C++ | AK/MappedFile.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 4 | 2021-02-23T05:35:25.000Z | 2021-06-08T06:11:06.000Z | AK/MappedFile.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 4 | 2021-04-27T20:44:44.000Z | 2021-06-30T18:07:10.000Z | AK/MappedFile.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 1 | 2022-01-10T08:02:34.000Z | 2022-01-10T08:02:34.000Z | /*
* Copyright (c) 2018-2021, Andreas Kling <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/MappedFile.h>
#include <AK/ScopeGuard.h>
#include <AK/String.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace AK {
Result<NonnullRefPtr<MappedFile>, OSError> MappedFile::map(const String& path)
{
int fd = open(path.characters(), O_RDONLY | O_CLOEXEC, 0);
if (fd < 0)
return OSError(errno);
ScopeGuard fd_close_guard = [fd] {
close(fd);
};
struct stat st;
if (fstat(fd, &st) < 0) {
auto saved_errno = errno;
return OSError(saved_errno);
}
auto size = st.st_size;
auto* ptr = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED)
return OSError(errno);
return adopt_ref(*new MappedFile(ptr, size));
}
MappedFile::MappedFile(void* ptr, size_t size)
: m_data(ptr)
, m_size(size)
{
}
MappedFile::~MappedFile()
{
auto rc = munmap(m_data, m_size);
VERIFY(rc == 0);
}
}
| 19.428571 | 78 | 0.627757 | shubhdev |
9c349d12895913e37f7dabba7864ee7f7724e541 | 21,610 | cpp | C++ | shared/ebm_native/CalculateInteractionScore.cpp | jruales/interpret | edb7418cd12865e55e352ace6c61ff5cef8e1061 | [
"MIT"
] | null | null | null | shared/ebm_native/CalculateInteractionScore.cpp | jruales/interpret | edb7418cd12865e55e352ace6c61ff5cef8e1061 | [
"MIT"
] | null | null | null | shared/ebm_native/CalculateInteractionScore.cpp | jruales/interpret | edb7418cd12865e55e352ace6c61ff5cef8e1061 | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Microsoft Corporation
// Licensed under the MIT license.
// Author: Paul Koch <[email protected]>
#include "PrecompiledHeader.h"
#include <stddef.h> // size_t, ptrdiff_t
#include <limits> // numeric_limits
#include "ebm_native.h"
#include "EbmInternal.h"
#include "Logging.h" // EBM_ASSERT & LOG
// feature includes
#include "FeatureAtomic.h"
#include "FeatureGroup.h"
// dataset depends on features
#include "DataSetInteraction.h"
#include "CachedThreadResourcesInteraction.h"
#include "InteractionDetector.h"
#include "TensorTotalsSum.h"
extern void BinInteraction(
InteractionDetector * const pInteractionDetector,
const FeatureGroup * const pFeatureGroup,
HistogramBucketBase * const aHistogramBuckets
#ifndef NDEBUG
, const unsigned char * const aHistogramBucketsEndDebug
#endif // NDEBUG
);
extern FloatEbmType FindBestInteractionGainPairs(
InteractionDetector * const pInteractionDetector,
const FeatureGroup * const pFeatureGroup,
const size_t cSamplesRequiredForChildSplitMin,
HistogramBucketBase * pAuxiliaryBucketZone,
HistogramBucketBase * const aHistogramBuckets
#ifndef NDEBUG
, const HistogramBucketBase * const aHistogramBucketsDebugCopy
, const unsigned char * const aHistogramBucketsEndDebug
#endif // NDEBUG
);
static bool CalculateInteractionScoreInternal(
CachedInteractionThreadResources * const pCachedThreadResources,
InteractionDetector * const pInteractionDetector,
const FeatureGroup * const pFeatureGroup,
const size_t cSamplesRequiredForChildSplitMin,
FloatEbmType * const pInteractionScoreReturn
) {
// TODO : we NEVER use the denominator term in HistogramBucketVectorEntry when calculating interaction scores, but we're spending time calculating
// it, and it's taking up precious memory. We should eliminate the denominator term HERE in our datastructures OR we should think whether we can
// use the denominator as part of the gain function!!!
const ptrdiff_t runtimeLearningTypeOrCountTargetClasses = pInteractionDetector->GetRuntimeLearningTypeOrCountTargetClasses();
const bool bClassification = IsClassification(runtimeLearningTypeOrCountTargetClasses);
LOG_0(TraceLevelVerbose, "Entered CalculateInteractionScoreInternal");
const size_t cDimensions = pFeatureGroup->GetCountFeatures();
EBM_ASSERT(1 <= cDimensions); // situations with 0 dimensions should have been filtered out before this function was called (but still inside the C++)
size_t cAuxillaryBucketsForBuildFastTotals = 0;
size_t cTotalBucketsMainSpace = 1;
for(size_t iDimension = 0; iDimension < cDimensions; ++iDimension) {
const size_t cBins = pFeatureGroup->GetFeatureGroupEntries()[iDimension].m_pFeature->GetCountBins();
EBM_ASSERT(2 <= cBins); // situations with 1 bin should have been filtered out before this function was called (but still inside the C++)
// if cBins could be 1, then we'd need to check at runtime for overflow of cAuxillaryBucketsForBuildFastTotals
// if this wasn't true then we'd have to check IsAddError(cAuxillaryBucketsForBuildFastTotals, cTotalBucketsMainSpace) at runtime
EBM_ASSERT(cAuxillaryBucketsForBuildFastTotals < cTotalBucketsMainSpace);
// since cBins must be 2 or more, cAuxillaryBucketsForBuildFastTotals must grow slower than cTotalBucketsMainSpace, and we checked at allocation
// that cTotalBucketsMainSpace would not overflow
EBM_ASSERT(!IsAddError(cAuxillaryBucketsForBuildFastTotals, cTotalBucketsMainSpace));
// this can overflow, but if it does then we're guaranteed to catch the overflow via the multiplication check below
cAuxillaryBucketsForBuildFastTotals += cTotalBucketsMainSpace;
if(IsMultiplyError(cTotalBucketsMainSpace, cBins)) {
// unlike in the boosting code where we check at allocation time if the tensor created overflows on multiplication
// we don't know what group of features our caller will give us for calculating the interaction scores,
// so we need to check if our caller gave us a tensor that overflows multiplication
LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal IsMultiplyError(cTotalBucketsMainSpace, cBins)");
return true;
}
cTotalBucketsMainSpace *= cBins;
// if this wasn't true then we'd have to check IsAddError(cAuxillaryBucketsForBuildFastTotals, cTotalBucketsMainSpace) at runtime
EBM_ASSERT(cAuxillaryBucketsForBuildFastTotals < cTotalBucketsMainSpace);
}
const size_t cAuxillaryBucketsForSplitting = 4;
const size_t cAuxillaryBuckets =
cAuxillaryBucketsForBuildFastTotals < cAuxillaryBucketsForSplitting ? cAuxillaryBucketsForSplitting : cAuxillaryBucketsForBuildFastTotals;
if(IsAddError(cTotalBucketsMainSpace, cAuxillaryBuckets)) {
LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal IsAddError(cTotalBucketsMainSpace, cAuxillaryBuckets)");
return true;
}
const size_t cTotalBuckets = cTotalBucketsMainSpace + cAuxillaryBuckets;
const size_t cVectorLength = GetVectorLength(runtimeLearningTypeOrCountTargetClasses);
if(GetHistogramBucketSizeOverflow(bClassification, cVectorLength)) {
LOG_0(
TraceLevelWarning,
"WARNING CalculateInteractionScoreInternal GetHistogramBucketSizeOverflow<bClassification>(cVectorLength)"
);
return true;
}
const size_t cBytesPerHistogramBucket = GetHistogramBucketSize(bClassification, cVectorLength);
if(IsMultiplyError(cTotalBuckets, cBytesPerHistogramBucket)) {
LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal IsMultiplyError(cTotalBuckets, cBytesPerHistogramBucket)");
return true;
}
const size_t cBytesBuffer = cTotalBuckets * cBytesPerHistogramBucket;
// this doesn't need to be freed since it's tracked and re-used by the class CachedInteractionThreadResources
HistogramBucketBase * const aHistogramBuckets = pCachedThreadResources->GetThreadByteBuffer1(cBytesBuffer);
if(UNLIKELY(nullptr == aHistogramBuckets)) {
LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal nullptr == aHistogramBuckets");
return true;
}
if(bClassification) {
HistogramBucket<true> * const aHistogramBucketsLocal = aHistogramBuckets->GetHistogramBucket<true>();
for(size_t i = 0; i < cTotalBuckets; ++i) {
HistogramBucket<true> * const pHistogramBucket =
GetHistogramBucketByIndex(cBytesPerHistogramBucket, aHistogramBucketsLocal, i);
pHistogramBucket->Zero(cVectorLength);
}
} else {
HistogramBucket<false> * const aHistogramBucketsLocal = aHistogramBuckets->GetHistogramBucket<false>();
for(size_t i = 0; i < cTotalBuckets; ++i) {
HistogramBucket<false> * const pHistogramBucket =
GetHistogramBucketByIndex(cBytesPerHistogramBucket, aHistogramBucketsLocal, i);
pHistogramBucket->Zero(cVectorLength);
}
}
HistogramBucketBase * pAuxiliaryBucketZone =
GetHistogramBucketByIndex(cBytesPerHistogramBucket, aHistogramBuckets, cTotalBucketsMainSpace);
#ifndef NDEBUG
const unsigned char * const aHistogramBucketsEndDebug = reinterpret_cast<unsigned char *>(aHistogramBuckets) + cBytesBuffer;
#endif // NDEBUG
BinInteraction(
pInteractionDetector,
pFeatureGroup,
aHistogramBuckets
#ifndef NDEBUG
, aHistogramBucketsEndDebug
#endif // NDEBUG
);
#ifndef NDEBUG
// make a copy of the original binned buckets for debugging purposes
size_t cTotalBucketsDebug = 1;
for(size_t iDimensionDebug = 0; iDimensionDebug < cDimensions; ++iDimensionDebug) {
const size_t cBins = pFeatureGroup->GetFeatureGroupEntries()[iDimensionDebug].m_pFeature->GetCountBins();
EBM_ASSERT(!IsMultiplyError(cTotalBucketsDebug, cBins)); // we checked this above
cTotalBucketsDebug *= cBins;
}
// we wouldn't have been able to allocate our main buffer above if this wasn't ok
EBM_ASSERT(!IsMultiplyError(cTotalBucketsDebug, cBytesPerHistogramBucket));
HistogramBucketBase * const aHistogramBucketsDebugCopy =
EbmMalloc<HistogramBucketBase>(cTotalBucketsDebug, cBytesPerHistogramBucket);
if(nullptr != aHistogramBucketsDebugCopy) {
// if we can't allocate, don't fail.. just stop checking
const size_t cBytesBufferDebug = cTotalBucketsDebug * cBytesPerHistogramBucket;
memcpy(aHistogramBucketsDebugCopy, aHistogramBuckets, cBytesBufferDebug);
}
#endif // NDEBUG
TensorTotalsBuild(
runtimeLearningTypeOrCountTargetClasses,
pFeatureGroup,
pAuxiliaryBucketZone,
aHistogramBuckets
#ifndef NDEBUG
, aHistogramBucketsDebugCopy
, aHistogramBucketsEndDebug
#endif // NDEBUG
);
if(2 == cDimensions) {
LOG_0(TraceLevelVerbose, "CalculateInteractionScoreInternal Starting bin sweep loop");
FloatEbmType bestSplittingScore = FindBestInteractionGainPairs(
pInteractionDetector,
pFeatureGroup,
cSamplesRequiredForChildSplitMin,
pAuxiliaryBucketZone,
aHistogramBuckets
#ifndef NDEBUG
, aHistogramBucketsDebugCopy
, aHistogramBucketsEndDebug
#endif // NDEBUG
);
LOG_0(TraceLevelVerbose, "CalculateInteractionScoreInternal Done bin sweep loop");
if(nullptr != pInteractionScoreReturn) {
// we started our score at zero, and didn't replace with anything lower, so it can't be below zero
// if we collected a NaN value, then we kept it
EBM_ASSERT(std::isnan(bestSplittingScore) || FloatEbmType { 0 } <= bestSplittingScore);
EBM_ASSERT((!bClassification) || !std::isinf(bestSplittingScore));
// if bestSplittingScore was NaN we make it zero so that it's not included. If infinity, also don't include it since we overloaded something
// even though bestSplittingScore shouldn't be +-infinity for classification, we check it for +-infinity
// here since it's most efficient to check that the exponential is all ones, which is the case only for +-infinity and NaN, but not others
// comparing to max is a good way to check for +infinity without using infinity, which can be problematic on
// some compilers with some compiler settings. Using <= helps avoid optimization away because the compiler
// might assume that nothing is larger than max if it thinks there's no +infinity
if(UNLIKELY(UNLIKELY(std::isnan(bestSplittingScore)) ||
UNLIKELY(std::numeric_limits<FloatEbmType>::max() <= bestSplittingScore))) {
bestSplittingScore = FloatEbmType { 0 };
}
*pInteractionScoreReturn = bestSplittingScore;
}
} else {
EBM_ASSERT(false); // we only support pairs currently
LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal 2 != cDimensions");
// TODO: handle this better
if(nullptr != pInteractionScoreReturn) {
// for now, just return any interactions that have other than 2 dimensions as zero, which means they won't be considered
*pInteractionScoreReturn = FloatEbmType { 0 };
}
}
#ifndef NDEBUG
free(aHistogramBucketsDebugCopy);
#endif // NDEBUG
LOG_0(TraceLevelVerbose, "Exited CalculateInteractionScoreInternal");
return false;
}
// we made this a global because if we had put this variable inside the InteractionDetector object, then we would need to dereference that before getting
// the count. By making this global we can send a log message incase a bad InteractionDetector object is sent into us we only decrease the count if the
// count is non-zero, so at worst if there is a race condition then we'll output this log message more times than desired, but we can live with that
static int g_cLogCalculateInteractionScoreParametersMessages = 10;
EBM_NATIVE_IMPORT_EXPORT_BODY IntEbmType EBM_NATIVE_CALLING_CONVENTION CalculateInteractionScore(
InteractionDetectorHandle interactionDetectorHandle,
IntEbmType countFeaturesInGroup,
const IntEbmType * featureIndexes,
IntEbmType countSamplesRequiredForChildSplitMin,
FloatEbmType * interactionScoreOut
) {
LOG_COUNTED_N(
&g_cLogCalculateInteractionScoreParametersMessages,
TraceLevelInfo,
TraceLevelVerbose,
"CalculateInteractionScore parameters: interactionDetectorHandle=%p, countFeaturesInGroup=%" IntEbmTypePrintf ", featureIndexes=%p, countSamplesRequiredForChildSplitMin=%" IntEbmTypePrintf ", interactionScoreOut=%p",
static_cast<void *>(interactionDetectorHandle),
countFeaturesInGroup,
static_cast<const void *>(featureIndexes),
countSamplesRequiredForChildSplitMin,
static_cast<void *>(interactionScoreOut)
);
InteractionDetector * pInteractionDetector = reinterpret_cast<InteractionDetector *>(interactionDetectorHandle);
if(nullptr == pInteractionDetector) {
if(LIKELY(nullptr != interactionScoreOut)) {
*interactionScoreOut = FloatEbmType { 0 };
}
LOG_0(TraceLevelError, "ERROR CalculateInteractionScore ebmInteraction cannot be nullptr");
return 1;
}
LOG_COUNTED_0(pInteractionDetector->GetPointerCountLogEnterMessages(), TraceLevelInfo, TraceLevelVerbose, "Entered CalculateInteractionScore");
if(countFeaturesInGroup < 0) {
if(LIKELY(nullptr != interactionScoreOut)) {
*interactionScoreOut = FloatEbmType { 0 };
}
LOG_0(TraceLevelError, "ERROR CalculateInteractionScore countFeaturesInGroup must be positive");
return 1;
}
if(0 != countFeaturesInGroup && nullptr == featureIndexes) {
if(LIKELY(nullptr != interactionScoreOut)) {
*interactionScoreOut = FloatEbmType { 0 };
}
LOG_0(TraceLevelError, "ERROR CalculateInteractionScore featureIndexes cannot be nullptr if 0 < countFeaturesInGroup");
return 1;
}
if(!IsNumberConvertable<size_t>(countFeaturesInGroup)) {
if(LIKELY(nullptr != interactionScoreOut)) {
*interactionScoreOut = FloatEbmType { 0 };
}
LOG_0(TraceLevelError, "ERROR CalculateInteractionScore countFeaturesInGroup too large to index");
return 1;
}
size_t cFeaturesInGroup = static_cast<size_t>(countFeaturesInGroup);
if(0 == cFeaturesInGroup) {
LOG_0(TraceLevelInfo, "INFO CalculateInteractionScore empty feature group");
if(nullptr != interactionScoreOut) {
// we return the lowest value possible for the interaction score, but we don't return an error since we handle it even though we'd prefer our
// caler be smarter about this condition
*interactionScoreOut = FloatEbmType { 0 };
}
return 0;
}
if(0 == pInteractionDetector->GetDataSetByFeature()->GetCountSamples()) {
// if there are zero samples, there isn't much basis to say whether there are interactions, so just return zero
LOG_0(TraceLevelInfo, "INFO CalculateInteractionScore zero samples");
if(nullptr != interactionScoreOut) {
// we return the lowest value possible for the interaction score, but we don't return an error since we handle it even though we'd prefer our
// caler be smarter about this condition
*interactionScoreOut = 0;
}
return 0;
}
size_t cSamplesRequiredForChildSplitMin = size_t { 1 }; // this is the min value
if(IntEbmType { 1 } <= countSamplesRequiredForChildSplitMin) {
cSamplesRequiredForChildSplitMin = static_cast<size_t>(countSamplesRequiredForChildSplitMin);
if(!IsNumberConvertable<size_t>(countSamplesRequiredForChildSplitMin)) {
// we can never exceed a size_t number of samples, so let's just set it to the maximum if we were going to overflow because it will generate
// the same results as if we used the true number
cSamplesRequiredForChildSplitMin = std::numeric_limits<size_t>::max();
}
} else {
LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScore countSamplesRequiredForChildSplitMin can't be less than 1. Adjusting to 1.");
}
const Feature * const aFeatures = pInteractionDetector->GetFeatures();
const IntEbmType * pFeatureIndexes = featureIndexes;
const IntEbmType * const pFeatureIndexesEnd = featureIndexes + cFeaturesInGroup;
do {
const IntEbmType indexFeatureInterop = *pFeatureIndexes;
if(indexFeatureInterop < 0) {
if(LIKELY(nullptr != interactionScoreOut)) {
*interactionScoreOut = FloatEbmType { 0 };
}
LOG_0(TraceLevelError, "ERROR CalculateInteractionScore featureIndexes value cannot be negative");
return 1;
}
if(!IsNumberConvertable<size_t>(indexFeatureInterop)) {
if(LIKELY(nullptr != interactionScoreOut)) {
*interactionScoreOut = FloatEbmType { 0 };
}
LOG_0(TraceLevelError, "ERROR CalculateInteractionScore featureIndexes value too big to reference memory");
return 1;
}
const size_t iFeatureInGroup = static_cast<size_t>(indexFeatureInterop);
if(pInteractionDetector->GetCountFeatures() <= iFeatureInGroup) {
if(LIKELY(nullptr != interactionScoreOut)) {
*interactionScoreOut = FloatEbmType { 0 };
}
LOG_0(TraceLevelError, "ERROR CalculateInteractionScore featureIndexes value must be less than the number of features");
return 1;
}
const Feature * const pFeature = &aFeatures[iFeatureInGroup];
if(pFeature->GetCountBins() <= 1) {
if(nullptr != interactionScoreOut) {
// we return the lowest value possible for the interaction score, but we don't return an error since we handle it even though we'd prefer
// our caler be smarter about this condition
*interactionScoreOut = 0;
}
LOG_0(TraceLevelInfo, "INFO CalculateInteractionScore feature with 0/1 value");
return 0;
}
++pFeatureIndexes;
} while(pFeatureIndexesEnd != pFeatureIndexes);
if(k_cDimensionsMax < cFeaturesInGroup) {
// if we try to run with more than k_cDimensionsMax we'll exceed our memory capacity, so let's exit here instead
LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScore k_cDimensionsMax < cFeaturesInGroup");
return 1;
}
// put the pFeatureGroup object on the stack. We want to put it into a FeatureGroup object since we want to share code with boosting,
// which calls things like building the tensor totals (which is templated to be compiled many times)
char FeatureGroupBuffer[FeatureGroup::GetFeatureGroupCountBytes(k_cDimensionsMax)];
FeatureGroup * const pFeatureGroup = reinterpret_cast<FeatureGroup *>(&FeatureGroupBuffer);
pFeatureGroup->Initialize(cFeaturesInGroup, 0);
pFeatureIndexes = featureIndexes; // restart from the start
FeatureGroupEntry * pFeatureGroupEntry = pFeatureGroup->GetFeatureGroupEntries();
do {
const IntEbmType indexFeatureInterop = *pFeatureIndexes;
EBM_ASSERT(0 <= indexFeatureInterop);
EBM_ASSERT(IsNumberConvertable<size_t>(indexFeatureInterop)); // we already checked indexFeatureInterop was good above
size_t iFeatureInGroup = static_cast<size_t>(indexFeatureInterop);
EBM_ASSERT(iFeatureInGroup < pInteractionDetector->GetCountFeatures());
const Feature * const pFeature = &aFeatures[iFeatureInGroup];
EBM_ASSERT(2 <= pFeature->GetCountBins()); // we should have filtered out anything with 1 bin above
pFeatureGroupEntry->m_pFeature = pFeature;
++pFeatureGroupEntry;
++pFeatureIndexes;
} while(pFeatureIndexesEnd != pFeatureIndexes);
if(ptrdiff_t { 0 } == pInteractionDetector->GetRuntimeLearningTypeOrCountTargetClasses() || ptrdiff_t { 1 } == pInteractionDetector->GetRuntimeLearningTypeOrCountTargetClasses()) {
LOG_0(TraceLevelInfo, "INFO CalculateInteractionScore target with 0/1 classes");
if(nullptr != interactionScoreOut) {
// if there is only 1 classification target, then we can predict the outcome with 100% accuracy and there is no need for logits or
// interactions or anything else. We return 0 since interactions have no benefit
*interactionScoreOut = FloatEbmType { 0 };
}
return 0;
}
// TODO : be smarter about our CachedInteractionThreadResources, otherwise why have it?
CachedInteractionThreadResources * const pCachedThreadResources = CachedInteractionThreadResources::Allocate();
if(nullptr == pCachedThreadResources) {
return 1;
}
IntEbmType ret = CalculateInteractionScoreInternal(
pCachedThreadResources,
pInteractionDetector,
pFeatureGroup,
cSamplesRequiredForChildSplitMin,
interactionScoreOut
);
CachedInteractionThreadResources::Free(pCachedThreadResources);
if(0 != ret) {
LOG_N(TraceLevelWarning, "WARNING CalculateInteractionScore returned %" IntEbmTypePrintf, ret);
}
if(nullptr != interactionScoreOut) {
// if *interactionScoreOut was negative for floating point instability reasons, we zero it so that we don't return a negative number to our caller
EBM_ASSERT(FloatEbmType { 0 } <= *interactionScoreOut);
LOG_COUNTED_N(
pInteractionDetector->GetPointerCountLogExitMessages(),
TraceLevelInfo,
TraceLevelVerbose,
"Exited CalculateInteractionScore %" FloatEbmTypePrintf, *interactionScoreOut
);
} else {
LOG_COUNTED_0(pInteractionDetector->GetPointerCountLogExitMessages(), TraceLevelInfo, TraceLevelVerbose, "Exited CalculateInteractionScore");
}
return ret;
}
| 49.002268 | 222 | 0.741323 | jruales |
9c35b8ac2db3bbc1bdeff2051048e22eec55d45b | 4,159 | cpp | C++ | BookSamples/Capitolo7/Filtro_Shelving_II_ordine/Filtro_Shelving_II_ordine/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | BookSamples/Capitolo7/Filtro_Shelving_II_ordine/Filtro_Shelving_II_ordine/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | BookSamples/Capitolo7/Filtro_Shelving_II_ordine/Filtro_Shelving_II_ordine/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string.h>
#include "audioIO.h"
#define F0 (3000)
#define FB (1000)
using namespace std;
typedef struct
{
float f0;
float fb;
float G;
float wL[2];
float wR[2];
} filtro;
/* Parametri del filtro Shelving del II ordine ----------------------- */
float shelving_II_ordine(float x, float f0, float fb, float G, float *xw)
{
float k, d, V0, H0, a, xh;
float y1, y;
V0 = pow(10, G/20.0); // G è in dB
H0 = V0 - 1;
k = tan(M_PI * fb / (float)SAMPLE_RATE);
d = -cos(2 * M_PI * f0 / (float)SAMPLE_RATE);
if (G >= 0)
a = (k - 1) / (k + 1); // Peak
else
a = (k - V0) / (k + V0); // Notch
xh = x - d * (1 - a) * xw[0] + a * xw[1];
y1 = -a * xh + d * (1 - a) * xw[0] + xw[1];
xw[1] = xw[0];
xw[0] = xh;
y = 0.5 * H0 * (x - y1) + x; // Peak/Notch
return y;
}
/* Stream Callback ------------------------------------------------------ */
static int stream_Callback(const void* inputBuffer, void* outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void* userData)
{
float *in = (float*)inputBuffer;
float *out = (float*)outputBuffer;
filtro *data = (filtro*)userData;
float f0 = data->f0, fb = data->fb, G = data->G;
float *wL = data->wL, *wR = data->wR;
unsigned long i;
(void)timeInfo;
(void)statusFlags;
for (i = 0; i<framesPerBuffer; i++)
{
*out++ = shelving_II_ordine(*in++, f0, fb, G, wL);
*out++ = shelving_II_ordine(*in++, f0, fb, G, wR);
}
return paContinue;
}
/* Print Error ------------------------------------------------------ */
int printError(PaError p_err)
{
Pa_Terminate();
cout << "Si è verificato un errore" << endl
<< "Codice di errore: " << p_err << endl
<< "Messaggio di errore: " << Pa_GetErrorText(p_err) << endl;
return -1;
}
/* Funzione MAIN ------------------------------------------------------ */
int main(int argc, char *argv[])
{
PaStreamParameters outputParameters;
PaStreamParameters inputParameters;
PaStream *stream;
PaError err;
filtro *h;
(void)argv;
(void)argc;
/* Inizializzazione di PortAudio*/
err = Pa_Initialize();
if (err != paNoError)
return(printError(err));
outputParameters.device = Pa_GetDefaultOutputDevice(); /* device di default in input */
outputParameters.channelCount = NUM_CANALI; /* stereo */
outputParameters.sampleFormat = PA_SAMPLE_TYPE; /* 32 bit floating point */
outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
outputParameters.hostApiSpecificStreamInfo = NULL;
inputParameters.device = Pa_GetDefaultInputDevice(); /* device di default in output */
inputParameters.channelCount = NUM_CANALI; /* stereo */
inputParameters.sampleFormat = PA_SAMPLE_TYPE; /* 32 bit floating point */
inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
inputParameters.hostApiSpecificStreamInfo = NULL;
h = (filtro*)malloc(sizeof(filtro));
h->f0 = F0;
h->fb = FB;
h->G = 20;
h->wL[0] = 0.0;
h->wL[1] = 0.0;
h->wR[0] = 0.0;
h->wR[1] = 0.0;
err = Pa_OpenStream(&stream,
&inputParameters,
&outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
paClipOff,
stream_Callback,
h );
if (err != paNoError)
return(printError(err));
err = Pa_StartStream(stream);
if (err != paNoError)
return(printError(err));
cout << "Premi ENTER per terminare il programma." << endl;
getchar();
err = Pa_StopStream(stream);
if (err != paNoError)
return(printError(err));
err = Pa_CloseStream(stream);
if (err != paNoError)
return(printError(err));
Pa_Terminate();
free(h);
return 0;
}
| 27.183007 | 108 | 0.550373 | mscarpiniti |
9c383eab4379b324dceb5df57df14d90c2349016 | 4,562 | cpp | C++ | hard/training_army/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | hard/training_army/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | hard/training_army/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// edge
struct E {
int from;
int to;
int cap;
int rev;
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, t;
cin >> n >> t;
int source = n + t;
int sink = n + t + 1;
int nodes_total = n + t + 2;
vector<int> skills(n, 0);
for (auto &i : skills) {
cin >> i;
}
vector<vector<int>> adj(nodes_total); // node -> edge id in es
int e_id = 0;
vector<E> es; // edges
// connect source and sink to skill nodes
for (int i = 0; i < skills.size(); ++i) {
adj[source].push_back(e_id);
adj[i].push_back(e_id + 1);
es.push_back(
E{.from = source, .to = i, .cap = skills[i], .rev = e_id + 1});
es.push_back(E{.from = i, .to = source, .cap = 0, .rev = e_id});
e_id += 2;
adj[i].push_back(e_id);
adj[sink].push_back(e_id + 1);
es.push_back(E{.from = i, .to = sink, .cap = 1, .rev = e_id + 1});
es.push_back(E{.from = sink, .to = i, .cap = 0, .rev = e_id});
e_id += 2;
}
// process trainer nodes
for (int i = 0; i < t; ++i) {
int l;
cin >> l;
vector<int> from(l, 0);
for (auto &j : from) {
cin >> j;
j--;
}
cin >> l;
vector<int> to(l, 0);
for (auto &j : to) {
cin >> j;
j--;
}
// connect trainer nodes to other skill nodes
for (auto j : from) {
adj[j].push_back(e_id);
adj[n + i].push_back(e_id + 1);
es.push_back(E{.from = j, .to = n + i, .cap = 1, .rev = e_id + 1});
es.push_back(E{.from = n + i, .to = j, .cap = 0, .rev = e_id});
e_id += 2;
}
for (auto j : to) {
adj[n + i].push_back(e_id);
adj[j].push_back(e_id + 1);
es.push_back(E{.from = n + i, .to = j, .cap = 1, .rev = e_id + 1});
es.push_back(E{.from = j, .to = n + i, .cap = 0, .rev = e_id});
e_id += 2;
}
}
assert(e_id == es.size());
vector<int> node_levels(nodes_total);
int ans = 0;
while (true) {
// construct level graph from residual graph
fill(node_levels.begin(), node_levels.end(), -1);
node_levels[source] = 0;
deque<int> q{source};
while (q.size() > 0) {
auto idx = q.front();
q.pop_front();
for (auto edge_id : adj[idx]) {
auto edge = es[edge_id];
assert(edge.from == idx);
int neighbour = edge.to;
int residual = edge.cap;
if ((residual > 0) && (node_levels[neighbour] == -1)) {
node_levels[neighbour] = node_levels[idx] + 1;
q.push_back(neighbour);
}
}
}
if (node_levels[sink] == -1) {
break;
}
// avoid searching repeatedly for adjacent edges to a node
vector<int> idx_edge_start(nodes_total, 0);
// find an augmenting path
auto dfs_search = [&](int cur, int par, int fwd_flow, auto f) -> int {
if (cur == sink || fwd_flow == 0) {
return fwd_flow;
}
for (int &index = idx_edge_start[cur]; index < adj[cur].size();
++index) {
int edge_id = adj[cur][index];
auto &edge = es[edge_id];
int neighbour = edge.to;
assert(edge.from == cur);
int residual = edge.cap;
if (node_levels[cur] + 1 == node_levels[neighbour] &&
residual > 0) {
int fwd_flow_constrained = min(fwd_flow, residual);
int fwd_augment =
f(neighbour, cur, fwd_flow_constrained, f);
if (fwd_augment > 0) {
edge.cap -= fwd_augment;
es[edge.rev].cap += fwd_augment;
assert(edge.cap >= 0);
assert(es[edge.rev].cap >= 0);
return fwd_augment;
}
}
}
return 0;
};
int flow;
do {
flow =
dfs_search(source, -1, numeric_limits<int>::max(), dfs_search);
ans += flow;
} while (flow > 0);
}
cout << ans << endl;
fflush(stdout);
return 0;
}
| 26.523256 | 79 | 0.437089 | exbibyte |
9c3b081fbe4be5f759063ecd100484698ed4247f | 778 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/thread/experimental/config/inline_namespace.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 17,104 | 2016-12-28T07:45:54.000Z | 2022-03-31T07:02:52.000Z | ios/Pods/boost-for-react-native/boost/thread/experimental/config/inline_namespace.hpp | c7yrus/alyson-v3 | 5ad95a8f782f5f5d2fd543d44ca6a8b093395965 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | ios/Pods/boost-for-react-native/boost/thread/experimental/config/inline_namespace.hpp | c7yrus/alyson-v3 | 5ad95a8f782f5f5d2fd543d44ca6a8b093395965 | [
"Apache-2.0"
] | 3,568 | 2016-12-28T07:47:46.000Z | 2022-03-31T02:13:19.000Z | #ifndef BOOST_THREAD_EXPERIMENTAL_CONFIG_INLINE_NAMESPACE_HPP
#define BOOST_THREAD_EXPERIMENTAL_CONFIG_INLINE_NAMESPACE_HPP
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Vicente J. Botet Escriba 2014. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/thread for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/config.hpp>
#if !defined(BOOST_NO_CXX11_INLINE_NAMESPACES)
# define BOOST_THREAD_INLINE_NAMESPACE(name) inline namespace name
#else
# define BOOST_THREAD_INLINE_NAMESPACE(name) namespace name
#endif
#endif
| 32.416667 | 78 | 0.642674 | Harshitha91 |
9c47edd0ee7c2fd984564056dbdd7887a290a433 | 17,345 | cc | C++ | util/cache.cc | paritytech/rocksdb | 362c69481d18f8bf1bc59d93750dfebf4705bd2e | [
"BSD-3-Clause"
] | 2 | 2021-04-22T06:28:43.000Z | 2021-11-12T06:34:16.000Z | util/cache.cc | paritytech/rocksdb | 362c69481d18f8bf1bc59d93750dfebf4705bd2e | [
"BSD-3-Clause"
] | null | null | null | util/cache.cc | paritytech/rocksdb | 362c69481d18f8bf1bc59d93750dfebf4705bd2e | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "rocksdb/cache.h"
#include "port/port.h"
#include "util/autovector.h"
#include "util/hash.h"
#include "util/mutexlock.h"
namespace rocksdb {
Cache::~Cache() {
}
namespace {
// LRU cache implementation
// An entry is a variable length heap-allocated structure.
// Entries are referenced by cache and/or by any external entity.
// The cache keeps all its entries in table. Some elements
// are also stored on LRU list.
//
// LRUHandle can be in these states:
// 1. Referenced externally AND in hash table.
// In that case the entry is *not* in the LRU. (refs > 1 && in_cache == true)
// 2. Not referenced externally and in hash table. In that case the entry is
// in the LRU and can be freed. (refs == 1 && in_cache == true)
// 3. Referenced externally and not in hash table. In that case the entry is
// in not on LRU and not in table. (refs >= 1 && in_cache == false)
//
// All newly created LRUHandles are in state 1. If you call LRUCache::Release
// on entry in state 1, it will go into state 2. To move from state 1 to
// state 3, either call LRUCache::Erase or LRUCache::Insert with the same key.
// To move from state 2 to state 1, use LRUCache::Lookup.
// Before destruction, make sure that no handles are in state 1. This means
// that any successful LRUCache::Lookup/LRUCache::Insert have a matching
// RUCache::Release (to move into state 2) or LRUCache::Erase (for state 3)
struct LRUHandle {
void* value;
void (*deleter)(const Slice&, void* value);
LRUHandle* next_hash;
LRUHandle* next;
LRUHandle* prev;
size_t charge; // TODO(opt): Only allow uint32_t?
size_t key_length;
uint32_t refs; // a number of refs to this entry
// cache itself is counted as 1
bool in_cache; // true, if this entry is referenced by the hash table
uint32_t hash; // Hash of key(); used for fast sharding and comparisons
char key_data[1]; // Beginning of key
Slice key() const {
// For cheaper lookups, we allow a temporary Handle object
// to store a pointer to a key in "value".
if (next == this) {
return *(reinterpret_cast<Slice*>(value));
} else {
return Slice(key_data, key_length);
}
}
void Free() {
assert((refs == 1 && in_cache) || (refs == 0 && !in_cache));
(*deleter)(key(), value);
delete[] reinterpret_cast<char*>(this);
}
};
// We provide our own simple hash table since it removes a whole bunch
// of porting hacks and is also faster than some of the built-in hash
// table implementations in some of the compiler/runtime combinations
// we have tested. E.g., readrandom speeds up by ~5% over the g++
// 4.4.3's builtin hashtable.
class HandleTable {
public:
HandleTable() : length_(0), elems_(0), list_(nullptr) { Resize(); }
template <typename T>
void ApplyToAllCacheEntries(T func) {
for (uint32_t i = 0; i < length_; i++) {
LRUHandle* h = list_[i];
while (h != nullptr) {
auto n = h->next_hash;
assert(h->in_cache);
func(h);
h = n;
}
}
}
~HandleTable() {
ApplyToAllCacheEntries([](LRUHandle* h) {
if (h->refs == 1) {
h->Free();
}
});
delete[] list_;
}
LRUHandle* Lookup(const Slice& key, uint32_t hash) {
return *FindPointer(key, hash);
}
LRUHandle* Insert(LRUHandle* h) {
LRUHandle** ptr = FindPointer(h->key(), h->hash);
LRUHandle* old = *ptr;
h->next_hash = (old == nullptr ? nullptr : old->next_hash);
*ptr = h;
if (old == nullptr) {
++elems_;
if (elems_ > length_) {
// Since each cache entry is fairly large, we aim for a small
// average linked list length (<= 1).
Resize();
}
}
return old;
}
LRUHandle* Remove(const Slice& key, uint32_t hash) {
LRUHandle** ptr = FindPointer(key, hash);
LRUHandle* result = *ptr;
if (result != nullptr) {
*ptr = result->next_hash;
--elems_;
}
return result;
}
private:
// The table consists of an array of buckets where each bucket is
// a linked list of cache entries that hash into the bucket.
uint32_t length_;
uint32_t elems_;
LRUHandle** list_;
// Return a pointer to slot that points to a cache entry that
// matches key/hash. If there is no such cache entry, return a
// pointer to the trailing slot in the corresponding linked list.
LRUHandle** FindPointer(const Slice& key, uint32_t hash) {
LRUHandle** ptr = &list_[hash & (length_ - 1)];
while (*ptr != nullptr &&
((*ptr)->hash != hash || key != (*ptr)->key())) {
ptr = &(*ptr)->next_hash;
}
return ptr;
}
void Resize() {
uint32_t new_length = 16;
while (new_length < elems_ * 1.5) {
new_length *= 2;
}
LRUHandle** new_list = new LRUHandle*[new_length];
memset(new_list, 0, sizeof(new_list[0]) * new_length);
uint32_t count = 0;
for (uint32_t i = 0; i < length_; i++) {
LRUHandle* h = list_[i];
while (h != nullptr) {
LRUHandle* next = h->next_hash;
uint32_t hash = h->hash;
LRUHandle** ptr = &new_list[hash & (new_length - 1)];
h->next_hash = *ptr;
*ptr = h;
h = next;
count++;
}
}
assert(elems_ == count);
delete[] list_;
list_ = new_list;
length_ = new_length;
}
};
// A single shard of sharded cache.
class LRUCache {
public:
LRUCache();
~LRUCache();
// Separate from constructor so caller can easily make an array of LRUCache
// if current usage is more than new capacity, the function will attempt to
// free the needed space
void SetCapacity(size_t capacity);
// Like Cache methods, but with an extra "hash" parameter.
Cache::Handle* Insert(const Slice& key, uint32_t hash,
void* value, size_t charge,
void (*deleter)(const Slice& key, void* value));
Cache::Handle* Lookup(const Slice& key, uint32_t hash);
void Release(Cache::Handle* handle);
void Erase(const Slice& key, uint32_t hash);
// Although in some platforms the update of size_t is atomic, to make sure
// GetUsage() and GetPinnedUsage() work correctly under any platform, we'll
// protect them with mutex_.
size_t GetUsage() const {
MutexLock l(&mutex_);
return usage_;
}
size_t GetPinnedUsage() const {
MutexLock l(&mutex_);
assert(usage_ >= lru_usage_);
return usage_ - lru_usage_;
}
void ApplyToAllCacheEntries(void (*callback)(void*, size_t),
bool thread_safe);
private:
void LRU_Remove(LRUHandle* e);
void LRU_Append(LRUHandle* e);
// Just reduce the reference count by 1.
// Return true if last reference
bool Unref(LRUHandle* e);
// Free some space following strict LRU policy until enough space
// to hold (usage_ + charge) is freed or the lru list is empty
// This function is not thread safe - it needs to be executed while
// holding the mutex_
void EvictFromLRU(size_t charge,
autovector<LRUHandle*>* deleted);
// Initialized before use.
size_t capacity_;
// Memory size for entries residing in the cache
size_t usage_;
// Memory size for entries residing only in the LRU list
size_t lru_usage_;
// mutex_ protects the following state.
// We don't count mutex_ as the cache's internal state so semantically we
// don't mind mutex_ invoking the non-const actions.
mutable port::Mutex mutex_;
// Dummy head of LRU list.
// lru.prev is newest entry, lru.next is oldest entry.
// LRU contains items which can be evicted, ie reference only by cache
LRUHandle lru_;
HandleTable table_;
};
LRUCache::LRUCache() : usage_(0), lru_usage_(0) {
// Make empty circular linked list
lru_.next = &lru_;
lru_.prev = &lru_;
}
LRUCache::~LRUCache() {}
bool LRUCache::Unref(LRUHandle* e) {
assert(e->refs > 0);
e->refs--;
return e->refs == 0;
}
// Call deleter and free
void LRUCache::ApplyToAllCacheEntries(void (*callback)(void*, size_t),
bool thread_safe) {
if (thread_safe) {
mutex_.Lock();
}
table_.ApplyToAllCacheEntries([callback](LRUHandle* h) {
callback(h->value, h->charge);
});
if (thread_safe) {
mutex_.Unlock();
}
}
void LRUCache::LRU_Remove(LRUHandle* e) {
assert(e->next != nullptr);
assert(e->prev != nullptr);
e->next->prev = e->prev;
e->prev->next = e->next;
e->prev = e->next = nullptr;
lru_usage_ -= e->charge;
}
void LRUCache::LRU_Append(LRUHandle* e) {
// Make "e" newest entry by inserting just before lru_
assert(e->next == nullptr);
assert(e->prev == nullptr);
e->next = &lru_;
e->prev = lru_.prev;
e->prev->next = e;
e->next->prev = e;
lru_usage_ += e->charge;
}
void LRUCache::EvictFromLRU(size_t charge,
autovector<LRUHandle*>* deleted) {
while (usage_ + charge > capacity_ && lru_.next != &lru_) {
LRUHandle* old = lru_.next;
assert(old->in_cache);
assert(old->refs == 1); // LRU list contains elements which may be evicted
LRU_Remove(old);
table_.Remove(old->key(), old->hash);
old->in_cache = false;
Unref(old);
usage_ -= old->charge;
deleted->push_back(old);
}
}
void LRUCache::SetCapacity(size_t capacity) {
autovector<LRUHandle*> last_reference_list;
{
MutexLock l(&mutex_);
capacity_ = capacity;
EvictFromLRU(0, &last_reference_list);
}
// we free the entries here outside of mutex for
// performance reasons
for (auto entry : last_reference_list) {
entry->Free();
}
}
Cache::Handle* LRUCache::Lookup(const Slice& key, uint32_t hash) {
MutexLock l(&mutex_);
LRUHandle* e = table_.Lookup(key, hash);
if (e != nullptr) {
assert(e->in_cache);
if (e->refs == 1) {
LRU_Remove(e);
}
e->refs++;
}
return reinterpret_cast<Cache::Handle*>(e);
}
void LRUCache::Release(Cache::Handle* handle) {
LRUHandle* e = reinterpret_cast<LRUHandle*>(handle);
bool last_reference = false;
{
MutexLock l(&mutex_);
last_reference = Unref(e);
if (last_reference) {
usage_ -= e->charge;
}
if (e->refs == 1 && e->in_cache) {
// The item is still in cache, and nobody else holds a reference to it
if (usage_ > capacity_) {
// the cache is full
// The LRU list must be empty since the cache is full
assert(lru_.next == &lru_);
// take this opportunity and remove the item
table_.Remove(e->key(), e->hash);
e->in_cache = false;
Unref(e);
usage_ -= e->charge;
last_reference = true;
} else {
// put the item on the list to be potentially freed
LRU_Append(e);
}
}
}
// free outside of mutex
if (last_reference) {
e->Free();
}
}
Cache::Handle* LRUCache::Insert(
const Slice& key, uint32_t hash, void* value, size_t charge,
void (*deleter)(const Slice& key, void* value)) {
// Allocate the memory here outside of the mutex
// If the cache is full, we'll have to release it
// It shouldn't happen very often though.
LRUHandle* e = reinterpret_cast<LRUHandle*>(
new char[sizeof(LRUHandle) - 1 + key.size()]);
autovector<LRUHandle*> last_reference_list;
e->value = value;
e->deleter = deleter;
e->charge = charge;
e->key_length = key.size();
e->hash = hash;
e->refs = 2; // One from LRUCache, one for the returned handle
e->next = e->prev = nullptr;
e->in_cache = true;
memcpy(e->key_data, key.data(), key.size());
{
MutexLock l(&mutex_);
// Free the space following strict LRU policy until enough space
// is freed or the lru list is empty
EvictFromLRU(charge, &last_reference_list);
// insert into the cache
// note that the cache might get larger than its capacity if not enough
// space was freed
LRUHandle* old = table_.Insert(e);
usage_ += e->charge;
if (old != nullptr) {
old->in_cache = false;
if (Unref(old)) {
usage_ -= old->charge;
// old is on LRU because it's in cache and its reference count
// was just 1 (Unref returned 0)
LRU_Remove(old);
last_reference_list.push_back(old);
}
}
}
// we free the entries here outside of mutex for
// performance reasons
for (auto entry : last_reference_list) {
entry->Free();
}
return reinterpret_cast<Cache::Handle*>(e);
}
void LRUCache::Erase(const Slice& key, uint32_t hash) {
LRUHandle* e;
bool last_reference = false;
{
MutexLock l(&mutex_);
e = table_.Remove(key, hash);
if (e != nullptr) {
last_reference = Unref(e);
if (last_reference) {
usage_ -= e->charge;
}
if (last_reference && e->in_cache) {
LRU_Remove(e);
}
e->in_cache = false;
}
}
// mutex not held here
// last_reference will only be true if e != nullptr
if (last_reference) {
e->Free();
}
}
static int kNumShardBits = 4; // default values, can be overridden
class ShardedLRUCache : public Cache {
private:
LRUCache* shards_;
port::Mutex id_mutex_;
port::Mutex capacity_mutex_;
uint64_t last_id_;
int num_shard_bits_;
size_t capacity_;
static inline uint32_t HashSlice(const Slice& s) {
return Hash(s.data(), s.size(), 0);
}
uint32_t Shard(uint32_t hash) {
// Note, hash >> 32 yields hash in gcc, not the zero we expect!
return (num_shard_bits_ > 0) ? (hash >> (32 - num_shard_bits_)) : 0;
}
public:
ShardedLRUCache(size_t capacity, int num_shard_bits)
: last_id_(0), num_shard_bits_(num_shard_bits), capacity_(capacity) {
int num_shards = 1 << num_shard_bits_;
shards_ = new LRUCache[num_shards];
const size_t per_shard = (capacity + (num_shards - 1)) / num_shards;
for (int s = 0; s < num_shards; s++) {
shards_[s].SetCapacity(per_shard);
}
}
virtual ~ShardedLRUCache() {
delete[] shards_;
}
virtual void SetCapacity(size_t capacity) override {
int num_shards = 1 << num_shard_bits_;
const size_t per_shard = (capacity + (num_shards - 1)) / num_shards;
MutexLock l(&capacity_mutex_);
for (int s = 0; s < num_shards; s++) {
shards_[s].SetCapacity(per_shard);
}
capacity_ = capacity;
}
virtual Handle* Insert(const Slice& key, void* value, size_t charge,
void (*deleter)(const Slice& key,
void* value)) override {
const uint32_t hash = HashSlice(key);
return shards_[Shard(hash)].Insert(key, hash, value, charge, deleter);
}
virtual Handle* Lookup(const Slice& key) override {
const uint32_t hash = HashSlice(key);
return shards_[Shard(hash)].Lookup(key, hash);
}
virtual void Release(Handle* handle) override {
LRUHandle* h = reinterpret_cast<LRUHandle*>(handle);
shards_[Shard(h->hash)].Release(handle);
}
virtual void Erase(const Slice& key) override {
const uint32_t hash = HashSlice(key);
shards_[Shard(hash)].Erase(key, hash);
}
virtual void* Value(Handle* handle) override {
return reinterpret_cast<LRUHandle*>(handle)->value;
}
virtual uint64_t NewId() override {
MutexLock l(&id_mutex_);
return ++(last_id_);
}
virtual size_t GetCapacity() const override { return capacity_; }
virtual size_t GetUsage() const override {
// We will not lock the cache when getting the usage from shards.
int num_shards = 1 << num_shard_bits_;
size_t usage = 0;
for (int s = 0; s < num_shards; s++) {
usage += shards_[s].GetUsage();
}
return usage;
}
virtual size_t GetUsage(Handle* handle) const override {
return reinterpret_cast<LRUHandle*>(handle)->charge;
}
virtual size_t GetPinnedUsage() const override {
// We will not lock the cache when getting the usage from shards.
int num_shards = 1 << num_shard_bits_;
size_t usage = 0;
for (int s = 0; s < num_shards; s++) {
usage += shards_[s].GetPinnedUsage();
}
return usage;
}
virtual void DisownData() override { shards_ = nullptr; }
virtual void ApplyToAllCacheEntries(void (*callback)(void*, size_t),
bool thread_safe) override {
int num_shards = 1 << num_shard_bits_;
for (int s = 0; s < num_shards; s++) {
shards_[s].ApplyToAllCacheEntries(callback, thread_safe);
}
}
};
} // end anonymous namespace
shared_ptr<Cache> NewLRUCache(size_t capacity) {
return NewLRUCache(capacity, kNumShardBits);
}
shared_ptr<Cache> NewLRUCache(size_t capacity, int num_shard_bits) {
if (num_shard_bits >= 20) {
return nullptr; // the cache cannot be sharded into too many fine pieces
}
return std::make_shared<ShardedLRUCache>(capacity, num_shard_bits);
}
} // namespace rocksdb
| 29.751286 | 79 | 0.638109 | paritytech |
9c4b32435f73e16e3c625751edcb717c87c70655 | 1,402 | cpp | C++ | CK3toEU4/Source/Mappers/ReligionGroupScraper/ReligionGroupScraper.cpp | Idhrendur/CK3toEU4 | 25137130f14d78ade8962dfc87ff9c4fc237973d | [
"MIT"
] | 1 | 2020-09-03T00:08:27.000Z | 2020-09-03T00:08:27.000Z | CK3toEU4/Source/Mappers/ReligionGroupScraper/ReligionGroupScraper.cpp | PheonixScale9094/CK3toEU4 | fcf891880ec6cc5cbafbb4d249b5c9f6528f9fd0 | [
"MIT"
] | null | null | null | CK3toEU4/Source/Mappers/ReligionGroupScraper/ReligionGroupScraper.cpp | PheonixScale9094/CK3toEU4 | fcf891880ec6cc5cbafbb4d249b5c9f6528f9fd0 | [
"MIT"
] | null | null | null | #include "ReligionGroupScraper.h"
#include "Log.h"
#include "OSCompatibilityLayer.h"
#include "ParserHelpers.h"
#include "ReligionGroupScraping.h"
#include "CommonRegexes.h"
mappers::ReligionGroupScraper::ReligionGroupScraper()
{
LOG(LogLevel::Info) << "-> Scraping religion hierarchy.";
registerKeys();
for (const auto& fileName: commonItems::GetAllFilesInFolder("blankmod/output/common/religions/"))
parseFile("blankmod/output/common/religions/" + fileName);
clearRegisteredKeywords();
LOG(LogLevel::Info) << "<> Loaded " << religionGroups.size() << " religion groups.";
}
mappers::ReligionGroupScraper::ReligionGroupScraper(std::istream& theStream)
{
registerKeys();
parseStream(theStream);
clearRegisteredKeywords();
}
void mappers::ReligionGroupScraper::registerKeys()
{
registerRegex(commonItems::catchallRegex, [this](const std::string& religionGroupName, std::istream& theStream) {
const auto religions = ReligionGroupScraping(theStream);
const auto& foundReligions = religions.getReligionNames();
religionGroups[religionGroupName].insert(foundReligions.begin(), foundReligions.end());
});
}
std::optional<std::string> mappers::ReligionGroupScraper::getReligionGroupForReligion(const std::string& religion) const
{
for (const auto& religionGroupItr: religionGroups)
if (religionGroupItr.second.count(religion))
return religionGroupItr.first;
return std::nullopt;
}
| 34.195122 | 120 | 0.773894 | Idhrendur |
9c4da66bcaa4000103323c8634fea629a15c3aa5 | 5,376 | cpp | C++ | src/graphs/laplacian.cpp | wmotte/toolkid | 2a8f82e1492c9efccde9a4935ce3019df1c68cde | [
"MIT"
] | null | null | null | src/graphs/laplacian.cpp | wmotte/toolkid | 2a8f82e1492c9efccde9a4935ce3019df1c68cde | [
"MIT"
] | null | null | null | src/graphs/laplacian.cpp | wmotte/toolkid | 2a8f82e1492c9efccde9a4935ce3019df1c68cde | [
"MIT"
] | null | null | null | #include "tkdCmdParser.h"
#include "graphCommon.h"
/**
* Calculate (normalized) laplacian and eigenvector/values.
*/
class Laplacian
{
public:
typedef double PixelType;
/**
* Run app.
*/
void Run( const std::string& filename, const std::string& outputFileName,
bool normalize,
const std::string& outputFileNameEigen,
unsigned int numberOfEigenVectors,
bool outputEigenFiles,
const std::string& outputFileNameKmeans,
unsigned int numberOfClusters,
bool outputKmeans,
bool sparse )
{
// get dimensions...
unsigned int dims = graph::Graph< PixelType >::GetImageDimensions( filename );
if ( dims == 2 )
{
graph::Graph< PixelType >::ImagePointerType image;
graph::Graph< PixelType >::ReadMatrix( image, filename );
PixelType* buffer = image->GetPixelContainer()->GetBufferPointer( );
graph::Graph< PixelType >::ImageType::RegionType region = image->GetLargestPossibleRegion( );
graph::Graph< PixelType >::ImageType::SizeType size = region.GetSize();
int rows = size[ 0 ];
int cols = size[ 1 ];
graph::Graph< PixelType >::DataMatrixType G( rows, cols, buffer );
graph::Graph< PixelType >::DiagMatrixType D;
graph::Graph< PixelType >::MatrixType L;
// [ 1 ]
graph::Graph< PixelType >::CalculateLaplacian( L, G, D, normalize );
// [ 2 ]
graph::Graph< PixelType >::MatrixType eigenVectors;
graph::Graph< PixelType >::VectorType eigenValues;
if( sparse )
{
// convert dense matrix into sparse matrix...
vnl_sparse_matrix< PixelType > S( L.rows(), L.cols() );
for( unsigned int i = 0; i < L.rows(); i++ )
for( unsigned int j = i; j < L.cols(); j++ )
if( L( i, j ) != 0 )
S( i, j ) = L( i, j );
graph::Graph< PixelType >::GeneralizedEigenCalculation( S, eigenVectors, eigenValues, numberOfEigenVectors );
}
else
graph::Graph< PixelType >::GeneralizedEigenCalculation( L, D, eigenVectors, eigenValues );
// Output eigenfiles...
graph::Graph< PixelType >::WriteEigenFiles( outputFileNameEigen, numberOfEigenVectors, eigenVectors, eigenValues );
if( !outputFileName.empty() )
{
graph::Graph< PixelType >::WriteMatrixToFile( L, outputFileName );
}
// [ 3 ] Optional: run KMEANS++
if( outputKmeans )
{
graph::Graph< PixelType >::VectorType clusters;
graph::Graph< PixelType >::KMeansPP( eigenVectors, numberOfClusters, clusters );
graph::Graph< PixelType >::WriteVectorToFile(
outputFileNameKmeans + "_clusters.txt", clusters );
}
}
else
{
std::cerr << "Number of input (matrix) dimensions should be 2!"<< std::endl;
exit( EXIT_FAILURE );
}
}
};
/**
* Main.
*/
int main( int argc, char ** argv )
{
tkd::CmdParser p( argv[0], "Compute Laplacian of graph's adjacency matrix");
std::string inputFileName;
std::string outputFileName;
std::string outputFileNameEigen = "eigen";
int numberOfEigenVectors = 15;
bool outputEigenFiles = false;
bool normalize = false;
std::string outputFileNameKmeans = "kmeans";
int numberOfClusters = 15;
bool outputKmeans = false;
bool sparse = false;
p.AddArgument( inputFileName, "input" )
->AddAlias( "i" )
->SetInput( "filename" )
->SetDescription( "Input image: 2D adjacency matrix" )
->SetRequired( true );
p.AddArgument( outputFileName, "output" )
->AddAlias( "o" )
->SetInput( "filename" )
->SetDescription( "Output image: 2D laplacian matrix" )
->SetRequired( false );
p.AddArgument( outputFileNameEigen, "output-eigen-root" )
->AddAlias( "oer" )
->SetInput( "root filename" )
->SetDescription( "Root eigen files (default: 'eigen')" )
->SetRequired( false );
p.AddArgument( numberOfEigenVectors, "output-eigenvector-number" )
->AddAlias( "oen" )
->SetInput( "int" )
->SetDescription( "Number of eigenvectors to output (default: 15; first (zero) eigenvector is ignored)" )
->SetRequired( false );
p.AddArgument( outputEigenFiles, "output-eigen-files" )
->AddAlias( "oef" )
->SetInput( "bool" )
->SetDescription( "Output eigenvectors and eigenvalues (default: false)" )
->SetRequired( false );
p.AddArgument( outputFileNameKmeans, "output-kmeans-root" )
->AddAlias( "okr" )
->SetInput( "root filename" )
->SetDescription( "Root kmeans files (default: 'kmeans')" )
->SetRequired( false );
p.AddArgument( numberOfClusters, "output-kmeans-clusters" )
->AddAlias( "okc" )
->SetInput( "int" )
->SetDescription( "Number of clusters to output (default: 15)" )
->SetRequired( false );
p.AddArgument( outputKmeans, "output-kmeans-file" )
->AddAlias( "okf" )
->SetInput( "bool" )
->SetDescription( "Output kmeans++ segmentation (default: false)" )
->SetRequired( false );
p.AddArgument( normalize, "normalize" )
->AddAlias( "n" )
->SetInput( "bool" )
->SetDescription( "Normalize laplacian matrix (default: false)" )
->SetRequired( false );
p.AddArgument( sparse, "sparse" )
->AddAlias( "s" )
->SetInput( "bool" )
->SetDescription( "Use Lanczos algorithm to estimate eigen-vectors (default: false)" )
->SetRequired( false );
if ( !p.Parse( argc, argv ) )
{
p.PrintUsage( std::cout );
return EXIT_FAILURE;
}
Laplacian laplacian;
laplacian.Run( inputFileName, outputFileName, normalize,
outputFileNameEigen, (unsigned) numberOfEigenVectors, outputEigenFiles,
outputFileNameKmeans, (unsigned) numberOfClusters, outputKmeans, sparse );
return EXIT_SUCCESS;
}
| 28.748663 | 118 | 0.678943 | wmotte |
9c4e385a8b4226636de01172b84b207f5451ceb8 | 4,656 | cc | C++ | uuv_sensor_plugins/uuv_sensor_plugins/src/MagnetometerPlugin.cc | Abhi10arora/uuv_simulator | bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | uuv_sensor_plugins/uuv_sensor_plugins/src/MagnetometerPlugin.cc | Abhi10arora/uuv_simulator | bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | uuv_sensor_plugins/uuv_sensor_plugins/src/MagnetometerPlugin.cc | Abhi10arora/uuv_simulator | bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2018-10-18T15:11:01.000Z | 2018-10-18T15:11:01.000Z | // Copyright (c) 2016 The UUV Simulator 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.
//
// This source code is derived from hector_gazebo
// (https://github.com/tu-darmstadt-ros-pkg/hector_gazebo)
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt,
// licensed under the BSD 3-Clause license,
// cf. 3rd-party-licenses.txt file in the root directory of this source tree.
//
// The original code was modified to:
// - be more consistent with other sensor plugins within uuv_simulator,
// - remove its dependency on ROS. The ROS interface is instead implemented in
// a derived class within the uuv_sensor_plugins_ros package,
// - adhere to Gazebo's coding standards.
#include <uuv_sensor_plugins/MagnetometerPlugin.hh>
#include <gazebo/physics/physics.hh>
#include "Common.hh"
namespace gazebo {
GazeboMagnetometerPlugin::GazeboMagnetometerPlugin()
: GazeboSensorPlugin()
{
}
GazeboMagnetometerPlugin::~GazeboMagnetometerPlugin()
{
}
void GazeboMagnetometerPlugin::Load(physics::ModelPtr _model,
sdf::ElementPtr _sdf)
{
GazeboSensorPlugin::Load(_model, _sdf);
// Load settings specific to this type of sensor
getSdfParam<double>(_sdf, "intensity", parameters_.intensity, 1.0);
getSdfParam<double>(_sdf, "referenceHeading", parameters_.heading, M_PI);
getSdfParam<double>(_sdf, "declination", parameters_.declination, 0.0);
getSdfParam<double>(_sdf, "inclination", parameters_.inclination,
60.*M_PI/180.);
getSdfParam<double>(_sdf, "noise_xy", parameters_.noiseXY, 1.0);
getSdfParam<double>(_sdf, "noise_z", parameters_.noiseZ, 1.4);
getSdfParam<double>(_sdf, "turn_on_bias", parameters_.turnOnBias, 2.0);
// Now Prepare derived values
// Note: Gazebo uses NorthWestUp coordinate system,
// heading and declination are compass headings
magneticFieldWorld_.x = parameters_.intensity*cos(parameters_.inclination)
* cos(parameters_.heading - parameters_.declination);
magneticFieldWorld_.y = parameters_.intensity*cos(parameters_.inclination)
* sin(parameters_.heading - parameters_.declination);
magneticFieldWorld_.z = parameters_.intensity
*(-sin(parameters_.inclination));
turnOnBias_.x = parameters_.turnOnBias *
normal_(rndGen_);
turnOnBias_.y = parameters_.turnOnBias *
normal_(rndGen_);
turnOnBias_.z = parameters_.turnOnBias *
normal_(rndGen_);
// Fill constant fields of sensor message already
// TODO: This should better be a 3x3 matrix instead
magneticGazeboMessage_.add_magnetic_field_covariance(
parameters_.noiseXY*parameters_.noiseXY);
magneticGazeboMessage_.add_magnetic_field_covariance(
parameters_.noiseXY*parameters_.noiseXY);
magneticGazeboMessage_.add_magnetic_field_covariance(
parameters_.noiseZ*parameters_.noiseZ);
if (this->sensorTopic_.empty())
this->sensorTopic_ = "magnetometer";
publisher_ = nodeHandle_->Advertise<sensor_msgs::msgs::Magnetic>(
sensorTopic_, 10);
}
void GazeboMagnetometerPlugin::SimulateMeasurement(
const common::UpdateInfo& info)
{
math::Pose pose = link_->GetWorldPose();
math::Vector3 noise(parameters_.noiseXY*normal_(rndGen_),
parameters_.noiseXY*normal_(rndGen_),
parameters_.noiseZ*normal_(rndGen_));
measMagneticField_ = pose.rot.RotateVectorReverse(magneticFieldWorld_)
+ turnOnBias_ + noise;
}
bool GazeboMagnetometerPlugin::OnUpdate(const common::UpdateInfo& _info)
{
if (!ShouldIGenerate(_info))
return false;
SimulateMeasurement(_info);
gazebo::msgs::Vector3d* field = new gazebo::msgs::Vector3d();
field->set_x(this->measMagneticField_.x);
field->set_y(this->measMagneticField_.y);
field->set_z(this->measMagneticField_.z);
this->magneticGazeboMessage_.set_allocated_magnetic_field(field);
publisher_->Publish(magneticGazeboMessage_);
return true;
}
GZ_REGISTER_MODEL_PLUGIN(GazeboMagnetometerPlugin);
}
| 36.375 | 78 | 0.717354 | Abhi10arora |
9c4ee80c068c69dfe9733e6e35573ed539111929 | 632 | cpp | C++ | t1m1/FOSSSim/ExplicitEuler.cpp | dailysoap/CSMM.104x | 4515b30ab5f60827a9011b23ef155a3063584a9d | [
"MIT"
] | null | null | null | t1m1/FOSSSim/ExplicitEuler.cpp | dailysoap/CSMM.104x | 4515b30ab5f60827a9011b23ef155a3063584a9d | [
"MIT"
] | null | null | null | t1m1/FOSSSim/ExplicitEuler.cpp | dailysoap/CSMM.104x | 4515b30ab5f60827a9011b23ef155a3063584a9d | [
"MIT"
] | null | null | null | #include "ExplicitEuler.h"
bool ExplicitEuler::stepScene( TwoDScene& scene, scalar dt )
{
// Your code goes here!
// Some tips on getting data from TwoDScene:
// A vector containing all of the system's position DoFs. x0, y0, x1, y1, ...
//VectorXs& x = scene.getX();
// A vector containing all of the system's velocity DoFs. v0, v0, v1, v1, ...
//VectorXs& v = scene.getV();
// A vector containing the masses associated to each DoF. m0, m0, m1, m1, ...
//const VectorXs& m = scene.getM();
// Determine if the ith particle is fixed
// if( scene.isFixed(i) )
return true;
}
| 31.6 | 81 | 0.620253 | dailysoap |
9c52156354e973d58ee13f744cf22c0fdb5f0dd2 | 18,521 | hpp | C++ | include/beap_view.hpp | degski/beap | 6fffd5b536f29ed7551bdbe66ad20eb39e7024c8 | [
"MIT"
] | 1 | 2020-03-12T15:17:50.000Z | 2020-03-12T15:17:50.000Z | include/beap_view.hpp | degski/beap | 6fffd5b536f29ed7551bdbe66ad20eb39e7024c8 | [
"MIT"
] | null | null | null | include/beap_view.hpp | degski/beap | 6fffd5b536f29ed7551bdbe66ad20eb39e7024c8 | [
"MIT"
] | null | null | null |
// MIT License
//
// Copyright (c) 2020 degski
//
// 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, rhs_, 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 <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <compare>
#include <limits>
#include <optional>
#include <span>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "detail/hedley.hpp"
#define BEAP_PURE HEDLEY_PURE
#define BEAP_UNPREDICTABLE HEDLEY_UNPREDICTABLE
#define BEAP_LIKELY HEDLEY_LIKELY
#define BEAP_UNLIKELY HEDLEY_UNLIKELY
#include "detail/triangular.hpp"
#define ever \
; \
;
template<typename ValueType, typename SignedSizeType = int32_t, typename Compare = std::less<SignedSizeType>>
class beap_view {
// Current beap_height of beap_view. Note that beap_height is defined as
// distance between consecutive layers, so for single - element
// beap_view beap_height is 0, and for empty, we initialize it to - 1.
//
// An example of the lay-out:
//
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ..
// { 72, 68, 63, 44, 62, 55, 33, 22, 32, 51, 13, 18, 21, 19, 22, 11, 12, 14, 17, 9, 13, 3, 2, 10, 54 }
// _ _ _ _ _ _ _ _
public:
using size_type = SignedSizeType;
private:
template<typename T, typename Comp>
struct basic_value_type {
T v;
constexpr basic_value_type ( T value_ ) noexcept : v{ value_ } {}
[[nodiscard]] constexpr size_type operator<=> ( basic_value_type const & r_ ) const noexcept {
return static_cast<size_type> ( static_cast<int> ( not( Comp ( ) ( r_.v, v ) ) ) -
static_cast<int> ( Comp ( ) ( v, r_.v ) ) );
};
template<typename Stream>
[[maybe_unused]] friend Stream & operator<< ( Stream & out_, basic_value_type const & value_ ) noexcept {
out_ << value_.v;
return out_;
}
};
using value_type = basic_value_type<ValueType, Compare>;
using container_type = std::vector<value_type>;
using container_type_ptr = std::vector<value_type> *;
public:
using difference_type = size_type;
using reference = typename container_type::reference;
using const_reference = typename container_type::const_reference;
using pointer = typename container_type::pointer;
using const_pointer = typename container_type::const_pointer;
using iterator = typename container_type::iterator;
using const_iterator = typename container_type::const_iterator;
using reverse_iterator = typename container_type::reverse_iterator;
using const_reverse_iterator = typename container_type::const_reverse_iterator;
private:
using span_type = tri::basic_span_type<size_type>;
public:
beap_view ( ) noexcept = delete;
beap_view ( beap_view const & b_ ) = default;
beap_view ( beap_view && b_ ) = delete;
beap_view ( std::vector<ValueType> & data_ ) :
container ( reinterpret_cast<std::vector<value_type> *> ( &data_ ) ),
data ( reinterpret_cast<value_type *> ( data_.data ( ) ) ),
end_span ( span_type::span ( tri::nth_triangular_root ( static_cast<size_type> ( data_.size ( ) ) ) - 1 ) ) {}
[[maybe_unused]] beap_view & operator= ( beap_view const & b_ ) = default;
[[maybe_unused]] beap_view & operator= ( beap_view && b_ ) = delete;
// Operations (private).
private:
[[nodiscard]] span_type search ( value_type const & v ) const noexcept {
span_type s = end_span;
size_type beap_height = s.end - s.beg, i = s.beg + 1, h = beap_height, len = length ( );
for ( ever ) {
switch ( value_type const & d = data[ i ]; BEAP_UNPREDICTABLE ( v <=> d ) ) {
case -1: {
if ( BEAP_UNLIKELY ( i == ( len - 1 ) ) ) {
--s, i -= h--;
continue;
}
if ( size_type i_ = i + h + 2; BEAP_UNLIKELY ( i_ < len ) ) {
++s, i = i_, h += 1;
continue;
}
if ( BEAP_UNLIKELY ( i++ == ( s.end - 1 ) ) )
return { end_span.end, beap_height };
continue;
}
case +1: {
if ( BEAP_UNLIKELY ( i == s.end ) )
return { end_span.end, beap_height };
--s, i -= h--;
continue;
}
default: {
return { i, h };
}
}
}
}
[[nodiscard]] size_type breadth_first_search ( value_type const & v_ ) noexcept {
size_type siz = size ( );
for ( size_type base_l = 0, base_i = tri::nth_triangular ( base_l ); BEAP_UNLIKELY ( base_i < siz );
base_l += 1, base_i += base_l + 1 ) {
for ( size_type lev = base_l + 1, l_i = base_i + 2, r_i = base_i + ( lev + 2 ) - 2;
BEAP_UNLIKELY ( l_i < siz and r_i < siz ); lev += 1, l_i += ( lev + 1 ), r_i += ( ( lev + 2 ) - 2 ) ) {
if ( BEAP_UNLIKELY ( v_ == data[ l_i ] ) )
return l_i;
if ( BEAP_UNLIKELY ( v_ == data[ r_i ] ) )
return r_i;
}
}
return siz;
}
[[maybe_unused]] size_type bubble_up ( size_type i_, size_type h_ ) noexcept {
span_type s = end_span;
while ( BEAP_LIKELY ( h_ ) ) {
span_type p = s.prev ( );
size_type d = i_ - s.beg;
size_type l = 0, r = 0;
if ( BEAP_UNLIKELY ( i_ != s.beg ) )
l = p.beg + d - 1;
if ( BEAP_UNLIKELY ( i_ != s.end ) )
r = p.beg + d;
if ( BEAP_UNPREDICTABLE ( ( l ) and ( refof ( i_ ) > refof ( l ) ) and ( not r or ( refof ( l ) < refof ( r ) ) ) ) ) {
std::swap ( refof ( i_ ), refof ( l ) );
i_ = l;
}
else if ( BEAP_UNPREDICTABLE ( ( r ) and ( refof ( i_ ) > refof ( r ) ) ) ) {
std::swap ( refof ( i_ ), refof ( r ) );
i_ = r;
}
else {
return i_;
}
s = p;
h_ -= 1;
}
assert ( i_ == 0 );
return i_;
}
[[nodiscard]] size_type bubble_down ( size_type i_, size_type h_ ) noexcept {
span_type s = end_span;
size_type const h_1 = s.end - s.beg - 1, len = length ( );
while ( BEAP_LIKELY ( h_ < h_1 ) ) {
span_type c = s.next ( );
size_type l = c.beg + i_ - s.beg, r = 0;
if ( BEAP_LIKELY ( l < len ) ) {
r = l + 1;
if ( BEAP_UNLIKELY ( r >= len ) )
r = 0;
}
else {
l = 0;
}
if ( BEAP_UNPREDICTABLE ( l and refof ( i_ ) < refof ( l ) and ( not r or refof ( l ) > refof ( r ) ) ) ) {
std::swap ( refof ( i_ ), refof ( l ) );
i_ = l;
}
else if ( BEAP_UNPREDICTABLE ( r and refof ( i_ ) < refof ( r ) ) ) {
std::swap ( refof ( i_ ), refof ( r ) );
i_ = r;
}
else {
return i_;
}
s = c;
h_ += 1;
}
return i_;
}
[[maybe_unused]] void erase_impl ( size_type i_, size_type h_ ) noexcept {
size_type len = length ( );
if ( BEAP_UNLIKELY ( len == end_span.beg ) ) {
--end_span;
shrink_to_fit ( ); // only when load is less than 50%.
}
assert ( i_ != ( len - 1 ) );
refof ( i_ ) = pop_data ( );
if ( size_type i = bubble_down ( i_, h_ ); BEAP_LIKELY ( i == i_ ) )
bubble_up ( i_, h_ );
}
template<typename... Args>
[[maybe_unused]] size_type emplace_impl ( size_type i_, Args... args_ ) noexcept {
container->emplace_back ( std::forward<Args> ( args_ )... );
return bubble_up ( i_, end_span.end - end_span.beg );
}
// Operations (public).
public:
[[maybe_unused]] size_type insert ( value_type const & v_ ) { return emplace ( value_type{ v_ } ); }
template<typename ForwardIt>
void insert ( ForwardIt b_, ForwardIt e_ ) noexcept {
reserve ( tri::nth_triangular_ceil ( static_cast<size_type> ( container->size ( ) + std::distance ( b_, e_ ) ) ) );
size_type c = size ( );
while ( b_ != e_ )
emplace_impl ( c++, value_type{ *b_ } );
}
// clang-format on
template<typename... Args>
[[maybe_unused]] size_type emplace ( Args... args_ ) {
size_type i = length ( );
if ( BEAP_UNLIKELY ( i == end_span.end ) ) {
++end_span;
reserve ( end_span.end );
}
return emplace_impl ( i, std::forward<Args> ( args_ )... );
}
template<typename ForwardIt>
[[maybe_unused]] void emplace ( ForwardIt b_, ForwardIt e_ ) noexcept {
reserve ( tri::nth_triangular_ceil ( static_cast<size_type> ( container->size ( ) + std::distance ( b_, e_ ) ) ) );
size_type c = size ( );
while ( b_ != e_ )
emplace_impl ( c++, std::move ( *b_ ) );
}
void erase ( value_type const & v_ ) noexcept {
auto [ i, h ] = search ( v_ );
if ( BEAP_UNLIKELY ( i == end_span.end ) )
return;
erase_impl ( i, h );
}
void erase_by_index ( size_type i_ ) noexcept {
if ( BEAP_UNLIKELY ( i_ == end_span.end ) )
return;
erase_impl ( i_, tri::nth_triangular_root ( i_ ) );
}
[[nodiscard]] size_type find ( value_type const & v_ ) const noexcept { return search ( v_ ).beg; }
[[nodiscard]] bool contains ( value_type const & v_ ) const noexcept { return find ( v_ ) != end_span.end; }
// Sizes.
[[nodiscard]] BEAP_PURE size_type size ( ) const noexcept { return static_cast<int> ( container->size ( ) ); }
[[nodiscard]] BEAP_PURE size_type length ( ) const noexcept { return size ( ); }
[[nodiscard]] BEAP_PURE size_type capacity ( ) const noexcept { return static_cast<int> ( container->capacity ( ) ); }
void shrink_to_fit ( ) {
if ( BEAP_UNLIKELY ( ( capacity ( ) >> 1 ) == size ( ) ) ) { // iff 100% over-allocated, force shrinking.
container_type tmp;
tmp.reserve ( end_span.end );
*container = std::move ( ( tmp = *container ) );
data = container->data ( );
}
}
public:
[[nodiscard]] BEAP_PURE iterator begin ( ) noexcept { return container->begin ( ); }
[[nodiscard]] BEAP_PURE const_iterator cbegin ( ) const noexcept { return container->begin ( ); }
[[nodiscard]] BEAP_PURE iterator end ( ) noexcept { return container->end ( ); }
[[nodiscard]] BEAP_PURE const_iterator cend ( ) const noexcept { return container->end ( ); }
[[nodiscard]] BEAP_PURE iterator rbegin ( ) noexcept { return container->rbegin ( ); }
[[nodiscard]] BEAP_PURE const_iterator crbegin ( ) const noexcept { return container->rbegin ( ); }
[[nodiscard]] BEAP_PURE iterator rend ( ) noexcept { return container->rend ( ); }
[[nodiscard]] BEAP_PURE const_iterator crend ( ) const noexcept { return container->rend ( ); }
// Beap.
static inline void make_beap ( ) noexcept {
end_span = span_type::span ( 0 );
size_type c = 1;
iterator b = container->begin ( ) + 1, e = container->end ( );
while ( b != e )
emplace_impl ( c++, std::move ( *b ) );
}
[[nodiscard]] static inline ValueType pop_beap ( ) noexcept {
after_exit_erase_top guard ( this );
return container->front ( ).v;
}
[[maybe_unused]] size_type push_beap ( value_type const & v_ ) { return insert ( v_ ); }
[[nodiscard]] BEAP_PURE reference top ( ) noexcept { return container->front ( ); }
[[nodiscard]] BEAP_PURE const_reference top ( ) const noexcept { return container->front ( ); }
[[nodiscard]] BEAP_PURE const_reference bottom ( ) const noexcept {
for ( size_type min = end_span.beg, i = min + 1, data_end = size ( ); BEAP_LIKELY ( i < data_end ); ++i )
if ( BEAP_UNPREDICTABLE ( data[ i ] < data[ min ] ) )
min = i;
}
[[nodiscard]] BEAP_PURE reference bottom ( ) noexcept { return const_cast<reference> ( std::as_const ( this )->bottom ( ) ); }
template<typename ForwardIt>
[[nodiscard]] static ForwardIt is_beap_untill ( ForwardIt b_, ForwardIt e_ ) noexcept {
auto const data = &*b_;
// 72,
// 68, 63,
// 44, 62, 55,
// 33, 22, 32, 51,
// 13, 18, 21, 19, 31,
// 11, 12, 14, 17, 9, 13,
// 3, 2, 10
size_type size = static_cast<size_type> ( std::distance ( b_, e_ ) );
// Searches for out-of-order element, top-down and breadth-first.
for ( size_type base_l = 0, base_i = tri::nth_triangular ( base_l ); BEAP_UNLIKELY ( base_i < size );
base_l += 1, base_i += base_l + 1 ) {
for ( size_type lev = base_l + 1, l_p = base_i - lev + 1, l_i = l_p + ( lev ) + 1, r_p = base_i,
r_i = r_p + ( lev + 2 ) - 2;
BEAP_UNLIKELY ( l_i < size and r_i < size ); lev += 1, l_i += ( lev + 1 ), r_i += ( ( lev + 2 ) - 2 ) ) {
if ( not BEAP_UNLIKELY ( Compare ( ) ( data[ l_i ], data[ l_p ] ) ) )
return b_ + l_i;
if ( not BEAP_UNLIKELY ( Compare ( ) ( data[ r_i ], data[ r_p ] ) ) )
return b_ + r_i;
l_p = l_i;
r_p = r_i;
}
}
return e_;
}
template<typename ForwardIt>
[[nodiscard]] static bool is_beap ( ForwardIt b_, ForwardIt e_ ) noexcept {
return is_beap_untill ( b_, e_ ) == e_;
}
[[nodiscard]] size_type is_beap_untill ( ) noexcept {
// Searches for out-of-order element, top-down and breadth-first.
size_type siz = size ( );
for ( size_type base_l = 0, base_i = tri::nth_triangular ( base_l ); BEAP_UNLIKELY ( base_i < siz );
base_l += 1, base_i += base_l + 1 ) {
for ( size_type lev = base_l + 1, l_p = base_i - lev + 1, l_i = l_p + ( lev ) + 1, r_p = base_i,
r_i = r_p + ( lev + 2 ) - 2;
BEAP_UNLIKELY ( l_i < siz and r_i < siz ); lev += 1, l_i += ( lev + 1 ), r_i += ( ( lev + 2 ) - 2 ) ) {
if ( not BEAP_UNLIKELY ( data[ l_i ] < data[ l_p ] ) )
return l_i;
if ( not BEAP_UNLIKELY ( data[ r_i ] < data[ r_p ] ) )
return r_i;
l_p = l_i;
r_p = r_i;
}
}
return siz;
}
// Miscelanious.
void clear ( ) noexcept { container->clear ( ); }
[[nodiscard]] constexpr size_type max_size ( ) const noexcept { return std::numeric_limits<size_type>::max ( ); }
void swap ( beap_view & rhs_ ) noexcept { std::swap ( *this, rhs_ ); }
[[nodiscard]] bool contains ( ValueType const & v_ ) const noexcept { return search ( v_ ).beg; }
[[nodiscard]] bool empty ( ) const noexcept { return container->empty ( ); }
// Output.
template<typename Stream>
[[maybe_unused]] friend Stream & operator<< ( Stream & out_, beap_view const & beap_ ) noexcept {
std::for_each ( beap_.cbegin ( ), beap_.cend ( ), [ &out_ ] ( auto & e ) { out_ << e << sp; } );
return out_;
}
// Miscelanious.
private:
[[nodiscard]] BEAP_PURE const_reference refof ( size_type i_ ) const noexcept { return data[ i_ ]; }
[[nodiscard]] BEAP_PURE reference refof ( size_type i_ ) noexcept { return data[ i_ ]; }
struct after_exit_erase_top {
beap_view * b;
after_exit_erase_top ( beap_view * b_ ) noexcept : b ( b_ ) {}
~after_exit_erase_top ( ) noexcept { b->erase_impl ( 0, 1 ); };
};
struct after_exit_pop_back {
container_type_ptr c;
after_exit_pop_back ( container_type_ptr c_ ) noexcept : c ( c_ ) {}
~after_exit_pop_back ( ) noexcept { c->pop_back ( ); }
};
[[nodiscard]] value_type pop_data ( ) noexcept {
after_exit_pop_back guard ( container );
return container->back ( );
}
void reserve ( size_type c_ ) {
container->reserve ( static_cast<std::size_t> ( c_ ) );
data = container->data ( );
}
// Members.
container_type_ptr container = nullptr;
pointer data = nullptr;
span_type end_span = { 0, 0 };
};
#undef PRIVATE
#undef PUBLIC
#undef BEAP_PURE
#undef BEAP_UNPREDICTABLE
#undef BEAP_LIKELY
#undef BEAP_UNLIKELY
#undef ever
| 39.915948 | 132 | 0.528049 | degski |
9c53de73ff008b60db768a75560594941870e0d9 | 1,000 | cpp | C++ | src/Core/Status.cpp | anisimovsergey/gluino_test | 7de141362cafb244841b13b7b86c17d00f550fba | [
"MIT"
] | 5 | 2017-10-07T06:46:23.000Z | 2018-12-10T07:14:47.000Z | src/Core/Status.cpp | anisimovsergey/gluino_test | 7de141362cafb244841b13b7b86c17d00f550fba | [
"MIT"
] | 8 | 2017-01-07T15:01:32.000Z | 2017-07-16T20:18:10.000Z | src/Core/Status.cpp | anisimovsergey/gluino_test | 7de141362cafb244841b13b7b86c17d00f550fba | [
"MIT"
] | 4 | 2017-01-07T14:58:00.000Z | 2019-10-30T09:38:53.000Z | #include "Status.hpp"
#include "Memory.hpp"
using namespace Core;
Status Status::OK(StatusCode::OK, "OK");
Status Status::NotImplemented(StatusCode::NotImplemented, "Not implemented.");
Status::Status() : code(StatusCode::OK), message("OK") {
}
Status::Status(const StatusCode& code, const std::string& message) :
code(code), message(message) {
}
Status::Status(const StatusCode& code, const std::string& message, const Status& innerResult) :
code(code), message(message), innerStatus(std::make_unique<Status>(innerResult)) {
}
Status::Status(const Status& status) :
code(status.code), message(status.message) {
if (status.getInnerStatus()) {
innerStatus = std::make_unique<Status>(*status.getInnerStatus());
}
}
Status&
Status::operator = (const Status& status) {
if (this != &status) {
code = status.code;
message = status.message;
if (status.getInnerStatus()) {
innerStatus = std::make_unique<Status>(*status.getInnerStatus());
}
}
return *this;
}
| 26.315789 | 95 | 0.693 | anisimovsergey |
9c56ca81ea5c09699806b48f266a19f636eb89df | 9,051 | hpp | C++ | include/sprout/cstdlib/str_to_float.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | 4 | 2021-12-29T22:17:40.000Z | 2022-03-23T11:53:44.000Z | dsp/lib/sprout/sprout/cstdlib/str_to_float.hpp | TheSlowGrowth/TapeLooper | ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264 | [
"MIT"
] | 16 | 2021-10-31T21:41:09.000Z | 2022-01-22T10:51:34.000Z | include/sprout/cstdlib/str_to_float.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_CSTDLIB_STR_TO_FLOAT_HPP
#define SPROUT_CSTDLIB_STR_TO_FLOAT_HPP
#include <cstdlib>
#include <cmath>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/workaround/std/cstddef.hpp>
#include <sprout/limits.hpp>
#include <sprout/iterator/operation.hpp>
#include <sprout/ctype/ascii.hpp>
#include <sprout/detail/char_literal.hpp>
#include <sprout/detail/char_type_of_consecutive.hpp>
namespace sprout {
namespace detail {
template<typename FloatType, typename NullTerminatedIterator>
inline SPROUT_CONSTEXPR FloatType
str_to_float_impl_scale(
NullTerminatedIterator const& str,
bool negative,
FloatType number = FloatType(),
std::size_t num_digits = 0,
std::size_t num_decimals = 0,
long exponent = 0,
long n = 0,
FloatType p10 = FloatType(10)
)
{
return n ? sprout::detail::str_to_float_impl_scale<FloatType>(
str,
negative,
n & 1 ? (exponent < 0 ? number / p10 : number * p10) : number,
num_digits,
num_decimals,
exponent,
n >> 1,
p10 * p10
)
: number
;
}
template<typename FloatType, typename NullTerminatedIterator>
inline SPROUT_CONSTEXPR FloatType
str_to_float_impl_exponent_2(
NullTerminatedIterator const& str,
bool negative,
FloatType number = FloatType(),
std::size_t num_digits = 0,
std::size_t num_decimals = 0,
long exponent = 0
)
{
return exponent >= sprout::numeric_limits<FloatType>::min_exponent
&& exponent <= sprout::numeric_limits<FloatType>::max_exponent
? sprout::detail::str_to_float_impl_scale<FloatType>(
str,
negative,
number,
num_digits,
num_decimals,
exponent,
exponent < 0 ? -exponent : exponent
)
: HUGE_VAL
;
}
template<typename FloatType, typename NullTerminatedIterator>
inline SPROUT_CONSTEXPR FloatType
str_to_float_impl_exponent_1(
NullTerminatedIterator const& str,
bool negative,
FloatType number = FloatType(),
std::size_t num_digits = 0,
std::size_t num_decimals = 0,
long exponent = 0,
long n = 0
)
{
typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type;
SPROUT_STATIC_ASSERT(sprout::detail::is_char_type_of_consecutive_digits<char_type>::value);
return sprout::ascii::isdigit(*str) ? sprout::detail::str_to_float_impl_exponent_1<FloatType>(
sprout::next(str),
negative,
number,
num_digits,
num_decimals,
exponent,
n * 10 + (*str - SPROUT_CHAR_LITERAL('0', char_type))
)
: sprout::detail::str_to_float_impl_exponent_2<FloatType>(
str,
negative,
number,
num_digits,
num_decimals,
negative ? exponent + n : exponent - n
)
;
}
template<typename FloatType, typename NullTerminatedIterator>
inline SPROUT_CONSTEXPR FloatType
str_to_float_impl_exponent(
NullTerminatedIterator const& str,
bool negative,
FloatType number = FloatType(),
std::size_t num_digits = 0,
std::size_t num_decimals = 0,
long exponent = 0
)
{
typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type;
return (*str == SPROUT_CHAR_LITERAL('e', char_type) || *str == SPROUT_CHAR_LITERAL('E', char_type))
? *sprout::next(str) == SPROUT_CHAR_LITERAL('-', char_type)
? sprout::detail::str_to_float_impl_exponent_1<FloatType>(
sprout::next(str, 2),
true,
number,
num_digits,
num_decimals,
exponent
)
: sprout::detail::str_to_float_impl_exponent_1<FloatType>(
sprout::next(str, 2),
false,
number,
num_digits,
num_decimals,
exponent
)
: sprout::detail::str_to_float_impl_exponent_2<FloatType>(
str,
negative,
number,
num_digits,
num_decimals,
exponent
)
;
}
template<typename FloatType, typename NullTerminatedIterator>
inline SPROUT_CONSTEXPR FloatType
str_to_float_impl_decimal_1(
NullTerminatedIterator const& str,
bool negative,
FloatType number = FloatType(),
std::size_t num_digits = 0,
std::size_t num_decimals = 0,
long exponent = 0
)
{
return num_digits == 0 ? FloatType()
: sprout::detail::str_to_float_impl_exponent<FloatType>(
str,
negative,
negative ? -number : number,
num_digits,
num_decimals,
exponent
)
;
}
template<typename FloatType, typename NullTerminatedIterator>
inline SPROUT_CONSTEXPR FloatType
str_to_float_impl_decimal(
NullTerminatedIterator const& str,
bool negative,
FloatType number = FloatType(),
std::size_t num_digits = 0,
std::size_t num_decimals = 0,
long exponent = 0
)
{
typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type;
SPROUT_STATIC_ASSERT(sprout::detail::is_char_type_of_consecutive_digits<char_type>::value);
return sprout::ascii::isdigit(*str) ? sprout::detail::str_to_float_impl_decimal<FloatType>(
sprout::next(str),
negative,
number * 10 + (*str - SPROUT_CHAR_LITERAL('0', char_type)),
num_digits + 1,
num_decimals + 1,
exponent
)
: sprout::detail::str_to_float_impl_decimal_1<FloatType>(
str,
negative,
number,
num_digits,
num_decimals,
exponent - num_decimals
)
;
}
template<typename FloatType, typename NullTerminatedIterator>
inline SPROUT_CONSTEXPR FloatType
str_to_float_impl(
NullTerminatedIterator const& str,
bool negative,
FloatType number = FloatType(),
std::size_t num_digits = 0
)
{
typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type;
SPROUT_STATIC_ASSERT(sprout::detail::is_char_type_of_consecutive_digits<char_type>::value);
return sprout::ascii::isdigit(*str) ? sprout::detail::str_to_float_impl<FloatType>(
sprout::next(str),
negative,
number * 10 + (*str - SPROUT_CHAR_LITERAL('0', char_type)),
num_digits + 1
)
: *str == SPROUT_CHAR_LITERAL('.', char_type) ? sprout::detail::str_to_float_impl_decimal<FloatType>(
sprout::next(str),
negative,
number,
num_digits
)
: sprout::detail::str_to_float_impl_decimal_1<FloatType>(
str,
negative,
number,
num_digits
)
;
}
template<typename FloatType, typename NullTerminatedIterator>
inline SPROUT_CONSTEXPR FloatType
str_to_float(NullTerminatedIterator const& str) {
typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type;
return sprout::ascii::isspace(*str)
? sprout::detail::str_to_float<FloatType>(sprout::next(str))
: *str == SPROUT_CHAR_LITERAL('-', char_type)
? sprout::detail::str_to_float_impl<FloatType>(sprout::next(str), true)
: *str == SPROUT_CHAR_LITERAL('+', char_type)
? sprout::detail::str_to_float_impl<FloatType>(sprout::next(str), false)
: sprout::detail::str_to_float_impl<FloatType>(str, false)
;
}
template<typename FloatType, typename NullTerminatedIterator, typename CharPtr>
inline SPROUT_CONSTEXPR FloatType
str_to_float(NullTerminatedIterator const& str, CharPtr* endptr) {
return !endptr ? sprout::detail::str_to_float<FloatType>(str)
#if defined(__MINGW32__)
: std::is_same<typename std::remove_cv<FloatType>::type, float>::value ? ::strtof(&*str, endptr)
: std::is_same<typename std::remove_cv<FloatType>::type, double>::value ? std::strtod(&*str, endptr)
: ::strtold(&*str, endptr)
#else
: std::is_same<typename std::remove_cv<FloatType>::type, float>::value ? std::strtof(&*str, endptr)
: std::is_same<typename std::remove_cv<FloatType>::type, double>::value ? std::strtod(&*str, endptr)
: std::strtold(&*str, endptr)
#endif
;
}
} // namespace detail
//
// str_to_float
//
template<typename FloatType, typename Char>
inline SPROUT_CONSTEXPR typename std::enable_if<
std::is_floating_point<FloatType>::value,
FloatType
>::type
str_to_float(Char const* str, Char** endptr) {
return sprout::detail::str_to_float<FloatType>(str, endptr);
}
template<typename FloatType, typename Char>
inline SPROUT_CONSTEXPR typename std::enable_if<
std::is_floating_point<FloatType>::value,
FloatType
>::type
str_to_float(Char const* str, std::nullptr_t) {
return sprout::detail::str_to_float<FloatType>(str);
}
template<typename FloatType, typename Char>
inline SPROUT_CONSTEXPR typename std::enable_if<
std::is_floating_point<FloatType>::value,
FloatType
>::type
str_to_float(Char const* str) {
return sprout::detail::str_to_float<FloatType>(str);
}
} // namespace sprout
#endif // #ifndef SPROUT_CSTDLIB_STR_TO_FLOAT_HPP
| 30.681356 | 105 | 0.689537 | thinkoid |
9c578e32666ef7cd89a35e26154d369a33841d14 | 5,032 | cpp | C++ | inference-engine/src/multi_device/multi_device_async_infer_request.cpp | oxygenxo/openvino | a984e7e81bcf4a18138b57632914b5a88815282d | [
"Apache-2.0"
] | null | null | null | inference-engine/src/multi_device/multi_device_async_infer_request.cpp | oxygenxo/openvino | a984e7e81bcf4a18138b57632914b5a88815282d | [
"Apache-2.0"
] | 27 | 2020-12-29T14:38:34.000Z | 2022-02-21T13:04:03.000Z | inference-engine/src/multi_device/multi_device_async_infer_request.cpp | dorloff/openvino | 1c3848a96fdd325b044babe6d5cd26db341cf85b | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <string>
#include <vector>
#include <memory>
#include <map>
#include "multi_device_async_infer_request.hpp"
namespace MultiDevicePlugin {
using namespace InferenceEngine;
MultiDeviceAsyncInferRequest::MultiDeviceAsyncInferRequest(
const MultiDeviceInferRequest::Ptr& inferRequest,
const bool needPerfCounters,
const MultiDeviceExecutableNetwork::Ptr& multiDeviceExecutableNetwork,
const ITaskExecutor::Ptr& callbackExecutor) :
AsyncInferRequestThreadSafeDefault(inferRequest, nullptr, callbackExecutor),
_multiDeviceExecutableNetwork{multiDeviceExecutableNetwork},
_inferRequest{inferRequest},
_needPerfCounters{needPerfCounters} {
// this executor starts the inference while the task (checking the result) is passed to the next stage
struct ThisRequestExecutor : public ITaskExecutor {
explicit ThisRequestExecutor(MultiDeviceAsyncInferRequest* _this_) : _this{_this_} {}
void run(Task task) override {
auto workerInferRequest = _this->_workerInferRequest;
workerInferRequest->_task = std::move(task);
workerInferRequest->_inferRequest.StartAsync();
};
MultiDeviceAsyncInferRequest* _this = nullptr;
};
_pipeline = {
// if the request is coming with device-specific remote blobs make sure it is scheduled to the specific device only:
{ /*TaskExecutor*/ std::make_shared<ImmediateExecutor>(), /*task*/ [this] {
// by default, no preferred device:
_multiDeviceExecutableNetwork->_thisPreferredDeviceName = "";
// if any input is remote (e.g. was set with SetBlob), let' use the corresponding device
for (const auto &it : _multiDeviceExecutableNetwork->GetInputsInfo()) {
Blob::Ptr b;
_inferRequest->GetBlob(it.first.c_str(), b);
auto r = b->as<RemoteBlob>();
if (r) {
const auto name = r->getDeviceName();
const auto res = std::find_if(
_multiDeviceExecutableNetwork->_devicePrioritiesInitial.cbegin(),
_multiDeviceExecutableNetwork->_devicePrioritiesInitial.cend(),
[&name](const MultiDevicePlugin::DeviceInformation& d){ return d.deviceName == name; });
if (_multiDeviceExecutableNetwork->_devicePrioritiesInitial.cend() == res) {
THROW_IE_EXCEPTION << "None of the devices (for which current MULTI-device configuration was "
"initialized) supports a remote blob created on the device named " << name;
} else {
// it is ok to take the c_str() here (as pointed in the multi_device_exec_network.hpp we need to use const char*)
// as the original strings are from the "persistent" vector (with the right lifetime)
_multiDeviceExecutableNetwork->_thisPreferredDeviceName = res->deviceName.c_str();
break;
}
}
}
}},
// as the scheduling algo may select any device, this stage accepts the scheduling decision (actual workerRequest)
// then sets the device-agnostic blobs to the actual (device-specific) request
{
/*TaskExecutor*/ _multiDeviceExecutableNetwork, /*task*/ [this] {
_workerInferRequest = MultiDeviceExecutableNetwork::_thisWorkerInferRequest;
_inferRequest->SetBlobsToAnotherRequest(_workerInferRequest->_inferRequest);
}},
// final task in the pipeline:
{ /*TaskExecutor*/std::make_shared<ThisRequestExecutor>(this), /*task*/ [this] {
auto status = _workerInferRequest->_status;
if (InferenceEngine::StatusCode::OK != status) {
if (nullptr != InferenceEngine::CurrentException())
std::rethrow_exception(InferenceEngine::CurrentException());
else
THROW_IE_EXCEPTION << InferenceEngine::details::as_status << status;
}
if (_needPerfCounters)
_perfMap = _workerInferRequest->_inferRequest.GetPerformanceCounts();
}}
};
}
void MultiDeviceAsyncInferRequest::Infer_ThreadUnsafe() {
InferUsingAsync();
}
void MultiDeviceAsyncInferRequest::GetPerformanceCounts_ThreadUnsafe(std::map<std::string, InferenceEngineProfileInfo> &perfMap) const {
perfMap = std::move(_perfMap);
}
MultiDeviceAsyncInferRequest::~MultiDeviceAsyncInferRequest() {
StopAndWait();
}
} // namespace MultiDevicePlugin
| 50.828283 | 141 | 0.614269 | oxygenxo |
9c59b39adaec4554bc712f329391175a5ffd0c10 | 3,695 | cpp | C++ | src/Bme280Spi.cpp | karol57/Bme280SpiTest | ecbd64a71396f63be1e4595b2562f6feaa6690ae | [
"MIT"
] | null | null | null | src/Bme280Spi.cpp | karol57/Bme280SpiTest | ecbd64a71396f63be1e4595b2562f6feaa6690ae | [
"MIT"
] | null | null | null | src/Bme280Spi.cpp | karol57/Bme280SpiTest | ecbd64a71396f63be1e4595b2562f6feaa6690ae | [
"MIT"
] | null | null | null | #include "Bme280Spi.hpp"
#include <cstring>
#include <iostream>
#include <thread>
#include <chrono>
namespace {
void ensureValidSpiSpeed(SpiDevice& spi)
{
constexpr uint32_t Mhz20 = 20'000'000;
if (const uint32_t spiSpeed = spi.getMaxSpeedHz(); spiSpeed > Mhz20)
{
spi.setMaxSpeedHz(Mhz20);
std::cout << "Reduced SPI speed from " << spiSpeed << " Hz to " << Mhz20 << " Hz" << std::endl;
}
}
void delayUs(uint32_t period, void */*intf_ptr*/)
{
std::this_thread::sleep_for(std::chrono::microseconds(period));
}
int8_t spiRead(uint8_t reg_addr, uint8_t * const reg_data, uint32_t len, void * const intf_ptr)
{
if (not reg_data or not intf_ptr)
return BME280_E_NULL_PTR;
SpiDevice& bme280 = *reinterpret_cast<SpiDevice*>(intf_ptr);
spi_ioc_transfer xfer[2] = {};
xfer[0].tx_buf = reinterpret_cast<uintptr_t>(®_addr);
xfer[0].len = 1;
xfer[1].rx_buf = reinterpret_cast<uintptr_t>(reg_data);
xfer[1].len = len;
bme280.transfer(xfer);
return BME280_OK;
}
int8_t spiWrite(uint8_t reg_addr, const uint8_t * const reg_data, uint32_t len, void * const intf_ptr)
{
if (not reg_data or not intf_ptr)
return BME280_E_NULL_PTR;
SpiDevice& bme280 = *reinterpret_cast<SpiDevice*>(intf_ptr);
spi_ioc_transfer xfer[2] = {};
xfer[0].tx_buf = reinterpret_cast<uintptr_t>(®_addr);
xfer[0].len = 1;
xfer[1].tx_buf = reinterpret_cast<uintptr_t>(reg_data);
xfer[1].len = len;
bme280.transfer(xfer);
return BME280_OK;
}
[[gnu::cold, noreturn]]
static void throwBME280Error(int8_t error)
{
switch (error)
{
case BME280_E_NULL_PTR: throw std::runtime_error("BME280: Null pointer");
case BME280_E_DEV_NOT_FOUND: throw std::runtime_error("BME280: Device not found");
case BME280_E_INVALID_LEN: throw std::runtime_error("BME280: Invalid length");
case BME280_E_COMM_FAIL: throw std::runtime_error("BME280: Communication failure");
case BME280_E_SLEEP_MODE_FAIL: throw std::runtime_error("BME280: Sleep mode failure");
case BME280_E_NVM_COPY_FAILED: throw std::runtime_error("BME280: NVM copy failed");
default:
throw std::runtime_error("BME280: Unknown error " + std::to_string(error));
}
}
static void verifyBme280Result(int8_t result)
{
if (result < 0)
throwBME280Error(result);
switch (result)
{
case BME280_OK: return;
case BME280_W_INVALID_OSR_MACRO:
std::cerr << "BME280: Invalid osr macro";
break;
default:
std::cerr << "BME280: Unknown warning " << result;
}
}
}
Bme280Spi::Bme280Spi(const char* path)
: m_spi(path)
{
ensureValidSpiSpeed(m_spi);
m_dev.intf_ptr = &m_spi;
m_dev.intf = BME280_SPI_INTF;
m_dev.read = spiRead;
m_dev.write = spiWrite;
m_dev.delay_us = delayUs;
verifyBme280Result(bme280_init(&m_dev));
// Temporary default initialization
m_dev.settings.osr_h = BME280_OVERSAMPLING_1X;
m_dev.settings.osr_p = BME280_OVERSAMPLING_16X;
m_dev.settings.osr_t = BME280_OVERSAMPLING_2X;
m_dev.settings.filter = BME280_FILTER_COEFF_16;
uint8_t settings_sel = BME280_OSR_PRESS_SEL | BME280_OSR_TEMP_SEL | BME280_OSR_HUM_SEL | BME280_FILTER_SEL;
verifyBme280Result(bme280_set_sensor_settings(settings_sel, &m_dev));
verifyBme280Result(bme280_set_sensor_mode(BME280_NORMAL_MODE, &m_dev));
std::this_thread::sleep_for(std::chrono::milliseconds(bme280_cal_meas_delay(&m_dev.settings)));
}
bme280_data Bme280Spi::getData()
{
bme280_data result;
verifyBme280Result(bme280_get_sensor_data(BME280_ALL, &result, &m_dev));
return result;
} | 32.699115 | 111 | 0.69364 | karol57 |
9c5a54d102180c96470f77c1515c8b5ea4243363 | 3,115 | cpp | C++ | trainings/2015-08-02-ZOJ-Monthly-2015-July/F.cpp | HcPlu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | 9 | 2017-10-07T13:35:45.000Z | 2021-06-07T17:36:55.000Z | trainings/2015-08-02-ZOJ-Monthly-2015-July/F.cpp | zhijian-liu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | null | null | null | trainings/2015-08-02-ZOJ-Monthly-2015-July/F.cpp | zhijian-liu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | 3 | 2018-04-24T05:27:21.000Z | 2019-04-25T06:06:00.000Z | #include <cstdio>
#include <iostream>
using namespace std;
const int N = 10000010;
int n, m;
int num[N], a[111111];
bool U_prime[N];
int cnt = 0;
struct Node {
int l, r, Max, sum;
} tree[400444];
void update(int root) {
tree[root].Max = max(tree[root << 1].Max, tree[root << 1 | 1].Max);
tree[root].sum = tree[root << 1].sum + tree[root << 1 | 1].sum;
return;
}
void build(int root, int x, int y) {
tree[root].l = x, tree[root].r = y;
if (x == y) {
tree[root].Max = a[x];
tree[root].sum = num[a[x]];
return;
}
int mid = x + y >> 1;
build(root << 1, x, mid);
build(root << 1 | 1, mid + 1, y);
update(root);
}
void update(int root, int x, int y) {
if (tree[root].l == tree[root].r) {
tree[root].Max = y;
tree[root].sum = num[y];
return;
}
int mid = tree[root].l + tree[root].r >> 1;
if (x <= mid) {
update(root << 1, x, y);
} else {
update(root << 1 | 1, x, y);
}
update(root);
}
int Query(int root, int x, int y) {
if (tree[root].l == x && tree[root].r == y) {
return tree[root].sum;
}
int mid = tree[root].l + tree[root].r >> 1;
if (y <= mid) {
return Query(root << 1, x, y);
} else if (x > mid) {
return Query(root << 1 | 1, x, y);
} else {
return Query(root << 1, x, mid) + Query(root << 1 | 1, mid + 1, y);
}
}
void update(int root, int x, int y, int key) {
if (tree[root].l == x && tree[root].r == y && tree[root].Max < key) {
return;
}
if (tree[root].l == tree[root].r) {
tree[root].Max %= key;
tree[root].sum = num[tree[root].Max];
return;
}
int mid = tree[root].l + tree[root].r >> 1;
if (y <= mid) {
update(root << 1, x, y, key);
} else if (x > mid) {
update(root << 1 | 1, x, y, key);
} else {
update(root << 1, x, mid, key), update(root << 1 | 1, mid + 1, y, key);
}
update(root);
}
int main() {
for (int i = 2; i <= N - 5; i++) {
if (!U_prime[i]) {
num[i] = 1;
} else {
continue;
}
for (int j = 2 * i; j <= N - 5; j += i) {
U_prime[j] = true;
}
}
int now = 2;
for (; now <= N - 5; now *= 2) {
num[now] = 1;
}
num[6] = num[0] = num[1] = 1;
while (scanf("%d", &n) == 1) {
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
build(1, 1, n);
int m;
scanf("%d", &m);
for (int i = 1; i <= m; i++) {
int type;
scanf("%d", &type);
if (type == 1) {
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", Query(1, x, y));
}
if (type == 2) {
int x, y, r;
scanf("%d%d%d", &x, &y, &r);
update(1, x, y, r);
}
if (type == 3) {
int x, r;
scanf("%d%d", &x, &r);
update(1, x, r);
}
}
}
return 0;
}
| 23.961538 | 79 | 0.402247 | HcPlu |
9c5aea0a6ffeba117367b70a8617ce4bca0ed544 | 4,936 | cpp | C++ | ame/src/v20190916/model/TRTCJoinRoomInput.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ame/src/v20190916/model/TRTCJoinRoomInput.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ame/src/v20190916/model/TRTCJoinRoomInput.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/ame/v20190916/model/TRTCJoinRoomInput.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ame::V20190916::Model;
using namespace std;
TRTCJoinRoomInput::TRTCJoinRoomInput() :
m_signHasBeenSet(false),
m_roomIdHasBeenSet(false),
m_sdkAppIdHasBeenSet(false),
m_userIdHasBeenSet(false)
{
}
CoreInternalOutcome TRTCJoinRoomInput::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Sign") && !value["Sign"].IsNull())
{
if (!value["Sign"].IsString())
{
return CoreInternalOutcome(Core::Error("response `TRTCJoinRoomInput.Sign` IsString=false incorrectly").SetRequestId(requestId));
}
m_sign = string(value["Sign"].GetString());
m_signHasBeenSet = true;
}
if (value.HasMember("RoomId") && !value["RoomId"].IsNull())
{
if (!value["RoomId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `TRTCJoinRoomInput.RoomId` IsString=false incorrectly").SetRequestId(requestId));
}
m_roomId = string(value["RoomId"].GetString());
m_roomIdHasBeenSet = true;
}
if (value.HasMember("SdkAppId") && !value["SdkAppId"].IsNull())
{
if (!value["SdkAppId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `TRTCJoinRoomInput.SdkAppId` IsString=false incorrectly").SetRequestId(requestId));
}
m_sdkAppId = string(value["SdkAppId"].GetString());
m_sdkAppIdHasBeenSet = true;
}
if (value.HasMember("UserId") && !value["UserId"].IsNull())
{
if (!value["UserId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `TRTCJoinRoomInput.UserId` IsString=false incorrectly").SetRequestId(requestId));
}
m_userId = string(value["UserId"].GetString());
m_userIdHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void TRTCJoinRoomInput::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_signHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Sign";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_sign.c_str(), allocator).Move(), allocator);
}
if (m_roomIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RoomId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_roomId.c_str(), allocator).Move(), allocator);
}
if (m_sdkAppIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SdkAppId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_sdkAppId.c_str(), allocator).Move(), allocator);
}
if (m_userIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UserId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_userId.c_str(), allocator).Move(), allocator);
}
}
string TRTCJoinRoomInput::GetSign() const
{
return m_sign;
}
void TRTCJoinRoomInput::SetSign(const string& _sign)
{
m_sign = _sign;
m_signHasBeenSet = true;
}
bool TRTCJoinRoomInput::SignHasBeenSet() const
{
return m_signHasBeenSet;
}
string TRTCJoinRoomInput::GetRoomId() const
{
return m_roomId;
}
void TRTCJoinRoomInput::SetRoomId(const string& _roomId)
{
m_roomId = _roomId;
m_roomIdHasBeenSet = true;
}
bool TRTCJoinRoomInput::RoomIdHasBeenSet() const
{
return m_roomIdHasBeenSet;
}
string TRTCJoinRoomInput::GetSdkAppId() const
{
return m_sdkAppId;
}
void TRTCJoinRoomInput::SetSdkAppId(const string& _sdkAppId)
{
m_sdkAppId = _sdkAppId;
m_sdkAppIdHasBeenSet = true;
}
bool TRTCJoinRoomInput::SdkAppIdHasBeenSet() const
{
return m_sdkAppIdHasBeenSet;
}
string TRTCJoinRoomInput::GetUserId() const
{
return m_userId;
}
void TRTCJoinRoomInput::SetUserId(const string& _userId)
{
m_userId = _userId;
m_userIdHasBeenSet = true;
}
bool TRTCJoinRoomInput::UserIdHasBeenSet() const
{
return m_userIdHasBeenSet;
}
| 27.120879 | 144 | 0.680308 | suluner |
9c62c70f747d78ce976c8b75b284d2e70a231f8f | 2,199 | hh | C++ | src/Distributed/MortonOrderRedistributeNodes.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/Distributed/MortonOrderRedistributeNodes.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/Distributed/MortonOrderRedistributeNodes.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++----------------------------------//
// MortonOrderRedistributeNodes
//
// Attempt to redistribute nodes such that they are laid out in memory
// in a Morton ordering. Note that this involves renumbering the nodes of
// each NodeList, not just redistributing them between processors.
//
// Warren & Salmon (1995), Computer Physics Communications, 87, 266-290.
//
// Created by JMO, Tue Mar 25 14:19:18 PDT 2008
//----------------------------------------------------------------------------//
#ifndef MortonOrderRedistributeNodes_HH
#define MortonOrderRedistributeNodes_HH
#include "SpaceFillingCurveRedistributeNodes.hh"
namespace Spheral {
template<typename Dimension> class DataBase;
}
namespace Spheral {
template<typename Dimension>
class MortonOrderRedistributeNodes: public SpaceFillingCurveRedistributeNodes<Dimension> {
public:
//--------------------------- Public Interface ---------------------------//
typedef typename Dimension::Scalar Scalar;
typedef typename Dimension::Vector Vector;
typedef typename Dimension::Tensor Tensor;
typedef typename Dimension::SymTensor SymTensor;
typedef KeyTraits::Key Key;
// Constructors
MortonOrderRedistributeNodes(const double dummy,
const double minNodesPerDomainFraction = 0.5,
const double maxNodesPerDomainFraction = 1.5,
const bool workBalance = true,
const bool localReorderOnly = false);
// Destructor
virtual ~MortonOrderRedistributeNodes();
// Hash the positions.
virtual
FieldList<Dimension, Key>
computeHashedIndices(const DataBase<Dimension>& dataBase) const override;
private:
//--------------------------- Private Interface ---------------------------//
// No copy or assignment operations.
MortonOrderRedistributeNodes(const MortonOrderRedistributeNodes& nodes);
MortonOrderRedistributeNodes& operator=(const MortonOrderRedistributeNodes& rhs);
};
}
#else
// Forward declare the MortonOrderRedistributeNodes class.
namespace Spheral {
template<typename Dimension> class MortonOrderRedistributeNodes;
}
#endif
| 32.820896 | 90 | 0.653024 | jmikeowen |
9c697b6e0764a0944673453b6b221ca376f1b109 | 6,923 | cpp | C++ | src/singletons/settingsmanager.cpp | alexandera3/chatterino2 | 41fbcc738b34a19f66eef3cca8d5dea0b89e07a3 | [
"MIT"
] | 1 | 2018-03-24T18:40:00.000Z | 2018-03-24T18:40:00.000Z | src/singletons/settingsmanager.cpp | alexandera3/chatterino2 | 41fbcc738b34a19f66eef3cca8d5dea0b89e07a3 | [
"MIT"
] | null | null | null | src/singletons/settingsmanager.cpp | alexandera3/chatterino2 | 41fbcc738b34a19f66eef3cca8d5dea0b89e07a3 | [
"MIT"
] | null | null | null | #include "singletons/settingsmanager.hpp"
#include "debug/log.hpp"
#include "singletons/pathmanager.hpp"
#include "singletons/resourcemanager.hpp"
#include "singletons/windowmanager.hpp"
using namespace chatterino::messages;
namespace chatterino {
namespace singletons {
std::vector<std::weak_ptr<pajlada::Settings::ISettingData>> _settings;
void _registerSetting(std::weak_ptr<pajlada::Settings::ISettingData> setting)
{
_settings.push_back(setting);
}
SettingManager::SettingManager()
: snapshot(nullptr)
, _ignoredKeywords(new std::vector<QString>)
{
this->wordFlagsListener.addSetting(this->showTimestamps);
this->wordFlagsListener.addSetting(this->showBadges);
this->wordFlagsListener.addSetting(this->enableBttvEmotes);
this->wordFlagsListener.addSetting(this->enableEmojis);
this->wordFlagsListener.addSetting(this->enableFfzEmotes);
this->wordFlagsListener.addSetting(this->enableTwitchEmotes);
this->wordFlagsListener.cb = [this](auto) {
this->updateWordTypeMask(); //
};
this->moderationActions.connect([this](auto, auto) { this->updateModerationActions(); });
this->ignoredKeywords.connect([this](auto, auto) { this->updateIgnoredKeywords(); });
this->timestampFormat.connect(
[](auto, auto) { singletons::WindowManager::getInstance().layoutVisibleChatWidgets(); });
}
MessageElement::Flags SettingManager::getWordFlags()
{
return this->wordFlags;
}
bool SettingManager::isIgnoredEmote(const QString &)
{
return false;
}
void SettingManager::init()
{
QString settingsPath = PathManager::getInstance().settingsFolderPath + "/settings.json";
pajlada::Settings::SettingManager::load(qPrintable(settingsPath));
}
void SettingManager::updateWordTypeMask()
{
uint32_t newMaskUint = MessageElement::Text;
if (this->showTimestamps) {
newMaskUint |= MessageElement::Timestamp;
}
newMaskUint |=
enableTwitchEmotes ? MessageElement::TwitchEmoteImage : MessageElement::TwitchEmoteText;
newMaskUint |= enableFfzEmotes ? MessageElement::FfzEmoteImage : MessageElement::FfzEmoteText;
newMaskUint |=
enableBttvEmotes ? MessageElement::BttvEmoteImage : MessageElement::BttvEmoteText;
newMaskUint |= enableEmojis ? MessageElement::EmojiImage : MessageElement::EmojiText;
newMaskUint |= MessageElement::BitsAmount;
newMaskUint |= enableGifAnimations ? MessageElement::BitsAnimated : MessageElement::BitsStatic;
if (this->showBadges) {
newMaskUint |= MessageElement::Badges;
}
newMaskUint |= MessageElement::Username;
newMaskUint |= MessageElement::AlwaysShow;
MessageElement::Flags newMask = static_cast<MessageElement::Flags>(newMaskUint);
if (newMask != this->wordFlags) {
this->wordFlags = newMask;
emit wordFlagsChanged();
}
}
void SettingManager::saveSnapshot()
{
rapidjson::Document *d = new rapidjson::Document(rapidjson::kObjectType);
rapidjson::Document::AllocatorType &a = d->GetAllocator();
for (const auto &weakSetting : _settings) {
auto setting = weakSetting.lock();
if (!setting) {
continue;
}
rapidjson::Value key(setting->getPath().c_str(), a);
rapidjson::Value val = setting->marshalInto(*d);
d->AddMember(key.Move(), val.Move(), a);
}
this->snapshot.reset(d);
debug::Log("hehe: {}", pajlada::Settings::SettingManager::stringify(*d));
}
void SettingManager::recallSnapshot()
{
if (!this->snapshot) {
return;
}
const auto &snapshotObject = this->snapshot->GetObject();
for (const auto &weakSetting : _settings) {
auto setting = weakSetting.lock();
if (!setting) {
debug::Log("Error stage 1 of loading");
continue;
}
const char *path = setting->getPath().c_str();
if (!snapshotObject.HasMember(path)) {
debug::Log("Error stage 2 of loading");
continue;
}
setting->unmarshalValue(snapshotObject[path]);
}
}
std::vector<ModerationAction> SettingManager::getModerationActions() const
{
return this->_moderationActions;
}
const std::shared_ptr<std::vector<QString>> SettingManager::getIgnoredKeywords() const
{
return this->_ignoredKeywords;
}
void SettingManager::updateModerationActions()
{
auto &resources = singletons::ResourceManager::getInstance();
this->_moderationActions.clear();
static QRegularExpression newLineRegex("(\r\n?|\n)+");
static QRegularExpression replaceRegex("[!/.]");
static QRegularExpression timeoutRegex("^[./]timeout.* (\\d+)");
QStringList list = this->moderationActions.getValue().split(newLineRegex);
int multipleTimeouts = 0;
for (QString &str : list) {
if (timeoutRegex.match(str).hasMatch()) {
multipleTimeouts++;
if (multipleTimeouts > 1) {
break;
}
}
}
for (int i = 0; i < list.size(); i++) {
QString &str = list[i];
if (str.isEmpty()) {
continue;
}
auto timeoutMatch = timeoutRegex.match(str);
if (timeoutMatch.hasMatch()) {
if (multipleTimeouts > 1) {
QString line1;
QString line2;
int amount = timeoutMatch.captured(1).toInt();
if (amount < 60) {
line1 = QString::number(amount);
line2 = "s";
} else if (amount < 60 * 60) {
line1 = QString::number(amount / 60);
line2 = "m";
} else if (amount < 60 * 60 * 24) {
line1 = QString::number(amount / 60 / 60);
line2 = "h";
} else {
line1 = QString::number(amount / 60 / 60 / 24);
line2 = "d";
}
this->_moderationActions.emplace_back(line1, line2, str);
} else {
this->_moderationActions.emplace_back(resources.buttonTimeout, str);
}
} else if (str.startsWith("/ban ")) {
this->_moderationActions.emplace_back(resources.buttonBan, str);
} else {
QString xD = str;
xD.replace(replaceRegex, "");
this->_moderationActions.emplace_back(xD.mid(0, 2), xD.mid(2, 2), str);
}
}
}
void SettingManager::updateIgnoredKeywords()
{
static QRegularExpression newLineRegex("(\r\n?|\n)+");
auto items = new std::vector<QString>();
for (const QString &line : this->ignoredKeywords.getValue().split(newLineRegex)) {
QString line2 = line.trimmed();
if (!line2.isEmpty()) {
items->push_back(line2);
}
}
this->_ignoredKeywords = std::shared_ptr<std::vector<QString>>(items);
}
} // namespace singletons
} // namespace chatterino
| 29.459574 | 99 | 0.628485 | alexandera3 |
9c6a7e723996e5e54041d88ec331b20845a226db | 2,255 | cpp | C++ | ir/node.cpp | pierce-m/p4c | afe96cf5a658f7bf5e1b95a044c241d9afb13dc6 | [
"Apache-2.0"
] | null | null | null | ir/node.cpp | pierce-m/p4c | afe96cf5a658f7bf5e1b95a044c241d9afb13dc6 | [
"Apache-2.0"
] | null | null | null | ir/node.cpp | pierce-m/p4c | afe96cf5a658f7bf5e1b95a044c241d9afb13dc6 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ir.h"
void IR::Node::traceVisit(const char* visitor) const
{ LOG3("Visiting " << visitor << " " << id << ":" << node_type_name()); }
void IR::Node::traceCreation() const { LOG5("Created node " << id); }
int IR::Node::currentId = 0;
void IR::Node::toJSON(JSONGenerator &json) const {
json << json.indent << "\"Node_ID\" : " << id << ", " << std::endl
<< json.indent << "\"Node_Type\" : " << node_type_name();
}
IR::Node::Node(JSONLoader &json) : id(-1) {
json.load("Node_ID", id);
if (id < 0)
id = currentId++;
else if (id >= currentId)
currentId = id+1;
}
cstring IR::dbp(const IR::INode* node) {
std::stringstream str;
if (node == nullptr) {
str << "<nullptr>";
} else {
if (node->is<IR::IDeclaration>()) {
node->getNode()->Node::dbprint(str);
str << " " << node->to<IR::IDeclaration>()->getName();
} else if (node->is<IR::Type_MethodBase>()) {
str << node;
} else if (node->is<IR::Member>()) {
node->getNode()->Node::dbprint(str);
str << " ." << node->to<IR::Member>()->member;
} else if (node->is<IR::PathExpression>() ||
node->is<IR::Path>() ||
node->is<IR::TypeNameExpression>() ||
node->is<IR::Constant>() ||
node->is<IR::Type_Name>() ||
node->is<IR::Type_Base>()) {
node->getNode()->Node::dbprint(str);
str << " " << node->toString();
} else {
node->getNode()->Node::dbprint(str);
}
}
return str.str();
}
IRNODE_DEFINE_APPLY_OVERLOAD(Node, , )
| 33.161765 | 73 | 0.566741 | pierce-m |
9c6cc0772cd6f8a3fc597daf84a19aec3613854c | 782 | cpp | C++ | GPTP/src/graphics/draw_hook.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 8 | 2015-04-03T16:50:59.000Z | 2021-01-06T17:12:29.000Z | GPTP/src/graphics/draw_hook.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 6 | 2015-04-03T18:10:56.000Z | 2016-02-18T05:04:21.000Z | GPTP/src/graphics/draw_hook.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 6 | 2015-04-04T04:37:33.000Z | 2018-04-09T09:03:50.000Z | #include "draw_hook.h"
#include "../SCBW/api.h"
#include "../hook_tools.h"
#include "graphics_misc.h"
namespace {
//-------- Draw hook taken from BWAPI --------//
bool wantRefresh = false;
void __stdcall DrawHook(graphics::Bitmap *surface, Bounds *bounds) {
if (wantRefresh) {
wantRefresh = false;
scbw::refreshScreen();
}
oldDrawGameProc(surface, bounds);
//if ( BW::BWDATA::GameScreenBuffer->isValid() )
//{
// unsigned int numShapes = BWAPI::BroodwarImpl.drawShapes();
//
// if ( numShapes )
// wantRefresh = true;
//}
if (graphics::drawAllShapes() > 0)
wantRefresh = true;
}
} //unnamed namespace
namespace hooks {
void injectDrawHook() {
memoryPatch(0x004BD68D, &DrawHook);
}
} //hooks
| 20.578947 | 70 | 0.609974 | idmontie |
9c6ef314c1bc19517b00f75bb594d36395203b8e | 18,170 | cpp | C++ | src/hook.cpp | juce/taksi | 154ce405d5c51429d66c5e160891afa60dd23044 | [
"BSD-3-Clause"
] | 2 | 2020-10-23T02:42:18.000Z | 2021-12-08T14:01:46.000Z | src/hook.cpp | juce/taksi | 154ce405d5c51429d66c5e160891afa60dd23044 | [
"BSD-3-Clause"
] | null | null | null | src/hook.cpp | juce/taksi | 154ce405d5c51429d66c5e160891afa60dd23044 | [
"BSD-3-Clause"
] | null | null | null | /* hook */
/* Version 1.1 (with Win32 GUI) by Juce. */
#include <windows.h>
#include <windef.h>
#include <string.h>
#include <stdio.h>
#include "mydll.h"
#include "shared.h"
#include "win32gui.h"
#include "config.h"
#include "hook.h"
FILE* log = NULL;
// Program Configuration
static TAXI_CONFIG config = {
DEFAULT_DEBUG,
DEFAULT_CAPTURE_DIR,
DEFAULT_TARGET_FRAME_RATE,
DEFAULT_VKEY_INDICATOR, DEFAULT_VKEY_HOOK_MODE,
DEFAULT_VKEY_SMALL_SCREENSHOT, DEFAULT_VKEY_SCREENSHOT,
DEFAULT_VKEY_VIDEO_CAPTURE,
DEFAULT_USE_DIRECT_INPUT,
DEFAULT_STARTUP_MODE_SYSTEM_WIDE,
DEFAULT_FULL_SIZE_VIDEO,
DEFAULT_CUSTOM_LIST
};
BOOL dropDownSelecting = false;
TAXI_CUSTOM_CONFIG* g_curCfg = NULL;
// function prototypes
void ApplySettings(void);
void ForceReconf(void);
void RestoreSettings(void);
void InitializeCustomConfigs(void);
BOOL GetDevice8Methods(HWND hWnd, DWORD* present, DWORD* reset);
BOOL GetDevice9Methods(HWND hWnd, DWORD* present, DWORD* reset);
/**
* Increase the reconf-counter thus telling all the mapped DLLs that
* they need to reconfigure themselves.
*/
void ForceReconf(void)
{
ZeroMemory(config.captureDir, BUFLEN);
SendMessage(g_captureDirectoryControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)config.captureDir);
// make sure it ends with backslash.
if (config.captureDir[lstrlen(config.captureDir)-1] != '\\')
{
lstrcat(config.captureDir, "\\");
SendMessage(g_captureDirectoryControl, WM_SETTEXT, 0, (LPARAM)config.captureDir);
}
int frate = 0;
char buf[BUFLEN];
ZeroMemory(buf, BUFLEN);
SendMessage(g_frameRateControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)buf);
if (sscanf(buf, "%d", &frate) == 1 && frate > 0)
{
config.targetFrameRate = frate;
}
else
{
config.targetFrameRate = GetTargetFrameRate();
sprintf(buf, "%d", config.targetFrameRate);
SendMessage(g_frameRateControl, WM_SETTEXT, 0, (LPARAM)buf);
}
// Apply new settings
ApplySettings();
// Save
if (WriteConfig(&config))
{
SetReconfCounter(GetReconfCounter() + 1);
}
}
/**
* Apply settings from config
*/
void ApplySettings(void)
{
char buf[BUFLEN];
// apply general settings
SetDebug(config.debug);
if (lstrlen(config.captureDir)==0)
{
// If capture directory is still unknown at this point
// set it to the current directory then.
ZeroMemory(config.captureDir, BUFLEN);
GetModuleFileName(NULL, config.captureDir, BUFLEN);
// strip off file name
char* p = config.captureDir + lstrlen(config.captureDir);
while (p > config.captureDir && *p != '\\') p--;
p[1] = '\0';
}
SetCaptureDir(config.captureDir);
SendMessage(g_captureDirectoryControl, WM_SETTEXT, 0, (LPARAM)config.captureDir);
SetTargetFrameRate(config.targetFrameRate);
ZeroMemory(buf, BUFLEN);
sprintf(buf,"%d",config.targetFrameRate);
SendMessage(g_frameRateControl, WM_SETTEXT, 0, (LPARAM)buf);
// apply keys
SetKey(VKEY_INDICATOR_TOGGLE, config.vKeyIndicator);
VKEY_TEXT(VKEY_INDICATOR_TOGGLE, buf, BUFLEN);
SendMessage(g_keyIndicatorControl, WM_SETTEXT, 0, (LPARAM)buf);
SetKey(VKEY_HOOK_MODE_TOGGLE, config.vKeyHookMode);
VKEY_TEXT(VKEY_HOOK_MODE_TOGGLE, buf, BUFLEN);
SendMessage(g_keyModeToggleControl, WM_SETTEXT, 0, (LPARAM)buf);
SetKey(VKEY_SMALL_SCREENSHOT, config.vKeySmallScreenShot);
VKEY_TEXT(VKEY_SMALL_SCREENSHOT, buf, BUFLEN);
SendMessage(g_keySmallScreenshotControl, WM_SETTEXT, 0, (LPARAM)buf);
SetKey(VKEY_SCREENSHOT, config.vKeyScreenShot);
VKEY_TEXT(VKEY_SCREENSHOT, buf, BUFLEN);
SendMessage(g_keyScreenshotControl, WM_SETTEXT, 0, (LPARAM)buf);
SetKey(VKEY_VIDEO_CAPTURE, config.vKeyVideoCapture);
VKEY_TEXT(VKEY_VIDEO_CAPTURE, buf, BUFLEN);
SendMessage(g_keyVideoToggleControl, WM_SETTEXT, 0, (LPARAM)buf);
// apply useDirectInput
SetUseDirectInput(config.useDirectInput);
// apply startupModeSystemWide
SetStartupModeSystemWide(config.startupModeSystemWide);
// apply fullSizeVideo
SetFullSizeVideo(config.fullSizeVideo);
// apply custom configs
SendMessage(g_customSettingsListControl, CB_RESETCONTENT, 0, 0);
SendMessage(g_customPatternControl, WM_SETTEXT, 0, (LPARAM)"");
SendMessage(g_customFrameRateControl, WM_SETTEXT, 0, (LPARAM)"");
SendMessage(g_customFrameWeightControl, WM_SETTEXT, 0, (LPARAM)"");
InitializeCustomConfigs();
}
/**
* Restores last saved settings.
*/
void RestoreSettings(void)
{
g_curCfg = NULL;
FreeCustomConfigs(&config);
// read optional configuration file
ReadConfig(&config);
// check for "silent" mode
if (config.debug == 0)
{
if (log != NULL) fclose(log);
DeleteFile(MAINLOGFILE);
log = NULL;
}
ApplySettings();
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
int home, away, timecode;
char buf[BUFLEN];
switch(uMsg)
{
case WM_DESTROY:
// Set flag, so that mydll knows to unhook device methods
SetUnhookFlag(true);
SetExiting(true);
// Free memory taken by custom configs
FreeCustomConfigs(&config);
// close LOG file
if (log != NULL) fclose(log);
// Uninstall the hook
UninstallTheHook();
// Exit the application when the window closes
PostQuitMessage(1);
return true;
case WM_APP_REHOOK:
// Re-install system-wide hook
LOG(log, (log, "Received message to re-hook GetMsgProc\n"));
if (InstallTheHook())
{
LOG(log, (log, "GetMsgProc successfully re-hooked.\n"));
}
break;
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED)
{
if ((HWND)lParam == g_saveButtonControl)
{
// update current custom config
if (g_curCfg != NULL)
{
SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern);
int value = 0;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value;
float dvalue = 0.0f;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue;
}
ForceReconf();
// modify status text
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"SAVED");
}
else if ((HWND)lParam == g_restoreButtonControl)
{
RestoreSettings();
// modify status text
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"RESTORED");
}
else if ((HWND)lParam == g_customAddButtonControl)
{
// update current custom config
if (g_curCfg != NULL)
{
SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern);
int value = 0;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value;
float dvalue = 0.0f;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue;
}
g_curCfg = NULL;
// clear out controls
SendMessage(g_customSettingsListControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
// set focus on appId comboBox
SendMessage(g_customSettingsListControl,WM_SETFOCUS, 0, 0);
}
else if ((HWND)lParam == g_customDropButtonControl)
{
// remove current custom config
if (g_curCfg != NULL)
{
int idx = (int)SendMessage(g_customSettingsListControl, CB_FINDSTRING, BUFLEN, (LPARAM)g_curCfg->appId);
//ZeroMemory(buf, BUFLEN);
//sprintf(buf,"idx = %d", idx);
//SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)buf);
if (idx != -1)
{
SendMessage(g_customSettingsListControl, CB_DELETESTRING, idx, 0);
DeleteCustomConfig(&config, g_curCfg->appId);
}
SendMessage(g_customSettingsListControl, CB_SETCURSEL, 0, 0);
ZeroMemory(buf, BUFLEN);
SendMessage(g_customSettingsListControl, CB_GETLBTEXT, 0, (LPARAM)buf);
g_curCfg = LookupExistingCustomConfig(&config, buf);
if (g_curCfg != NULL)
{
// update custom controls
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)g_curCfg->pattern);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%d", g_curCfg->frameRate);
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%1.4f", g_curCfg->frameWeight);
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
}
else
{
// clear out controls
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
}
}
}
}
else if (HIWORD(wParam) == CBN_KILLFOCUS)
{
ZeroMemory(buf, BUFLEN);
SendMessage(g_customSettingsListControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)buf);
if (lstrlen(buf)>0)
{
if (lstrcmp(buf, g_curCfg->appId)!=0)
{
if (g_curCfg != NULL)
{
// find list item with old appId
int idx = SendMessage(g_customSettingsListControl, CB_FINDSTRING, BUFLEN, (LPARAM)g_curCfg->appId);
// delete this item, if found
if (idx != -1) SendMessage(g_customSettingsListControl, CB_DELETESTRING, idx, 0);
// change appId
strncpy(g_curCfg->appId, buf, BUFLEN-1);
// add a new list item
SendMessage(g_customSettingsListControl, CB_ADDSTRING, 0, (LPARAM)g_curCfg->appId);
}
else
{
// we have a new custom config
g_curCfg = LookupCustomConfig(&config, buf);
// add a new list item
SendMessage(g_customSettingsListControl, CB_ADDSTRING, 0, (LPARAM)g_curCfg->appId);
}
}
}
else
{
// cannot use empty string. Restore the old one, if known.
if (g_curCfg != NULL)
{
// restore previous text
SendMessage(g_customSettingsListControl, WM_SETTEXT, 0, (LPARAM)g_curCfg->appId);
}
}
}
else if (HIWORD(wParam) == CBN_SELCHANGE)
{
// update previously selected custom config
if (g_curCfg != NULL)
{
SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern);
int value = 0;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value;
float dvalue = 0.0f;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue;
}
// user selected different custom setting in drop-down
int idx = (int)SendMessage(g_customSettingsListControl, CB_GETCURSEL, 0, 0);
ZeroMemory(buf, BUFLEN);
SendMessage(g_customSettingsListControl, CB_GETLBTEXT, idx, (LPARAM)buf);
TAXI_CUSTOM_CONFIG* cfg = LookupExistingCustomConfig(&config, buf);
if (cfg == NULL) break;
// update custom controls
dropDownSelecting = true;
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)cfg->pattern);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%d", cfg->frameRate);
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%1.4f", cfg->frameWeight);
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
dropDownSelecting = false;
// remember new current config
g_curCfg = cfg;
}
else if (HIWORD(wParam) == EN_CHANGE)
{
HWND control = (HWND)lParam;
if (!dropDownSelecting)
{
// modify status text
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE");
}
}
else if (HIWORD(wParam) == CBN_EDITCHANGE)
{
HWND control = (HWND)lParam;
// modify status text
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE");
}
break;
case WM_APP_KEYDEF:
HWND target = (HWND)lParam;
ZeroMemory(buf, BUFLEN);
GetKeyNameText(MapVirtualKey(wParam, 0) << 16, buf, BUFLEN);
SendMessage(target, WM_SETTEXT, 0, (LPARAM)buf);
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE");
// update config
if (target == g_keyIndicatorControl) config.vKeyIndicator = (WORD)wParam;
else if (target == g_keyModeToggleControl) config.vKeyHookMode = (WORD)wParam;
else if (target == g_keySmallScreenshotControl) config.vKeySmallScreenShot = (WORD)wParam;
else if (target == g_keyScreenshotControl) config.vKeyScreenShot = (WORD)wParam;
else if (target == g_keyVideoToggleControl) config.vKeyVideoCapture = (WORD)wParam;
break;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
bool InitApp(HINSTANCE hInstance, LPSTR lpCmdLine)
{
WNDCLASSEX wcx;
// cbSize - the size of the structure.
wcx.cbSize = sizeof(WNDCLASSEX);
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpfnWndProc = (WNDPROC)WindowProc;
wcx.cbClsExtra = 0;
wcx.cbWndExtra = 0;
wcx.hInstance = hInstance;
wcx.hIcon = LoadIcon(NULL,IDI_APPLICATION);
wcx.hCursor = LoadCursor(NULL,IDC_ARROW);
wcx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wcx.lpszMenuName = NULL;
wcx.lpszClassName = "TAXICLS";
wcx.hIconSm = NULL;
// Register the class with Windows
if(!RegisterClassEx(&wcx))
return false;
// open log
log = fopen(MAINLOGFILE, "wt");
// read optional configuration file
ReadConfig(&config);
// check for "silent" mode
if (config.debug == 0)
{
if (log != NULL) fclose(log);
DeleteFile(MAINLOGFILE);
log = NULL;
}
// clear exiting flag
SetExiting(false);
return true;
}
HWND BuildWindow(int nCmdShow)
{
DWORD style, xstyle;
HWND retval;
style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
xstyle = WS_EX_LEFT;
retval = CreateWindowEx(xstyle,
"TAXICLS", // class name
TAXI_WINDOW_TITLE, // title for our window (appears in the titlebar)
style,
CW_USEDEFAULT, // initial x coordinate
CW_USEDEFAULT, // initial y coordinate
WIN_WIDTH, WIN_HEIGHT, // width and height of the window
NULL, // no parent window.
NULL, // no menu
NULL, // no creator
NULL); // no extra data
if (retval == NULL) return NULL; // BAD.
ShowWindow(retval,nCmdShow); // Show the window
return retval; // return its handle for future use.
}
void InitializeCustomConfigs(void)
{
TAXI_CUSTOM_CONFIG* cfg = config.customList;
while (cfg != NULL)
{
SendMessage(g_customSettingsListControl,CB_INSERTSTRING,(WPARAM)0, (LPARAM)cfg->appId);
if (cfg->next == NULL)
{
// Pre-select iteam
SendMessage(g_customSettingsListControl,CB_SETCURSEL,(WPARAM)0,(LPARAM)0);
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)cfg->pattern);
char buf[BUFLEN];
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%d", cfg->frameRate);
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%1.4f", cfg->frameWeight);
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
// remember current config
g_curCfg = cfg;
}
cfg = cfg->next;
}
// clear status text
SendMessage(g_statusTextControl, WM_SETTEXT, (WPARAM)0, (LPARAM)"");
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg; int retval;
if(InitApp(hInstance, lpCmdLine) == false)
return 0;
HWND hWnd = BuildWindow(nCmdShow);
if(hWnd == NULL)
return 0;
// build GUI
if (!BuildControls(hWnd))
return 0;
// Initialize all controls
ApplySettings();
// show credits
char buf[BUFLEN];
ZeroMemory(buf, BUFLEN);
strncpy(buf, CREDITS, BUFLEN-1);
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)buf);
// Get method pointers of IDirect3DDevice8 vtable
DWORD present8_addr = 0, reset8_addr = 0;
if (GetDevice8Methods(hWnd, &present8_addr, &reset8_addr))
{
SetPresent8(present8_addr);
SetReset8(reset8_addr);
}
// Get method pointers of IDirect3DDevice9 vtable
DWORD present9_addr = 0, reset9_addr = 0;
if (GetDevice9Methods(hWnd, &present9_addr, &reset9_addr))
{
SetPresent9(present9_addr);
SetReset9(reset9_addr);
}
// Clear the flag, so that mydll hooks on device methods
SetUnhookFlag(false);
// Set HWND for later use
SetServerWnd(hWnd);
// Install the hook
InstallTheHook();
while((retval = GetMessage(&msg,NULL,0,0)) != 0)
{
// capture key-def events
if ((msg.hwnd == g_keyIndicatorControl || msg.hwnd == g_keyModeToggleControl ||
msg.hwnd == g_keySmallScreenshotControl || msg.hwnd == g_keyScreenshotControl ||
msg.hwnd == g_keyVideoToggleControl) &&
(msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN))
{
PostMessage(hWnd, WM_APP_KEYDEF, msg.wParam, (LPARAM)msg.hwnd);
continue;
}
if(retval == -1)
return 0; // an error occured while getting a message
if (!IsDialogMessage(hWnd, &msg)) // need to call this to make WS_TABSTOP work
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
| 31.273666 | 111 | 0.671987 | juce |
9c7349434259d3d42f01b7ed9e66f64d09e76ef2 | 7,923 | cpp | C++ | src/rx/core/memory/buddy_allocator.cpp | DethRaid/rex | 21ba92d38398240faa45a402583c11f8c72e6e41 | [
"MIT"
] | 2 | 2020-06-13T11:39:46.000Z | 2021-03-10T01:03:03.000Z | src/rx/core/memory/buddy_allocator.cpp | DethRaid/rex | 21ba92d38398240faa45a402583c11f8c72e6e41 | [
"MIT"
] | null | null | null | src/rx/core/memory/buddy_allocator.cpp | DethRaid/rex | 21ba92d38398240faa45a402583c11f8c72e6e41 | [
"MIT"
] | 1 | 2021-01-06T03:47:08.000Z | 2021-01-06T03:47:08.000Z | #include <string.h> // memcpy
#include "rx/core/memory/buddy_allocator.h"
#include "rx/core/concurrency/scope_lock.h"
#include "rx/core/hints/unlikely.h"
#include "rx/core/hints/likely.h"
#include "rx/core/assert.h"
namespace Rx::Memory {
// Each allocation in the heap is prefixed with this header.
struct alignas(Allocator::ALIGNMENT) Block {
Size size;
bool free;
};
// Returns the next block in the intrusive, flat linked-list structure.
static inline Block* next(Block* _block) {
return reinterpret_cast<Block*>(reinterpret_cast<Byte*>(_block) + _block->size);
}
// Returns size that is needed for |_size|.
static inline Size needed(Size _size) {
Size result = Allocator::ALIGNMENT; // Smallest allocation
// Storage for the block.
_size += sizeof(Block);
// Continually double result until |_size| fits.
while (_size > result) {
result <<= 1;
}
return result;
}
// Continually divides the block |block_| until it's the optimal size for
// an allocation of size |_size|.
static Block* divide(Block* block_, Size _size) {
while (block_->size > _size) {
// Split block into two halves, half-size each.
const auto size = block_->size >> 1;
block_->size = size;
block_ = next(block_);
block_->size = size;
block_->free = true;
}
return block_->size >= _size ? block_ : nullptr;
}
// Searches for a free block that matches the given size |_size| in the list
// defined by |_head| and |_tail|. When a block cannot be found which satisifies
// the size |_size| but there is a larger free block, this divides the free
// block into two halves of the same size until the block optimally fits the
// size |_size| in it. If there is no larger free block available, this returns
// nullptr.
//
// This function also merges adjacent free blocks as it searches to make larger,
// free blocks available during the search.
static Block* find_available(Block* _head, Block* _tail, Size _size) {
Block* region = _head;
Block* buddy = next(region);
Block* closest = nullptr;
// When at the end of the heap and the region is free.
if (buddy == _tail && region->free) {
// Split it into a block to satisfy the request leaving what is left over
// for any future allocations. This is the one edge case the general
// algorithm cannot cover.
return divide(region, _size);
}
// Find the closest minimum sized match within the heap.
Size closest_size = 0;
while (region < _tail && buddy < _tail) {
// When both the region and the buddy are free, merge those adjacent
// free blocks.
if (region->free && buddy->free && region->size == buddy->size) {
region->size <<= 1;
const Size region_size = region->size;
if (_size <= region_size && (!closest || region_size <= closest->size)) {
closest = region;
}
if ((region = next(buddy)) < _tail) {
buddy = next(region);
}
} else {
if (closest) {
closest_size = closest->size;
}
// Check the region block.
const Size region_size = region->size;
if (region->free && _size <= region_size
&& (!closest || region_size <= closest->size))
{
closest = region;
closest_size = region_size;
}
// Check the buddy block.
const Size buddy_size = buddy->size;
if (buddy->free && _size <= buddy_size
&& (!closest || buddy_size <= closest->size))
{
closest = buddy;
closest_size = buddy_size;
}
// The buddy has been split up into smaller blocks.
if (region_size > buddy_size) {
region = buddy;
buddy = next(buddy);
} else if ((region = next(buddy)) < _tail) {
// Skip the base and buddy region for the next iteration.
buddy = next(region);
}
}
}
if (closest) {
// Perfect match.
if (closest_size == _size) {
return closest;
}
// Split |current| in halves continually until it optimally fits |_size|.
return divide(closest, _size);
}
// Potentially out of memory.
return nullptr;
}
// Performs a single level merge of adjacent free blocks in the list given
// by |_head| and |_tail|.
static bool merge_free(Block* _head, Block* _tail) {
Block* region = _head;
Block* buddy = next(region);
bool modified = false;
while (region < _tail && buddy < _tail) {
// Both the region and buddy are free.
if (region->free && buddy->free && region->size == buddy->size) {
// Merge the blocks back into one, larger one.
region->size <<= 1;
if ((region = next(region)) < _tail) {
buddy = next(region);
}
modified = true;
} else if (region->size > buddy->size) {
// The buddy block has been split into smaller blocks.
region = buddy;
buddy = next(buddy);
} else if ((region = next(buddy)) < _tail) {
// Skip the base and buddy region for the next iteration.
buddy = next(region);
}
}
return modified;
}
BuddyAllocator::BuddyAllocator(Byte* _data, Size _size) {
// Ensure |_data| and |_size| are multiples of |ALIGNMENT|.
RX_ASSERT(reinterpret_cast<UintPtr>(_data) % ALIGNMENT == 0,
"_data not aligned on %zu-byte boundary", ALIGNMENT);
RX_ASSERT(_size % ALIGNMENT == 0,
"_size not a multiple of %zu", ALIGNMENT);
// Ensure |_size| is a power of two.
RX_ASSERT((_size & (_size - 1)) == 0, "_size not a power of two");
// Create the root block structure.
Block* head = reinterpret_cast<Block*>(_data);
head->size = _size;
head->free = true;
m_head = reinterpret_cast<void*>(head);
m_tail = reinterpret_cast<void*>(next(head));
}
Byte* BuddyAllocator::allocate(Size _size) {
Concurrency::ScopeLock lock{m_lock};
return allocate_unlocked(_size);
}
Byte* BuddyAllocator::reallocate(void* _data, Size _size) {
Concurrency::ScopeLock lock{m_lock};
return reallocate_unlocked(_data, _size);
}
void BuddyAllocator::deallocate(void* _data) {
Concurrency::ScopeLock lock{m_lock};
deallocate_unlocked(_data);
}
Byte* BuddyAllocator::allocate_unlocked(Size _size) {
const auto size = needed(_size);
const auto head = reinterpret_cast<Block*>(m_head);
const auto tail = reinterpret_cast<Block*>(m_tail);
auto find = find_available(head, tail, size);
if (RX_HINT_LIKELY(find)) {
find->free = false;
return reinterpret_cast<Byte*>(find + 1);
}
// Merge free blocks until they're all merged.
while (merge_free(head, tail)) {
;
}
// Search again for a free block.
if ((find = find_available(head, tail, size))) {
find->free = false;
return reinterpret_cast<Byte*>(find + 1);
}
// Out of memory.
return nullptr;
}
Byte* BuddyAllocator::reallocate_unlocked(void* _data, Size _size) {
if (RX_HINT_LIKELY(_data)) {
const auto region = reinterpret_cast<Block*>(_data) - 1;
const auto head = reinterpret_cast<Block*>(m_head);
const auto tail = reinterpret_cast<Block*>(m_tail);
RX_ASSERT(region >= head, "out of heap");
RX_ASSERT(region <= tail - 1, "out of heap");
// No need to resize.
if (region->size >= needed(_size)) {
return reinterpret_cast<Byte*>(_data);
}
// Create a new allocation.
auto resize = allocate_unlocked(_size);
if (RX_HINT_LIKELY(resize)) {
memcpy(resize, _data, region->size - sizeof *region);
deallocate_unlocked(_data);
return resize;
}
// Out of memory.
return nullptr;
}
return allocate_unlocked(_size);
}
void BuddyAllocator::deallocate_unlocked(void* _data) {
if (RX_HINT_LIKELY(_data)) {
const auto region = reinterpret_cast<Block*>(_data) - 1;
const auto head = reinterpret_cast<Block*>(m_head);
const auto tail = reinterpret_cast<Block*>(m_tail);
RX_ASSERT(region >= head, "out of heap");
RX_ASSERT(region <= tail - 1, "out of heap");
region->free = true;
}
}
} // namespace rx::memory
| 28.397849 | 82 | 0.649628 | DethRaid |
9c753066d459755141cd3223d7174009bedff3ca | 2,172 | cpp | C++ | rmw_connext_dynamic_cpp/src/publish_take.cpp | ross-desmond/rmw_connext | 6c22e0a4a76c7ca6ffe2340e0009eaeca40789e9 | [
"Apache-2.0"
] | 24 | 2017-11-15T09:16:24.000Z | 2022-03-30T07:32:15.000Z | rmw_connext_dynamic_cpp/src/publish_take.cpp | ross-desmond/rmw_connext | 6c22e0a4a76c7ca6ffe2340e0009eaeca40789e9 | [
"Apache-2.0"
] | 394 | 2015-03-07T01:00:13.000Z | 2022-02-03T15:40:52.000Z | rmw_connext_dynamic_cpp/src/publish_take.cpp | ross-desmond/rmw_connext | 6c22e0a4a76c7ca6ffe2340e0009eaeca40789e9 | [
"Apache-2.0"
] | 41 | 2015-08-13T02:07:08.000Z | 2021-07-07T03:41:44.000Z | // Copyright 2014-2016 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "./publish_take.hpp"
#include "./templates.hpp"
bool using_introspection_c_typesupport(const char * typesupport_identifier)
{
return typesupport_identifier == rosidl_typesupport_introspection_c__identifier;
}
bool using_introspection_cpp_typesupport(const char * typesupport_identifier)
{
return typesupport_identifier ==
rosidl_typesupport_introspection_cpp::typesupport_identifier;
}
bool _publish(DDS_DynamicData * dynamic_data, const void * ros_message,
const void * untyped_members, const char * typesupport)
{
if (using_introspection_c_typesupport(typesupport)) {
return publish<rosidl_typesupport_introspection_c__MessageMembers>(
dynamic_data, ros_message, untyped_members);
} else if (using_introspection_cpp_typesupport(typesupport)) {
return publish<rosidl_typesupport_introspection_cpp::MessageMembers>(
dynamic_data, ros_message, untyped_members);
}
RMW_SET_ERROR_MSG("Unknown typesupport identifier")
return false;
}
bool _take(DDS_DynamicData * dynamic_data, void * ros_message,
const void * untyped_members, const char * typesupport)
{
if (using_introspection_c_typesupport(typesupport)) {
return take<rosidl_typesupport_introspection_c__MessageMembers>(
dynamic_data, ros_message, untyped_members);
} else if (using_introspection_cpp_typesupport(typesupport)) {
return take<rosidl_typesupport_introspection_cpp::MessageMembers>(
dynamic_data, ros_message, untyped_members);
}
RMW_SET_ERROR_MSG("Unknown typesupport identifier")
return false;
}
| 38.105263 | 82 | 0.785912 | ross-desmond |
9c7bb56013c79a1f386e8d97d0786a977e22fb38 | 1,967 | cpp | C++ | 601-700/647-Palindromic_Substrings-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | 1 | 2018-10-02T22:44:52.000Z | 2018-10-02T22:44:52.000Z | 601-700/647-Palindromic_Substrings-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | null | null | null | 601-700/647-Palindromic_Substrings-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | null | null | null | // Given a string, your task is to count how many palindromic substrings in
// this string.
// The substrings with different start indexes or end indexes are counted as
// different substrings even they consist of same characters.
// Example 1:
// Input: "abc"
// Output: 3
// Explanation: Three palindromic strings: "a", "b", "c".
// Example 2:
// Input: "aaa"
// Output: 6
// Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
// Note:
// The input string length won't exceed 1000.
// Manacher’s Algorithm
// https://articles.leetcode.com/longest-palindromic-substring-part-ii/
// https://www.felix021.com/blog/read.php?2040
class Solution {
string prepare(const string &s) {
stringstream Ts("^");
for (auto &&c : s)
Ts << '#' << c;
if (!s.empty())
Ts << '#';
Ts << '$';
return Ts.str();
}
public:
int countSubstrings(string s) {
string T = prepare(s); // transformed string
vector<int> P(T.size()); // longest palindrome
int C = 0, R = 0; // center, right
for (int i = 1; i < T.size() - 1; ++i) {
P[i] = R > i ? min(R - i, P[2 * C - i]) : 0;
while (T[i + P[i] + 1] == T[i - P[i] - 1])
++P[i];
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
int ret = 0;
for (auto &&pl : P)
ret += (pl + 1) / 2;
return ret;
}
};
// method 2, extend center
class Solution {
public:
int countSubstrings(string S) {
int n = S.size();
int ret = 0, l, r;
for (int i = 0; i < n; ++i) {
l = r = i;
while (l >= 0 && r < n && S[l--] == S[r++])
++ret;
l = i, r = i + 1;
while (l >= 0 && r < n && S[l--] == S[r++])
++ret;
}
return ret;
}
};
// method 3, dp, TODO | 23.141176 | 76 | 0.457041 | ysmiles |
9c8310c2a2dea6ab25be8ccf42817c5a1bac54a4 | 957 | hpp | C++ | src/Evolution/Systems/NewtonianEuler/BoundaryConditions/BoundaryCondition.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/Evolution/Systems/NewtonianEuler/BoundaryConditions/BoundaryCondition.hpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/Evolution/Systems/NewtonianEuler/BoundaryConditions/BoundaryCondition.hpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <pup.h>
#include "Domain/BoundaryConditions/BoundaryCondition.hpp"
namespace NewtonianEuler {
/// \brief Boundary conditions for the Newtonian Euler hydrodynamics system
namespace BoundaryConditions {
/// \brief The base class off of which all boundary conditions must inherit
template <size_t Dim>
class BoundaryCondition : public domain::BoundaryConditions::BoundaryCondition {
public:
BoundaryCondition() = default;
BoundaryCondition(BoundaryCondition&&) = default;
BoundaryCondition& operator=(BoundaryCondition&&) = default;
BoundaryCondition(const BoundaryCondition&) = default;
BoundaryCondition& operator=(const BoundaryCondition&) = default;
~BoundaryCondition() override = default;
explicit BoundaryCondition(CkMigrateMessage* msg);
void pup(PUP::er& p) override;
};
} // namespace BoundaryConditions
} // namespace NewtonianEuler
| 33 | 80 | 0.781609 | nilsvu |
9c83e8cb9572500dad8edbde3cd9091d57c3fae1 | 6,487 | cpp | C++ | ui-cpp/src/IsosurfaceWidget.cpp | MSallermann/spirit | d3b771bcbf2f1eb4b28d48899091c17a48f12c67 | [
"MIT"
] | 46 | 2020-08-24T22:40:15.000Z | 2022-02-28T06:54:54.000Z | ui-cpp/src/IsosurfaceWidget.cpp | MSallermann/spirit | d3b771bcbf2f1eb4b28d48899091c17a48f12c67 | [
"MIT"
] | null | null | null | ui-cpp/src/IsosurfaceWidget.cpp | MSallermann/spirit | d3b771bcbf2f1eb4b28d48899091c17a48f12c67 | [
"MIT"
] | 4 | 2020-09-05T13:24:41.000Z | 2021-11-06T07:46:47.000Z | #include <QtWidgets>
#include "IsosurfaceWidget.hpp"
#include "SpinWidget.hpp"
IsosurfaceWidget::IsosurfaceWidget(std::shared_ptr<State> state, SpinWidget *spinWidget, int i)
{
this->state = state;
this->spinWidget = spinWidget;
setAttribute(Qt::WA_DeleteOnClose);
// Setup User Interface
this->setupUi(this);
// Create renderer pointer
this->m_renderer = std::make_shared<VFRendering::IsosurfaceRenderer>(*spinWidget->view(), *spinWidget->vectorfield());
// Defaults
this->setShowIsosurface(true);
this->setIsovalue(0);
this->setIsocomponent(2);
this->setDrawShadows(false);
if (i == 1) {
this->setIsovalue(0.96);
this->setIsocomponent(0);
this->setDrawShadows(false);
}
if (i == 2) {
this->setIsovalue(-0.96);
this->setIsocomponent(0);
this->setDrawShadows(false);
}
// Read values
auto isovalue = this->isovalue();
horizontalSlider_isovalue->setRange(0, 100);
horizontalSlider_isovalue->setValue((int)(isovalue + 1 * 50));
int component = this->isocomponent();
if (component == 0) this->radioButton_isosurface_x->setChecked(true);
else if (component == 1) this->radioButton_isosurface_y->setChecked(true);
else if (component == 2) this->radioButton_isosurface_z->setChecked(true);
// Add this isosurface to the SpinWidget
this->spinWidget->addIsosurface(m_renderer);
// Connect Slots
this->setupSlots();
// Input validation
QRegularExpression re("[+|-]?[\\d]*[\\.]?[\\d]*");
this->number_validator = new QRegularExpressionValidator(re);
this->setupInputValidators();
}
bool IsosurfaceWidget::showIsosurface()
{
return this->m_show_isosurface;
}
void IsosurfaceWidget::setShowIsosurface(bool show)
{
this->m_show_isosurface = show;
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
float IsosurfaceWidget::isovalue()
{
return this->m_isovalue;
}
void IsosurfaceWidget::setIsovalue(float value)
{
this->m_isovalue = value;
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::ISOVALUE>(m_isovalue);
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
int IsosurfaceWidget::isocomponent()
{
return this->m_isocomponent;
}
void IsosurfaceWidget::setIsocomponent(int component)
{
this->m_isocomponent = component;
if (this->m_isocomponent == 0)
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type {
(void)position;
return direction.x;
});
}
else if (this->m_isocomponent == 1)
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type {
(void)position;
return direction.y;
});
}
else if (this->m_isocomponent == 2)
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type {
(void)position;
return direction.z;
});
}
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
bool IsosurfaceWidget::drawShadows()
{
return this->m_draw_shadows;
}
void IsosurfaceWidget::setDrawShadows(bool show)
{
this->m_draw_shadows = show;
if (this->m_draw_shadows)
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::LIGHTING_IMPLEMENTATION>(
"uniform vec3 uLightPosition;"
"float lighting(vec3 position, vec3 normal)"
"{"
" vec3 lightDirection = -normalize(uLightPosition-position);"
" float diffuse = 0.7*max(0.0, dot(normal, lightDirection));"
" float ambient = 0.2;"
" return diffuse+ambient;"
"}");
}
else
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::LIGHTING_IMPLEMENTATION>(
"float lighting(vec3 position, vec3 normal) { return 1.0; }");
}
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
void IsosurfaceWidget::setupSlots()
{
connect(horizontalSlider_isovalue, SIGNAL(valueChanged(int)), this, SLOT(slot_setIsovalue_slider()));
connect(lineEdit_isovalue, SIGNAL(returnPressed()), this, SLOT(slot_setIsovalue_lineedit()));
connect(radioButton_isosurface_x, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent()));
connect(radioButton_isosurface_y, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent()));
connect(radioButton_isosurface_z, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent()));
connect(checkBox_invert_lighting, SIGNAL(stateChanged(int)), this, SLOT(slot_setTriangleNormal()));
connect(pushButton_remove, SIGNAL(clicked()), this, SLOT(close()));
}
void IsosurfaceWidget::slot_setIsovalue_slider()
{
float isovalue = horizontalSlider_isovalue->value() / 50.0f - 1.0f;
this->lineEdit_isovalue->setText(QString::number(isovalue));
this->setIsovalue(isovalue);
}
void IsosurfaceWidget::slot_setIsovalue_lineedit()
{
float isovalue = this->lineEdit_isovalue->text().toFloat();
this->horizontalSlider_isovalue->setValue((int)(isovalue * 50 + 50));
this->setIsovalue(isovalue);
}
void IsosurfaceWidget::slot_setIsocomponent()
{
if (this->radioButton_isosurface_x->isChecked())
{
this->setIsocomponent(0);
}
else if (this->radioButton_isosurface_y->isChecked())
{
this->setIsocomponent(1);
}
else if (this->radioButton_isosurface_z->isChecked())
{
this->setIsocomponent(2);
}
}
void IsosurfaceWidget::slot_setTriangleNormal()
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::FLIP_NORMALS>(this->checkBox_invert_lighting->isChecked());
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
void IsosurfaceWidget::setupInputValidators()
{
// Isovalue
this->lineEdit_isovalue->setValidator(this->number_validator);
}
void IsosurfaceWidget::closeEvent(QCloseEvent *event)
{
// Remove this isosurface from the SpinWidget
this->spinWidget->removeIsosurface(m_renderer);
// Notify others that this widget was closed
emit closedSignal();
// Close
event->accept();
} | 30.744076 | 196 | 0.681517 | MSallermann |
9c84c3b4bd9b231a0935b3b1cc9bb16255245dcd | 1,946 | cpp | C++ | Sources/Sentry/SentryThreadMetadataCache.cpp | mrtnrst/sentry-cocoa | b8724668c3df2a41600d80b7bbde930f70c20f4a | [
"MIT"
] | null | null | null | Sources/Sentry/SentryThreadMetadataCache.cpp | mrtnrst/sentry-cocoa | b8724668c3df2a41600d80b7bbde930f70c20f4a | [
"MIT"
] | null | null | null | Sources/Sentry/SentryThreadMetadataCache.cpp | mrtnrst/sentry-cocoa | b8724668c3df2a41600d80b7bbde930f70c20f4a | [
"MIT"
] | null | null | null | #include "SentryThreadMetadataCache.hpp"
#if SENTRY_TARGET_PROFILING_SUPPORTED
# include "SentryStackBounds.hpp"
# include "SentryThreadHandle.hpp"
# include <algorithm>
# include <string>
# include <vector>
namespace {
bool
isSentryOwnedThreadName(const std::string &name)
{
return name.rfind("io.sentry", 0) == 0;
}
constexpr std::size_t kMaxThreadNameLength = 100;
} // namespace
namespace sentry {
namespace profiling {
ThreadMetadata
ThreadMetadataCache::metadataForThread(const ThreadHandle &thread)
{
const auto handle = thread.nativeHandle();
const auto it = std::find_if(cache_.cbegin(), cache_.cend(),
[handle](const ThreadHandleMetadataPair &pair) { return pair.handle == handle; });
if (it == cache_.cend()) {
ThreadMetadata metadata;
metadata.threadID = ThreadHandle::tidFromNativeHandle(handle);
metadata.priority = thread.priority();
// If getting the priority fails (via pthread_getschedparam()), that
// means the rest of this is probably going to fail too.
if (metadata.priority != -1) {
auto threadName = thread.name();
if (isSentryOwnedThreadName(threadName)) {
// Don't collect backtraces for Sentry-owned threads.
metadata.priority = 0;
metadata.threadID = 0;
cache_.push_back({ handle, metadata });
return metadata;
}
if (threadName.size() > kMaxThreadNameLength) {
threadName.resize(kMaxThreadNameLength);
}
metadata.name = threadName;
}
cache_.push_back({ handle, metadata });
return metadata;
} else {
return (*it).metadata;
}
}
} // namespace profiling
} // namespace sentry
#endif
| 29.044776 | 94 | 0.588386 | mrtnrst |
9c84dc71b0e1c6286420085b9baad54835b0be76 | 491 | hpp | C++ | Source/Tools/relive_api/JsonMapRootInfoReader.hpp | mouzedrift/alive_reversing | be7dfbaed3be99b452459e974bc4e79f9503c178 | [
"MIT"
] | 208 | 2018-06-06T13:14:03.000Z | 2022-03-30T02:21:27.000Z | Source/Tools/relive_api/JsonMapRootInfoReader.hpp | mouzedrift/alive_reversing | be7dfbaed3be99b452459e974bc4e79f9503c178 | [
"MIT"
] | 537 | 2018-06-06T16:50:45.000Z | 2022-03-31T16:41:15.000Z | Source/Tools/relive_api/JsonMapRootInfoReader.hpp | mouzedrift/alive_reversing | be7dfbaed3be99b452459e974bc4e79f9503c178 | [
"MIT"
] | 42 | 2018-06-06T00:40:08.000Z | 2022-03-23T08:38:55.000Z | #pragma once
#include "JsonModelTypes.hpp"
#include <fstream>
namespace ReliveAPI {
// Reads the root fields to read the version/game type (we need to know this so we can create a game specific reader/do an upgrade of the json).
class JsonMapRootInfoReader final
{
public:
void Read(const std::string& fileName);
MapRootInfo mMapRootInfo;
};
void readFileContentsIntoString(std::string& target, std::ifstream& ifs);
std::string& getStaticStringBuffer();
} // namespace ReliveAPI
| 25.842105 | 144 | 0.759674 | mouzedrift |
9c8778de92fe31f69d52a077c62dd553c09fa5a6 | 1,107 | cpp | C++ | cannon/math/rootfinding.test.cpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | null | null | null | cannon/math/rootfinding.test.cpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | 46 | 2021-01-12T23:03:52.000Z | 2021-10-01T17:29:01.000Z | cannon/math/rootfinding.test.cpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | null | null | null | #include <catch2/catch.hpp>
#include <iomanip>
#include <cannon/math/rootfinding.hpp>
#include <cannon/math/nearly_equal.hpp>
#include <cannon/log/registry.hpp>
using namespace cannon::math;
using namespace cannon::log;
TEST_CASE("Rootfinding", "[math]") {
double r = bisection_method([](double x){
return x * x - 10;
}, -10, 0);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, -std::sqrt(10)));
r = bisection_method([](double x){
return x * x - 10;
}, 0, 10);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, std::sqrt(10)));
r = regula_falsi([](double x){
return x * x - 10;
}, -10, 0);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, -std::sqrt(10)));
r = regula_falsi([](double x){
return x * x - 10;
}, 0, 10);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, std::sqrt(10)));
r = newton_method([](double x) { return x * x - 10; },
[](double x) { return 2 * x; }, -10);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, -std::sqrt(10)));
}
| 26.357143 | 57 | 0.600723 | cannontwo |
9c87dcece66731b3452b1626ab75c3f291c718b3 | 3,646 | cpp | C++ | src/python/pypangolin/window.cpp | Yoyochen0106/Pangolin | e55463bd2bdd758e46ded7d95332e31f9cdc4f71 | [
"MIT"
] | 662 | 2019-09-01T02:16:59.000Z | 2022-03-29T19:24:07.000Z | src/python/pypangolin/window.cpp | Yoyochen0106/Pangolin | e55463bd2bdd758e46ded7d95332e31f9cdc4f71 | [
"MIT"
] | 38 | 2019-09-05T05:02:20.000Z | 2022-03-30T02:59:49.000Z | src/python/pypangolin/window.cpp | Yoyochen0106/Pangolin | e55463bd2bdd758e46ded7d95332e31f9cdc4f71 | [
"MIT"
] | 104 | 2019-09-01T07:41:58.000Z | 2022-03-27T16:24:54.000Z | /* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) Andrey Mnatsakanov
*
* 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 "window.hpp"
#include <pangolin/display/window.h>
namespace py_pangolin {
class PyWindowInterface: public pangolin::WindowInterface{
public:
using pangolin::WindowInterface::WindowInterface;
void ToggleFullscreen() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
ToggleFullscreen);
}
void Move(int x, int y) override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
Move,
x,
y);
}
void Resize(unsigned int w, unsigned int h) override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
Resize,
w,
h);
}
void MakeCurrent() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
MakeCurrent);
}
void RemoveCurrent() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
RemoveCurrent);
}
void ProcessEvents() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
ProcessEvents);
}
void SwapBuffers() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
SwapBuffers);
}
};
void bind_window(pybind11::module &m) {
pybind11::class_<pangolin::WindowInterface, PyWindowInterface > windows_interface(m, "WindowsInterface");
windows_interface
.def(pybind11::init<>())
.def("ToggleFullscreen", &pangolin::WindowInterface::ToggleFullscreen)
.def("Move", &pangolin::WindowInterface::Move)
.def("Resize", &pangolin::WindowInterface::Resize)
.def("MakeCurrent", &pangolin::WindowInterface::MakeCurrent)
.def("ProcessEvents", &pangolin::WindowInterface::ProcessEvents)
.def("SwapBuffers", &pangolin::WindowInterface::SwapBuffers);
}
}
| 34.396226 | 109 | 0.583379 | Yoyochen0106 |
9c8e8209f90318ea5fa25580e127abbba470d4de | 896 | cpp | C++ | 510A.cpp | dipubiswas1303/codeforces_solve | ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79 | [
"MIT"
] | null | null | null | 510A.cpp | dipubiswas1303/codeforces_solve | ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79 | [
"MIT"
] | null | null | null | 510A.cpp | dipubiswas1303/codeforces_solve | ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
/*
NAME : DIPU BISWAS
JUST CSE 2019 - 2020
PROBLEM CODE : 510A
LINK : https://codeforces.com/problemset/problem/510/A
*/
int main()
{
int m, n, i = 0, j = 0, k = 2;
cin >> m >> n;
for(i = 0; i < m; i++){
if(i % 2 == 0)
for(j = 0; j < n; j++)
cout << '#';
else if(i % 2 == 1 && k % 2 == 0){
for(j = 0; j < n; j++)
if(j == n - 1)
cout << '#';
else
cout << '.';
k++;
}
else if(i % 2 == 1 && k % 2 == 1)
{
k--;
for(j = 0; j < n; j++)
if(j == 0)
cout << '#';
else
cout << '.';
}
cout << endl;
}
return 0;
}
| 21.853659 | 57 | 0.287946 | dipubiswas1303 |
9c8f7b6ec3bed83c367fd83de701506ff241464c | 1,837 | cpp | C++ | kernel/node/Pipe.cpp | busybox11/skift | 778ae3a0dc5ac29d7de02200c49d3533e47854c5 | [
"MIT"
] | 2 | 2020-07-14T21:16:54.000Z | 2020-10-08T08:40:47.000Z | kernel/node/Pipe.cpp | busybox11/skift | 778ae3a0dc5ac29d7de02200c49d3533e47854c5 | [
"MIT"
] | null | null | null | kernel/node/Pipe.cpp | busybox11/skift | 778ae3a0dc5ac29d7de02200c49d3533e47854c5 | [
"MIT"
] | null | null | null |
#include <libsystem/Result.h>
#include "kernel/node/Handle.h"
#include "kernel/node/Pipe.h"
#define PIPE_BUFFER_SIZE 4096
static bool pipe_can_read(FsPipe *node, FsHandle *handle)
{
__unused(handle);
// FIXME: make this atomic or something...
return !ringbuffer_is_empty(node->buffer) || !node->writers;
}
static bool pipe_can_write(FsPipe *node, FsHandle *handle)
{
__unused(handle);
// FIXME: make this atomic or something...
return !ringbuffer_is_full(node->buffer) || !node->readers;
}
static Result pipe_read(FsPipe *node, FsHandle *handle, void *buffer, size_t size, size_t *read)
{
__unused(handle);
if (!node->writers)
{
return ERR_STREAM_CLOSED;
}
*read = ringbuffer_read(node->buffer, (char *)buffer, size);
return SUCCESS;
}
static Result pipe_write(FsPipe *node, FsHandle *handle, const void *buffer, size_t size, size_t *written)
{
__unused(handle);
if (!node->readers)
{
return ERR_STREAM_CLOSED;
}
*written = ringbuffer_write(node->buffer, (const char *)buffer, size);
return SUCCESS;
}
static size_t pipe_size(FsPipe *node, FsHandle *handle)
{
__unused(node);
__unused(handle);
return PIPE_BUFFER_SIZE;
}
static void pipe_destroy(FsPipe *node)
{
ringbuffer_destroy(node->buffer);
}
FsNode *fspipe_create()
{
FsPipe *pipe = __create(FsPipe);
fsnode_init(pipe, FILE_TYPE_PIPE);
pipe->can_read = (FsNodeCanReadCallback)pipe_can_read;
pipe->can_write = (FsNodeCanWriteCallback)pipe_can_write;
pipe->read = (FsNodeReadCallback)pipe_read;
pipe->write = (FsNodeWriteCallback)pipe_write;
pipe->size = (FsNodeSizeCallback)pipe_size;
pipe->destroy = (FsNodeDestroyCallback)pipe_destroy;
pipe->buffer = ringbuffer_create(PIPE_BUFFER_SIZE);
return (FsNode *)pipe;
}
| 22.13253 | 106 | 0.696788 | busybox11 |
9c93bc9334c49d76bfcedb4a8635ce8500a2f71c | 1,253 | cpp | C++ | 1595/1573862_AC_0MS_56K.cpp | vandreas19/POJ_sol | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 18 | 2017-08-14T07:34:42.000Z | 2022-01-29T14:20:29.000Z | 1595/1573862_AC_0MS_56K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | null | null | null | 1595/1573862_AC_0MS_56K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 14 | 2016-12-21T23:37:22.000Z | 2021-07-24T09:38:57.000Z | #include<iostream.h>
#include<math.h>
void main()
{
const int iPrimeCount=169;
const int iPrimeNum[iPrimeCount]={1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103
,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211
,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331
,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449
,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587
,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709
,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853
,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991
,997};
int iN,iC,iLimit,iLow,iHigh,i;
while(cin>>iN>>iC)
{
for(i=0;i<iPrimeCount;i++)
{
if(i==iPrimeCount-1)
iLimit=i;
else if(iPrimeNum[i+1]>iN)
{
iLimit=i;
break;
}
}
if(iC>iLimit/2+1)
{
iLow=0;
iHigh=iLimit;
}
else
{
iLow=iLimit/2-iC+1;
iHigh=iLimit/2+iC-1+iLimit%2;
}
cout<<iN<<" "<<iC<<":";
for(i=iLow;i<=iHigh;i++)
cout<<" "<<iPrimeNum[i];
cout<<"\n\n";
}
} | 28.477273 | 116 | 0.621708 | vandreas19 |
9c96bae813bc435c8a8298983f54fe5b60797beb | 4,708 | cc | C++ | analysis/zz_deprecated/untested/RadShockPosn.cc | jfbucas/PION | e0a66aa301e4d94d581ba4df078f1a3b82faab99 | [
"BSD-3-Clause"
] | 4 | 2020-08-20T11:31:22.000Z | 2020-12-05T13:30:03.000Z | analysis/zz_deprecated/untested/RadShockPosn.cc | Mapoet/PION | 51559b18f700c372974ac8658a266b6a647ec764 | [
"BSD-3-Clause"
] | null | null | null | analysis/zz_deprecated/untested/RadShockPosn.cc | Mapoet/PION | 51559b18f700c372974ac8658a266b6a647ec764 | [
"BSD-3-Clause"
] | 4 | 2020-08-20T14:33:19.000Z | 2022-03-07T10:29:34.000Z | /** \file RadShockPosn.cc
* \author Jonathan Mackey
*
* This file reads in a series of fits files, which are assumed to be outputs
* of radiative shock simulations in 1D or 2D. For each file it determines
* the position of the shock in the x-direction, in the 1st y-column, and
* writes the (time,position) pair to a tab delimited text file. The first line
* of the file should contain info about the simulation that the data is from.
*
* This is explicitly serial code, so if there are parallel outputs to multiple
* files this code won't work.
*
* Compile with:\n
* g++ -Wall -DSERIAL RadShockPosn.cc ../testing/global.cc ../testing/uniformGrid.cc ../testing/dataio.cc -lreadline -lcfitsio
*
* Run with (example):\n
* ./a.out v140.txt ../results/RadShock2D_n128x32_v140_n10_T1e4 0 50
*
* */
#include "fitsio.h"
using namespace std;
#include "../testing/global.h"
#include "../testing/uniformGrid.h"
#include "../testing/dataio.h"
int main(int argc, char **argv)
{
// Get two input files and one output file from cmd-line args.
if (argc!=5) {
cerr << "Error: must call with 4 arguments...\n";
cerr << "RadShockPosn: <executable> <OutfileName> <file-base> <FirstOutput> <OutputFreq>\n";
rep.error("Bad number of Args",argc);
}
string outfile = argv[1];
string infilebase = argv[2];
int startct = atoi(argv[3]);
int opfreq = atoi(argv[4]);
if (isnan(startct) || isnan(opfreq) || opfreq==0) rep.error("Bad ints in args",opfreq);
cout <<"reading from first file "<<infilebase<<"."<<startct<<".fits\n";
cout <<"Writing shock position to file "<<outfile<<"\n";
cout <<"**********************************************\n";
class DataIOFits dataio;
class file_status fs;
// First we need to open the first file in the list, and get the grid dimensions,
// so we can set it up once and use it for all the infiles.
string infile;
ostringstream temp; temp.str("");
temp << infilebase <<"."<<startct <<".fits";
infile=temp.str();
cout <<"Initially reading from file "<<infile<<endl;
int err=0;
if (!fs.file_exists(infile)) rep.error("First file not found!",infile);
err = dataio.ReadHeader(infile);
if (err) rep.error("read header went bad",err);
// check dimensionality is ok.
if (SimPM.ndim!=1 && SimPM.ndim!=2)
rep.error("need 1D or 2D sim for rad.shock test",SimPM.ndim);
// Now the header should contain the sim dimensionality, number of vars,
// size of box, so we can use these to set up the grid.
cout <<"(UniformFV::setup_grid) Setting up grid...\n";
grid = new UniformGrid (SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Xmin, SimPM.Xmax, SimPM.NG);
if (grid==0) rep.error("(IntUniformFV::setup_grid) Couldn't assign data!", grid);
cout <<"(setup_grid) Done. g="<<grid<<"\n";
// Set up and open outfile
if (fs.file_exists(outfile)) cout <<"WARNING:: file exists, I am overwriting a text file.\n";
ofstream outf(outfile.c_str());
if(!outf.is_open()) rep.error("couldn't open outfile",outfile);
outf.setf( ios_base::scientific );
outf.precision(6);
outf << "# Radiative Shock Test Problem outputs. First file: "<<infile<<endl;
outf << "# Columns are time and shock position, and should be in cgs units (s,cm).\n\n";
int count = startct; double refvel=0.0;
// Need to loop this over all timesteps, incrementing 'start' by 'step' each time
// until there are no more files to analyse (note the last one might get left out).
do {
cout <<"Reading from file "<<infile<<endl;
// read data onto grid.
err += dataio.ReadHeader(infile);
err += dataio.ReadData(infile);
if (err) rep.error("read data went bad for file",err);
// get first point, and move to XP end of grid.
cell *c = grid->FirstPt();
do {c=grid->NextPt(c,XP);} while (grid->NextPt(c,XP) !=0);
cell *c2 = grid->NextPt(c,XN); if (!c2) {rep.error("Lost on grid",c2); grid->PrintCell(c);}
refvel = c->P[VX];
// find the shock position by locating where VX first changes by >10%
while ( fabs(fabs(c2->P[VX]/refvel)-1.0) <= 0.3) {
c = c2;
c2 = grid->NextPt(c2,XN);
if (!c2) { cout <<"no shock found!\n"; c2=c; break; }
}
// Write (x_sh,t_sim) to file.
outf <<SimPM.simtime<<"\t"<<c2->x[XX]<<"\n";
// increment filename
count += opfreq;
temp.str("");
temp << infilebase <<"."<< count <<".fits"; infile=temp.str();
} while (fs.file_exists(infile));
// loop over all timesteps.
cout <<"\n***************************************************\n";
cout <<"couldn't find file "<<infile<<" for step "<<count<<"... assuming i'm finished!\n";
outf.close();
delete grid; grid=0;
return 0;
}
| 40.586207 | 126 | 0.634452 | jfbucas |
9c98a694e55d27be8b03bea36cf1e5bb88a1f3cd | 6,158 | hpp | C++ | CppSprtPkg/Include/ext/pb_ds/detail/binomial_heap_base_/binomial_heap_base_.hpp | lvjianmin-loongson/uefi | d6fba2f83e00125ff0362b4583461958d459fb4b | [
"BSD-2-Clause"
] | null | null | null | CppSprtPkg/Include/ext/pb_ds/detail/binomial_heap_base_/binomial_heap_base_.hpp | lvjianmin-loongson/uefi | d6fba2f83e00125ff0362b4583461958d459fb4b | [
"BSD-2-Clause"
] | null | null | null | CppSprtPkg/Include/ext/pb_ds/detail/binomial_heap_base_/binomial_heap_base_.hpp | lvjianmin-loongson/uefi | d6fba2f83e00125ff0362b4583461958d459fb4b | [
"BSD-2-Clause"
] | null | null | null | // -*- C++ -*-
// Copyright (C) 2005, 2006, 2009 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library 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.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file binomial_heap_base_.hpp
* Contains an implementation class for a base of binomial heaps.
*/
#ifndef PB_DS_BINOMIAL_HEAP_BASE_HPP
#define PB_DS_BINOMIAL_HEAP_BASE_HPP
/*
* Binomial heap base.
* Vuillemin J is the mastah.
* Modified from CLRS.
*/
#include <debug/debug.h>
#include <ext/pb_ds/detail/cond_dealtor.hpp>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <ext/pb_ds/detail/left_child_next_sibling_heap_/left_child_next_sibling_heap_.hpp>
#include <ext/pb_ds/detail/left_child_next_sibling_heap_/null_metadata.hpp>
namespace __gnu_pbds
{
namespace detail
{
#define PB_DS_CLASS_T_DEC \
template<typename Value_Type, class Cmp_Fn, class Allocator>
#define PB_DS_CLASS_C_DEC \
binomial_heap_base_<Value_Type, Cmp_Fn, Allocator>
#ifdef _GLIBCXX_DEBUG
#define PB_DS_BASE_C_DEC \
left_child_next_sibling_heap_<Value_Type, Cmp_Fn, \
typename Allocator::size_type, \
Allocator, false>
#else
#define PB_DS_BASE_C_DEC \
left_child_next_sibling_heap_<Value_Type, Cmp_Fn, \
typename Allocator::size_type, Allocator>
#endif
/**
* class description = "8y|\|0|\/|i41 h34p 74813">
**/
template<typename Value_Type, class Cmp_Fn, class Allocator>
class binomial_heap_base_ : public PB_DS_BASE_C_DEC
{
private:
typedef PB_DS_BASE_C_DEC base_type;
protected:
typedef typename base_type::node node;
typedef typename base_type::node_pointer node_pointer;
typedef typename base_type::const_node_pointer const_node_pointer;
public:
typedef typename Allocator::size_type size_type;
typedef typename Allocator::difference_type difference_type;
typedef Value_Type value_type;
typedef
typename Allocator::template rebind<
value_type>::other::pointer
pointer;
typedef
typename Allocator::template rebind<
value_type>::other::const_pointer
const_pointer;
typedef
typename Allocator::template rebind<
value_type>::other::reference
reference;
typedef
typename Allocator::template rebind<
value_type>::other::const_reference
const_reference;
typedef
typename PB_DS_BASE_C_DEC::const_point_iterator
const_point_iterator;
typedef typename PB_DS_BASE_C_DEC::point_iterator point_iterator;
typedef typename PB_DS_BASE_C_DEC::const_iterator const_iterator;
typedef typename PB_DS_BASE_C_DEC::iterator iterator;
typedef Cmp_Fn cmp_fn;
typedef Allocator allocator_type;
public:
inline point_iterator
push(const_reference r_val);
void
modify(point_iterator it, const_reference r_new_val);
inline const_reference
top() const;
void
pop();
void
erase(point_iterator it);
inline void
clear();
template<typename Pred>
size_type
erase_if(Pred pred);
template<typename Pred>
void
split(Pred pred, PB_DS_CLASS_C_DEC& other);
void
join(PB_DS_CLASS_C_DEC& other);
protected:
binomial_heap_base_();
binomial_heap_base_(const Cmp_Fn& r_cmp_fn);
binomial_heap_base_(const PB_DS_CLASS_C_DEC& other);
void
swap(PB_DS_CLASS_C_DEC& other);
~binomial_heap_base_();
template<typename It>
void
copy_from_range(It first_it, It last_it);
inline void
find_max();
#ifdef _GLIBCXX_DEBUG
void
assert_valid(bool strictly_binomial) const;
void
assert_max() const;
#endif
private:
inline node_pointer
fix(node_pointer p_nd) const;
inline void
insert_node(node_pointer p_nd);
inline void
remove_parentless_node(node_pointer p_nd);
inline node_pointer
join(node_pointer p_lhs, node_pointer p_rhs) const;
#ifdef _GLIBCXX_DEBUG
void
assert_node_consistent(const_node_pointer, bool, bool) const;
#endif
protected:
node_pointer m_p_max;
};
#include <ext/pb_ds/detail/binomial_heap_base_/constructors_destructor_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/debug_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/find_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/insert_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/erase_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/split_join_fn_imps.hpp>
#undef PB_DS_CLASS_C_DEC
#undef PB_DS_CLASS_T_DEC
#undef PB_DS_BASE_C_DEC
} // namespace detail
} // namespace __gnu_pbds
#endif
| 26.204255 | 91 | 0.729458 | lvjianmin-loongson |
9c9ad6755960492a50c414be65c6f06b2bee3a93 | 35,058 | cpp | C++ | Source/Tools/Editor/Editor.cpp | tatjam/rbfx | 565b505a8ded1ddf6e0fd0f322e004cb9aefc499 | [
"MIT"
] | 1 | 2021-01-09T14:42:48.000Z | 2021-01-09T14:42:48.000Z | Source/Tools/Editor/Editor.cpp | tatjam/rbfx | 565b505a8ded1ddf6e0fd0f322e004cb9aefc499 | [
"MIT"
] | null | null | null | Source/Tools/Editor/Editor.cpp | tatjam/rbfx | 565b505a8ded1ddf6e0fd0f322e004cb9aefc499 | [
"MIT"
] | 1 | 2020-06-29T08:05:12.000Z | 2020-06-29T08:05:12.000Z | //
// Copyright (c) 2017-2020 the rbfx project.
//
// 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.
//
#ifdef WIN32
#include <windows.h>
#endif
#include <Urho3D/Engine/EngineDefs.h>
#include <Urho3D/Engine/EngineEvents.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/WorkQueue.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Resource/JSONArchive.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <Urho3D/SystemUI/Console.h>
#include <Urho3D/SystemUI/DebugHud.h>
#include <Urho3D/LibraryInfo.h>
#include <Urho3D/Core/CommandLine.h>
#include <Urho3D/Audio/Sound.h>
#include <Toolbox/ToolboxAPI.h>
#include <Toolbox/SystemUI/Widgets.h>
#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include <nativefiledialog/nfd.h>
#include "Editor.h"
#include "EditorEvents.h"
#include "EditorIconCache.h"
#include "Tabs/Scene/SceneTab.h"
#include "Tabs/Scene/EditorSceneSettings.h"
#include "Tabs/UI/UITab.h"
#include "Tabs/InspectorTab.h"
#include "Tabs/HierarchyTab.h"
#include "Tabs/ConsoleTab.h"
#include "Tabs/ResourceTab.h"
#include "Tabs/PreviewTab.h"
#include "Pipeline/Asset.h"
#include "Pipeline/Commands/CookScene.h"
#include "Pipeline/Commands/BuildAssets.h"
#include "Pipeline/Importers/ModelImporter.h"
#include "Pipeline/Importers/SceneConverter.h"
#include "Pipeline/Importers/TextureImporter.h"
#if URHO3D_PLUGINS
# include "Plugins/PluginManager.h"
# include "Plugins/ModulePlugin.h"
#endif
#include "Plugins/ScriptBundlePlugin.h"
#include "Inspector/AssetInspector.h"
#include "Inspector/MaterialInspector.h"
#include "Inspector/ModelInspector.h"
#include "Inspector/NodeInspector.h"
#include "Inspector/ComponentInspector.h"
#include "Inspector/SerializableInspector.h"
#include "Inspector/SoundInspector.h"
#include "Inspector/UIElementInspector.h"
#include "Tabs/ProfilerTab.h"
#include "EditorUndo.h"
namespace Urho3D
{
namespace
{
const auto&& DEFAULT_TAB_TYPES = {
InspectorTab::GetTypeStatic(),
HierarchyTab::GetTypeStatic(),
ResourceTab::GetTypeStatic(),
ConsoleTab::GetTypeStatic(),
PreviewTab::GetTypeStatic(),
SceneTab::GetTypeStatic(),
ProfilerTab::GetTypeStatic()
};
}
Editor::Editor(Context* context)
: Application(context)
{
}
void Editor::Setup()
{
context_->RegisterSubsystem(this, Editor::GetTypeStatic());
#ifdef _WIN32
// Required until SDL supports hdpi on windows
if (HMODULE hLibrary = LoadLibraryA("Shcore.dll"))
{
typedef HRESULT(WINAPI*SetProcessDpiAwarenessType)(size_t value);
if (auto fn = GetProcAddress(hLibrary, "SetProcessDpiAwareness"))
((SetProcessDpiAwarenessType)fn)(2); // PROCESS_PER_MONITOR_DPI_AWARE
FreeLibrary(hLibrary);
}
#endif
// Discover resource prefix path by looking for CoreData and going up.
for (coreResourcePrefixPath_ = context_->GetFileSystem()->GetProgramDir();;
coreResourcePrefixPath_ = GetParentPath(coreResourcePrefixPath_))
{
if (context_->GetFileSystem()->DirExists(coreResourcePrefixPath_ + "CoreData"))
break;
else
{
#if WIN32
if (coreResourcePrefixPath_.length() <= 3) // Root path of any drive
#else
if (coreResourcePrefixPath_ == "/") // Filesystem root
#endif
{
URHO3D_LOGERROR("Prefix path not found, unable to continue. Prefix path must contain all of your data "
"directories (including CoreData).");
engine_->Exit();
}
}
}
engineParameters_[EP_WINDOW_TITLE] = GetTypeName();
engineParameters_[EP_HEADLESS] = false;
engineParameters_[EP_FULL_SCREEN] = false;
engineParameters_[EP_LOG_LEVEL] = LOG_DEBUG;
engineParameters_[EP_WINDOW_RESIZABLE] = true;
engineParameters_[EP_AUTOLOAD_PATHS] = "";
engineParameters_[EP_RESOURCE_PATHS] = "CoreData;EditorData";
engineParameters_[EP_RESOURCE_PREFIX_PATHS] = coreResourcePrefixPath_;
engineParameters_[EP_WINDOW_MAXIMIZE] = true;
engineParameters_[EP_ENGINE_AUTO_LOAD_SCRIPTS] = false;
#if URHO3D_SYSTEMUI_VIEWPORTS
engineParameters_[EP_HIGH_DPI] = true;
engineParameters_[EP_SYSTEMUI_FLAGS] = ImGuiConfigFlags_ViewportsEnable | ImGuiConfigFlags_DpiEnableScaleViewports;
#else
engineParameters_[EP_HIGH_DPI] = false;
#endif
// Load editor settings
{
auto* fs = context_->GetFileSystem();
ea::string editorSettingsDir = fs->GetAppPreferencesDir("rbfx", "Editor");
if (!fs->DirExists(editorSettingsDir))
fs->CreateDir(editorSettingsDir);
ea::string editorSettingsFile = editorSettingsDir + "Editor.json";
if (fs->FileExists(editorSettingsFile))
{
JSONFile file(context_);
if (file.LoadFile(editorSettingsFile))
{
JSONInputArchive archive(&file);
if (!Serialize(archive))
URHO3D_LOGERROR("Loading of editor settings failed.");
engineParameters_[EP_WINDOW_WIDTH] = windowSize_.x_;
engineParameters_[EP_WINDOW_HEIGHT] = windowSize_.y_;
engineParameters_[EP_WINDOW_POSITION_X] = windowPos_.x_;
engineParameters_[EP_WINDOW_POSITION_Y] = windowPos_.y_;
}
}
}
context_->GetLog()->SetLogFormat("[%H:%M:%S] [%l] [%n] : %v");
SetRandomSeed(Time::GetTimeSinceEpoch());
// Register factories
context_->RegisterFactory<EditorIconCache>();
context_->RegisterFactory<SceneTab>();
context_->RegisterFactory<UITab>();
context_->RegisterFactory<ConsoleTab>();
context_->RegisterFactory<HierarchyTab>();
context_->RegisterFactory<InspectorTab>();
context_->RegisterFactory<ResourceTab>();
context_->RegisterFactory<PreviewTab>();
context_->RegisterFactory<ProfilerTab>();
// Inspectors.
inspectors_.push_back(SharedPtr(new AssetInspector(context_)));
inspectors_.push_back(SharedPtr(new ModelInspector(context_)));
inspectors_.push_back(SharedPtr(new MaterialInspector(context_)));
inspectors_.push_back(SharedPtr(new SoundInspector(context_)));
inspectors_.push_back(SharedPtr(new NodeInspector(context_)));
inspectors_.push_back(SharedPtr(new ComponentInspector(context_)));
inspectors_.push_back(SharedPtr(new UIElementInspector(context_)));
// FIXME: If user registers their own inspector later then SerializableInspector would no longer come in last.
inspectors_.push_back(SharedPtr(new SerializableInspector(context_)));
#if URHO3D_PLUGINS
RegisterPluginsLibrary(context_);
#endif
RegisterToolboxTypes(context_);
EditorSceneSettings::RegisterObject(context_);
context_->RegisterFactory<SerializableInspector>();
// Importers
ModelImporter::RegisterObject(context_);
SceneConverter::RegisterObject(context_);
TextureImporter::RegisterObject(context_);
Asset::RegisterObject(context_);
// Define custom command line parameters here
auto& cmd = GetCommandLineParser();
cmd.add_option("project", defaultProjectPath_, "Project to open or create on startup.")->set_custom_option("dir");
// Subcommands
RegisterSubcommand<CookScene>();
RegisterSubcommand<BuildAssets>();
keyBindings_.Bind(ActionType::OpenProject, this, &Editor::OpenOrCreateProject);
keyBindings_.Bind(ActionType::Exit, this, &Editor::OnExitHotkeyPressed);
}
void Editor::Start()
{
// Execute specified subcommand and exit.
for (SharedPtr<SubCommand>& cmd : subCommands_)
{
if (GetCommandLineParser().got_subcommand(cmd->GetTypeName().c_str()))
{
context_->GetLog()->SetLogFormat("%v");
ExecuteSubcommand(cmd);
engine_->Exit();
return;
}
}
// Continue with normal editor initialization
context_->RegisterSubsystem(new SceneManager(context_));
context_->RegisterSubsystem(new EditorIconCache(context_));
context_->GetInput()->SetMouseMode(MM_ABSOLUTE);
context_->GetInput()->SetMouseVisible(true);
context_->GetCache()->SetAutoReloadResources(true);
engine_->SetAutoExit(false);
SubscribeToEvent(E_UPDATE, [this](StringHash, VariantMap& args) { OnUpdate(args); });
// Creates console but makes sure it's UI is not rendered. Console rendering is done manually in editor.
auto* console = engine_->CreateConsole();
console->SetAutoVisibleOnError(false);
context_->GetFileSystem()->SetExecuteConsoleCommands(false);
SubscribeToEvent(E_CONSOLECOMMAND, [this](StringHash, VariantMap& args) { OnConsoleCommand(args); });
console->RefreshInterpreters();
SubscribeToEvent(E_ENDFRAME, [this](StringHash, VariantMap&) { OnEndFrame(); });
SubscribeToEvent(E_EXITREQUESTED, [this](StringHash, VariantMap&) { OnExitRequested(); });
SubscribeToEvent(E_EDITORPROJECTSERIALIZE, [this](StringHash, VariantMap&) { UpdateWindowTitle(); });
SubscribeToEvent(E_CONSOLEURICLICK, [this](StringHash, VariantMap& args) { OnConsoleUriClick(args); });
SubscribeToEvent(E_EDITORSELECTIONCHANGED, &Editor::OnSelectionChanged);
SetupSystemUI();
if (!defaultProjectPath_.empty())
{
ui::GetIO().IniFilename = nullptr; // Avoid creating imgui.ini in some cases
OpenProject(defaultProjectPath_);
}
// Hud will be rendered manually.
context_->GetEngine()->CreateDebugHud()->SetMode(DEBUGHUD_SHOW_NONE);
}
void Editor::ExecuteSubcommand(SubCommand* cmd)
{
if (!defaultProjectPath_.empty())
{
project_ = new Project(context_);
context_->RegisterSubsystem(project_);
if (!project_->LoadProject(defaultProjectPath_))
{
URHO3D_LOGERRORF("Loading project '%s' failed.", pendingOpenProject_.c_str());
exitCode_ = EXIT_FAILURE;
engine_->Exit();
return;
}
}
cmd->Execute();
}
void Editor::Stop()
{
// Save editor settings
if (!engine_->IsHeadless())
{
// Save window geometry
auto* graphics = GetSubsystem<Graphics>();
windowPos_ = graphics->GetWindowPosition();
windowSize_ = graphics->GetSize();
auto* fs = context_->GetFileSystem();
ea::string editorSettingsDir = fs->GetAppPreferencesDir("rbfx", "Editor");
if (!fs->DirExists(editorSettingsDir))
fs->CreateDir(editorSettingsDir);
JSONFile json(context_);
JSONOutputArchive archive(&json);
if (Serialize(archive))
{
if (!json.SaveFile(editorSettingsDir + "Editor.json"))
URHO3D_LOGERROR("Saving of editor settings failed.");
}
else
URHO3D_LOGERROR("Serializing of editor settings failed.");
}
context_->GetWorkQueue()->Complete(0);
if (auto* manager = GetSubsystem<SceneManager>())
manager->UnloadAll();
CloseProject();
context_->RemoveSubsystem<WorkQueue>(); // Prevents deadlock when unloading plugin AppDomain in managed host.
context_->RemoveSubsystem<Editor>();
}
void Editor::OnUpdate(VariantMap& args)
{
ImGuiWindowFlags flags = ImGuiWindowFlags_MenuBar;
flags |= ImGuiWindowFlags_NoDocking;
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace", nullptr, flags);
ImGui::PopStyleVar();
RenderMenuBar();
RenderSettingsWindow();
bool hasModified = false;
if (project_.NotNull())
{
dockspaceId_ = ui::GetID("Root");
ui::DockSpace(dockspaceId_);
auto tabsCopy = tabs_;
for (auto& tab : tabsCopy)
{
if (tab->RenderWindow())
{
// Only active window may override another active window
if (activeTab_ != tab && tab->IsActive())
{
activeTab_ = tab;
tab->OnFocused();
}
hasModified |= tab->IsModified();
}
else if (!tab->IsUtility())
// Content tabs get closed permanently
tabs_.erase(tabs_.find(tab));
}
if (!activeTab_.Expired())
{
activeTab_->OnActiveUpdate();
}
if (loadDefaultLayout_ && project_)
{
loadDefaultLayout_ = false;
LoadDefaultLayout();
}
}
else
{
// Render start page
auto& style = ui::GetStyle();
auto* lists = ui::GetWindowDrawList();
ImRect rect{ui::GetWindowContentRegionMin(), ui::GetWindowContentRegionMax()};
ImVec2 tileSize{200, 200};
ui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2{10, 10});
ui::SetCursorPos(rect.GetCenter() - ImVec2{tileSize.x * 1.5f + 10, tileSize.y * 1.5f + 10});
ui::BeginGroup();
struct State
{
explicit State(Editor* editor)
{
FileSystem *fs = editor->GetContext()->GetFileSystem();
StringVector& recents = editor->recentProjects_;
snapshots_.resize(recents.size());
for (int i = 0; i < recents.size();)
{
const ea::string& projectPath = recents[i];
ea::string snapshotFile = AddTrailingSlash(projectPath) + ".snapshot.png";
if (fs->FileExists(snapshotFile))
{
Image img(editor->context_);
if (img.LoadFile(snapshotFile))
{
SharedPtr<Texture2D> texture(editor->context_->CreateObject<Texture2D>());
texture->SetData(&img);
snapshots_[i] = texture;
}
}
++i;
}
}
ea::vector<SharedPtr<Texture2D>> snapshots_;
};
auto* state = ui::GetUIState<State>(this);
const StringVector& recents = recentProjects_;
int index = 0;
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++, index++)
{
SharedPtr<Texture2D> snapshot;
if (state->snapshots_.size() > index)
snapshot = state->snapshots_[index];
if (recents.size() <= index || (row == 2 && col == 2)) // Last tile never shows a project.
{
if (ui::Button("Open/Create Project", tileSize))
OpenOrCreateProject();
}
else
{
const ea::string& projectPath = recents[index];
if (snapshot.NotNull())
{
if (ui::ImageButton(snapshot.Get(), tileSize - style.ItemInnerSpacing * 2))
OpenProject(projectPath);
}
else
{
if (ui::Button(recents[index].c_str(), tileSize))
OpenProject(projectPath);
}
if (ui::IsItemHovered())
ui::SetTooltip("%s", projectPath.c_str());
}
ui::SameLine();
}
ui::NewLine();
}
ui::EndGroup();
ui::PopStyleVar();
}
ui::End();
ImGui::PopStyleVar();
// Dialog for a warning when application is being closed with unsaved resources.
if (exiting_)
{
if (!context_->GetWorkQueue()->IsCompleted(0))
{
ui::OpenPopup("Completing Tasks");
if (ui::BeginPopupModal("Completing Tasks", nullptr, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_Popup))
{
ui::TextUnformatted("Some tasks are in progress and are being completed. Please wait.");
static float totalIncomplete = context_->GetWorkQueue()->GetNumIncomplete(0);
ui::ProgressBar(100.f / totalIncomplete * Min(totalIncomplete - (float)context_->GetWorkQueue()->GetNumIncomplete(0), totalIncomplete));
ui::EndPopup();
}
}
else if (hasModified)
{
ui::OpenPopup("Save All?");
if (ui::BeginPopupModal("Save All?", nullptr, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_Popup))
{
ui::TextUnformatted("You have unsaved resources. Save them before exiting?");
if (ui::Button(ICON_FA_SAVE " Save & Close"))
{
for (auto& tab : tabs_)
{
if (tab->IsModified())
tab->SaveResource();
}
ui::CloseCurrentPopup();
}
ui::SameLine();
if (ui::Button(ICON_FA_EXCLAMATION_TRIANGLE " Close without saving"))
{
engine_->Exit();
}
ui::SetHelpTooltip(ICON_FA_EXCLAMATION_TRIANGLE " All unsaved changes will be lost!", KEY_UNKNOWN);
ui::SameLine();
if (ui::Button(ICON_FA_TIMES " Cancel"))
{
exiting_ = false;
ui::CloseCurrentPopup();
}
ui::EndPopup();
}
}
else
{
context_->GetWorkQueue()->Complete(0);
if (project_.NotNull())
{
project_->SaveProject();
CloseProject();
}
engine_->Exit();
}
}
}
Tab* Editor::CreateTab(StringHash type)
{
SharedPtr<Tab> tab(DynamicCast<Tab>(context_->CreateObject(type)));
tabs_.push_back(tab);
return tab.Get();
}
StringVector Editor::GetObjectsByCategory(const ea::string& category)
{
StringVector result;
const auto& factories = context_->GetObjectFactories();
auto it = context_->GetObjectCategories().find(category);
if (it != context_->GetObjectCategories().end())
{
for (const StringHash& type : it->second)
{
auto jt = factories.find(type);
if (jt != factories.end())
result.push_back(jt->second->GetTypeName());
}
}
return result;
}
void Editor::OnConsoleCommand(VariantMap& args)
{
using namespace ConsoleCommand;
if (args[P_COMMAND].GetString() == "revision")
URHO3D_LOGINFOF("Engine revision: %s", GetRevision());
}
void Editor::OnEndFrame()
{
// Opening a new project must be done at the point when SystemUI is not in use. End of the frame is a good
// candidate. This subsystem will be recreated.
if (!pendingOpenProject_.empty())
{
CloseProject();
// Reset SystemUI so that imgui loads it's config proper.
context_->RemoveSubsystem<SystemUI>();
#if URHO3D_SYSTEMUI_VIEWPORTS
unsigned flags = ImGuiConfigFlags_ViewportsEnable | ImGuiConfigFlags_DpiEnableScaleViewports;
#else
unsigned flags = 0;
#endif
context_->RegisterSubsystem(new SystemUI(context_, flags));
SetupSystemUI();
project_ = new Project(context_);
context_->RegisterSubsystem(project_);
bool loaded = project_->LoadProject(pendingOpenProject_);
// SystemUI has to be started after loading project, because project sets custom settings file path. Starting
// subsystem reads this file and loads settings.
if (loaded)
{
auto* fs = context_->GetFileSystem();
loadDefaultLayout_ = project_->NeeDefaultUIPlacement();
StringVector& recents = recentProjects_;
// Remove latest project if it was already opened or any projects that no longer exists.
for (auto it = recents.begin(); it != recents.end();)
{
if (*it == pendingOpenProject_ || !fs->DirExists(*it))
it = recents.erase(it);
else
++it;
}
// Latest project goes to front
recents.insert(recents.begin(), pendingOpenProject_);
// Limit recents list size
if (recents.size() > 10)
recents.resize(10);
}
else
{
CloseProject();
URHO3D_LOGERROR("Loading project failed.");
}
pendingOpenProject_.clear();
}
}
void Editor::OnExitRequested()
{
if (auto* preview = GetTab<PreviewTab>())
{
if (preview->GetSceneSimulationStatus() != SCENE_SIMULATION_STOPPED)
preview->Stop();
}
exiting_ = true;
}
void Editor::OnExitHotkeyPressed()
{
if (!exiting_)
OnExitRequested();
}
void Editor::CreateDefaultTabs()
{
for (StringHash type : DEFAULT_TAB_TYPES)
context_->RemoveSubsystem(type);
tabs_.clear();
for (StringHash type : DEFAULT_TAB_TYPES)
{
SharedPtr<Tab> tab;
tab.StaticCast(context_->CreateObject(type));
tabs_.push_back(tab);
}
}
void Editor::LoadDefaultLayout()
{
CreateDefaultTabs();
auto* inspector = GetTab<InspectorTab>();
auto* hierarchy = GetTab<HierarchyTab>();
auto* resources = GetTab<ResourceTab>();
auto* console = GetTab<ConsoleTab>();
auto* preview = GetTab<PreviewTab>();
auto* scene = GetTab<SceneTab>();
auto* profiler = GetTab<ProfilerTab>();
profiler->SetOpen(false);
ImGui::DockBuilderRemoveNode(dockspaceId_);
ImGui::DockBuilderAddNode(dockspaceId_, 0);
ImGui::DockBuilderSetNodeSize(dockspaceId_, ui::GetMainViewport()->Size);
ImGuiID dock_main_id = dockspaceId_;
ImGuiID dockHierarchy = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Left, 0.20f, nullptr, &dock_main_id);
ImGuiID dockResources = ImGui::DockBuilderSplitNode(dockHierarchy, ImGuiDir_Down, 0.40f, nullptr, &dockHierarchy);
ImGuiID dockInspector = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.30f, nullptr, &dock_main_id);
ImGuiID dockLog = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Down, 0.30f, nullptr, &dock_main_id);
ImGui::DockBuilderDockWindow(hierarchy->GetUniqueTitle().c_str(), dockHierarchy);
ImGui::DockBuilderDockWindow(resources->GetUniqueTitle().c_str(), dockResources);
ImGui::DockBuilderDockWindow(console->GetUniqueTitle().c_str(), dockLog);
ImGui::DockBuilderDockWindow(profiler->GetUniqueTitle().c_str(), dockLog);
ImGui::DockBuilderDockWindow(scene->GetUniqueTitle().c_str(), dock_main_id);
ImGui::DockBuilderDockWindow(preview->GetUniqueTitle().c_str(), dock_main_id);
ImGui::DockBuilderDockWindow(inspector->GetUniqueTitle().c_str(), dockInspector);
ImGui::DockBuilderFinish(dockspaceId_);
scene->Activate();
}
void Editor::OpenProject(const ea::string& projectPath)
{
pendingOpenProject_ = AddTrailingSlash(projectPath);
}
void Editor::CloseProject()
{
SendEvent(E_EDITORPROJECTCLOSING);
context_->RemoveSubsystem<Project>();
for (StringHash type : DEFAULT_TAB_TYPES)
context_->RemoveSubsystem(type);
tabs_.clear();
project_.Reset();
}
Tab* Editor::GetTabByName(const ea::string& uniqueName)
{
for (auto& tab : tabs_)
{
if (tab->GetUniqueName() == uniqueName)
return tab.Get();
}
return nullptr;
}
Tab* Editor::GetTabByResource(const ea::string& resourceName)
{
for (auto& tab : tabs_)
{
auto resource = DynamicCast<BaseResourceTab>(tab);
if (resource && resource->GetResourceName() == resourceName)
return resource.Get();
}
return nullptr;
}
Tab* Editor::GetTab(StringHash type)
{
for (auto& tab : tabs_)
{
if (tab->GetType() == type)
return tab.Get();
}
return nullptr;
}
void Editor::SetupSystemUI()
{
static ImWchar fontAwesomeIconRanges[] = {ICON_MIN_FA, ICON_MAX_FA, 0};
static ImWchar notoSansRanges[] = {0x20, 0x52f, 0x1ab0, 0x2189, 0x2c60, 0x2e44, 0xa640, 0xab65, 0};
static ImWchar notoMonoRanges[] = {0x20, 0x513, 0x1e00, 0x1f4d, 0};
SystemUI* systemUI = GetSubsystem<SystemUI>();
systemUI->ApplyStyleDefault(true, 1.0f);
systemUI->AddFont("Fonts/NotoSans-Regular.ttf", notoSansRanges, 16.f);
systemUI->AddFont("Fonts/" FONT_ICON_FILE_NAME_FAS, fontAwesomeIconRanges, 14.f, true);
monoFont_ = systemUI->AddFont("Fonts/NotoMono-Regular.ttf", notoMonoRanges, 14.f);
systemUI->AddFont("Fonts/" FONT_ICON_FILE_NAME_FAS, fontAwesomeIconRanges, 12.f, true);
ui::GetStyle().WindowRounding = 3;
// Disable imgui saving ui settings on it's own. These should be serialized to project file.
auto& io = ui::GetIO();
#if URHO3D_SYSTEMUI_VIEWPORTS
io.ConfigViewportsNoAutoMerge = true;
#endif
io.IniFilename = nullptr;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard;
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.ConfigWindowsResizeFromEdges = true;
// TODO: Make configurable.
auto& style = ImGui::GetStyle();
style.FrameBorderSize = 0;
style.WindowBorderSize = 1;
style.ItemSpacing = {4, 4};
ImVec4* colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_Border] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.26f, 0.26f, 0.26f, 1.00f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.32f, 0.32f, 0.32f, 1.00f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.37f, 0.37f, 0.37f, 1.00f);
colors[ImGuiCol_TitleBg] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.00f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.56f, 0.56f, 0.56f, 1.00f);
colors[ImGuiCol_Button] = ImVec4(0.27f, 0.27f, 0.27f, 1.00f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.34f, 0.34f, 0.34f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.38f, 0.38f, 0.38f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.35f, 0.35f, 0.35f, 1.00f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.44f, 0.44f, 0.44f, 1.00f);
colors[ImGuiCol_Separator] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.34f, 0.34f, 0.34f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.37f, 0.37f, 0.37f, 1.00f);
colors[ImGuiCol_Tab] = ImVec4(0.26f, 0.26f, 0.26f, 0.40f);
colors[ImGuiCol_TabHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_TabActive] = ImVec4(0.28f, 0.28f, 0.28f, 1.00f);
colors[ImGuiCol_TabUnfocused] = ImVec4(0.17f, 0.17f, 0.17f, 1.00f);
colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.26f, 0.26f, 0.26f, 1.00f);
colors[ImGuiCol_DockingPreview] = ImVec4(0.55f, 0.55f, 0.55f, 1.00f);
colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.78f, 0.88f, 1.00f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.44f, 0.44f, 0.44f, 0.35f);
ImGuiSettingsHandler handler;
handler.TypeName = "Project";
handler.TypeHash = ImHashStr(handler.TypeName, 0, 0);
handler.ReadOpenFn = [](ImGuiContext* context, ImGuiSettingsHandler* handler, const char* name) -> void*
{
return (void*) name;
};
handler.ReadLineFn = [](ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
auto* systemUI = ui::GetSystemUI();
auto* editor = systemUI->GetSubsystem<Editor>();
const char* name = static_cast<const char*>(entry);
if (strcmp(name, "Window") == 0)
editor->CreateDefaultTabs();
else
{
Tab* tab = editor->GetTabByName(name);
if (tab == nullptr)
{
StringVector parts = ea::string(name).split('#');
tab = editor->CreateTab(parts.front());
}
tab->OnLoadUISettings(name, line);
}
};
handler.WriteAllFn = [](ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
auto* systemUI = ui::GetSystemUI();
auto* editor = systemUI->GetSubsystem<Editor>();
buf->appendf("[Project][Window]\n");
// Save tabs
for (auto& tab : editor->GetContentTabs())
tab->OnSaveUISettings(buf);
};
ui::GetCurrentContext()->SettingsHandlers.push_back(handler);
}
void Editor::UpdateWindowTitle(const ea::string& resourcePath)
{
if (context_->GetEngine()->IsHeadless())
return;
auto* project = GetSubsystem<Project>();
ea::string title;
if (project == nullptr)
title = "Editor";
else
{
ea::string projectName = GetFileName(RemoveTrailingSlash(project->GetProjectPath()));
title = ToString("Editor | %s", projectName.c_str());
if (!resourcePath.empty())
title += ToString(" | %s", GetFileName(resourcePath).c_str());
}
context_->GetGraphics()->SetWindowTitle(title);
}
template<typename T>
void Editor::RegisterSubcommand()
{
T::RegisterObject(context_);
SharedPtr<T> cmd(context_->CreateObject<T>());
subCommands_.push_back(DynamicCast<SubCommand>(cmd));
if (CLI::App* subCommand = GetCommandLineParser().add_subcommand(T::GetTypeNameStatic().c_str()))
cmd->RegisterCommandLine(*subCommand);
else
URHO3D_LOGERROR("Sub-command '{}' was not registered due to user error.", T::GetTypeNameStatic());
}
void Editor::OpenOrCreateProject()
{
nfdchar_t* projectDir = nullptr;
if (NFD_PickFolder("", &projectDir) == NFD_OKAY)
{
OpenProject(projectDir);
NFD_FreePath(projectDir);
}
}
#if URHO3D_STATIC && URHO3D_PLUGINS
bool Editor::RegisterPlugin(PluginApplication* plugin)
{
return project_->GetPlugins()->RegisterPlugin(plugin);
}
#endif
void Editor::OnConsoleUriClick(VariantMap& args)
{
using namespace ConsoleUriClick;
if (ui::IsMouseClicked(MOUSEB_LEFT))
{
const ea::string& protocol = args[P_PROTOCOL].GetString();
const ea::string& address = args[P_ADDRESS].GetString();
if (protocol == "res")
context_->GetFileSystem()->SystemOpen(context_->GetCache()->GetResourceFileName(address));
}
}
void Editor::OnSelectionChanged(StringHash, VariantMap& args)
{
using namespace EditorSelectionChanged;
auto tab = static_cast<Tab*>(args[P_TAB].GetPtr());
auto undo = GetSubsystem<UndoStack>();
ByteVector newSelection = tab->SerializeSelection();
if (tab == selectionTab_)
{
if (newSelection == selectionBuffer_)
return;
}
else
{
if (!selectionTab_.Expired())
selectionTab_->ClearSelection();
}
undo->Add<UndoSetSelection>(selectionTab_, selectionBuffer_, tab, newSelection);
selectionTab_ = tab;
selectionBuffer_ = newSelection;
}
}
| 37.656284 | 152 | 0.631325 | tatjam |
9c9aea0af0fc323928b9b900169e7839ac20ee13 | 34 | hpp | C++ | NamedPipes/src/Config.hpp | TDToolbox/btdapi | b8349ef33d5bc2dacc85e96ced86dc37e972e8ee | [
"MIT"
] | null | null | null | NamedPipes/src/Config.hpp | TDToolbox/btdapi | b8349ef33d5bc2dacc85e96ced86dc37e972e8ee | [
"MIT"
] | 8 | 2020-03-10T23:11:09.000Z | 2020-03-14T01:19:32.000Z | NamedPipes/src/Config.hpp | TDToolbox/btdapi | b8349ef33d5bc2dacc85e96ced86dc37e972e8ee | [
"MIT"
] | null | null | null | #pragma once
#define PIPE_LOGGING | 11.333333 | 20 | 0.823529 | TDToolbox |
9c9e6fae539b7a36045dfb2e1a46ba04630bdc5c | 20,900 | cpp | C++ | planet.cpp | CobaltXII/planet | 4b22ecd4df38a971debeb2714001a6450cebf181 | [
"MIT"
] | 10 | 2019-01-13T00:21:41.000Z | 2021-06-23T20:11:12.000Z | planet.cpp | CobaltXII/planet | 4b22ecd4df38a971debeb2714001a6450cebf181 | [
"MIT"
] | null | null | null | planet.cpp | CobaltXII/planet | 4b22ecd4df38a971debeb2714001a6450cebf181 | [
"MIT"
] | 2 | 2020-07-31T22:09:04.000Z | 2020-08-11T02:33:46.000Z | /*
GLM header include directives. Please use GLM 0.9.9.3 or greater for known
results. Previous versions of GLM are not guaranteed to work correctly.
*/
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
/*
libnoise header include directives. libnoise is used to generate coherent
noise for generating procedural planets.
*/
#include <noise/noise.h>
/*
noiseutils header include directives. noiseutils is used as a utility library
on top of libnoise.
*/
#include "noiseutils.h"
/*
GLAD header include directives. GLAD is used to load OpenGL 3.3 Core
functions.
*/
#include "glad.h"
/*
SDL header include directives. Please use SDL 2.0.9 or greater for known
results. Previous versions of SDL are not guaranteed to work correctly.
*/
#include <SDL2/SDL.h>
/*
Standard header include directives.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <tuple>
/*
A std::tuple<int, int, int> is used to represent a triangle defined by indices
in a list of vertices.
*/
typedef std::tuple<int, int, int> triangle_indices;
/*
Add a vertex to a std::vector<glm::vec3> while ensuring that the vertex lies
on the unit sphere.
*/
int add_vertex(std::vector<glm::vec3>& vector, glm::vec3 vertex)
{
vector.push_back(vertex / glm::length(vertex));
return vector.size() - 1;
}
/*
Return the index of a vertex in the middle of p_1 and p_2.
*/
int get_middle_point(std::vector<glm::vec3>& vector, int p_1, int p_2)
{
glm::vec3 pt_1 = vector[p_1];
glm::vec3 pt_2 = vector[p_2];
glm::vec3 pt_middle = (pt_1 + pt_2) / 2.0f;
int i = add_vertex(vector, pt_middle);
return i;
}
/*
Create an icosphere with the given amount of subdivisions.
*/
std::vector<glm::vec3> create_icosphere(int subdivisions = 8)
{
// Generate the icosphere's vertices.
std::vector<glm::vec3> icosphere_vertices;
// Generate the 12 vertices of an icosahedron.
float t = (1.0f + sqrt(5.0f)) / 2.0f;
add_vertex(icosphere_vertices, glm::vec3(-1.0f, t, 0.0f));
add_vertex(icosphere_vertices, glm::vec3( 1.0f, t, 0.0f));
add_vertex(icosphere_vertices, glm::vec3(-1.0f, -t, 0.0f));
add_vertex(icosphere_vertices, glm::vec3( 1.0f, -t, 0.0f));
add_vertex(icosphere_vertices, glm::vec3(0.0f, -1.0f, t));
add_vertex(icosphere_vertices, glm::vec3(0.0f, 1.0f, t));
add_vertex(icosphere_vertices, glm::vec3(0.0f, -1.0f, -t));
add_vertex(icosphere_vertices, glm::vec3(0.0f, 1.0f, -t));
add_vertex(icosphere_vertices, glm::vec3( t, 0.0f, -1.0f));
add_vertex(icosphere_vertices, glm::vec3( t, 0.0f, 1.0f));
add_vertex(icosphere_vertices, glm::vec3(-t, 0.0f, -1.0f));
add_vertex(icosphere_vertices, glm::vec3(-t, 0.0f, 1.0f));
// Generate the 20 faces of an icosahedron.
std::vector<triangle_indices> icosphere_indices;
icosphere_indices.push_back(triangle_indices(0x0, 0xB, 0x5));
icosphere_indices.push_back(triangle_indices(0x0, 0x5, 0x1));
icosphere_indices.push_back(triangle_indices(0x0, 0x1, 0x7));
icosphere_indices.push_back(triangle_indices(0x0, 0x7, 0xA));
icosphere_indices.push_back(triangle_indices(0x0, 0xA, 0xB));
icosphere_indices.push_back(triangle_indices(0x1, 0x5, 0x9));
icosphere_indices.push_back(triangle_indices(0x5, 0xB, 0x4));
icosphere_indices.push_back(triangle_indices(0xB, 0xA, 0x2));
icosphere_indices.push_back(triangle_indices(0xA, 0x7, 0x6));
icosphere_indices.push_back(triangle_indices(0x7, 0x1, 0x8));
icosphere_indices.push_back(triangle_indices(0x3, 0x9, 0x4));
icosphere_indices.push_back(triangle_indices(0x3, 0x4, 0x2));
icosphere_indices.push_back(triangle_indices(0x3, 0x2, 0x6));
icosphere_indices.push_back(triangle_indices(0x3, 0x6, 0x8));
icosphere_indices.push_back(triangle_indices(0x3, 0x8, 0x9));
icosphere_indices.push_back(triangle_indices(0x4, 0x9, 0x5));
icosphere_indices.push_back(triangle_indices(0x2, 0x4, 0xB));
icosphere_indices.push_back(triangle_indices(0x6, 0x2, 0xA));
icosphere_indices.push_back(triangle_indices(0x8, 0x6, 0x7));
icosphere_indices.push_back(triangle_indices(0x9, 0x8, 0x1));
// Subdivide the icosphere.
for (int i = 0; i < subdivisions; i++)
{
// Generate a temporary mesh to hold the result of the next
// subdivision.
std::vector<triangle_indices> new_icosphere_indices;
// Subdivide each triangle in the current mesh.
for (int j = 0; j < icosphere_indices.size(); j++)
{
triangle_indices tri = icosphere_indices[j];
int a = get_middle_point(icosphere_vertices, std::get<0>(tri), std::get<1>(tri));
int b = get_middle_point(icosphere_vertices, std::get<1>(tri), std::get<2>(tri));
int c = get_middle_point(icosphere_vertices, std::get<2>(tri), std::get<0>(tri));
// Add the 4 new triangles to the temporary mesh.
new_icosphere_indices.push_back(triangle_indices(std::get<0>(tri), a, c));
new_icosphere_indices.push_back(triangle_indices(std::get<1>(tri), b, a));
new_icosphere_indices.push_back(triangle_indices(std::get<2>(tri), c, b));
new_icosphere_indices.push_back(triangle_indices(a, b, c));
}
// Replace the current mesh with the temporary mesh.
icosphere_indices = new_icosphere_indices;
}
// Convert the icosphere's structured triangle_indices vector to a list of
// ordered vertices.
std::vector<glm::vec3> icosphere_mesh;
for (int i = 0; i < icosphere_indices.size(); i++)
{
icosphere_mesh.push_back(icosphere_vertices[std::get<0>(icosphere_indices[i])]);
icosphere_mesh.push_back(icosphere_vertices[std::get<1>(icosphere_indices[i])]);
icosphere_mesh.push_back(icosphere_vertices[std::get<2>(icosphere_indices[i])]);
}
// Return the icosphere's mesh.
return icosphere_mesh;
};
/*
Load a shader program from two files.
*/
GLuint load_shader_program
(
std::string shader_path_0,
std::string shader_path_1,
GLenum shader_type_0,
GLenum shader_type_1
)
{
// Open shader_path_0 and shader_path_1 as input file streams.
std::ifstream shader_file_0(shader_path_0);
std::ifstream shader_file_1(shader_path_1);
if (!shader_file_0.is_open())
{
std::cout << "Could not open file \"" << shader_path_0 << "\"." << std::endl;
exit(EXIT_FAILURE);
}
else if (!shader_file_1.is_open())
{
std::cout << "Could not open file \"" << shader_path_1 << "\"." << std::endl;
exit(EXIT_FAILURE);
}
// Load the text context of shader_path_0 and shader_path_1 into
// shader_buffer_0 and shader_buffer_1.
std::stringstream shader_buffer_0;
std::stringstream shader_buffer_1;
shader_buffer_0 << shader_file_0.rdbuf() << "\0";
shader_buffer_1 << shader_file_1.rdbuf() << "\0";
// Convert shader_buffer_0 and shader_buffer_1 from std::stringstream to
// std::string, and then to const GLchar* (const char*).
std::string shader_text_0 = shader_buffer_0.str();
std::string shader_text_1 = shader_buffer_1.str();
const GLchar* shader_data_0 = shader_text_0.c_str();
const GLchar* shader_data_1 = shader_text_1.c_str();
// Create shader_0 and shader_1 with the types shader_type_0 and
// shader_type_1, then source them with shader_data_0 and shader_data_1.
GLuint shader_0 = glCreateShader(shader_type_0);
GLuint shader_1 = glCreateShader(shader_type_1);
glShaderSource(shader_0, 1, &shader_data_0, NULL);
glShaderSource(shader_1, 1, &shader_data_1, NULL);
// Compile shader_0 and shader_1.
glCompileShader(shader_0);
glCompileShader(shader_1);
// Check if shader_0 or shader_1 failed compilation. If so, print out the
// error message provided by OpenGL.
GLint success_0 = 0;
GLint success_1 = 0;
GLchar crash_information_0[16 * 1024];
GLchar crash_information_1[16 * 1024];
glGetShaderiv(shader_0, GL_COMPILE_STATUS, &success_0);
glGetShaderiv(shader_1, GL_COMPILE_STATUS, &success_1);
if (!success_0)
{
std::cout << "Could not compile shader loaded from \"" << shader_path_0 << "\"." << std::endl;
glGetShaderInfoLog(shader_0, 16 * 1024, NULL, crash_information_0);
std::cout << crash_information_0;
exit(EXIT_FAILURE);
}
else if (!success_1)
{
std::cout << "Could not compile shader loaded from \"" << shader_path_1 << "\"." << std::endl;
glGetShaderInfoLog(shader_1, 16 * 1024, NULL, crash_information_1);
std::cout << crash_information_1;
exit(EXIT_FAILURE);
}
// Create an empty shader program.
GLuint shader_program = glCreateProgram();
// Attach shader_0 and shader_1 to shader_program, and then link
// shader_program.
glAttachShader(shader_program, shader_0);
glAttachShader(shader_program, shader_1);
glLinkProgram(shader_program);
// Check if shader_program failed linkage. If so, print out the error
// message provied by OpenGL.
GLint success_program = 0;
glGetProgramiv(shader_program, GL_LINK_STATUS, &success_program);
if (!success_program)
{
std::cout << "Could not link shader program loaded from \"" << shader_path_0 << "\" and \"" << shader_path_1 << "\"." << std::endl;
GLchar crash_information_program[16 * 1024];
glGetProgramInfoLog(shader_program, 16 * 1024, NULL, crash_information_program);
std::cout << crash_information_program;
exit(EXIT_FAILURE);
}
// Delete shader_0 and shader_1, then return shader_program.
glDeleteShader(shader_0);
glDeleteShader(shader_1);
return shader_program;
}
/*
Entry point.
*/
int main(int argc, char** argv)
{
// Initialize SDL.
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cout << "Could not initialize SDL." << std::endl;
return EXIT_FAILURE;
}
// Create a SDL_Window*.
int sdl_x_res = 960;
int sdl_y_res = 960;
SDL_Window* sdl_window = SDL_CreateWindow
(
"SDL 2.0 with OpenGL 3.3 Core",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
sdl_x_res,
sdl_y_res,
SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL
);
// Make sure the SDL_Window* was created successfully.
if (!sdl_window)
{
std::cout << "Could not create a SDL_Window*." << std::endl;
return EXIT_FAILURE;
}
// Request OpenGL 3.3 Core.
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// Create a SDL_GLContext.
SDL_GLContext gl_context = SDL_GL_CreateContext(sdl_window);
// Make sure the SDL_GLContext was created successfully.
if (!gl_context)
{
std::cout << "Could not create a SDL_GLContext." << std::endl;
return EXIT_FAILURE;
}
// Load all OpenGL 3.3 Core functions using GLAD.
if (!gladLoadGLLoader(SDL_GL_GetProcAddress))
{
std::cout << "Could not load OpenGL 3.3 Core functions using GLAD." << std::endl;
return EXIT_FAILURE;
}
// Make sure the OpenGL version that was loaded by GLAD is greater than or
// equal to OpenGL 3.3.
if (GLVersion.major * 10 + GLVersion.minor < 33)
{
std::cout << "Could not load OpenGL 3.3 Core functions using GLAD." << std::endl;
return EXIT_FAILURE;
}
// Create and initialize a noise::module::Perlin. This noise module will
// dictate the general shape of the islands on the planet.
noise::module::Perlin noise_1;
{
// Set the seed to the current time, so that the output noise will be
// slightly different every time.
noise_1.SetSeed(time(NULL));
// Set the octave count to 16 for a high level of detail.
noise_1.SetOctaveCount(16);
// Set the frequency to 2.0f to make the noise more random and less
// coherent.
noise_1.SetFrequency(2.0f);
}
// Create and initialize a noise::module::RidgedMulti. This noise module
// will create round basins and sharp mountain ranges.
noise::module::RidgedMulti noise_2;
{
// Set the seed to the current time, so that the output noise will be
// slightly different every time.
noise_2.SetSeed(time(NULL));
// Set the octave count to 16 for a high level of detail.
noise_2.SetOctaveCount(16);
// Set the frequency to 2.0f to make the noise more random and less
// coherent.
noise_2.SetFrequency(1.0f);
}
// Create a gradient to define the color of points on the planet based on
// the point's elevation.
noise::utils::GradientColor color_map;
color_map.Clear();
color_map.AddGradientPoint(0.0f - 1.0000f, noise::utils::Color(0x00, 0x00, 0x80, 0xFF));
color_map.AddGradientPoint(0.0f - 0.2500f, noise::utils::Color(0x00, 0x00, 0xFF, 0xFF));
color_map.AddGradientPoint(0.0f + 0.0000f, noise::utils::Color(0x00, 0x80, 0xFF, 0xFF));
color_map.AddGradientPoint(0.0f + 0.0625f, noise::utils::Color(0xF0, 0xF0, 0x40, 0xFF));
color_map.AddGradientPoint(0.0f + 0.1250f, noise::utils::Color(0x20, 0xA0, 0x00, 0xFF));
color_map.AddGradientPoint(0.0f + 0.3750f, noise::utils::Color(0xE0, 0xE0, 0x00, 0xFF));
color_map.AddGradientPoint(0.0f + 0.7500f, noise::utils::Color(0x80, 0x80, 0x80, 0xFF));
color_map.AddGradientPoint(0.0f + 1.0000f, noise::utils::Color(0xFF, 0xFF, 0xFF, 0xFF));
// Generate the base icosphere.
std::vector<glm::vec3> icosphere_managed_vertices = create_icosphere(8);
// Allocate space to hold the vertex data of the icosphere.
float* icosphere_vertices = (float*)malloc(icosphere_managed_vertices.size() * (9 * sizeof(float)));
// Perturb the terrain using the noise modules by iterating through each
// triangle rather than each vertex. This is done to make it easy to
// calculate triangle normals.
for (int i = 0; i < icosphere_managed_vertices.size(); i += 3)
{
// Create an array to hold the noise values at the three vertices of
// the current triangle.
float noise_map[3];
for (int j = 0; j < 3; j++)
{
// Get the current vertex.
glm::vec3 vertex = icosphere_managed_vertices[i + j];
// Get the noise value at the current vertex.
float actual_noise_value = noise_1.GetValue(vertex.x, vertex.y, vertex.z) * (noise_2.GetValue(vertex.x, vertex.y, vertex.z) + 0.2f);
// Clamp the noise value to create smooth, flat water.
float noise_value = std::max(0.0f, actual_noise_value);
noise_map[j] = actual_noise_value;
// Perturb the current vertex by the noise value.
icosphere_managed_vertices[i + j] = vertex * (1.0f + noise_value * 0.075f);
}
// Calculate the triangle's normal.
glm::vec3 edge_1 = icosphere_managed_vertices[i + 1] - icosphere_managed_vertices[i];
glm::vec3 edge_2 = icosphere_managed_vertices[i + 2] - icosphere_managed_vertices[i];
glm::vec3 normal = glm::normalize(glm::cross(edge_1, edge_2));
float nx = normal.x;
float ny = normal.y;
float nz = normal.z;
// Generate the vertex data.
for (int j = 0; j < 3; j++)
{
utils::Color color = color_map.GetColor(noise_map[j]);
// Write the position of the current vertex.
icosphere_vertices[(i + j) * 9 + 0] = icosphere_managed_vertices[i + j].x;
icosphere_vertices[(i + j) * 9 + 1] = icosphere_managed_vertices[i + j].y;
icosphere_vertices[(i + j) * 9 + 2] = icosphere_managed_vertices[i + j].z;
// Write the color of the current vertex.
icosphere_vertices[(i + j) * 9 + 3] = color.red / 255.0f;
icosphere_vertices[(i + j) * 9 + 4] = color.green / 255.0f;
icosphere_vertices[(i + j) * 9 + 5] = color.blue / 255.0f;
// Write the surface normal of the current vertex.
icosphere_vertices[(i + j) * 9 + 6] = nx;
icosphere_vertices[(i + j) * 9 + 7] = ny;
icosphere_vertices[(i + j) * 9 + 8] = nz;
}
}
// Generate a VAO and a VBO for the icosphere.
GLuint icosphere_vao;
GLuint icosphere_vbo;
glGenVertexArrays(1, &icosphere_vao);
glGenBuffers(1, &icosphere_vbo);
// Bind the VAO and the VBO of the icosphere to the current state.
glBindVertexArray(icosphere_vao);
glBindBuffer(GL_ARRAY_BUFFER, icosphere_vbo);
// Upload the icosphere data to the VBO.
glBufferData(GL_ARRAY_BUFFER, icosphere_managed_vertices.size() * (10 * sizeof(float)), icosphere_vertices, GL_STATIC_DRAW);
// Enable the required vertex attribute pointers.
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(0 * sizeof(float)));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(3 * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
// Unbind the VAO and the VBO of the icosphere from the current state.
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Load the default shader program.
GLuint default_shader_program = load_shader_program("default_vertex.glsl", "default_fragment.glsl", GL_VERTEX_SHADER, GL_FRAGMENT_SHADER);
// Define variables to hold the state of the mouse and the application's
// state.
int sdl_mouse_x = 0;
int sdl_mouse_y = 0;
bool sdl_mouse_l = false;
bool sdl_mouse_r = false;
bool sdl_running = true;
// Enter the main loop.
while (sdl_running)
{
// Refresh the window's size.
SDL_GetWindowSize(sdl_window, &sdl_x_res, &sdl_y_res);
// Poll and handle events.
SDL_Event e;
while (SDL_PollEvent(&e))
{
if (e.type == SDL_QUIT)
{
// The application was quit.
sdl_running = false;
}
else if (e.type == SDL_MOUSEMOTION)
{
// The mouse moved.
sdl_mouse_x = e.motion.x;
sdl_mouse_y = e.motion.y;
}
else if (e.type == SDL_MOUSEBUTTONDOWN)
{
// A mouse button was pressed.
if (e.button.button == SDL_BUTTON_LEFT)
{
sdl_mouse_l = true;
}
else if (e.button.button == SDL_BUTTON_RIGHT)
{
sdl_mouse_r = true;
}
}
else if (e.type == SDL_MOUSEBUTTONUP)
{
// A mouse button was released.
if (e.button.button == SDL_BUTTON_LEFT)
{
sdl_mouse_l = false;
}
else if (e.button.button == SDL_BUTTON_RIGHT)
{
sdl_mouse_r = false;
}
}
else if (e.type == SDL_KEYDOWN)
{
// A key was pressed.
SDL_Keycode key = e.key.keysym.sym;
if (key == SDLK_ESCAPE)
{
// Quit the application.
sdl_running = false;
}
}
}
// Clear the screen to black.
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
{
// Enable the default shader program.
glUseProgram(default_shader_program);
// Enable depth testing.
glEnable(GL_DEPTH_TEST);
// Enable backface culling.
glEnable(GL_CULL_FACE);
{
// Calculate the aspect ratio.
float aspect_ratio = (float)sdl_x_res / (float)sdl_y_res;
// Calculate the projection matrix.
glm::mat4 matrix_projection = glm::perspective(glm::radians(70.0f), aspect_ratio, 0.128f, 1024.0f);
// Calculate the view matrix.
glm::mat4 matrix_view = glm::mat4(1.0f);
// Rotate the view matrix.
matrix_view = glm::rotate(matrix_view, glm::radians(0.0f), glm::vec3(1.0f, 0.0f, 0.0f));
matrix_view = glm::rotate(matrix_view, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
// Calculate the model matrix.
glm::mat4 matrix_model = glm::mat4(1.0f);
// Translate the model matrix.
matrix_model = glm::translate(matrix_model, glm::vec3(0.0f, 0.0f, 0.2f * -10.0f));
// Rotate the model matrix.
matrix_model = glm::rotate(matrix_model, glm::radians(SDL_GetTicks() / 100.0f), glm::vec3(1.0f, 0.0f, 0.0f));
matrix_model = glm::rotate(matrix_model, glm::radians(SDL_GetTicks() / 100.0f), glm::vec3(0.0f, 1.0f, 0.0f));
// Pass matrix_projection, matrix_view and matrix_model to the
// default_shader_program.
glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_projection"), 1, GL_FALSE, &matrix_projection[0][0]);
glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_view"), 1, GL_FALSE, &matrix_view[0][0]);
glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_model"), 1, GL_FALSE, &matrix_model[0][0]);
}
// Bind the icosphere VAO to the current state.
glBindVertexArray(icosphere_vao);
// Set the polygon mode to render wireframes.
if (false)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
// Draw the icosphere VAO as an array of triangles.
glDrawArrays(GL_TRIANGLES, 0, icosphere_managed_vertices.size());
// Unbind the icosphere VAO from the current state.
glBindVertexArray(0);
// Disable backface culling.
glDisable(GL_CULL_FACE);
// Disable depth testing.
glDisable(GL_DEPTH_TEST);
// Disable the default shader program.
glUseProgram(0);
}
// Swap the sdl_window's current buffer to display the contents of the
// back buffer to the screen.
SDL_GL_SwapWindow(sdl_window);
}
// Free the icosphere's vertices.
free(icosphere_vertices);
// Destroy the default shader program.
glDeleteProgram(default_shader_program);
// Destroy all SDL_GL resources.
SDL_GL_DeleteContext(gl_context);
// Destroy all SDL resources.
SDL_DestroyWindow(sdl_window);
// Quit SDL.
SDL_Quit();
// Exit successfully.
return EXIT_SUCCESS;
} | 25.770654 | 139 | 0.70933 | CobaltXII |
9ca0a6fba5e0922b0bc99853009fee24bf8c7ed2 | 19,548 | cpp | C++ | samples/sample_encode/src/pipeline_user.cpp | me176c-dev/MediaSDK | 0c7f315958b78c98c5c06bd60565eb8c1ad15d41 | [
"MIT"
] | null | null | null | samples/sample_encode/src/pipeline_user.cpp | me176c-dev/MediaSDK | 0c7f315958b78c98c5c06bd60565eb8c1ad15d41 | [
"MIT"
] | null | null | null | samples/sample_encode/src/pipeline_user.cpp | me176c-dev/MediaSDK | 0c7f315958b78c98c5c06bd60565eb8c1ad15d41 | [
"MIT"
] | null | null | null | /******************************************************************************\
Copyright (c) 2005-2019, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This sample was distributed or derived from the Intel's Media Samples package.
The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio
or https://software.intel.com/en-us/media-client-solutions-support.
\**********************************************************************************/
#include "mfx_samples_config.h"
#include "pipeline_user.h"
#include "sysmem_allocator.h"
#ifndef MFX_VERSION
#error MFX_VERSION not defined
#endif
mfxStatus CUserPipeline::InitRotateParam(sInputParams *pInParams)
{
MSDK_CHECK_POINTER(pInParams, MFX_ERR_NULL_PTR);
MSDK_ZERO_MEMORY(m_pluginVideoParams);
m_pluginVideoParams.AsyncDepth = pInParams->nAsyncDepth; // the maximum number of tasks that can be submitted before any task execution finishes
m_pluginVideoParams.vpp.In.FourCC = MFX_FOURCC_NV12;
m_pluginVideoParams.vpp.In.Width = m_pluginVideoParams.vpp.In.CropW = pInParams->nWidth;
m_pluginVideoParams.vpp.In.Height = m_pluginVideoParams.vpp.In.CropH = pInParams->nHeight;
m_pluginVideoParams.vpp.Out.FourCC = MFX_FOURCC_NV12;
m_pluginVideoParams.vpp.Out.Width = m_pluginVideoParams.vpp.Out.CropW = pInParams->nWidth;
m_pluginVideoParams.vpp.Out.Height = m_pluginVideoParams.vpp.Out.CropH = pInParams->nHeight;
if (pInParams->memType != SYSTEM_MEMORY)
m_pluginVideoParams.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY;
m_RotateParams.Angle = pInParams->nRotationAngle;
return MFX_ERR_NONE;
}
mfxStatus CUserPipeline::AllocFrames()
{
MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED);
mfxStatus sts = MFX_ERR_NONE;
mfxFrameAllocRequest EncRequest, RotateRequest;
mfxU16 nEncSurfNum = 0; // number of frames at encoder input (rotate output)
mfxU16 nRotateSurfNum = 0; // number of frames at rotate input
MSDK_ZERO_MEMORY(EncRequest);
sts = m_pmfxENC->QueryIOSurf(&m_mfxEncParams, &EncRequest);
MSDK_CHECK_STATUS(sts, "m_pmfxENC->QueryIOSurf failed");
if (EncRequest.NumFrameSuggested < m_mfxEncParams.AsyncDepth)
return MFX_ERR_MEMORY_ALLOC;
nEncSurfNum = EncRequest.NumFrameSuggested;
// The number of surfaces for plugin input - so that plugin can work at async depth = m_nAsyncDepth
nRotateSurfNum = MSDK_MAX(m_mfxEncParams.AsyncDepth, m_nMemBuffer);
// If surfaces are shared by 2 components, c1 and c2. NumSurf = c1_out + c2_in - AsyncDepth + 1
nEncSurfNum += nRotateSurfNum - m_mfxEncParams.AsyncDepth + 1;
// prepare allocation requests
EncRequest.NumFrameSuggested = EncRequest.NumFrameMin = nEncSurfNum;
RotateRequest.NumFrameSuggested = RotateRequest.NumFrameMin = nRotateSurfNum;
mfxU16 mem_type = MFX_MEMTYPE_EXTERNAL_FRAME;
mem_type |= (SYSTEM_MEMORY == m_memType) ?
(mfxU16)MFX_MEMTYPE_SYSTEM_MEMORY
:(mfxU16)MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET;
EncRequest.Type = RotateRequest.Type = mem_type;
EncRequest.Type |= MFX_MEMTYPE_FROM_ENCODE;
RotateRequest.Type |= MFX_MEMTYPE_FROM_VPPOUT; // THIS IS A WORKAROUND, NEED TO ADJUST ALLOCATOR
MSDK_MEMCPY_VAR(EncRequest.Info, &(m_mfxEncParams.mfx.FrameInfo), sizeof(mfxFrameInfo));
MSDK_MEMCPY_VAR(RotateRequest.Info, &(m_pluginVideoParams.vpp.In), sizeof(mfxFrameInfo));
// alloc frames for encoder input
sts = m_pMFXAllocator->Alloc(m_pMFXAllocator->pthis, &EncRequest, &m_EncResponse);
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Alloc failed");
// alloc frames for rotate input
sts = m_pMFXAllocator->Alloc(m_pMFXAllocator->pthis, &(RotateRequest), &m_PluginResponse);
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Alloc failed");
// prepare mfxFrameSurface1 array for components
m_pEncSurfaces = new mfxFrameSurface1 [nEncSurfNum];
MSDK_CHECK_POINTER(m_pEncSurfaces, MFX_ERR_MEMORY_ALLOC);
m_pPluginSurfaces = new mfxFrameSurface1 [nRotateSurfNum];
MSDK_CHECK_POINTER(m_pPluginSurfaces, MFX_ERR_MEMORY_ALLOC);
for (int i = 0; i < nEncSurfNum; i++)
{
MSDK_ZERO_MEMORY(m_pEncSurfaces[i]);
MSDK_MEMCPY_VAR(m_pEncSurfaces[i].Info, &(m_mfxEncParams.mfx.FrameInfo), sizeof(mfxFrameInfo));
if (SYSTEM_MEMORY != m_memType)
{
// external allocator used - provide just MemIds
m_pEncSurfaces[i].Data.MemId = m_EncResponse.mids[i];
}
else
{
sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, m_EncResponse.mids[i], &(m_pEncSurfaces[i].Data));
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed");
}
}
for (int i = 0; i < nRotateSurfNum; i++)
{
MSDK_ZERO_MEMORY(m_pPluginSurfaces[i]);
MSDK_MEMCPY_VAR(m_pPluginSurfaces[i].Info, &(m_pluginVideoParams.vpp.In), sizeof(mfxFrameInfo));
if (SYSTEM_MEMORY != m_memType)
{
// external allocator used - provide just MemIds
m_pPluginSurfaces[i].Data.MemId = m_PluginResponse.mids[i];
}
else
{
sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, m_PluginResponse.mids[i], &(m_pPluginSurfaces[i].Data));
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed");
}
}
return MFX_ERR_NONE;
}
void CUserPipeline::DeleteFrames()
{
MSDK_SAFE_DELETE_ARRAY(m_pPluginSurfaces);
CEncodingPipeline::DeleteFrames();
}
CUserPipeline::CUserPipeline() : CEncodingPipeline()
{
m_pPluginSurfaces = NULL;
m_PluginModule = NULL;
m_pusrPlugin = NULL;
MSDK_ZERO_MEMORY(m_PluginResponse);
MSDK_ZERO_MEMORY(m_pluginVideoParams);
MSDK_ZERO_MEMORY(m_RotateParams);
m_MVCflags = MVC_DISABLED;
}
CUserPipeline::~CUserPipeline()
{
Close();
}
mfxStatus CUserPipeline::Init(sInputParams *pParams)
{
MSDK_CHECK_POINTER(pParams, MFX_ERR_NULL_PTR);
mfxStatus sts = MFX_ERR_NONE;
m_PluginModule = msdk_so_load(pParams->strPluginDLLPath);
MSDK_CHECK_POINTER(m_PluginModule, MFX_ERR_NOT_FOUND);
PluginModuleTemplate::fncCreateGenericPlugin pCreateFunc = (PluginModuleTemplate::fncCreateGenericPlugin)msdk_so_get_addr(m_PluginModule, "mfxCreateGenericPlugin");
MSDK_CHECK_POINTER(pCreateFunc, MFX_ERR_NOT_FOUND);
m_pusrPlugin = (*pCreateFunc)();
MSDK_CHECK_POINTER(m_pusrPlugin, MFX_ERR_NOT_FOUND);
// prepare input file reader
sts = m_FileReader.Init(pParams->InputFiles,
pParams->FileInputFourCC );
MSDK_CHECK_STATUS(sts, "m_FileReader.Init failed");
// set memory type
m_memType = pParams->memType;
m_nMemBuffer = pParams->nMemBuf;
m_nTimeout = pParams->nTimeout;
m_bCutOutput = !pParams->bUncut;
// prepare output file writer
sts = InitFileWriters(pParams);
MSDK_CHECK_STATUS(sts, "InitFileWriters failed");
mfxIMPL impl = pParams->bUseHWLib ? MFX_IMPL_HARDWARE : MFX_IMPL_SOFTWARE;
// if d3d11 surfaces are used ask the library to run acceleration through D3D11
// feature may be unsupported due to OS or MSDK API version
if (D3D11_MEMORY == pParams->memType)
impl |= MFX_IMPL_VIA_D3D11;
mfxVersion min_version;
mfxVersion version; // real API version with which library is initialized
// we set version to 1.0 and later we will query actual version of the library which will got leaded
min_version.Major = 1;
min_version.Minor = 0;
// create a session for the second vpp and encode
sts = m_mfxSession.Init(impl, &min_version);
MSDK_CHECK_STATUS(sts, "m_mfxSession.Init failed");
sts = MFXQueryVersion(m_mfxSession , &version); // get real API version of the loaded library
MSDK_CHECK_STATUS(sts, "MFXQueryVersion failed");
if (CheckVersion(&version, MSDK_FEATURE_PLUGIN_API)) {
// we check if codec is distributed as a mediasdk plugin and load it if yes
// else if codec is not in the list of mediasdk plugins, we assume, that it is supported inside mediasdk library
// in case of HW library (-hw key) we will firstly try to load HW plugin
// in case of failure - we will try SW one
mfxIMPL impl2 = pParams->bUseHWLib ? MFX_IMPL_HARDWARE : MFX_IMPL_SOFTWARE;
if (AreGuidsEqual(MSDK_PLUGINGUID_NULL,pParams->pluginParams.pluginGuid))
{
pParams->pluginParams.pluginGuid = msdkGetPluginUID(impl2, MSDK_VENCODE, pParams->CodecId);
}
if (AreGuidsEqual(pParams->pluginParams.pluginGuid, MSDK_PLUGINGUID_NULL) && impl2 == MFX_IMPL_HARDWARE)
pParams->pluginParams.pluginGuid = msdkGetPluginUID(MFX_IMPL_SOFTWARE, MSDK_VENCODE, pParams->CodecId);
if (!AreGuidsEqual(pParams->pluginParams.pluginGuid, MSDK_PLUGINGUID_NULL))
{
m_pPlugin.reset(LoadPlugin(MFX_PLUGINTYPE_VIDEO_ENCODE, m_mfxSession, pParams->pluginParams.pluginGuid, 1));
if (m_pPlugin.get() == NULL) sts = MFX_ERR_UNSUPPORTED;
}
}
// create encoder
m_pmfxENC = new MFXVideoENCODE(m_mfxSession);
MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_MEMORY_ALLOC);
sts = InitMfxEncParams(pParams);
MSDK_CHECK_STATUS(sts, "InitMfxEncParams failed");
sts = InitRotateParam(pParams);
MSDK_CHECK_STATUS(sts, "InitRotateParam failed");
// create and init frame allocator
sts = CreateAllocator();
MSDK_CHECK_STATUS(sts, "CreateAllocator failed");
sts = ResetMFXComponents(pParams);
MSDK_CHECK_STATUS(sts, "ResetMFXComponents failed");
// register plugin callbacks in Media SDK
mfxPlugin plg = make_mfx_plugin_adapter(m_pusrPlugin);
sts = MFXVideoUSER_Register(m_mfxSession, 0, &plg);
MSDK_CHECK_STATUS(sts, "MFXVideoUSER_Register failed");
// need to call Init after registration because mfxCore interface is needed
sts = m_pusrPlugin->Init(&m_pluginVideoParams);
MSDK_CHECK_STATUS(sts, "m_pusrPlugin->Init failed");
sts = m_pusrPlugin->SetAuxParams(&m_RotateParams, sizeof(m_RotateParams));
MSDK_CHECK_STATUS(sts, "m_pusrPlugin->SetAuxParams failed");
return MFX_ERR_NONE;
}
void CUserPipeline::Close()
{
MFXVideoUSER_Unregister(m_mfxSession, 0);
CEncodingPipeline::Close();
MSDK_SAFE_DELETE(m_pusrPlugin);
if (m_PluginModule)
{
msdk_so_free(m_PluginModule);
m_PluginModule = NULL;
}
}
mfxStatus CUserPipeline::ResetMFXComponents(sInputParams* pParams)
{
MSDK_CHECK_POINTER(pParams, MFX_ERR_NULL_PTR);
MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED);
mfxStatus sts = MFX_ERR_NONE;
sts = m_pmfxENC->Close();
MSDK_IGNORE_MFX_STS(sts, MFX_ERR_NOT_INITIALIZED);
MSDK_CHECK_STATUS(sts, "m_pmfxENC->Close failed");
// free allocated frames
DeleteFrames();
m_TaskPool.Close();
sts = AllocFrames();
MSDK_CHECK_STATUS(sts, "AllocFrames failed");
sts = m_pmfxENC->Init(&m_mfxEncParams);
MSDK_CHECK_STATUS(sts, "m_pmfxENC->Init failed");
mfxU32 nEncodedDataBufferSize = m_mfxEncParams.mfx.FrameInfo.Width * m_mfxEncParams.mfx.FrameInfo.Height * 4;
sts = m_TaskPool.Init(&m_mfxSession, m_FileWriters.first, m_mfxEncParams.AsyncDepth, nEncodedDataBufferSize, m_FileWriters.second);
MSDK_CHECK_STATUS(sts, "m_TaskPool.Init failed");
sts = FillBuffers();
MSDK_CHECK_STATUS(sts, "FillBuffers failed");
return MFX_ERR_NONE;
}
mfxStatus CUserPipeline::Run()
{
m_statOverall.StartTimeMeasurement();
MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED);
mfxStatus sts = MFX_ERR_NONE;
sTask *pCurrentTask = NULL; // a pointer to the current task
mfxU16 nEncSurfIdx = 0; // index of free surface for encoder input
mfxU16 nRotateSurfIdx = 0; // ~ for rotation plugin input
mfxSyncPoint RotateSyncPoint = NULL; // ~ with rotation plugin call
sts = MFX_ERR_NONE;
// main loop, preprocessing and encoding
while (MFX_ERR_NONE <= sts || MFX_ERR_MORE_DATA == sts)
{
// get a pointer to a free task (bit stream and sync point for encoder)
sts = GetFreeTask(&pCurrentTask);
MSDK_BREAK_ON_ERROR(sts);
if (m_nMemBuffer)
{
nRotateSurfIdx = m_nFramesRead % m_nMemBuffer;
}
else
{
nRotateSurfIdx = GetFreeSurface(m_pPluginSurfaces, m_PluginResponse.NumFrameActual);
}
MSDK_CHECK_ERROR(nRotateSurfIdx, MSDK_INVALID_SURF_IDX, MFX_ERR_MEMORY_ALLOC);
m_statFile.StartTimeMeasurement();
sts = LoadNextFrame(&m_pPluginSurfaces[nRotateSurfIdx]);
m_statFile.StopTimeMeasurement();
if ( (MFX_ERR_MORE_DATA == sts) && !m_bTimeOutExceed)
continue;
MSDK_BREAK_ON_ERROR(sts);
nEncSurfIdx = GetFreeSurface(m_pEncSurfaces, m_EncResponse.NumFrameActual);
MSDK_CHECK_ERROR(nEncSurfIdx, MSDK_INVALID_SURF_IDX, MFX_ERR_MEMORY_ALLOC);
// rotation
for(;;)
{
mfxHDL h1, h2;
h1 = &m_pPluginSurfaces[nRotateSurfIdx];
h2 = &m_pEncSurfaces[nEncSurfIdx];
sts = MFXVideoUSER_ProcessFrameAsync(m_mfxSession, &h1, 1, &h2, 1, &RotateSyncPoint);
if (MFX_WRN_DEVICE_BUSY == sts)
{
MSDK_SLEEP(1); // just wait and then repeat the same call
}
else
{
break;
}
}
MSDK_BREAK_ON_ERROR(sts);
// save the id of preceding rotate task which will produce input data for the encode task
if (RotateSyncPoint)
{
pCurrentTask->DependentVppTasks.push_back(RotateSyncPoint);
RotateSyncPoint = NULL;
}
for (;;)
{
InsertIDR(pCurrentTask->encCtrl, m_bInsertIDR);
m_bInsertIDR = false;
sts = m_pmfxENC->EncodeFrameAsync(&pCurrentTask->encCtrl, &m_pEncSurfaces[nEncSurfIdx], &pCurrentTask->mfxBS, &pCurrentTask->EncSyncP);
if (MFX_ERR_NONE < sts && !pCurrentTask->EncSyncP) // repeat the call if warning and no output
{
if (MFX_WRN_DEVICE_BUSY == sts)
MSDK_SLEEP(1); // wait if device is busy
}
else if (MFX_ERR_NONE < sts && pCurrentTask->EncSyncP)
{
sts = MFX_ERR_NONE; // ignore warnings if output is available
break;
}
else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts)
{
sts = AllocateSufficientBuffer(pCurrentTask->mfxBS);
MSDK_CHECK_STATUS(sts, "AllocateSufficientBuffer failed");
}
else
{
break;
}
}
}
// means that the input file has ended, need to go to buffering loops
MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA);
// exit in case of other errors
MSDK_CHECK_STATUS(sts, "m_pmfENC->EncodeFrameAsync failed");
// rotate plugin doesn't buffer frames
// loop to get buffered frames from encoder
while (MFX_ERR_NONE <= sts)
{
// get a free task (bit stream and sync point for encoder)
sts = GetFreeTask(&pCurrentTask);
MSDK_BREAK_ON_ERROR(sts);
for (;;)
{
InsertIDR(pCurrentTask->encCtrl, m_bInsertIDR);
m_bInsertIDR = false;
sts = m_pmfxENC->EncodeFrameAsync(&pCurrentTask->encCtrl, NULL, &pCurrentTask->mfxBS, &pCurrentTask->EncSyncP);
if (MFX_ERR_NONE < sts && !pCurrentTask->EncSyncP) // repeat the call if warning and no output
{
if (MFX_WRN_DEVICE_BUSY == sts)
MSDK_SLEEP(1); // wait if device is busy
}
else if (MFX_ERR_NONE < sts && pCurrentTask->EncSyncP)
{
sts = MFX_ERR_NONE; // ignore warnings if output is available
break;
}
else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts)
{
sts = AllocateSufficientBuffer(pCurrentTask->mfxBS);
MSDK_CHECK_STATUS(sts, "AllocateSufficientBuffer failed");
}
else
{
break;
}
}
MSDK_BREAK_ON_ERROR(sts);
}
// MFX_ERR_MORE_DATA is the correct status to exit buffering loop with
// indicates that there are no more buffered frames
MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA);
// exit in case of other errors
MSDK_CHECK_STATUS(sts, "m_pmfxENC->EncodeFrameAsync failed");
// synchronize all tasks that are left in task pool
while (MFX_ERR_NONE == sts)
{
sts = m_TaskPool.SynchronizeFirstTask();
}
// MFX_ERR_NOT_FOUND is the correct status to exit the loop with,
// EncodeFrameAsync and SyncOperation don't return this status
MSDK_IGNORE_MFX_STS(sts, MFX_ERR_NOT_FOUND);
// report any errors that occurred in asynchronous part
MSDK_CHECK_STATUS(sts, "m_TaskPool.SynchronizeFirstTask failed");
m_statOverall.StopTimeMeasurement();
return sts;
}
mfxStatus CUserPipeline::FillBuffers()
{
if (m_nMemBuffer)
{
for (mfxU32 i = 0; i < m_nMemBuffer; i++)
{
mfxFrameSurface1* surface = &m_pPluginSurfaces[i];
mfxStatus sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, surface->Data.MemId, &surface->Data);
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed");
sts = m_FileReader.LoadNextFrame(surface);
MSDK_CHECK_STATUS(sts, "m_FileReader.LoadNextFrame failed");
sts = m_pMFXAllocator->Unlock(m_pMFXAllocator->pthis, surface->Data.MemId, &surface->Data);
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Unlock failed");
}
}
return MFX_ERR_NONE;
}
void CUserPipeline::PrintInfo()
{
msdk_printf(MSDK_STRING("\nPipeline with rotation plugin"));
msdk_printf(MSDK_STRING("\nNOTE: Some of command line options may have been ignored as non-supported for this pipeline. For details see readme-encode.rtf.\n\n"));
CEncodingPipeline::PrintInfo();
}
| 38.862823 | 755 | 0.689227 | me176c-dev |
9ca17dc30c08fb42cd049a2ac44052e498d89e13 | 526 | cpp | C++ | SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystemUnitTest/ManagerUnitTest.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystemUnitTest/ManagerUnitTest.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystemUnitTest/ManagerUnitTest.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "CppUnitTest.h"
#include"..\ManagerEmployeeSystem\Manager.cpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ManagerEmployeeSystemUnitTest
{
TEST_CLASS(ManagerUnitTest)
{
public:
TEST_METHOD(ManagerUnitTest_parseManager)
{
string manEmp = "a->b,c,d.b->e,f.";
Manager manager;
list<string>managerList = manager.parseManager(manEmp);
string expected = "b";
managerList.pop_front();
Assert::AreEqual(expected, managerList.front());
}
};
} | 22.869565 | 62 | 0.73384 | llanesjuan |
9ca5ec64c1f00539f658fe4201a0f7815d2f8f74 | 933 | cpp | C++ | Test/Core/Hash/hash.cpp | CodogoFreddie/FredLib | 8c7307d039f285e16a1a6979e05a071a2c18717e | [
"Apache-2.0"
] | 2 | 2016-04-28T22:59:58.000Z | 2016-05-04T01:04:27.000Z | Test/Core/Hash/hash.cpp | CodogoFreddie/FredLib | 8c7307d039f285e16a1a6979e05a071a2c18717e | [
"Apache-2.0"
] | null | null | null | Test/Core/Hash/hash.cpp | CodogoFreddie/FredLib | 8c7307d039f285e16a1a6979e05a071a2c18717e | [
"Apache-2.0"
] | null | null | null | #include<Core/hash.hpp>
#include<gtest/gtest.h>
#include<gmock/gmock.h>
using namespace core;
TEST(HashInt, DoneAtCompile){
static_assert(hashInt(1234) != 1234, "Not evaluted at compileTime");
}
TEST(Hash, IsItSalty){
EXPECT_NE(hashInt(1234 ), hashInt(1234,1));
EXPECT_NE(hashInt(1234,1), hashInt(1234,2));
EXPECT_NE(hashInt(1234 ), hashInt(1234,2));
EXPECT_NE(hashConstStr("foo" ), hashConstStr("foo",1));
EXPECT_NE(hashConstStr("foo",1), hashConstStr("foo",2));
EXPECT_NE(hashConstStr("foo" ), hashConstStr("foo",2));
}
TEST(HashString, TakesCorrectInputs){
const char* cc = "foo";
std::string ss = "bar";
EXPECT_NE(hashConstStr(cc), hashStdStr(ss));
EXPECT_NE(hashConstStr("baz"), hashStdStr(ss));
EXPECT_NE(hashConstStr(cc), hashConstStr("baz"));
}
TEST(HashString, DoneAtCompile){
static_assert(hashConstStr("foo") == 193491849, "Not evaluated at compileTime");
}
| 27.441176 | 84 | 0.687031 | CodogoFreddie |
9ca92ab7a35f4878cbec4de5b9e03f6c9db9316f | 40,214 | cc | C++ | psdaq/drp/BldDetectorSlow.cc | valmar/lcls2 | 1c24da076a8cd252cf6601e125dd721fd2004f2a | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/drp/BldDetectorSlow.cc | valmar/lcls2 | 1c24da076a8cd252cf6601e125dd721fd2004f2a | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/drp/BldDetectorSlow.cc | valmar/lcls2 | 1c24da076a8cd252cf6601e125dd721fd2004f2a | [
"BSD-3-Clause-LBNL"
] | null | null | null | #define __STDC_FORMAT_MACROS 1
#include "BldDetector.hh"
#include <bitset>
#include <chrono>
#include <iostream>
#include <memory>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include "DataDriver.h"
#include "RunInfoDef.hh"
#include "psdaq/service/kwargs.hh"
#include "psdaq/service/EbDgram.hh"
#include "xtcdata/xtc/DescData.hh"
#include "xtcdata/xtc/ShapesData.hh"
#include "xtcdata/xtc/NamesLookup.hh"
#include "psdaq/eb/TebContributor.hh"
#include "psalg/utils/SysLog.hh"
#include <getopt.h>
#include <Python.h>
#include <inttypes.h>
#include <poll.h>
using json = nlohmann::json;
using logging = psalg::SysLog;
namespace Drp {
static const XtcData::Name::DataType xtype[] = {
XtcData::Name::UINT8 , // pvBoolean
XtcData::Name::INT8 , // pvByte
XtcData::Name::INT16, // pvShort
XtcData::Name::INT32 , // pvInt
XtcData::Name::INT64 , // pvLong
XtcData::Name::UINT8 , // pvUByte
XtcData::Name::UINT16, // pvUShort
XtcData::Name::UINT32, // pvUInt
XtcData::Name::UINT64, // pvULong
XtcData::Name::FLOAT , // pvFloat
XtcData::Name::DOUBLE, // pvDouble
XtcData::Name::CHARSTR, // pvString
};
BldPVA::BldPVA(std::string det,
unsigned interface) : _interface(interface)
{
//
// Parse '+' separated list of detName, detType, detId
//
size_t p1 = det.find('+',0);
if (p1 == std::string::npos) {
}
size_t p2 = det.find('+',p1+1);
if (p2 == std::string::npos) {
}
_detName = det.substr( 0, p1).c_str();
_detType = det.substr(p1+1,p2-p1-1).c_str();
_detId = det.substr(p2+1).c_str();
std::string sname(_detId);
_pvaAddr = std::make_shared<Pds_Epics::PVBase>((sname+":ADDR" ).c_str());
_pvaPort = std::make_shared<Pds_Epics::PVBase>((sname+":PORT" ).c_str());
_pvaPayload = std::make_shared<BldDescriptor> ((sname+":PAYLOAD").c_str());
logging::info("BldPVA::BldPVA looking up multicast parameters for %s/%s from %s",
_detName.c_str(), _detType.c_str(), _detId.c_str());
}
BldPVA::~BldPVA()
{
}
//
// LCLS-I Style
//
BldFactory::BldFactory(const char* name,
unsigned interface) :
_alg ("raw", 2, 0, 0)
{
logging::debug("BldFactory::BldFactory %s", name);
if (strchr(name,':'))
name = strrchr(name,':')+1;
_detName = std::string(name);
_detType = std::string(name);
_detId = std::string(name);
_pvaPayload = 0;
unsigned payloadSize = 0;
unsigned mcaddr = 0;
unsigned mcport = 10148; // 12148, eventually
uint64_t tscorr = 0x259e9d80ULL << 32;
//
// Make static configuration of BLD :(
//
if (strncmp("ebeam",name,5)==0) {
if (name[5]=='h') {
mcaddr = 0xefff1800;
}
else {
mcaddr = 0xefff1900;
}
tscorr = 0;
_alg = XtcData::Alg("raw", 2, 0, 0);
_varDef.NameVec.push_back(XtcData::Name("damageMask" , XtcData::Name::UINT32));
_varDef.NameVec.push_back(XtcData::Name("ebeamCharge" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamL3Energy" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTUPosX" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTUPosY" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLUTAngX" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTUAngY" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamPkCurrBC2" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamEnergyBC2" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamPkCurrBC1" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamEnergyBC1" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamUndPosX" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamUndPosY" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamUndAngX" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamUndAngY" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamXTCAVAmpl" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamXTCAVPhase" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamDumpCharge" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamPhotonEnergy", XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTU250" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTU450" , XtcData::Name::DOUBLE));
payloadSize = 164;
}
else if (strncmp("pcav",name,4)==0) {
if (name[4]=='h') {
mcaddr = 0xefff1801;
}
else {
mcaddr = 0xefff1901;
}
_alg = XtcData::Alg("raw", 2, 0, 0);
_varDef.NameVec.push_back(XtcData::Name("fitTime1" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("fitTime2" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("charge1" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("charge2" , XtcData::Name::DOUBLE));
payloadSize = 32;
}
else if (strncmp("gmd",name,3)==0) {
mcaddr = 0xefff1902;
_alg = XtcData::Alg("raw", 2, 1, 0);
_varDef.NameVec.push_back(XtcData::Name("energy" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("xpos" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ypos" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("avgIntensity", XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("rmsElectronSum", XtcData::Name::INT64));
_varDef.NameVec.push_back(XtcData::Name("electron1BkgNoiseAvg", XtcData::Name::INT16));
_varDef.NameVec.push_back(XtcData::Name("electron2BkgNoiseAvg", XtcData::Name::INT16));
payloadSize = 44;
}
else if (strcmp("xgmd",name)==0) {
mcaddr = 0xefff1903;
_alg = XtcData::Alg("raw", 2, 1, 0);
_varDef.NameVec.push_back(XtcData::Name("energy" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("xpos" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ypos" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("avgIntensity", XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("rmsElectronSum", XtcData::Name::INT64));
_varDef.NameVec.push_back(XtcData::Name("electron1BkgNoiseAvg", XtcData::Name::INT16));
_varDef.NameVec.push_back(XtcData::Name("electron2BkgNoiseAvg", XtcData::Name::INT16));
payloadSize = 44;
}
else {
throw std::string("BLD name ")+name+" not recognized";
}
_handler = std::make_shared<Bld>(mcaddr, mcport, interface, Bld::DgramTimestampPos, Bld::DgramHeaderSize, payloadSize,
tscorr);
}
//
// LCLS-II Style
//
BldFactory::BldFactory(const BldPVA& pva) :
_detName (pva._detName),
_detType (pva._detType),
_detId (pva._detId),
_alg ("raw", 2, 0, 0),
_pvaPayload (pva._pvaPayload)
{
while(1) {
if (pva._pvaAddr ->ready() &&
pva._pvaPort ->ready() &&
pva._pvaPayload->ready())
break;
usleep(10000);
}
unsigned mcaddr = pva._pvaAddr->getScalarAs<unsigned>();
unsigned mcport = pva._pvaPort->getScalarAs<unsigned>();
unsigned payloadSize = 0;
_varDef = pva._pvaPayload->get(payloadSize);
if (_detType == "hpsex" ||
_detType == "hpscp" ||
_detType == "hpscpb") {
_alg = XtcData::Alg("raw", 2, 0, 0);
// validate _varDef against version here
}
else {
throw std::string("BLD type ")+_detType+" not recognized";
}
_handler = std::make_shared<Bld>(mcaddr, mcport, pva._interface, Bld::TimestampPos, Bld::HeaderSize, payloadSize);
}
BldFactory::BldFactory(const BldFactory& o) :
_detName (o._detName),
_detType (o._detType),
_detId (o._detId),
_alg (o._alg),
_pvaPayload (o._pvaPayload)
{
logging::error("BldFactory copy ctor called");
}
BldFactory::~BldFactory()
{
}
Bld& BldFactory::handler()
{
return *_handler;
}
XtcData::NameIndex BldFactory::addToXtc (XtcData::Xtc& xtc,
const XtcData::NamesId& namesId)
{
XtcData::Names& bldNames = *new(xtc) XtcData::Names(_detName.c_str(), _alg,
_detType.c_str(), _detId.c_str(), namesId);
bldNames.add(xtc, _varDef);
return XtcData::NameIndex(bldNames);
}
unsigned interfaceAddress(const std::string& interface)
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct ifreq ifr;
strcpy(ifr.ifr_name, interface.c_str());
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
logging::debug("%s", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
return ntohl(*(unsigned*)&(ifr.ifr_addr.sa_data[2]));
}
BldDescriptor::~BldDescriptor()
{
logging::debug("~BldDescriptor");
}
XtcData::VarDef BldDescriptor::get(unsigned& payloadSize)
{
payloadSize = 0;
XtcData::VarDef vd;
const pvd::StructureConstPtr& structure = _strct->getStructure();
if (!structure) {
logging::error("BLD with no payload. Is FieldMask empty?");
throw std::string("BLD with no payload. Is FieldMask empty?");
}
const pvd::StringArray& names = structure->getFieldNames();
const pvd::FieldConstPtrArray& fields = structure->getFields();
for (unsigned i=0; i<fields.size(); i++) {
switch (fields[i]->getType()) {
case pvd::scalar: {
const pvd::Scalar* scalar = static_cast<const pvd::Scalar*>(fields[i].get());
XtcData::Name::DataType type = xtype[scalar->getScalarType()];
vd.NameVec.push_back(XtcData::Name(names[i].c_str(), type));
payloadSize += XtcData::Name::get_element_size(type);
break;
}
default: {
throw std::string("PV type ")+pvd::TypeFunc::name(fields[i]->getType())+
" for field "+names[i]+" not supported";
break;
}
}
}
std::string fnames("fields: ");
for(auto & elem: vd.NameVec)
fnames += std::string(elem.name()) + "[" + elem.str_type() + "],";
logging::debug("%s",fnames.c_str());
return vd;
}
#define HANDLE_ERR(str) { \
perror(str); \
throw std::string(str); }
Bld::Bld(unsigned mcaddr,
unsigned port,
unsigned interface,
unsigned timestampPos,
unsigned headerSize,
unsigned payloadSize,
uint64_t timestampCorr) :
m_timestampPos(timestampPos), m_headerSize(headerSize), m_payloadSize(payloadSize),
m_bufferSize(0), m_position(0), m_buffer(Bld::MTU), m_payload(m_buffer.data()),
m_timestampCorr(timestampCorr)
{
logging::debug("Bld listening for %x.%d with payload size %u",mcaddr,port,payloadSize);
m_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (m_sockfd < 0)
HANDLE_ERR("Open socket");
{ unsigned skbSize = 0x1000000;
if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, &skbSize, sizeof(skbSize)) == -1)
HANDLE_ERR("set so_rcvbuf");
}
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(mcaddr);
saddr.sin_port = htons(port);
memset(saddr.sin_zero, 0, sizeof(saddr.sin_zero));
if (bind(m_sockfd, (sockaddr*)&saddr, sizeof(saddr)) < 0)
HANDLE_ERR("bind");
int y = 1;
if (setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(y)) == -1)
HANDLE_ERR("set reuseaddr");
ip_mreq ipmreq;
bzero(&ipmreq, sizeof(ipmreq));
ipmreq.imr_multiaddr.s_addr = htonl(mcaddr);
ipmreq.imr_interface.s_addr = htonl(interface);
if (setsockopt(m_sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&ipmreq, sizeof(ipmreq)) == -1)
HANDLE_ERR("mcast join");
}
Bld::Bld(const Bld& o) :
m_timestampPos(o.m_timestampPos),
m_headerSize (o.m_headerSize),
m_payloadSize (o.m_payloadSize),
m_sockfd (o.m_sockfd)
{
logging::error("Bld copy ctor called");
}
Bld::~Bld()
{
close(m_sockfd);
}
/*
memory layout for bld packet
header:
uint64_t pulseId
uint64_t timeStamp
uint32_t id;
uint8_t payload[]
following events []
uint32_t pulseIdOffset
uint8_t payload[]
*/
uint64_t Bld::next()
{
uint64_t timestamp(0L);
// get new multicast if buffer is empty
if ((m_position + m_payloadSize + 4) > m_bufferSize) {
m_bufferSize = recv(m_sockfd, m_buffer.data(), Bld::MTU, 0);
timestamp = headerTimestamp();
m_payload = &m_buffer[m_headerSize];
m_position = m_headerSize + m_payloadSize;
}
else {
uint32_t timestampOffset = *reinterpret_cast<uint32_t*>(m_buffer.data() + m_position)&0xfffff;
timestamp = headerTimestamp() + timestampOffset;
m_payload = &m_buffer[m_position + 4];
m_position += 4 + m_payloadSize;
}
logging::debug("BLD timestamp %16llx",timestamp);
return timestamp;
}
class BldDetector : public XpmDetector
{
public:
BldDetector(Parameters& para, DrpBase& drp) : XpmDetector(¶, &drp.pool) {}
void event(XtcData::Dgram& dgram, PGPEvent* event) override {}
};
Pgp::Pgp(Parameters& para, DrpBase& drp, Detector* det) :
m_para(para), m_drp(drp), m_det(det),
m_config(0), m_terminate(false), m_running(false),
m_available(0), m_current(0), m_lastComplete(0), m_next(0)
{
m_nodeId = det->nodeId;
uint8_t mask[DMA_MASK_SIZE];
dmaInitMaskBytes(mask);
for (unsigned i=0; i<PGP_MAX_LANES; i++) {
if (para.laneMask & (1 << i)) {
logging::info("setting lane %d", i);
dmaAddMaskBytes((uint8_t*)mask, dmaDest(i, 0));
}
}
dmaSetMaskBytes(m_drp.pool.fd(), mask);
}
Pds::EbDgram* Pgp::_handle(uint32_t& current, uint64_t& bytes)
{
int32_t size = dmaRet[m_current];
uint32_t index = dmaIndex[m_current];
uint32_t lane = (dest[m_current] >> 8) & 7;
bytes += size;
if (unsigned(size) > m_drp.pool.dmaSize()) {
logging::critical("DMA overflowed buffer: %d vs %d", size, m_drp.pool.dmaSize());
throw "DMA overflowed buffer";
}
const uint32_t* data = (uint32_t*)m_drp.pool.dmaBuffers[index];
uint32_t evtCounter = data[5] & 0xffffff;
const unsigned bufferMask = m_drp.pool.nbuffers() - 1;
current = evtCounter & (m_drp.pool.nbuffers() - 1);
PGPEvent* event = &m_drp.pool.pgpEvents[current];
DmaBuffer* buffer = &event->buffers[lane];
buffer->size = size;
buffer->index = index;
event->mask |= (1 << lane);
logging::debug("PGPReader lane %d size %d hdr %016lx.%016lx.%08x",
lane, size,
reinterpret_cast<const uint64_t*>(data)[0],
reinterpret_cast<const uint64_t*>(data)[1],
reinterpret_cast<const uint32_t*>(data)[4]);
const Pds::TimingHeader* timingHeader = reinterpret_cast<const Pds::TimingHeader*>(data);
if (timingHeader->error()) {
logging::error("Timing header error bit is set");
}
XtcData::TransitionId::Value transitionId = timingHeader->service();
if (transitionId != XtcData::TransitionId::L1Accept) {
if (transitionId != XtcData::TransitionId::SlowUpdate) {
logging::info("PGPReader saw %s @ %u.%09u (%014lx)",
XtcData::TransitionId::name(transitionId),
timingHeader->time.seconds(), timingHeader->time.nanoseconds(),
timingHeader->pulseId());
}
else {
logging::debug("PGPReader saw %s @ %u.%09u (%014lx)",
XtcData::TransitionId::name(transitionId),
timingHeader->time.seconds(), timingHeader->time.nanoseconds(),
timingHeader->pulseId());
}
if (transitionId == XtcData::TransitionId::BeginRun) {
m_lastComplete = 0; // EvtCounter reset
}
}
if (evtCounter != ((m_lastComplete + 1) & 0xffffff)) {
logging::critical("%sPGPReader: Jump in complete l1Count %u -> %u | difference %d, tid %s%s",
RED_ON, m_lastComplete, evtCounter, evtCounter - m_lastComplete, XtcData::TransitionId::name(transitionId), RED_OFF);
logging::critical("data: %08x %08x %08x %08x %08x %08x",
data[0], data[1], data[2], data[3], data[4], data[5]);
logging::critical("lastTid %s", XtcData::TransitionId::name(m_lastTid));
logging::critical("lastData: %08x %08x %08x %08x %08x %08x",
m_lastData[0], m_lastData[1], m_lastData[2], m_lastData[3], m_lastData[4], m_lastData[5]);
throw "Jump in event counter";
for (unsigned e=m_lastComplete+1; e<evtCounter; e++) {
PGPEvent* brokenEvent = &m_drp.pool.pgpEvents[e & bufferMask];
logging::error("broken event: %08x", brokenEvent->mask);
brokenEvent->mask = 0;
}
}
m_lastComplete = evtCounter;
m_lastTid = transitionId;
memcpy(m_lastData, data, 24);
event->l3InpBuf = m_drp.tebContributor().allocate(*timingHeader, (void*)((uintptr_t)current));
// make new dgram in the pebble
// It must be an EbDgram in order to be able to send it to the MEB
Pds::EbDgram* dgram = new(m_drp.pool.pebble[current]) Pds::EbDgram(*timingHeader, XtcData::Src(m_nodeId), m_para.rogMask);
return dgram;
}
Pds::EbDgram* Pgp::next(uint32_t& evtIndex, uint64_t& bytes)
{
// get new buffers
if (m_current == m_available) {
m_current = 0;
m_available = dmaReadBulkIndex(m_drp.pool.fd(), MAX_RET_CNT_C, dmaRet, dmaIndex, NULL, NULL, dest);
if (m_available == 0)
return nullptr;
m_drp.pool.allocate(m_available);
}
Pds::EbDgram* dgram = _handle(evtIndex, bytes);
m_current++;
return dgram;
}
void Pgp::shutdown()
{
m_terminate.store(true, std::memory_order_release);
m_det->namesLookup().clear(); // erase all elements
}
void Pgp::worker(std::shared_ptr<Pds::MetricExporter> exporter)
{
// setup monitoring
uint64_t nevents = 0L;
std::map<std::string, std::string> labels{{"instrument", m_para.instrument},
{"partition", std::to_string(m_para.partition)},
{"detname", m_para.detName},
{"detseg", std::to_string(m_para.detSegment)},
{"alias", m_para.alias}};
exporter->add("drp_event_rate", labels, Pds::MetricType::Rate,
[&](){return nevents;});
uint64_t bytes = 0L;
exporter->add("drp_pgp_byte_rate", labels, Pds::MetricType::Rate,
[&](){return bytes;});
uint64_t nmissed = 0L;
exporter->add("bld_miss_count", labels, Pds::MetricType::Counter,
[&](){return nmissed;});
//
// Setup the multicast receivers
//
m_config.erase(m_config.begin(), m_config.end());
unsigned interface = interfaceAddress(m_para.kwargs["interface"]);
//
// Cache the BLD types that require lookup
//
std::vector<std::shared_ptr<BldPVA> > bldPva(0);
std::string s(m_para.detType);
logging::debug("Parsing %s",s.c_str());
for(size_t curr = 0, next = 0; next != std::string::npos; curr = next+1) {
next = s.find(',',curr+1);
size_t pvpos = s.find('+',curr+1);
logging::debug("(%d,%d,%d)",curr,pvpos,next);
if (next == std::string::npos) {
if (pvpos != std::string::npos)
bldPva.push_back(std::make_shared<BldPVA>(s.substr(curr,next),
interface));
else
m_config.push_back(std::make_shared<BldFactory>(s.substr(curr,next).c_str(),
interface));
}
else if (pvpos > curr && pvpos < next)
bldPva.push_back(std::make_shared<BldPVA>(s.substr(curr,next-curr),
interface));
else
m_config.push_back(std::make_shared<BldFactory>(s.substr(curr,next-curr).c_str(),
interface));
}
for(unsigned i=0; i<bldPva.size(); i++)
m_config.push_back(std::make_shared<BldFactory>(*bldPva[i].get()));
// Event builder variables
unsigned index;
Pds::EbDgram* dgram = 0;
uint64_t timestamp[m_config.size()];
memset(timestamp,0,sizeof(timestamp));
bool lMissing = false;
XtcData::NamesLookup& namesLookup = m_det->namesLookup();
// Poll
// this was 4ms, but EBeam bld timed out in rix intermittently,
// increased it to 50ms, but then we get deadtime running bld
// with no eventcode 136 @120Hz. 120Hz corresponds to 8ms, so try 7ms.
unsigned tmo = 7; // milliseconds
{
std::map<std::string,std::string>::iterator it = m_para.kwargs.find("timeout");
if (it != m_para.kwargs.end())
tmo = strtoul(it->second.c_str(),NULL,0);
}
unsigned nfds = m_config.size()+1;
pollfd pfd[nfds];
pfd[0].fd = m_drp.pool.fd();
pfd[0].events = POLLIN;
for(unsigned i=0; i<m_config.size(); i++) {
pfd[i+1].fd = m_config[i]->handler().fd();
pfd[i+1].events = POLL_IN;
}
m_terminate.store(false, std::memory_order_release);
while (true) {
if (m_terminate.load(std::memory_order_relaxed)) {
break;
}
int rval = poll(pfd, nfds, tmo);
if (rval < 0) { // error
}
/**
else if (rval == 0) { // timeout
// flush dgrams
if (pfd[0].events == 0) {
bool lMissed = false;
uint64_t ts = dgram->time.value();
for(unsigned i=0; i<m_config.size(); i++) {
if (timestamp[i] == ts) {
XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i);
const Bld& bld = m_config[i]->handler();
XtcData::DescribedData desc(dgram->xtc, namesLookup, namesId);
memcpy(desc.data(), bld.payload(), bld.payloadSize());
desc.set_data_length(bld.payloadSize());
pfd[i+1].events = POLLIN;
}
else {
lMissed = true;
if (!lMissing)
logging::debug("Missed bld[%u]: pgp %016lx bld %016lx",
i, ts, timestamp[i]);
}
}
if (lMissed) {
lMissing = true;
dgram->xtc.damage.increase(XtcData::Damage::DroppedContribution);
}
else
lMissing = false;
logging::debug("poll tmo flush dgram %p extent %u dmg 0x%x",
dgram, dgram->xtc.extent, dgram->xtc.damage.value());
_sendToTeb(*dgram, index);
nevents++;
pfd[0].events = POLLIN;
}
for(unsigned i=0; i<m_config.size(); i++)
pfd[i+1].events = POLLIN;
}
**/
else {
logging::debug("poll rval[%d] pfd[0].events %u pfd[1].events %u dgram %p",
rval, pfd[0].events,pfd[1].events,dgram);
// handle pgp
if (pfd[0].revents == POLLIN) {
dgram = next(index, bytes);
pfd[0].events = 0;
}
// handle bld
for(unsigned i=0; i<m_config.size(); i++) {
if (pfd[i+1].revents == POLLIN) {
timestamp[i] = m_config[i]->handler().next();
pfd[i+1].events = 0;
}
}
if (dgram) {
bool lready = true;
uint64_t ts = dgram->time.value();
for(unsigned i=0; i<m_config.size(); i++) {
if (timestamp[i] < ts) {
pfd[i+1].events = POLLIN;
lready = false;
}
}
// Accept non-L1 transitions
if (dgram->service() != XtcData::TransitionId::L1Accept) {
// Allocate a transition dgram from the pool and initialize its header
Pds::EbDgram* trDgram = m_drp.pool.allocateTr();
memcpy((void*)trDgram, (const void*)dgram, sizeof(*dgram) - sizeof(dgram->xtc));
// copy the temporary xtc created on phase 1 of the transition
// into the real location
XtcData::Xtc& trXtc = m_det->transitionXtc();
memcpy((void*)&trDgram->xtc, (const void*)&trXtc, trXtc.extent);
PGPEvent* pgpEvent = &m_drp.pool.pgpEvents[index];
pgpEvent->transitionDgram = trDgram;
if (dgram->service() == XtcData::TransitionId::Configure) {
logging::info("BLD configure");
// Revisit: This is intended to be done by BldDetector::configure()
for(unsigned i=0; i<m_config.size(); i++) {
XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i);
namesLookup[namesId] = m_config[i]->addToXtc(trDgram->xtc, namesId);
}
}
_sendToTeb(*dgram, index);
nevents++;
pfd[0].events = POLLIN;
dgram = 0;
}
// Accept L1 transitions
else if (lready or rval==0) {
bool lMissed = false;
for(unsigned i=0; i<m_config.size(); i++) {
if (timestamp[i] == ts) {
XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i);
const Bld& bld = m_config[i]->handler();
XtcData::DescribedData desc(dgram->xtc, namesLookup, namesId);
memcpy(desc.data(), bld.payload(), bld.payloadSize());
desc.set_data_length(bld.payloadSize());
pfd[i+1].events = POLLIN;
}
else {
lMissed = true;
if (!lMissing)
logging::debug("Missed bld[%u]: pgp %016lx bld %016lx",
i, ts, timestamp[i]);
}
}
if (lMissed) {
lMissing = true;
dgram->xtc.damage.increase(XtcData::Damage::DroppedContribution);
}
else
lMissing = false;
_sendToTeb(*dgram, index);
nevents++;
pfd[0].events = POLLIN;
dgram = 0;
}
}
}
}
logging::info("Worker thread finished");
}
void Pgp::_sendToTeb(Pds::EbDgram& dgram, uint32_t index)
{
// Make sure the datagram didn't get too big
const size_t size = sizeof(dgram) + dgram.xtc.sizeofPayload();
const size_t maxSize = ((dgram.service() == XtcData::TransitionId::L1Accept) ||
(dgram.service() == XtcData::TransitionId::SlowUpdate))
? m_drp.pool.bufferSize()
: m_para.maxTrSize;
if (size > maxSize) {
logging::critical("%s Dgram of size %zd overflowed buffer of size %zd", XtcData::TransitionId::name(dgram.service()), size, maxSize);
throw "Dgram overflowed buffer";
}
PGPEvent* event = &m_drp.pool.pgpEvents[index];
if (event->l3InpBuf) { // else timed out
Pds::EbDgram* l3InpDg = new(event->l3InpBuf) Pds::EbDgram(dgram);
if (l3InpDg->isEvent()) {
if (m_drp.triggerPrimitive()) { // else this DRP doesn't provide input
m_drp.triggerPrimitive()->event(m_drp.pool, index, dgram.xtc, l3InpDg->xtc); // Produce
}
}
m_drp.tebContributor().process(l3InpDg);
}
}
BldApp::BldApp(Parameters& para) :
CollectionApp(para.collectionHost, para.partition, "drp", para.alias),
m_drp (para, context()),
m_para (para),
m_det (new BldDetector(m_para, m_drp)),
m_unconfigure(false)
{
Py_Initialize(); // for use by configuration
if (m_det == nullptr) {
logging::critical("Error !! Could not create Detector object for %s", m_para.detType.c_str());
throw "Could not create Detector object for " + m_para.detType;
}
if (m_para.outputDir.empty()) {
logging::info("output dir: n/a");
} else {
logging::info("output dir: %s", m_para.outputDir.c_str());
}
logging::info("Ready for transitions");
}
BldApp::~BldApp()
{
// Try to take things down gracefully when an exception takes us off the
// normal path so that the most chance is given for prints to show up
handleReset(json({}));
if (m_det) {
delete m_det;
}
Py_Finalize(); // for use by configuration
}
void BldApp::_disconnect()
{
m_drp.disconnect();
m_det->shutdown();
}
void BldApp::_unconfigure()
{
m_drp.unconfigure(); // TebContributor must be shut down before the worker
if (m_pgp) {
m_pgp->shutdown();
if (m_workerThread.joinable()) {
m_workerThread.join();
}
m_pgp.reset();
}
m_unconfigure = false;
}
json BldApp::connectionInfo()
{
std::string ip = m_para.kwargs.find("ep_domain") != m_para.kwargs.end()
? getNicIp(m_para.kwargs["ep_domain"])
: getNicIp(m_para.kwargs["forceEnet"] == "yes");
logging::debug("nic ip %s", ip.c_str());
json body = {{"connect_info", {{"nic_ip", ip}}}};
json info = m_det->connectionInfo();
body["connect_info"].update(info);
json bufInfo = m_drp.connectionInfo(ip);
body["connect_info"].update(bufInfo);
return body;
}
void BldApp::connectionShutdown()
{
m_drp.shutdown();
if (m_exporter) {
m_exporter.reset();
}
}
void BldApp::_error(const std::string& which, const nlohmann::json& msg, const std::string& errorMsg)
{
json body = json({});
body["err_info"] = errorMsg;
json answer = createMsg(which, msg["header"]["msg_id"], getId(), body);
reply(answer);
}
void BldApp::handleConnect(const nlohmann::json& msg)
{
std::string errorMsg = m_drp.connect(msg, getId());
if (!errorMsg.empty()) {
logging::error("Error in BldApp::handleConnect");
logging::error("%s", errorMsg.c_str());
_error("connect", msg, errorMsg);
return;
}
// Check for proper command-line parameters
std::map<std::string,std::string>::iterator it = m_para.kwargs.find("interface");
if (it == m_para.kwargs.end()) {
logging::error("Error in BldApp::handleConnect");
logging::error("No multicast interface specified");
_error("connect", msg, std::string("No multicast interface specified"));
return;
}
unsigned interface = interfaceAddress(it->second);
if (!interface) {
logging::error("Error in BldApp::handleConnect");
logging::error("Failed to lookup multicast interface %s",it->second.c_str());
_error("connect", msg, std::string("Failed to lookup multicast interface"));
return;
}
m_det->nodeId = m_drp.nodeId();
m_det->connect(msg, std::to_string(getId()));
json body = json({});
json answer = createMsg("connect", msg["header"]["msg_id"], getId(), body);
reply(answer);
}
void BldApp::handleDisconnect(const json& msg)
{
// Carry out the queued Unconfigure, if there was one
if (m_unconfigure) {
_unconfigure();
}
_disconnect();
json body = json({});
reply(createMsg("disconnect", msg["header"]["msg_id"], getId(), body));
}
void BldApp::handlePhase1(const json& msg)
{
std::string key = msg["header"]["key"];
logging::debug("handlePhase1 for %s in BldDetectorApp", key.c_str());
XtcData::Xtc& xtc = m_det->transitionXtc();
XtcData::TypeId tid(XtcData::TypeId::Parent, 0);
xtc.src = XtcData::Src(m_det->nodeId); // set the src field for the event builders
xtc.damage = 0;
xtc.contains = tid;
xtc.extent = sizeof(XtcData::Xtc);
json phase1Info{ "" };
if (msg.find("body") != msg.end()) {
if (msg["body"].find("phase1Info") != msg["body"].end()) {
phase1Info = msg["body"]["phase1Info"];
}
}
json body = json({});
if (key == "configure") {
if (m_unconfigure) {
_unconfigure();
}
std::string errorMsg = m_drp.configure(msg);
if (!errorMsg.empty()) {
errorMsg = "Phase 1 error: " + errorMsg;
logging::error("%s", errorMsg.c_str());
_error(key, msg, errorMsg);
return;
}
m_pgp = std::make_unique<Pgp>(m_para, m_drp, m_det);
if (m_exporter) m_exporter.reset();
m_exporter = std::make_shared<Pds::MetricExporter>();
if (m_drp.exposer()) {
m_drp.exposer()->RegisterCollectable(m_exporter);
}
std::string config_alias = msg["body"]["config_alias"];
unsigned error = m_det->configure(config_alias, xtc);
if (error) {
std::string errorMsg = "Phase 1 error in Detector::configure";
logging::error("%s", errorMsg.c_str());
_error(key, msg, errorMsg);
return;
}
m_workerThread = std::thread{&Pgp::worker, std::ref(*m_pgp), m_exporter};
m_drp.runInfoSupport(xtc, m_det->namesLookup());
}
else if (key == "unconfigure") {
// "Queue" unconfiguration until after phase 2 has completed
m_unconfigure = true;
}
else if (key == "beginrun") {
RunInfo runInfo;
std::string errorMsg = m_drp.beginrun(phase1Info, runInfo);
if (!errorMsg.empty()) {
logging::error("%s", errorMsg.c_str());
_error(key, msg, errorMsg);
return;
}
m_drp.runInfoData(xtc, m_det->namesLookup(), runInfo);
}
else if (key == "endrun") {
std::string errorMsg = m_drp.endrun(phase1Info);
if (!errorMsg.empty()) {
logging::error("%s", errorMsg.c_str());
_error(key, msg, errorMsg);
return;
}
}
json answer = createMsg(key, msg["header"]["msg_id"], getId(), body);
reply(answer);
}
void BldApp::handleReset(const nlohmann::json& msg)
{
unsubscribePartition(); // ZMQ_UNSUBSCRIBE
_unconfigure();
_disconnect();
connectionShutdown();
}
} // namespace Drp
int main(int argc, char* argv[])
{
Drp::Parameters para;
std::string kwargs_str;
int c;
while((c = getopt(argc, argv, "l:p:o:C:b:d:D:u:P:T::k:M:v")) != EOF) {
switch(c) {
case 'p':
para.partition = std::stoi(optarg);
break;
case 'l':
para.laneMask = strtoul(optarg,NULL,0);
break;
case 'o':
para.outputDir = optarg;
break;
case 'C':
para.collectionHost = optarg;
break;
case 'b':
para.detName = optarg;
break;
case 'd':
para.device = optarg;
break;
case 'D':
para.detType = optarg;
break;
case 'u':
para.alias = optarg;
break;
case 'P':
para.instrument = optarg;
break;
case 'k':
kwargs_str = kwargs_str.empty()
? optarg
: kwargs_str + ", " + optarg;
break;
case 'M':
para.prometheusDir = optarg;
break;
case 'v':
++para.verbose;
break;
default:
return 1;
}
}
switch (para.verbose) {
case 0: logging::init(para.instrument.c_str(), LOG_INFO); break;
default: logging::init(para.instrument.c_str(), LOG_DEBUG); break;
}
logging::info("logging configured");
if (optind < argc)
{
logging::error("Unrecognized argument:");
while (optind < argc)
logging::error(" %s ", argv[optind++]);
return 1;
}
if (para.instrument.empty()) {
logging::warning("-P: instrument name is missing");
}
// Check required parameters
if (para.partition == unsigned(-1)) {
logging::critical("-p: partition is mandatory");
return 1;
}
if (para.device.empty()) {
logging::critical("-d: device is mandatory");
return 1;
}
if (para.alias.empty()) {
logging::critical("-u: alias is mandatory");
return 1;
}
// Only one lane is supported by this DRP
if (std::bitset<PGP_MAX_LANES>(para.laneMask).count() != 1) {
logging::critical("-l: lane mask must have only 1 bit set");
return 1;
}
// Alias must be of form <detName>_<detSegment>
size_t found = para.alias.rfind('_');
if ((found == std::string::npos) || !isdigit(para.alias.back())) {
logging::critical("-u: alias must have _N suffix");
return 1;
}
para.detName = "bld"; //para.alias.substr(0, found);
para.detSegment = std::stoi(para.alias.substr(found+1, para.alias.size()));
get_kwargs(kwargs_str, para.kwargs);
for (const auto& kwargs : para.kwargs) {
if (kwargs.first == "forceEnet") continue;
if (kwargs.first == "ep_fabric") continue;
if (kwargs.first == "ep_domain") continue;
if (kwargs.first == "ep_provider") continue;
if (kwargs.first == "sim_length") continue; // XpmDetector
if (kwargs.first == "timebase") continue; // XpmDetector
if (kwargs.first == "pebbleBufSize") continue; // DrpBase
if (kwargs.first == "batching") continue; // DrpBase
if (kwargs.first == "directIO") continue; // DrpBase
if (kwargs.first == "interface") continue;
if (kwargs.first == "timeout") continue;
logging::critical("Unrecognized kwarg '%s=%s'\n",
kwargs.first.c_str(), kwargs.second.c_str());
return 1;
}
para.maxTrSize = 256 * 1024;
try {
Drp::BldApp app(para);
app.run();
return 0;
}
catch (std::exception& e) { logging::critical("%s", e.what()); }
catch (std::string& e) { logging::critical("%s", e.c_str()); }
catch (char const* e) { logging::critical("%s", e); }
catch (...) { logging::critical("Default exception"); }
return EXIT_FAILURE;
}
| 35.841355 | 143 | 0.557418 | valmar |
66d4adbd39653ccee1c693950dc60d6fe1d7d823 | 1,825 | cpp | C++ | src/Mapper.cpp | binss/HTTPServer | 8f2bcae86b00fed7c237c51aa4e6990d852d9370 | [
"MIT"
] | null | null | null | src/Mapper.cpp | binss/HTTPServer | 8f2bcae86b00fed7c237c51aa4e6990d852d9370 | [
"MIT"
] | null | null | null | src/Mapper.cpp | binss/HTTPServer | 8f2bcae86b00fed7c237c51aa4e6990d852d9370 | [
"MIT"
] | null | null | null | /***********************************************************
* FileName: Mapper.cpp
* Author: binss
* Create: 2015-11-06 11:24:22
* Description: No Description
***********************************************************/
#include "Mapper.h"
Mapper * Mapper::mapper = NULL;
Mapper * Mapper::GetInstance()
{
if(mapper == NULL)
{
mapper = new Mapper();
}
return mapper;
}
Mapper::Mapper():logger_("Mapper", DEBUG, true)
{
InitContentTypeMap();
InitViewMap();
InitReasonMap();
}
void Mapper::InitContentTypeMap()
{
// 0 - 9 chucked
content_type_map_[""] = 0;
content_type_map_["tml"] = 1;
// 10 - 19 fixed-length text file
content_type_map_[".js"] = 10;
content_type_map_["css"] = 11;
// 20 - 29 image
content_type_map_["png"] = 20;
content_type_map_["jpg"] = 21;
content_type_map_["gif"] = 22;
content_type_map_["ico"] = 23;
}
void Mapper::InitReasonMap()
{
// 0 - 9 chucked
reason_map_[200] = "200 OK";
reason_map_[304] = "304 Not Modified";
reason_map_[403] = "403 Forbidden";
reason_map_[404] = "404 Not Found";
reason_map_[500] = "500 Internal Server Error";
}
int Mapper::GetContentType(string file_type)
{
// 默认为0
return content_type_map_[file_type];
}
void Mapper::InitViewMap()
{
view_map_["/"] = main_page;
view_map_["/404/"] = error_404;
view_map_["/403/"] = error_403;
view_map_["/upload/"] = upload_page;
view_map_["/user/"] = user_page;
}
View Mapper::GetView(string target)
{
View view = view_map_[target];
if(NULL == view)
{
logger_<<"Can not find the view of the target["<<target<<"]"<<endl;
return view_map_["/404/"];
}
return view;
}
string & Mapper::GetReason(int code)
{
return reason_map_[code];
}
| 20.505618 | 75 | 0.568767 | binss |
66d5fffc8f179b4dd7597fcf56070e93f11a7dc7 | 5,640 | cpp | C++ | Source/UiUndoRedo.cpp | StefanoLusardi/BilinearOscillator | cb53ba05a865cc360243adf0e04ef9421028abcf | [
"MIT"
] | 1 | 2020-03-15T17:48:01.000Z | 2020-03-15T17:48:01.000Z | Source/UiUndoRedo.cpp | StefanoLusardi/BilinearOscillator | cb53ba05a865cc360243adf0e04ef9421028abcf | [
"MIT"
] | null | null | null | Source/UiUndoRedo.cpp | StefanoLusardi/BilinearOscillator | cb53ba05a865cc360243adf0e04ef9421028abcf | [
"MIT"
] | null | null | null | /*
==============================================================================
This is an automatically generated GUI class created by the Projucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Projucer version: 5.4.3
------------------------------------------------------------------------------
The Projucer is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
#include "Core.h"
//[/Headers]
#include "UiUndoRedo.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
UiUndoRedo::UiUndoRedo (Component* parent, Core& core)
: mParent{parent}, mUndoManager{core.getUndoManager()}
{
//[Constructor_pre] You can add your own custom stuff here..
//[/Constructor_pre]
setName ("UiUndoRedo");
mButtonUndo.reset (new TextButton ("ButtonUndo"));
addAndMakeVisible (mButtonUndo.get());
mButtonUndo->setButtonText (TRANS("Undo"));
mButtonUndo->setColour (TextButton::buttonOnColourId, Colour (0xffa45c94));
mButtonRedo.reset (new TextButton ("ButtonRedo"));
addAndMakeVisible (mButtonRedo.get());
mButtonRedo->setButtonText (TRANS("Redo"));
mButtonRedo->setColour (TextButton::buttonOnColourId, Colour (0xffa45c94));
//[UserPreSize]
mButtonUndo->setEnabled(false);
mButtonRedo->setEnabled(false);
//[/UserPreSize]
setSize (600, 400);
//[Constructor] You can add your own custom stuff here..
mButtonUndo->onClick = [&] { mUndoManager.undo(); };
mButtonRedo->onClick = [&] { mUndoManager.redo(); };
startTimer (250);
//[/Constructor]
}
UiUndoRedo::~UiUndoRedo()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
mButtonUndo = nullptr;
mButtonRedo = nullptr;
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void UiUndoRedo::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
{
float x = 0.0f, y = 0.0f, width = static_cast<float> (proportionOfWidth (1.0000f)), height = static_cast<float> (proportionOfHeight (1.0000f));
Colour fillColour = Colours::yellow;
Colour strokeColour = Colours::black;
//[UserPaintCustomArguments] Customize the painting arguments here..
//[/UserPaintCustomArguments]
g.setColour (fillColour);
g.fillRoundedRectangle (x, y, width, height, 20.000f);
g.setColour (strokeColour);
g.drawRoundedRectangle (x, y, width, height, 20.000f, 5.000f);
}
//[UserPaint] Add your own custom painting code here..
//[/UserPaint]
}
void UiUndoRedo::resized()
{
//[UserPreResize] Add your own custom resize code here..
//[/UserPreResize]
mButtonUndo->setBounds (proportionOfWidth (0.0391f), proportionOfHeight (0.2530f), proportionOfWidth (0.4104f), proportionOfHeight (0.5060f));
mButtonRedo->setBounds (proportionOfWidth (0.5570f), proportionOfHeight (0.2530f), proportionOfWidth (0.4104f), proportionOfHeight (0.5060f));
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
void UiUndoRedo::timerCallback()
{
mButtonUndo->setEnabled(mUndoManager.canUndo());
mButtonRedo->setEnabled(mUndoManager.canRedo());
}
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Projucer information section --
This is where the Projucer stores the metadata that describe this GUI layout, so
make changes in here at your peril!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="UiUndoRedo" componentName="UiUndoRedo"
parentClasses="public Component, public Timer" constructorParams="Component* parent, Core& core"
variableInitialisers="mParent{parent}, mUndoManager{core.getUndoManager()}"
snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.330"
fixedSize="0" initialWidth="600" initialHeight="400">
<BACKGROUND backgroundColour="0">
<ROUNDRECT pos="0 0 100% 100%" cornerSize="20.0" fill="solid: ffffff00"
hasStroke="1" stroke="5, mitered, butt" strokeColour="solid: ff000000"/>
</BACKGROUND>
<TEXTBUTTON name="ButtonUndo" id="2905daae1318e8f9" memberName="mButtonUndo"
virtualName="" explicitFocusOrder="0" pos="3.867% 25.397% 40.884% 50.794%"
bgColOn="ffa45c94" buttonText="Undo" connectedEdges="0" needsCallback="0"
radioGroupId="0"/>
<TEXTBUTTON name="ButtonRedo" id="f80fc073aaa0b332" memberName="mButtonRedo"
virtualName="" explicitFocusOrder="0" pos="55.801% 25.397% 40.884% 50.794%"
bgColOn="ffa45c94" buttonText="Redo" connectedEdges="0" needsCallback="0"
radioGroupId="0"/>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
//[EndFile] You can add extra defines here...
//[/EndFile]
| 35.923567 | 152 | 0.606738 | StefanoLusardi |
66d7ac6c6ee2501963e8ba43336d8cb525e8cfeb | 904 | hpp | C++ | Engine/Lang/AST/Nodes/Conditional/ASTNodeIfStatement.hpp | GabyForceQ/PolluxEngine | 2dbc84ed1d434f1b6d794f775f315758f0e8cc49 | [
"BSD-3-Clause"
] | 3 | 2020-05-19T20:24:28.000Z | 2020-09-27T11:28:42.000Z | Engine/Lang/AST/Nodes/Conditional/ASTNodeIfStatement.hpp | GabyForceQ/PolluxEngine | 2dbc84ed1d434f1b6d794f775f315758f0e8cc49 | [
"BSD-3-Clause"
] | 31 | 2020-05-27T11:01:27.000Z | 2020-08-08T15:53:23.000Z | Engine/Lang/AST/Nodes/Conditional/ASTNodeIfStatement.hpp | GabyForceQ/PolluxEngine | 2dbc84ed1d434f1b6d794f775f315758f0e8cc49 | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************************************************************************
* Copyright 2020 Gabriel Gheorghe. All rights reserved.
* This code is licensed under the BSD 3-Clause "New" or "Revised" License
* License url: https://github.com/GabyForceQ/PolluxEngine/blob/master/LICENSE
*****************************************************************************************************************************/
#pragma once
#include "../../ASTNodeBase.hpp"
namespace Pollux::Lang
{
class ASTNodeIfStatement final : public ASTNodeBase
{
public:
ASTNodeIfStatement() noexcept;
void Accept(IASTNodeVisitor* pVisitor) override;
ASTNodeExpression* pExpression = nullptr;
ASTNodeScope* pIfScope = nullptr;
ASTNodeScope* pElseScope = nullptr;
bool bHasElseScope = false;
bool bComptimeEval = false;
AST_FRIENDS_BODY
};
} | 28.25 | 127 | 0.533186 | GabyForceQ |
66e0f863acb0141a66c782bd5ef9047cf5fc03ad | 10,265 | cpp | C++ | Flow3D/Flow3D/src/Flow3D/Components/ComponentManager.cpp | florianvoelkers/Flow3D | 017d2f321f943dfecc360bec9fc6f17c77ffde68 | [
"MIT"
] | 2 | 2020-05-09T10:06:00.000Z | 2021-03-10T00:10:41.000Z | Flow3D/Flow3D/src/Flow3D/Components/ComponentManager.cpp | florianvoelkers/Flow3D | 017d2f321f943dfecc360bec9fc6f17c77ffde68 | [
"MIT"
] | 1 | 2022-03-04T09:17:15.000Z | 2022-03-04T09:17:15.000Z | Flow3D/Flow3D/src/Flow3D/Components/ComponentManager.cpp | florianvoelkers/Flow3D | 017d2f321f943dfecc360bec9fc6f17c77ffde68 | [
"MIT"
] | 2 | 2020-02-17T00:43:03.000Z | 2020-11-26T11:55:19.000Z | #include "ComponentManager.hpp"
const std::size_t Component::Type = std::hash<std::string>()(TO_STRING(Component));
// All class definitions for components
// CLASS_DEFINITION(parent class, sub class)
CLASS_DEFINITION(Component, Rotatable)
CLASS_DEFINITION(Component, FreeCamera)
CLASS_DEFINITION(Component, Renderable)
CLASS_DEFINITION(Component, BaseLight)
CLASS_DEFINITION(BaseLight, DirectionalLight)
CLASS_DEFINITION(BaseLight, PointLight)
CLASS_DEFINITION(BaseLight, SpotLight)
CLASS_DEFINITION(Component, ComponentToggler)
CLASS_DEFINITION(Component, GameObjectToggler)
#include "Flow3D/ImGui/ImGuiFreeCameraEditor.hpp"
#include "Flow3D/ImGui/ImGuiGameObjectTogglerEditor.hpp"
#include "Flow3D/ImGui/ImGuiComponentTogglerEditor.hpp"
#include "Flow3D/ImGui/ImGuiDirectionalLightEditor.hpp"
#include "Flow3D/ImGui/ImGuiPointLightEditor.hpp"
#include "Flow3D/ImGui/ImGuiSpotLightEditor.hpp"
#include "Flow3D/ImGui/ImGuiRenderableEditor.hpp"
#include "Flow3D/Serializer.hpp"
#include <io.h> // For access().
#include <sys/types.h> // For stat().
#include <sys/stat.h> // For stat().
#include <filesystem>
std::string ComponentManager::ChooseComponentPopup(std::string componentName)
{
if (componentName == "Rotatable")
{
return "Rotatable";
}
else if (componentName == "FreeCamera")
{
return "FreeCamera";
}
else if (componentName == "Renderable")
{
return "Renderable";
}
else if (componentName == "DirectionalLight")
{
return "DirectionalLight";
}
else if (componentName == "PointLight")
{
return "PointLight";
}
else if (componentName == "SpotLight")
{
return "SpotLight";
}
else if (componentName == "ComponentToggler")
{
return "ComponentToggler";
}
else if (componentName == "GameObjectToggler")
{
return "GameObjectToggler";
}
}
void ComponentManager::DuplicateComponent(Component& component, GameObject& gameObject)
{
std::string componentName = component.GetName();
if (componentName == "FreeCamera")
{
FLOW_CORE_WARN("a camera component should not be copied");
}
else if (componentName == "GameObjectToggler")
{
gameObject.AddComponent<GameObjectToggler>(&gameObject, component.GetEnabled());
GameObjectToggler& goToggler = *dynamic_cast<GameObjectToggler*>(&component);
std::vector<std::tuple<GameObject*, std::string, Keycode>>& gameObjectsToToggle = goToggler.GetGameObjectsToToggle();
GameObjectToggler& togglerOfNewGameObject = gameObject.GetComponent<GameObjectToggler>();
for (unsigned int i = 0; i < gameObjectsToToggle.size(); i++)
{
togglerOfNewGameObject.AddGameObjectToToggle(std::make_tuple(std::get<0>(gameObjectsToToggle[i]),
std::get<1>(gameObjectsToToggle[i]), std::get<2>(gameObjectsToToggle[i])), false);
}
}
else if (componentName == "ComponentToggler")
{
gameObject.AddComponent<ComponentToggler>(&gameObject, component.GetEnabled());
ComponentToggler& toggler = *dynamic_cast<ComponentToggler*>(&component);
std::vector<std::tuple<Component*, Keycode>>& componentsToToggle = toggler.GetComponentsToToggle();
ComponentToggler& togglerOfNewGameObject = gameObject.GetComponent<ComponentToggler>();
for (unsigned int i = 0; i < componentsToToggle.size(); i++)
{
togglerOfNewGameObject.AddComponentToToggle(std::make_tuple(std::get<0>(componentsToToggle[i]),
std::get<1>(componentsToToggle[i])), false);
}
}
else if (componentName == "DirectionalLight")
{
FLOW_CORE_WARN("a directional light component should not be copied");
}
else if (componentName == "PointLight")
{
PointLight& pointLight = *dynamic_cast<PointLight*>(&component);
gameObject.AddComponent<PointLight>(&gameObject, pointLight.GetAmbientIntensity(), pointLight.GetDiffuseIntensity(), pointLight.GetSpecularIntensity(),
pointLight.GetAttenuation(), pointLight.GetEnabled());
Application::Get().GetCurrentScene().AddPointLight(&gameObject.GetComponent<PointLight>());
}
else if (componentName == "SpotLight")
{
SpotLight& spotLight = *dynamic_cast<SpotLight*>(&component);
gameObject.AddComponent<SpotLight>(&gameObject, spotLight.GetAmbientIntensity(), spotLight.GetDiffuseIntensity(), spotLight.GetSpecularIntensity(),
spotLight.GetCutoff(), spotLight.GetOuterCutoff(), spotLight.GetAttenuation(), spotLight.GetEnabled());
Application::Get().GetCurrentScene().AddPointLight(&gameObject.GetComponent<PointLight>());
}
else if (componentName == "Renderable")
{
Renderable& renderable = *dynamic_cast<Renderable*>(&component);
std::string shaderName = renderable.GetShader().m_Name;
Model& model = renderable.GetModel();
std::string modelFilepath = model.filepath;
if (modelFilepath.empty())
{
if (model.GetCube() != nullptr)
{
Cube& cube = *model.GetCube();
if (cube.GetIsTextured())
{
Texture& diffuseTexture = cube.GetDiffuseTexture();
std::string diffusePath = diffuseTexture.path;
Texture& specularTexture = cube.GetSpecularTexture();
std::string specularPath = specularTexture.path;
gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Cube>(ResourceManager::Get().FindTexture(diffusePath),
ResourceManager::Get().FindTexture(specularPath))),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
else
{
gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Cube>(cube.GetColor())),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
}
else if (model.GetPlane() != nullptr)
{
Plane& plane = *model.GetPlane();
if (plane.GetIsTextured())
{
Texture& diffuseTexture = plane.GetDiffuseTexture();
std::string diffusePath = diffuseTexture.path;
Texture& specularTexture = plane.GetSpecularTexture();
std::string specularPath = specularTexture.path;
gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Plane>(ResourceManager::Get().FindTexture(diffusePath),
ResourceManager::Get().FindTexture(specularPath))),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
else
{
gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Plane>(plane.GetColor())),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
}
}
else
{
gameObject.AddComponent<Renderable>(&gameObject, ResourceManager::Get().FindModel(modelFilepath),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
}
}
void ComponentManager::ShowComponentEditor(std::string componentName, std::vector<std::string> componentNames, Component* component, const std::vector<std::shared_ptr<Component>>& components)
{
if (componentName == "FreeCamera")
{
FreeCameraEditor editor = FreeCameraEditor();
editor.Draw(dynamic_cast<FreeCamera*>(component));
}
else if (componentName == "GameObjectToggler")
{
GameObjectTogglerEditor editor = GameObjectTogglerEditor();
editor.Draw(dynamic_cast<GameObjectToggler*>(component));
}
else if (componentName == "ComponentToggler")
{
ComponentTogglerEditor editor = ComponentTogglerEditor();
editor.Draw(dynamic_cast<ComponentToggler*>(component), components, componentNames);
}
else if (componentName == "DirectionalLight")
{
DirectionalLightEditor editor = DirectionalLightEditor();
editor.Draw(dynamic_cast<DirectionalLight*>(component));
}
else if (componentName == "PointLight")
{
PointLightEditor editor = PointLightEditor();
editor.Draw(dynamic_cast<PointLight*>(component));
}
else if (componentName == "SpotLight")
{
SpotLightEditor editor = SpotLightEditor();
editor.Draw(dynamic_cast<SpotLight*>(component));
}
else if (componentName == "Renderable")
{
RenderableEditor editor = RenderableEditor();
editor.Draw(dynamic_cast<Renderable*>(component));
}
}
void ComponentManager::SerializeComponent(const std::string& componentName, std::ofstream& myfile, Component* component, const std::string& componentDirectory)
{
if (componentName == "Rotatable")
{
Serializer::SerializeRotatable(myfile, component);
}
else if (componentName == "FreeCamera")
{
Serializer::SerializeFreeCamera(myfile, component);
}
else if (componentName == "GameObjectToggler")
{
Serializer::SerializeGameObjectToggler(myfile, component);
}
else if (componentName == "ComponentToggler")
{
Serializer::SerializeComponentToggler(myfile, component);
}
else if (componentName == "DirectionalLight")
{
Serializer::SerializeDirectionalLight(myfile, component);
}
else if (componentName == "PointLight")
{
Serializer::SerializePointLight(myfile, component);
}
else if (componentName == "SpotLight")
{
Serializer::SerializeSpotLight(myfile, component);
}
else if (componentName == "Renderable")
{
Serializer::SerializeRenderable(myfile, component, componentDirectory);
}
}
void ComponentManager::DeserializeComponent(const std::string& componentName, json & json, GameObject & gameObject, Scene & scene, const std::string & componentsDirectory, std::vector<std::shared_ptr<GameObject>>& gameObjectsWithGameObjectToggler)
{
if (componentName == "Rotatable")
{
Serializer::DeserializeRotatable(json, gameObject, scene);
}
else if (componentName == "FreeCamera")
{
Serializer::DeserializeFreeCamera(json, gameObject, scene);
}
else if (componentName == "GameObjectToggler")
{
Serializer::DeserializeGameObjectToggler(json, gameObject, scene, gameObjectsWithGameObjectToggler);
}
else if (componentName == "ComponentToggler")
{
Serializer::DeserializeComponentToggler(json, gameObject, scene);
}
else if (componentName == "DirectionalLight")
{
Serializer::DeserializeDirectionalLight(json, gameObject, scene);
}
else if (componentName == "PointLight")
{
Serializer::DeserializePointLight(json, gameObject, scene);
}
else if (componentName == "SpotLight")
{
Serializer::DeserializeSpotLight(json, gameObject, scene);
}
else if (componentName == "Renderable")
{
Serializer::DeserializeRenderable(json, gameObject, scene, componentsDirectory);
}
}
| 35.642361 | 247 | 0.746322 | florianvoelkers |
66e0fff5a52a9989a2f801c9d318e01be21aa13e | 804 | cpp | C++ | Source/examples/inherits-via-dominance.cpp | nojhan/leathers | d8a2867a477baab515affdf320d872896e01a797 | [
"BSD-2-Clause"
] | 86 | 2015-05-11T22:47:52.000Z | 2021-09-05T11:26:05.000Z | Source/examples/inherits-via-dominance.cpp | nojhan/leathers | d8a2867a477baab515affdf320d872896e01a797 | [
"BSD-2-Clause"
] | 6 | 2015-07-03T12:34:26.000Z | 2020-03-08T09:01:51.000Z | Source/examples/inherits-via-dominance.cpp | nojhan/leathers | d8a2867a477baab515affdf320d872896e01a797 | [
"BSD-2-Clause"
] | 12 | 2015-09-01T11:36:37.000Z | 2021-12-01T12:56:44.000Z | // Copyright (c) 2014, Ruslan Baratov
// All rights reserved.
#include <leathers/push>
#include <leathers/object-layout-change>
#include <leathers/c++98-compat>
#include <leathers/weak-vtables>
#include <leathers/padded>
class Foo {
public:
virtual void foo() {
}
virtual ~Foo() {
}
};
class Boo : virtual public Foo {
public:
virtual void foo() override {
}
virtual ~Boo() override {
}
};
#include <leathers/pop>
#include <leathers/push>
#include <leathers/object-layout-change>
#include <leathers/padded>
#include <leathers/c++98-compat>
#if !defined(SHOW_WARNINGS)
# include <leathers/inherits-via-dominance>
#endif
class Baz : public Boo, virtual public Foo {
virtual ~Baz() override {
}
};
#include <leathers/pop>
int main() {
}
| 18.697674 | 45 | 0.656716 | nojhan |
66e10c3dc38d490ec22dc8dc847583b3fa75b4cf | 1,002 | cpp | C++ | 124-binary-tree-maximum-path-sum.cpp | ranveeraggarwal/leetcode-cpp | 931dd37c00076ee8e49d2ba3dbafbe0113e35376 | [
"MIT"
] | null | null | null | 124-binary-tree-maximum-path-sum.cpp | ranveeraggarwal/leetcode-cpp | 931dd37c00076ee8e49d2ba3dbafbe0113e35376 | [
"MIT"
] | null | null | null | 124-binary-tree-maximum-path-sum.cpp | ranveeraggarwal/leetcode-cpp | 931dd37c00076ee8e49d2ba3dbafbe0113e35376 | [
"MIT"
] | null | null | null | #include "stdafx.h"
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
int vmax;
public:
int maxPathSum(TreeNode *root)
{
vmax = INT_MIN;
subPath(root);
return vmax;
}
int subPath(TreeNode *root)
{
if (root == NULL)
return 0;
int val = root->val;
int left = subPath(root->left);
int right = subPath(root->right);
if (left >= 0 && right >= 0)
{
vmax = max(vmax, left + right + val);
return max(left, right) + val;
}
else if (left >= 0)
{
vmax = max(vmax, left + val);
return left + val;
}
else if (right >= 0)
{
vmax = max(vmax, right + val);
return right + val;
}
else
{
vmax = max(vmax, val);
return val;
}
}
}; | 19.647059 | 56 | 0.443114 | ranveeraggarwal |
66e80b14adfe64ada87ef0a12ac183ac7975680e | 1,363 | cpp | C++ | Util/testsuite/src/MapConfigurationTest.cpp | AppAnywhere/agent-sdk | c5495c4a1d892f2d3bca5b82a7436db7d8adff71 | [
"BSL-1.0"
] | null | null | null | Util/testsuite/src/MapConfigurationTest.cpp | AppAnywhere/agent-sdk | c5495c4a1d892f2d3bca5b82a7436db7d8adff71 | [
"BSL-1.0"
] | null | null | null | Util/testsuite/src/MapConfigurationTest.cpp | AppAnywhere/agent-sdk | c5495c4a1d892f2d3bca5b82a7436db7d8adff71 | [
"BSL-1.0"
] | null | null | null | //
// MapConfigurationTest.cpp
//
// $Id: //poco/1.7/Util/testsuite/src/MapConfigurationTest.cpp#1 $
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "MapConfigurationTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Util/MapConfiguration.h"
#include "Poco/AutoPtr.h"
using Poco::Util::AbstractConfiguration;
using Poco::Util::MapConfiguration;
using Poco::AutoPtr;
MapConfigurationTest::MapConfigurationTest(const std::string& name): AbstractConfigurationTest(name)
{
}
MapConfigurationTest::~MapConfigurationTest()
{
}
void MapConfigurationTest::testClear()
{
AutoPtr<MapConfiguration> pConf = new MapConfiguration;
pConf->setString("foo", "bar");
assert (pConf->hasProperty("foo"));
pConf->clear();
assert (!pConf->hasProperty("foo"));
}
AbstractConfiguration* MapConfigurationTest::allocConfiguration() const
{
return new MapConfiguration;
}
void MapConfigurationTest::setUp()
{
}
void MapConfigurationTest::tearDown()
{
}
CppUnit::Test* MapConfigurationTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MapConfigurationTest");
AbstractConfigurationTest_addTests(pSuite, MapConfigurationTest);
CppUnit_addTest(pSuite, MapConfigurationTest, testClear);
return pSuite;
}
| 18.930556 | 100 | 0.758621 | AppAnywhere |
66e84a1cf50265f1578c87458a7eddb20fe53d13 | 72,652 | cpp | C++ | extensions/standard-processors/tests/unit/TailFileTests.cpp | nghiaxlee/nifi-minifi-cpp | ddddb22d63c4a60b97066e555f771135c8dbb26d | [
"Apache-2.0"
] | 1 | 2017-03-14T15:42:08.000Z | 2017-03-14T15:42:08.000Z | extensions/standard-processors/tests/unit/TailFileTests.cpp | nghiaxlee/nifi-minifi-cpp | ddddb22d63c4a60b97066e555f771135c8dbb26d | [
"Apache-2.0"
] | null | null | null | extensions/standard-processors/tests/unit/TailFileTests.cpp | nghiaxlee/nifi-minifi-cpp | ddddb22d63c4a60b97066e555f771135c8dbb26d | [
"Apache-2.0"
] | 1 | 2020-07-17T15:27:37.000Z | 2020-07-17T15:27:37.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.
*/
#include <cstdio>
#include <fstream>
#include <map>
#include <memory>
#include <utility>
#include <string>
#include <iostream>
#include <set>
#include <algorithm>
#include <random>
#include <cstdlib>
#include "FlowController.h"
#include "TestBase.h"
#include "core/Core.h"
#include "core/FlowFile.h"
#include "utils/file/FileUtils.h"
#include "utils/file/PathUtils.h"
#include "unit/ProvenanceTestHelper.h"
#include "core/Processor.h"
#include "core/ProcessContext.h"
#include "core/ProcessSession.h"
#include "core/ProcessorNode.h"
#include "TailFile.h"
#include "LogAttribute.h"
static std::string NEWLINE_FILE = "" // NOLINT
"one,two,three\n"
"four,five,six, seven";
static const char *TMP_FILE = "minifi-tmpfile.txt";
static const char *STATE_FILE = "minifi-state-file.txt";
namespace {
std::string createTempFile(const std::string &directory, const std::string &file_name, const std::string &contents,
std::ios_base::openmode open_mode = std::ios::out | std::ios::binary) {
std::string full_file_name = directory + utils::file::FileUtils::get_separator() + file_name;
std::ofstream tmpfile{full_file_name, open_mode};
tmpfile << contents;
return full_file_name;
}
void appendTempFile(const std::string &directory, const std::string &file_name, const std::string &contents,
std::ios_base::openmode open_mode = std::ios::app | std::ios::binary) {
createTempFile(directory, file_name, contents, open_mode);
}
void removeFile(const std::string &directory, const std::string &file_name) {
std::string full_file_name = directory + utils::file::FileUtils::get_separator() + file_name;
std::remove(full_file_name.c_str());
}
void renameTempFile(const std::string &directory, const std::string &old_file_name, const std::string &new_file_name) {
std::string old_full_file_name = directory + utils::file::FileUtils::get_separator() + old_file_name;
std::string new_full_file_name = directory + utils::file::FileUtils::get_separator() + new_file_name;
rename(old_full_file_name.c_str(), new_full_file_name.c_str());
}
} // namespace
TEST_CASE("TailFile reads the file until the first delimiter", "[simple]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
std::stringstream state_file;
state_file << dir << utils::file::FileUtils::get_separator() << STATE_FILE;
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
testController.runSession(plan, false);
auto records = plan->getProvenanceRecords();
REQUIRE(records.size() == 5); // line 1: CREATE, MODIFY; line 2: CREATE, MODIFY, DROP
testController.runSession(plan, false);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files"));
REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(NEWLINE_FILE.find_first_of('\n') + 1) + " Offset:0"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile picks up the second line if a delimiter is written between runs", "[state]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt"));
plan->reset(true); // start a new but with state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
std::ofstream appendStream;
appendStream.open(temp_file.str(), std::ios_base::app | std::ios_base::binary);
appendStream << std::endl;
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile re-reads the file if the state is deleted between runs", "[state]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt"));
plan->reset(true); // start a new but with state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->clear();
testController.runSession(plan, true);
// if we lose state we restart
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt"));
}
TEST_CASE("TailFile picks up the state correctly if it is rewritten between runs", "[state]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
std::ofstream appendStream;
appendStream.open(temp_file.str(), std::ios_base::app | std::ios_base::binary);
appendStream.write("\n", 1);
appendStream.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt"));
std::string filePath, fileName;
REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file.str(), filePath, fileName));
// should stay the same
for (int i = 0; i < 5; i++) {
plan->reset(true); // start a new but with state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->set({{"file.0.name", fileName},
{"file.0.position", "14"},
{"file.0.current", temp_file.str()}});
testController.runSession(plan, true);
// if we lose state we restart
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt"));
}
for (int i = 14; i < 34; i++) {
plan->reset(true); // start a new but with state file
plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->set({{"file.0.name", fileName},
{"file.0.position", std::to_string(i)},
{"file.0.current", temp_file.str()}});
testController.runSession(plan, true);
}
plan->runCurrentProcessor();
for (int i = 14; i < 34; i++) {
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile." + std::to_string(i) + "-34.txt"));
}
}
TEST_CASE("TailFile converts the old-style state file to the new-style state", "[state][migration]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
auto plan = testController.createPlan();
auto tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
auto logattribute = plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream state_file;
state_file << dir << utils::file::FileUtils::get_separator() << STATE_FILE;
auto statefile = state_file.str() + "." + id;
SECTION("single") {
const std::string temp_file = createTempFile(dir, TMP_FILE, NEWLINE_FILE + '\n');
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::StateFile.getName(), state_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::ofstream newstatefile;
newstatefile.open(statefile);
SECTION("legacy") {
newstatefile << "FILENAME=" << temp_file << std::endl;
newstatefile << "POSITION=14" << std::endl;
}
SECTION("newer single") {
newstatefile << "FILENAME=" << TMP_FILE << std::endl;
newstatefile << "POSITION." << TMP_FILE << "=14" << std::endl;
newstatefile << "CURRENT." << TMP_FILE << "=" << temp_file << std::endl;
}
newstatefile.close();
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt"));
std::unordered_map<std::string, std::string> state;
REQUIRE(plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->get(state));
std::string filePath, fileName;
REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file, filePath, fileName));
std::unordered_map<std::string, std::string> expected_state{{"file.0.name", fileName},
{"file.0.position", "35"},
{"file.0.current", temp_file},
{"file.0.checksum", "1404369522"}};
for (const auto& key_value_pair : expected_state) {
const auto it = state.find(key_value_pair.first);
REQUIRE(it != state.end());
REQUIRE(it->second == key_value_pair.second);
}
REQUIRE(state.find("file.0.last_read_time") != state.end());
}
SECTION("multiple") {
const std::string file_name_1 = "bar.txt";
const std::string file_name_2 = "foo.txt";
const std::string temp_file_1 = createTempFile(dir, file_name_1, NEWLINE_FILE + '\n');
const std::string temp_file_2 = createTempFile(dir, file_name_2, NEWLINE_FILE + '\n');
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.txt");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::StateFile.getName(), state_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::ofstream newstatefile;
newstatefile.open(statefile);
newstatefile << "FILENAME=" << file_name_1 << std::endl;
newstatefile << "POSITION." << file_name_1 << "=14" << std::endl;
newstatefile << "CURRENT." << file_name_1 << "=" << temp_file_1 << std::endl;
newstatefile << "FILENAME=" << file_name_2 << std::endl;
newstatefile << "POSITION." << file_name_2 << "=15" << std::endl;
newstatefile << "CURRENT." << file_name_2 << "=" << temp_file_2 << std::endl;
newstatefile.close();
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains(file_name_1.substr(0, file_name_1.rfind('.')) + ".14-34.txt"));
REQUIRE(LogTestController::getInstance().contains(file_name_2.substr(0, file_name_2.rfind('.')) + ".15-34.txt"));
std::unordered_map<std::string, std::string> state;
REQUIRE(plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->get(state));
std::string filePath1, filePath2, fileName1, fileName2;
REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file_1, filePath1, fileName1));
REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file_2, filePath2, fileName2));
std::unordered_map<std::string, std::string> expected_state{{"file.0.name", fileName1},
{"file.0.position", "35"},
{"file.0.current", temp_file_1},
{"file.0.checksum", "1404369522"},
{"file.1.name", fileName2},
{"file.1.position", "35"},
{"file.1.current", temp_file_2},
{"file.1.checksum", "2289158555"}};
for (const auto& key_value_pair : expected_state) {
const auto it = state.find(key_value_pair.first);
REQUIRE(it != state.end());
REQUIRE(it->second == key_value_pair.second);
}
REQUIRE(state.find("file.0.last_read_time") != state.end());
REQUIRE(state.find("file.1.last_read_time") != state.end());
}
}
TEST_CASE("TailFile picks up the new File to Tail if it is changed between runs", "[state]") {
TestController testController;
LogTestController::getInstance().setDebug<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tail_file = plan->addProcessor("TailFile", "tail_file");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> log_attribute = plan->addProcessor("LogAttribute", "log_attribute", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
char format[] = "/tmp/gt.XXXXXX";
std::string directory = testController.createTempDirectory(format);
std::string first_test_file = createTempFile(directory, "first.log", "my first log line\n");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), first_test_file);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.0-17.log"));
SECTION("The new file gets picked up") {
std::string second_test_file = createTempFile(directory, "second.log", "my second log line\n");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), second_test_file);
plan->reset(true); // clear the memory, but keep the state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:second.0-18.log"));
}
SECTION("The old file will no longer be tailed") {
appendTempFile(directory, "first.log", "add some more stuff\n");
std::string second_test_file = createTempFile(directory, "second.log", "");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), second_test_file);
plan->reset(true); // clear the memory, but keep the state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 0 flow files"));
}
}
TEST_CASE("TailFile picks up the new File to Tail if it is changed between runs (multiple file mode)", "[state][multiple_file]") {
TestController testController;
LogTestController::getInstance().setDebug<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
std::string directory = testController.createTempDirectory(format);
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tail_file = plan->addProcessor("TailFile", "tail_file");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), directory);
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "first\\..*\\.log");
std::shared_ptr<core::Processor> log_attribute = plan->addProcessor("LogAttribute", "log_attribute", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
createTempFile(directory, "first.fruit.log", "apple\n");
createTempFile(directory, "second.fruit.log", "orange\n");
createTempFile(directory, "first.animal.log", "hippopotamus\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.0-5.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.animal.0-12.log"));
appendTempFile(directory, "first.fruit.log", "banana\n");
appendTempFile(directory, "first.animal.log", "hedgehog\n");
SECTION("If a file no longer matches the new regex, then we stop tailing it") {
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "first\\.f.*\\.log");
plan->reset(true); // clear the memory, but keep the state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.6-12.log"));
}
SECTION("If a new file matches the new regex, we start tailing it") {
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.fruit\\.log");
plan->reset(true); // clear the memory, but keep the state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.6-12.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:second.fruit.0-6.log"));
}
}
TEST_CASE("TailFile finds the single input file in both Single and Multiple mode", "[simple]") {
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "");
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
SECTION("Single") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
}
SECTION("Multiple") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-.*\\.txt");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
}
testController.runSession(plan, false);
auto records = plan->getProvenanceRecords();
REQUIRE(records.size() == 2);
testController.runSession(plan, false);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files"));
REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(NEWLINE_FILE.size()) + " Offset:0"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile picks up new files created between runs", "[multiple_file]") {
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
createTempFile(dir, "application.log", "line1\nline2\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
createTempFile(dir, "another.log", "some more content\n");
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile can handle input files getting removed", "[multiple_file]") {
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute",
core::Relationship("success", "description"),
true);
plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
createTempFile(dir, "one.log", "line one\n");
createTempFile(dir, "two.log", "some stuff\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
appendTempFile(dir, "one.log", "line two\nline three\nline four\n");
removeFile(dir, "two.log");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile processes a very long line correctly", "[simple]") {
std::string line1("foo\n");
std::string line2(8050, 0);
std::mt19937 gen(std::random_device{}()); // NOLINT (linter wants a space before '{')
std::generate_n(line2.begin(), line2.size() - 1, [&]() -> char {
return 32 + gen() % (127 - 32);
});
line2.back() = '\n';
std::string line3("bar\n");
std::string line4("buzz");
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
LogTestController::getInstance().setTrace<core::ProcessSession>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << line1 << line2 << line3 << line4;
tmpfile.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
plan->setProperty(log_attr, processors::LogAttribute::HexencodePayload.getName(), "true");
uint32_t line_length = 0U;
SECTION("with line length 80") {
line_length = 80U;
}
SECTION("with line length 200") {
line_length = 200U;
plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "200");
}
SECTION("with line length 0") {
line_length = 0U;
plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "0");
}
SECTION("with line length 16") {
line_length = 16U;
plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "16");
}
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line1)));
auto line2_hex = utils::StringUtils::to_hex(line2);
if (line_length == 0U) {
REQUIRE(LogTestController::getInstance().contains(line2_hex));
} else {
std::stringstream line2_hex_lines;
for (size_t i = 0; i < line2_hex.size(); i += line_length) {
line2_hex_lines << line2_hex.substr(i, line_length) << '\n';
}
REQUIRE(LogTestController::getInstance().contains(line2_hex_lines.str()));
}
REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line3)));
REQUIRE(false == LogTestController::getInstance().contains(utils::StringUtils::to_hex(line4), std::chrono::seconds(0)));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile processes a long line followed by multiple newlines correctly", "[simple][edge_case]") {
// Test having two delimiters on the buffer boundary
std::string line1(4098, '\n');
std::mt19937 gen(std::random_device { }());
std::generate_n(line1.begin(), 4095, [&]() -> char {
return 32 + gen() % (127 - 32);
});
std::string line2("foo\n");
std::string line3("bar\n");
std::string line4("buzz");
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
LogTestController::getInstance().setTrace<core::ProcessSession>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << line1 << line2 << line3 << line4;
tmpfile.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
plan->setProperty(log_attr, processors::LogAttribute::HexencodePayload.getName(), "true");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 5 flow files"));
auto line1_hex = utils::StringUtils::to_hex(line1.substr(0, 4096));
std::stringstream line1_hex_lines;
for (size_t i = 0; i < line1_hex.size(); i += 80) {
line1_hex_lines << line1_hex.substr(i, 80) << '\n';
}
REQUIRE(LogTestController::getInstance().contains(line1_hex_lines.str()));
REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line2)));
REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line3)));
REQUIRE(false == LogTestController::getInstance().contains(utils::StringUtils::to_hex(line4), std::chrono::seconds(0)));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile onSchedule throws if file(s) to tail cannot be determined", "[configuration]") {
TestController testController;
LogTestController::getInstance().setDebug<minifi::processors::TailFile>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
SECTION("Single file mode by default") {
SECTION("No FileName") {
}
SECTION("FileName does not contain the path") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-log.txt");
}
}
SECTION("Explicit Single file mode") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Single file");
SECTION("No FileName") {
}
SECTION("FileName does not contain the path") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-log.txt");
}
}
SECTION("Multiple file mode") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
SECTION("No FileName and no BaseDirectory") {
}
SECTION("No BaseDirectory") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-.*\\.txt");
}
}
REQUIRE_THROWS(plan->runNextProcessor());
}
TEST_CASE("TailFile onSchedule throws in Multiple mode if the Base Directory does not exist", "[configuration][multiple_file]") {
TestController testController;
LogTestController::getInstance().setDebug<minifi::processors::TailFile>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
plan->setProperty(tailfile, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, processors::TailFile::FileName.getName(), ".*\\.log");
SECTION("No Base Directory is set") {
REQUIRE_THROWS(plan->runNextProcessor());
}
SECTION("Base Directory is set, but does not exist") {
std::string nonexistent_file_name{"/no-such-directory/688b01d0-9e5f-11ea-820d-f338c34d39a1/31d1a81a-9e5f-11ea-a77b-8b27d514a452"};
plan->setProperty(tailfile, processors::TailFile::BaseDirectory.getName(), nonexistent_file_name);
REQUIRE_THROWS(plan->runNextProcessor());
}
SECTION("Base Directory is set and it exists") {
char format[] = "/tmp/gt.XXXXXX";
std::string directory = testController.createTempDirectory(format);
plan->setProperty(tailfile, processors::TailFile::BaseDirectory.getName(), directory);
plan->setProperty(tailfile, processors::TailFile::LookupFrequency.getName(), "0 sec");
REQUIRE_NOTHROW(plan->runNextProcessor());
}
}
TEST_CASE("TailFile finds and finishes the renamed file and continues with the new log file", "[rotation]") {
TestController testController;
const char DELIM = ',';
size_t expected_pieces = std::count(NEWLINE_FILE.begin(), NEWLINE_FILE.end(), DELIM); // The last piece is left as considered unfinished
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
auto plan = testController.createPlan();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::string in_file = dir + utils::file::FileUtils::get_separator() + "testfifo.txt";
std::ofstream in_file_stream(in_file, std::ios::out | std::ios::binary);
in_file_stream << NEWLINE_FILE;
in_file_stream.flush();
// Build MiNiFi processing graph
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), std::string(1, DELIM));
SECTION("single") {
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), in_file);
}
SECTION("Multiple") {
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "testfifo.txt");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
}
auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
// Log as many FFs as it can to make sure exactly the expected amount is produced
plan->runNextProcessor(); // Tail
plan->runNextProcessor(); // Log
REQUIRE(LogTestController::getInstance().contains(std::string("Logged ") + std::to_string(expected_pieces) + " flow files"));
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // make sure the new file gets newer modification time
in_file_stream << DELIM;
in_file_stream.close();
std::string rotated_file = (in_file + ".1");
REQUIRE(rename(in_file.c_str(), rotated_file.c_str()) == 0);
std::ofstream new_in_file_stream(in_file, std::ios::out | std::ios::binary);
new_in_file_stream << "five" << DELIM << "six" << DELIM;
new_in_file_stream.close();
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
plan->runNextProcessor(); // Tail
plan->runNextProcessor(); // Log
// Find the last flow file in the rotated file, and then pick up the new file
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.txt.28-34.1"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.0-4.txt"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.5-8.txt"));
}
TEST_CASE("TailFile finds and finishes multiple rotated files and continues with the new log file", "[rotation]") {
TestController testController;
const char DELIM = ':';
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
auto plan = testController.createPlan();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::string test_file = dir + utils::file::FileUtils::get_separator() + "fruits.log";
std::ofstream test_file_stream_0(test_file, std::ios::binary);
test_file_stream_0 << "Apple" << DELIM << "Orange" << DELIM;
test_file_stream_0.flush();
// Build MiNiFi processing graph
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), std::string(1, DELIM));
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file);
auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0-5.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.6-12.log"));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
test_file_stream_0 << "Pear" << DELIM;
test_file_stream_0.close();
std::string first_rotated_file = dir + utils::file::FileUtils::get_separator() + "fruits.0.log";
REQUIRE(rename(test_file.c_str(), first_rotated_file.c_str()) == 0);
std::ofstream test_file_stream_1(test_file, std::ios::binary);
test_file_stream_1 << "Pineapple" << DELIM << "Kiwi" << DELIM;
test_file_stream_1.close();
std::string second_rotated_file = dir + utils::file::FileUtils::get_separator() + "fruits.1.log";
REQUIRE(rename(test_file.c_str(), second_rotated_file.c_str()) == 0);
std::ofstream test_file_stream_2(test_file, std::ios::binary);
test_file_stream_2 << "Apricot" << DELIM;
test_file_stream_2.close();
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 4 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0.13-17.log")); // Pear
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.1.0-9.log")); // Pineapple
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.1.10-14.log")); // Kiwi
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0-7.log")); // Apricot
}
TEST_CASE("TailFile ignores old rotated files", "[rotation]") {
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
const std::string dir = testController.createTempDirectory(format);
std::string log_file_name = dir + utils::file::FileUtils::get_separator() + "test.log";
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), log_file_name);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute",
core::Relationship("success", "description"),
true);
plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
createTempFile(dir, "test.2019-08-20", "line1\nline2\nline3\nline4\n"); // very old rotated file
std::this_thread::sleep_for(std::chrono::seconds(1));
createTempFile(dir, "test.log", "line5\nline6\nline7\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
REQUIRE(!LogTestController::getInstance().contains("key:filename value:test.2019-08-20"));
std::string rotated_log_file_name = dir + utils::file::FileUtils::get_separator() + "test.2020-05-18";
REQUIRE(rename(log_file_name.c_str(), rotated_log_file_name.c_str()) == 0);
createTempFile(dir, "test.log", "line8\nline9\n");
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(!LogTestController::getInstance().contains("key:filename value:test.2019-08-20"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile rotation works with multiple input files", "[rotation][multiple_file]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
auto plan = testController.createPlan();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
createTempFile(dir, "fruit.log", "apple\npear\nbanana\n");
createTempFile(dir, "animal.log", "bear\ngiraffe\n");
createTempFile(dir, "color.log", "red\nblue\nyellow\npurple\n");
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged " + std::to_string(3 + 2 + 4) + " flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.0-5.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.6-10.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.11-17.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.0-4.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.5-12.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.0-3.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.4-8.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.9-15.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.16-22.log"));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
appendTempFile(dir, "fruit.log", "orange\n");
appendTempFile(dir, "animal.log", "axolotl\n");
appendTempFile(dir, "color.log", "aquamarine\n");
renameTempFile(dir, "fruit.log", "fruit.0");
renameTempFile(dir, "animal.log", "animal.0");
createTempFile(dir, "fruit.log", "peach\n");
createTempFile(dir, "animal.log", "dinosaur\n");
appendTempFile(dir, "color.log", "turquoise\n");
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 6 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.18-24.0"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.0-5.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.13-20.0"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.0-8.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.23-33.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.34-43.log"));
}
TEST_CASE("TailFile handles the Rolling Filename Pattern property correctly", "[rotation]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
auto plan = testController.createPlan();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::string test_file = createTempFile(dir, "test.log", "some stuff\n");
// Build MiNiFi processing graph
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file);
std::vector<std::string> expected_log_lines;
SECTION("If no pattern is set, we use the default, which is ${filename}.*, so the unrelated file will be picked up") {
expected_log_lines = std::vector<std::string>{"Logged 2 flow files",
"test.rolled.11-24.log",
"test.0-15.txt"};
}
SECTION("If a pattern is set to exclude the unrelated file, we no longer pick it up") {
plan->setProperty(tail_file, processors::TailFile::RollingFilenamePattern.getName(), "${filename}.*.log");
expected_log_lines = std::vector<std::string>{"Logged 1 flow file",
"test.rolled.11-24.log"};
}
SECTION("We can also set the pattern to not include the file name") {
plan->setProperty(tail_file, processors::TailFile::RollingFilenamePattern.getName(), "other_roll??.log");
expected_log_lines = std::vector<std::string>{"Logged 1 flow file",
"other_rolled.11-24.log"};
}
auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-10.log"));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
appendTempFile(dir, "test.log", "one more line\n");
renameTempFile(dir, "test.log", "test.rolled.log");
createTempFile(dir, "test.txt", "unrelated stuff\n");
createTempFile(dir, "other_rolled.log", "some stuff\none more line\n"); // same contents as test.rolled.log
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
for (const auto &log_line : expected_log_lines) {
REQUIRE(LogTestController::getInstance().contains(log_line));
}
}
TEST_CASE("TailFile finds and finishes the renamed file and continues with the new log file after a restart", "[rotation][restart]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char log_dir_format[] = "/tmp/gt.XXXXXX";
auto log_dir = testController.createTempDirectory(log_dir_format);
std::string test_file_1 = createTempFile(log_dir, "test.1", "line one\nline two\nline three\n"); // old rotated file
std::this_thread::sleep_for(std::chrono::seconds(1));
std::string test_file = createTempFile(log_dir, "test.log", "line four\nline five\nline six\n"); // current log file
char state_dir_format[] = "/tmp/gt.XXXXXX";
auto state_dir = testController.createTempDirectory(state_dir_format);
utils::Identifier tail_file_uuid = utils::IdGenerator::getIdGenerator()->generate();
const core::Relationship success_relationship{"success", "everything is fine"};
{
auto test_plan = testController.createPlan(nullptr, state_dir.c_str());
auto tail_file = test_plan->addProcessor("TailFile", tail_file_uuid, "Tail", {success_relationship});
test_plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file);
auto log_attr = test_plan->addProcessor("LogAttribute", "Log", success_relationship, true);
test_plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
test_plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
testController.runSession(test_plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
}
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
appendTempFile(log_dir, "test.log", "line seven\n");
renameTempFile(log_dir, "test.1", "test.2");
renameTempFile(log_dir, "test.log", "test.1");
createTempFile(log_dir, "test.log", "line eight is the last line\n");
{
auto test_plan = testController.createPlan(nullptr, state_dir.c_str());
auto tail_file = test_plan->addProcessor("TailFile", tail_file_uuid, "Tail", {success_relationship});
test_plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file);
auto log_attr = test_plan->addProcessor("LogAttribute", "Log", success_relationship, true);
test_plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
test_plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
testController.runSession(test_plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.29-39.1"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-27.log"));
}
}
TEST_CASE("TailFile yields if no work is done", "[yield]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), temp_directory);
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
SECTION("Empty log file => yield") {
createTempFile(temp_directory, "first.log", "");
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
SECTION("No logging happened between onTrigger calls => yield") {
plan->reset();
tail_file->clearYield();
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
}
SECTION("Some logging happened between onTrigger calls => don't yield") {
plan->reset();
tail_file->clearYield();
appendTempFile(temp_directory, "first.log", "stuff stuff\nand stuff\n");
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
}
SECTION("Non-empty log file => don't yield") {
createTempFile(temp_directory, "second.log", "some content\n");
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
SECTION("No logging happened between onTrigger calls => yield") {
plan->reset();
tail_file->clearYield();
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
}
SECTION("Some logging happened between onTrigger calls => don't yield") {
plan->reset();
tail_file->clearYield();
appendTempFile(temp_directory, "second.log", "stuff stuff\nand stuff\n");
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
}
}
TEST_CASE("TailFile yields if no work is done on any files", "[yield][multiple_file]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), temp_directory);
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
createTempFile(temp_directory, "first.log", "stuff\n");
createTempFile(temp_directory, "second.log", "different stuff\n");
createTempFile(temp_directory, "third.log", "stuff stuff\n");
testController.runSession(plan, true);
plan->reset();
tail_file->clearYield();
SECTION("No file changed => yield") {
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
}
SECTION("One file changed => don't yield") {
SECTION("first") { appendTempFile(temp_directory, "first.log", "more stuff\n"); }
SECTION("second") { appendTempFile(temp_directory, "second.log", "more stuff\n"); }
SECTION("third") { appendTempFile(temp_directory, "third.log", "more stuff\n"); }
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
SECTION("More than one file changed => don't yield") {
SECTION("first and third") {
appendTempFile(temp_directory, "first.log", "more stuff\n");
appendTempFile(temp_directory, "third.log", "more stuff\n");
}
SECTION("all of them") {
appendTempFile(temp_directory, "first.log", "more stuff\n");
appendTempFile(temp_directory, "second.log", "more stuff\n");
appendTempFile(temp_directory, "third.log", "more stuff\n");
}
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
}
TEST_CASE("TailFile doesn't yield if work was done on rotated files only", "[yield][rotation]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
std::string full_file_name = createTempFile(temp_directory, "test.log", "stuff\n");
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name);
testController.runSession(plan, true);
plan->reset();
tail_file->clearYield();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
SECTION("File rotated but not written => yield") {
renameTempFile(temp_directory, "test.log", "test.1");
SECTION("Don't create empty new log file") {
}
SECTION("Create empty new log file") {
createTempFile(temp_directory, "test.log", "");
}
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
}
SECTION("File rotated and new stuff is added => don't yield") {
SECTION("New content before rotation") {
appendTempFile(temp_directory, "test.log", "more stuff\n");
}
renameTempFile(temp_directory, "test.log", "test.1");
SECTION("New content after rotation") {
createTempFile(temp_directory, "test.log", "even more stuff\n");
}
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
}
TEST_CASE("TailFile handles the Delimiter setting correctly", "[delimiter]") {
std::vector<std::pair<std::string, std::string>> test_cases = {
// first = value of Delimiter in the config
// second = the expected delimiter char which will be used
{"", ""}, {",", ","}, {"\t", "\t"}, {"\\t", "\t"}, {"\n", "\n"}, {"\\n", "\n"}, {"\\", "\\"}, {"\\\\", "\\"}};
for (const auto &test_case : test_cases) {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
std::string delimiter = test_case.second;
std::string full_file_name = createTempFile(temp_directory, "test.log", "one" + delimiter + "two" + delimiter);
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), test_case.first);
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name);
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
if (delimiter.empty()) {
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-5.log"));
} else {
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-3.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.4-7.log"));
}
}
}
TEST_CASE("TailFile handles Unix/Windows line endings correctly", "[simple]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
std::string full_file_name = createTempFile(temp_directory, "test.log", "line1\nline two\n", std::ios::out); // write in text mode
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name);
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
#ifdef WIN32
std::size_t line_ending_size = 2;
#else
std::size_t line_ending_size = 1;
#endif
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(5 + line_ending_size) + " Offset:0"));
REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(8 + line_ending_size) + " Offset:0"));
}
TEST_CASE("TailFile can tail all files in a directory recursively", "[multiple]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
std::string base_directory = testController.createTempDirectory(format);
std::string directory1 = base_directory + utils::file::FileUtils::get_separator() + "one";
utils::file::FileUtils::create_dir(directory1);
std::string directory11 = directory1 + utils::file::FileUtils::get_separator() + "one_child";
utils::file::FileUtils::create_dir(directory11);
std::string directory2 = base_directory + utils::file::FileUtils::get_separator() + "two";
utils::file::FileUtils::create_dir(directory2);
createTempFile(base_directory, "test.orange.log", "orange juice\n");
createTempFile(directory1, "test.blue.log", "blue\n");
createTempFile(directory1, "test.orange.log", "orange autumn leaves\n");
createTempFile(directory11, "test.camel.log", "camel\n");
createTempFile(directory2, "test.triangle.log", "triangle\n");
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), base_directory);
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
plan->setProperty(log_attribute, processors::LogAttribute::LogPayload.getName(), "true");
SECTION("Recursive lookup not set => defaults to false") {
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
}
SECTION("Recursive lookup set to false") {
plan->setProperty(tail_file, processors::TailFile::RecursiveLookup.getName(), "false");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
}
SECTION("Recursive lookup set to true") {
plan->setProperty(tail_file, processors::TailFile::RecursiveLookup.getName(), "true");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 5 flow files"));
}
}
TEST_CASE("TailFile interprets the lookup frequency property correctly", "[multiple]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
std::string directory = testController.createTempDirectory(format);
createTempFile(directory, "test.red.log", "cherry\n");
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), directory);
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
SECTION("Lookup frequency not set => defaults to 10 minutes") {
std::shared_ptr<processors::TailFile> tail_file_processor = std::dynamic_pointer_cast<processors::TailFile>(tail_file);
REQUIRE(tail_file_processor);
REQUIRE(tail_file_processor->getLookupFrequency() == std::chrono::minutes{10});
}
SECTION("Lookup frequency set to zero => new files are picked up immediately") {
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->reset(true);
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
createTempFile(directory, "test.blue.log", "sky\n");
createTempFile(directory, "test.green.log", "grass\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
}
SECTION("Lookup frequency set to 10 ms => new files are only picked up after 10 ms") {
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "10 ms");
plan->reset(true);
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
createTempFile(directory, "test.blue.log", "sky\n");
createTempFile(directory, "test.green.log", "grass\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 0 flow files"));
plan->reset(false);
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
std::this_thread::sleep_for(std::chrono::milliseconds(11));
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
}
}
| 47.054404 | 155 | 0.710111 | nghiaxlee |
66ea13aa778e838ccbb81d1729c4b485d3927fd3 | 27,043 | cpp | C++ | src/WtBtCore/HftMocker.cpp | v1otusc/wondertrader | fd65a052d26be32882f89e8e9dfcd1d7b8736a3b | [
"MIT"
] | null | null | null | src/WtBtCore/HftMocker.cpp | v1otusc/wondertrader | fd65a052d26be32882f89e8e9dfcd1d7b8736a3b | [
"MIT"
] | 1 | 2022-03-21T06:51:59.000Z | 2022-03-21T06:51:59.000Z | src/WtBtCore/HftMocker.cpp | v1otusc/wondertrader | fd65a052d26be32882f89e8e9dfcd1d7b8736a3b | [
"MIT"
] | null | null | null | /*!
* \file HftMocker.cpp
* \project WonderTrader
*
* \author Wesley
* \date 2020/03/30
*
* \brief
*/
#include "HftMocker.h"
#include "WtHelper.h"
#include <stdarg.h>
#include <boost/filesystem.hpp>
#include "../Includes/WTSVariant.hpp"
#include "../Includes/WTSContractInfo.hpp"
#include "../Share/decimal.h"
#include "../Share/TimeUtils.hpp"
#include "../Share/StrUtil.hpp"
#include "../WTSTools/WTSLogger.h"
uint32_t makeLocalOrderID()
{
static std::atomic<uint32_t> _auto_order_id{ 0 };
if (_auto_order_id == 0)
{
uint32_t curYear = TimeUtils::getCurDate() / 10000 * 10000 + 101;
_auto_order_id = (uint32_t)((TimeUtils::getLocalTimeNow() - TimeUtils::makeTime(curYear, 0)) / 1000 * 50);
}
return _auto_order_id.fetch_add(1);
}
std::vector<uint32_t> splitVolume(uint32_t vol)
{
if (vol == 0) return std::move(std::vector<uint32_t>());
uint32_t minQty = 1;
uint32_t maxQty = 100;
uint32_t length = maxQty - minQty + 1;
std::vector<uint32_t> ret;
if (vol <= minQty)
{
ret.emplace_back(vol);
}
else
{
uint32_t left = vol;
srand((uint32_t)time(NULL));
while (left > 0)
{
uint32_t curVol = minQty + (uint32_t)rand() % length;
if (curVol >= left)
curVol = left;
if (curVol == 0)
continue;
ret.emplace_back(curVol);
left -= curVol;
}
}
return std::move(ret);
}
std::vector<double> splitVolume(double vol, double minQty = 1.0, double maxQty = 100.0, double qtyTick = 1.0)
{
auto length = (std::size_t)round((maxQty - minQty)/qtyTick) + 1;
std::vector<double> ret;
if (vol <= minQty)
{
ret.emplace_back(vol);
}
else
{
double left = vol;
srand((uint32_t)time(NULL));
while (left > 0)
{
double curVol = minQty + (rand() % length)*qtyTick;
if (curVol >= left)
curVol = left;
if (curVol == 0)
continue;
ret.emplace_back(curVol);
left -= curVol;
}
}
return std::move(ret);
}
uint32_t genRand(uint32_t maxVal = 10000)
{
srand(TimeUtils::getCurMin());
return rand() % maxVal;
}
inline uint32_t makeHftCtxId()
{
static std::atomic<uint32_t> _auto_context_id{ 6000 };
return _auto_context_id.fetch_add(1);
}
HftMocker::HftMocker(HisDataReplayer* replayer, const char* name)
: IHftStraCtx(name)
, _replayer(replayer)
, _strategy(NULL)
, _thrd(NULL)
, _stopped(false)
, _use_newpx(false)
, _error_rate(0)
, _has_hook(false)
, _hook_valid(true)
, _resumed(false)
{
_commodities = CommodityMap::create();
_context_id = makeHftCtxId();
}
HftMocker::~HftMocker()
{
if(_strategy)
{
_factory._fact->deleteStrategy(_strategy);
}
_commodities->release();
}
void HftMocker::procTask()
{
if (_tasks.empty())
{
return;
}
_mtx_control.lock();
while (!_tasks.empty())
{
Task& task = _tasks.front();
task();
{
std::unique_lock<std::mutex> lck(_mtx);
_tasks.pop();
}
}
_mtx_control.unlock();
}
void HftMocker::postTask(Task task)
{
{
std::unique_lock<std::mutex> lck(_mtx);
_tasks.push(task);
return;
}
if(_thrd == NULL)
{
_thrd.reset(new std::thread([this](){
while (!_stopped)
{
if(_tasks.empty())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
_mtx_control.lock();
while(!_tasks.empty())
{
Task& task = _tasks.front();
task();
{
std::unique_lock<std::mutex> lck(_mtx);
_tasks.pop();
}
}
_mtx_control.unlock();
}
}));
}
}
bool HftMocker::init_hft_factory(WTSVariant* cfg)
{
if (cfg == NULL)
return false;
const char* module = cfg->getCString("module");
_use_newpx = cfg->getBoolean("use_newpx");
_error_rate = cfg->getUInt32("error_rate");
DllHandle hInst = DLLHelper::load_library(module);
if (hInst == NULL)
return false;
FuncCreateHftStraFact creator = (FuncCreateHftStraFact)DLLHelper::get_symbol(hInst, "createStrategyFact");
if (creator == NULL)
{
DLLHelper::free_library(hInst);
return false;
}
_factory._module_inst = hInst;
_factory._module_path = module;
_factory._creator = creator;
_factory._remover = (FuncDeleteHftStraFact)DLLHelper::get_symbol(hInst, "deleteStrategyFact");
_factory._fact = _factory._creator();
WTSVariant* cfgStra = cfg->get("strategy");
if(cfgStra)
{
_strategy = _factory._fact->createStrategy(cfgStra->getCString("name"), "hft");
_strategy->init(cfgStra->get("params"));
}
return true;
}
void HftMocker::handle_tick(const char* stdCode, WTSTickData* curTick)
{
on_tick(stdCode, curTick);
}
void HftMocker::handle_order_detail(const char* stdCode, WTSOrdDtlData* curOrdDtl)
{
on_order_detail(stdCode, curOrdDtl);
}
void HftMocker::handle_order_queue(const char* stdCode, WTSOrdQueData* curOrdQue)
{
on_order_queue(stdCode, curOrdQue);
}
void HftMocker::handle_transaction(const char* stdCode, WTSTransData* curTrans)
{
on_transaction(stdCode, curTrans);
}
void HftMocker::handle_bar_close(const char* stdCode, const char* period, uint32_t times, WTSBarStruct* newBar)
{
on_bar(stdCode, period, times, newBar);
}
void HftMocker::handle_init()
{
on_init();
on_channel_ready();
}
void HftMocker::handle_schedule(uint32_t uDate, uint32_t uTime)
{
//on_schedule(uDate, uTime);
}
void HftMocker::handle_session_begin(uint32_t curTDate)
{
on_session_begin(curTDate);
}
void HftMocker::handle_session_end(uint32_t curTDate)
{
on_session_end(curTDate);
}
void HftMocker::handle_replay_done()
{
dump_outputs();
this->on_bactest_end();
}
void HftMocker::on_bar(const char* stdCode, const char* period, uint32_t times, WTSBarStruct* newBar)
{
if (_strategy)
_strategy->on_bar(this, stdCode, period, times, newBar);
}
void HftMocker::enable_hook(bool bEnabled /* = true */)
{
_hook_valid = bEnabled;
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calculating hook %s", bEnabled ? "enabled" : "disabled");
}
void HftMocker::install_hook()
{
_has_hook = true;
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "HFT hook installed");
}
void HftMocker::step_tick()
{
if (!_has_hook)
return;
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Notify calc thread, wait for calc done");
while (!_resumed)
_cond_calc.notify_all();
{
StdUniqueLock lock(_mtx_calc);
_cond_calc.wait(_mtx_calc);
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc done notified");
_resumed = false;
}
}
void HftMocker::on_tick(const char* stdCode, WTSTickData* newTick)
{
_price_map[stdCode] = newTick->price();
{
std::unique_lock<std::recursive_mutex> lck(_mtx_control);
}
update_dyn_profit(stdCode, newTick);
procTask();
if (!_orders.empty())
{
OrderIDs ids;
for (auto it = _orders.begin(); it != _orders.end(); it++)
{
uint32_t localid = it->first;
bool bNeedErase = procOrder(localid);
if (bNeedErase)
ids.emplace_back(localid);
}
for(uint32_t localid : ids)
{
auto it = _orders.find(localid);
_orders.erase(it);
}
}
if (_has_hook && _hook_valid)
{
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Waiting for resume notify");
StdUniqueLock lock(_mtx_calc);
_cond_calc.wait(_mtx_calc);
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc resumed");
_resumed = true;
}
on_tick_updated(stdCode, newTick);
if (_has_hook && _hook_valid)
{
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc done, notify control thread");
while (_resumed)
_cond_calc.notify_all();
}
}
void HftMocker::on_tick_updated(const char* stdCode, WTSTickData* newTick)
{
auto it = _tick_subs.find(stdCode);
if (it == _tick_subs.end())
return;
if (_strategy)
_strategy->on_tick(this, stdCode, newTick);
}
void HftMocker::on_order_queue(const char* stdCode, WTSOrdQueData* newOrdQue)
{
on_ordque_updated(stdCode, newOrdQue);
}
void HftMocker::on_ordque_updated(const char* stdCode, WTSOrdQueData* newOrdQue)
{
if (_strategy)
_strategy->on_order_queue(this, stdCode, newOrdQue);
}
void HftMocker::on_order_detail(const char* stdCode, WTSOrdDtlData* newOrdDtl)
{
on_orddtl_updated(stdCode, newOrdDtl);
}
void HftMocker::on_orddtl_updated(const char* stdCode, WTSOrdDtlData* newOrdDtl)
{
if (_strategy)
_strategy->on_order_detail(this, stdCode, newOrdDtl);
}
void HftMocker::on_transaction(const char* stdCode, WTSTransData* newTrans)
{
on_trans_updated(stdCode, newTrans);
}
void HftMocker::on_trans_updated(const char* stdCode, WTSTransData* newTrans)
{
if (_strategy)
_strategy->on_transaction(this, stdCode, newTrans);
}
uint32_t HftMocker::id()
{
return _context_id;
}
void HftMocker::on_init()
{
if (_strategy)
_strategy->on_init(this);
}
void HftMocker::on_session_begin(uint32_t curTDate)
{
//每个交易日开始,要把冻结持仓置零
for (auto& it : _pos_map)
{
const char* stdCode = it.first.c_str();
PosInfo& pInfo = (PosInfo&)it.second;
if (!decimal::eq(pInfo._frozen, 0))
{
log_debug("%.0f of %s frozen released on %u", pInfo._frozen, stdCode, curTDate);
pInfo._frozen = 0;
}
}
if (_strategy)
_strategy->on_session_begin(this, curTDate);
}
void HftMocker::on_session_end(uint32_t curTDate)
{
uint32_t curDate = curTDate;// _replayer->get_trading_date();
double total_profit = 0;
double total_dynprofit = 0;
for (auto it = _pos_map.begin(); it != _pos_map.end(); it++)
{
const char* stdCode = it->first.c_str();
const PosInfo& pInfo = it->second;
total_profit += pInfo._closeprofit;
total_dynprofit += pInfo._dynprofit;
}
_fund_logs << StrUtil::printf("%d,%.2f,%.2f,%.2f,%.2f\n", curDate,
_fund_info._total_profit, _fund_info._total_dynprofit,
_fund_info._total_profit + _fund_info._total_dynprofit - _fund_info._total_fees, _fund_info._total_fees);
if (_strategy)
_strategy->on_session_end(this, curTDate);
}
double HftMocker::stra_get_undone(const char* stdCode)
{
double ret = 0;
for (auto it = _orders.begin(); it != _orders.end(); it++)
{
const OrderInfo& ordInfo = it->second;
if (strcmp(ordInfo._code, stdCode) == 0)
{
ret += ordInfo._left * ordInfo._isBuy ? 1 : -1;
}
}
return ret;
}
bool HftMocker::stra_cancel(uint32_t localid)
{
postTask([this, localid](){
auto it = _orders.find(localid);
if (it == _orders.end())
return;
StdLocker<StdRecurMutex> lock(_mtx_ords);
OrderInfo& ordInfo = (OrderInfo&)it->second;
ordInfo._left = 0;
on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, true, ordInfo._usertag);
_orders.erase(it);
});
return true;
}
OrderIDs HftMocker::stra_cancel(const char* stdCode, bool isBuy, double qty /* = 0 */)
{
OrderIDs ret;
uint32_t cnt = 0;
for (auto it = _orders.begin(); it != _orders.end(); it++)
{
const OrderInfo& ordInfo = it->second;
if(ordInfo._isBuy == isBuy && strcmp(ordInfo._code, stdCode) == 0)
{
double left = ordInfo._left;
stra_cancel(it->first);
ret.emplace_back(it->first);
cnt++;
if (left < qty)
qty -= left;
else
break;
}
}
return ret;
}
OrderIDs HftMocker::stra_buy(const char* stdCode, double price, double qty, const char* userTag, int flag /* = 0 */)
{
WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode);
if (commInfo == NULL)
{
log_error("Cannot find corresponding commodity info of %s", stdCode);
return OrderIDs();
}
if (decimal::le(qty, 0))
{
log_error("Entrust error: qty {} <= 0", qty);
return OrderIDs();
}
uint32_t localid = makeLocalOrderID();
OrderInfo order;
order._localid = localid;
strcpy(order._code, stdCode);
strcpy(order._usertag, userTag);
order._isBuy = true;
order._price = price;
order._total = qty;
order._left = qty;
{
_mtx_ords.lock();
_orders[localid] = order;
_mtx_ords.unlock();
}
postTask([this, localid](){
const OrderInfo& ordInfo = _orders[localid];
on_entrust(localid, ordInfo._code, true, "下单成功", ordInfo._usertag);
});
OrderIDs ids;
ids.emplace_back(localid);
return ids;
}
void HftMocker::on_order(uint32_t localid, const char* stdCode, bool isBuy, double totalQty, double leftQty, double price, bool isCanceled /* = false */, const char* userTag /* = "" */)
{
if(_strategy)
_strategy->on_order(this, localid, stdCode, isBuy, totalQty, leftQty, price, isCanceled, userTag);
}
void HftMocker::on_trade(uint32_t localid, const char* stdCode, bool isBuy, double vol, double price, const char* userTag/* = ""*/)
{
const PosInfo& posInfo = _pos_map[stdCode];
double curPos = posInfo._volume + vol * (isBuy ? 1 : -1);
do_set_position(stdCode, curPos, price, userTag);
if (_strategy)
_strategy->on_trade(this, localid, stdCode, isBuy, vol, price, userTag);
}
void HftMocker::on_entrust(uint32_t localid, const char* stdCode, bool bSuccess, const char* message, const char* userTag/* = ""*/)
{
if (_strategy)
_strategy->on_entrust(localid, bSuccess, message, userTag);
}
void HftMocker::on_channel_ready()
{
if (_strategy)
_strategy->on_channel_ready(this);
}
void HftMocker::update_dyn_profit(const char* stdCode, WTSTickData* newTick)
{
auto it = _pos_map.find(stdCode);
if (it != _pos_map.end())
{
PosInfo& pInfo = (PosInfo&)it->second;
if (pInfo._volume == 0)
{
pInfo._dynprofit = 0;
}
else
{
bool isLong = decimal::gt(pInfo._volume, 0);
double price = isLong ? newTick->bidprice(0) : newTick->askprice(0);
WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode);
double dynprofit = 0;
for (auto pit = pInfo._details.begin(); pit != pInfo._details.end(); pit++)
{
DetailInfo& dInfo = *pit;
dInfo._profit = dInfo._volume*(price - dInfo._price)*commInfo->getVolScale()*(dInfo._long ? 1 : -1);
if (dInfo._profit > 0)
dInfo._max_profit = max(dInfo._profit, dInfo._max_profit);
else if (dInfo._profit < 0)
dInfo._max_loss = min(dInfo._profit, dInfo._max_loss);
dynprofit += dInfo._profit;
}
pInfo._dynprofit = dynprofit;
}
}
}
bool HftMocker::procOrder(uint32_t localid)
{
auto it = _orders.find(localid);
if (it == _orders.end())
return false;
StdLocker<StdRecurMutex> lock(_mtx_ords);
OrderInfo& ordInfo = (OrderInfo&)it->second;
//第一步,如果在撤单概率中,则执行撤单
if(_error_rate>0 && genRand(10000)<=_error_rate)
{
on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, true, ordInfo._usertag);
log_info("Random error order: %u", localid);
return true;
}
else
{
on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, false, ordInfo._usertag);
}
WTSTickData* curTick = stra_get_last_tick(ordInfo._code);
if (curTick == NULL)
return false;
double curPx = curTick->price();
double orderQty = ordInfo._isBuy ? curTick->askqty(0) : curTick->bidqty(0); //看对手盘的数量
if (decimal::eq(orderQty, 0.0))
return false;
if (!_use_newpx)
{
curPx = ordInfo._isBuy ? curTick->askprice(0) : curTick->bidprice(0);
//if (curPx == 0.0)
if(decimal::eq(curPx, 0.0))
{
curTick->release();
return false;
}
}
curTick->release();
//如果没有成交条件,则退出逻辑
if(!decimal::eq(ordInfo._price, 0.0))
{
if(ordInfo._isBuy && decimal::gt(curPx, ordInfo._price))
{
//买单,但是当前价大于限价,不成交
return false;
}
if (!ordInfo._isBuy && decimal::lt(curPx, ordInfo._price))
{
//卖单,但是当前价小于限价,不成交
return false;
}
}
/*
* 下面就要模拟成交了
*/
double maxQty = min(orderQty, ordInfo._left);
auto vols = splitVolume((uint32_t)maxQty);
for(uint32_t curQty : vols)
{
on_trade(ordInfo._localid, ordInfo._code, ordInfo._isBuy, curQty, curPx, ordInfo._usertag);
ordInfo._left -= curQty;
on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, false, ordInfo._usertag);
double curPos = stra_get_position(ordInfo._code);
_sig_logs << _replayer->get_date() << "." << _replayer->get_raw_time() << "." << _replayer->get_secs() << ","
<< (ordInfo._isBuy ? "+" : "-") << curQty << "," << curPos << "," << curPx << std::endl;
}
//if(ordInfo._left == 0)
if(decimal::eq(ordInfo._left, 0.0))
{
return true;
}
return false;
}
OrderIDs HftMocker::stra_sell(const char* stdCode, double price, double qty, const char* userTag, int flag /* = 0 */)
{
WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode);
if (commInfo == NULL)
{
log_error("Cannot find corresponding commodity info of %s", stdCode);
return OrderIDs();
}
if (decimal::le(qty, 0))
{
log_error("Entrust error: qty {} <= 0", qty);
return OrderIDs();
}
//如果不能做空,则要看可用持仓
if(!commInfo->canShort())
{
double curPos = stra_get_position(stdCode, true);//只读可用持仓
if(decimal::gt(qty, curPos))
{
log_error("No enough position of %s to sell", stdCode);
return OrderIDs();
}
}
uint32_t localid = makeLocalOrderID();
OrderInfo order;
order._localid = localid;
strcpy(order._code, stdCode);
strcpy(order._usertag, userTag);
order._isBuy = false;
order._price = price;
order._total = qty;
order._left = qty;
{
StdLocker<StdRecurMutex> lock(_mtx_ords);
_orders[localid] = order;
}
postTask([this, localid]() {
const OrderInfo& ordInfo = _orders[localid];
on_entrust(localid, ordInfo._code, true, "下单成功", ordInfo._usertag);
});
OrderIDs ids;
ids.emplace_back(localid);
return ids;
}
WTSCommodityInfo* HftMocker::stra_get_comminfo(const char* stdCode)
{
return _replayer->get_commodity_info(stdCode);
}
WTSKlineSlice* HftMocker::stra_get_bars(const char* stdCode, const char* period, uint32_t count)
{
std::string basePeriod = "";
uint32_t times = 1;
if (strlen(period) > 1)
{
basePeriod.append(period, 1);
times = strtoul(period + 1, NULL, 10);
}
else
{
basePeriod = period;
}
return _replayer->get_kline_slice(stdCode, basePeriod.c_str(), count, times);
}
WTSTickSlice* HftMocker::stra_get_ticks(const char* stdCode, uint32_t count)
{
return _replayer->get_tick_slice(stdCode, count);
}
WTSOrdQueSlice* HftMocker::stra_get_order_queue(const char* stdCode, uint32_t count)
{
return _replayer->get_order_queue_slice(stdCode, count);
}
WTSOrdDtlSlice* HftMocker::stra_get_order_detail(const char* stdCode, uint32_t count)
{
return _replayer->get_order_detail_slice(stdCode, count);
}
WTSTransSlice* HftMocker::stra_get_transaction(const char* stdCode, uint32_t count)
{
return _replayer->get_transaction_slice(stdCode, count);
}
WTSTickData* HftMocker::stra_get_last_tick(const char* stdCode)
{
return _replayer->get_last_tick(stdCode);
}
double HftMocker::stra_get_position(const char* stdCode, bool bOnlyValid/* = false*/)
{
const PosInfo& pInfo = _pos_map[stdCode];
if (bOnlyValid)
{
//这里理论上,只有多头才会进到这里
//其他地方要保证,空头持仓的话,_frozen要为0
return pInfo._volume - pInfo._frozen;
}
else
return pInfo._volume;
}
double HftMocker::stra_get_position_profit(const char* stdCode)
{
const PosInfo& pInfo = _pos_map[stdCode];
return pInfo._dynprofit;
}
double HftMocker::stra_get_price(const char* stdCode)
{
return _replayer->get_cur_price(stdCode);
}
uint32_t HftMocker::stra_get_date()
{
return _replayer->get_date();
}
uint32_t HftMocker::stra_get_time()
{
return _replayer->get_raw_time();
}
uint32_t HftMocker::stra_get_secs()
{
return _replayer->get_secs();
}
void HftMocker::stra_sub_ticks(const char* stdCode)
{
/*
* By Wesley @ 2022.03.01
* 主动订阅tick会在本地记一下
* tick数据回调的时候先检查一下
*/
_tick_subs.insert(stdCode);
_replayer->sub_tick(_context_id, stdCode);
}
void HftMocker::stra_sub_order_queues(const char* stdCode)
{
_replayer->sub_order_queue(_context_id, stdCode);
}
void HftMocker::stra_sub_order_details(const char* stdCode)
{
_replayer->sub_order_detail(_context_id, stdCode);
}
void HftMocker::stra_sub_transactions(const char* stdCode)
{
_replayer->sub_transaction(_context_id, stdCode);
}
void HftMocker::stra_log_info(const char* message)
{
WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_INFO, message);
}
void HftMocker::stra_log_debug(const char* message)
{
WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_DEBUG, message);
}
void HftMocker::stra_log_error(const char* message)
{
WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_ERROR, message);
}
const char* HftMocker::stra_load_user_data(const char* key, const char* defVal /*= ""*/)
{
auto it = _user_datas.find(key);
if (it != _user_datas.end())
return it->second.c_str();
return defVal;
}
void HftMocker::stra_save_user_data(const char* key, const char* val)
{
_user_datas[key] = val;
_ud_modified = true;
}
void HftMocker::dump_outputs()
{
std::string folder = WtHelper::getOutputDir();
folder += _name;
folder += "/";
boost::filesystem::create_directories(folder.c_str());
std::string filename = folder + "trades.csv";
std::string content = "code,time,direct,action,price,qty,fee,usertag\n";
content += _trade_logs.str();
StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size());
filename = folder + "closes.csv";
content = "code,direct,opentime,openprice,closetime,closeprice,qty,profit,maxprofit,maxloss,totalprofit,entertag,exittag\n";
content += _close_logs.str();
StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size());
filename = folder + "funds.csv";
content = "date,closeprofit,positionprofit,dynbalance,fee\n";
content += _fund_logs.str();
StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size());
filename = folder + "signals.csv";
content = "time, action, position, price\n";
content += _sig_logs.str();
StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size());
}
void HftMocker::log_trade(const char* stdCode, bool isLong, bool isOpen, uint64_t curTime, double price, double qty, double fee, const char* userTag/* = ""*/)
{
_trade_logs << stdCode << "," << curTime << "," << (isLong ? "LONG" : "SHORT") << "," << (isOpen ? "OPEN" : "CLOSE")
<< "," << price << "," << qty << "," << fee << "," << userTag << "\n";
}
void HftMocker::log_close(const char* stdCode, bool isLong, uint64_t openTime, double openpx, uint64_t closeTime, double closepx, double qty, double profit, double maxprofit, double maxloss,
double totalprofit /* = 0 */, const char* enterTag/* = ""*/, const char* exitTag/* = ""*/)
{
_close_logs << stdCode << "," << (isLong ? "LONG" : "SHORT") << "," << openTime << "," << openpx
<< "," << closeTime << "," << closepx << "," << qty << "," << profit << "," << maxprofit << "," << maxloss << ","
<< totalprofit << "," << enterTag << "," << exitTag << "\n";
}
void HftMocker::do_set_position(const char* stdCode, double qty, double price /* = 0.0 */, const char* userTag /*= ""*/)
{
PosInfo& pInfo = _pos_map[stdCode];
double curPx = price;
if (decimal::eq(price, 0.0))
curPx = _price_map[stdCode];
uint64_t curTm = (uint64_t)_replayer->get_date() * 1000000000 + (uint64_t)_replayer->get_min_time()*100000 + _replayer->get_secs();
uint32_t curTDate = _replayer->get_trading_date();
//手数相等则不用操作了
if (decimal::eq(pInfo._volume, qty))
return;
log_info("[%04u.%05u] %s position updated: %.0f -> %0.f", _replayer->get_min_time(), _replayer->get_secs(), stdCode, pInfo._volume, qty);
WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode);
if (commInfo == NULL)
return;
//成交价
double trdPx = curPx;
double diff = qty - pInfo._volume;
bool isBuy = decimal::gt(diff, 0.0);
if (decimal::gt(pInfo._volume*diff, 0))//当前持仓和仓位变化方向一致, 增加一条明细, 增加数量即可
{
pInfo._volume = qty;
//如果T+1,则冻结仓位要增加
if (commInfo->isT1())
{
//ASSERT(diff>0);
pInfo._frozen += diff;
log_debug("%s frozen position up to %.0f", stdCode, pInfo._frozen);
}
DetailInfo dInfo;
dInfo._long = decimal::gt(qty, 0);
dInfo._price = trdPx;
dInfo._volume = abs(diff);
dInfo._opentime = curTm;
dInfo._opentdate = curTDate;
strcpy(dInfo._usertag, userTag);
pInfo._details.emplace_back(dInfo);
double fee = _replayer->calc_fee(stdCode, trdPx, abs(diff), 0);
_fund_info._total_fees += fee;
log_trade(stdCode, dInfo._long, true, curTm, trdPx, abs(diff), fee, userTag);
}
else
{//持仓方向和仓位变化方向不一致,需要平仓
double left = abs(diff);
pInfo._volume = qty;
if (decimal::eq(pInfo._volume, 0))
pInfo._dynprofit = 0;
uint32_t count = 0;
for (auto it = pInfo._details.begin(); it != pInfo._details.end(); it++)
{
DetailInfo& dInfo = *it;
double maxQty = min(dInfo._volume, left);
if (decimal::eq(maxQty, 0))
continue;
double maxProf = dInfo._max_profit * maxQty / dInfo._volume;
double maxLoss = dInfo._max_loss * maxQty / dInfo._volume;
dInfo._volume -= maxQty;
left -= maxQty;
if (decimal::eq(dInfo._volume, 0))
count++;
double profit = (trdPx - dInfo._price) * maxQty * commInfo->getVolScale();
if (!dInfo._long)
profit *= -1;
pInfo._closeprofit += profit;
pInfo._dynprofit = pInfo._dynprofit*dInfo._volume / (dInfo._volume + maxQty);//浮盈也要做等比缩放
_fund_info._total_profit += profit;
double fee = _replayer->calc_fee(stdCode, trdPx, maxQty, dInfo._opentdate == curTDate ? 2 : 1);
_fund_info._total_fees += fee;
//这里写成交记录
log_trade(stdCode, dInfo._long, false, curTm, trdPx, maxQty, fee, userTag);
//这里写平仓记录
log_close(stdCode, dInfo._long, dInfo._opentime, dInfo._price, curTm, trdPx, maxQty, profit, maxProf, maxLoss, pInfo._closeprofit, dInfo._usertag, userTag);
if (left == 0)
break;
}
//需要清理掉已经平仓完的明细
while (count > 0)
{
auto it = pInfo._details.begin();
pInfo._details.erase(it);
count--;
}
//最后,如果还有剩余的,则需要反手了
if (left > 0)
{
left = left * qty / abs(qty);
//如果T+1,则冻结仓位要增加
if (commInfo->isT1())
{
pInfo._frozen += left;
log_debug("%s frozen position up to %.0f", stdCode, pInfo._frozen);
}
DetailInfo dInfo;
dInfo._long = decimal::gt(qty, 0);
dInfo._price = trdPx;
dInfo._volume = abs(left);
dInfo._opentime = curTm;
dInfo._opentdate = curTDate;
strcpy(dInfo._usertag, userTag);
pInfo._details.emplace_back(dInfo);
//这里还需要写一笔成交记录
double fee = _replayer->calc_fee(stdCode, trdPx, abs(left), 0);
_fund_info._total_fees += fee;
log_trade(stdCode, dInfo._long, true, curTm, trdPx, abs(left), fee, userTag);
}
}
}
| 24.947417 | 191 | 0.662205 | v1otusc |
66eb96db8ae4810dc6bbda0ebcd0bd7d351ed05c | 5,785 | cpp | C++ | src/network/udp_socket.cpp | Revolution-Populi/fc | 02b7593a96b02d9966358c59d22f344d86fa9a19 | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | 37 | 2017-02-04T09:42:48.000Z | 2021-02-17T14:59:15.000Z | src/network/udp_socket.cpp | Revolution-Populi/fc | 02b7593a96b02d9966358c59d22f344d86fa9a19 | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | 120 | 2017-11-09T19:46:40.000Z | 2022-01-20T18:26:23.000Z | src/network/udp_socket.cpp | Revolution-Populi/fc | 02b7593a96b02d9966358c59d22f344d86fa9a19 | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | 109 | 2017-01-16T14:24:31.000Z | 2022-03-18T21:10:07.000Z | #include <fc/network/udp_socket.hpp>
#include <fc/network/ip.hpp>
#include <fc/fwd_impl.hpp>
#include <fc/asio.hpp>
namespace fc {
class udp_socket::impl {
public:
impl():_sock( fc::asio::default_io_service() ){}
~impl(){
// _sock.cancel();
}
boost::asio::ip::udp::socket _sock;
};
boost::asio::ip::udp::endpoint to_asio_ep( const fc::ip::endpoint& e ) {
return boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4(e.get_address()), e.port() );
}
fc::ip::endpoint to_fc_ep( const boost::asio::ip::udp::endpoint& e ) {
return fc::ip::endpoint( e.address().to_v4().to_ulong(), e.port() );
}
udp_socket::udp_socket()
:my( new impl() )
{
}
udp_socket::udp_socket( const udp_socket& s )
:my(s.my)
{
}
udp_socket::~udp_socket()
{
try
{
my->_sock.close(); //close boost socket to make any pending reads run their completion handler
}
catch (...) //avoid destructor throw and likely this is just happening because socket wasn't open.
{
}
}
size_t udp_socket::send_to( const char* buffer, size_t length, const ip::endpoint& to )
{
try
{
return my->_sock.send_to( boost::asio::buffer(buffer, length), to_asio_ep(to) );
}
catch( const boost::system::system_error& e )
{
if( e.code() != boost::asio::error::would_block )
throw;
}
promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::send_to");
my->_sock.async_send_to( boost::asio::buffer(buffer, length), to_asio_ep(to),
asio::detail::read_write_handler(completion_promise) );
return completion_promise->wait();
}
size_t udp_socket::send_to( const std::shared_ptr<const char>& buffer, size_t length,
const fc::ip::endpoint& to )
{
try
{
return my->_sock.send_to( boost::asio::buffer(buffer.get(), length), to_asio_ep(to) );
}
catch( const boost::system::system_error& e )
{
if( e.code() != boost::asio::error::would_block )
throw;
}
promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::send_to");
my->_sock.async_send_to( boost::asio::buffer(buffer.get(), length), to_asio_ep(to),
asio::detail::read_write_handler_with_buffer(completion_promise, buffer) );
return completion_promise->wait();
}
void udp_socket::open() {
my->_sock.open( boost::asio::ip::udp::v4() );
my->_sock.non_blocking(true);
}
void udp_socket::set_receive_buffer_size( size_t s ) {
my->_sock.set_option(boost::asio::socket_base::receive_buffer_size(s) );
}
void udp_socket::bind( const fc::ip::endpoint& e ) {
my->_sock.bind( to_asio_ep(e) );
}
size_t udp_socket::receive_from( const std::shared_ptr<char>& receive_buffer, size_t receive_buffer_length, fc::ip::endpoint& from )
{
try
{
boost::asio::ip::udp::endpoint boost_from_endpoint;
size_t bytes_read = my->_sock.receive_from( boost::asio::buffer(receive_buffer.get(), receive_buffer_length),
boost_from_endpoint );
from = to_fc_ep(boost_from_endpoint);
return bytes_read;
}
catch( const boost::system::system_error& e )
{
if( e.code() != boost::asio::error::would_block )
throw;
}
boost::asio::ip::udp::endpoint boost_from_endpoint;
promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::receive_from");
my->_sock.async_receive_from( boost::asio::buffer(receive_buffer.get(), receive_buffer_length),
boost_from_endpoint,
asio::detail::read_write_handler_with_buffer(completion_promise, receive_buffer) );
size_t bytes_read = completion_promise->wait();
from = to_fc_ep(boost_from_endpoint);
return bytes_read;
}
size_t udp_socket::receive_from( char* receive_buffer, size_t receive_buffer_length, fc::ip::endpoint& from )
{
try
{
boost::asio::ip::udp::endpoint boost_from_endpoint;
size_t bytes_read = my->_sock.receive_from( boost::asio::buffer(receive_buffer, receive_buffer_length),
boost_from_endpoint );
from = to_fc_ep(boost_from_endpoint);
return bytes_read;
}
catch( const boost::system::system_error& e )
{
if( e.code() != boost::asio::error::would_block )
throw;
}
boost::asio::ip::udp::endpoint boost_from_endpoint;
promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::receive_from");
my->_sock.async_receive_from( boost::asio::buffer(receive_buffer, receive_buffer_length), boost_from_endpoint,
asio::detail::read_write_handler(completion_promise) );
size_t bytes_read = completion_promise->wait();
from = to_fc_ep(boost_from_endpoint);
return bytes_read;
}
void udp_socket::close() {
//my->_sock.cancel();
my->_sock.close();
}
fc::ip::endpoint udp_socket::local_endpoint()const {
return to_fc_ep( my->_sock.local_endpoint() );
}
void udp_socket::connect( const fc::ip::endpoint& e ) {
my->_sock.connect( to_asio_ep(e) );
}
void udp_socket::set_multicast_enable_loopback( bool s )
{
my->_sock.set_option( boost::asio::ip::multicast::enable_loopback(s) );
}
void udp_socket::set_reuse_address( bool s )
{
my->_sock.set_option( boost::asio::ip::udp::socket::reuse_address(s) );
}
void udp_socket::join_multicast_group( const fc::ip::address& a )
{
my->_sock.set_option( boost::asio::ip::multicast::join_group( boost::asio::ip::address_v4(a) ) );
}
}
| 33.247126 | 134 | 0.631979 | Revolution-Populi |
66ef2aca7561189fc1efddd261320af007ffb270 | 834 | cpp | C++ | Toast/src/Platform/Windows/WindowsInput.cpp | Toastmastern87/Toast | be9efd2f4f62597c3d95b47d242a2e783571620b | [
"Apache-2.0"
] | 17 | 2020-07-02T19:07:56.000Z | 2021-11-30T14:23:49.000Z | Toast/src/Platform/Windows/WindowsInput.cpp | Toastmastern87/Toast | be9efd2f4f62597c3d95b47d242a2e783571620b | [
"Apache-2.0"
] | null | null | null | Toast/src/Platform/Windows/WindowsInput.cpp | Toastmastern87/Toast | be9efd2f4f62597c3d95b47d242a2e783571620b | [
"Apache-2.0"
] | 3 | 2020-06-30T00:22:26.000Z | 2021-11-30T14:23:56.000Z | #include "tpch.h"
#include "Toast/Core/Input.h"
#include "Toast/Core/Application.h"
namespace Toast {
bool Input::IsKeyPressed(const KeyCode keycode)
{
auto state = GetAsyncKeyState(static_cast<int>(keycode));
return (state & 0x8000);
}
bool Input::IsMouseButtonPressed(const MouseCode button)
{
auto state = GetAsyncKeyState(static_cast<int>(button));
return (state & 0x8000);
}
DirectX::XMFLOAT2 Input::GetMousePosition()
{
POINT p;
GetCursorPos(&p);
return { (float)p.x, (float)p.y };
}
float Input::GetMouseX()
{
return GetMousePosition().x;
}
float Input::GetMouseY()
{
return GetMousePosition().y;
}
float Input::sMouseWheelDelta;
float Input::GetMouseWheelDelta()
{
return sMouseWheelDelta;
}
void Input::SetMouseWheelDelta(float delta)
{
sMouseWheelDelta = delta;
}
} | 16.038462 | 59 | 0.699041 | Toastmastern87 |
66f18b9bca9f0d727ec2959ca99299390269f65a | 81,261 | cpp | C++ | ecl/eclcc/eclcc.cpp | emuharemagic/HPCC-Platform | bbd5423b25f6ba2d675521c8917f9ecfa97dace5 | [
"Apache-2.0"
] | 1 | 2020-08-01T19:54:56.000Z | 2020-08-01T19:54:56.000Z | ecl/eclcc/eclcc.cpp | emuharemagic/HPCC-Platform | bbd5423b25f6ba2d675521c8917f9ecfa97dace5 | [
"Apache-2.0"
] | null | null | null | ecl/eclcc/eclcc.cpp | emuharemagic/HPCC-Platform | bbd5423b25f6ba2d675521c8917f9ecfa97dace5 | [
"Apache-2.0"
] | null | null | null | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
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 <stdio.h>
#include "jcomp.hpp"
#include "jfile.hpp"
#include "jlzw.hpp"
#include "jqueue.tpp"
#include "jargv.hpp"
#include "junicode.hpp"
#include "build-config.h"
#include "workunit.hpp"
#ifndef _WIN32
#include <pwd.h>
#endif
#include "hqlecl.hpp"
#include "hqlir.hpp"
#include "hqlerrors.hpp"
#include "hqlwuerr.hpp"
#include "hqlfold.hpp"
#include "hqlplugins.hpp"
#include "hqlmanifest.hpp"
#include "hqlcollect.hpp"
#include "hqlrepository.hpp"
#include "hqlerror.hpp"
#include "hqlcerrors.hpp"
#include "hqlgram.hpp"
#include "hqltrans.ipp"
#include "hqlutil.hpp"
#include "build-config.h"
#include "rmtfile.hpp"
#ifdef _USE_CPPUNIT
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#endif
//#define TEST_LEGACY_DEPENDENCY_CODE
#define INIFILE "eclcc.ini"
#define SYSTEMCONFDIR CONFIG_DIR
#define DEFAULTINIFILE "eclcc.ini"
#define SYSTEMCONFFILE ENV_CONF_FILE
#define DEFAULT_OUTPUTNAME "a.out"
//=========================================================================================
//The following flag could be used not free items to speed up closedown
static bool optDebugMemLeak = false;
#if defined(_WIN32) && defined(_DEBUG)
static HANDLE leakHandle;
static void appendLeaks(size32_t len, const void * data)
{
SetFilePointer(leakHandle, 0, 0, FILE_END);
DWORD written;
WriteFile(leakHandle, data, len, &written, 0);
}
void initLeakCheck(const char * title)
{
StringBuffer leakFilename("eclccleaks.log");
leakHandle = CreateFile(leakFilename.str(), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, 0);
if (title)
appendLeaks(strlen(title), title);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG );
_CrtSetReportFile( _CRT_WARN, leakHandle );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG );
_CrtSetReportFile( _CRT_ERROR, leakHandle );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG );
_CrtSetReportFile( _CRT_ASSERT, leakHandle );
//
// set the states we want to monitor
//
int LeakTmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
LeakTmpFlag &= ~_CRTDBG_CHECK_CRT_DF;
LeakTmpFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(LeakTmpFlag);
}
/**
* Error handler for ctrl-break: Don't care about memory leaks.
*/
void __cdecl IntHandler(int)
{
enableMemLeakChecking(false);
exit(2);
}
#include <signal.h> // for signal()
MODULE_INIT(INIT_PRIORITY_STANDARD)
{
signal(SIGINT, IntHandler);
return true;
}
#else
void initLeakCheck(const char *)
{
}
#endif // _WIN32 && _DEBUG
static bool extractOption(StringBuffer & option, IProperties * globals, const char * envName, const char * propertyName, const char * defaultPrefix, const char * defaultSuffix)
{
if (option.length()) // check if already specified via a command line option
return true;
if (globals->getProp(propertyName, option))
return true;
const char * env = getenv(envName);
if (env)
{
option.append(env);
return true;
}
option.append(defaultPrefix).append(defaultSuffix);
return false;
}
static bool extractOption(StringAttr & option, IProperties * globals, const char * envName, const char * propertyName, const char * defaultPrefix, const char * defaultSuffix)
{
if (option)
return true;
StringBuffer temp;
bool ret = extractOption(temp, globals, envName, propertyName, defaultPrefix, defaultSuffix);
option.set(temp.str());
return ret;
}
static bool getPackageFolder(StringBuffer & path)
{
StringBuffer folder;
splitDirTail(queryCurrentProcessPath(), folder);
removeTrailingPathSepChar(folder);
if (folder.length())
{
StringBuffer foldersFolder;
splitDirTail(folder.str(), foldersFolder);
if (foldersFolder.length())
{
path = foldersFolder;
return true;
}
}
return false;
}
static bool getHomeFolder(StringBuffer & homepath)
{
if (!getHomeDir(homepath))
return false;
addPathSepChar(homepath);
#ifndef WIN32
homepath.append('.');
#endif
homepath.append(DIR_NAME);
return true;
}
struct EclCompileInstance
{
public:
EclCompileInstance(IFile * _inputFile, IErrorReceiver & _errorProcessor, FILE * _errout, const char * _outputFilename, bool _legacyImport, bool _legacyWhen) :
inputFile(_inputFile), errorProcessor(&_errorProcessor), errout(_errout), outputFilename(_outputFilename)
{
legacyImport = _legacyImport;
legacyWhen = _legacyWhen;
ignoreUnknownImport = false;
fromArchive = false;
stats.parseTime = 0;
stats.generateTime = 0;
stats.xmlSize = 0;
stats.cppSize = 0;
}
void logStats();
void checkEclVersionCompatible();
bool reportErrorSummary();
inline IErrorReceiver & queryErrorProcessor() { return *errorProcessor; }
public:
Linked<IFile> inputFile;
Linked<IPropertyTree> archive;
Linked<IWorkUnit> wu;
Owned<IEclRepository> dataServer; // A member which can be cleared after parsing the query
OwnedHqlExpr query; // parsed query - cleared when generating to free memory
StringAttr eclVersion;
const char * outputFilename;
FILE * errout;
Owned<IPropertyTree> srcArchive;
Owned<IPropertyTree> generatedMeta;
bool legacyImport;
bool legacyWhen;
bool fromArchive;
bool ignoreUnknownImport;
struct {
unsigned parseTime;
unsigned generateTime;
offset_t xmlSize;
offset_t cppSize;
} stats;
protected:
Linked<IErrorReceiver> errorProcessor;
};
class EclCC : public CInterfaceOf<ICodegenContextCallback>
{
public:
EclCC(int _argc, const char **_argv)
: programName(_argv[0])
{
argc = _argc;
argv = _argv;
logVerbose = false;
logTimings = false;
optArchive = false;
optCheckEclVersion = true;
optEvaluateResult = false;
optGenerateMeta = false;
optGenerateDepend = false;
optIncludeMeta = false;
optLegacyImport = false;
optLegacyWhen = false;
optShared = false;
optWorkUnit = false;
optNoCompile = false;
optNoLogFile = false;
optNoStdInc = false;
optNoBundles = false;
optOnlyCompile = false;
optBatchMode = false;
optSaveQueryText = false;
optGenerateHeader = false;
optShowPaths = false;
optTargetClusterType = HThorCluster;
optTargetCompiler = DEFAULT_COMPILER;
optThreads = 0;
optLogDetail = 0;
batchPart = 0;
batchSplit = 1;
batchLog = NULL;
cclogFilename.append("cc.").append((unsigned)GetCurrentProcessId()).append(".log");
defaultAllowed = true;
}
bool parseCommandLineOptions(int argc, const char* argv[]);
void loadOptions();
void loadManifestOptions();
bool processFiles();
void processBatchedFile(IFile & file, bool multiThreaded);
virtual void noteCluster(const char *clusterName);
virtual void registerFile(const char * filename, const char * description);
virtual bool allowAccess(const char * category);
protected:
void addFilenameDependency(StringBuffer & target, EclCompileInstance & instance, const char * filename);
void applyApplicationOptions(IWorkUnit * wu);
void applyDebugOptions(IWorkUnit * wu);
bool checkWithinRepository(StringBuffer & attributePath, const char * sourcePathname);
IFileIO * createArchiveOutputFile(EclCompileInstance & instance);
ICppCompiler *createCompiler(const char * coreName, const char * sourceDir = NULL, const char * targetDir = NULL);
void evaluateResult(EclCompileInstance & instance);
bool generatePrecompiledHeader();
void generateOutput(EclCompileInstance & instance);
void instantECL(EclCompileInstance & instance, IWorkUnit *wu, const char * queryFullName, IErrorReceiver & errorProcessor, const char * outputFile);
bool isWithinPath(const char * sourcePathname, const char * searchPath);
void getComplexity(IWorkUnit *wu, IHqlExpression * query, IErrorReceiver & errorProcessor);
void outputXmlToOutputFile(EclCompileInstance & instance, IPropertyTree * xml);
void processSingleQuery(EclCompileInstance & instance,
IFileContents * queryContents,
const char * queryAttributePath);
void processXmlFile(EclCompileInstance & instance, const char *archiveXML);
void processFile(EclCompileInstance & info);
void processReference(EclCompileInstance & instance, const char * queryAttributePath);
void processBatchFiles();
void reportCompileErrors(IErrorReceiver & errorProcessor, const char * processName);
void setDebugOption(const char * name, bool value);
void usage();
inline const char * queryTemplateDir() { return templatePath.length() ? templatePath.str() : NULL; }
protected:
Owned<IEclRepository> pluginsRepository;
Owned<IEclRepository> libraryRepository;
Owned<IEclRepository> bundlesRepository;
Owned<IEclRepository> includeRepository;
const char * programName;
StringBuffer cppIncludePath;
StringBuffer pluginsPath;
StringBuffer hooksPath;
StringBuffer templatePath;
StringBuffer eclLibraryPath;
StringBuffer eclBundlePath;
StringBuffer stdIncludeLibraryPath;
StringBuffer includeLibraryPath;
StringBuffer compilerPath;
StringBuffer libraryPath;
StringBuffer cclogFilename;
StringAttr optLogfile;
StringAttr optIniFilename;
StringAttr optManifestFilename;
StringAttr optOutputDirectory;
StringAttr optOutputFilename;
StringAttr optQueryRepositoryReference;
FILE * batchLog;
IFileArray inputFiles;
StringArray inputFileNames;
StringArray applicationOptions;
StringArray debugOptions;
StringArray warningMappings;
StringArray compileOptions;
StringArray linkOptions;
StringArray libraryPaths;
StringArray allowedPermissions;
StringArray deniedPermissions;
bool defaultAllowed;
ClusterType optTargetClusterType;
CompilerType optTargetCompiler;
unsigned optThreads;
unsigned batchPart;
unsigned batchSplit;
unsigned optLogDetail;
bool logVerbose;
bool logTimings;
bool optArchive;
bool optCheckEclVersion;
bool optEvaluateResult;
bool optGenerateMeta;
bool optGenerateDepend;
bool optIncludeMeta;
bool optWorkUnit;
bool optNoCompile;
bool optNoLogFile;
bool optNoStdInc;
bool optNoBundles;
bool optBatchMode;
bool optShared;
bool optOnlyCompile;
bool optSaveQueryText;
bool optLegacyImport;
bool optLegacyWhen;
bool optGenerateHeader;
bool optShowPaths;
int argc;
const char **argv;
};
//=========================================================================================
static int doSelfTest(int argc, const char *argv[])
{
#ifdef _USE_CPPUNIT
queryStderrLogMsgHandler()->setMessageFields(MSGFIELD_time | MSGFIELD_prefix);
CppUnit::TextUi::TestRunner runner;
if (argc==2)
{
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest( registry.makeTest() );
}
else
{
// MORE - maybe add a 'list' function here?
for (int name = 2; name < argc; name++)
{
if (stricmp(argv[name], "-q")==0)
{
removeLog();
}
else
{
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(argv[name]);
runner.addTest( registry.makeTest() );
}
}
}
bool wasSucessful = runner.run( "", false );
releaseAtoms();
return wasSucessful;
#else
return true;
#endif
}
static int doMain(int argc, const char *argv[])
{
if (argc>=2 && stricmp(argv[1], "-selftest")==0)
return doSelfTest(argc, argv);
EclCC processor(argc, argv);
if (!processor.parseCommandLineOptions(argc, argv))
return 1;
try
{
if (!processor.processFiles())
return 2;
}
catch (IException *E)
{
StringBuffer m("Error: ");
E->errorMessage(m);
fputs(m.newline().str(), stderr);
E->Release();
return 2;
}
#ifndef _DEBUG
catch (...)
{
ERRLOG("Unexpected exception\n");
return 4;
}
#endif
return 0;
}
int main(int argc, const char *argv[])
{
EnableSEHtoExceptionMapping();
setTerminateOnSEH(true);
InitModuleObjects();
queryStderrLogMsgHandler()->setMessageFields(0);
// Turn logging down (we turn it back up if -v option seen)
Owned<ILogMsgFilter> filter = getCategoryLogMsgFilter(MSGAUD_user, MSGCLS_error);
queryLogMsgManager()->changeMonitorFilter(queryStderrLogMsgHandler(), filter);
unsigned exitCode = doMain(argc, argv);
releaseAtoms();
removeFileHooks();
return exitCode;
}
//=========================================================================================
bool setTargetPlatformOption(const char *platform, ClusterType &optTargetClusterType)
{
if (!platform || !*platform)
return false;
ClusterType clusterType = getClusterType(platform);
if (clusterType == NoCluster)
{
ERRLOG("Unknown ecl target platform %s\n", platform);
return false;
}
optTargetClusterType = clusterType;
return true;
}
void EclCC::loadManifestOptions()
{
if (!optManifestFilename)
return;
Owned<IPropertyTree> mf = createPTreeFromXMLFile(optManifestFilename);
IPropertyTree *ecl = mf->queryPropTree("ecl");
if (ecl)
{
if (ecl->hasProp("@filename"))
{
StringBuffer dir, abspath;
splitDirTail(optManifestFilename, dir);
makeAbsolutePath(ecl->queryProp("@filename"), dir.str(), abspath);
processArgvFilename(inputFiles, abspath.str());
}
if (!optLegacyImport && !optLegacyWhen)
{
bool optLegacy = ecl->getPropBool("@legacy");
optLegacyImport = ecl->getPropBool("@legacyImport", optLegacy);
optLegacyWhen = ecl->getPropBool("@legacyWhen", optLegacy);
}
if (!optQueryRepositoryReference && ecl->hasProp("@main"))
optQueryRepositoryReference.set(ecl->queryProp("@main"));
if (ecl->hasProp("@targetPlatform"))
setTargetPlatformOption(ecl->queryProp("@targetPlatform"), optTargetClusterType);
else if (ecl->hasProp("@targetClusterType")) //deprecated name
setTargetPlatformOption(ecl->queryProp("@targetClusterType"), optTargetClusterType);
Owned<IPropertyTreeIterator> paths = ecl->getElements("IncludePath");
ForEach(*paths)
{
IPropertyTree &item = paths->query();
if (item.hasProp("@path"))
includeLibraryPath.append(ENVSEPCHAR).append(item.queryProp("@path"));
}
paths.setown(ecl->getElements("LibraryPath"));
ForEach(*paths)
{
IPropertyTree &item = paths->query();
if (item.hasProp("@path"))
libraryPaths.append(item.queryProp("@path"));
}
}
}
void EclCC::loadOptions()
{
Owned<IProperties> globals;
if (!optIniFilename)
{
if (checkFileExists(INIFILE))
optIniFilename.set(INIFILE);
else
{
StringBuffer fn(SYSTEMCONFDIR);
fn.append(PATHSEPSTR).append(DEFAULTINIFILE);
if (checkFileExists(fn))
optIniFilename.set(fn);
}
}
if (logVerbose && optIniFilename.length())
fprintf(stdout, "Found ini file '%s'\n", optIniFilename.get());
globals.setown(createProperties(optIniFilename, true));
if (globals->hasProp("targetGcc"))
optTargetCompiler = globals->getPropBool("targetGcc") ? GccCppCompiler : Vs6CppCompiler;
StringBuffer syspath, homepath;
if (getPackageFolder(syspath) && getHomeFolder(homepath))
{
#if _WIN32
extractOption(compilerPath, globals, "CL_PATH", "compilerPath", syspath, "componentfiles\\cl");
#else
extractOption(compilerPath, globals, "CL_PATH", "compilerPath", "/usr", NULL);
#endif
if (!extractOption(libraryPath, globals, "ECLCC_LIBRARY_PATH", "libraryPath", syspath, "lib"))
libraryPath.append(ENVSEPCHAR).append(syspath).append("plugins");
extractOption(cppIncludePath, globals, "ECLCC_INCLUDE_PATH", "includePath", syspath, "componentfiles" PATHSEPSTR "cl" PATHSEPSTR "include");
extractOption(pluginsPath, globals, "ECLCC_PLUGIN_PATH", "plugins", syspath, "plugins");
extractOption(hooksPath, globals, "HPCC_FILEHOOKS_PATH", "filehooks", syspath, "filehooks");
extractOption(templatePath, globals, "ECLCC_TPL_PATH", "templatePath", syspath, "componentfiles");
extractOption(eclLibraryPath, globals, "ECLCC_ECLLIBRARY_PATH", "eclLibrariesPath", syspath, "share" PATHSEPSTR "ecllibrary" PATHSEPSTR);
extractOption(eclBundlePath, globals, "ECLCC_ECLBUNDLE_PATH", "eclBundlesPath", homepath, PATHSEPSTR "bundles" PATHSEPSTR);
}
extractOption(stdIncludeLibraryPath, globals, "ECLCC_ECLINCLUDE_PATH", "eclIncludePath", ".", NULL);
if (!optLogfile.length() && !optBatchMode && !optNoLogFile)
extractOption(optLogfile, globals, "ECLCC_LOGFILE", "logfile", "eclcc.log", NULL);
if ((logVerbose || optLogfile) && !optNoLogFile)
{
if (optLogfile.length())
{
StringBuffer lf;
openLogFile(lf, optLogfile, optLogDetail, false);
if (logVerbose)
fprintf(stdout, "Logging to '%s'\n",lf.str());
}
}
if (hooksPath.length())
installFileHooks(hooksPath.str());
if (!optNoCompile)
setCompilerPath(compilerPath.str(), cppIncludePath.str(), libraryPath.str(), NULL, optTargetCompiler, logVerbose);
}
//=========================================================================================
void EclCC::applyDebugOptions(IWorkUnit * wu)
{
ForEachItemIn(i, debugOptions)
{
const char * option = debugOptions.item(i);
const char * eq = strchr(option, '=');
if (eq)
{
StringAttr name;
name.set(option, eq-option);
wu->setDebugValue(name, eq+1, true);
}
else
{
size_t len = strlen(option);
if (len)
{
char last = option[len-1];
if (last == '-' || last == '+')
{
StringAttr name;
name.set(option, len-1);
wu->setDebugValueInt(name, last == '+' ? 1 : 0, true);
}
else
wu->setDebugValue(option, "1", true);
}
}
}
}
void EclCC::applyApplicationOptions(IWorkUnit * wu)
{
ForEachItemIn(i, applicationOptions)
{
const char * option = applicationOptions.item(i);
const char * eq = strchr(option, '=');
if (eq)
{
StringAttr name;
name.set(option, eq-option);
wu->setApplicationValue("eclcc", name, eq+1, true);
}
else
{
wu->setApplicationValueInt("eclcc", option, 1, true);
}
}
}
//=========================================================================================
ICppCompiler * EclCC::createCompiler(const char * coreName, const char * sourceDir, const char * targetDir)
{
Owned<ICppCompiler> compiler = ::createCompiler(coreName, sourceDir, targetDir, optTargetCompiler, logVerbose);
compiler->setOnlyCompile(optOnlyCompile);
compiler->setCCLogPath(cclogFilename);
ForEachItemIn(iComp, compileOptions)
compiler->addCompileOption(compileOptions.item(iComp));
ForEachItemIn(iLink, linkOptions)
compiler->addLinkOption(linkOptions.item(iLink));
ForEachItemIn(iLib, libraryPaths)
compiler->addLibraryPath(libraryPaths.item(iLib));
return compiler.getClear();
}
void EclCC::reportCompileErrors(IErrorReceiver & errorProcessor, const char * processName)
{
StringBuffer failText;
StringBuffer absCCLogName;
if (optLogfile.get())
createUNCFilename(optLogfile.get(), absCCLogName, false);
else
absCCLogName = "log file";
failText.appendf("Compile/Link failed for %s (see '%s' for details)",processName,absCCLogName.str());
errorProcessor.reportError(ERR_INTERNALEXCEPTION, failText.toCharArray(), processName, 0, 0, 0);
try
{
StringBuffer s;
Owned<IFile> log = createIFile(cclogFilename);
Owned<IFileIO> io = log->open(IFOread);
if (io)
{
offset_t len = io->size();
if (len)
{
io->read(0, (size32_t)len, s.reserve((size32_t)len));
#ifdef _WIN32
const char * noCompiler = "is not recognized as an internal";
#else
const char * noCompiler = "could not locate compiler";
#endif
if (strstr(s.str(), noCompiler))
{
ERRLOG("Fatal Error: Unable to locate C++ compiler/linker");
}
ERRLOG("\n---------- compiler output --------------\n%s\n--------- end compiler output -----------", s.str());
}
}
}
catch (IException * e)
{
e->Release();
}
}
//=========================================================================================
void EclCC::instantECL(EclCompileInstance & instance, IWorkUnit *wu, const char * queryFullName, IErrorReceiver & errorProcessor, const char * outputFile)
{
StringBuffer processName(outputFile);
if (instance.query && containsAnyActions(instance.query))
{
try
{
const char * templateDir = queryTemplateDir();
bool optSaveTemps = wu->getDebugValueBool("saveEclTempFiles", false);
bool optSaveCpp = optSaveTemps || optNoCompile || wu->getDebugValueBool("saveCppTempFiles", false);
//New scope - testing things are linked correctly
{
Owned<IHqlExprDllGenerator> generator = createDllGenerator(&errorProcessor, processName.toCharArray(), NULL, wu, templateDir, optTargetClusterType, this, false, false);
setWorkunitHash(wu, instance.query);
if (!optShared)
wu->setDebugValueInt("standAloneExe", 1, true);
EclGenerateTarget target = optWorkUnit ? EclGenerateNone : (optNoCompile ? EclGenerateCpp : optShared ? EclGenerateDll : EclGenerateExe);
if (optManifestFilename)
generator->addManifest(optManifestFilename);
if (instance.srcArchive)
{
generator->addManifestFromArchive(instance.srcArchive);
instance.srcArchive.clear();
}
generator->setSaveGeneratedFiles(optSaveCpp);
bool generateOk = generator->processQuery(instance.query, target); // NB: May clear instance.query
instance.stats.cppSize = generator->getGeneratedSize();
if (generateOk && !optNoCompile)
{
Owned<ICppCompiler> compiler = createCompiler(processName.toCharArray());
compiler->setSaveTemps(optSaveTemps);
bool compileOk = true;
if (optShared)
{
compileOk = generator->generateDll(compiler);
}
else
{
if (optTargetClusterType==RoxieCluster)
generator->addLibrary("ccd");
else
generator->addLibrary("hthor");
compileOk = generator->generateExe(compiler);
}
if (!compileOk)
reportCompileErrors(errorProcessor, processName);
}
else
wu->setState(generateOk ? WUStateCompleted : WUStateFailed);
}
if (logVerbose)
{
switch (wu->getState())
{
case WUStateCompiled:
fprintf(stdout, "Output file '%s' created\n",outputFile);
break;
case WUStateFailed:
ERRLOG("Failed to create output file '%s'\n",outputFile);
break;
case WUStateUploadingFiles:
fprintf(stdout, "Output file '%s' created, local file upload required\n",outputFile);
break;
case WUStateCompleted:
fprintf(stdout, "No DLL/SO required\n");
break;
default:
ERRLOG("Unexpected Workunit state %d\n", (int) wu->getState());
break;
}
}
}
catch (IException * e)
{
if (e->errorCode() != HQLERR_ErrorAlreadyReported)
{
StringBuffer exceptionText;
e->errorMessage(exceptionText);
errorProcessor.reportError(ERR_INTERNALEXCEPTION, exceptionText.toCharArray(), queryFullName, 1, 0, 0);
}
e->Release();
}
try
{
Owned<IFile> log = createIFile(cclogFilename);
log->remove();
}
catch (IException * e)
{
e->Release();
}
}
}
//=========================================================================================
void EclCC::getComplexity(IWorkUnit *wu, IHqlExpression * query, IErrorReceiver & errs)
{
double complexity = getECLcomplexity(query, &errs, wu, optTargetClusterType);
LOG(MCstats, unknownJob, "Complexity = %g", complexity);
}
//=========================================================================================
static bool convertPathToModule(StringBuffer & out, const char * filename)
{
const char * dot = strrchr(filename, '.');
if (dot)
{
if (!strieq(dot, ".ecl") && !strieq(dot, ".hql") && !strieq(dot, ".eclmod") && !strieq(dot, ".eclattr"))
return false;
}
else
return false;
const unsigned copyLen = dot-filename;
if (copyLen == 0)
return false;
out.ensureCapacity(copyLen);
for (unsigned i= 0; i < copyLen; i++)
{
char next = filename[i];
if (isPathSepChar(next))
next = '.';
out.append(next);
}
return true;
}
static bool findFilenameInSearchPath(StringBuffer & attributePath, const char * searchPath, const char * expandedSourceName)
{
const char * cur = searchPath;
unsigned lenSource = strlen(expandedSourceName);
loop
{
const char * sep = strchr(cur, ENVSEPCHAR);
StringBuffer curExpanded;
if (!sep)
{
if (*cur)
makeAbsolutePath(cur, curExpanded);
}
else if (sep != cur)
{
StringAttr temp(cur, sep-cur);
makeAbsolutePath(temp, curExpanded);
}
if (curExpanded.length() && (curExpanded.length() < lenSource))
{
#ifdef _WIN32
//windows paths are case insensitive
bool same = memicmp(curExpanded.str(), expandedSourceName, curExpanded.length()) == 0;
#else
bool same = memcmp(curExpanded.str(), expandedSourceName, curExpanded.length()) == 0;
#endif
if (same)
{
const char * tail = expandedSourceName+curExpanded.length();
if (isPathSepChar(*tail))
tail++;
if (convertPathToModule(attributePath, tail))
return true;
}
}
if (!sep)
return false;
cur = sep+1;
}
}
bool EclCC::isWithinPath(const char * sourcePathname, const char * searchPath)
{
if (!sourcePathname)
return false;
StringBuffer expandedSourceName;
makeAbsolutePath(sourcePathname, expandedSourceName);
StringBuffer attributePath;
return findFilenameInSearchPath(attributePath, searchPath, expandedSourceName);
}
bool EclCC::checkWithinRepository(StringBuffer & attributePath, const char * sourcePathname)
{
if (!sourcePathname)
return false;
StringBuffer searchPath;
searchPath.append(eclLibraryPath).append(ENVSEPCHAR);
if (!optNoBundles)
searchPath.append(eclBundlePath).append(ENVSEPCHAR);
if (!optNoStdInc)
searchPath.append(stdIncludeLibraryPath).append(ENVSEPCHAR);
searchPath.append(includeLibraryPath);
StringBuffer expandedSourceName;
makeAbsolutePath(sourcePathname, expandedSourceName);
return findFilenameInSearchPath(attributePath, searchPath, expandedSourceName);
}
void EclCC::evaluateResult(EclCompileInstance & instance)
{
IHqlExpression *query = instance.query;
if (query->getOperator()==no_output)
query = query->queryChild(0);
if (query->getOperator()==no_datasetfromdictionary)
query = query->queryChild(0);
if (query->getOperator()==no_selectfields)
query = query->queryChild(0);
if (query->getOperator()==no_createdictionary)
query = query->queryChild(0);
OwnedHqlExpr folded = foldHqlExpression(instance.queryErrorProcessor(), query, NULL, HFOthrowerror|HFOloseannotations|HFOforcefold|HFOfoldfilterproject|HFOconstantdatasets);
StringBuffer out;
IValue *result = folded->queryValue();
if (result)
result->generateECL(out);
else if (folded->getOperator()==no_list)
{
out.append('[');
ForEachChild(idx, folded)
{
IHqlExpression *child = folded->queryChild(idx);
if (idx)
out.append(", ");
result = child->queryValue();
if (result)
result->generateECL(out);
else
throw MakeStringException(1, "Expression cannot be evaluated");
}
out.append(']');
}
else if (folded->getOperator()==no_inlinetable)
{
IHqlExpression *transformList = folded->queryChild(0);
if (transformList && transformList->getOperator()==no_transformlist)
{
IHqlExpression *transform = transformList->queryChild(0);
assertex(transform && transform->getOperator()==no_transform);
out.append('[');
ForEachChild(idx, transform)
{
IHqlExpression *child = transform->queryChild(idx);
assertex(child->getOperator()==no_assign);
if (idx)
out.append(", ");
result = child->queryChild(1)->queryValue();
if (result)
result->generateECL(out);
else
throw MakeStringException(1, "Expression cannot be evaluated");
}
out.append(']');
}
else
throw MakeStringException(1, "Expression cannot be evaluated");
}
else
{
#ifdef _DEBUG
EclIR::dump_ir(folded);
#endif
throw MakeStringException(1, "Expression cannot be evaluated");
}
printf("%s\n", out.str());
}
void EclCC::processSingleQuery(EclCompileInstance & instance,
IFileContents * queryContents,
const char * queryAttributePath)
{
#ifdef TEST_LEGACY_DEPENDENCY_CODE
setLegacyEclSemantics(instance.legacyImportMode, instance.legacyWhenMode);
Owned<IPropertyTree> dependencies = gatherAttributeDependencies(instance.dataServer, "");
if (dependencies)
saveXML("depends.xml", dependencies);
#endif
Owned<IErrorReceiver> wuErrs = new WorkUnitErrorReceiver(instance.wu, "eclcc");
Owned<IErrorReceiver> compoundErrs = createCompoundErrorReceiver(&instance.queryErrorProcessor(), wuErrs);
Owned<ErrorSeverityMapper> severityMapper = new ErrorSeverityMapper(*compoundErrs);
//Apply command line mappings...
ForEachItemIn(i, warningMappings)
{
if (!severityMapper->addCommandLineMapping(warningMappings.item(i)))
return;
//Preserve command line mappings in the generated archive
if (instance.archive)
instance.archive->addPropTree("OnWarning", createPTree())->setProp("@value",warningMappings.item(i));
}
//Apply preserved onwarning mappings from any source archive
if (instance.srcArchive)
{
Owned<IPropertyTreeIterator> iter = instance.srcArchive->getElements("OnWarning");
ForEach(*iter)
{
const char * option = iter->query().queryProp("@value");
if (!severityMapper->addCommandLineMapping(option))
return;
}
}
IErrorReceiver & errorProcessor = *severityMapper;
//All dlls/exes are essentially cloneable because you may be running multiple instances at once
//The only exception would be a dll created for a one-time query. (Currently handled by eclserver.)
instance.wu->setCloneable(true);
applyDebugOptions(instance.wu);
applyApplicationOptions(instance.wu);
if (optTargetCompiler != DEFAULT_COMPILER)
instance.wu->setDebugValue("targetCompiler", compilerTypeText[optTargetCompiler], true);
bool withinRepository = (queryAttributePath && *queryAttributePath);
bool syntaxChecking = instance.wu->getDebugValueBool("syntaxCheck", false);
size32_t prevErrs = errorProcessor.errCount();
unsigned startTime = msTick();
const char * sourcePathname = queryContents ? queryContents->querySourcePath()->str() : NULL;
const char * defaultErrorPathname = sourcePathname ? sourcePathname : queryAttributePath;
//The following is only here to provide information about the source file being compiled when reporting leaks
setActiveSource(instance.inputFile->queryFilename());
{
//Minimize the scope of the parse context to reduce lifetime of cached items.
HqlParseContext parseCtx(instance.dataServer, instance.archive);
if (optGenerateMeta || optIncludeMeta)
{
HqlParseContext::MetaOptions options;
options.includePublicDefinitions = instance.wu->getDebugValueBool("metaIncludePublic", true);
options.includePrivateDefinitions = instance.wu->getDebugValueBool("metaIncludePrivate", true);
options.onlyGatherRoot = instance.wu->getDebugValueBool("metaIncludeMainOnly", false);
options.includeImports = instance.wu->getDebugValueBool("metaIncludeImports", true);
options.includeExternalUses = instance.wu->getDebugValueBool("metaIncludeExternalUse", true);
options.includeExternalUses = instance.wu->getDebugValueBool("metaIncludeExternalUse", true);
options.includeLocations = instance.wu->getDebugValueBool("metaIncludeLocations", true);
options.includeJavadoc = instance.wu->getDebugValueBool("metaIncludeJavadoc", true);
parseCtx.setGatherMeta(options);
}
setLegacyEclSemantics(instance.legacyImport, instance.legacyWhen);
if (instance.archive)
{
instance.archive->setPropBool("@legacyImport", instance.legacyImport);
instance.archive->setPropBool("@legacyWhen", instance.legacyWhen);
}
parseCtx.ignoreUnknownImport = instance.ignoreUnknownImport;
try
{
HqlLookupContext ctx(parseCtx, &errorProcessor);
if (withinRepository)
{
if (instance.archive)
{
instance.archive->setProp("Query", "");
instance.archive->setProp("Query/@attributePath", queryAttributePath);
}
instance.query.setown(getResolveAttributeFullPath(queryAttributePath, LSFpublic, ctx));
if (!instance.query && !syntaxChecking && (errorProcessor.errCount() == prevErrs))
{
StringBuffer msg;
msg.append("Could not resolve attribute ").append(queryAttributePath);
errorProcessor.reportError(3, msg.str(), defaultErrorPathname, 0, 0, 0);
}
}
else
{
Owned<IHqlScope> scope = createPrivateScope();
if (instance.legacyImport)
importRootModulesToScope(scope, ctx);
instance.query.setown(parseQuery(scope, queryContents, ctx, NULL, NULL, true));
if (instance.archive)
{
StringBuffer queryText;
queryText.append(queryContents->length(), queryContents->getText());
const char * p = queryText;
if (0 == strncmp(p, (const char *)UTF8_BOM,3))
p += 3;
instance.archive->setProp("Query", p );
instance.archive->setProp("Query/@originalFilename", sourcePathname);
}
}
gatherParseWarnings(ctx.errs, instance.query, parseCtx.orphanedWarnings);
if (instance.query && !syntaxChecking && !optGenerateMeta && !optEvaluateResult)
instance.query.setown(convertAttributeToQuery(instance.query, ctx));
instance.stats.parseTime = msTick()-startTime;
if (instance.wu->getDebugValueBool("addTimingToWorkunit", true))
updateWorkunitTimeStat(instance.wu, "eclcc", "workunit", "parse time", NULL, milliToNano(instance.stats.parseTime), 1, 0);
if (optIncludeMeta || optGenerateMeta)
instance.generatedMeta.setown(parseCtx.getMetaTree());
if (optEvaluateResult && !errorProcessor.errCount() && instance.query)
evaluateResult(instance);
}
catch (IException *e)
{
StringBuffer s;
e->errorMessage(s);
errorProcessor.reportError(3, s.toCharArray(), defaultErrorPathname, 1, 0, 0);
e->Release();
}
}
//Free up the repository (and any cached expressions) as soon as the expression has been parsed
instance.dataServer.clear();
if (!syntaxChecking && (errorProcessor.errCount() == prevErrs) && (!instance.query || !containsAnyActions(instance.query)))
{
errorProcessor.reportError(3, "Query is empty", defaultErrorPathname, 1, 0, 0);
return;
}
if (instance.archive)
return;
if (syntaxChecking || optGenerateMeta || optEvaluateResult)
return;
StringBuffer targetFilename;
const char * outputFilename = instance.outputFilename;
if (!outputFilename)
{
addNonEmptyPathSepChar(targetFilename.append(optOutputDirectory));
targetFilename.append(DEFAULT_OUTPUTNAME);
}
else if (strcmp(outputFilename, "-") == 0)
targetFilename.append("stdout:");
else
addNonEmptyPathSepChar(targetFilename.append(optOutputDirectory)).append(outputFilename);
//Check if it overlaps with the source file and add .eclout if so
if (instance.inputFile)
{
const char * originalFilename = instance.inputFile->queryFilename();
if (streq(targetFilename, originalFilename))
targetFilename.append(".eclout");
}
if (errorProcessor.errCount() == prevErrs)
{
const char * queryFullName = NULL;
instantECL(instance, instance.wu, queryFullName, errorProcessor, targetFilename);
}
else
{
if (stdIoHandle(targetFilename) == -1)
{
// MORE - what about intermediate files?
#ifdef _WIN32
StringBuffer goer;
remove(goer.append(targetFilename).append(".exe"));
remove(goer.clear().append(targetFilename).append(".exe.manifest"));
#else
remove(targetFilename);
#endif
}
}
unsigned totalTime = msTick() - startTime;
instance.stats.generateTime = totalTime - instance.stats.parseTime;
if (instance.wu->getDebugValueBool("addTimingToWorkunit", true))
updateWorkunitTimeStat(instance.wu, "eclcc", "workunit", "totalTime", NULL, milliToNano(totalTime), 1, 0);
}
void EclCC::processXmlFile(EclCompileInstance & instance, const char *archiveXML)
{
instance.srcArchive.setown(createPTreeFromXMLString(archiveXML, ipt_caseInsensitive));
IPropertyTree * archiveTree = instance.srcArchive;
Owned<IPropertyTreeIterator> iter = archiveTree->getElements("Option");
ForEach(*iter)
{
IPropertyTree &item = iter->query();
instance.wu->setDebugValue(item.queryProp("@name"), item.queryProp("@value"), true);
}
const char * queryText = archiveTree->queryProp("Query");
const char * queryAttributePath = archiveTree->queryProp("Query/@attributePath");
//Takes precedence over an entry in the archive - so you can submit parts of an archive.
if (optQueryRepositoryReference)
queryAttributePath = optQueryRepositoryReference;
//The legacy mode (if specified) in the archive takes precedence - it needs to match to compile.
instance.legacyImport = archiveTree->getPropBool("@legacyMode", instance.legacyImport);
instance.legacyWhen = archiveTree->getPropBool("@legacyMode", instance.legacyWhen);
instance.legacyImport = archiveTree->getPropBool("@legacyImport", instance.legacyImport);
instance.legacyWhen = archiveTree->getPropBool("@legacyWhen", instance.legacyWhen);
//Some old archives contained imports, but no definitions of the module. This option is to allow them to compile.
//It shouldn't be needed for new archives in non-legacy mode. (But neither should it cause any harm.)
instance.ignoreUnknownImport = archiveTree->getPropBool("@ignoreUnknownImport", true);
instance.eclVersion.set(archiveTree->queryProp("@eclVersion"));
if (optCheckEclVersion)
instance.checkEclVersionCompatible();
Owned<IEclSourceCollection> archiveCollection;
if (archiveTree->getPropBool("@testRemoteInterface", false))
{
//This code is purely here for regression testing some of the classes used in the enterprise version.
Owned<IXmlEclRepository> xmlRepository = createArchiveXmlEclRepository(archiveTree);
archiveCollection.setown(createRemoteXmlEclCollection(NULL, *xmlRepository, NULL, false));
archiveCollection->checkCacheValid();
}
else
archiveCollection.setown(createArchiveEclCollection(archiveTree));
EclRepositoryArray repositories;
repositories.append(*LINK(pluginsRepository));
if (archiveTree->getPropBool("@useLocalSystemLibraries", false)) // Primarily for testing.
repositories.append(*LINK(libraryRepository));
Owned<IFileContents> contents;
StringBuffer fullPath; // Here so it doesn't get freed when leaving the else block
if (queryText || queryAttributePath)
{
const char * sourceFilename = archiveTree->queryProp("Query/@originalFilename");
Owned<ISourcePath> sourcePath = createSourcePath(sourceFilename);
contents.setown(createFileContentsFromText(queryText, sourcePath));
if (queryAttributePath && queryText && *queryText)
{
Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(queryAttributePath, contents);
repositories.append(*createRepository(inputFileCollection));
}
}
else
{
//This is really only useful for regression testing
const char * queryText = archiveTree->queryProp("SyntaxCheck");
const char * syntaxCheckModule = archiveTree->queryProp("SyntaxCheck/@module");
const char * syntaxCheckAttribute = archiveTree->queryProp("SyntaxCheck/@attribute");
if (!queryText || !syntaxCheckModule || !syntaxCheckAttribute)
throw MakeStringException(1, "No query found in xml");
instance.wu->setDebugValueInt("syntaxCheck", true, true);
fullPath.append(syntaxCheckModule).append('.').append(syntaxCheckAttribute);
queryAttributePath = fullPath.str();
//Create a repository with just that attribute, and place it before the archive in the resolution order.
Owned<IFileContents> contents = createFileContentsFromText(queryText, NULL);
repositories.append(*createSingleDefinitionEclRepository(syntaxCheckModule, syntaxCheckAttribute, contents));
}
repositories.append(*createRepository(archiveCollection));
instance.dataServer.setown(createCompoundRepository(repositories));
//Ensure classes are not linked by anything else
archiveCollection.clear();
repositories.kill();
processSingleQuery(instance, contents, queryAttributePath);
}
//=========================================================================================
void EclCC::processFile(EclCompileInstance & instance)
{
const char * curFilename = instance.inputFile->queryFilename();
assertex(curFilename);
Owned<ISourcePath> sourcePath = createSourcePath(curFilename);
Owned<IFileContents> queryText = createFileContentsFromFile(curFilename, sourcePath);
const char * queryTxt = queryText->getText();
if (optArchive || optGenerateDepend)
instance.archive.setown(createAttributeArchive());
instance.wu.setown(createLocalWorkUnit());
if (optSaveQueryText)
{
Owned<IWUQuery> q = instance.wu->updateQuery();
q->setQueryText(queryTxt);
}
//On a system with userECL not allowed, all compilations must be from checked-in code that has been
//deployed to the eclcc machine via other means (typically via a version-control system)
if (!allowAccess("userECL") && (!optQueryRepositoryReference || queryText->length()))
{
instance.queryErrorProcessor().reportError(HQLERR_UserCodeNotAllowed, HQLERR_UserCodeNotAllowed_Text, NULL, 1, 0, 0);
}
else if (isArchiveQuery(queryTxt))
{
instance.fromArchive = true;
processXmlFile(instance, queryTxt);
}
else
{
StringBuffer attributePath;
bool withinRepository = false;
bool inputFromStdIn = streq(curFilename, "stdin:");
//Specifying --main indicates that the query text (if present) replaces that definition
if (optQueryRepositoryReference)
{
withinRepository = true;
attributePath.clear().append(optQueryRepositoryReference);
}
else
{
withinRepository = !inputFromStdIn && checkWithinRepository(attributePath, curFilename);
}
StringBuffer expandedSourceName;
if (!inputFromStdIn)
makeAbsolutePath(curFilename, expandedSourceName);
else
expandedSourceName.append(curFilename);
EclRepositoryArray repositories;
repositories.append(*LINK(pluginsRepository));
repositories.append(*LINK(libraryRepository));
if (bundlesRepository)
repositories.append(*LINK(bundlesRepository));
//Ensure that this source file is used as the definition (in case there are potential clashes)
//Note, this will not override standard library files.
if (withinRepository)
{
//-main only overrides the definition if the query is non-empty. Otherwise use the existing text.
if (!optQueryRepositoryReference || queryText->length())
{
Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(attributePath, queryText);
repositories.append(*createRepository(inputFileCollection));
}
}
else
{
//Ensure that $ is valid for any file submitted - even if it isn't in the include direcotories
//Disable this for the moment when running the regression suite.
if (!optBatchMode && !withinRepository && !inputFromStdIn && !optLegacyImport)
{
//Associate the contents of the directory with an internal module called _local_directory_
//(If it was root it might override existing root symbols). $ is the only public way to get at the symbol
const char * moduleName = "_local_directory_";
IIdAtom * moduleNameId = createIdAtom(moduleName);
StringBuffer thisDirectory;
StringBuffer thisTail;
splitFilename(expandedSourceName, &thisDirectory, &thisDirectory, &thisTail, NULL);
attributePath.append(moduleName).append(".").append(thisTail);
Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(attributePath, queryText);
repositories.append(*createRepository(inputFileCollection));
Owned<IEclSourceCollection> directory = createFileSystemEclCollection(&instance.queryErrorProcessor(), thisDirectory, 0, 0);
Owned<IEclRepository> directoryRepository = createRepository(directory, moduleName);
Owned<IEclRepository> nested = createNestedRepository(moduleNameId, directoryRepository);
repositories.append(*LINK(nested));
}
}
repositories.append(*LINK(includeRepository));
instance.dataServer.setown(createCompoundRepository(repositories));
repositories.kill();
processSingleQuery(instance, queryText, attributePath.str());
}
if (instance.reportErrorSummary() && !instance.archive && !(optGenerateMeta && instance.generatedMeta))
return;
generateOutput(instance);
}
IFileIO * EclCC::createArchiveOutputFile(EclCompileInstance & instance)
{
StringBuffer archiveName;
if (instance.outputFilename && !streq(instance.outputFilename, "-"))
addNonEmptyPathSepChar(archiveName.append(optOutputDirectory)).append(instance.outputFilename);
else
archiveName.append("stdout:");
//Work around windows problem writing 64K to stdout if not redirected/piped
OwnedIFile ifile = createIFile(archiveName);
return ifile->open(IFOcreate);
}
void EclCC::outputXmlToOutputFile(EclCompileInstance & instance, IPropertyTree * xml)
{
OwnedIFileIO ifileio = createArchiveOutputFile(instance);
if (ifileio)
{
//Work around windows problem writing 64K to stdout if not redirected/piped
Owned<IIOStream> stream = createIOStream(ifileio.get());
Owned<IIOStream> buffered = createBufferedIOStream(stream,0x8000);
saveXML(*buffered, xml);
}
}
void EclCC::addFilenameDependency(StringBuffer & target, EclCompileInstance & instance, const char * filename)
{
if (!filename)
return;
//Ignore plugins and standard library components
if (isWithinPath(filename, pluginsPath) || isWithinPath(filename, eclLibraryPath))
return;
//Don't include the input file in the dependencies.
if (instance.inputFile)
{
const char * sourceFilename = instance.inputFile->queryFilename();
if (sourceFilename && streq(sourceFilename, filename))
return;
}
target.append(filename).newline();
}
void EclCC::generateOutput(EclCompileInstance & instance)
{
const char * outputFilename = instance.outputFilename;
if (instance.archive)
{
if (optGenerateDepend)
{
//Walk the archive, and output all filenames that aren't
//a)in a plugin b) in std.lib c) the original source file.
StringBuffer filenames;
Owned<IPropertyTreeIterator> modIter = instance.archive->getElements("Module");
ForEach(*modIter)
{
IPropertyTree * module = &modIter->query();
if (module->hasProp("@plugin"))
continue;
addFilenameDependency(filenames, instance, module->queryProp("@sourcePath"));
Owned<IPropertyTreeIterator> defIter = module->getElements("Attribute");
ForEach(*defIter)
{
IPropertyTree * definition = &defIter->query();
addFilenameDependency(filenames, instance, definition->queryProp("@sourcePath"));
}
}
OwnedIFileIO ifileio = createArchiveOutputFile(instance);
if (ifileio)
ifileio->write(0, filenames.length(), filenames.str());
}
else
{
// Output option settings
Owned<IStringIterator> debugValues = &instance.wu->getDebugValues();
ForEach (*debugValues)
{
SCMStringBuffer debugStr, valueStr;
debugValues->str(debugStr);
instance.wu->getDebugValue(debugStr.str(), valueStr);
Owned<IPropertyTree> option = createPTree("Option");
option->setProp("@name", debugStr.str());
option->setProp("@value", valueStr.str());
instance.archive->addPropTree("Option", option.getClear());
}
if (optManifestFilename)
addManifestResourcesToArchive(instance.archive, optManifestFilename);
outputXmlToOutputFile(instance, instance.archive);
}
}
if (optGenerateMeta && instance.generatedMeta)
outputXmlToOutputFile(instance, instance.generatedMeta);
if (optWorkUnit && instance.wu)
{
StringBuffer xmlFilename;
addNonEmptyPathSepChar(xmlFilename.append(optOutputDirectory));
if (outputFilename)
xmlFilename.append(outputFilename);
else
xmlFilename.append(DEFAULT_OUTPUTNAME);
xmlFilename.append(".xml");
exportWorkUnitToXMLFile(instance.wu, xmlFilename, 0, true, false);
}
}
void EclCC::processReference(EclCompileInstance & instance, const char * queryAttributePath)
{
const char * outputFilename = instance.outputFilename;
instance.wu.setown(createLocalWorkUnit());
if (optArchive || optGenerateDepend)
instance.archive.setown(createAttributeArchive());
EclRepositoryArray repositories;
repositories.append(*LINK(pluginsRepository));
repositories.append(*LINK(libraryRepository));
if (bundlesRepository)
repositories.append(*LINK(bundlesRepository));
repositories.append(*LINK(includeRepository));
instance.dataServer.setown(createCompoundRepository(repositories));
processSingleQuery(instance, NULL, queryAttributePath);
if (instance.reportErrorSummary())
return;
generateOutput(instance);
}
bool EclCC::generatePrecompiledHeader()
{
if (inputFiles.ordinality() != 0)
{
ERRLOG("No input files should be specified when generating precompiled header");
return false;
}
StringArray paths;
paths.appendList(cppIncludePath, ENVSEPSTR);
const char *foundPath = NULL;
ForEachItemIn(idx, paths)
{
StringBuffer fullpath;
fullpath.append(paths.item(idx));
addPathSepChar(fullpath).append("eclinclude4.hpp");
if (checkFileExists(fullpath))
{
foundPath = paths.item(idx);
break;
}
}
if (!foundPath)
{
ERRLOG("Cannot find eclinclude4.hpp");
return false;
}
Owned<ICppCompiler> compiler = createCompiler("eclinclude4.hpp", foundPath, NULL);
compiler->setDebug(true); // a precompiled header with debug can be used for no-debug, but not vice versa
compiler->setPrecompileHeader(true);
if (compiler->compile())
{
try
{
Owned<IFile> log = createIFile(cclogFilename);
log->remove();
}
catch (IException * e)
{
e->Release();
}
return true;
}
else
{
ERRLOG("Compilation failed - see %s for details", cclogFilename.str());
return false;
}
}
bool EclCC::processFiles()
{
loadOptions();
ForEachItemIn(idx, inputFileNames)
{
processArgvFilename(inputFiles, inputFileNames.item(idx));
}
if (optShowPaths)
{
printf("CL_PATH=%s\n", compilerPath.str());
printf("ECLCC_ECLBUNDLE_PATH=%s\n", eclBundlePath.str());
printf("ECLCC_ECLINCLUDE_PATH=%s\n", stdIncludeLibraryPath.str());
printf("ECLCC_ECLLIBRARY_PATH=%s\n", eclLibraryPath.str());
printf("ECLCC_INCLUDE_PATH=%s\n", cppIncludePath.str());
printf("ECLCC_LIBRARY_PATH=%s\n", libraryPath.str());
printf("ECLCC_PLUGIN_PATH=%s\n", pluginsPath.str());
printf("ECLCC_TPL_PATH=%s\n", templatePath.str());
printf("HPCC_FILEHOOKS_PATH=%s\n", hooksPath.str());
return true;
}
if (optGenerateHeader)
{
return generatePrecompiledHeader();
}
else if (inputFiles.ordinality() == 0)
{
if (optBatchMode || !optQueryRepositoryReference)
{
ERRLOG("No input files could be opened");
return false;
}
}
StringBuffer searchPath;
if (!optNoStdInc)
searchPath.append(stdIncludeLibraryPath).append(ENVSEPCHAR);
searchPath.append(includeLibraryPath);
Owned<IErrorReceiver> errs = createFileErrorReceiver(stderr);
pluginsRepository.setown(createNewSourceFileEclRepository(errs, pluginsPath.str(), ESFallowplugins, logVerbose ? PLUGIN_DLL_MODULE : 0));
if (!optNoBundles)
bundlesRepository.setown(createNewSourceFileEclRepository(errs, eclBundlePath.str(), 0, 0));
libraryRepository.setown(createNewSourceFileEclRepository(errs, eclLibraryPath.str(), 0, 0));
includeRepository.setown(createNewSourceFileEclRepository(errs, searchPath.str(), 0, 0));
//Ensure symbols for plugins are initialised - see comment before CHqlMergedScope...
// lookupAllRootDefinitions(pluginsRepository);
bool ok = true;
if (optBatchMode)
{
processBatchFiles();
}
else if (inputFiles.ordinality() == 0)
{
assertex(optQueryRepositoryReference);
EclCompileInstance info(NULL, *errs, stderr, optOutputFilename, optLegacyImport, optLegacyWhen);
processReference(info, optQueryRepositoryReference);
ok = (errs->errCount() == 0);
info.logStats();
}
else
{
EclCompileInstance info(&inputFiles.item(0), *errs, stderr, optOutputFilename, optLegacyImport, optLegacyWhen);
processFile(info);
ok = (errs->errCount() == 0);
info.logStats();
}
if (logTimings)
{
StringBuffer s;
fprintf(stderr, "%s", defaultTimer->getTimings(s).str());
}
return ok;
}
void EclCC::setDebugOption(const char * name, bool value)
{
StringBuffer temp;
temp.append(name).append("=").append(value ? "1" : "0");
debugOptions.append(temp);
}
void EclCompileInstance::checkEclVersionCompatible()
{
//Strange function that might modify errorProcessor...
::checkEclVersionCompatible(errorProcessor, eclVersion);
}
void EclCompileInstance::logStats()
{
if (wu && wu->getDebugValueBool("logCompileStats", false))
{
memsize_t peakVm, peakResident;
getPeakMemUsage(peakVm, peakResident);
//Stats: added as a prefix so it is easy to grep, and a comma so can be read as a csv list.
DBGLOG("Stats:,parse,%u,generate,%u,peakmem,%u,xml,%"I64F"u,cpp,%"I64F"u",
stats.parseTime, stats.generateTime, (unsigned)(peakResident / 0x100000),
(unsigned __int64)stats.xmlSize, (unsigned __int64)stats.cppSize);
}
}
bool EclCompileInstance::reportErrorSummary()
{
if (errorProcessor->errCount() || errorProcessor->warnCount())
{
fprintf(errout, "%d error%s, %d warning%s\n", errorProcessor->errCount(), errorProcessor->errCount()<=1 ? "" : "s",
errorProcessor->warnCount(), errorProcessor->warnCount()<=1?"":"s");
}
return errorProcessor->errCount() != 0;
}
//=========================================================================================
void EclCC::noteCluster(const char *clusterName)
{
}
void EclCC::registerFile(const char * filename, const char * description)
{
}
bool EclCC::allowAccess(const char * category)
{
ForEachItemIn(idx1, deniedPermissions)
{
if (stricmp(deniedPermissions.item(idx1), category)==0)
return false;
}
ForEachItemIn(idx2, allowedPermissions)
{
if (stricmp(allowedPermissions.item(idx2), category)==0)
return true;
}
return defaultAllowed;
}
//=========================================================================================
bool EclCC::parseCommandLineOptions(int argc, const char* argv[])
{
if (argc < 2)
{
usage();
return false;
}
ArgvIterator iter(argc, argv);
StringAttr tempArg;
bool tempBool;
bool showHelp = false;
for (; !iter.done(); iter.next())
{
const char * arg = iter.query();
if (iter.matchFlag(tempArg, "-a"))
{
applicationOptions.append(tempArg);
}
else if (iter.matchOption(tempArg, "--allow"))
{
allowedPermissions.append(tempArg);
}
else if (iter.matchFlag(optBatchMode, "-b"))
{
}
else if (iter.matchOption(tempArg, "-brk"))
{
#if defined(_WIN32) && defined(_DEBUG)
unsigned id = atoi(tempArg);
if (id == 0)
DebugBreak();
else
_CrtSetBreakAlloc(id);
#endif
}
else if (iter.matchFlag(optOnlyCompile, "-c"))
{
}
else if (iter.matchFlag(optCheckEclVersion, "-checkVersion"))
{
}
else if (iter.matchOption(tempArg, "--deny"))
{
if (stricmp(tempArg, "all")==0)
defaultAllowed = false;
else
deniedPermissions.append(tempArg);
}
else if (iter.matchFlag(optArchive, "-E"))
{
}
else if (iter.matchFlag(tempArg, "-f"))
{
debugOptions.append(tempArg);
}
else if (iter.matchFlag(tempBool, "-g"))
{
if (tempBool)
{
debugOptions.append("debugQuery");
debugOptions.append("saveCppTempFiles");
}
else
debugOptions.append("debugQuery=0");
}
else if (strcmp(arg, "-internal")==0)
{
testHqlInternals();
}
else if (iter.matchFlag(tempBool, "-save-cpps"))
{
setDebugOption("saveCppTempFiles", tempBool);
}
else if (iter.matchFlag(tempBool, "-save-temps"))
{
setDebugOption("saveEclTempFiles", tempBool);
}
else if (iter.matchFlag(showHelp, "-help") || iter.matchFlag(showHelp, "--help"))
{
}
else if (iter.matchPathFlag(includeLibraryPath, "-I"))
{
}
else if (iter.matchFlag(tempArg, "-L"))
{
libraryPaths.append(tempArg);
}
else if (iter.matchFlag(tempBool, "-legacy"))
{
optLegacyImport = tempBool;
optLegacyWhen = tempBool;
}
else if (iter.matchFlag(optLegacyImport, "-legacyimport"))
{
}
else if (iter.matchFlag(optLegacyWhen, "-legacywhen"))
{
}
else if (iter.matchOption(optLogfile, "--logfile"))
{
}
else if (iter.matchFlag(optNoLogFile, "--nologfile"))
{
}
else if (iter.matchFlag(optNoStdInc, "--nostdinc"))
{
}
else if (iter.matchFlag(optNoBundles, "--nobundles"))
{
}
else if (iter.matchOption(optLogDetail, "--logdetail"))
{
}
else if (iter.matchOption(optQueryRepositoryReference, "-main"))
{
}
else if (iter.matchFlag(optDebugMemLeak, "-m"))
{
}
else if (iter.matchFlag(optIncludeMeta, "-meta"))
{
}
else if (iter.matchFlag(optGenerateMeta, "-M"))
{
}
else if (iter.matchFlag(optGenerateDepend, "-Md"))
{
}
else if (iter.matchFlag(optEvaluateResult, "-Me"))
{
}
else if (iter.matchFlag(optOutputFilename, "-o"))
{
}
else if (iter.matchFlag(optOutputDirectory, "-P"))
{
}
else if (iter.matchFlag(optGenerateHeader, "-pch"))
{
}
else if (iter.matchFlag(optSaveQueryText, "-q"))
{
}
else if (iter.matchFlag(optNoCompile, "-S"))
{
}
else if (iter.matchFlag(optShared, "-shared"))
{
}
else if (iter.matchFlag(tempBool, "-syntax"))
{
setDebugOption("syntaxCheck", tempBool);
}
else if (iter.matchOption(optIniFilename, "-specs"))
{
if (!checkFileExists(optIniFilename))
{
ERRLOG("Error: INI file '%s' does not exist",optIniFilename.get());
return false;
}
}
else if (iter.matchFlag(optShowPaths, "-showpaths"))
{
}
else if (iter.matchOption(optManifestFilename, "-manifest"))
{
if (!isManifestFileValid(optManifestFilename))
return false;
}
else if (iter.matchOption(tempArg, "-split"))
{
batchPart = atoi(tempArg)-1;
const char * split = strchr(tempArg, ':');
if (!split)
{
ERRLOG("Error: syntax is -split=part:splits\n");
return false;
}
batchSplit = atoi(split+1);
if (batchSplit == 0)
batchSplit = 1;
if (batchPart >= batchSplit)
batchPart = 0;
}
else if (iter.matchFlag(logTimings, "--timings"))
{
}
else if (iter.matchOption(tempArg, "-platform") || /*deprecated*/ iter.matchOption(tempArg, "-target"))
{
if (!setTargetPlatformOption(tempArg.get(), optTargetClusterType))
return false;
}
else if (iter.matchFlag(logVerbose, "-v") || iter.matchFlag(logVerbose, "--verbose"))
{
Owned<ILogMsgFilter> filter = getDefaultLogMsgFilter();
queryLogMsgManager()->changeMonitorFilter(queryStderrLogMsgHandler(), filter);
}
else if (strcmp(arg, "--version")==0)
{
fprintf(stdout,"%s %s\n", LANGUAGE_VERSION, BUILD_TAG);
return false;
}
else if (startsWith(arg, "-Wc,"))
{
expandCommaList(compileOptions, arg+4);
}
else if (startsWith(arg, "-Wl,"))
{
//Pass these straight through to the linker - with -Wl, prefix removed
linkOptions.append(arg+4);
}
else if (startsWith(arg, "-Wp,") || startsWith(arg, "-Wa,"))
{
//Pass these straight through to the gcc compiler
compileOptions.append(arg);
}
else if (iter.matchFlag(optWorkUnit, "-wu"))
{
}
else if (iter.matchFlag(tempArg, "-w"))
{
//Any other option beginning -wxxx are treated as warning mappings
warningMappings.append(tempArg);
}
else if (strcmp(arg, "-")==0)
{
inputFileNames.append("stdin:");
}
else if (arg[0] == '-')
{
ERRLOG("Error: unrecognised option %s",arg);
usage();
return false;
}
else
inputFileNames.append(arg);
}
if (showHelp)
{
usage();
return false;
}
// Option post processing follows:
if (optArchive || optWorkUnit || optGenerateMeta || optGenerateDepend || optShowPaths)
optNoCompile = true;
loadManifestOptions();
if (inputFileNames.ordinality() == 0)
{
if (optGenerateHeader || optShowPaths || (!optBatchMode && optQueryRepositoryReference))
return true;
ERRLOG("No input filenames supplied");
return false;
}
if (optDebugMemLeak)
{
StringBuffer title;
title.append(inputFileNames.item(0)).newline();
initLeakCheck(title);
}
return true;
}
//=========================================================================================
// Exclamation in the first column indicates it is only part of the verbose output
const char * const helpText[] = {
"",
"Usage:",
" eclcc <options> queryfile.ecl",
"",
"General options:",
" -I <path> Add path to locations to search for ecl imports",
" -L <path> Add path to locations to search for system libraries",
" -o <file> Specify name of output file (default a.out if linking to",
" executable, or stdout)",
" -manifest Specify path to manifest file listing resources to add",
" -foption[=value] Set an ecl option (#option)",
" -main <ref> Compile definition <ref> from the source collection",
" -syntax Perform a syntax check of the ECL",
" -platform=hthor Generate code for hthor executable (default)",
" -platform=roxie Generate code for roxie cluster",
" -platform=thor Generate code for thor cluster",
"",
"Output control options",
" -E Output preprocessed ECL in xml archive form",
"! -M Output meta information for the ecl files",
"! -Md Output dependency information",
"! -Me eclcc should evaluate supplied ecl code rather than generating a workunit",
" -q Save ECL query text as part of workunit",
" -wu Only generate workunit information as xml file",
"",
"c++ options",
" -S Generate c++ output, but don't compile",
"! -c compile only (don't link)",
" -g Enable debug symbols in generated code",
" -Wc,xx Pass option xx to the c++ compiler",
"! -Wl,xx Pass option xx to the linker",
"! -Wa,xx Passed straight through to c++ compiler",
"! -Wp,xx Passed straight through to c++ compiler",
"! -save-cpps Do not delete generated c++ files (implied if -g)",
"! -save-temps Do not delete intermediate files",
" -shared Generate workunit shared object instead of a stand-alone exe",
"",
"Other options:",
"! -aoption[=value] Set an application option",
"! --allow=str Allow use of named feature",
"! -b Batch mode. Each source file is processed in turn. Output",
"! name depends on the input filename",
"! -checkVersion Enable/disable ecl version checking from archives",
#ifdef _WIN32
"! -brk <n> Trigger a break point in eclcc after nth allocation",
#endif
"! --deny=all Disallow use of all named features not specifically allowed using --allow",
"! --deny=str Disallow use of named feature",
" -help, --help Display this message",
" -help -v Display verbose help message",
"! -internal Run internal tests",
"! -legacy Use legacy import and when semantics (deprecated)",
"! -legacyimport Use legacy import semantics (deprecated)",
"! -legacywhen Use legacy when/side-effects semantics (deprecated)",
" --logfile <file> Write log to specified file",
"! --logdetail=n Set the level of detail in the log file",
"! --nologfile Do not write any logfile",
#ifdef _WIN32
"! -m Enable leak checking",
#endif
#ifndef _WIN32
"! -pch Generate precompiled header for eclinclude4.hpp",
#endif
"! -P <path> Specify the path of the output files (only with -b option)",
"! -showpaths Print information about the searchpaths eclcc is using",
" -specs file Read eclcc configuration from specified file",
"! -split m:n Process a subset m of n input files (only with -b option)",
" -v --verbose Output additional tracing information while compiling",
" -wcode=level Set the severity for a particular warning code",
"! level=ignore|log|warning|error|fail",
" --version Output version information",
"! --timings Output additional timing information",
"!",
"!#options",
"! -factivitiesPerCpp Number of activities in each c++ file",
"! (requires -fspanMultipleCpp)",
"! -fapplyInstantEclTransformations Limit non file outputs with a CHOOSEN",
"! -fapplyInstantEclTransformationsLimit Number of records to limit to",
"! -fcheckAsserts Check ASSERT() statements",
"! -fmaxCompileThreads Number of compiler instances to compile the c++",
"! -fnoteRecordSizeInGraph Add estimates of record sizes to the graph",
"! -fpickBestEngine Allow simple thor queries to be passed to thor",
"! -fshowActivitySizeInGraph Show estimates of generated c++ size in the graph",
"! -fshowMetaInGraph Add distribution/sort orders to the graph",
"! -fshowRecordCountInGraph Show estimates of record counts in the graph",
"! -fspanMultipleCpp Generate a work unit in multiple c++ files",
"",
};
void EclCC::usage()
{
for (unsigned line=0; line < _elements_in(helpText); line++)
{
const char * text = helpText[line];
if (*text == '!')
{
if (logVerbose)
{
//Allow conditional headers
if (text[1] == ' ')
fprintf(stdout, " %s\n", text+1);
else
fprintf(stdout, "%s\n", text+1);
}
}
else
fprintf(stdout, "%s\n", text);
}
}
//=========================================================================================
// The following methods are concerned with running eclcc in batch mode (primarily to aid regression testing)
void EclCC::processBatchedFile(IFile & file, bool multiThreaded)
{
StringBuffer basename, logFilename, xmlFilename, outFilename;
splitFilename(file.queryFilename(), NULL, NULL, &basename, &basename);
addNonEmptyPathSepChar(logFilename.append(optOutputDirectory)).append(basename).append(".log");
addNonEmptyPathSepChar(xmlFilename.append(optOutputDirectory)).append(basename).append(".xml");
splitFilename(file.queryFilename(), NULL, NULL, &outFilename, &outFilename);
unsigned startTime = msTick();
FILE * logFile = fopen(logFilename.str(), "w");
if (!logFile)
throw MakeStringException(99, "couldn't create log output %s", logFilename.str());
Owned<ILogMsgHandler> handler;
try
{
// Print compiler and arguments to help reproduce problems
for (int i=0; i<argc; i++)
fprintf(logFile, "%s ", argv[i]);
fprintf(logFile, "\n");
fprintf(logFile, "--- %s --- \n", basename.str());
{
if (!multiThreaded)
{
handler.setown(getHandleLogMsgHandler(logFile, 0, false));
Owned<ILogMsgFilter> filter = getCategoryLogMsgFilter(MSGAUD_all, MSGCLS_all, DefaultDetail);
queryLogMsgManager()->addMonitor(handler, filter);
resetUniqueId();
resetLexerUniqueNames();
}
Owned<IErrorReceiver> localErrs = createFileErrorReceiver(logFile);
EclCompileInstance info(&file, *localErrs, logFile, outFilename, optLegacyImport, optLegacyWhen);
processFile(info);
//Following only produces output if the system has been compiled with TRANSFORM_STATS defined
dbglogTransformStats(true);
if (info.wu &&
(info.wu->getDebugValueBool("generatePartialOutputOnError", false) || info.queryErrorProcessor().errCount() == 0))
{
exportWorkUnitToXMLFile(info.wu, xmlFilename, XML_NoBinaryEncode64, true, false);
Owned<IFile> xml = createIFile(xmlFilename);
info.stats.xmlSize = xml->size();
}
info.logStats();
}
}
catch (IException * e)
{
StringBuffer s;
e->errorMessage(s);
e->Release();
fprintf(logFile, "Unexpected exception: %s", s.str());
}
if (handler)
{
queryLogMsgManager()->removeMonitor(handler);
handler.clear();
}
fflush(logFile);
fclose(logFile);
unsigned nowTime = msTick();
StringBuffer s;
s.append(basename).append(":");
s.padTo(50);
s.appendf("%8d ms\n", nowTime-startTime);
fprintf(batchLog, "%s", s.str());
// fflush(batchLog);
}
typedef SafeQueueOf<IFile, true> RegressQueue;
class BatchThread : public Thread
{
public:
BatchThread(EclCC & _compiler, RegressQueue & _queue, Semaphore & _fileReady)
: compiler(_compiler), queue(_queue), fileReady(_fileReady)
{
}
virtual int run()
{
loop
{
fileReady.wait();
IFile * next = queue.dequeue();
if (!next)
return 0;
compiler.processBatchedFile(*next, true);
next->Release();
}
}
protected:
EclCC & compiler;
RegressQueue & queue;
Semaphore & fileReady;
};
int compareFilenames(IInterface * * pleft, IInterface * * pright)
{
IFile * left = static_cast<IFile *>(*pleft);
IFile * right = static_cast<IFile *>(*pright);
return stricmp(pathTail(left->queryFilename()), pathTail(right->queryFilename()));
}
void EclCC::processBatchFiles()
{
Thread * * threads = NULL;
RegressQueue queue;
Semaphore fileReady;
unsigned startAllTime = msTick();
if (optThreads > 0)
{
threads = new Thread * [optThreads];
for (unsigned i = 0; i < optThreads; i++)
{
threads[i] = new BatchThread(*this, queue, fileReady);
threads[i]->start();
}
}
StringBuffer batchLogName;
addNonEmptyPathSepChar(batchLogName.append(optOutputDirectory)).append("_batch_.");
batchLogName.append(batchPart+1);
batchLogName.append(".log");
batchLog = fopen(batchLogName.str(), "w");
if (!batchLog)
throw MakeStringException(99, "couldn't create log output %s", batchLogName.str());
//Divide the files up based on file size, rather than name
inputFiles.sort(compareFilenames);
unsigned __int64 totalSize = 0;
ForEachItemIn(iSize, inputFiles)
{
IFile & cur = inputFiles.item(iSize);
totalSize += cur.size();
}
//Sort the filenames so you have a consistent order between windows and linux
unsigned __int64 averageFileSize = totalSize / inputFiles.ordinality();
unsigned splitter = 0;
unsigned __int64 sizeSoFar = 0;
ForEachItemIn(i, inputFiles)
{
IFile &file = inputFiles.item(i);
if (splitter == batchPart)
{
if (optThreads > 0)
{
queue.enqueue(LINK(&file));
fileReady.signal();
}
else
processBatchedFile(file, false);
}
unsigned __int64 thisSize = file.size();
sizeSoFar += thisSize;
if (sizeSoFar > averageFileSize)
{
sizeSoFar = 0;
splitter++;
}
if (splitter == batchSplit)
splitter = 0;
}
if (optThreads > 0)
{
for (unsigned i = 0; i < optThreads; i++)
fileReady.signal();
for (unsigned j = 0; j < optThreads; j++)
threads[j]->join();
for (unsigned i2 = 0; i2 < optThreads; i2++)
threads[i2]->Release();
delete [] threads;
}
fprintf(batchLog, "@%5ds total time for part %d\n", (msTick()-startAllTime)/1000, batchPart);
fclose(batchLog);
batchLog = NULL;
}
| 35.300174 | 184 | 0.612988 | emuharemagic |
66f5b2c623ee7880fa709b0ca8bee1dd351cc54f | 137,676 | cpp | C++ | src/ngraph/runtime/cpu/pass/cpu_mkldnn_primitive_build.cpp | ilya-lavrenov/ngraph | 2d8b2b4b30dbcabda0c3de2ae458418e63da057a | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/cpu/pass/cpu_mkldnn_primitive_build.cpp | ilya-lavrenov/ngraph | 2d8b2b4b30dbcabda0c3de2ae458418e63da057a | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/cpu/pass/cpu_mkldnn_primitive_build.cpp | ilya-lavrenov/ngraph | 2d8b2b4b30dbcabda0c3de2ae458418e63da057a | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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 <string>
#include "cpu_mkldnn_primitive_build.hpp"
#include "ngraph/code_writer.hpp"
#include "ngraph/op/add.hpp"
#include "ngraph/op/avg_pool.hpp"
#include "ngraph/op/batch_norm.hpp"
#include "ngraph/op/concat.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/convert.hpp"
#include "ngraph/op/convolution.hpp"
#include "ngraph/op/dequantize.hpp"
#include "ngraph/op/experimental/quantized_conv_bias.hpp"
#include "ngraph/op/experimental/quantized_conv_relu.hpp"
#include "ngraph/op/experimental/quantized_dot_bias.hpp"
#include "ngraph/op/get_output_element.hpp"
#include "ngraph/op/lrn.hpp"
#include "ngraph/op/max_pool.hpp"
#include "ngraph/op/quantize.hpp"
#include "ngraph/op/quantized_convolution.hpp"
#include "ngraph/op/quantized_dot.hpp"
#include "ngraph/op/relu.hpp"
#include "ngraph/op/replace_slice.hpp"
#include "ngraph/op/reshape.hpp"
#include "ngraph/op/sigmoid.hpp"
#include "ngraph/op/slice.hpp"
#include "ngraph/op/softmax.hpp"
#include "ngraph/runtime/cpu/cpu_executor.hpp"
#include "ngraph/runtime/cpu/cpu_tensor_view_wrapper.hpp"
#include "ngraph/runtime/cpu/mkldnn_emitter.hpp"
#include "ngraph/runtime/cpu/mkldnn_utils.hpp"
#include "ngraph/runtime/cpu/op/convert_layout.hpp"
#include "ngraph/runtime/cpu/op/lstm.hpp"
#include "ngraph/runtime/cpu/op/max_pool_with_indices.hpp"
#include "ngraph/runtime/cpu/op/rnn.hpp"
#include "ngraph/runtime/cpu/op/update_slice.hpp"
#define WRITE_MKLDNN_DIMS(X) writer << "mkldnn::memory::dims{" << join(X) << "}, \n";
using namespace ngraph;
using namespace ngraph::op;
using namespace ngraph::runtime::cpu;
namespace ngraph
{
namespace runtime
{
namespace cpu
{
namespace pass
{
// serialize memory descriptors
static void serialize_memory_descs(std::ofstream& desc_file,
std::vector<mkldnn::memory::desc>& descs,
size_t index)
{
for (auto i = 0; i < descs.size(); i++)
{
desc_file << index;
desc_file.write(reinterpret_cast<char*>(&descs[i]),
sizeof(mkldnn::memory::desc));
index++;
}
}
// The following functions build the MKLDNN primitive for each type of nGraph Node.
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Add)
{
auto input0_data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto input1_data_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto sum_pd = mkldnn_emitter.get_elementwise_add_desc(node);
mkldnn_emitter.query_scratchpad_sum(sum_pd);
// Add needs 4 primitives: input0, input1, result, and sum.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
input0_data_desc, input1_data_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "std::vector<float> scale_vector(2, 1);\n";
writer << "std::vector<mkldnn::memory::desc> inputs_desc{"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], "
<< "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "]};\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
// elementwise sum primitive descriptor
writer << "mkldnn::sum::primitive_desc sum_pd = "
"mkldnn::sum::primitive_desc(*cg_ctx->mkldnn_descriptors["
<< desc_index + 2
<< "], "
"scale_vector, inputs_desc, cg_ctx->global_cpu_engine, attr);\n";
writer << "\n// build sum primitive\n";
// sum primitive
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::sum(sum_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(sum_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_rnn(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
const auto& out = node->get_outputs();
const auto& args = node->get_inputs();
auto rnn_node = static_cast<const OP*>(node);
auto src_sequence_length_max =
static_cast<unsigned long>(rnn_node->get_src_sequence_length());
auto direction = static_cast<unsigned long>(rnn_node->get_direction());
auto num_fused_layers =
static_cast<unsigned long>(rnn_node->get_num_fused_layers());
auto feature_size =
static_cast<unsigned long>(rnn_node->get_src_iter_feature_size());
auto batch = static_cast<unsigned long>(rnn_node->get_batch_size());
auto rnn_cell_n_gates =
static_cast<unsigned long>(rnn_node->get_gates_per_cell());
auto get_mkldnn_rnn_direction_string = [&]() {
switch (direction)
{
case 1:
return std::string("mkldnn::rnn_direction::unidirectional_left2right");
case 2: return std::string("mkldnn::rnn_direction::bidirectional_concat");
default: throw ngraph_error("unsupported mkldnn rnn direction");
}
};
auto get_mkldnn_rnn_direction = [&]() {
switch (direction)
{
case 1: return mkldnn::rnn_direction::unidirectional_left2right;
case 2: return mkldnn::rnn_direction::bidirectional_concat;
default: throw ngraph_error("unsupported mkldnn rnn direction");
}
};
if (out[0].get_shape().size() == 2 &&
(out[0].get_shape()[1] != direction * feature_size))
{
throw ngraph_error(
"input slc{ht} feature size is not equal to output dlc{ht} feature "
"size ");
}
if (out[1].get_shape().size() == 2 && (out[1].get_shape()[1] != feature_size) &&
rnn_node->get_num_timesteps() != 1)
{
throw ngraph_error(
"input sic{ht_1|ct_1} feature size is not equal to output "
"dlc{ht_1|ct_1} "
"feature size ");
}
Shape src_layer_tz{
src_sequence_length_max,
batch,
static_cast<unsigned long>(rnn_node->get_src_layer_feature_size())};
Shape src_iter_tz{num_fused_layers, direction, batch, feature_size};
Shape src_iter_c_tz{num_fused_layers, direction, batch, feature_size};
Shape wei_layer_tz{
num_fused_layers,
direction,
static_cast<unsigned long>(rnn_node->get_src_layer_feature_size()),
rnn_cell_n_gates,
feature_size};
Shape wei_iter_tz{
num_fused_layers, direction, feature_size, rnn_cell_n_gates, feature_size};
Shape bias_tz{num_fused_layers, direction, rnn_cell_n_gates, feature_size};
Shape dst_layer_tz{src_sequence_length_max, batch, direction * feature_size};
Shape dst_iter_tz{num_fused_layers, direction, batch, feature_size};
Shape dst_iter_c_tz{num_fused_layers, direction, batch, feature_size};
// We create the memory descriptors used by the user
auto src_layer_md = mkldnn_emitter.build_memory_descriptor(
src_layer_tz, args[0].get_element_type(), mkldnn::memory::format_tag::tnc);
auto src_iter_md = mkldnn_emitter.build_memory_descriptor(
src_iter_tz, args[1].get_element_type(), mkldnn::memory::format_tag::ldnc);
auto src_iter_c_md =
mkldnn_emitter.build_memory_descriptor(src_iter_c_tz,
args[1].get_element_type(),
mkldnn::memory::format_tag::ldnc);
auto wei_layer_md =
mkldnn_emitter.build_memory_descriptor(wei_layer_tz,
args[2].get_element_type(),
mkldnn::memory::format_tag::ldigo);
auto wei_iter_md = mkldnn_emitter.build_memory_descriptor(
wei_iter_tz, args[3].get_element_type(), mkldnn::memory::format_tag::ldigo);
auto bias_md = mkldnn_emitter.build_memory_descriptor(
bias_tz, args[4].get_element_type(), mkldnn::memory::format_tag::ldgo);
auto dst_layer_md = mkldnn_emitter.build_memory_descriptor(
dst_layer_tz, out[0].get_element_type(), mkldnn::memory::format_tag::tnc);
auto dst_iter_md = mkldnn_emitter.build_memory_descriptor(
dst_iter_tz, out[1].get_element_type(), mkldnn::memory::format_tag::ldnc);
auto dst_iter_c_md = mkldnn_emitter.build_memory_descriptor(
dst_iter_c_tz, out[1].get_element_type(), mkldnn::memory::format_tag::ldnc);
// query scratchpad size
auto rnn_desc = mkldnn::lstm_forward::desc(mkldnn::prop_kind::forward_training,
get_mkldnn_rnn_direction(),
src_layer_md,
src_iter_md,
src_iter_c_md,
wei_layer_md,
wei_iter_md,
bias_md,
dst_layer_md,
dst_iter_md,
dst_iter_c_md);
mkldnn_emitter.query_scratchpad_rnn_forward(rnn_desc);
// Lstm/Rnn needs 11 primitives: src_layer, src_iter, src_iter_c, weights_layer,
// weights_iter, bias,
// dst_layer, dst_iter, dst_iter_c, workspace, and rnn_forward.
// It needs a new workspace.
index = mkldnn_emitter.reserve_primitive_space(11, true /* new workspace */);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {src_layer_md,
src_iter_md,
src_iter_c_md,
wei_layer_md,
wei_iter_md,
bias_md,
dst_layer_md,
dst_iter_md,
dst_iter_c_md};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build lstm/rnn primitive descriptor\n";
writer << "auto rnn_desc = "
"mkldnn::lstm_forward::desc(mkldnn::prop_kind::forward_training, "
<< get_mkldnn_rnn_direction_string() << ", "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 3 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 4 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 5 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 6 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 7 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 8 << "]);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto rnn_prim_desc = mkldnn::lstm_forward::primitive_desc(rnn_desc, "
"attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[9])
<< "] = new "
"mkldnn::memory(rnn_prim_desc.workspace_desc(), "
"cg_ctx->global_cpu_engine, nullptr);\n";
writer << "auto workspace = "
"(char*)malloc(rnn_prim_desc.workspace_desc().get_size());"
"\n";
writer << "if (!workspace)\n";
writer.block_begin();
writer << "throw std::bad_alloc();\n";
writer.block_end();
writer << "cg_ctx->mkldnn_workspaces.push_back(workspace);\n";
deps[10] = mkldnn_emitter.reserve_workspace();
writer << "\n// build lstm/rnn primitive\n";
// lstm/rnn primitive
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::lstm_forward(rnn_prim_desc);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(rnn_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Lstm)
{
construct_primitive_build_string_rnn<Lstm>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Rnn)
{
construct_primitive_build_string_rnn<Rnn>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <typename OP>
void construct_primitive_build_string_batchnorm(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file,
const bool append_relu,
const bool training)
{
const auto& args = node->get_inputs();
// batchnorm forward needs 6 primitives: input, weights, result, mean,
// variance, and batch_normalization_forward.
index = mkldnn_emitter.reserve_primitive_space(6);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
if (append_relu)
{
writer << "mkldnn::post_ops pops;\n";
writer << "const float ops_scale = 1.f;\n";
writer << "const float ops_alpha = -0.f; // relu negative slope\n";
writer << "const float ops_beta = 0.f;\n";
writer << "pops.append_eltwise("
"ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, "
"ops_beta);\n";
}
else
{
writer << "mkldnn::post_ops pops = mkldnn::post_ops();\n";
}
auto weights_shape =
Shape{2, args[0].get_tensor().get_tensor_layout()->get_size()};
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
auto weights_desc = mkldnn_emitter.build_memory_descriptor(
weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
const float ops_scale = 1.f;
const float ops_alpha = -0.f; // relu negative slope
const float ops_beta = 0.f;
mkldnn::post_ops ops;
if (append_relu)
{
ops.append_eltwise(
ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, ops_beta);
}
bool use_global_stats;
const mkldnn::memory::desc *mean_desc, *variance_desc;
if (training && args.size() == 3)
{
mean_desc = &mkldnn_utils::get_output_mkldnn_md(node, 1);
variance_desc = &mkldnn_utils::get_output_mkldnn_md(node, 2);
use_global_stats = false;
// query scratchpad size
auto batchnorm_desc =
mkldnn_emitter.get_batchnorm_forward_desc<OP>(node, true);
mkldnn_emitter.query_scratchpad_batchnorm_forward(batchnorm_desc, ops);
}
else
{
mean_desc = &mkldnn_utils::get_input_mkldnn_md(node, 3);
variance_desc = &mkldnn_utils::get_input_mkldnn_md(node, 4);
use_global_stats = true;
// query scratchpad size
auto batchnorm_desc =
mkldnn_emitter.get_batchnorm_forward_desc<OP>(node, false);
mkldnn_emitter.query_scratchpad_batchnorm_forward(batchnorm_desc, ops);
}
auto batchnorm = static_cast<const OP*>(node);
auto eps = batchnorm->get_eps_value();
writer << "mkldnn::primitive_attr bn_attr;\n";
writer << "bn_attr.set_post_ops(pops);\n";
writer << "bn_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build batchnorm primitive descriptor\n";
if (use_global_stats)
{
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
input_desc, *mean_desc, *variance_desc, weights_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto batchnorm_desc = "
"mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::"
"forward_training, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], " << eps
<< ", "
"mkldnn::normalization_flags::use_scale_shift | "
"mkldnn::normalization_flags::use_global_stats);\n";
}
else
{
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
input_desc, weights_desc, result_desc, *mean_desc, *variance_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto batchnorm_desc = "
"mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::"
"forward_training, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], " << eps
<< ", "
"mkldnn::normalization_flags::use_scale_shift);\n";
}
writer << "auto batchnorm_prim_desc = "
"mkldnn::batch_normalization_forward::primitive_desc(batchnorm_"
"desc, "
"bn_attr, cg_ctx->global_cpu_engine);\n";
writer << "\n// build batchnorm primitive\n";
// batchnorm primitive
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new "
"mkldnn::batch_normalization_forward(batchnorm_prim_desc);\n";
writer
<< "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(batchnorm_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormTraining)
{
construct_primitive_build_string_batchnorm<BatchNormTraining>(
mkldnn_emitter,
node,
construct_string,
deps,
index,
desc_file,
false /*Append relu*/,
true /*Training*/);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormInference)
{
construct_primitive_build_string_batchnorm<BatchNormInference>(
mkldnn_emitter,
node,
construct_string,
deps,
index,
desc_file,
false /*Append relu*/,
false /*Training*/);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormTrainingRelu)
{
construct_primitive_build_string_batchnorm<BatchNormTrainingRelu>(
mkldnn_emitter,
node,
construct_string,
deps,
index,
desc_file,
true /*Append relu*/,
true /*Training*/);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormInferenceRelu)
{
construct_primitive_build_string_batchnorm<BatchNormInferenceRelu>(
mkldnn_emitter,
node,
construct_string,
deps,
index,
desc_file,
true /*Append relu*/,
false /*Training*/);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormTrainingBackprop)
{
const auto& args = node->get_inputs();
const auto* batchnorm = static_cast<const BatchNormTrainingBackprop*>(node);
auto eps = batchnorm->get_eps_value();
auto weights_shape =
Shape{2, args[0].get_tensor().get_tensor_layout()->get_size()};
auto weights_desc = mkldnn_emitter.build_memory_descriptor(
weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc);
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
auto mean_desc = mkldnn_utils::get_input_mkldnn_md(node, 3);
auto variance_desc = mkldnn_utils::get_input_mkldnn_md(node, 4);
auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 5);
auto dinput_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto dweights_desc = mkldnn_emitter.build_memory_descriptor(
weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc);
// query scratchpad size
auto batchnorm_desc = mkldnn_emitter.get_batchnorm_backward_desc(node);
mkldnn_emitter.query_scratchpad_batchnorm_backward(
batchnorm_desc, input_desc, eps);
// batchnorm backward needs 8 primitives: weights, input, mean, variance,
// dinput, dweights, and batch_normalization_backward.
index = mkldnn_emitter.reserve_primitive_space(8);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {weights_desc,
input_desc,
mean_desc,
variance_desc,
delta_desc,
dinput_desc,
dweights_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto batchnorm_fdesc = "
"mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::"
"forward_training, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "], " << eps
<< ", "
"mkldnn::normalization_flags::use_scale_shift);\n";
writer << "auto batchnorm_fpd = "
"mkldnn::batch_normalization_forward::primitive_desc("
"batchnorm_fdesc, cg_ctx->global_cpu_engine);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto batchnorm_desc = "
"mkldnn::batch_normalization_backward::desc(mkldnn::prop_kind::"
"backward, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 4 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "], " << eps
<< ", "
"mkldnn::normalization_flags::use_scale_shift);\n";
writer << "auto batchnorm_prim_desc = "
"mkldnn::batch_normalization_backward::primitive_desc(batchnorm_"
"desc, "
"attr, cg_ctx->global_cpu_engine, batchnorm_fpd);\n";
writer << "\n// build batchnorm primitive\n";
// batchnorm primitive
writer << "\n// build batchnorm primitives\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new "
"mkldnn::batch_normalization_backward(batchnorm_prim_desc);\n";
writer
<< "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(batchnorm_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_concat(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto concat = static_cast<OP*>(node);
size_t concat_dim = concat->get_concatenation_axis();
size_t nargs = node->get_inputs().size();
// query scratchpad size
auto concat_pd = mkldnn_emitter.get_concat_desc<OP>(node, nargs);
mkldnn_emitter.query_scratchpad_concat(concat_pd);
// Concat needs number of inputs plus 2 primitives; those two are for result and
// concat.
index = mkldnn_emitter.reserve_primitive_space(nargs + 2);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs;
for (size_t i = 0; i < nargs; i++)
{
descs.push_back(mkldnn_utils::get_input_mkldnn_md(node, i));
}
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
descs.push_back(result_desc);
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "std::vector<mkldnn::memory::desc> inputs_desc;\n";
writer << "for (size_t i = " << desc_index << "; i < " << desc_index + nargs
<< "; i++)\n";
writer.block_begin();
writer << "inputs_desc.push_back(*cg_ctx->mkldnn_descriptors[i]);\n";
writer.block_end();
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto concat_prim_desc = "
"mkldnn::concat::primitive_desc( "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + nargs << "], "
<< std::to_string(static_cast<int>(concat_dim))
<< ", inputs_desc, cg_ctx->global_cpu_engine, attr);\n";
writer << "\n// build concat primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::concat(concat_prim_desc);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(concat_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Concat)
{
construct_primitive_build_string_concat<Concat>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(LRN)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto lrn_desc = mkldnn_emitter.get_lrn_forward_desc(node);
mkldnn_emitter.query_scratchpad_lrn_forward(lrn_desc);
// LRN needs 3 primitives: input, result, and lrn_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
const auto* lrn = static_cast<const LRN*>(node);
auto alpha = static_cast<float>(lrn->get_alpha());
auto beta = static_cast<float>(lrn->get_beta());
auto bias = static_cast<float>(lrn->get_bias());
auto nsize = static_cast<int>(lrn->get_nsize());
writer << "auto lrn_desc = "
"mkldnn::lrn_forward::desc(mkldnn::prop_kind::forward_scoring, "
"mkldnn::algorithm::lrn_across_channels, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], " << nsize << ", " << alpha << ", " << beta << ", "
<< bias << ");\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto lrn_prim_desc = "
"mkldnn::lrn_forward::primitive_desc(lrn_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build lrn primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::lrn_forward(lrn_prim_desc);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(lrn_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Slice)
{
const auto& out = node->get_outputs();
const Slice* slice = static_cast<const Slice*>(node);
auto result_shape = out[0].get_shape();
auto lower_bounds = slice->get_lower_bounds();
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// sub memory desc
auto dims = mkldnn::memory::dims(result_shape.begin(), result_shape.end());
auto offsets = mkldnn::memory::dims(lower_bounds.begin(), lower_bounds.end());
auto input_sub_desc = input_desc.submemory_desc(dims, offsets);
// Slice needs 3 primitives: input, result, and reorder.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_sub_desc, result_desc};
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build reorder primitives\n";
writer << "auto reorder_pd = "
"mkldnn::reorder::primitive_desc("
"*cg_ctx->mkldnn_memories["
<< std::to_string(deps[0]) << "]"
", *cg_ctx->mkldnn_memories["
<< std::to_string(deps[1]) << "], attr);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::reorder(reorder_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_conv(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto convolution = static_cast<const OP*>(node);
// query scratchpad size
auto conv_desc = mkldnn_emitter.get_convolution_forward_desc<OP>(node);
auto conv_attr = mkldnn_emitter.get_convolution_forward_attr<OP>(node);
mkldnn_emitter.query_scratchpad_convolution_forward(conv_desc, conv_attr);
Strides window_dilation_strides_adjusted;
for (size_t s : convolution->get_window_dilation_strides())
{
window_dilation_strides_adjusted.push_back(s - 1);
}
auto data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto strides = convolution->get_window_movement_strides();
auto pad_below = convolution->get_padding_below();
auto pad_above = convolution->get_padding_above();
if (mkldnn_emitter.has_bias<OP>())
{
index = mkldnn_emitter.reserve_primitive_space(5);
}
else
{
index = mkldnn_emitter.reserve_primitive_space(4);
}
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
writer << "// Write in memory descriptors\n";
std::vector<mkldnn::memory::desc> descs = {
data_desc, weights_desc, result_desc};
if (mkldnn_emitter.has_bias<OP>())
{
auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
descs.insert(descs.begin() + 2, bias_desc);
}
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build QConv primitive descriptor\n";
writer << "auto conv_desc = "
"mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n"
"mkldnn::algorithm::convolution_direct,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
if (mkldnn_emitter.has_bias<OP>())
{
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + (descs.size() - 1)
<< "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "mkldnn::post_ops ops;\n";
if (std::is_same<OP, ngraph::op::ConvolutionBiasAdd>() ||
std::is_same<OP, ngraph::op::ConvolutionAdd>())
{
writer << "ops.append_sum(1.f);\n";
}
if (std::is_same<OP, ngraph::op::QuantizedConvolutionBiasAdd>() ||
std::is_same<OP, ngraph::op::QuantizedConvolutionBiasSignedAdd>())
{
writer << "ops.append_sum(dyn_post_op_scales[0]);\n";
}
if (has_relu<OP>(node))
{
writer << "const float ops_scale = 1.f;\n";
writer << "const float ops_alpha = -0.f; // relu negative slope\n";
writer << "const float ops_beta = 0.f;\n";
writer << "ops.append_eltwise("
"ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, "
"ops_beta);\n";
}
writer << "mkldnn::primitive_attr conv_attr;\n";
writer << "conv_attr.set_post_ops(ops);\n";
writer << "conv_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
if (mkldnn_emitter.is_quantized_conv<OP>())
{
writer << "conv_attr.set_output_scales(mask, dyn_scales);\n";
}
writer << "auto conv_pd = mkldnn::convolution_forward::primitive_desc("
"conv_desc, conv_attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::convolution_forward(conv_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(conv_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Convolution)
{
construct_primitive_build_string_conv<Convolution>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolution)
{
construct_primitive_build_string_conv<QuantizedConvolution>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionRelu)
{
construct_primitive_build_string_conv<ConvolutionRelu>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolutionRelu)
{
construct_primitive_build_string_conv<QuantizedConvolutionRelu>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionBias)
{
construct_primitive_build_string_conv<ConvolutionBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolutionBias)
{
construct_primitive_build_string_conv<QuantizedConvolutionBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ConvolutionBiasAdd)
{
construct_primitive_build_string_conv<ConvolutionBiasAdd>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolutionBiasAdd)
{
construct_primitive_build_string_conv<QuantizedConvolutionBiasAdd>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionAdd)
{
construct_primitive_build_string_conv<ConvolutionAdd>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolutionBiasSignedAdd)
{
construct_primitive_build_string_conv<QuantizedConvolutionBiasSignedAdd>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
GroupConvolution)
{
construct_primitive_build_string_conv<GroupConvolution>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
GroupConvolutionBias)
{
construct_primitive_build_string_conv<GroupConvolutionBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <typename OP>
void construct_primitive_build_string_conv_backward_filters(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto has_bias = false;
if (mkldnn_emitter.has_bias<OP>())
{
has_bias = true;
}
auto convolution = static_cast<const OP*>(node);
// query scratchpad size
auto bwd_desc = mkldnn_emitter.get_convolution_backward_weights_desc<OP>(node);
auto fwd_desc =
mkldnn_emitter.get_convolution_forward_desc_for_backward_op<OP>(node);
mkldnn_emitter.query_scratchpad_convolution_backward_weights(fwd_desc,
bwd_desc);
Strides window_dilation_strides_adjusted;
for (size_t s : convolution->get_window_dilation_strides_forward())
{
window_dilation_strides_adjusted.push_back(s - 1);
}
auto arg0_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto arg1_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto out0_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto strides = convolution->get_window_movement_strides_forward();
auto pad_below = convolution->get_padding_below_forward();
auto pad_above = convolution->get_padding_above_forward();
mkldnn::algorithm conv_algo = mkldnn_utils::get_conv_algo();
auto conv_algo_string = conv_algo == mkldnn::algorithm::convolution_auto
? "mkldnn::algorithm::convolution_auto,\n"
: "mkldnn::algorithm::convolution_direct,\n";
std::vector<mkldnn::memory::desc> descs = {arg0_desc, arg1_desc, out0_desc};
// ConvolutionBackpropFilter needs 4 primitives: src, diff_dst, diff_weights,
// and convolution_backward_weights.
// ConvolutionBackpropFiltersBias needs 5 primitives: src, diff_dst,
// diff_weights,
// diff_bias, and convolution_backward_weights.
if (has_bias)
{
index = mkldnn_emitter.reserve_primitive_space(5);
auto out1_desc = mkldnn_utils::get_output_mkldnn_md(node, 1);
descs.push_back(out1_desc);
}
else
{
index = mkldnn_emitter.reserve_primitive_space(4);
}
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n";
writer << conv_algo_string;
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n";
if (has_bias)
{
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "\nauto bwd_desc = "
"mkldnn::convolution_backward_weights::desc(\n";
writer << conv_algo_string;
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n";
if (has_bias)
{
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create forward primitive descriptor\n";
writer << "auto fwd_pd = mkldnn::convolution_forward::primitive_desc(fwd_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// create backward primitive_descriptor\n";
writer << "auto bwd_pd = "
"mkldnn::convolution_backward_weights::primitive_desc(bwd_desc, "
"attr, "
"cg_ctx->global_cpu_engine, fwd_pd);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::convolution_backward_weights(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ConvolutionBackpropFilters)
{
construct_primitive_build_string_conv_backward_filters<
ConvolutionBackpropFilters>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ConvolutionBiasBackpropFiltersBias)
{
construct_primitive_build_string_conv_backward_filters<
ConvolutionBiasBackpropFiltersBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ConvolutionBackpropData)
{
auto convolution = static_cast<const ConvolutionBackpropData*>(node);
// query scratchpad size
auto bwd_desc = mkldnn_emitter.get_convolution_backward_data_desc<
ngraph::op::ConvolutionBackpropData>(node);
auto fwd_desc = mkldnn_emitter.get_convolution_forward_desc_for_backward_op<
ngraph::op::ConvolutionBackpropData>(node);
mkldnn_emitter.query_scratchpad_convolution_backward_data(fwd_desc, bwd_desc);
Strides window_dilation_strides_adjusted;
for (size_t s : convolution->get_window_dilation_strides_forward())
{
window_dilation_strides_adjusted.push_back(s - 1);
}
auto arg0_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto arg1_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto out0_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto strides = convolution->get_window_movement_strides_forward();
auto pad_below = convolution->get_padding_below_forward();
auto pad_above = convolution->get_padding_above_forward();
mkldnn::algorithm conv_algo = mkldnn_utils::get_conv_algo();
auto conv_algo_string = conv_algo == mkldnn::algorithm::convolution_auto
? "mkldnn::algorithm::convolution_auto,\n"
: "mkldnn::algorithm::convolution_direct,\n";
std::vector<mkldnn::memory::desc> descs = {arg0_desc, arg1_desc, out0_desc};
// ConvolutionBackpropData needs 4 primitives: weights, diff_dst, diff_src,
// and convolution_backward_data.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n";
writer << conv_algo_string;
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "\nauto bwd_desc = "
"mkldnn::convolution_backward_data::desc(\n";
writer << conv_algo_string;
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create forward primitive descriptor\n";
writer << "auto fwd_pd = mkldnn::convolution_forward::primitive_desc(fwd_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// create backward primitive_descriptor\n";
writer << "auto bwd_pd = "
"mkldnn::convolution_backward_data::primitive_desc(bwd_desc, attr, "
"cg_ctx->global_cpu_engine, fwd_pd);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::convolution_backward_data(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
DeconvolutionBias)
{
auto dconv = static_cast<const DeconvolutionBias*>(node);
// query scratchpad size
auto deconvbias_desc =
mkldnn_emitter
.get_deconvolutionbias_forward_data<ngraph::op::DeconvolutionBias>(
node);
mkldnn_emitter.query_scratchpad_deconvolution_forward(deconvbias_desc);
// For dilation, MKLDNN wants to know how many elements to insert between, not
// how far
// apart to space the elements like nGraph. So we have to subtract 1 from each
// pos.
Strides window_dilation_strides_adjusted;
for (size_t s : dconv->get_window_dilation_strides_forward())
{
window_dilation_strides_adjusted.push_back(s - 1);
}
auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto window_strides = dconv->get_window_movement_strides_forward();
auto padding_below = dconv->get_padding_below_forward();
auto padding_above = dconv->get_padding_above_forward();
CodeWriter writer;
std::vector<mkldnn::memory::desc> descs = {
weights_desc, delta_desc, bias_desc, result_desc};
// DeconvolutionBias needs 5 primitives: weights, delta, bias, result,
// and deconvolutionbias.
index = mkldnn_emitter.reserve_primitive_space(5);
deps = mkldnn_emitter.get_primitive_deps(index);
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
if (dconv->with_relu())
{
writer << "mkldnn::post_ops pops;\n";
writer << "const float ops_scale = 1.f;\n";
writer << "const float ops_alpha = -0.f; // relu negative slope\n";
writer << "const float ops_beta = 0.f;\n";
writer << "pops.append_eltwise("
"ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, "
"ops_beta);\n";
}
else
{
writer << "mkldnn::post_ops pops = mkldnn::post_ops();\n";
}
writer << "mkldnn::primitive_attr dconv_attr;\n";
writer << "dconv_attr.set_post_ops(pops);\n";
writer << "dconv_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\nauto dconv_desc = "
"mkldnn::deconvolution_forward::desc(\n"
"mkldnn::prop_kind::forward,\n"
"mkldnn::algorithm::deconvolution_direct,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 0 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 3 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "\n// create forward primitive descriptor\n";
writer << "auto dconv_pd = "
"mkldnn::deconvolution_forward::primitive_desc(dconv_desc, "
"dconv_attr, cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::deconvolution_forward(dconv_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(dconv_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_max_pool(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto pool = static_cast<const OP*>(node);
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto max_pool_desc =
mkldnn_emitter.get_max_pooling_forward_desc<ngraph::op::MaxPool>(node,
false);
mkldnn_emitter.query_scratchpad_pooling_forward(max_pool_desc);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
CodeWriter writer;
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build Maxpool primitive descriptor\n";
writer << "auto max_pool_desc = ";
writer << "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_"
"inference,\n";
writer << "mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto max_pool_pd = mkldnn::pooling_forward::primitive_desc("
"max_pool_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_forward(max_pool_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(max_pool_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_avg_pool(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto pool = static_cast<const OP*>(node);
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto avg_pool_desc =
mkldnn_emitter.get_avg_pooling_forward_desc<ngraph::op::AvgPool>(node,
false);
mkldnn_emitter.query_scratchpad_pooling_forward(avg_pool_desc);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
auto include_padding_in_avg_computation =
pool->get_include_padding_in_avg_computation();
CodeWriter writer;
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build Avgpool primitive descriptor\n";
writer << "auto avg_pool_desc = ";
writer << "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_"
"inference,\n";
if (include_padding_in_avg_computation)
{
writer << "mkldnn::algorithm::pooling_avg_include_padding,\n";
}
else
{
writer << "mkldnn::algorithm::pooling_avg_exclude_padding,\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto avg_pool_pd = mkldnn::pooling_forward::primitive_desc("
"avg_pool_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_forward(avg_pool_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(avg_pool_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(MaxPool)
{
construct_primitive_build_string_max_pool<MaxPool>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(AvgPool)
{
construct_primitive_build_string_avg_pool<AvgPool>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
MaxPoolWithIndices)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
// query scratchpad size
auto max_pool_desc = mkldnn_emitter.get_max_pooling_with_indices_forward_desc<
ngraph::op::MaxPoolWithIndices>(node);
mkldnn_emitter.query_scratchpad_pooling_forward(max_pool_desc);
// MaxPoolWithIndices needs 4 primitives: input, result, workspace, and
// pooling_forward.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto pool_desc = "
"mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build primitive descriptor\n";
writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{pool_desc, "
"cg_ctx->global_cpu_engine};\n";
writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[2])
<< "] = new mkldnn::memory(fwd_pd.workspace_desc(), "
"cg_ctx->global_cpu_engine, nullptr);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_forward(fwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(fwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(AvgPoolBackprop)
{
auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto pool = static_cast<const ngraph::op::AvgPoolBackprop*>(node);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
auto algo_string = pool->get_include_padding_in_avg_computation()
? "mkldnn::algorithm::pooling_avg_include_padding"
: "mkldnn::algorithm::pooling_avg_exclude_padding";
// query scratchpad size
auto avg_pool_fwd_desc =
mkldnn_emitter.get_avg_pooling_forward_desc<ngraph::op::AvgPoolBackprop>(
node, true);
auto avg_pool_desc =
mkldnn_emitter.get_avg_pooling_backward_desc<ngraph::op::AvgPoolBackprop>(
node);
mkldnn_emitter.query_scratchpad_avg_pooling_backward(avg_pool_fwd_desc,
avg_pool_desc);
// AvgPoolBackprop needs 3 primitives: diff_dst, diff_src, and pooling_backward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {diff_dst_desc, diff_src_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer
<< "auto fwd_desc = "
"mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n";
writer << algo_string << ",\n";
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "auto bwd_desc = "
"mkldnn::pooling_backward::desc(\n";
writer << algo_string << ",\n";
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build primitive descriptor\n";
writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, "
"cg_ctx->global_cpu_engine};\n";
writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, "
"cg_ctx->global_cpu_engine, fwd_pd};\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_backward(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(MaxPoolBackprop)
{
auto fprop_src_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
// query scratchpad size
auto fwd_pool_desc =
mkldnn_emitter.get_max_pooling_forward_desc<ngraph::op::MaxPoolBackprop>(
node, true);
auto bwd_pool_desc =
mkldnn_emitter.get_max_pooling_backward_desc<ngraph::op::MaxPoolBackprop>(
node);
mkldnn_emitter.query_scratchpad_max_pooling_backward(fwd_pool_desc,
bwd_pool_desc);
// MaxPoolBackprop needs 6 primitives: fprop_src, diff_dst, diff_src, workspace
// pooling forward, and pooling_backward.
// It needs a new workspace.
index = mkldnn_emitter.reserve_primitive_space(6, true /* new workspace */);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
fprop_src_desc, diff_dst_desc, diff_src_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "\nauto bwd_desc = "
"mkldnn::pooling_backward::desc(\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build primitive descriptor\n";
writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, attr, "
"cg_ctx->global_cpu_engine};\n";
writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, "
"cg_ctx->global_cpu_engine, fwd_pd};\n";
// This is implemented differently from cpu builder,
// we only use one index and one deps here.
writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[3])
<< "] = new mkldnn::memory(fwd_pd.workspace_desc(), "
"cg_ctx->global_cpu_engine, nullptr);\n";
writer << "auto workspace = "
"(char*)malloc(fwd_pd.workspace_desc().get_size());"
"\n";
writer << "if (!workspace)\n";
writer.block_begin();
writer << "throw std::bad_alloc();\n";
writer.block_end();
writer << "cg_ctx->mkldnn_workspaces.push_back(workspace);\n";
deps[5] = mkldnn_emitter.reserve_workspace();
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(deps[4])
<< "] = new mkldnn::pooling_forward(fwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(deps[4])
<< "] = new mkldnn::memory::desc(fwd_pd.scratchpad_desc());\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_backward(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
MaxPoolWithIndicesBackprop)
{
auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
// query scratchpad size
auto fwd_pool_desc =
mkldnn_emitter
.get_max_pooling_forward_desc<ngraph::op::MaxPoolWithIndicesBackprop>(
node, true);
auto bwd_pool_desc =
mkldnn_emitter
.get_max_pooling_backward_desc<ngraph::op::MaxPoolWithIndicesBackprop>(
node);
mkldnn_emitter.query_scratchpad_max_pooling_with_indices_backward(
fwd_pool_desc, bwd_pool_desc);
// MaxPoolWithIndicesBackprop needs 4 primitives: diff_dst, fprop_workspace,
// diff_src
// and pooling_backward.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {diff_dst_desc, diff_src_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "auto bwd_desc = "
"mkldnn::pooling_backward::desc(\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build primitive descriptor\n";
writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, "
"cg_ctx->global_cpu_engine};\n";
writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, "
"cg_ctx->global_cpu_engine, fwd_pd};\n";
// this is different from cpu builder because we do not write workspace desc to
// desc_file.
// here workspace's mkldnn primitive index is in deps[2] in stead of deps[1].
writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[2])
<< "] = new mkldnn::memory(fwd_pd.workspace_desc(), "
"cg_ctx->global_cpu_engine, nullptr);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_backward(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ngraph::runtime::cpu::op::ConvertLayout)
{
const auto& args = node->get_inputs();
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
bool input_format_is_nchw = mkldnn_utils::mkldnn_md_matches_format_tag(
input_desc.data, mkldnn::memory::format_tag::nchw);
if (input_format_is_nchw &&
mkldnn_utils::mkldnn_md_matches_format_tag(
result_desc.data, mkldnn::memory::format_tag::goihw))
{
// becomes a copy
input_desc = result_desc;
}
else if ((input_format_is_nchw ||
mkldnn_utils::mkldnn_md_matches_format_tag(
input_desc.data, mkldnn::memory::format_tag::nhwc)) &&
(mkldnn_utils::mkldnn_md_matches_format_tag(
result_desc.data, mkldnn::memory::format_tag::OIhw4i16o4i) &&
// check if compensation is conv_s8s8(1U)
result_desc.data.extra.flags & 0x1U))
{
auto arg0_shape = args[0].get_shape();
input_desc = mkldnn::memory::desc(
mkldnn::memory::dims(arg0_shape.begin(), arg0_shape.end()),
mkldnn_utils::get_mkldnn_data_type(args[0].get_element_type()),
mkldnn::memory::format_tag::oihw);
}
else if (input_format_is_nchw && input_desc.data.ndims == 4 &&
result_desc.data.ndims == 5 && node->get_users().size() == 1)
{
Shape weights_shape_groups;
if (auto gconv = std::dynamic_pointer_cast<ngraph::op::GroupConvolution>(
node->get_users()[0]))
{
weights_shape_groups = gconv->get_weights_dimensions();
}
else if (auto gconvb =
std::dynamic_pointer_cast<ngraph::op::GroupConvolutionBias>(
node->get_users()[0]))
{
weights_shape_groups = gconvb->get_weights_dimensions();
}
else
{
throw ngraph_error(
"Incompatible input/output shape in ConvertLayout op");
}
input_desc = mkldnn::memory::desc(
mkldnn::memory::dims(weights_shape_groups.begin(),
weights_shape_groups.end()),
mkldnn_utils::get_mkldnn_data_type(args[0].get_element_type()),
mkldnn::memory::format_tag::goihw);
}
// query scratchpad size
mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc);
// ConvertLayout needs 3 primitives: input, result, and reorder.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build reorder primitive\n";
writer << "auto reorder_pd = "
"mkldnn::reorder::primitive_desc("
"*cg_ctx->mkldnn_memories["
<< std::to_string(deps[0]) << "]"
", *cg_ctx->mkldnn_memories["
<< std::to_string(deps[1]) << "], attr);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::reorder(reorder_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ReluBackprop)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto bwd_desc = mkldnn_emitter.get_relu_backward_desc(node);
auto fwd_desc = mkldnn_emitter.get_relu_forward_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_backward(fwd_desc, bwd_desc);
// ReluBackprop needs 4 primitives: input, delta, result, and eltwise_backward.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, delta_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "const float negative_slope = 0.0f;\n";
writer << "auto fwd_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], negative_slope);\n";
writer << "auto bwd_desc = "
"mkldnn::eltwise_backward::desc(mkldnn::algorithm::eltwise_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], negative_slope);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create forward relu primitive descriptor\n";
writer
<< "auto relu_fwd_pd = mkldnn::eltwise_forward::primitive_desc(fwd_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// create backward relu primitive_descriptor\n";
writer << "auto relu_bwd_pd = "
"mkldnn::eltwise_backward::primitive_desc(bwd_desc, attr, "
"cg_ctx->global_cpu_engine, relu_fwd_pd);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_backward(relu_bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(relu_bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Relu)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto relu_desc = mkldnn_emitter.get_relu_forward_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_forward(relu_desc);
// Relu needs 3 primitives: input, result, and eltwise_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "const float negative_slope = 0.0f;\n";
writer << "auto relu_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], negative_slope);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create relu primitive_descriptor\n";
writer << "auto relu_pd = "
"mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_forward(relu_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(CPULeakyRelu)
{
auto leaky_relu_node = static_cast<const ngraph::op::CPULeakyRelu*>(node);
float alpha = leaky_relu_node->get_alpha();
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto leaky_relu_desc = mkldnn_emitter.get_leaky_relu_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_forward(leaky_relu_desc);
// CPULeakyRelu needs 3 primitives: input, result, and eltwise_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "const float alpha = " << alpha << ";\n";
writer << "auto relu_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], alpha, 0.0f);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create relu primitive_descriptor\n";
writer << "auto relu_pd = "
"mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_forward(relu_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(BoundedRelu)
{
auto bounded_relu_node = static_cast<const ngraph::op::BoundedRelu*>(node);
float alpha = bounded_relu_node->get_alpha();
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto bounded_relu_desc = mkldnn_emitter.get_bounded_relu_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_forward(bounded_relu_desc);
// BoundedRelu needs 3 primitives: input, result, and eltwise_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "const float alpha = " << alpha << ";\n";
writer << "auto relu_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_bounded_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], alpha, 0.0f);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create relu primitive_descriptor\n";
writer << "auto relu_pd = "
"mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_forward(relu_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Sigmoid)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto sigmoid_desc = mkldnn_emitter.get_sigmoid_forward_desc(node, false);
mkldnn_emitter.query_scratchpad_eltwise_forward(sigmoid_desc);
// Sigmoid needs 3 primitives: input, result, and eltwise_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto sigmoid_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward_training, "
"mkldnn::algorithm::eltwise_logistic, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], 0, 0);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create sigmoid primitive_descriptor\n";
writer << "auto sigmoid_pd = "
"mkldnn::eltwise_forward::primitive_desc(sigmoid_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_forward(sigmoid_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(sigmoid_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(SigmoidBackprop)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto fwd_desc = mkldnn_emitter.get_sigmoid_forward_desc(node, true);
auto bwd_desc = mkldnn_emitter.get_sigmoid_backward_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_backward(fwd_desc, bwd_desc);
// SigmoidBackprop needs 4 primitives: input, delta, result, and
// eltwise_backward.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, delta_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_logistic, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], 0, 0);\n";
writer << "auto bwd_desc = "
"mkldnn::eltwise_backward::desc(mkldnn::algorithm::eltwise_logistic, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], 0, 0);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create forward sigmoid primitive descriptor\n";
writer << "auto sigmoid_fwd_pd = "
"mkldnn::eltwise_forward::primitive_desc(fwd_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// create backward sigmoid primitive_descriptor\n";
writer << "auto sigmoid_bwd_pd = "
"mkldnn::eltwise_backward::primitive_desc(bwd_desc, attr, "
"cg_ctx->global_cpu_engine, sigmoid_fwd_pd);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_backward(sigmoid_bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(sigmoid_bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Softmax)
{
auto softmax = static_cast<const ngraph::op::Softmax*>(node);
if (softmax->get_axes().size() != 1)
{
throw ngraph_error("MKLDNN supports softmax only across single axis");
}
int softmax_axis = static_cast<int>(*(softmax->get_axes().begin()));
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto softmax_desc = mkldnn_emitter.get_softmax_forward_desc(node);
mkldnn_emitter.query_scratchpad_softmax_forward(softmax_desc);
// Softmax needs 3 primitives: input, result, and softmax_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto softmax_desc = "
"mkldnn::softmax_forward::desc(mkldnn::prop_kind::forward_scoring, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], " << softmax_axis << ");\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create softmax primitive_descriptor\n";
writer << "auto softmax_pd = "
"mkldnn::softmax_forward::primitive_desc(softmax_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::softmax_forward(softmax_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(softmax_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Quantize)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc);
// Quantize needs 3 primitives: input, result, and reorder.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_output_scales(mask, dyn_scales);\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build reorder primitive\n";
writer << "auto reorder_pd = "
"mkldnn::reorder::primitive_desc("
"*cg_ctx->mkldnn_memories["
<< std::to_string(deps[0]) << "]"
", *cg_ctx->mkldnn_memories["
<< std::to_string(deps[1]) << "], attr);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::reorder(reorder_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Dequantize)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc);
// Dequantize needs 3 primitives: input, result, and reorder.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_output_scales(mask, dyn_scales);\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build reorder primitive\n";
writer << "auto reorder_pd = "
"mkldnn::reorder::primitive_desc("
"*cg_ctx->mkldnn_memories["
<< std::to_string(deps[0]) << "]"
", *cg_ctx->mkldnn_memories["
<< std::to_string(deps[1]) << "], attr);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::reorder(reorder_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_inner_product(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto has_bias = false;
if (mkldnn_emitter.has_bias<OP>())
{
has_bias = true;
}
auto data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto ip_desc = mkldnn_emitter.get_inner_product_forward_desc<OP>(node);
auto ip_attr = mkldnn_emitter.get_inner_product_forward_attr<OP>(node);
mkldnn_emitter.query_scratchpad_ip_forward(ip_desc, ip_attr);
if (has_bias)
{
// QuantizedDotBias needs 5 primitives: input, weights, bias, result, and
// inner_product.
index = mkldnn_emitter.reserve_primitive_space(5);
}
else
{
// QuantizedDot needs 4 primitives: input, weights, result, and
// inner_product.
index = mkldnn_emitter.reserve_primitive_space(4);
}
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
data_desc, weights_desc, result_desc};
if (has_bias)
{
auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
descs.push_back(bias_desc);
}
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build primitive descriptor\n";
writer << "auto ip_desc = "
"mkldnn::inner_product_forward::desc(mkldnn::prop_kind::forward,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
if (has_bias)
{
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "]);\n";
writer << "\nmkldnn::post_ops ops;\n";
if (std::is_same<OP, ngraph::op::QuantizedDotBias>() &&
has_relu<ngraph::op::QuantizedDotBias>(node))
{
writer << "const float ops_scale = 1.f;\n";
writer << "const float ops_alpha = -0.f; // relu negative slope\n";
writer << "const float ops_beta = 0.f;\n";
writer << "ops.append_eltwise("
"ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, "
"ops_beta);\n";
}
writer << "mkldnn::primitive_attr ip_attr;\n";
writer << "ip_attr.set_post_ops(ops);\n";
writer << "ip_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
if (mkldnn_emitter.is_quantized_inner_product<OP>())
{
writer << "ip_attr.set_output_scales(mask, dyn_scales);\n";
}
writer << "auto ip_pd = "
"mkldnn::inner_product_forward::primitive_desc(ip_desc, ip_attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::inner_product_forward(ip_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(ip_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedDotBias)
{
construct_primitive_build_string_inner_product<QuantizedDotBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(QuantizedMatmul)
{
construct_primitive_build_string_inner_product<QuantizedMatmul>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
}
}
}
}
using namespace ngraph::runtime::cpu::pass;
#define TI(x) std::type_index(typeid(x))
static const PrimitiveBuildStringConstructOpMap prim_build_string_construct_dispatcher{
{TI(Add), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Add>},
{TI(BoundedRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BoundedRelu>},
{TI(Concat), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Concat>},
{TI(runtime::cpu::op::ConvertLayout),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<runtime::cpu::op::ConvertLayout>},
{TI(BatchNormInference),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormInference>},
{TI(BatchNormTraining),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTraining>},
{TI(BatchNormInferenceRelu),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormInferenceRelu>},
{TI(BatchNormTrainingRelu),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTrainingRelu>},
{TI(BatchNormTrainingBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTrainingBackprop>},
{TI(CPULeakyRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<CPULeakyRelu>},
{TI(LRN), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<LRN>},
{TI(Lstm), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Lstm>},
{TI(Relu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Relu>},
{TI(ReluBackprop), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ReluBackprop>},
{TI(Rnn), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Rnn>},
{TI(Convolution), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Convolution>},
{TI(ConvolutionRelu),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionRelu>},
{TI(ConvolutionBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBias>},
{TI(ConvolutionBiasAdd),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBiasAdd>},
{TI(ConvolutionAdd),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionAdd>},
{TI(GroupConvolution),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<GroupConvolution>},
{TI(GroupConvolutionBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<GroupConvolutionBias>},
{TI(QuantizedConvolution),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolution>},
{TI(QuantizedConvolutionRelu),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionRelu>},
{TI(QuantizedConvolutionBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionBias>},
{TI(QuantizedConvolutionBiasAdd),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionBiasAdd>},
{TI(QuantizedConvolutionBiasSignedAdd),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<
QuantizedConvolutionBiasSignedAdd>},
{TI(ConvolutionBackpropData),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBackpropData>},
{TI(ConvolutionBackpropFilters),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBackpropFilters>},
{TI(ConvolutionBiasBackpropFiltersBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<
ConvolutionBiasBackpropFiltersBias>},
{TI(DeconvolutionBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<DeconvolutionBias>},
{TI(MaxPoolWithIndices),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolWithIndices>},
{TI(MaxPoolWithIndicesBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolWithIndicesBackprop>},
{TI(Sigmoid), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Sigmoid>},
{TI(SigmoidBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<SigmoidBackprop>},
{TI(Slice), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Slice>},
{TI(Softmax), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Softmax>},
{TI(MaxPool), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPool>},
{TI(AvgPool), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<AvgPool>},
{TI(AvgPoolBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<AvgPoolBackprop>},
{TI(MaxPoolBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolBackprop>},
{TI(Quantize), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Quantize>},
{TI(Dequantize), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Dequantize>},
{TI(QuantizedDotBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedDotBias>},
{TI(QuantizedMatmul),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedMatmul>},
};
bool MKLDNNPrimitiveBuildPass::run_on_call_graph(const std::list<std::shared_ptr<Node>>& nodes)
{
std::ofstream desc_file(m_desc_filename, std::ios::out | std::ios::binary);
for (const auto& shp_node : nodes)
{
Node* node = shp_node.get();
if (mkldnn_utils::use_mkldnn_kernel(node))
{
auto handler = prim_build_string_construct_dispatcher.find(TI(*node));
NGRAPH_CHECK(handler != prim_build_string_construct_dispatcher.end(),
"Unsupported node '",
node->description(),
"' in MKLDNNPrimitiveBuildPass");
std::string construct_string;
std::vector<size_t> deps;
size_t index;
handler->second(m_mkldnn_emitter, node, construct_string, deps, index, desc_file);
m_node_primitive_string_deps_index_map[node] =
std::tuple<std::string, std::vector<size_t>, size_t>(construct_string, deps, index);
}
}
return false;
}
#undef TI
| 53.487179 | 100 | 0.506523 | ilya-lavrenov |
66f87caac8919d0b19be2e829a3cdac4adec20d8 | 456 | cpp | C++ | 1474/b.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | 1 | 2021-10-24T00:46:37.000Z | 2021-10-24T00:46:37.000Z | 1474/b.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | null | null | null | 1474/b.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
using namespace std;
bool is_prime(int x) {
if (x < 4) {
return true;
}
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
void solve() {
int d;
cin >> d;
int p = d + 1;
for (; !is_prime(p); ++p) {}
int q = p + d;
for (; !is_prime(q); ++q) {}
cout << p * q << "\n";
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
| 13.028571 | 36 | 0.440789 | vladshablinsky |
66fa8463e3800378bb1d93248fa38aef09506b44 | 678 | hpp | C++ | include/mizuiro/color/set_percentage.hpp | cpreh/mizuiro | 5ab15bde4e72e3a4978c034b8ff5700352932485 | [
"BSL-1.0"
] | 1 | 2015-08-22T04:19:39.000Z | 2015-08-22T04:19:39.000Z | include/mizuiro/color/set_percentage.hpp | freundlich/mizuiro | 5ab15bde4e72e3a4978c034b8ff5700352932485 | [
"BSL-1.0"
] | null | null | null | include/mizuiro/color/set_percentage.hpp | freundlich/mizuiro | 5ab15bde4e72e3a4978c034b8ff5700352932485 | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef MIZUIRO_COLOR_SET_PERCENTAGE_HPP_INCLUDED
#define MIZUIRO_COLOR_SET_PERCENTAGE_HPP_INCLUDED
#include <mizuiro/color/denormalize.hpp>
namespace mizuiro::color
{
template <typename Color, typename Channel, typename Float>
void set_percentage(Color &_color, Channel const &_channel, Float const _value)
{
_color.set(
_channel,
mizuiro::color::denormalize<typename Color::format>(_color.format_store(), _channel, _value));
}
}
#endif
| 27.12 | 100 | 0.747788 | cpreh |
66fdff7856d661ac7599dbf154fde7b7a69021ce | 70 | cpp | C++ | test/unit/main.unit.cpp | flisboac/gq | 36f78933127ab4c04d0b2712fa1c07ae0184ecd4 | [
"MIT"
] | null | null | null | test/unit/main.unit.cpp | flisboac/gq | 36f78933127ab4c04d0b2712fa1c07ae0184ecd4 | [
"MIT"
] | null | null | null | test/unit/main.unit.cpp | flisboac/gq | 36f78933127ab4c04d0b2712fa1c07ae0184ecd4 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "gq.def.hpp"
| 14 | 25 | 0.757143 | flisboac |
0f07995cbfb34d3844b62df4fc07e0cc78a1eec9 | 144 | hpp | C++ | src/geom/ex.hpp | orsonbraines/apytuuengine | b2a02e5f979bea0a3a75ad40f43d8d0c56bfe2a0 | [
"MIT"
] | null | null | null | src/geom/ex.hpp | orsonbraines/apytuuengine | b2a02e5f979bea0a3a75ad40f43d8d0c56bfe2a0 | [
"MIT"
] | null | null | null | src/geom/ex.hpp | orsonbraines/apytuuengine | b2a02e5f979bea0a3a75ad40f43d8d0c56bfe2a0 | [
"MIT"
] | null | null | null | #ifndef APYTUU_ENGINE_GEOM_EX
#define APYTUU_ENGINE_GEOM_EX
namespace apytuu_engine_geom{
class GeomException{
public:
private:
};
}
#endif
| 14.4 | 29 | 0.8125 | orsonbraines |
0f0e439eb3f208d14e230aff66fa78aa9e5e14cf | 15,980 | cpp | C++ | src/backend/uop.cpp | jeroendebaat/lc3tools | b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41 | [
"Apache-2.0"
] | 58 | 2018-07-13T03:41:38.000Z | 2022-03-08T19:06:20.000Z | src/backend/uop.cpp | jeroendebaat/lc3tools | b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41 | [
"Apache-2.0"
] | 26 | 2019-12-02T05:33:00.000Z | 2022-03-12T15:54:26.000Z | src/backend/uop.cpp | jeroendebaat/lc3tools | b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41 | [
"Apache-2.0"
] | 24 | 2019-08-30T15:00:13.000Z | 2022-01-26T05:11:36.000Z | /*
* Copyright 2020 McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education.
*/
#include "decoder.h"
#include "isa.h"
#include "state.h"
#include "uop.h"
using namespace lc3::core;
PIMicroOp IMicroOp::insert(PIMicroOp new_next)
{
if(next == nullptr) {
next = new_next;
} else {
PIMicroOp cur = next;
while(cur->next != nullptr) {
cur = cur->next;
}
cur->next = new_next;
}
return next;
}
std::string IMicroOp::regToString(uint16_t reg_id) const
{
if(reg_id < 8) {
return lc3::utils::ssprintf("R%d", reg_id);
} else {
return lc3::utils::ssprintf("T%d", reg_id - 8);
}
}
void FetchMicroOp::handleMicroOp(MachineState & state)
{
if(isAccessViolation(state.readPC(), state)) {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)");
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
} else {
uint16_t value = std::get<0>(state.readMem(state.readPC()));
state.writeIR(value);
}
}
std::string FetchMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("IR:0x%0.4hx <= M[0x%0.4hx]:0x%0.4hx", state.readIR(), state.readPC(),
std::get<0>(state.readMem(state.readPC())));
}
void DecodeMicroOp::handleMicroOp(MachineState & state)
{
lc3::optional<PIInstruction> inst = decoder.decode(state.readIR());
if(inst) {
insert((*inst)->buildMicroOps(state));
state.writeDecodedIR(*inst);
} else {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("unknown opcode");
PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1);
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x1,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(dec_pc);
dec_pc->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
}
}
std::string DecodeMicroOp::toString(MachineState const & state) const
{
lc3::optional<PIInstruction> inst = decoder.decode(state.readIR());
if(inst) {
(*inst)->buildMicroOps(state);
return lc3::utils::ssprintf("dIR <= %s", (*inst)->toValueString().c_str());
} else {
return "dIR <= Illegal instruction";
}
}
void PCWriteRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(reg_id);
state.writePC(value);
}
std::string PCWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("PC:0x%0.4hx <= %s:0x%0.4hx", state.readPC(), regToString(reg_id).c_str(),
state.readReg(reg_id));
}
void PSRWriteRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(reg_id);
state.writePSR(value);
}
std::string PSRWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("PSR:0x%0.4hx <= %s:0x%0.4hx", state.readPSR(), regToString(reg_id).c_str(),
state.readReg(reg_id));
}
void PCAddImmMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readPC() + amnt;
state.writePC(value);
}
std::string PCAddImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("PC:0x%0.4hx <= (PC:0x%0.4hx + #%d):0x%0.4hx", state.readPC(), state.readPC(), amnt,
state.readPC() + amnt);
}
void RegWriteImmMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(reg_id, value);
}
std::string RegWriteImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= 0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id), value);
}
void RegWriteRegMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(dst_id, state.readReg(src_id));
}
std::string RegWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= %s:0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id),
regToString(src_id).c_str(), state.readReg(src_id));
}
void RegWritePCMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(reg_id, state.readPC());
}
std::string RegWritePCMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= PC:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id),
state.readPC());
}
void RegWritePSRMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(reg_id, state.readPSR());
}
std::string RegWritePSRMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= PSR:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id),
state.readPSR());
}
void RegWriteSSPMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(reg_id, state.readSSP());
}
std::string RegWriteSSPMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= SSP:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id),
state.readSSP());
}
void SSPWriteRegMicroOp::handleMicroOp(MachineState & state)
{
state.writeSSP(state.readReg(reg_id));
}
std::string SSPWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("SSP:0x%0.4hx <= %s:0x%0.4hx", state.readSSP(), regToString(reg_id).c_str(),
state.readReg(reg_id));
}
void RegAddImmMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(src_id) + amnt;
state.writeReg(dst_id, value);
}
std::string RegAddImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx + #%d):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id), amnt, state.readReg(src_id) + amnt);
}
void RegAddRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(src_id1) + state.readReg(src_id2);
state.writeReg(dst_id, value);
}
std::string RegAddRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx + %s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id1).c_str(), state.readReg(src_id1), regToString(src_id2).c_str(),
state.readReg(src_id2), state.readReg(src_id1) + state.readReg(src_id2));
}
void RegAndImmMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(src_id) & amnt;
state.writeReg(dst_id, value);
}
std::string RegAndImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx & #%d):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id), amnt, state.readReg(src_id) & amnt);
}
void RegAndRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(src_id1) & state.readReg(src_id2);
state.writeReg(dst_id, value);
}
std::string RegAndRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx & %s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id1).c_str(), state.readReg(src_id1), regToString(src_id2).c_str(),
state.readReg(src_id2), state.readReg(src_id1) & state.readReg(src_id2));
}
void RegNotMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = ~state.readReg(src_id);
state.writeReg(dst_id, value);
}
std::string RegNotMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (~%s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id),
~state.readReg(src_id));
}
void MemReadMicroOp::handleMicroOp(MachineState & state)
{
uint16_t addr = state.readReg(addr_reg_id);
if(isAccessViolation(addr, state)) {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)");
PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1);
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(dec_pc);
dec_pc->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
} else {
std::pair<uint16_t, PIMicroOp> read_result = state.readMem(addr);
uint16_t value = std::get<0>(read_result);
PIMicroOp op = std::get<1>(read_result);
if(op) {
insert(op);
}
state.writeReg(dst_id, value);
}
}
std::string MemReadMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= MEM[%s:0x%0.4hx]:0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(addr_reg_id).c_str(), state.readReg(addr_reg_id),
std::get<0>(state.readMem(state.readReg(addr_reg_id))));
}
void MemWriteImmMicroOp::handleMicroOp(MachineState & state)
{
uint16_t addr = state.readReg(addr_reg_id);
if(isAccessViolation(addr, state)) {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)");
PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1);
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(dec_pc);
dec_pc->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
} else {
PIMicroOp op = state.writeMem(addr, value);
if(op) {
insert(op);
}
}
}
std::string MemWriteImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("MEM[%s:0x%0.4hx]:0x%0.4hx <= 0x%0.4hx", regToString(addr_reg_id).c_str(),
state.readReg(addr_reg_id), std::get<0>(state.readMem(state.readReg(addr_reg_id))), value);
}
void MemWriteRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t addr = state.readReg(addr_reg_id);
if(isAccessViolation(addr, state)) {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)");
PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1);
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(dec_pc);
dec_pc->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
} else {
PIMicroOp op = state.writeMem(addr, state.readReg(src_id));
if(op) {
insert(op);
}
}
}
std::string MemWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("MEM[%s:0x%0.4hx]:0x%0.4hx <= %s:0x%0.4hx", regToString(addr_reg_id).c_str(),
state.readReg(addr_reg_id), std::get<0>(state.readMem(state.readReg(addr_reg_id))), regToString(src_id).c_str(),
state.readReg(src_id));
}
void CCUpdateRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t psr_value = state.readPSR();
char cc_char = getCCChar(state.readReg(reg_id));
if(cc_char == 'N') {
state.writePSR((psr_value & 0xFFF8) | 0x0004);
} else if(cc_char == 'Z') {
state.writePSR((psr_value & 0xFFF8) | 0x0002);
} else {
state.writePSR((psr_value & 0xFFF8) | 0x0001);
}
}
std::string CCUpdateRegMicroOp::toString(MachineState const & state) const
{
char cur_cc_char;
uint16_t psr_value = state.readPSR();
if((psr_value & 0x0004) != 0) {
cur_cc_char = 'N';
} else if((psr_value & 0x0002) != 0) {
cur_cc_char = 'Z';
} else {
cur_cc_char = 'P';
}
return lc3::utils::ssprintf("CC:%c <= ComputeCC(0x%0.4hx):%c", cur_cc_char, state.readReg(reg_id),
getCCChar(state.readReg(reg_id)));
}
char CCUpdateRegMicroOp::getCCChar(uint16_t value) const
{
if((value & 0x8000) != 0) {
return 'N';
} else if(value == 0) {
return 'Z';
} else {
return 'P';
}
}
void BranchMicroOp::handleMicroOp(MachineState & state)
{
bool result = pred(state);
if(result) {
next = true_next;
} else {
next = false_next;
}
}
std::string BranchMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("uBEN <= (%s):%s", msg.c_str(), pred(state) ? "true" : "false");
}
PIMicroOp BranchMicroOp::insert(PIMicroOp new_next)
{
if(true_next) { true_next->insert(new_next); }
if(false_next) { false_next->insert(new_next); }
return new_next;
}
void CallbackMicroOp::handleMicroOp(MachineState & state)
{
state.addPendingCallback(type);
}
std::string CallbackMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("callbacks <= %s", callbackTypeToString(type).c_str());
}
void PushInterruptTypeMicroOp::handleMicroOp(MachineState & state)
{
state.enqueueInterrupt(type);
}
std::string PushInterruptTypeMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("interrupts <= %s", interruptTypeToString(type).c_str());
}
void PopInterruptTypeMicroOp::handleMicroOp(MachineState & state)
{
state.dequeueInterrupt();
}
std::string PopInterruptTypeMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("interrupts <= interrupts.removeFront()");
}
void PushFuncTypeMicroOp::handleMicroOp(MachineState & state)
{
state.pushFuncTraceType(type);
}
std::string PushFuncTypeMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("traceStack <= %s", funcTypeToString(type).c_str());
}
void PopFuncTypeMicroOp::handleMicroOp(MachineState & state)
{
state.popFuncTraceType();
}
std::string PopFuncTypeMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("traceStack <= traceStack.removeTop()");
}
void PrintMessageMicroOp::handleMicroOp(MachineState & state)
{
(void) state;
}
std::string PrintMessageMicroOp::toString(MachineState const & state) const
{
(void) state;
return msg;
}
| 32.088353 | 153 | 0.678285 | jeroendebaat |
0f10b1b9bde8b54535b9adda144c603e94b19c5c | 5,127 | cc | C++ | test/cctest/heap/test-concurrent-marking.cc | YBApp-Bot/org_chromium_v8 | de9efd579907d75b4599b33cfcc8c00468a72b9b | [
"BSD-3-Clause"
] | 1 | 2019-04-25T17:50:34.000Z | 2019-04-25T17:50:34.000Z | test/cctest/heap/test-concurrent-marking.cc | YBApp-Bot/org_chromium_v8 | de9efd579907d75b4599b33cfcc8c00468a72b9b | [
"BSD-3-Clause"
] | null | null | null | test/cctest/heap/test-concurrent-marking.cc | YBApp-Bot/org_chromium_v8 | de9efd579907d75b4599b33cfcc8c00468a72b9b | [
"BSD-3-Clause"
] | 1 | 2018-11-28T07:47:41.000Z | 2018-11-28T07:47:41.000Z | // Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdlib.h>
#include "src/v8.h"
#include "src/heap/concurrent-marking.h"
#include "src/heap/heap-inl.h"
#include "src/heap/heap.h"
#include "src/heap/mark-compact.h"
#include "src/heap/worklist.h"
#include "test/cctest/cctest.h"
#include "test/cctest/heap/heap-utils.h"
namespace v8 {
namespace internal {
namespace heap {
void PublishSegment(ConcurrentMarking::MarkingWorklist* worklist,
HeapObject* object) {
for (size_t i = 0; i <= ConcurrentMarking::MarkingWorklist::kSegmentCapacity;
i++) {
worklist->Push(0, object);
}
CHECK(worklist->Pop(0, &object));
}
TEST(ConcurrentMarking) {
if (!i::FLAG_concurrent_marking) return;
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
CcTest::CollectAllGarbage();
if (!heap->incremental_marking()->IsStopped()) return;
MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
ConcurrentMarking::MarkingWorklist shared, bailout, on_hold;
WeakObjects weak_objects;
ConcurrentMarking* concurrent_marking =
new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects);
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->ScheduleTasks();
concurrent_marking->Stop(
ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING);
delete concurrent_marking;
}
TEST(ConcurrentMarkingReschedule) {
if (!i::FLAG_concurrent_marking) return;
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
CcTest::CollectAllGarbage();
if (!heap->incremental_marking()->IsStopped()) return;
MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
ConcurrentMarking::MarkingWorklist shared, bailout, on_hold;
WeakObjects weak_objects;
ConcurrentMarking* concurrent_marking =
new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects);
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->ScheduleTasks();
concurrent_marking->Stop(
ConcurrentMarking::StopRequest::COMPLETE_ONGOING_TASKS);
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->RescheduleTasksIfNeeded();
concurrent_marking->Stop(
ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING);
delete concurrent_marking;
}
TEST(ConcurrentMarkingPreemptAndReschedule) {
if (!i::FLAG_concurrent_marking) return;
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
CcTest::CollectAllGarbage();
if (!heap->incremental_marking()->IsStopped()) return;
MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
ConcurrentMarking::MarkingWorklist shared, bailout, on_hold;
WeakObjects weak_objects;
ConcurrentMarking* concurrent_marking =
new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects);
for (int i = 0; i < 5000; i++)
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->ScheduleTasks();
concurrent_marking->Stop(ConcurrentMarking::StopRequest::PREEMPT_TASKS);
for (int i = 0; i < 5000; i++)
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->RescheduleTasksIfNeeded();
concurrent_marking->Stop(
ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING);
delete concurrent_marking;
}
TEST(ConcurrentMarkingMarkedBytes) {
if (!i::FLAG_concurrent_marking) return;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Heap* heap = CcTest::heap();
HandleScope sc(isolate);
Handle<FixedArray> root = isolate->factory()->NewFixedArray(1000000);
CcTest::CollectAllGarbage();
if (!heap->incremental_marking()->IsStopped()) return;
heap::SimulateIncrementalMarking(heap, false);
heap->concurrent_marking()->Stop(
ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING);
CHECK_GE(heap->concurrent_marking()->TotalMarkedBytes(), root->Size());
}
UNINITIALIZED_TEST(ConcurrentMarkingStoppedOnTeardown) {
if (!i::FLAG_concurrent_marking) return;
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
{
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
Factory* factory = i_isolate->factory();
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::New(isolate)->Enter();
for (int i = 0; i < 10000; i++) {
factory->NewJSWeakMap();
}
Heap* heap = i_isolate->heap();
heap::SimulateIncrementalMarking(heap, false);
}
isolate->Dispose();
}
} // namespace heap
} // namespace internal
} // namespace v8
| 34.409396 | 79 | 0.736883 | YBApp-Bot |
0f1220db98a4d9c01264add6c01eefb52615a0fd | 6,900 | cpp | C++ | toonz/sources/toonzlib/txshsoundlevel.cpp | jhonsu01/opentoonz | b8b0f90055ae6a54fc5926c46a063d460c9884d7 | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonzlib/txshsoundlevel.cpp | jhonsu01/opentoonz | b8b0f90055ae6a54fc5926c46a063d460c9884d7 | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonzlib/txshsoundlevel.cpp | jhonsu01/opentoonz | b8b0f90055ae6a54fc5926c46a063d460c9884d7 | [
"BSD-3-Clause"
] | null | null | null |
#include "toonz/txshsoundlevel.h"
#include "tsound_io.h"
#include "toonz/toonzscene.h"
#include "toonz/sceneproperties.h"
#include "toonz/txshleveltypes.h"
#include "tstream.h"
#include "toutputproperties.h"
#include "tconvert.h"
//-----------------------------------------------------------------------------
DEFINE_CLASS_CODE(TXshSoundLevel, 53)
PERSIST_IDENTIFIER(TXshSoundLevel, "soundLevel")
//=============================================================================
TXshSoundLevel::TXshSoundLevel(std::wstring name, int startOffset,
int endOffset)
: TXshLevel(m_classCode, name)
, m_soundTrack(0)
, m_duration(0)
, m_samplePerFrame(0)
, m_frameSoundCount(0)
, m_fps(12)
, m_path() {}
//-----------------------------------------------------------------------------
TXshSoundLevel::~TXshSoundLevel() {}
//-----------------------------------------------------------------------------
TXshSoundLevel *TXshSoundLevel::clone() const {
TXshSoundLevel *sound = new TXshSoundLevel();
sound->setSoundTrack(m_soundTrack->clone());
sound->m_duration = m_duration;
sound->m_path = m_path;
sound->m_samplePerFrame = m_samplePerFrame;
sound->m_frameSoundCount = m_frameSoundCount;
sound->m_fps = m_fps;
return sound;
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::setScene(ToonzScene *scene) {
assert(scene);
TXshLevel::setScene(scene);
TOutputProperties *properties = scene->getProperties()->getOutputProperties();
assert(properties);
setFrameRate(properties->getFrameRate());
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::loadSoundTrack() {
assert(getScene());
TSceneProperties *properties = getScene()->getProperties();
if (properties) {
TOutputProperties *outputProperties = properties->getOutputProperties();
if (outputProperties) m_fps = outputProperties->getFrameRate();
}
TFilePath path = getScene()->decodeFilePath(m_path);
try {
loadSoundTrack(path);
} catch (TException &e) {
throw TException(e.getMessage());
}
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::loadSoundTrack(const TFilePath &fileName) {
try {
TSoundTrackP st;
TFilePath path(fileName);
bool ret = TSoundTrackReader::load(path, st);
if (ret) {
m_duration = st->getDuration();
setName(fileName.getWideName());
setSoundTrack(st);
}
} catch (TException &) {
return;
}
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::load() { loadSoundTrack(); }
//-----------------------------------------------------------------------------
void TXshSoundLevel::save() { save(m_path); }
//-----------------------------------------------------------------------------
void TXshSoundLevel::save(const TFilePath &path) {
TSoundTrackWriter::save(path, m_soundTrack);
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::loadData(TIStream &is) {
is >> m_name;
setName(m_name);
std::string tagName;
bool flag = false;
int type = UNKNOWN_XSHLEVEL;
for (;;) {
if (is.matchTag(tagName)) {
if (tagName == "path") {
is >> m_path;
is.matchEndTag();
} else if (tagName == "type") {
std::string v;
is >> v;
if (v == "sound") type = SND_XSHLEVEL;
is.matchEndTag();
} else
throw TException("unexpected tag " + tagName);
} else
break;
}
setType(type);
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::saveData(TOStream &os) {
os << m_name;
std::map<std::string, std::string> attr;
os.child("type") << L"sound";
os.child("path") << m_path;
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::computeValues(int frameHeight) {
if (frameHeight == 0) frameHeight = 1;
m_values.clear();
if (!m_soundTrack) {
m_frameSoundCount = 0;
m_samplePerFrame = 0;
return;
}
m_samplePerFrame = m_soundTrack->getSampleRate() / m_fps;
double samplePerPixel = m_samplePerFrame / frameHeight;
int sampleCount = m_soundTrack->getSampleCount();
if (sampleCount <= 0) // This was if(!sampleCount) :(
return; //
m_frameSoundCount = tceil(sampleCount / m_samplePerFrame);
double maxPressure = 0.0;
double minPressure = 0.0;
m_soundTrack->getMinMaxPressure(TINT32(0), (TINT32)sampleCount, TSound::LEFT,
minPressure, maxPressure);
double absMaxPressure = std::max(fabs(minPressure), fabs(maxPressure));
if (absMaxPressure <= 0) return;
// Adjusting using a fixed scaleFactor
double weightA = 20.0 / absMaxPressure;
long i = 0, j;
long p = 0; // se p parte da zero notazione per pixel,
// se parte da 1 notazione per frame
while (i < m_frameSoundCount) {
for (j = 0; j < frameHeight - 1; ++j) {
double min = 0.0;
double max = 0.0;
m_soundTrack->getMinMaxPressure(
(TINT32)(i * m_samplePerFrame + j * samplePerPixel),
(TINT32)(i * m_samplePerFrame + (j + 1) * samplePerPixel - 1),
TSound::MONO, min, max);
m_values.insert(std::pair<int, std::pair<double, double>>(
p + j, std::pair<double, double>(min * weightA, max * weightA)));
}
double min = 0.0;
double max = 0.0;
m_soundTrack->getMinMaxPressure(
(TINT32)(i * m_samplePerFrame + j * samplePerPixel),
(TINT32)((i + 1) * m_samplePerFrame - 1), TSound::MONO, min, max);
m_values.insert(std::pair<int, std::pair<double, double>>(
p + j, std::pair<double, double>(min * weightA, max * weightA)));
++i;
p += frameHeight;
}
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::getValueAtPixel(int pixel, DoublePair &values) const {
std::map<int, DoublePair>::const_iterator it = m_values.find(pixel);
if (it != m_values.end()) values = it->second;
}
//-----------------------------------------------------------------------------
void TXshSoundLevel::setFrameRate(double fps) {
if (m_fps != fps) {
m_fps = fps;
computeValues();
}
}
//-----------------------------------------------------------------------------
int TXshSoundLevel::getFrameCount() const {
int frameCount = m_duration * m_fps;
return (frameCount == 0) ? 1 : frameCount;
}
//-----------------------------------------------------------------------------
// Implementato per utilita'
void TXshSoundLevel::getFids(std::vector<TFrameId> &fids) const {
int i;
for (i = 0; i < getFrameCount(); i++) fids.push_back(TFrameId(i));
}
| 29.237288 | 80 | 0.51913 | jhonsu01 |
0f1248f1cc04475c9c56f11c28f8e637ece37de1 | 15,808 | cpp | C++ | immBodyDistanceSmooth.cpp | TomLKoller/Boxplus-IMM | 4f610967b8b9d3ed5b7110db7019d2acbc8ca57b | [
"MIT"
] | 4 | 2021-07-16T08:50:46.000Z | 2021-09-13T13:45:56.000Z | immBodyDistanceSmooth.cpp | TomLKoller/Boxplus-IMM | 4f610967b8b9d3ed5b7110db7019d2acbc8ca57b | [
"MIT"
] | 3 | 2021-07-16T06:50:19.000Z | 2021-10-04T13:37:04.000Z | immBodyDistanceSmooth.cpp | TomLKoller/Boxplus-IMM | 4f610967b8b9d3ed5b7110db7019d2acbc8ca57b | [
"MIT"
] | 1 | 2020-07-17T08:39:15.000Z | 2020-07-17T08:39:15.000Z | #include "ADEKF.h"
#include "ManifoldCreator.h"
#include "types/SO3.h"
#include "adekf_viz.h"
#include "PoseRenderer.h"
#include "BPIMM.h"
#include "BPRTSIMM.h"
#include "PathCreatorOrientation.h"
#include "SimulatedBodyMeas.h"
#include "GaussianNoiseVector.h"
#include <numeric>
#define GRAVITY_CONSTANT 9.81
//#define SHOW_VIZ
//Declaration of State
ADEKF_MANIFOLD(CT_State, ((adekf::SO3, rotate_world_to_body)), (3, w_position), (3, w_velocity), (3, w_angular_rate))
ADEKF_MANIFOLD(Sub_State, ((adekf::SO3, rotate_world_to_body)), (3, w_position))
//Declaration of measurement
ADEKF_MANIFOLD(Radar4, , (3, radar1), (3, radar2), (3, radar3), (3, radar4))
#include "NAIVE_IMM.h"
#include "Naive_RTSIMM.h"
#include "rts-smoother.hpp"
#include "naive_rts-smoother.hpp"
//#define EKS
//#define MEKS
#define RTSIMMS
#define NIMMS
#define EKF_MODEL constant_turn_model
#define EKF_SIGMA ct_sigma
#define NOISE_ON_CONSTANT_TURN 0.//10. for consistent evaluation // 0 for original implementation
/**
* The constant turn model function.
*/
struct constant_turn_model
{
/**
* Implements the constant turn dynamic.
* @tparam T The Scalar type (required for auto diff)
* @tparam Noise The type of the noise vector
* @param state The state
* @param noise The noise vector to apply the non additive noise
* @param deltaT The time difference since the last measurement.
*/
template <typename T, typename Noise>
void operator()(CT_State<T> &state, const Noise &noise, double deltaT)
{
//pre calculate values
T omega = norm(state.w_angular_rate);
T c1 = omega == 0. ? -pow(deltaT, 2) * cos(omega * deltaT) / 2. : (cos(omega * deltaT) - 1.) / pow(omega, 2);
T c2 = omega == 0. ? deltaT * cos(omega * deltaT) : sin(omega * deltaT) / omega;
T c3 = omega == 0. ? -pow(deltaT, 3) * cos(omega * deltaT) / 6. : 1. / pow(omega, 2) * (sin(omega * deltaT) / omega - deltaT);
T wx = state.w_angular_rate.x(), wy = state.w_angular_rate.y(), wz = state.w_angular_rate.z();
T d1 = pow(wy, 2) + pow(wz, 2);
T d2 = pow(wx, 2) + pow(wz, 2);
T d3 = pow(wx, 2) + pow(wy, 2);
//calcualte A and B Matrix according to [2]
Eigen::Matrix<T, 3, 3> A, B;
A << c1 * d1, -c2 * wz - c1 * wx * wy, c2 * wy - c1 * wx * wz,
c2 * wz - c1 * wx * wy, c1 * d2, -c2 * wx - c1 * wy * wz,
-c2 * wy - c1 * wx * wz, c2 * wx - c1 * wy * wz, c1 * d3;
B << c3 * d1, c1 * wz - c3 * wx * wy, -c1 * wy - c3 * wx * wz,
-c1 * wz - c3 * wx * wy, c3 * d2, c1 * wx - c3 * wy * wz,
c1 * wy - c3 * wx * wz, -c1 * wx - c3 * wy * wz, c3 * d3;
//Implement constant turn dynamic
state.w_position += B * state.w_velocity + state.w_velocity * deltaT+NOISE(3,3)*deltaT;
state.w_velocity += A * state.w_velocity;
state.rotate_world_to_body = state.rotate_world_to_body * adekf::SO3(state.w_angular_rate * deltaT).conjugate();
state.w_angular_rate += NOISE(0,3) * deltaT;
};
//Create static object
} constant_turn_model;
/**
* Performs the simulation of a flying drone with camera.
* @param argc argument counter
* @param argv command line arguments
* @return 0
*/
int main(int argc, char *argv[])
{
constexpr double deltaT = 0.05;
PathCreator path{deltaT, 10};
//Setup covariance of constant turn model
adekf::SquareMatrixType<double, 6> ct_sigma = ct_sigma.Identity() * 0.1;
(ct_sigma.block<3,3>(3,3))=Eigen::Matrix3d::Identity()*NOISE_ON_CONSTANT_TURN;
//straight model
auto straight_model = [](auto &state, auto noise, double deltaT) {
state.w_velocity += NOISE(0,3) * deltaT;
state.w_position += state.w_velocity * deltaT;
//orientation and angular rate stay constant
};
//Setup covariance of straight model
adekf::SquareMatrixType<double, 6> sm_sigma = sm_sigma.Identity() * 10;
auto free_model = [](auto &state, auto noise, double deltaT) {
state.w_velocity += NOISE(0, 3) * deltaT;
state.w_position += state.w_velocity * deltaT;
state.w_angular_rate += NOISE(3, 3) * deltaT;
state.rotate_world_to_body = state.rotate_world_to_body * adekf::SO3(state.w_angular_rate * deltaT).conjugate();
};
Eigen::Matrix<double, 6, 1> fm_diag;
fm_diag << 10., 10., 10., .1, .1, .1;
Eigen::Matrix<double, 6, 6> fm_sigma = fm_diag.asDiagonal();
//Setup landmarks.
SimulatedRadar radar1(Eigen::Vector3d(0, 40, -150)), radar2(Eigen::Vector3d(-120, 40, -150)), radar3(Eigen::Vector3d(-30, 0, -150)), radar4(Eigen::Vector3d(-90, 80, -150));
//measurement model of 4 simultaneous landmark measurements
auto radar_model = [](auto &&state, const SimulatedRadar &radar1, const SimulatedRadar &radar2, const SimulatedRadar &radar3, const SimulatedRadar &radar4) {
return Radar4{radar1.getRadar<ScalarOf(state)>(state.w_position, state.rotate_world_to_body),
radar2.getRadar<ScalarOf(state)>(state.w_position, state.rotate_world_to_body),
radar3.getRadar<ScalarOf(state)>(state.w_position, state.rotate_world_to_body),
radar4.getRadar<ScalarOf(state)>(state.w_position, state.rotate_world_to_body)};
};
double rad_sigma = 1;
GaussianNoiseVector radar_noise(0, rad_sigma, rad_sigma, rad_sigma);
//Setup noise of measurement
Eigen::Matrix<double, 12, 12> rm4_sigma = rm4_sigma.Zero();
rm4_sigma.block<3, 3>(0, 0) = rm4_sigma.block<3, 3>(3, 3) = rm4_sigma.block<3, 3>(6, 6) = rm4_sigma.block<3, 3>(9, 9) = radar_noise.getCov();
constexpr size_t monte_carlo_runs = 100;
std::map<const char *, adekf::aligned_vector<Eigen::Matrix<double, 6, 1> > > metrics;
for (size_t run_number = 0; run_number < monte_carlo_runs; run_number++)
{
//Setup ekf
adekf::ADEKF ekf{CT_State<double>(), Eigen::Matrix<double, 12, 12>::Identity()};
ekf.mu.w_velocity.x() = 10.;
ekf.mu.w_position=path.path[0];
ekf.mu.w_angular_rate.z() = 0.0;
//Setup Smoother
adekf::RTS_Smoother smoother{ekf};
adekf::Naive_RTS_Smoother naive_smoother{ekf};
#if defined(RTSIMMS) || defined(NIMMS)
//setup BP RTS IMM
adekf::BPRTSIMM rts_imm{ekf.mu, ekf.sigma, {sm_sigma, ct_sigma}, straight_model, constant_turn_model};
adekf::Naive_RTSIMM naive_imm{ekf.mu, ekf.sigma, {sm_sigma, ct_sigma}, straight_model, constant_turn_model};
rts_imm.addFilters({0, 1});
naive_imm.addFilters({0, 1});
//Setup of start conditions
Eigen::Matrix<double, 2, 2> t_prob;
t_prob << 0.95, 0.05,
0.05, 0.95;
rts_imm.setTransitionProbabilities(t_prob);
naive_imm.setTransitionProbabilities(t_prob);
Eigen::Vector2d start_prob(0.5, 0.5);
rts_imm.setStartProbabilities(start_prob);
naive_imm.setStartProbabilities(start_prob);
#endif //IMMS
auto calcConsistency = [](auto &&filter_state, auto &&sigma, auto &>) {
auto diff = (filter_state - gt).eval();
return (diff.transpose() * sigma.inverse() * diff)(0);
};
adekf::aligned_vector<Radar4<double>> all_measurements;
auto calcPerformanceMetrics = [&](auto &filter, const char *title, auto &stateGetter, auto &sigmaGetter) {
double rmse_pos = 0., rmse_orient = 0., consistency_state = 0., consistency_measurement = 0.;
Eigen::Matrix<double, 6, 1> state_delta = state_delta.Zero();
Radar4<double>::DeltaType<double> meas_delta = meas_delta.Zero();
size_t size = path.path.size();
for (size_t i = 0; i < size; i++)
{
auto way_point = path.path[i];
auto orient = path.orientations[i].conjugate();
auto mu = stateGetter(filter, i);
rmse_pos += pow((mu.w_position - way_point).norm(), 2);
rmse_orient += pow((mu.rotate_world_to_body - orient).norm(), 2);
state_delta.segment<3>(0) += mu.rotate_world_to_body - orient;
state_delta.segment<3>(3) += mu.w_position - way_point;
consistency_state += calcConsistency(Sub_State{mu.rotate_world_to_body, mu.w_position}, sigmaGetter(filter, i).template block<6, 6>(0, 0), Sub_State{orient, way_point});
//consistency_state+=calcConsistency(mu.w_position,sigmaGetter(filter,i).template block<3,3>(3,3),way_point);
Radar4<double> expected_meas = radar_model(mu, radar1, radar2, radar3, radar4);
meas_delta += expected_meas - all_measurements[i];
auto input = radar_model(adekf::eval(mu + adekf::getDerivator<CT_State<double>::DOF>()), radar1, radar2, radar3, radar4).vector_part;
auto H=adekf::extractJacobi(input);
consistency_measurement += calcConsistency(all_measurements[i], H * sigmaGetter(filter, i) * H.transpose() + rm4_sigma, expected_meas);
}
Eigen::Matrix<double, 6, 1> metric_values;
metric_values << sqrt(rmse_pos / size),
sqrt(rmse_orient / size),
state_delta.norm() / size,
consistency_state / size,
meas_delta.norm() / size,
consistency_measurement / size;
auto metric = metrics.find(title);
if (metric == metrics.end())
{
metrics.emplace(title, adekf::aligned_vector<Eigen::Matrix<double, 6, 1> >());
metric=metrics.find(title);
}
metric->second.push_back( metric_values);
if (run_number == monte_carlo_runs - 1)
{
Eigen::Matrix<double,6,1> zeros=zeros.Zero(); // Is instantiated before so it has the type Eigen::Matrix instead of cwise nullary exp. Deduces wrong type in accumulate otherwise.
Eigen::Matrix<double,6,1> mean=std::accumulate(metric->second.begin(),metric->second.end(),zeros)/monte_carlo_runs;
Eigen::Matrix<double,6,1> sigma=std::accumulate(metric->second.begin(),metric->second.end(),zeros,[&](const auto & a, const auto & b){
auto diff=b-mean;
return a+diff*diff.transpose().diagonal();
})/monte_carlo_runs;
std::cout << setprecision(6) << title << " Performance values: " << std::endl
<< "\t Pos RMSE: " << mean(0)
<< "\t Orient RMSE: " << mean(1)
<< "\t Mu bias: " << mean(2)
<< "\t Mu Cons: " << mean(3)
<< "\t Z bias: " << mean(4)
<< "\t Z Cons: " << mean(5)
<< std::endl;
std::cout << sigma.transpose()<< std::endl;
}
};
std::vector<std::tuple<double>> all_controls;
for (size_t i = 1; i < path.path.size(); i++)
{
//read Ground truth path
auto way_point = path.path[i];
auto orient = path.orientations[i].conjugate();
all_controls.emplace_back(deltaT);
Radar4<double> target{(radar1.getRadar(way_point, orient) + radar_noise.poll()),
(radar2.getRadar(way_point, orient) + radar_noise.poll()),
(radar3.getRadar(way_point, orient) + radar_noise.poll()),
(radar4.getRadar(way_point, orient) + radar_noise.poll())};
all_measurements.push_back(target);
#ifdef RTSIMMS
//RTSIMM
rts_imm.interaction();
rts_imm.predictWithNonAdditiveNoise(deltaT);
rts_imm.update(radar_model, rm4_sigma, target, radar1, radar2, radar3, radar4);
rts_imm.combination();
rts_imm.storeEstimation();
#endif
#ifdef NIMMS
//Naive IMM
naive_imm.interaction();
naive_imm.predictWithNonAdditiveNoise(deltaT);
naive_imm.update(radar_model, rm4_sigma, target, radar1, radar2, radar3, radar4);
naive_imm.combination();
naive_imm.storeEstimation();
#endif
#ifdef EKS
//[+]-EKS
smoother.predictWithNonAdditiveNoise(EKF_MODEL, EKF_SIGMA, deltaT);
smoother.storePredictedEstimation();
smoother.update(radar_model, rm4_sigma, target, radar1, radar2, radar3, radar4);
smoother.storeEstimation();
#endif
//(M)-EKS
#ifdef MEKS
naive_smoother.predictWithNonAdditiveNoise(EKF_MODEL, EKF_SIGMA, deltaT);
naive_smoother.storePredictedEstimation();
naive_smoother.update(radar_model, rm4_sigma, target, radar1, radar2, radar3, radar4);
naive_smoother.storeEstimation();
#endif
}
//Getters for calc metrics
auto getOldMu = [](auto &filter, int i) { return filter.old_mus[i]; };
auto getOldSigma = [](auto &filter, int i) { return filter.old_sigmas[i]; };
auto getSmoothedMu = [](auto &filter, int i) { return filter.smoothed_mus[i]; };
auto getSmoothedSigma = [](auto &filter, int i) { return filter.smoothed_sigmas[i]; };
//call all smoothers
//Call metrics for each filter
#ifdef EKS
smoother.smoothAllWithNonAdditiveNoise(EKF_MODEL, EKF_SIGMA, all_controls);
calcPerformanceMetrics(smoother, "[+]-EKF", getOldMu, getOldSigma);
calcPerformanceMetrics(smoother, "[+]-EKS", getSmoothedMu, getSmoothedSigma);
#endif
#ifdef MEKS
naive_smoother.smoothAllWithNonAdditiveNoise(EKF_MODEL, EKF_SIGMA, all_controls);
calcPerformanceMetrics(naive_smoother, "(M)-EKS", getSmoothedMu, getSmoothedSigma);
#endif
#ifdef RTSIMMS
rts_imm.smoothAllWithNonAdditiveNoise(all_controls);
calcPerformanceMetrics(rts_imm, "[+]-IMM", getOldMu, getOldSigma);
calcPerformanceMetrics(rts_imm, "[+]-RTSIMMS", getSmoothedMu, getSmoothedSigma);
#endif
#ifdef NIMMS
naive_imm.smoothAllWithNonAdditiveNoise(all_controls);
calcPerformanceMetrics(naive_imm, "Naive-IMM", getOldMu, getOldSigma);
calcPerformanceMetrics(naive_imm, "Naive-(M)-RTSIMMS", getSmoothedMu, getSmoothedSigma);
#endif
//#define SHOW_VIZ
#ifdef SHOW_VIZ //Currently not working
//Vectors to store path for evaluation
std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> ekf_estimated_poses, imm_estimated_poses, rts_imm_estimated_poses, smoother_estimated_poses;
//visualize paths
adekf::viz::initGuis(argc, argv);
adekf::viz::PoseRenderer::displayPath(path.path, "red");
for(auto state: smoother.old_mus){
ekf_estimated_poses.push_back(state.w_position);
}
adekf::viz::PoseRenderer::displayPath(ekf_estimated_poses, "black");
/*adekf::viz::PoseRenderer::displayPath(imm_estimated_poses, "green");
adekf::viz::PoseRenderer::displayPath(rts_imm_estimated_poses, "blue");
adekf::viz::PoseRenderer::displayPath(smoother_estimated_poses, "orange");*/
adekf::viz::PoseRenderer::displayPoints({radar1.position, radar2.position, radar3.position, radar4.position}, "red", 5);
adekf::viz::runGuis();
#endif //SHOW_VIZ
}
std::cout << "Naive indefinite Counter: " << adekf::Naive_RTS_Smoother<CT_State<double>>::indefinite_counter << std::endl;
std::cout << "[+] indefinite Counter: " << adekf::RTS_Smoother<CT_State<double>>::indefinite_counter << std::endl;
return 0;
}
| 48.490798 | 194 | 0.615764 | TomLKoller |
Subsets and Splits