hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
โŒ€
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
โŒ€
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
โŒ€
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
โŒ€
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
โŒ€
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
โŒ€
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
โŒ€
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
โŒ€
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
โŒ€
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
1946511e9585cbaf319a9816fa1f3de02358c68f
1,085
cc
C++
creational/src/prototype/maze_prototype_factory.cc
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
9
2016-08-03T16:15:57.000Z
2021-11-08T13:15:46.000Z
creational/src/prototype/maze_prototype_factory.cc
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
null
null
null
creational/src/prototype/maze_prototype_factory.cc
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
4
2016-08-03T16:16:01.000Z
2017-12-27T05:14:55.000Z
// Based on "Design Patterns: Elements of Reusable Object-Oriented Software" // book by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm // // Created by Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. #include "maze_prototype_factory.h" namespace creational { namespace prototype { MazePrototypeFactory::MazePrototypeFactory(commons::Maze* m, commons::Wall* w, commons::Room* r, commons::Door* d) { prototype_maze_ = m; prototype_wall_ = w; prototype_room_ = r; prototype_door_ = d; } commons::Room *MazePrototypeFactory::MakeRoom(const int&) const { auto room = prototype_room_->Clone(); return room; } commons::Maze *MazePrototypeFactory::MakeMaze() const { return prototype_maze_->Clone(); } commons::Wall *MazePrototypeFactory::MakeWall() const { return prototype_wall_->Clone(); } commons::Door *MazePrototypeFactory::MakeDoor(const commons::Room& first_room, const commons::Room& second_room) const { auto door = prototype_door_->Clone(); door->Initialize(first_room, second_room); return door; } } }
24.111111
118
0.758525
rachwal
19479dd6b3bc0d9adfe49819ccb09e8be6112570
1,120
cpp
C++
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
#include "../../../PrecompiledHeaders/stdafx.h" #include "IndexBuffer.h" namespace dx11 { // Constructors and Destructor: IndexBuffer::IndexBuffer(RenderSystem& renderSystem, const std::vector<uint16>& indices) : count( UINT( indices.size() ) ) { D3D11_BUFFER_DESC index_buffer_desc = {}; index_buffer_desc.BindFlags = D3D11_BIND_INDEX_BUFFER; index_buffer_desc.Usage = D3D11_USAGE_DEFAULT; index_buffer_desc.CPUAccessFlags = 0u; index_buffer_desc.MiscFlags = 0u; index_buffer_desc.ByteWidth = UINT( count * sizeof( uint16 ) ); index_buffer_desc.StructureByteStride = sizeof( uint16 ); D3D11_SUBRESOURCE_DATA index_subresource_data = {}; index_subresource_data.pSysMem = indices.data(); Bindable::GetDevice( renderSystem )->CreateBuffer( &index_buffer_desc, &index_subresource_data, &m_pIndexBuffer ); } // Functions: void IndexBuffer::Bind(RenderSystem& renderSystem) noexcept { Bindable::GetContext( renderSystem )->IASetIndexBuffer( m_pIndexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0u ); } // Accessors: const UINT& IndexBuffer::GetCount() const noexcept { return count; } }
26.046512
116
0.755357
LexSheyn
194edcd60b676d2b702caf68ea5608d0ad8ce143
4,462
cpp
C++
src/main.cpp
tsaarni/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
27
2017-08-15T05:45:21.000Z
2022-03-27T21:32:46.000Z
src/main.cpp
AA6KL/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
1
2022-01-10T19:43:12.000Z
2022-01-10T19:43:12.000Z
src/main.cpp
AA6KL/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
11
2017-08-15T16:28:41.000Z
2021-04-26T11:52:54.000Z
// // BSD 3-Clause License // // Copyright (c) 2017, Tero Saarni // // // This software re-programs ATtiny85 fuses using the high-voltage // serial programming method. // // // References // // * ATtiny85 datasheet - // http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf // // * Online fuse value calculator - // http://www.engbedded.com/fusecalc/ // // // High-voltaga serial programming instruction set (from ATtiny85 datasheet) // // Write Fuse Low Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_A987_6543_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0110_0100_00 0_0110_1100_00 goes high. Write A - 3 = โ€œ0โ€ to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // // Write Fuse High Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_IHGF_EDCB_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0111_0100_00 0_0111_1100_00 goes high. Write I - B = โ€œ0โ€ to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // // Write Fuse Extended Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_0000_000J_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0110_0110_00 0_0110_1110_00 goes high. Write J = โ€œ0โ€ to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // #include <Arduino.h> // ATtiny85 pin mapaping at Arduino nano programmer #define SDI_PIN 9 // serial data input #define SII_PIN 10 // serial instruction input #define SDO_PIN 11 // serial data output #define SCI_PIN 12 // serial clock input #define RESET_PIN 13 // reset void avr_hvsp_write(uint8_t sdi, uint8_t sii) { digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); for (uint8_t i = 0; i < 8; i++) { digitalWrite(SDI_PIN, (sdi & (1 << (7-i)))); digitalWrite(SII_PIN, (sii & (1 << (7-i)))); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); } digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); } void avr_hvsp_write_lfuse(uint8_t lfuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(lfuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01100100); avr_hvsp_write(0b00000000, 0b01101100); while (digitalRead(SDO_PIN) == LOW) { }; } void avr_hvsp_write_hfuse(uint8_t hfuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(hfuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01110100); avr_hvsp_write(0b00000000, 0b01111100); while (digitalRead(SDO_PIN) == LOW) { }; } void avr_hvsp_write_efuse(uint8_t efuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(efuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01100110); avr_hvsp_write(0b00000000, 0b01101110); while (digitalRead(SDO_PIN) == LOW) { }; } void setup() { Serial.begin(9600); // setup pin modes pinMode(SDI_PIN, OUTPUT); pinMode(SII_PIN, OUTPUT); pinMode(SDO_PIN, OUTPUT); pinMode(SCI_PIN, OUTPUT); pinMode(RESET_PIN, OUTPUT); // enter programming mode digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SDO_PIN, LOW); digitalWrite(RESET_PIN, HIGH); // pull attiny85 reset pin to ground delayMicroseconds(20); digitalWrite(RESET_PIN, LOW); // attiny85 reset pin to 12V delayMicroseconds(10); pinMode(SDO_PIN, INPUT); delayMicroseconds(300); // write default fuse values avr_hvsp_write_lfuse(0x62); avr_hvsp_write_hfuse(0xdf); avr_hvsp_write_efuse(0xff); // exit programming mode digitalWrite(RESET_PIN, HIGH); // pull attiny85 reset pin to ground (arduino nano LED will be on) } void loop() { Serial.print("Programming done"); while (true) { delay(1000); Serial.print("."); } }
30.353741
112
0.680861
tsaarni
195296a7835c174b6c4a11ca841e1547ca0eb41e
1,861
cc
C++
Dragon/src/operators/activation/tanh_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
212
2015-07-05T07:57:17.000Z
2022-02-27T01:55:35.000Z
Dragon/src/operators/activation/tanh_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
6
2016-07-07T14:31:56.000Z
2017-12-12T02:21:15.000Z
Dragon/src/operators/activation/tanh_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
71
2016-03-24T09:02:41.000Z
2021-06-03T01:52:41.000Z
#include "operators/activation/tanh_op.h" #include "utils/math_functions.h" #include "utils/op_kernel.h" namespace dragon { template <class Context> template <typename T> void TanhOp<Context>::RunWithType() { auto* Xdata = input(0).template data<T, Context>(); auto* Ydata = output(0)->template mutable_data<T, Context>(); kernel::Tanh<T, Context>(output(0)->count(), Xdata, Ydata); } template <class Context> void TanhOp<Context>::RunOnDevice() { output(0)->ReshapeLike(input(0)); if (input(0).template IsType<float>()) RunWithType<float>(); else LOG(FATAL) << "Unsupported input types."; } DEPLOY_CPU(Tanh); #ifdef WITH_CUDA DEPLOY_CUDA(Tanh); #endif OPERATOR_SCHEMA(Tanh).NumInputs(1).NumOutputs(1).Inplace({ { 0, 0 } }); template <class Context> template <typename T> void TanhGradientOp<Context>::RunWithType() { auto* Ydata = input(0).template data<T, Context>(); auto* dYdata = input(1).template data<T, Context>(); auto* dXdata = output(0)->template mutable_data<T, Context>(); kernel::TanhGrad<T, Context>(output(0)->count(), dYdata, Ydata, dXdata); } template <class Context> void TanhGradientOp<Context>::RunOnDevice() { output(0)->ReshapeLike(input(0)); if (input(0).template IsType<float>()) RunWithType<float>(); else LOG(FATAL) << "Unsupported input types."; } DEPLOY_CPU(TanhGradient); #ifdef WITH_CUDA DEPLOY_CUDA(TanhGradient); #endif OPERATOR_SCHEMA(TanhGradient).NumInputs(2).NumOutputs(1).Inplace({ { 1, 0 } }); class GetTanhGradient final : public GradientMakerBase { public: GRADIENT_MAKER_CTOR(GetTanhGradient); vector<OperatorDef> MakeDefs() override { return SingleDef(def.type() + "Gradient", "", vector<string> {O(0), GO(0)}, vector<string> {GI(0)}); } }; REGISTER_GRADIENT(Tanh, GetTanhGradient); } // namespace dragon
30.508197
79
0.686728
neopenx
19555fe091d99443665ad7fd7a8d939577780fcb
4,925
cpp
C++
src/image_widget.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/image_widget.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/image_widget.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
/* Copyright (C) 2003-2014 by David White <davewx7@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "Canvas.hpp" #include "DisplayDevice.hpp" #include "image_widget.hpp" #include <iostream> namespace gui { ImageWidget::ImageWidget(const std::string& fname, int w, int h) : texture_(KRE::Texture::createTexture(fname)), rotate_(0.0f), image_name_(fname) { setEnvironment(); init(w, h); } ImageWidget::ImageWidget(KRE::TexturePtr tex, int w, int h) : texture_(tex), rotate_(0.0) { setEnvironment(); init(w, h); } ImageWidget::ImageWidget(const variant& v, game_logic::FormulaCallable* e) : Widget(v, e) { if(v.has_key("area")) { area_ = rect(v["area"]); } texture_ = KRE::Texture::createTexture(v); rotate_ = v.has_key("rotation") ? v["rotation"].as_float() : 0.0f; init(v["image_width"].as_int(-1), v["image_height"].as_int(-1)); setClaimMouseEvents(v["claim_mouse_events"].as_bool(false)); } void ImageWidget::init(int w, int h) { if(w < 0) { if(area_.w()) { w = area_.w()*2; } else { w = texture_->width(); } } if(h < 0) { if(area_.h()) { h = area_.h()*2; } else { h = texture_->height(); } } setDim(w,h); } void ImageWidget::handleDraw() const { if(area_.w() == 0) { KRE::Canvas::getInstance()->blitTexture(texture_, rotate_, rect(x(), y(), width(), height())); } else { KRE::Canvas::getInstance()->blitTexture(texture_, area_, rotate_, rect(x(), y(), width(), height())); } } WidgetPtr ImageWidget::clone() const { return WidgetPtr(new ImageWidget(*this)); } BEGIN_DEFINE_CALLABLE(ImageWidget, Widget) DEFINE_FIELD(image, "string") return variant(obj.image_name_); DEFINE_SET_FIELD_TYPE("string|map") if(value.is_string()) { obj.image_name_ = value.as_string(); obj.texture_ = KRE::Texture::createTexture(obj.image_name_); } else { obj.texture_ = KRE::Texture::createTexture(value); } DEFINE_FIELD(area, "[int,int,int,int]") return obj.area_.write(); DEFINE_SET_FIELD obj.area_ = rect(value); DEFINE_FIELD(rotation, "decimal") return variant(obj.rotate_); DEFINE_SET_FIELD obj.rotate_ = value.as_float(); DEFINE_FIELD(width, "int") return variant(obj.texture_->width()); DEFINE_FIELD(height, "int") return variant(obj.texture_->height()); DEFINE_FIELD(image_width, "int") return variant(obj.texture_->width()); DEFINE_FIELD(image_height, "int") return variant(obj.texture_->height()); DEFINE_FIELD(image_wh, "[int,int]") std::vector<variant> v; v.emplace_back(variant(obj.area_.w())); v.emplace_back(variant(obj.area_.h())); return variant(&v); DEFINE_SET_FIELD obj.init(value[0].as_int(), value[1].as_int()); END_DEFINE_CALLABLE(ImageWidget) GuiSectionWidget::GuiSectionWidget(const std::string& id, int w, int h, int scale) : section_(GuiSection::get(id)), scale_(scale) { setEnvironment(); if(section_ && w == -1) { setDim((section_->width()/2)*scale_, (section_->height()/2)*scale_); } else { setDim(w,h); } } GuiSectionWidget::GuiSectionWidget(const variant& v, game_logic::FormulaCallable* e) : Widget(v,e), section_(GuiSection::get(v)), scale_(v["scale"].as_int(1)) { if(!v.has_key("width") && section_) { setDim((section_->width()/2)*scale_, (section_->height()/2)*scale_); } } void GuiSectionWidget::setGuiSection(const std::string& id) { section_ = GuiSection::get(id); } void GuiSectionWidget::handleDraw() const { if(section_) { section_->blit(x(), y(), width(), height()); } } WidgetPtr GuiSectionWidget::clone() const { return WidgetPtr(new GuiSectionWidget(*this)); } BEGIN_DEFINE_CALLABLE(GuiSectionWidget, Widget) DEFINE_FIELD(name, "string") return variant(); DEFINE_SET_FIELD obj.setGuiSection(value.as_string()); DEFINE_FIELD(scale, "decimal") return variant(obj.scale_); DEFINE_SET_FIELD if(obj.section_) { obj.setDim((obj.section_->width()/2)*obj.scale_, (obj.section_->height()/2)*obj.scale_); } END_DEFINE_CALLABLE(GuiSectionWidget) }
25.651042
104
0.675533
gamobink
1958ce79e96fc3c2e4c92e2e5427e6916560a676
8,696
cpp
C++
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
#include "richtext.hpp" #include <SFML/Graphics.hpp> #include <sstream> static std::map<sf::String, sf::Color> colors; // same as sf::Text styles // define them locally to redefine them for a child class for example #define Regular 0 #define Bold 1 #define Italic 2 #define Underlined 4 // TextChunk functions TextChunk::TextChunk() { style = Regular; color = sf::Color::White; endsInNewline = false; } void TextChunk::add(std::vector<TextChunk*>& chunks, TextChunk*& current, TextChunk* last) { chunks.push_back(new TextChunk()); current = chunks.back(); if(chunks.size() > 2) { current->style = last->style; current->color = last->color; } } void TextChunk::format(TextChunk*& current, TextChunk* last, int32_t style) { if((last->style & style) >= 0) current->style ^= style; else current->style |= style; } // RichText functions RichText::RichText() { nlratio = 1.5; csize = 20; // default parameters font = nullptr; } RichText::RichText(const sf::String& source, const sf::Font& font, uint32_t csize) { nlratio = 1.5; this->csize = csize; this->font = &font; setString(source); // update the displayed string } RichText::~RichText() { clear(); } sf::String RichText::getString() const { return string; } sf::String RichText::getSource() const { return source; } void RichText::setString(const sf::String& source) { this->source = source; if(!font) return; // nothing to display, return clear(); if(source.getSize() == 0) return; chunks.push_back(new TextChunk()); TextChunk* current = chunks[0]; TextChunk* last = nullptr; bool escaped = false; // create the chunks for(uint32_t i = 0; i < source.getSize(); ++i) { last = current; if(escaped) { current->text += source[i]; escaped = false; continue; } switch(source[i]) { case '~': // italics { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Italic); current->color = last->color; break; } case '*': // bold { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Bold); current->color = last->color; break; } case '_': // underline { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Underlined); current->color = last->color; break; } case '#': // color { int32_t length = 0; int32_t start = i + 1; // seek forward until the next whitespace while(!isspace(source[++i])) ++length; TextChunk::add(chunks, current, last); bool isValid; sf::Color c = getColor(source.toWideString().substr(start, length), isValid); if(isValid) current->color = c; break; } case '\\': // escape sequence for escaping formatting characters { if(escaped) { current->text += source[i]; escaped = false; break; } if (i + 1 < source.getSize()) { switch (source[i + 1]) { case '~': case '*': case '_': case '#': { escaped = true; break; } default: break; } } if (!escaped) current->text += source[i]; break; } case '\n': // make a new chunk in the case of a newline { current->endsInNewline = true; TextChunk::add(chunks, current, last); break; } default: { escaped = false; current->text += source[i]; // append the character break; } } } build(); } void RichText::build() { float boundY = csize*nlratio; sf::Text* t = nullptr; sf::Vector2f partPos(0, 0); // still forced to clear here for(size_t i = 0; i < parts.size(); ++i) if(parts[i] != nullptr) delete parts[i]; parts.clear(); bounds.left = 0; bounds.top = 0; bounds.width = 0; bounds.height = 0; for(size_t i = 0; i < chunks.size(); ++i) { if(chunks[i]->text.getSize() != 0) { t = new sf::Text(); t->setFillColor(chunks[i]->color); t->setString(chunks[i]->text); t->setStyle(chunks[i]->style); t->setCharacterSize(csize); if(font) t->setFont(*font); t->setPosition(partPos); } if(t) partPos.x += t->getLocalBounds().width; if(partPos.x >= bounds.width) bounds.width = partPos.x; if(chunks[i]->endsInNewline) { partPos.y += boundY; partPos.x = 0; bounds.height += boundY; } else if(i == chunks.size()-1) { bounds.height += boundY; } if(t) { parts.push_back((sf::Drawable*)t); t = nullptr; } } } void RichText::clear() { for(size_t i = 0; i < chunks.size(); ++i) delete chunks[i]; chunks.clear(); for(size_t i = 0; i < parts.size(); ++i) if(parts[i] != nullptr) delete parts[i]; parts.clear(); bounds.left = 0; bounds.top = 0; bounds.width = 0; bounds.height = 0; } uint32_t RichText::getCharacterSize() const { return csize; } void RichText::setCharacterSize(uint32_t size) { csize = (size < 1) ? 1 : size; build(); } float RichText::getNewLineSize() const { return nlratio; } void RichText::setNewLineSize(float size) { nlratio = (size <= 0) ? 1.5 : size; build(); } const sf::Font* RichText::getFont() const { return font; } void RichText::setFont(const sf::Font& font) { this->font = &font; build(); } void RichText::setFont(const sf::Font* font) { this->font = font; build(); } sf::FloatRect RichText::getLocalBounds() const { return bounds; } sf::FloatRect RichText::getGlobalBounds() const { return getTransform().transformRect(getLocalBounds()); } void RichText::addColor(const sf::String& name, const sf::Color& color) { colors[name] = color; } void RichText::addColor(const sf::String& name, uint32_t argbHex) { colors[name] = getColor(argbHex); } void RichText::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); for(size_t i = 0; i < parts.size(); ++i) if(parts[i]) target.draw(*parts[i], states); } void RichText::initializeColors() { colors["default"] = sf::Color::White; colors["black"] = sf::Color::Black; colors["blue"] = sf::Color::Blue; colors["cyan"] = sf::Color::Cyan; colors["green"] = sf::Color::Green; colors["magenta"] = sf::Color::Magenta; colors["red"] = sf::Color::Red; colors["white"] = sf::Color::White; colors["yellow"] = sf::Color::Yellow; } sf::Color RichText::getColor(const sf::String& source, bool& isValid) { std::map<sf::String, sf::Color>::const_iterator result = colors.find(source); if(result == colors.end()) { // basic hexadecimal check for(size_t i = 0; i < source.getSize(); ++i) { if((source[i] < 'a' || source [i] > 'f') && (source[i] < 'A' || source[i] > 'F') && (source[i] < '0' || source[i] > '9')) { isValid = false; return sf::Color::White; } } uint32_t hex = 0x0; if(!(std::istringstream(source) >> std::hex >> hex)) { // Error parsing; return default isValid = false; return sf::Color::White; } isValid = true; return getColor(hex); } isValid = true; return result->second; } sf::Color RichText::getColor(uint32_t argbHex) { argbHex |= 0xff000000; return sf::Color(argbHex >> 16 & 0xFF, argbHex >> 8 & 0xFF, argbHex >> 0 & 0xFF, argbHex >> 24 & 0xFF); }
24.426966
133
0.504715
FoFabien
1959a87e2e79912fef60d33de6eec1fc1d807a5b
17,024
cc
C++
L1Trigger/L1TMuonEndCap/src/EMTFTrack2016Tools.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
L1Trigger/L1TMuonEndCap/src/EMTFTrack2016Tools.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
L1Trigger/L1TMuonEndCap/src/EMTFTrack2016Tools.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "L1Trigger/L1TMuonEndCap/interface/EMTFTrack2016Tools.h" namespace l1t { void EMTFTrack2016::ImportSP( const emtf::SP _SP, int _sector) { EMTFTrack2016::set_sector ( _sector ); EMTFTrack2016::set_sector_GMT ( calc_sector_GMT(_sector) ); EMTFTrack2016::set_mode ( _SP.Mode() ); EMTFTrack2016::set_quality ( _SP.Quality_GMT() ); EMTFTrack2016::set_bx ( _SP.TBIN() - 3 ); EMTFTrack2016::set_pt_GMT ( _SP.Pt_GMT() ); EMTFTrack2016::set_pt_LUT_addr ( _SP.Pt_LUT_addr() ); EMTFTrack2016::set_eta_GMT ( _SP.Eta_GMT() ); EMTFTrack2016::set_phi_loc_int ( _SP.Phi_full() ); EMTFTrack2016::set_phi_GMT ( _SP.Phi_GMT() ); EMTFTrack2016::set_charge ( (_SP.C() == 1) ? -1 : 1 ); // uGMT uses opposite of physical charge (to match pdgID) EMTFTrack2016::set_charge_GMT ( _SP.C() ); EMTFTrack2016::set_charge_valid ( _SP.VC() ); EMTFTrack2016::set_pt ( calc_pt( pt_GMT ) ); EMTFTrack2016::set_eta ( calc_eta( eta_GMT ) ); EMTFTrack2016::set_phi_loc_deg ( calc_phi_loc_deg( phi_loc_int ) ); EMTFTrack2016::set_phi_loc_rad ( calc_phi_loc_rad( phi_loc_int ) ); EMTFTrack2016::set_phi_glob_deg ( calc_phi_glob_deg( phi_loc_deg, _sector ) ); EMTFTrack2016::set_phi_glob_rad ( calc_phi_glob_rad( phi_loc_rad, _sector ) ); } // End EMTFTrack2016::ImportSP // Calculates special chamber ID for track address sent to uGMT, using CSC_ID, subsector, neighbor, and station int calc_uGMT_chamber( int _csc_ID, int _subsector, int _neighbor, int _station) { if (_station == 1) { if ( _csc_ID == 3 && _neighbor == 1 && _subsector == 2 ) return 1; else if ( _csc_ID == 6 && _neighbor == 1 && _subsector == 2 ) return 2; else if ( _csc_ID == 9 && _neighbor == 1 && _subsector == 2 ) return 3; else if ( _csc_ID == 3 && _neighbor == 0 && _subsector == 2 ) return 4; else if ( _csc_ID == 6 && _neighbor == 0 && _subsector == 2 ) return 5; else if ( _csc_ID == 9 && _neighbor == 0 && _subsector == 2 ) return 6; else return 0; } else { if ( _csc_ID == 3 && _neighbor == 1 ) return 1; else if ( _csc_ID == 9 && _neighbor == 1 ) return 2; else if ( _csc_ID == 3 && _neighbor == 0 ) return 3; else if ( _csc_ID == 9 && _neighbor == 0 ) return 4; else return 0; } } // Unpacks pT LUT address into dPhi, dTheta, CLCT, FR, eta, and mode // Based on L1Trigger/L1TMuonEndCap/interface/PtAssignment.h // "Mode" here is the true mode, not the inverted mode used in PtAssignment.h void EMTFTrack2016::ImportPtLUT(int _mode, unsigned long _address) { if (_mode == 12) { // mode_inv == 3 EMTFTrack2016::set_dPhi_12 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_12 (dPhi_12 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_12 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_2 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_2 (clct_2 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_2 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 10) { // mode_inv == 5 EMTFTrack2016::set_dPhi_13 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_13 (dPhi_13 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_13 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_3 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_3 (clct_3 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_3 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 9) { // mode_inv == 9 EMTFTrack2016::set_dPhi_14 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_14 (dPhi_14 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_14 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_4 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_4 (clct_4 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_4 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 6) { // mode_inv = 6 EMTFTrack2016::set_dPhi_23 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_23 (dPhi_23 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_23 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_2 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_2 (clct_2 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_3 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_3 (clct_3 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_2 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_3 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 5) { // mode_inv == 10 EMTFTrack2016::set_dPhi_24 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_24 (dPhi_24 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_24 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_2 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_2 (clct_2 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_4 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_4 (clct_4 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_2 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_4 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 3) { // mode_inv == 12 EMTFTrack2016::set_dPhi_34 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_34 (dPhi_34 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_34 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_3 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_3 (clct_3 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_4 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_4 (clct_4 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_3 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_4 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 14) { // mode_inv == 7 EMTFTrack2016::set_dPhi_12 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_23 ( ( _address >> (0+7) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_dPhi_12 (dPhi_12 * (( ( _address >> (0+7+5) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_23 (dPhi_23 * (( ( _address >> (0+7+5+1) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_13 ( ( _address >> (0+7+5+1+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+7+5+1+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+7+5+1+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+7+5+1+1+3+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 13) { // mode_inv == 11 EMTFTrack2016::set_dPhi_12 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_24 ( ( _address >> (0+7) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_dPhi_12 (dPhi_12 * (( ( _address >> (0+7+5) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_24 (dPhi_24 * (( ( _address >> (0+7+5+1) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_14 ( ( _address >> (0+7+5+1+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+7+5+1+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+7+5+1+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+7+5+1+1+3+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 11) { EMTFTrack2016::set_dPhi_13 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_34 ( ( _address >> (0+7) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_dPhi_13 (dPhi_13 * (( ( _address >> (0+7+5) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_34 (dPhi_34 * (( ( _address >> (0+7+5+1) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_14 ( ( _address >> (0+7+5+1+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+7+5+1+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+7+5+1+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+7+5+1+1+3+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 7) { // mode_inv == 14 EMTFTrack2016::set_dPhi_23 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_34 ( ( _address >> (0+7) ) & ( (1 << 6) - 1) ); EMTFTrack2016::set_dPhi_23 (dPhi_23 * (( ( _address >> (0+7+6) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_34 (dPhi_34 * (( ( _address >> (0+7+6+1) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_24 ( ( _address >> (0+7+6+1+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_2 ( ( _address >> (0+7+5+1+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_2 (clct_2 * ( ( ( _address >> (0+7+6+1+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+6+1+1+3+2+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+6+1+1+3+2+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 15) { // mode_inv == 15 EMTFTrack2016::set_dPhi_12 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_23 ( ( _address >> (0+7) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_dPhi_34 ( ( _address >> (0+7+5) ) & ( (1 << 6) - 1) ); EMTFTrack2016::set_dPhi_23 (dPhi_23 * (( ( _address >> (0+7+5+6) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_34 (dPhi_34 * (( ( _address >> (0+7+5+6+1) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+7+5+6+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+5+6+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+5+6+1+1+1+5) ) & ( (1 << 4) - 1) ); } } // End function: void EMTFTrack2016::ImportPtLUT EMTFTrack2016 EMTFTrack2016Extra::CreateEMTFTrack2016() { EMTFTrack2016 thisTrack; for (int iHit = 0; iHit < NumHitsExtra(); iHit++) { thisTrack.push_Hit( _HitsExtra.at(iHit).CreateEMTFHit2016() ); } thisTrack.set_endcap ( Endcap() ); thisTrack.set_sector ( Sector() ); thisTrack.set_sector_GMT ( Sector_GMT() ); thisTrack.set_sector_index ( Sector_index() ); thisTrack.set_mode ( Mode() ); thisTrack.set_mode_LUT ( Mode_LUT() ); thisTrack.set_quality ( Quality() ); thisTrack.set_bx ( BX() ); thisTrack.set_pt ( Pt() ); thisTrack.set_pt_GMT ( Pt_GMT() ); thisTrack.set_pt_LUT_addr ( Pt_LUT_addr() ); thisTrack.set_eta ( Eta() ); thisTrack.set_eta_GMT ( Eta_GMT() ); thisTrack.set_eta_LUT ( Eta_LUT() ); thisTrack.set_phi_loc_int ( Phi_loc_int() ); thisTrack.set_phi_loc_deg ( Phi_loc_deg() ); thisTrack.set_phi_loc_rad ( Phi_loc_rad() ); thisTrack.set_phi_GMT ( Phi_GMT() ); thisTrack.set_phi_glob_deg ( Phi_glob_deg() ); thisTrack.set_phi_glob_rad ( Phi_glob_rad() ); thisTrack.set_charge ( Charge() ); thisTrack.set_charge_GMT ( Charge_GMT() ); thisTrack.set_charge_valid ( Charge_valid() ); thisTrack.set_dPhi_12 ( DPhi_12() ); thisTrack.set_dPhi_13 ( DPhi_13() ); thisTrack.set_dPhi_14 ( DPhi_14() ); thisTrack.set_dPhi_23 ( DPhi_23() ); thisTrack.set_dPhi_24 ( DPhi_24() ); thisTrack.set_dPhi_34 ( DPhi_34() ); thisTrack.set_dTheta_12 ( DTheta_12() ); thisTrack.set_dTheta_13 ( DTheta_13() ); thisTrack.set_dTheta_14 ( DTheta_14() ); thisTrack.set_dTheta_23 ( DTheta_23() ); thisTrack.set_dTheta_24 ( DTheta_24() ); thisTrack.set_dTheta_34 ( DTheta_34() ); thisTrack.set_clct_1 ( CLCT_1() ); thisTrack.set_clct_2 ( CLCT_2() ); thisTrack.set_clct_3 ( CLCT_3() ); thisTrack.set_clct_4 ( CLCT_4() ); thisTrack.set_fr_1 ( FR_1() ); thisTrack.set_fr_2 ( FR_2() ); thisTrack.set_fr_3 ( FR_3() ); thisTrack.set_fr_4 ( FR_4() ); thisTrack.set_track_num ( Track_num() ); thisTrack.set_has_neighbor ( Has_neighbor() ); thisTrack.set_all_neighbor ( All_neighbor() ); return thisTrack; } // End EMTFTrack2016Extra::CreateEMTFTrack2016 } // End namespace l1t
67.288538
122
0.490954
pasmuss
195a845d8e8e2cc67adee07d0846fa4e01e7a053
169
cpp
C++
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
1
2015-11-05T06:07:12.000Z
2015-11-05T06:07:12.000Z
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
null
null
null
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
null
null
null
#include "test.h" #include "runtime/RegEx.h" using namespace snow; TEST_SUITE(RegEx); TEST_CASE(simple_match) { PENDING(); } TEST_CASE(simple_search) { PENDING(); }
13
26
0.721893
simonask
195bf2eed8dbab9b50896977c600a3caebae6cab
4,047
hpp
C++
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016-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. */ #pragma once #include "sched/entry/entry.hpp" #include "sched/queue/queue.hpp" class write_entry : public sched_entry, public postponed_fields<write_entry, ccl_sched_entry_field_src_mr, ccl_sched_entry_field_dst_mr> { public: static constexpr const char* class_name() noexcept { return "WRITE"; } write_entry() = delete; write_entry(ccl_sched* sched, ccl_buffer src_buf, atl_mr_t* src_mr, size_t cnt, ccl_datatype_internal_t dtype, size_t dst, atl_mr_t* dst_mr, size_t dst_buf_off) : sched_entry(sched), src_buf(src_buf), src_mr(src_mr), cnt(cnt), dtype(dtype), dst(dst), dst_mr(dst_mr), dst_buf_off(dst_buf_off) { } ~write_entry() { if (status == ccl_sched_entry_status_started) { LOG_DEBUG("cancel WRITE entry dst ", dst, ", req ", &req); atl_comm_cancel(sched->bin->get_comm_ctx(), &req); } } void start() override { update_fields(); LOG_DEBUG("WRITE entry dst ", dst, ", req ", &req); CCL_THROW_IF_NOT(src_buf && src_mr && dst_mr, "incorrect values"); if (!cnt) { status = ccl_sched_entry_status_complete; return; } size_t bytes = cnt * ccl_datatype_get_size(dtype); atl_status_t atl_status = atl_comm_write(sched->bin->get_comm_ctx(), src_buf.get_ptr(bytes), bytes, src_mr, (uint64_t)dst_mr->buf + dst_buf_off, dst_mr->r_key, dst, &req); update_status(atl_status); } void update() override { int req_status; atl_status_t atl_status = atl_comm_check(sched->bin->get_comm_ctx(), &req_status, &req); if (unlikely(atl_status != atl_status_success)) { CCL_THROW("WRITE entry failed. atl_status: ", atl_status_to_str(atl_status)); } if (req_status) { LOG_DEBUG("WRITE entry done, dst ", dst); status = ccl_sched_entry_status_complete; } } const char* name() const override { return class_name(); } atl_mr_t*& get_field_ref(field_id_t<ccl_sched_entry_field_src_mr> id) { return src_mr; } atl_mr_t*& get_field_ref(field_id_t<ccl_sched_entry_field_dst_mr> id) { return dst_mr; } protected: void dump_detail(std::stringstream& str) const override { ccl_logger::format(str, "dt ", ccl_datatype_get_name(dtype), ", cnt ", cnt, ", src_buf ", src_buf, ", src_mr ", src_mr, ", dst ", dst, ", dst_mr ", dst_mr, ", dst_off ", dst_buf_off, ", comm_id ", sched->coll_param.comm->id(), ", req %p", &req, "\n"); } private: ccl_buffer src_buf; atl_mr_t* src_mr; size_t cnt; ccl_datatype_internal_t dtype; size_t dst; atl_mr_t* dst_mr; size_t dst_buf_off; atl_req_t req{}; };
29.540146
100
0.547072
mshiryaev
19603e37219f2defe3844bb292c7f5ef815118a0
10,569
cpp
C++
src/domain.cpp
egdaub/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
12
2017-10-05T22:04:40.000Z
2020-08-31T08:32:17.000Z
src/domain.cpp
jhsa26/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
3
2020-05-06T16:48:32.000Z
2020-09-18T11:41:41.000Z
src/domain.cpp
jhsa26/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
12
2017-03-24T19:15:27.000Z
2020-08-31T08:32:18.000Z
#include <iostream> #include <fstream> #include <cassert> #include <string> #include "block.hpp" #include "cartesian.hpp" #include "domain.hpp" #include "fd.hpp" #include "fields.hpp" #include "friction.hpp" #include "interface.hpp" #include "rk.hpp" #include "slipweak.hpp" #include "stz.hpp" #include <mpi.h> using namespace std; domain::domain(const char* filename) { // constructor, no default as need to allocate memory int sbporder; string* iftype; int** nx_block; int** xm_block; nx_block = new int* [3]; xm_block = new int* [3]; // open input file, find appropriate place and read in parameters string line; ifstream paramfile(filename, ifstream::in); if (paramfile.is_open()) { // scan to start of domain list while (getline(paramfile,line)) { if (line == "[fdfault.domain]") { break; } } if (paramfile.eof()) { cerr << "Error reading domain from input file\n"; MPI_Abort(MPI_COMM_WORLD,-1); } else { // read domain variables paramfile >> ndim; paramfile >> mode; for (int i=0; i<3; i++) { paramfile >> nx[i]; } for (int i=0; i<3; i++) { paramfile >> nblocks[i]; } for (int i=0; i<3; i++) { nx_block[i] = new int [nblocks[i]]; xm_block[i] = new int [nblocks[i]]; } for (int i=0; i<3; i++) { for (int j=0; j<nblocks[i]; j++) { paramfile >> nx_block[i][j]; } } paramfile >> nifaces; iftype = new string [nifaces]; for (int i=0; i<nifaces; i++) { paramfile >> iftype[i]; } paramfile >> sbporder; paramfile >> material; } } else { cerr << "Error opening input file in domain.cpp\n"; MPI_Abort(MPI_COMM_WORLD,-1); } paramfile.close(); // check validity of input parameters assert(ndim == 2 || ndim == 3); assert(mode == 2 || mode == 3); assert(material == "elastic" || material == "plastic"); if (ndim == 2) { assert(nx[2] == 1); } for (int i=0; i<3; i++) { assert(nx[i] > 0); assert(nblocks[i] > 0); int sum = 0; for (int j=0; j<nblocks[i]; j++) { sum += nx_block[i][j]; } assert(sum == nx[i]); } // set other domain parameters if (material == "elastic") { is_plastic = false; } else { is_plastic = true; } nblockstot = nblocks[0]*nblocks[1]*nblocks[2]; for (int i=0; i<3; i++) { for (int j=0; j<nblocks[i]; j++) { if (j==0) { xm_block[i][j] = 0; } else { xm_block[i][j] = xm_block[i][j-1]+nx_block[i][j-1]; } } } // allocate memory for fd coefficients fd = new fd_type(sbporder); // set up cartesian type to hold domain decomposition information cart = new cartesian(filename, ndim, nx, nblocks, nx_block, xm_block, sbporder); f = new fields(filename, ndim, mode, material, *cart); // allocate memory and create blocks allocate_blocks(filename, nx_block, xm_block); // exchange neighbors to fill in ghost cells f->exchange_neighbors(); f->exchange_grid(); // allocate memory and create interfaces allocate_interfaces(filename, iftype); // set interface variables to match boundary conditions for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(0., 0., *f, true); } for (int i=0; i<3; i++) { delete[] nx_block[i]; delete[] xm_block[i]; } delete[] nx_block; delete[] xm_block; } domain::~domain() { // destructor, no default as need to deallocate memory deallocate_blocks(); deallocate_interfaces(); delete fd; delete cart; delete f; } int domain::get_ndim() const { // returns number of spatial dimensions return ndim; } int domain::get_mode() const { // returns mode return mode; } int domain::get_nblocks(const int index) const { // returns number of blocks assert(index >= 0 && index < 3); return nblocks[index]; } int domain::get_nblockstot() const { return nblockstot; } int domain::get_nifaces() const { return nifaces; } double domain::get_min_dx() const { // get min grid spacing divided by shear wave speed over all blocks double dxmin = 0., dxmintest, dxmin_all; for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { dxmintest = blocks[i][j][k]->get_min_dx(*f); if (dxmintest > 1.e-14) { // block has data if (dxmin <= 1.e-14 || dxmintest < dxmin) { dxmin = dxmintest; } } } } } if (dxmin <= 1.e-14) { cerr << "Error in domain.cpp get_min_dx -- a process does not have any grid spacing values\n"; MPI_Abort(MPI_COMM_WORLD,1); } MPI_Allreduce(&dxmin, &dxmin_all, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD); return dxmin_all; } void domain::do_rk_stage(const double dt, const int stage, const double t, rk_type& rk) { // advances domain fields for one RK stage of one time step // scale df by RK coefficient f->scale_df(rk.get_A(stage)); for (int i=0; i<nifaces; i++) { interfaces[i]->scale_df(rk.get_A(stage)); } // calculate df for blocks for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { blocks[i][j][k]->calc_df(dt,*f,*fd); // blocks[i][j][k]->set_mms(dt, t+rk.get_C(stage)*dt, *f); blocks[i][j][k]->set_boundaries(dt,*f); } } } // apply interface conditions for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(dt,t+rk.get_C(stage)*dt,*f,false); } // calculate df for interfaces for (int i=0; i<nifaces; i++) { interfaces[i]->calc_df(dt); } // update interfaces for (int i=0; i<nifaces; i++) { interfaces[i]->update(rk.get_B(stage)); } // update fields f->update(rk.get_B(stage)); // if last stage and response is plastic, solve plasticity equations if (stage+1 == rk.get_nstages() && is_plastic) { // set absolute stress f->set_stress(); for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { blocks[i][j][k]->calc_plastic(dt,*f); } } } // subtract stress f->remove_stress(); // apply interface conditions to correctly set slip rates (needed for correct output) for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(dt,t+rk.get_C(stage)*dt,*f,true); } } // exchange neighbors f->exchange_neighbors(); } void domain::free_exchange() { // frees MPI datatypes for ghost cell exchange f->free_exchange(); } void domain::set_stress() { // sets absolute stress f->set_stress(); } void domain::remove_stress() { // subtracts initial stress f->remove_stress(); } void domain::allocate_blocks(const char* filename, int** nx_block, int** xm_block) { // allocate memory for blocks and initialize int nxtmp[3]; int xmtmp[3]; int coords[3]; blocks = new block*** [nblocks[0]]; for (int i=0; i<nblocks[0]; i++) { blocks[i] = new block** [nblocks[1]]; } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { blocks[i][j] = new block* [nblocks[2]]; } } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { nxtmp[0] = nx_block[0][i]; nxtmp[1] = nx_block[1][j]; nxtmp[2] = nx_block[2][k]; xmtmp[0] = xm_block[0][i]; xmtmp[1] = xm_block[1][j]; xmtmp[2] = xm_block[2][k]; coords[0] = i; coords[1] = j; coords[2] = k; blocks[i][j][k] = new block(filename, ndim, mode, material, coords, nxtmp, xmtmp, *cart, *f, *fd); } } } } void domain::allocate_interfaces(const char* filename, string* iftype) { // allocate memory for interfaces for (int i=0; i<nifaces; i++) { assert(iftype[i] == "locked" || iftype[i] == "frictionless" || iftype[i] == "slipweak" || iftype[i] == "stz"); } interfaces = new interface* [nifaces]; for (int i=0; i<nifaces; i++) { if (iftype[i] == "locked") { interfaces[i] = new interface(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "frictionless") { interfaces[i] = new friction(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "slipweak") { interfaces[i] = new slipweak(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "stz") { interfaces[i] = new stz(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } } } void domain::deallocate_blocks() { // deallocate memory for blocks for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { delete blocks[i][j][k]; } } } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { delete[] blocks[i][j]; } } for (int i=0; i<nblocks[0]; i++) { delete[] blocks[i]; } delete[] blocks; } void domain::deallocate_interfaces() { // deallocate memory for interfaces for (int i=0; i<nifaces; i++) { delete interfaces[i]; } delete[] interfaces; }
25.40625
118
0.504589
egdaub
19615eb2b58a87deb7d55a47659c83c59f8acfb8
937
hh
C++
ImageSampleMap/imagesamplemap.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
ImageSampleMap/imagesamplemap.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
ImageSampleMap/imagesamplemap.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
#pragma once #include <functional> #include <Eigen/Core> typedef unsigned short ushort; typedef unsigned char uchar; namespace bold { /** Produces a map used in sub-sampling image data. * * A granularity function allows processing fewer than all pixels * in the image. * * Granularity is calculated based on y-value, and is specified in * both x and y dimensions. */ class ImageSampleMap { public: ImageSampleMap(std::function<Eigen::Matrix<uchar,2,1>(ushort)> granularityFunction, ushort width, ushort height); unsigned getPixelCount() const { return d_pixelCount; } ushort getSampleRowCount() const { return static_cast<ushort>(d_granularities.size()); } std::vector<Eigen::Matrix<uchar,2,1>>::const_iterator begin() const { return d_granularities.begin(); } private: std::vector<Eigen::Matrix<uchar,2,1>> d_granularities; unsigned d_pixelCount; ushort d_width; }; }
26.027778
117
0.712914
drewnoakes
19637585ea01d69d75a6ce0307360b900e55b8fd
1,431
cpp
C++
aws-cpp-sdk-lakeformation/source/model/BatchPermissionsFailureEntry.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-lakeformation/source/model/BatchPermissionsFailureEntry.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-lakeformation/source/model/BatchPermissionsFailureEntry.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
๏ปฟ/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lakeformation/model/BatchPermissionsFailureEntry.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace LakeFormation { namespace Model { BatchPermissionsFailureEntry::BatchPermissionsFailureEntry() : m_requestEntryHasBeenSet(false), m_errorHasBeenSet(false) { } BatchPermissionsFailureEntry::BatchPermissionsFailureEntry(JsonView jsonValue) : m_requestEntryHasBeenSet(false), m_errorHasBeenSet(false) { *this = jsonValue; } BatchPermissionsFailureEntry& BatchPermissionsFailureEntry::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("RequestEntry")) { m_requestEntry = jsonValue.GetObject("RequestEntry"); m_requestEntryHasBeenSet = true; } if(jsonValue.ValueExists("Error")) { m_error = jsonValue.GetObject("Error"); m_errorHasBeenSet = true; } return *this; } JsonValue BatchPermissionsFailureEntry::Jsonize() const { JsonValue payload; if(m_requestEntryHasBeenSet) { payload.WithObject("RequestEntry", m_requestEntry.Jsonize()); } if(m_errorHasBeenSet) { payload.WithObject("Error", m_error.Jsonize()); } return payload; } } // namespace Model } // namespace LakeFormation } // namespace Aws
19.08
90
0.742837
Neusoft-Technology-Solutions
1963f5b09d876859feb4f7a7147f97955500b5fb
2,013
hpp
C++
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
10
2016-10-26T13:36:18.000Z
2020-03-16T02:19:40.000Z
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
null
null
null
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
5
2016-10-07T12:28:59.000Z
2022-03-22T14:16:53.000Z
#ifndef qd_simple_locked_queue_hpp #define qd_simple_locked_queue_hpp qd_simple_locked_queue_hpp #include<array> #include<cassert> #include<mutex> #include<queue> class simple_locked_queue { std::mutex lock; std::queue<std::array<char, 128>> queue; typedef std::lock_guard<std::mutex> scoped_guard; typedef void(*ftype)(char*); /* some constants */ static const bool CLOSED = false; static const bool SUCCESS = true; void forwardall(char*, long i) { assert(i <= 120); if(i > 120) throw "up"; }; template<typename P, typename... Ts> void forwardall(char* buffer, long offset, P&& p, Ts&&... ts) { assert(offset <= 120); auto ptr = reinterpret_cast<P*>(&buffer[offset]); new (ptr) P(std::forward<P>(p)); forwardall(buffer, offset+sizeof(p), std::forward<Ts>(ts)...); } public: void open() { /* TODO this function should not even be here */ /* no-op as this is an "infinite" queue that always accepts more data */ } /** * @brief enqueues an entry * @tparam P return type of associated function * @param op wrapper function for associated function * @return SUCCESS on successful storing in queue, CLOSED otherwise */ template<typename... Ps> bool enqueue(ftype op, Ps*... ps) { std::array<char, 128> val; scoped_guard l(lock); queue.push(val); forwardall(queue.back().data(), 0, std::move(op), std::move(*ps)...); return SUCCESS; } /** execute all stored operations */ void flush() { scoped_guard l(lock); while(!queue.empty()) { auto operation = queue.front(); char* ptr = operation.data(); ftype* fun = reinterpret_cast<ftype*>(ptr); ptr += sizeof(ftype*); (*fun)(ptr); queue.pop(); } } /** execute one stored operation */ void flush_one() { scoped_guard l(lock); if(!queue.empty()) { char* ptr = queue.front().data(); ftype* fun = reinterpret_cast<ftype*>(ptr); ptr += sizeof(ftype); (*fun)(ptr); queue.pop(); } } }; #endif /* qd_simple_locked_queue_hpp */
26.142857
75
0.646299
lundgren87
1967025b038338dffdebb29e92ee55902368b726
6,878
cpp
C++
Tools/NodeParticleSystem2Port/Port.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
32
2016-05-22T23:09:19.000Z
2022-03-13T03:32:27.000Z
Tools/NodeParticleSystem2Port/Port.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
2
2016-05-30T19:45:58.000Z
2018-01-24T22:29:51.000Z
Tools/NodeParticleSystem2Port/Port.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
17
2016-05-27T11:01:42.000Z
2022-03-13T03:32:30.000Z
/* Port.cpp (c)2005 Palestar, Richard Lyle */ #define NODEPARTICLESYSTEM2PORT_DLL #include "stdafx.h" #include "Port.h" #include "Math/Helpers.h" #include "Tools/ScenePort/ChildFrame.h" #include "Tools/ResourcerDoc/Port.h" //---------------------------------------------------------------------------- IMPLEMENT_FACTORY( NodeParticleSystem2Port, NodePort ); REGISTER_FACTORY_KEY( NodeParticleSystem2Port, 4017674422569680758 ); BEGIN_PROPERTY_LIST( NodeParticleSystem2Port, NodePort ); ADD_PROPERTY( m_Seed ); ADD_PROPERTY( m_ParticleCount ); ADD_ENUM_PROPERTY( m_OriginType ); ADD_ENUM_OPTION( m_OriginType, BOX ); ADD_ENUM_OPTION( m_OriginType, SPHERE ); ADD_ENUM_OPTION( m_OriginType, LINE ); ADD_ENUM_OPTION( m_OriginType, CIRCLE ); ADD_PROPERTY( m_MinOrigin ); ADD_PROPERTY( m_MaxOrigin ); ADD_PROPERTY( m_MinVelocity ); ADD_PROPERTY( m_MaxVelocity ); ADD_PROPERTY( m_MinAcceleration ); ADD_PROPERTY( m_MaxAcceleration ); ADD_PROPERTY( m_MinLife ); ADD_PROPERTY( m_MaxLife ); ADD_PROPERTY( m_ReverseTime ); ADD_PROPERTY( m_bLocalSpace ); ADD_PROPERTY( m_Life ); ADD_PORT_PROPERTY( m_MaterialPort, MaterialPort ); ADD_PROPERTY( m_Visible ); ADD_PROPERTY( m_VisibleV ); ADD_PROPERTY( m_VisibleA ); ADD_PROPERTY( m_Scale ); ADD_PROPERTY( m_ScaleV ); ADD_PROPERTY( m_ScaleA ); ADD_PROPERTY( m_ScaleVar ); ADD_PROPERTY( m_Alpha ); ADD_PROPERTY( m_AlphaV ); ADD_PROPERTY( m_AlphaA ); END_PROPERTY_LIST(); NodeParticleSystem2Port::NodeParticleSystem2Port() : NodePort() { m_Class = m_Type = CLASS_KEY(NodeParticleSystem2); m_Seed = rand(); m_ParticleCount = 100; m_OriginType = BOX; m_Life = 10.0f; m_Visible = 1.0f; m_VisibleV = m_VisibleA = 0.0f; m_Scale = 1.0f; m_ScaleV = m_ScaleA = 0.0f; m_ScaleVar = 0.0f; m_Alpha = 1.0f; m_AlphaV = m_AlphaA = 0.0f; m_bLocalSpace = false; m_MinOrigin = m_MinVelocity = m_MinAcceleration = Vector3(-1,-1,-1); m_MaxOrigin = m_MaxVelocity = m_MaxAcceleration = Vector3(1,1,1); m_MinLife = m_MaxLife = 1.0f; m_ReverseTime = false; } //------------------------------------------------------------------------------- const int VERSION_082399 = 82399; const int VERSION_020200 = 020200; const int VERSION_102201 = 102201; bool NodeParticleSystem2Port::read( const InStream & input ) { if (! NodePort::read( input ) ) { int version; input >> version; switch( version ) { case VERSION_102201: input >> m_Seed; input >> m_ParticleCount; input >> m_OriginType; input >> m_MinOrigin; input >> m_MaxOrigin; input >> m_MinVelocity; input >> m_MaxVelocity; input >> m_MinAcceleration; input >> m_MaxAcceleration; input >> m_MinLife; input >> m_MaxLife; input >> m_ReverseTime; input >> m_Life; input >> m_MaterialPort; input >> m_Visible; input >> m_VisibleV; input >> m_VisibleA; input >> m_Scale; input >> m_ScaleV; input >> m_ScaleA; input >> m_ScaleV; input >> m_ScaleVar; input >> m_Alpha; input >> m_AlphaV; input >> m_AlphaA; break; case VERSION_020200: input >> m_ParticleCount; input >> m_OriginType; input >> m_MinOrigin; input >> m_MaxOrigin; input >> m_MinVelocity; input >> m_MaxVelocity; input >> m_MinAcceleration; input >> m_MaxAcceleration; input >> m_MinLife; input >> m_MaxLife; input >> m_ReverseTime; input >> m_Life; input >> m_MaterialPort; input >> m_Visible; input >> m_VisibleV; input >> m_VisibleA; input >> m_Scale; input >> m_ScaleV; input >> m_ScaleA; input >> m_ScaleV; input >> m_ScaleVar; input >> m_Alpha; input >> m_AlphaV; input >> m_AlphaA; m_Seed = rand(); break; case VERSION_082399: input >> m_ParticleCount; input >> m_MinOrigin; input >> m_MaxOrigin; input >> m_MinVelocity; input >> m_MaxVelocity; input >> m_MinAcceleration; input >> m_MaxAcceleration; input >> m_MinLife; input >> m_MaxLife; input >> m_Life; input >> m_MaterialPort; input >> m_Visible; input >> m_VisibleV; input >> m_VisibleA; input >> m_Scale; input >> m_ScaleV; input >> m_ScaleA; input >> m_ScaleV; input >> m_Alpha; input >> m_AlphaV; input >> m_AlphaA; m_Seed = rand(); m_OriginType = BOX; m_ScaleVar = 0.0f; m_ReverseTime = false; break; } } return true; } //------------------------------------------------------------------------------- void NodeParticleSystem2Port::dependencies( DependentArray & dep ) { dep.push( m_MaterialPort ); } CFrameWnd * NodeParticleSystem2Port::createView() { return NodePort::createView(); } BaseNode * NodeParticleSystem2Port::createNode() { return NodePort::createNode(); } void NodeParticleSystem2Port::initializeNode( BaseNode * pNode ) { NodePort::initializeNode( pNode ); NodeParticleSystem2 * pSystem = dynamic_cast<NodeParticleSystem2 *>( pNode ); if ( pSystem != NULL ) { srand( m_Seed ); // create all the particles for(int i=0;i<m_ParticleCount;i++) { Particle newParticle; switch( m_OriginType ) { case BOX: newParticle.origin = RandomVector( m_MinOrigin, m_MaxOrigin ); break; case SPHERE: { float minRadius = m_MinOrigin.magnitude(); float maxRadius = m_MaxOrigin.magnitude(); float radius = RandomFloat( minRadius, maxRadius ); Vector3 direction( RandomFloat( -1.0f, 1.0f ), RandomFloat( -1.0f, 1.0f ), RandomFloat( -1.0f, 1.0f) ); direction.normalize(); newParticle.origin = direction * radius; } break; case LINE: { Vector3 delta( m_MinOrigin - m_MaxOrigin ); float distance = delta.magnitude(); float d = RandomFloat( 0.0f, distance ); newParticle.origin = m_MaxOrigin + (delta * d); } break; case CIRCLE: { float minRadius = m_MinOrigin.magnitude(); float maxRadius = m_MaxOrigin.magnitude(); float radius = RandomFloat( minRadius, maxRadius ); Vector3 direction( RandomFloat( -1.0f, 1.0f ), 0, RandomFloat( -1.0f, 1.0f) ); direction.normalize(); newParticle.origin = direction * radius; } break; } newParticle.velocity = RandomVector( m_MinVelocity, m_MaxVelocity ); newParticle.acceleration = RandomVector( m_MinAcceleration, m_MaxAcceleration ); newParticle.life = RandomFloat( m_MinLife, m_MaxLife ); newParticle.scale = RandomFloat( -m_ScaleVar, m_ScaleVar ); pSystem->addParticle( newParticle ); } pSystem->setLife( m_Life ); pSystem->setMaterial( WidgetCast<Material>( Port::portResource( m_MaterialPort ) ) ); pSystem->setVisible( m_Visible, m_VisibleV, m_VisibleA ); pSystem->setScale( m_Scale, m_ScaleV, m_ScaleA ); pSystem->setAlpha( m_Alpha, m_AlphaV, m_AlphaA ); pSystem->setReverseTime( m_ReverseTime ); pSystem->setLocalSpace( m_bLocalSpace ); } } //------------------------------------------------------------------------------- // EOF
25.664179
108
0.658476
CarysT
19675ab5730b5e672335d8c569df4766e88cfe3f
3,883
cc
C++
src/ssl_info_action.cc
jeff-cn/doogie
1b4ed74adecbae773b51e674d298e3d5b09e4244
[ "MIT" ]
291
2017-07-19T22:32:25.000Z
2022-02-16T03:03:21.000Z
charts/doogie-0.7.8/src/ssl_info_action.cc
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
81
2017-09-06T15:46:27.000Z
2020-11-30T14:12:11.000Z
charts/doogie-0.7.8/src/ssl_info_action.cc
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
29
2017-09-18T19:14:50.000Z
2022-01-24T06:03:17.000Z
#include "ssl_info_action.h" namespace doogie { SslInfoAction::SslInfoAction(const Cef& cef, BrowserWidget* browser_widg) : QWidgetAction(browser_widg), cef_(cef), browser_widg_(browser_widg) { } QWidget* SslInfoAction::createWidget(QWidget* parent) { auto errored_ssl_info = browser_widg_->ErroredSslInfo(); auto errored_ssl_callback = browser_widg_->ErroredSslCallback(); auto ssl_status = browser_widg_->SslStatus(); auto layout = new QVBoxLayout; // SSL notes cef_cert_status_t status = CERT_STATUS_NONE; if (errored_ssl_info) { status = errored_ssl_info->GetCertStatus(); } else if (ssl_status) { status = ssl_status->GetCertStatus(); } auto status_strings = CertStatuses(status); if (!status_strings.isEmpty()) { auto status_layout = new QHBoxLayout; status_layout->addWidget(new QLabel("SSL Notes:"), 0, Qt::AlignTop); status_layout->addWidget(new QLabel(status_strings.join("\n")), 1); layout->addLayout(status_layout); } // Version and insecure content if (ssl_status) { auto version_layout = new QHBoxLayout; version_layout->addWidget(new QLabel("SSL Version:")); version_layout->addWidget( new QLabel(CertSslVersion(ssl_status->GetSSLVersion())), 1); layout->addLayout(version_layout); if (ssl_status->GetContentStatus() != SSL_CONTENT_NORMAL_CONTENT) { layout->addWidget(new QLabel("Displayed or ran insecure content")); } } // TODO(cretz): allow bypass // The button to view OS-level dialog auto details_button = new QPushButton("View Certificate Details"); connect(details_button, &QPushButton::clicked, [=](bool) { bool ok = false; if (errored_ssl_info) { ok = cef_.ShowCertDialog(errored_ssl_info->GetX509Certificate()); } else if (ssl_status) { ok = cef_.ShowCertDialog(ssl_status->GetX509Certificate()); } if (!ok) qWarning() << "Failed to show native cert dialog"; }); layout->addWidget(details_button, 0, Qt::AlignCenter); layout->addStretch(1); auto widg = new QWidget(parent); widg->setLayout(layout); return widg; } QStringList SslInfoAction::CertStatuses(cef_cert_status_t status) { const QHash<cef_cert_status_t, QString> strings = { { CERT_STATUS_COMMON_NAME_INVALID, "Common Name Invalid" }, { CERT_STATUS_DATE_INVALID, "Date Invalid" }, { CERT_STATUS_AUTHORITY_INVALID, "Authority Invalid" }, { CERT_STATUS_NO_REVOCATION_MECHANISM, "No Revocation Mechanism" }, { CERT_STATUS_UNABLE_TO_CHECK_REVOCATION, "Unable to Check Revocation" }, { CERT_STATUS_REVOKED, "Revoked" }, { CERT_STATUS_INVALID, "Invalid" }, { CERT_STATUS_WEAK_SIGNATURE_ALGORITHM, "Weak Signature Algorithm" }, { CERT_STATUS_NON_UNIQUE_NAME, "Non-Unique Name" }, { CERT_STATUS_WEAK_KEY, "Weak Key" }, { CERT_STATUS_PINNED_KEY_MISSING, "Pinned Key Missing" }, { CERT_STATUS_NAME_CONSTRAINT_VIOLATION, "Name Constraint Violation" }, { CERT_STATUS_VALIDITY_TOO_LONG, "Validity Too Long" }, { CERT_STATUS_IS_EV, "Extended Validation Certificate" }, { CERT_STATUS_REV_CHECKING_ENABLED, "Revocation Checking Enabled" }, { CERT_STATUS_SHA1_SIGNATURE_PRESENT, "SHA1 Signature Present" }, { CERT_STATUS_CT_COMPLIANCE_FAILED, "CT Compliance Failed" } }; QStringList ret; for (auto key : strings.keys()) { if (status & key) ret << strings[key]; } return ret; } QString SslInfoAction::CertSslVersion(cef_ssl_version_t ssl_version) { switch (ssl_version) { case SSL_CONNECTION_VERSION_SSL2: return "SSL 2.0"; case SSL_CONNECTION_VERSION_SSL3: return "SSL 3.0"; case SSL_CONNECTION_VERSION_TLS1: return "TLS 1.0"; case SSL_CONNECTION_VERSION_TLS1_1: return "TLS 1.1"; case SSL_CONNECTION_VERSION_TLS1_2: return "TLS 1.2"; case SSL_CONNECTION_VERSION_QUIC: return "QUIC"; default: return "(unknown)"; } } } // namespace doogie
37.699029
77
0.722637
jeff-cn
1967fc2cfe2e1f1dc101872396eb1497aa847e97
501
hpp
C++
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
#ifndef COMPARETORFACTORY_HPP #define COMPARETORFACTORY_HPP #include "comparetor.hpp" #include "QPointer" /** * @brief The deckType enum๏ผŒๅฎšไน‰ไบ†ๅ„็ง็‰Œๅž‹็š„ๆžšไธพ */ enum deckType{undefined,high_card,one_pair,two_pairs,three_of_a_kind,straight,flush,full_house,four_of_a_kind,straight_flush,royal_flush}; /** * @brief The comparetorFactory class๏ผŒๆฏ”่พƒๅ™จ็š„ๅทฅๅŽ‚็ฑป๏ผŒ่ฟ”ๅ›ž้œ€่ฆ็š„ๆฏ”่พƒๅ™จ */ class comparetorFactory { public: static QSharedPointer<comparetor> getComparetor(const deckType type); }; #endif // COMPARETORFACTORY_HPP
23.857143
138
0.802395
cloudicen
196de25f738ff244d1313b7e80e870f003bcbaa7
2,804
cpp
C++
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Construct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UWorkerTooltipStatsWidget_C::Construct() { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Construct"); UWorkerTooltipStatsWidget_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Tick // (BlueprintCosmetic, Event, Public, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // float* InDeltaTime (Parm, ZeroConstructor, IsPlainOldData) void UWorkerTooltipStatsWidget_C::Tick(struct FGeometry* MyGeometry, float* InDeltaTime) { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Tick"); UWorkerTooltipStatsWidget_C_Tick_Params params; params.MyGeometry = MyGeometry; params.InDeltaTime = InDeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.On Worker Preview State Changed // (BlueprintCallable, BlueprintEvent) void UWorkerTooltipStatsWidget_C::On_Worker_Preview_State_Changed() { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.On Worker Preview State Changed"); UWorkerTooltipStatsWidget_C_On_Worker_Preview_State_Changed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.ExecuteUbergraph_WorkerTooltipStatsWidget // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UWorkerTooltipStatsWidget_C::ExecuteUbergraph_WorkerTooltipStatsWidget(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.ExecuteUbergraph_WorkerTooltipStatsWidget"); UWorkerTooltipStatsWidget_C_ExecuteUbergraph_WorkerTooltipStatsWidget_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
29.208333
155
0.731455
Milxnor
196edfd0541a5114a81b67144dfa7bcf5ddb8c42
1,220
cpp
C++
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
136
2015-07-15T12:49:36.000Z
2022-03-24T12:30:25.000Z
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
59
2015-12-28T21:40:37.000Z
2022-03-31T13:11:50.000Z
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
33
2015-12-04T08:00:07.000Z
2022-01-28T23:39:25.000Z
#include <boost/python.hpp> #include <boost/cstdint.hpp> #include <Magick++/Drawable.h> #include <Magick++.h> using namespace boost::python; namespace { struct Magick_DrawableMatte_Wrapper: Magick::DrawableMatte { Magick_DrawableMatte_Wrapper(PyObject* py_self_, double p0, double p1, Magick::PaintMethod p2): Magick::DrawableMatte(p0, p1, p2), py_self(py_self_) {} PyObject* py_self; }; } void __DrawableMatte() { class_< Magick::DrawableMatte, bases<Magick::DrawableBase>, boost::noncopyable, Magick_DrawableMatte_Wrapper >("DrawableMatte", init< double, double, Magick::PaintMethod >()) .def("x", (void (Magick::DrawableMatte::*)(double) )&Magick::DrawableMatte::x) .def("x", (double (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::x) .def("y", (void (Magick::DrawableMatte::*)(double) )&Magick::DrawableMatte::y) .def("y", (double (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::y) .def("paintMethod", (void (Magick::DrawableMatte::*)(Magick::PaintMethod) )&Magick::DrawableMatte::paintMethod) .def("paintMethod", (Magick::PaintMethod (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::paintMethod) ; }
34.857143
178
0.688525
veryhappythings
196f7e48086742ca2f3d80e64272b0f92a8f4057
4,298
cpp
C++
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
null
null
null
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
2
2021-04-19T11:42:07.000Z
2021-04-21T10:26:04.000Z
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 /** * Copyright (C) 2021 Jihoon Lee <jhoon.it.lee@samsung.com> * * @file unittest_interpreter.cpp * @date 02 April 2021 * @brief interpreter test * @see https://github.com/nnstreamer/nntrainer * @author Jihoon Lee <jhoon.it.lee@samsung.com> * @bug No known bugs except for NYI items */ #include <functional> #include <gtest/gtest.h> #include <memory> #include <app_context.h> #include <ini_interpreter.h> #include <interpreter.h> #include <layer.h> #include <nntrainer_test_util.h> using LayerReprentation = std::pair<std::string, std::vector<std::string>>; auto &ac = nntrainer::AppContext::Global(); static std::shared_ptr<nntrainer::GraphRepresentation> makeGraph(const std::vector<LayerReprentation> &layer_reps) { auto graph = std::make_shared<nntrainer::GraphRepresentation>(); for (const auto &layer_representation : layer_reps) { std::shared_ptr<ml::train::Layer> layer = ac.createObject<ml::train::Layer>( layer_representation.first, layer_representation.second); graph->addLayer(std::static_pointer_cast<nntrainer::Layer>(layer)); } return graph; } const std::string pathResolver(const std::string &path) { return getResPath(path, {"test", "test_models", "models"}); } auto ini_interpreter = std::make_shared<nntrainer::IniGraphInterpreter>(ac, pathResolver); /** * @brief nntrainer Interpreter Test setup * * @note Proposing an evolutional path of current test * 1. A reference graph vs given paramter * 2. A reference graph vs list of models * 3. A reference graph vs (pick two models) a -> b -> a graph, b -> a -> b * graph */ class nntrainerInterpreterTest : public ::testing::TestWithParam< std::tuple<std::shared_ptr<nntrainer::GraphRepresentation>, const char *, std::shared_ptr<nntrainer::GraphInterpreter>>> { protected: virtual void SetUp() { auto params = GetParam(); reference = std::get<0>(params); file_path = pathResolver(std::get<1>(params)); interpreter = std::move(std::get<2>(params)); } std::shared_ptr<nntrainer::GraphRepresentation> reference; std::shared_ptr<nntrainer::GraphInterpreter> interpreter; std::string file_path; }; /** * @brief Check two compiled graph is equal * @note later this will be more complicated (getting N graph and compare each * other) * */ TEST_P(nntrainerInterpreterTest, graphEqual) { std::cerr << "testing " << file_path << '\n'; int status = reference->compile(nntrainer::LossType::LOSS_NONE); EXPECT_EQ(status, ML_ERROR_NONE); auto g = interpreter->deserialize(file_path); /// @todo: change this to something like graph::finalize status = g->compile(nntrainer::LossType::LOSS_NONE); EXPECT_EQ(status, ML_ERROR_NONE); /// @todo: make a graph equal /// 1. having same number of nodes /// 2. layer name is identical (this is too strict though) /// 3. attributes of layer is identical // EXPECT_EQ(*graph, *interpreter->deserialize(file_path)); auto layers = g->getLayers(); auto ref_layers = reference->getLayers(); EXPECT_EQ(layers.size(), ref_layers.size()); if (layers.size() == ref_layers.size()) { for (auto &layer : layers) { std::shared_ptr<nntrainer::Layer> ref_layer; EXPECT_NO_THROW(ref_layer = reference->getLayer(layer->getName())); /// @todo: layer->getProperties() and do check on each properties } } } auto fc0 = LayerReprentation("fully_connected", {"name=fc0", "unit=1", "input_shape=1:1:100"}); auto flatten = LayerReprentation("flatten", {"name=flat"}); /** * @brief make ini test case from given parameter */ static std::tuple<std::shared_ptr<nntrainer::GraphRepresentation>, const char *, std::shared_ptr<nntrainer::GraphInterpreter>> mkTc(std::shared_ptr<nntrainer::GraphRepresentation> graph, const char *file, std::shared_ptr<nntrainer::GraphInterpreter> interpreter) { return std::make_tuple(graph, file, interpreter); } // clang-format off INSTANTIATE_TEST_CASE_P(nntrainerAutoInterpreterTest, nntrainerInterpreterTest, ::testing::Values( mkTc(makeGraph({fc0, flatten}), "simple_fc.ini", ini_interpreter), mkTc(makeGraph({fc0, flatten}), "simple_fc_backbone.ini", ini_interpreter) )); // clang-format on
31.837037
80
0.701489
gichan-jang
197055abf1559514dd02c0f191b0e2957efbd748
2,495
cpp
C++
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
// // Renderer.cpp // // // Created by Narendra Umate on 9/7/13. // // #include "Renderer.h" Renderer::Renderer(const int& width, const int& height) : m_width(width) , m_height(height) , m_clearColor(Color4f(0.5f, 0.5f, 0.5f, 1.0f)) , m_clearDepth(1.0f) , m_clearStencil(1) { } Renderer::~Renderer() { m_width = 0; m_height = 0; } void Renderer::setNdcMatrix(const Mat4& matrix) { m_ndcMatrix = matrix; } Mat4 Renderer::getNdcMatrix() { return m_ndcMatrix; } void Renderer::setProjectionRange(const ProjectionRange& range) { m_projectionRange = range; } ProjectionRange Renderer::getProjectionRange() { return m_projectionRange; } void Renderer::setWidth(const int& width) { m_width = width; } int Renderer::getWidth() { return m_width; } void Renderer::setHeight(const int& height) { m_height = height; } int Renderer::getHeight() { return m_height; } void Renderer::draw(Bvh* bvh, VisualEffect* visualEffect, VisualMaterial* visualMaterial, const Mat4& worldMatrix, const Mat4& viewMatrix, const Mat4& viewProjectionMatrix, const Vec3& lightCoefficients, const Vec3& lightColor, const Vec3& lightPosition, const Vec3& eyePosition) { // Draw your self. draw(bvh->getBoundingBox(), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); // Draw your children. int childCount = bvh->getChildCount(); if (childCount) { for (int childIndex = 0; childIndex < childCount; ++childIndex) { draw(bvh->getChild(childIndex), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); } } } void Renderer::draw(Octree* octree, VisualEffect* visualEffect, VisualMaterial* visualMaterial, const Mat4& worldMatrix, const Mat4& viewMatrix, const Mat4& viewProjectionMatrix, const Vec3& lightCoefficients, const Vec3& lightColor, const Vec3& lightPosition, const Vec3& eyePosition) { // Draw your self. draw(octree->getBoundingBox(), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); // Draw your children. int childCount = octree->getChildCount(); if (childCount) { for (int childIndex = 0; childIndex < childCount; ++childIndex) { draw(octree->getChild(childIndex), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); } } }
30.802469
287
0.755511
narendraumate
19739d11d88c922729740fe17fd0519600b431f7
2,759
cpp
C++
src/mupnp/soap/SOAP.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
src/mupnp/soap/SOAP.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
src/mupnp/soap/SOAP.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************** * * mUPnP for C++ * * Copyright (C) Satoshi Konno 2002 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <string> #include <sstream> #include <string.h> #include <mupnp/soap/SOAP.h> #include <uhttp/util/StringUtil.h> //////////////////////////////////////////////// // CreateEnvelopeBodyNode //////////////////////////////////////////////// mupnp_shared_ptr<uXML::Node> uSOAP::SOAP::CreateEnvelopeBodyNode() { // <Envelope> std::string envNodeName; envNodeName += XMLNS; envNodeName += DELIM; envNodeName += ENVELOPE; uXML::Node *envNode = new uXML::Node(envNodeName.c_str()); std::string xmlNs; xmlNs += "xmlns"; xmlNs += DELIM; xmlNs += XMLNS; envNode->setAttribute(xmlNs.c_str(), XMLNS_URL); std::string encStyle; encStyle += XMLNS; encStyle += DELIM; encStyle += "encodingStyle"; envNode->setAttribute(encStyle.c_str(), ENCSTYLE_URL); // <Body> std::string bodyNodeName; bodyNodeName += XMLNS; bodyNodeName += DELIM; bodyNodeName += BODY; uXML::Node *bodyNode = new uXML::Node(bodyNodeName.c_str()); envNode->addNode(bodyNode); return mupnp_shared_ptr<uXML::Node>(envNode); } //////////////////////////////////////////////// // Header //////////////////////////////////////////////// const char *uSOAP::SOAP::GetHeader(const std::string &content, std::string &header) { header = ""; if (content.length() <= 0) return header.c_str(); std::string::size_type gtIdx = content.find(">"); if (gtIdx == std::string::npos) return header.c_str(); header = content.substr(0, gtIdx+1); return header.c_str(); } //////////////////////////////////////////////// // Encoding //////////////////////////////////////////////// const char *uSOAP::SOAP::GetEncording(const std::string &content, std::string &encording) { encording = ""; std::string header; SOAP::GetHeader(content, header); if (header.size() <= 0) return encording.c_str(); std::string::size_type encIdx = header.find(uSOAP::SOAP::ENCORDING); if (encIdx == std::string::npos) return encording.c_str(); std::string::size_type startIdx = header.find('\"', encIdx+strlen(uSOAP::SOAP::ENCORDING)+1); if (startIdx == std::string::npos) return encording.c_str(); std::string::size_type endIdx = header.find('\"', startIdx+1); encording = header.substr(startIdx+1, (endIdx-startIdx-1)); return encording.c_str(); } bool uSOAP::SOAP::IsEncording(const std::string &content, const std::string &encType) { std::string enc; SOAP::GetEncording(content, enc); uHTTP::String encStr(enc); return encStr.equalsIgnoreCase(encType); }
29.666667
95
0.576296
cybergarage
1973bcacdaee75bfcb4d0c30016fb6726d29e884
4,990
cpp
C++
_midynet/tests/test_randomgraph/test_erdosrenyi.cpp
charlesmurphy1/fast-midynet
22071d49077fce9d5f99a4664f36767b27edea64
[ "MIT" ]
null
null
null
_midynet/tests/test_randomgraph/test_erdosrenyi.cpp
charlesmurphy1/fast-midynet
22071d49077fce9d5f99a4664f36767b27edea64
[ "MIT" ]
null
null
null
_midynet/tests/test_randomgraph/test_erdosrenyi.cpp
charlesmurphy1/fast-midynet
22071d49077fce9d5f99a4664f36767b27edea64
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <list> #include <algorithm> #include <string> #include "FastMIDyNet/prior/sbm/edge_count.h" #include "FastMIDyNet/random_graph/erdosrenyi.h" #include "FastMIDyNet/types.h" #include "FastMIDyNet/utility/functions.h" #include "BaseGraph/types.h" #include "fixtures.hpp" using namespace std; using namespace FastMIDyNet; static const int NUM_EDGES = 50; static const int NUM_VERTICES = 50; class TestErdosRenyiFamily: public::testing::Test{ public: EdgeCountPoissonPrior edgeCountPrior = {NUM_EDGES}; ErdosRenyiFamily randomGraph = ErdosRenyiFamily(NUM_VERTICES, edgeCountPrior); void SetUp() { randomGraph.sample(); } }; TEST_F(TestErdosRenyiFamily, randomGraph_hasCorrectBlockSequence){ auto blocks = randomGraph.getBlocks(); for (auto b : blocks) EXPECT_EQ(b, 0); } TEST_F(TestErdosRenyiFamily, sample_getGraphWithCorrectNumberOfEdges){ randomGraph.sample(); EXPECT_EQ(randomGraph.getGraph().getTotalEdgeNumber(), randomGraph.getEdgeCount()); } TEST_F(TestErdosRenyiFamily, getLogLikelihoodRatioFromBlockMove_returnMinusInfinity){ BlockMove move = {0, 0, 1, 1}; double dS = randomGraph.getLogPriorRatioFromBlockMove(move); EXPECT_EQ(dS, -INFINITY); } TEST_F(TestErdosRenyiFamily, applyBlockMove_throwConsistencyError){ #if DEBUG BlockMove move = {0, 0, 1, 1}; EXPECT_THROW(randomGraph.applyBlockMove(move), ConsistencyError); #endif } TEST_F(TestErdosRenyiFamily, isCompatible_forGraphSampledFromSBM_returnTrue){ randomGraph.sample(); auto g = randomGraph.getGraph(); EXPECT_TRUE(randomGraph.isCompatible(g)); } TEST_F(TestErdosRenyiFamily, isCompatible_forEmptyGraph_returnFalse){ MultiGraph g(0); EXPECT_FALSE(randomGraph.isCompatible(g)); } TEST_F(TestErdosRenyiFamily, isCompatible_forGraphWithOneEdgeMissing_returnFalse){ randomGraph.sample(); auto g = randomGraph.getGraph(); for (auto vertex: g){ for (auto neighbor: g.getNeighboursOfIdx(vertex)){ g.removeEdgeIdx(vertex, neighbor.vertexIndex); break; } } EXPECT_FALSE(randomGraph.isCompatible(g)); } class TestSimpleErdosRenyiFamily: public::testing::Test{ public: EdgeCountDeltaPrior edgeCountPrior = {NUM_EDGES}; SimpleErdosRenyiFamily randomGraph = SimpleErdosRenyiFamily(NUM_VERTICES, edgeCountPrior); void SetUp() { randomGraph.samplePriors(); randomGraph.sample(); } }; TEST_F(TestSimpleErdosRenyiFamily, randomGraph_hasCorrectBlockSequence){ auto blocks = randomGraph.getBlocks(); for (auto b : blocks) EXPECT_EQ(b, 0); } TEST_F(TestSimpleErdosRenyiFamily, sample_getGraphWithCorrectNumberOfEdges){ randomGraph.sample(); EXPECT_EQ(randomGraph.getGraph().getTotalEdgeNumber(), randomGraph.getEdgeCount()); } TEST_F(TestSimpleErdosRenyiFamily, getLogLikelihoodRatioFromGraphMove_forAddedEdge_returnCorrectLogLikelihoodRatio){ auto graph = randomGraph.getGraph(); GraphMove move = {}; for (auto vertex: graph){ if (graph.getEdgeMultiplicityIdx(0, vertex) == 0) { move.addedEdges.push_back({0, vertex}); break; } } double actualLogLikelihoodRatio = randomGraph.getLogLikelihoodRatioFromGraphMove(move); double logLikelihoodBefore = randomGraph.getLogLikelihood(); randomGraph.applyGraphMove(move); double logLikelihoodAfter = randomGraph.getLogLikelihood(); EXPECT_NEAR(actualLogLikelihoodRatio, logLikelihoodAfter - logLikelihoodBefore, 1E-6); } TEST_F(TestSimpleErdosRenyiFamily, getLogLikelihoodRatioFromGraphMove_forRemovedEdge_returnCorrectLogLikelihoodRatio){ auto graph = randomGraph.getGraph(); GraphMove move = {}; for (auto neighbor: graph.getNeighboursOfIdx(0)){ move.removedEdges.push_back({0, neighbor.vertexIndex}); break; } double actualLogLikelihoodRatio = randomGraph.getLogLikelihoodRatioFromGraphMove(move); double logLikelihoodBefore = randomGraph.getLogLikelihood(); randomGraph.applyGraphMove(move); double logLikelihoodAfter = randomGraph.getLogLikelihood(); EXPECT_NEAR(actualLogLikelihoodRatio, logLikelihoodAfter - logLikelihoodBefore, 1E-6); } TEST_F(TestSimpleErdosRenyiFamily, isCompatible_forGraphSampledFromSBM_returnTrue){ randomGraph.sample(); auto g = randomGraph.getGraph(); EXPECT_TRUE(randomGraph.isCompatible(g)); } TEST_F(TestSimpleErdosRenyiFamily, isCompatible_forEmptyGraph_returnFalse){ MultiGraph g(0); EXPECT_FALSE(randomGraph.isCompatible(g)); } TEST_F(TestSimpleErdosRenyiFamily, isCompatible_forGraphWithOneEdgeMissing_returnFalse){ randomGraph.sample(); auto g = randomGraph.getGraph(); for (auto vertex: g){ for (auto neighbor: g.getNeighboursOfIdx(vertex)){ g.removeEdgeIdx(vertex, neighbor.vertexIndex); break; } } EXPECT_FALSE(randomGraph.isCompatible(g)); }
32.402597
118
0.742285
charlesmurphy1
1973c4eb8fbedd8255e7445a74b3b77d35326f97
411
cpp
C++
inv_pend_walk/test/check_foot_step_planner.cpp
AD58-3104/bipedal_training
f7bca20e12f65ed4be2a9ba93198286682642fca
[ "MIT" ]
null
null
null
inv_pend_walk/test/check_foot_step_planner.cpp
AD58-3104/bipedal_training
f7bca20e12f65ed4be2a9ba93198286682642fca
[ "MIT" ]
null
null
null
inv_pend_walk/test/check_foot_step_planner.cpp
AD58-3104/bipedal_training
f7bca20e12f65ed4be2a9ba93198286682642fca
[ "MIT" ]
null
null
null
#include "foot_step_planner.hpp" #include <iostream> #include <fstream> #include <vector> #include <cmath> #include <Eigen/Dense> #include <Eigen/Geometry> using namespace Eigen; int main(int argc, char const *argv[]) { footStepPlanner(2.0,2.0,0.30); planAlongSpline(); system("sleep 0.1"); system("gnuplot-x11 -persist show.plt"); system("gnuplot-x11 -persist spline.plt"); return 0; }
22.833333
46
0.688564
AD58-3104
197bac971e6f7d5e47fce66bdb276fe36a3542d7
930
cpp
C++
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
1
2016-01-09T09:57:55.000Z
2016-01-09T09:57:55.000Z
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
null
null
null
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
null
null
null
#include "gtfo/algorithm/count_if.hpp" #include "gtfo_testing/runtime/runtime_tests.hpp" using namespace gtfo::runtime_test_helpers; namespace { struct Foo { int x; Foo() : x(42) { } explicit Foo(int x) : x(x) { } }; class Bool { private: bool _value; public: explicit Bool(bool value) : _value(value) { } operator bool() const { return _value; } }; class Pred { private: int _x; public: explicit Pred(int x) : _x(x) { } Bool operator()(const Foo & foo) const { return Bool(foo.x == _x); } }; } using gtfo::count_if; GTFO_TEST_FUN_BEGIN Foo arr[10]; arr[3].x = 10; arr[5].x = 10; arr[8].x = 10; // two iterators + value GTFO_TEST_ASSERT_EQ(count_if(arr, arr + 10, Pred(42)), 7) // range + value GTFO_TEST_ASSERT_EQ(count_if(rev(arr), Pred(10)), 3) GTFO_TEST_FUN_END
19.375
76
0.569892
TMorozovsky
197cc9254e92cdc7eba34a5f8fddbec0df721dc9
32,594
cxx
C++
private/inet/mshtml/src/site/print/headfoot.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/mshtml/src/site/print/headfoot.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/mshtml/src/site/print/headfoot.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//+--------------------------------------------------------------------------- // // Microsoft Forms // Copyright (C) Microsoft Corporation, 1992 - 1996. // // File: headfoot.cxx // // Contents: CHeaderFooterInfo // //---------------------------------------------------------------------------- #include "headers.hxx" #ifndef X_HEADFOOT_HXX_ #define X_HEADFOOT_HXX_ #include "headfoot.hxx" #endif #ifndef X_FPRINT_HXX_ #define X_FPRINT_HXX_ #include "fprint.hxx" #endif #ifndef X_HEDELEMS_HXX_ #define X_HEDELEMS_HXX_ #include "hedelems.hxx" #endif #ifndef X__FONTLNK_H_ #define X__FONTLNK_H_ #include "_fontlnk.h" #endif MtDefine(CHeaderFooterInfo, Printing, "CHeaderFooterInfo") MtDefine(CHeaderFooterInfo_aryParts_pv, CHeaderFooterInfo, "CHeaderFooterInfo::_aryParts::_pv") MtDefine(CHeaderFooterInfo_pURL, CHeaderFooterInfo, "CHeaderFooterInfo::_pURL") MtDefine(CHeaderFooterInfo_pHeaderFooter, CHeaderFooterInfo, "CHeaderFooterInfo::_pHeaderFooter") MtDefine(CHeaderFooterInfo_pTitle, CHeaderFooterInfo, "CHeaderFooterInfo::_pTitle") MtDefine(CHeaderFooterInfoConvertNum_ppChars, Printing, "CHeaderFooterInfo::ConvertNum *ppChars") MtDefine(CDescr, Printing, "CDescr") MtDefine(CDescr_pPart, Printing, "CDescr::_pPart") #define NUMNOTSET -1 enum PartKindType { pkText,pkPageNum,pkMultipleBlank }; //--------------------------------------------------------------------------- // // Class: CDescr // // Synopsis: Describes one element in the Header or Footer // One element can be a text string or a Page number or MultipleBlank // if it is not a textstring then pPart is NULL. // // //--------------------------------------------------------------------------- class CDescr { public: DECLARE_MEMALLOC_NEW_DELETE(Mt(CDescr)) CDescr(void); ~CDescr(); TCHAR* pPart; PartKindType PartKind; int xPos; int iPixelLen; }; //--------------------------------------------------------------------------- // // Member: CDescr::CDescr // // Synopsis: Constructor of CDescr // // Arguments: None // //--------------------------------------------------------------------------- CDescr::CDescr(void) { pPart = NULL; }; //--------------------------------------------------------------------------- // // Member: CDescr::~CDescr // // Synopsis: Destructor of CDescr // Deletes allocated string containing part of Header or Footer // // Arguments: None // //--------------------------------------------------------------------------- CDescr::~CDescr() { // because we do not store the whole text, only the pointer if it is // a pagenumber, therefore we should not delete it if (PartKind != pkPageNum) delete [] pPart; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::CHeaderFooterInfo // // Synopsis: Constructor of CHeaderFooterInfo // Initializes the pointers of the original (user typed) header of footer, // the title and the URL address. // Moves NUMNOTSET value into number members. // // Arguments: None // //--------------------------------------------------------------------------- CHeaderFooterInfo::CHeaderFooterInfo(CPrintDoc* pPrintDoc) : _aryParts(Mt(CHeaderFooterInfo_aryParts_pv)) { Assert(pPrintDoc); _pHeaderFooter = NULL; _iLastPageNum = NUMNOTSET; _iTotalPages = NUMNOTSET; _pTitle = NULL; _iNrOfMultipleBlanks = 0; _bParsed = FALSE; _pURL = NULL; _tcscpy(_PageNumChars,_T("")); if (pPrintDoc->_pPrimaryMarkup->GetTitleElement()) { SetTitle(&(pPrintDoc->_pPrimaryMarkup->GetTitleElement()->_cstrTitle)); } _pPrintDoc = pPrintDoc; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::~CHeaderFooterInfo // // Synopsis: Destructor of CHeaderFooterInfo // Deletes the original (user typed) header of footer, // the parsed and assembled string, the title and the URL address. // Deletes the array containing parts of the header or footer. // // Arguments: None // //--------------------------------------------------------------------------- CHeaderFooterInfo::~CHeaderFooterInfo() { delete [] _pHeaderFooter; delete [] _pTitle; delete [] _pURL; DeleteArray(); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::DeleteArray // // Synopsis: Deletes the array containing parts of the header or footer // // Arguments: None // //--------------------------------------------------------------------------- void CHeaderFooterInfo::DeleteArray(void) { CDescr* pDescr; for (int i=0;i<_aryParts.Size();i++) { pDescr = _aryParts[i]; delete pDescr; }; _aryParts.DeleteAll(); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::SetHeaderFooterURL // // Synopsis: Set the URL address of the Document // // Arguments: pURL address of URL string // //--------------------------------------------------------------------------- void CHeaderFooterInfo::SetHeaderFooterURL(TCHAR* pURL) { delete _pURL; _pURL = NULL; if (!pURL) return; int iLen = _tcslen(pURL); if (iLen < 1) return; _pURL = new(Mt(CHeaderFooterInfo_pURL)) TCHAR[iLen+1]; Assert(_pURL); if (!_pURL) return; _tcscpy(_pURL,pURL); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::ConvertNum // // Synopsis: Converts a number to a string. Allocates string.If number is not set // gives back an empty string. // // Arguments: iNum integer number to be converted into string // ppChars string the number will be converted into (max 8 chars) // //--------------------------------------------------------------------------- void CHeaderFooterInfo::ConvertNum(int iNum,TCHAR** ppChars) { *ppChars = new(Mt(CHeaderFooterInfoConvertNum_ppChars)) TCHAR[8]; if (*ppChars) { if (iNum == NUMNOTSET) { _tcscpy(*ppChars,_T("")); } else { _itot(iNum,*ppChars,10); }; }; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::ConvertPageNum // // Synopsis: Convert the last page number by calling ConvertNum // // Arguments: ppNumChars string the page number will be converted into (max 8 chars) // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::ConvertPageNum(void) { _itot(_iLastPageNum,(TCHAR*)&_PageNumChars,10); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddTextDescr // // Synopsis: Allocates a new CDescr object, allocates memory inside the object to store // the new Text and sets the PartKind member to pkText // Append the new CDescr object to _aryParts collection. // // Arguments: pText text to be stored in a CDescr object // //--------------------------------------------------------------------------- void CHeaderFooterInfo::AddTextDescr(TCHAR* pText) { if (!pText) return; if (_tcslen(pText) < 1) return; CDescr* pDescr; pDescr = new CDescr; Assert(pDescr); if (!pDescr) return; pDescr->pPart = new(Mt(CDescr_pPart)) TCHAR[_tcslen(pText)+1]; Assert(pDescr->pPart); if (!pDescr->pPart) { delete pDescr; return; }; _tcscpy(pDescr->pPart,pText); pDescr->PartKind = pkText; _aryParts.Append(pDescr); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddTotalPages // // Synopsis: Converts the total pages into a string and add the new string into // _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- void CHeaderFooterInfo::AddTotalPages(void) { TCHAR* pTotalPagesChars; ConvertNum(_iTotalPages,&pTotalPagesChars); AddTextDescr(pTotalPagesChars); delete pTotalPagesChars; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddTime // // Synopsis: Converts the current time into a string and adds // it to the _aryParts collection. // // Arguments: dFlag 0 or TIME_FORCE24HOURFORMAT // //--------------------------------------------------------------------------- void CHeaderFooterInfo::AddTime(DWORD dFlag) { TCHAR TimeStr[DATE_STR_LENGTH]; SYSTEMTIME currentSysTime; GetLocalTime(&currentSysTime); #ifndef WIN16 if (GetTimeFormat(LOCALE_USER_DEFAULT,dFlag,&currentSysTime,NULL, (TCHAR*)&TimeStr,DATE_STR_LENGTH)) { AddTextDescr((TCHAR*)&TimeStr); }; #else // BUGWIN16 mblain--we currently always use the US C format for time! int cchResult; struct tm *LocalTm; LocalTm = localtime(&currentSysTime); if (TIME_FORCE24HOURFORMAT == dFlag) { cchResult = wsprintf(TimeStr, "%2d:%2d:%2d", LocalTm->tm_hour, LocalTm->tm_min, LocalTm->tm_sec ); } else { cchResult = wsprintf(TimeStr, "%2d:%2d:%2d %s", LocalTm->tm_hour % 12, LocalTm->tm_min, LocalTm->tm_sec, LocalTm->tm_hour < 12 ? "AM" : "PM" ); } Assert(cchResult <= DATE_STR_LENGTH); AddTextDescr((TCHAR*)&TimeStr); #endif // ndef WIN16 else }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddShortTime // // Synopsis: Converts the current time (short format) into a string and adds // it to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddShortTime(void) { AddTime(0); // zero means no 24 hour format }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddLongTime // // Synopsis: Converts the current time (long format) into a string and adds // it to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddLongTime(void) { AddTime(TIME_FORCE24HOURFORMAT); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddShortDate // // Synopsis: Converts the current date into a string and adds // it to the _aryParts collection. // // // Arguments: dFlag DATE_SHORTDATE or DATE_LONGDATE // //--------------------------------------------------------------------------- void CHeaderFooterInfo::AddDate(DWORD dFlag) { TCHAR DateStr[DATE_STR_LENGTH]; SYSTEMTIME currentSysTime; GetLocalTime(&currentSysTime); #ifndef WIN16 if (GetDateFormat(LOCALE_USER_DEFAULT,dFlag,&currentSysTime,NULL, (TCHAR*)&DateStr,DATE_STR_LENGTH)) { AddTextDescr((TCHAR*)&DateStr); }; #else // BUGWIN16 mblain--we currently always use the US C format for date! // we also always use 'short' format -- 18feb97 int cchResult; struct tm *LocalTm; LocalTm = localtime(&currentSysTime); //if (DATE_SHORTDATE == dFlag) { cchResult = wsprintf(DateStr, "%2d/%2d/%2d", LocalTm->tm_mon +1, LocalTm->tm_mday, LocalTm->tm_year % 100 ); } // else // do long format. Assert(cchResult <= DATE_STR_LENGTH); AddTextDescr((TCHAR*)&DateStr); #endif // ndef WIN16 else }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddShortDate // // Synopsis: Converts the current date (short format) into a string and adds // it to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddShortDate(void) { AddDate(DATE_SHORTDATE); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddLongDate // // Synopsis: Converts the current date (long format) into a string and adds // it to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddLongDate(void) { AddDate(DATE_LONGDATE); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddTitle // // Synopsis: Add the title from CDoc to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddTitle(void) { AddTextDescr(_pTitle); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddURL // // Synopsis: Add the URL address from CDoc to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddURL(void) { AddTextDescr(_pURL); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::ParseIt // // Synopsis: Parses the user typed _pHeaderFooter string and builds up // _aryParts collection. // // Special characters : // &p page number // &P total pages // &b multiple blank // &t time, short format // &T time, 24 hour format // &d date, short format // &D date, long format // &w title // &u URL address // // Arguments: None // //--------------------------------------------------------------------------- void CHeaderFooterInfo::ParseIt(void) { Assert(_pHeaderFooter); if (!_pHeaderFooter) return; if (_bParsed) return; DeleteArray(); int iLen = _tcslen(_pHeaderFooter); if (iLen > 0) { TCHAR* pO = _pHeaderFooter; TCHAR* pP = NULL; TCHAR SaveChar; _iNrOfMultipleBlanks = 0; while (*pO) { pP = _tcschr(pO,_T('&')); if (!pP) { AddTextDescr(pO); return; }; *pP = '\0'; AddTextDescr(pO); *pP = _T('&'); pP++; #ifdef UNIX pO = pP - 1; if (_tcslen(pP) < 1) { AddTextDescr(pO); return; } #endif pO = pP; pO++; switch(*pP) { case _T('b') : case _T('p') : CDescr* pDescr; pDescr = new CDescr; Assert(pDescr); if (pDescr) { pDescr->pPart = NULL; if (*pP == _T('p')) { pDescr->PartKind = pkPageNum; } else { pDescr->PartKind = pkMultipleBlank; _iNrOfMultipleBlanks++; }; _aryParts.Append(pDescr); }; break; case _T('P') : AddTotalPages(); break; case _T('d') : AddShortDate(); break; case _T('D') : AddLongDate(); break; case _T('t') : AddShortTime(); break; case _T('T') : AddLongTime(); break; case _T('w') : AddTitle(); break; case _T('u') : AddURL(); break; default : SaveChar = *pO; *pO = '\0'; AddTextDescr(pP); *pO = SaveChar; break; }; }; }; _bParsed = TRUE; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::SetHeaderFooter // // Synopsis: Stores the used typed Header or Footer and starts the parsing process // // Arguments: pHeaderFooter user typed string // //--------------------------------------------------------------------------- HRESULT CHeaderFooterInfo::SetHeaderFooter(TCHAR* pHeaderFooter) { delete [] _pHeaderFooter; _pHeaderFooter = NULL; if (!pHeaderFooter) { _pHeaderFooter = new(Mt(CHeaderFooterInfo_pHeaderFooter)) TCHAR[1]; if (_pHeaderFooter) _tcscpy(_pHeaderFooter,_T("")); } else { int iLen = _tcslen(pHeaderFooter); _pHeaderFooter = new(Mt(CHeaderFooterInfo_pHeaderFooter)) TCHAR[iLen+1]; Assert(_pHeaderFooter); if (_pHeaderFooter) _tcscpy(_pHeaderFooter,pHeaderFooter); }; return S_OK; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::SetTitle // // Synopsis: Stores the document title into the _aryParts collection // // Arguments: pTitle document title // //--------------------------------------------------------------------------- void CHeaderFooterInfo::SetTitle(CStr* pTitle) { LPTSTR pStr; if (!pTitle) return; pStr = LPTSTR(*pTitle); delete [] _pTitle; _pTitle = NULL; int iLen = pTitle->Length(); if (iLen > 0) { _pTitle = new(Mt(CHeaderFooterInfo_pTitle)) TCHAR[iLen + 1]; Assert(_pTitle); if (_pTitle) _tcscpy(_pTitle,pStr); }; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::CalcXPos // // Synopsis: Goes through the parts collection (_aryParts) and calculates the // x position of them // // Arguments: pDI CDrawInfo // hFont font handle // //--------------------------------------------------------------------------- void CHeaderFooterInfo::CalcXPos(CDrawInfo* pDI) { int iPixelLen = 0; // length of header or footer in pixels int iPixelFree; // remaining pixels after calculating iPixelLen int iPixelMultipleBlank = 0; // pixels for 1 multiple blank SIZE size; int xPos; ConvertPageNum(); int iPageNumLen = _tcslen((TCHAR*)&_PageNumChars); // length of page number in chars int iPixelPageNum = 0; // length of page number in pixels int i; CDescr* pDescr; GetTextExtentPoint32(pDI->_hdc,(TCHAR*)&_PageNumChars,iPageNumLen,&size); iPixelPageNum = size.cx; // we do it only once // calculate the length of parts in pixels for (i=0;i<_aryParts.Size();i++) { pDescr = _aryParts[i]; if (pDescr->PartKind == pkText) { GetTextExtentPoint32(pDI->_hdc,pDescr->pPart,_tcslen(pDescr->pPart),&size); pDescr->iPixelLen = size.cx; iPixelLen += size.cx; } else { if (pDescr->PartKind == pkPageNum) { pDescr->pPart = (TCHAR*)&_PageNumChars; pDescr->iPixelLen = iPixelPageNum; iPixelLen += iPixelPageNum; }; } } int iTabStopPos; int iMultipleBlankCounter = 0; // calculate complete width of page iPixelFree = _pPrintDoc->_rcClip.right - _pPrintDoc->_rcClip.left; xPos = iTabStopPos = _pPrintDoc->_rcClip.left; if (_iNrOfMultipleBlanks && (iPixelFree > 0)) { iPixelMultipleBlank = iPixelFree / _iNrOfMultipleBlanks; } // calculate the x position of every part for (i=0;i<_aryParts.Size();i++) { pDescr = _aryParts[i]; pDescr->xPos = xPos; if (pDescr->PartKind == pkMultipleBlank) { xPos += iPixelMultipleBlank; iTabStopPos += iPixelMultipleBlank; iMultipleBlankCounter++; } else { xPos += pDescr->iPixelLen; if (i > 0) { CDescr* pPrevDescr = _aryParts[i-1]; if (pPrevDescr->PartKind == pkMultipleBlank) { // previous element was a multipleblank // now try to center align the text part BOOL bTextCanBeCentered = (iTabStopPos + (pDescr->iPixelLen/2)) <= iPixelFree; BOOL bRemainingPartsFit = (iTabStopPos - (pDescr->iPixelLen/2) + iPixelLen) <= iPixelFree; if (bTextCanBeCentered && bRemainingPartsFit) { pDescr->xPos = iTabStopPos - (pDescr->iPixelLen / 2); xPos = pDescr->xPos + pDescr->iPixelLen; } else { // try to right align if ((iTabStopPos + iPixelLen) <= iPixelFree) { pDescr->xPos = iTabStopPos; xPos = iTabStopPos + pDescr->iPixelLen; } else { // we have to left align xPos = iTabStopPos - iPixelLen + pDescr->iPixelLen; pDescr->xPos = iTabStopPos - iPixelLen; // we have to make room for the other // parts as well } } } } iPixelLen -= pDescr->iPixelLen; // now it contains the length of the remaining parts } } } //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::DrawIt // // Synopsis: Goes through the parts collection (_aryParts) and draws the text parts // // Arguments: hdc device context handle // y the vertical position to draw at // //--------------------------------------------------------------------------- void CHeaderFooterInfo::DrawIt( CDrawInfo * pDI, const CCharFormat * pCF, int y, BOOL fHeader) { CDescr* pDescr; CDescr* pNextDescr; SIZE spaceSize; int nParts = _aryParts.Size(); int j; int nLen; GetTextExtentPoint32(pDI->_hdc,_T(" "),1,&spaceSize); for (int i=0;i<nParts;i++) { pDescr = _aryParts[i]; if (pDescr->pPart) { SIZE textsize; pNextDescr = NULL; int yPos; GetTextExtentPoint(pDI->_hdc,pDescr->pPart,_tcslen(pDescr->pPart),&textsize); if ((i < _aryParts.Size()-1) && (pDescr->PartKind != pkPageNum)) { pNextDescr = NULL; for (j=i+1;j<nParts;j++) { if (_aryParts[j]->pPart) { pNextDescr = _aryParts[j]; break; } } if (pNextDescr) { // Instead of doing >= I do > because if the user puts a space at the end // of the text we do not want to truncate it. // We do not know the user intentions wheather he/she wants to touch the next // part or not. if ((pDescr->xPos + textsize.cx ) > pNextDescr->xPos) { if (_tcslen(pDescr->pPart) < MAX_PATH) { // PathCompactPath assumes that the text at least MAX_PATH long // otherwise it overwrite the memory behind it. It is a bug in that code // BUGBUG if PathCompactPath will be fixed we do not need this whole if // statement. TCHAR* pNew = new(Mt(CDescr_pPart)) TCHAR[MAX_PATH+1]; if (pNew) { _tcscpy(pNew,pDescr->pPart); delete [] pDescr->pPart; pDescr->pPart = pNew; PathCompactPath(pDI->_hdc,pDescr->pPart,pNextDescr->xPos-pDescr->xPos-spaceSize.cx); } } else { PathCompactPath(pDI->_hdc,pDescr->pPart,pNextDescr->xPos-pDescr->xPos-spaceSize.cx); } if ((pDescr->xPos + textsize.cx ) > pNextDescr->xPos) { // because if the last part (after the rightmost slash) is too long // PathCompactPath does not truncate it right, therefore we have to // truncate it ourselves. nLen = _tcslen(pDescr->pPart); pDescr->pPart[nLen-1] = 0; while (nLen > 0) { GetTextExtentPoint(pDI->_hdc,pDescr->pPart,nLen-1,&textsize); if ((pDescr->xPos + textsize.cx ) > pNextDescr->xPos) { nLen--; pDescr->pPart[nLen] = 0; } else { break; } } } } } } // If we are drawing the footer, move the top of the text into the printable range. // To be sure that everything is visible, move up the footer by 120% of the text height: // MulDivQuick(spaceSize.cy, 6, 5). One of many PCL drivers that have a problem with this // mainly on Win95 is HP LaserJet 4Si MX. yPos = y - (fHeader ? 0 : MulDivQuick(spaceSize.cy, 6, 5)); // add 20% to the text height if (pCF) { FontLinkTextOut(pDI->_hdc, pDescr->xPos, yPos, 0, NULL, pDescr->pPart, _tcslen(pDescr->pPart), pDI, pCF, FLTO_TEXTOUTONLY); } else { TextOut(pDI->_hdc, pDescr->xPos, yPos, pDescr->pPart, _tcslen(pDescr->pPart)); } } } } //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::Draw // // Synopsis: Draws the stored _pParsed string into the top or the bottom margin // // Arguments: pDI pointer to DrawInfo // bHeader True if it is a header, false if it is a footer // hFont font handle //--------------------------------------------------------------------------- void CHeaderFooterInfo::Draw( CDrawInfo* pDI, const CCharFormat * pCF, BOOL bHeader, HFONT hFont) { if (!_pHeaderFooter) return; if (_tcslen(_pHeaderFooter) < 1) return; HRGN hrgn = CreateRectRgn(0, 0, 0, 0); if (hrgn == NULL) return; if (SaveDC(pDI->_hdc)) { int y = 0; HFONT hFontOld = NULL; COLORREF oldColor = SetTextColor(pDI->_hdc,RGB(0,0,0)); // black COLORREF oldBkColor = SetBkColor(pDI->_hdc,RGB(255,255,255)); // white if (GetClipRgn(pDI->_hdc,hrgn) != -1) { SelectClipRgn(pDI->_hdc, NULL); if (hFont) hFontOld = (HFONT)SelectObject(pDI->_hdc,hFont); if (!_bParsed) ParseIt(); CalcXPos(pDI); if (bHeader) { IntersectClipRect(pDI->_hdc, pDI->_ptDst.x, 0, pDI->_ptDst.x + pDI->_sizeDst.cx, pDI->_ptDst.y); } else { IntersectClipRect(pDI->_hdc, pDI->_ptDst.x, pDI->_ptDst.y + pDI->_sizeDst.cy, pDI->_ptDst.x + pDI->_sizeDst.cx, #ifdef WIN16 //BUGWIN16: we don't have the GetDeviceCaps for PHYSICALHEIGHT, so turning this // back to the old code pDI->_ptDst.y + pDI->_sizeDst.cy + _pPrintDoc->_PrintInfoBag.rtMargin.bottom); y = pDI->_ptDst.y+pDI->_sizeDst.cy; #else GetDeviceCaps(pDI->_hic, PHYSICALHEIGHT)); // set the footer y to the end of the print range. if not in clip-rect, we clip. y = MulDivQuick(100*GetDeviceCaps(pDI->_hic, VERTSIZE), GetDeviceCaps(pDI->_hic, LOGPIXELSY), 2540); #endif }; #ifdef UNIX //currently mainwin doesn't support initialization of hdcDesktop // try to find a temprary patch { if (!bHeader){ SIZE spaceSize; GetTextExtentPoint32(pDI->_hdc, _T(" "),1,&spaceSize); if (spaceSize.cy == 0) y = pDI->_ptDst.y + pDI->_sizeDst.cy; } } #endif //unix DrawIt(pDI, pCF, y, bHeader); SelectClipRgn(pDI->_hdc,hrgn); DeleteObject(hrgn); if (hFontOld) SelectObject(pDI->_hdc,hFontOld); }; if (oldColor != CLR_INVALID) SetTextColor(pDI->_hdc,oldColor); if (oldBkColor != CLR_INVALID) SetBkColor(pDI->_hdc,oldBkColor); RestoreDC(pDI->_hdc,-1); } };
30.604695
117
0.437289
King0987654
1987a2b4d96cf43b2be6d2b61e9ee7692691c499
9,723
cpp
C++
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
#include "stdafx_u.h" #include "StageSelect.h" #include "ParentSelectPanel.h" #include "InputManager.h" #include "SelectScreen.h" #include "ShakeComponent.h" #include "SelectPlayer.h" #include "SceneChangeAnimation.h" #include "GameSettings.h" #include"PauseManager.h" #include"Header/GameObjects/DefaultGameComponent/OutlineDrawComponent.h" int ButiEngine::StageSelect::stageNum = 0; int ButiEngine::StageSelect::maxStageNum = 19; //LastStageNum - 1 std::string ButiEngine::StageSelect::removeStageName = "none"; bool ButiEngine::StageSelect::isAnimation; int count=0; const float angle = 360.0f / (float)(ButiEngine::StageSelect::maxStageNum + 1) * 2.0f; void ButiEngine::StageSelect::OnUpdate() { Onece(); const auto childAngle = 180.0f / (ButiEngine::StageSelect::maxStageNum + 1) * 2.0f; auto parentSelectPanel = wkp_parentSelectPanel.lock()->GetGameComponent<ParentSelectPanel>(); if (intervalFrame > 20 && !isAnimation) { if (InputManager::OnPushRightKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushRight(); parentSelectPanel->ChildRotation(-childAngle,stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum<10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)), 0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } else if (InputManager::OnPushLeftKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushLeft(); parentSelectPanel->ChildRotation(childAngle,stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)),0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } if (InputManager::OnSkipKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushSkip(); parentSelectPanel->ChildRotation(-childAngle * ((maxStageNum + 1) / 2),stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)),0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } } else { intervalFrame++; } DecisionAnimation(); SelectRotation(); } void ButiEngine::StageSelect::OnSet() { } void ButiEngine::StageSelect::Start() { shp_pauseManager = GetManager().lock()->GetGameObject("PauseManager").lock()->GetGameComponent<PauseManager>(); GameSettings::isStageSelect = true; isOnece = false; isAnimation = false; animationFrame = 90; intervalFrame = 0; fadeCount = 0; wkp_parentSelectPanel = GetManager().lock()->GetGameObject("ParentSelectPanel"); wkp_animationPlayer = GetManager().lock()->AddObjectFromCereal("AnimationPlayer"); wkp_fadeObject = GetManager().lock()->AddObjectFromCereal("FadeObject", ObjectFactory::Create<Transform>(Vector3(0, 0, -0.01), Vector3::Zero, Vector3(2112, 1188, 1))); preParentRotation = stageNum * angle; auto sceneManager = gameObject.lock()->GetApplication().lock()->GetSceneManager(); if (stageNum <= 0) { std::string sceneName = "Stage" + std::to_string(maxStageNum); sceneManager->RemoveScene(sceneName); } else { int preStageNum = stageNum - 1; std::string sceneName = "Stage" + std::to_string(preStageNum); sceneManager->RemoveScene(sceneName); } se_enter = SoundTag("Sound/Enter.wav"); se_select = SoundTag("Sound/Select-Click.wav"); se_dash = SoundTag("Sound/Rat_Dash.wav"); se_hit = SoundTag("Sound/Rat_Hit.wav"); se_start = SoundTag("Sound/Rat_Start.wav"); bgm = SoundTag("Sound/BGM2.wav"); GetManager().lock()->GetApplication().lock()->GetSoundManager()->StopBGM(); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlayBGM(bgm, GameSettings::masterVolume + 0.5f); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)), 0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); GetManager().lock()->GetApplication().lock() ->GetGraphicDevice()->SetClearColor(Vector4((250.0f / 255.0f), (254.0f / 255.0f), (255.0f / 255.0f), 1.0f)); } void ButiEngine::StageSelect::OnShowUI() { } void ButiEngine::StageSelect::ShowGUI() { GUI::Begin("AnimationFrame"); GUI::Text(animationFrame); GUI::End(); GUI::Begin("StageNum"); GUI::BulletText("StageNum"); GUI::Text(stageNum); GUI::BulletText("Count"); GUI::Text(count); GUI::End(); } void ButiEngine::StageSelect::OnCollision(std::weak_ptr<GameObject> arg_other) { } std::shared_ptr<ButiEngine::GameComponent> ButiEngine::StageSelect::Clone() { return ObjectFactory::Create<StageSelect>(); } void ButiEngine::StageSelect::SetStageNum(int arg_stageNum) { stageNum = arg_stageNum; if (stageNum > maxStageNum) { stageNum = 0; } } void ButiEngine::StageSelect::SetRemoveStageName(std::string arg_removeStageName) { removeStageName = arg_removeStageName; } void ButiEngine::StageSelect::OnPushRight() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum++; if (stageNum > maxStageNum) { stageNum = 0; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnPushLeft() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum--; if (stageNum < 0) { stageNum = maxStageNum; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnPushSkip() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum += (maxStageNum + 1) / 2; if (stageNum > maxStageNum) { stageNum = stageNum - maxStageNum - 1; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnDecision() { GameSettings::isStageSelect = false; isAnimation = false; auto sceneManager = gameObject.lock()->GetApplication().lock()->GetSceneManager(); std::string sceneName = "Stage" + std::to_string(stageNum); sceneManager->RemoveScene(sceneName); sceneManager->LoadScene(sceneName); sceneManager->ChangeScene(sceneName); } void ButiEngine::StageSelect::DecisionAnimation() { if (InputManager::OnTriggerDecisionKey() && !isAnimation && !shp_pauseManager->IsPause()) { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_enter, GameSettings::masterVolume); isAnimation = true; } if (!isAnimation) return; if (animationFrame == screenRotateFrame) { GetManager().lock()->GetGameObject("SelectScreen").lock()->GetGameComponent<SelectScreen>()->StartAnimation(); } const int START_FRAME = 89; const int ZANZO_FRAME = 60; const int FLASH_FRAME = 40; const int AWAY_FRAME = 35; if (animationFrame == START_FRAME) { wkp_animationPlayer.lock()->GetGameComponent<SelectPlayer>()->Decision(); } else if (animationFrame == ZANZO_FRAME) { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_dash, GameSettings::masterVolume); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_start, GameSettings::masterVolume); GetManager().lock()->AddObjectFromCereal("SelectZanzo"); } else if (animationFrame == FLASH_FRAME) { GetManager().lock()->AddObjectFromCereal("SelectFlash"); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_hit, GameSettings::masterVolume); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_dash, GameSettings::masterVolume); } else if (animationFrame == AWAY_FRAME) { wkp_animationPlayer.lock()->GetGameComponent<SelectPlayer>()->Away(); } if (animationFrame <= 0) { isNext = true; } if (isNext) { fadeCount++; } if (fadeCount == 1) { GetManager().lock()->AddObjectFromCereal("FadeObject", ObjectFactory::Create<Transform>(Vector3(0, 1134, -0.01), Vector3::Zero, Vector3(2112, 1188, 1))); } const int NEXT_SCENE_COUNT = 30; if (fadeCount > NEXT_SCENE_COUNT) { OnDecision(); } if (animationFrame > 0) { animationFrame--; } } void ButiEngine::StageSelect::SelectRotation() { auto anim = wkp_parentSelectPanel.lock()->GetGameComponent<TransformAnimation>(); if (!anim) { anim = wkp_parentSelectPanel.lock()->AddGameComponent<TransformAnimation>(); anim->SetTargetTransform(wkp_parentSelectPanel.lock()->transform->Clone()); anim->GetTargetTransform()->SetLocalRotation(Matrix4x4::RollY(MathHelper::ToRadian( preParentRotation))); anim->SetSpeed(0.1f); anim->SetEaseType(Easing::EasingType::EaseOut); } } void ButiEngine::StageSelect::Onece() { if (isOnece) return; isOnece = true; auto parentSelectPanel = wkp_parentSelectPanel.lock()->GetGameComponent<ParentSelectPanel>(); auto childAngle = 180.0f / (maxStageNum + 1) * 2.0f; float rotate = childAngle * stageNum; preParentRotation = stageNum * angle; parentSelectPanel->ChildRotation(-rotate,stageNum); }
30.28972
168
0.724673
butibuti
198a5018ac5a706b5c257b0944f7ef607a993788
88
cpp
C++
src/util/Cancellable.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
null
null
null
src/util/Cancellable.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
null
null
null
src/util/Cancellable.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
1
2019-01-08T14:48:29.000Z
2019-01-08T14:48:29.000Z
#include "util/Cancellable.h" using namespace BeeeOn; Cancellable::~Cancellable() { }
11
29
0.738636
tacr-iotcloud
198afa841e2b4b299cfac1ee12484b0c5f49e1f8
7,593
cpp
C++
editor/mainwindow.cpp
ErrrOrrr503/DOORkaEngine
90084cc622b1bcc021d9c3de5ccb52b349d4217e
[ "WTFPL" ]
null
null
null
editor/mainwindow.cpp
ErrrOrrr503/DOORkaEngine
90084cc622b1bcc021d9c3de5ccb52b349d4217e
[ "WTFPL" ]
null
null
null
editor/mainwindow.cpp
ErrrOrrr503/DOORkaEngine
90084cc622b1bcc021d9c3de5ccb52b349d4217e
[ "WTFPL" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->console->setReadOnly(true); ui->texture_label->clear(); ogl_layout = new QHBoxLayout(ui->frame_ogl); ogl_layout->setContentsMargins(0, 0, 0, 0); ogl_layout->setSpacing(0); ogl_out = new oGL_out(ui->frame_ogl, &level); ogl_layout->addWidget(ogl_out); ogl_out->show(); QObject::connect(ogl_out, &oGL_out::print_console, this, &MainWindow::print_console); QObject::connect(&level, &Level::print_console, this, &MainWindow::print_console); QObject::connect(this, &MainWindow::ogl_change_mode, ogl_out, &oGL_out::ogl_change_mode); change_mode(draw_clipping_mode); print_console("Ready"); } MainWindow::~MainWindow() { delete ui; delete ogl_out; delete ogl_layout; outfile.close(); } void MainWindow::on_drawButton_clicked() { change_mode (draw_mode); } void MainWindow::on_selectButton_clicked() { change_mode (sel_mode); } void MainWindow::on_unselButton_clicked() { change_mode (unsel_mode); } void MainWindow::on_clippingButton_clicked() { change_mode (draw_clipping_mode); } void MainWindow::on_setPosButton_clicked() { change_mode (set_pos_mode); } void MainWindow::print_console (const std::string &s) { ui->console->insertPlainText ("["); ui->console->insertPlainText (QTime::currentTime().toString("h:m:s")); ui->console->insertPlainText ("]> "); ui->console->insertPlainText (QString::fromStdString (s)); ui->console->insertPlainText ("\n"); ui->console->ensureCursorVisible (); } void MainWindow::change_mode (edit_mode in_mode) { mode = in_mode; std::string console = "switched to "; switch (in_mode) { case draw_mode: console += "'draw'"; ui->text_tool->setText ("draw"); ui->drawButton->setDown (1); ui->clippingButton->setDown (0); ui->selectButton->setDown (0); ui->unselButton->setDown (0); ui->setPosButton->setDown (0); break; case draw_clipping_mode: console += "'draw_clipping'"; ui->text_tool->setText ("clip"); ui->drawButton->setDown (0); ui->clippingButton->setDown (1); ui->selectButton->setDown (0); ui->unselButton->setDown (0); ui->setPosButton->setDown (0); break; case sel_mode: console += "'select'"; ui->text_tool->setText ("select"); ui->drawButton->setDown (0); ui->clippingButton->setDown (0); ui->selectButton->setDown (1); ui->unselButton->setDown (0); ui->setPosButton->setDown (0); break; case unsel_mode: console += "'unselect'"; ui->text_tool->setText ("unsel"); ui->drawButton->setDown (0); ui->clippingButton->setDown (0); ui->selectButton->setDown (0); ui->unselButton->setDown (1); ui->setPosButton->setDown (0); break; case set_pos_mode: console += "'set player position'"; ui->text_tool->setText ("setPos"); ui->drawButton->setDown (0); ui->clippingButton->setDown (0); ui->selectButton->setDown (0); ui->unselButton->setDown (0); ui->setPosButton->setDown (1); default: break; } console += " mode"; #ifdef DEBUG_MISC print_console(console); #endif emit ogl_change_mode(in_mode); } void MainWindow::on_actionSave_triggered() { if (outfile.is_open ()) { outfile.close (); outfile.open (outfilename, outfile.binary | outfile.out | outfile.trunc); //truncate if (!outfile.is_open()) { print_console ("failed to truncate file while saving"); return; } level.save_level (outfile); } else { open_file_dialog (save); } } void MainWindow::on_actionLoad_triggered () { if (0){ //fixme::unsaved dialog } else { open_file_dialog (load); } } void MainWindow::on_actionDelete_wall_triggered () { print_console ("sorry from v0.hz deletion is unsuported due to triangles. No money, but hold on, best wishes, good mood..."); //level.delete_wall (); //ogl_out->update (); } void MainWindow::open_file_dialog (flag_saveload flag) { opendialog = new OpenDialog(this, flag); QObject::connect(opendialog, &OpenDialog::filename_read, this, &MainWindow::on_opendialog_finish); opendialog->show(); } void MainWindow::on_opendialog_finish(const std::string &filename, flag_saveload flag) { outfilename = filename; std::string console; console = "opening for "; if (flag == save) console += "save '"; else console += "load '"; console += filename; console += "' "; if (!std::filesystem::exists(filename) && flag == load){ // if no file to load console += "FAILED: check existing"; print_console (console); return; } //file exists if (flag == save) { outfile.open(filename, outfile.binary | outfile.out | outfile.trunc); if (!outfile.is_open()) { print_console(console + "FAILED"); return; } print_console(console + "SUCCESS"); level.save_level (outfile); } if (flag == load) { std::ifstream infile; infile.open(filename, infile.binary | infile.in); if (!infile.is_open()) { print_console(console + "FAILED for read"); return; } if (level.load_level (infile)) { infile.close (); print_console (console + "SUCCESS for read"); print_console ("level loading failed!"); return; } infile.close (); outfile.open(filename, outfile.binary | outfile.out | outfile.in); if (!outfile.is_open()) { print_console(console + "FAILED for write"); return; } print_console (console += "SUCCESS"); ogl_out->update (); } } void MainWindow::on_trig_sideButton_clicked() { if (level.trig_side_mode == both_sides) { level.trig_side_mode = one_side; ui->trig_sideButton->setDown (1); } else { level.trig_side_mode = both_sides; ui->trig_sideButton->setDown (0); } } void MainWindow::on_colorButoon_clicked() { QColorDialog *colordialog = new QColorDialog (this); QObject::connect(colordialog, &QColorDialog::colorSelected, this, &MainWindow::on_color_selected); colordialog->show(); } void MainWindow::on_color_selected (const QColor &newcolor) { level.wall_color[0] = newcolor.redF (); level.wall_color[1] = newcolor.greenF (); level.wall_color[2] = newcolor.blueF (); level.cur_texture_index = -1; ui->texture_label->clear (); } void MainWindow::on_actionRevert_chandes_triggered() { print_console ("ctrlz"); level.ctrl_z (); ogl_out->update (); } void MainWindow::on_sel_textureButton_clicked() { std::string tex_filename = QFileDialog::getOpenFileName (this, "Open level", "./textures").toUtf8 ().constData (); size_t last_slash_idx = tex_filename.find_last_of("\\/"); if (std::string::npos != last_slash_idx) { tex_filename.erase(0, last_slash_idx + 1); } level.select_texture (tex_filename); ui->texture_label->clear (); ui->texture_label->setText (QString::fromStdString (tex_filename)); }
28.226766
129
0.613591
ErrrOrrr503
198d0718efc73c0de5a00ae19fa727d5b91c2511
466
cpp
C++
cpp1st/week08/taehwan/example_regex_error.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
2
2022-03-10T10:18:23.000Z
2022-03-16T15:37:22.000Z
cpp1st/week08/taehwan/example_regex_error.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
8
2022-03-09T16:14:47.000Z
2022-03-28T15:35:17.000Z
cpp1st/week08/taehwan/example_regex_error.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
4
2022-03-08T00:22:29.000Z
2022-03-12T13:22:43.000Z
/// /// Copyright 2022 PentaDevs /// Author: Taehwan Kim /// Contents: Examples of regex_error (referenced from CppReference) #include <regex> #include <iostream> int main() { try { std::regex re("[a-b][a"); } catch (const std::regex_error& e) { std::cout << "regex_error caught: " << e.what() << '\n'; if (e.code() == std::regex_constants::error_brack) { std::cout << "The code was error_brack\n"; } } }
23.3
68
0.564378
th4inquiry
198f28e392557799ceb6a4a19f49e5e08e2c58a7
7,134
cpp
C++
src/rc_utils.cpp
mjdousti/therminator
d706ab43ac97a4266ce19618b1e35d4e0245cd5b
[ "Xnet", "X11", "RSA-MD" ]
3
2019-09-26T00:09:50.000Z
2021-08-09T03:19:38.000Z
src/rc_utils.cpp
mjdousti/therminator
d706ab43ac97a4266ce19618b1e35d4e0245cd5b
[ "Xnet", "X11", "RSA-MD" ]
null
null
null
src/rc_utils.cpp
mjdousti/therminator
d706ab43ac97a4266ce19618b1e35d4e0245cd5b
[ "Xnet", "X11", "RSA-MD" ]
5
2015-08-03T01:41:39.000Z
2021-01-06T18:14:11.000Z
/** * * Copyright (C) 2021 Mohammad Javad Dousti, Qing Xie, Mahdi Nazemi, * and Massoud Pedram. All rights reserved. * * Please refer to the LICENSE file for terms of use. * */ #include "headers/rc_utils.hpp" #include <omp.h> VALUE RCutils::calcThermalConductivity(VALUE k, VALUE thickness, VALUE area) { ASSERT(thickness != 0, "The thickness of an element cannot be zero."); return k * area / thickness; } VALUE RCutils::calcSubComponentCapacitance(SubComponent *sc) { auto volume = sc->getLength() * sc->getWidth() * sc->getHeight(); if (volume == 0) cout << sc->getName() << " has nil volume.\n"; else if (sc->getComponent()->getMaterial()->getSpecificHeat() == 0) cout << sc->getName() << " has nil specific heat.\n"; else if (sc->getComponent()->getMaterial()->getDensity() == 0) cout << sc->getName() << " has nil density.\n"; return C_FACTOR * sc->getComponent()->getMaterial()->getSpecificHeat() * sc->getComponent()->getMaterial()->getDensity() * volume; } VALUE RCutils::calcAmbientResistance(VALUE h, VALUE area) { return 1 / (h * area); } VALUE RCutils::overallParallelConductivity(VALUE k1, VALUE k2) { return (k1 * k2) / (k1 + k2); } bool RCutils::touchesAirInXDir(SubComponent *sc, Device *device) { if (utils::eq(sc->getX(), device->getX()) || utils::eq(sc->getX() + sc->getLength(), device->getX() + device->getLength())) return true; else return false; } bool RCutils::touchesAirInYDir(SubComponent *sc, Device *device) { if (utils::eq(sc->getY(), device->getY()) || utils::eq(sc->getY() + sc->getWidth(), device->getY() + device->getWidth())) { return true; } else { return false; } } bool RCutils::touchesAirFromTopBot(SubComponent *sc, Device *device) { if (utils::eq(sc->getZ(), device->getZ()) || utils::eq(sc->getZ() + sc->getHeight(), device->getZ() + device->getHeight())) return true; else return false; } VALUE RCutils::calcConductanceToAmbient(SubComponent *sc, Device *device) { VALUE commonArea; VALUE t1 = 0.0; VALUE k = 0.0; VALUE Kx = 0.0, Ky = 0.0, Kz = 0.0, Rx, Ry, Rz; // Unit: W/m^2/K; Source: // <http://www.engineeringtoolbox.com/convective-heat-transfer-d_430.html> VALUE h = 10 * 1.15; if (touchesAirFromTopBot(sc, device)) { // Touches air from top or bottom t1 = sc->getHeight() / 2; commonArea = sc->getLength() * sc->getWidth(); k = sc->getComponent()->getMaterial()->getNormalConductivity(); Kz = RCutils::calcThermalConductivity(k, t1, commonArea); Rz = RCutils::calcAmbientResistance(h, commonArea); Kz = RCutils::overallParallelConductivity(Kz, 1 / Rz); } if (touchesAirInXDir(sc, device)) { // Touches air from the X side t1 = sc->getLength() / 2; commonArea = sc->getWidth() * sc->getHeight(); // Setting the k1 value to the proper value if the planar conductivity // differs from the normal conductivity if (sc->getComponent()->getMaterial()->hasPlanarConductivity()) { k = sc->getComponent()->getMaterial()->getPlanarConductivity(); } else { k = sc->getComponent()->getMaterial()->getNormalConductivity(); } Kx = RCutils::calcThermalConductivity(k, t1, commonArea); Rx = RCutils::calcAmbientResistance(h, commonArea); Kx = RCutils::overallParallelConductivity(Kx, 1 / Rx); } if (touchesAirInYDir(sc, device)) { // Touches air from the Y side t1 = sc->getWidth() / 2; commonArea = sc->getLength() * sc->getHeight(); // Setting the k1 value to the proper value if the planar conductivity // differs from the normal conductivity if (sc->getComponent()->getMaterial()->hasPlanarConductivity()) { k = sc->getComponent()->getMaterial()->getPlanarConductivity(); } else { k = sc->getComponent()->getMaterial()->getNormalConductivity(); } Ky = RCutils::calcThermalConductivity(k, t1, commonArea); Ry = RCutils::calcAmbientResistance(h, commonArea); Ky = RCutils::overallParallelConductivity(Ky, 1 / Ry); } return Kx + Ky + Kz; } VALUE RCutils::calcCommonConductance(SubComponent *sc1, SubComponent *sc2) { VALUE commonArea; VALUE t1 = 0, t2 = 0; VALUE k1, k2; // common area in the Y & Z planes VALUE commonX, commonY, commonZ; commonX = min(sc1->getX() + sc1->getLength(), sc2->getX() + sc2->getLength()) - max(sc1->getX(), sc2->getX()); commonY = min(sc1->getY() + sc1->getWidth(), sc2->getY() + sc2->getWidth()) - max(sc1->getY(), sc2->getY()); commonZ = min(sc1->getZ() + sc1->getHeight(), sc2->getZ() + sc2->getHeight()) - max(sc1->getZ(), sc2->getZ()); if (commonZ > 0 && commonY > 0 && (utils::eq(sc1->getX() + sc1->getLength(), sc2->getX()) || utils::eq(sc2->getX() + sc2->getLength(), sc1->getX()))) { commonArea = commonY * commonZ; t1 = sc1->getLength() / 2; t2 = sc2->getLength() / 2; // using planar thermal conductivity if the material has different value for // it if (sc1->getComponent()->getMaterial()->hasPlanarConductivity()) { k1 = sc1->getComponent()->getMaterial()->getPlanarConductivity(); } else { k1 = sc1->getComponent()->getMaterial()->getNormalConductivity(); } if (sc2->getComponent()->getMaterial()->hasPlanarConductivity()) { k2 = sc2->getComponent()->getMaterial()->getPlanarConductivity(); } else { k2 = sc2->getComponent()->getMaterial()->getNormalConductivity(); } } else if (commonX > 0 && commonZ > 0 && (utils::eq(sc1->getY() + sc1->getWidth(), sc2->getY()) || utils::eq(sc2->getY() + sc2->getWidth(), sc1->getY()))) { commonArea = commonX * commonZ; t1 = sc1->getWidth() / 2; t2 = sc2->getWidth() / 2; // using planar thermal conductivity if the material has different value for // it if (sc1->getComponent()->getMaterial()->hasPlanarConductivity()) { k1 = sc1->getComponent()->getMaterial()->getPlanarConductivity(); } else { k1 = sc1->getComponent()->getMaterial()->getNormalConductivity(); } if (sc2->getComponent()->getMaterial()->hasPlanarConductivity()) { k2 = sc2->getComponent()->getMaterial()->getPlanarConductivity(); } else { k2 = sc2->getComponent()->getMaterial()->getNormalConductivity(); } } else if (commonX > 0 && commonY > 0 && (utils::eq(sc1->getZ() + sc1->getHeight(), sc2->getZ()) || utils::eq(sc2->getZ() + sc2->getHeight(), sc1->getZ()))) { commonArea = commonX * commonY; t1 = sc1->getHeight() / 2; t2 = sc2->getHeight() / 2; // using normal conductivity since it is in the vertical direction k1 = sc1->getComponent()->getMaterial()->getNormalConductivity(); k2 = sc2->getComponent()->getMaterial()->getNormalConductivity(); } else { commonArea = 0; return 0; } auto K1 = RCutils::calcThermalConductivity(k1, t1, commonArea); auto K2 = RCutils::calcThermalConductivity(k2, t2, commonArea); return RCutils::overallParallelConductivity(K1, K2); }
35.492537
80
0.624895
mjdousti
199034cd2c78220b6d27610356901fd7f2406bb0
1,685
cpp
C++
G53GRA.Framework/Code/Sky.cpp
baisebaoma/COMP3069CW
731627a4d5d961435f3c4064e2c789db6a70423a
[ "MIT" ]
null
null
null
G53GRA.Framework/Code/Sky.cpp
baisebaoma/COMP3069CW
731627a4d5d961435f3c4064e2c789db6a70423a
[ "MIT" ]
null
null
null
G53GRA.Framework/Code/Sky.cpp
baisebaoma/COMP3069CW
731627a4d5d961435f3c4064e2c789db6a70423a
[ "MIT" ]
null
null
null
#include "Sky.hpp" #include <iostream> #include <cmath> // TODO: ็Žฐๅœจๆ˜ฏๅ…จๅ†™ๅœจSky้‡Œ๏ผŒๅˆฐๆ—ถๅ€™ๅพ—ๅˆ†ๅผ€ๆˆๅ„ไธชไธœ่ฅฟใ€‚๏ผˆrefactor๏ผ‰ #include <stdio.h> #include <stdlib.h> // MAKE SURE WE INITIALISE OUR VARIABLES Sky::Sky() : keyframe(-1), animateTime(0.0), animateRotation(0.0), animateTranslation(0.0), interpA(0.0), interpB(0.0), interpTime(0.0){} Sky::Sky(const std::string& filename) : Sky() { texID = Scene::GetTexture(filename); } /// Update the Skys position in releation to delta time by use of mathematical /// mechanics, eq SUVAT void Sky::Update(const double& deltaTime) { // update the time and rotation steps animateTime += static_cast<float>(deltaTime); // animateRotation = animateTime*10;// animateRotation += static_cast<float>(deltaTime); } void Sky::drawPlane(GLfloat R, GLfloat G, GLfloat B, GLfloat size){ glColor3f(R, G, B); glEnable(GL_TEXTURE_2D); // Enable setting the colour of the material the cube is made from // as well as the material for blending. // glEnable(GL_COLOR_MATERIAL); // Tell openGL which texture buffer to use glBindTexture(GL_TEXTURE_2D, texID); glBegin(GL_POLYGON); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1*size, 0, -1*size); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1*size, 0, 1*size); glTexCoord2f(0.0f, 0.0f); glVertex3f(size, 0, size); glTexCoord2f(0.0f, 1.0f); glVertex3f(size, 0, -1*size); glEnd(); glDisable(GL_TEXTURE_2D); } void Sky::Display(void){ glPushMatrix(); glRotatef(animateRotation,0,1,0); // Sky glPushMatrix(); glTranslatef(5, 0, 5); drawPlane(0.7f, 0.7f, 0.7f, 20); glPopMatrix(); glPopMatrix(); }
24.42029
95
0.659347
baisebaoma
19963cc8374e09c591274312c5cda381f5d7e39d
12,753
cc
C++
src/core/user_interface.cc
juliomarcelopicardo/Wolfy2D
34cf5afca05e1f1cf57ad7899152efe09391ac7b
[ "MIT" ]
null
null
null
src/core/user_interface.cc
juliomarcelopicardo/Wolfy2D
34cf5afca05e1f1cf57ad7899152efe09391ac7b
[ "MIT" ]
null
null
null
src/core/user_interface.cc
juliomarcelopicardo/Wolfy2D
34cf5afca05e1f1cf57ad7899152efe09391ac7b
[ "MIT" ]
null
null
null
/** Copyright Julio Marcelo Picardo 2017-18, all rights reserved. * * @project Wolfy2D - Including JMP scripting language. * @author Julio Marcelo Picardo <juliomarcelopicardo@gmail.com> */ #include "core/user_interface.h" #include "GLFW/glfw3.h" #include "imgui.h" #include "imgui_dock.h" #include "core/core.h" #include <fstream> namespace W2D { /******************************************************************************* *** Constructor And Destructor *** *******************************************************************************/ UserInterface::UserInterface() { top_bar_height_ = 0.0f; bottom_bar_height_ = 30.0f; save_mode_ = 0; log_.set_active(true); } UserInterface::~UserInterface() {} /******************************************************************************* *** Public Methods *** *******************************************************************************/ void UserInterface::init() { setupInputKeys(); setupColors(); setupStyle(); setupUsersGuideText(); } void UserInterface::update() { updateTopBar(); updateEditorLayout(); updateBottomBar(); } /******************************************************************************* *** Private Methods *** *******************************************************************************/ void UserInterface::setupColors() const { ImVec4* colors = ImGui::GetStyle().Colors; colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.59f, 0.59f, 0.59f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 1.00f); colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 1.00f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f); colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); 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.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_SliderGrab] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f); colors[ImGuiCol_Button] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ButtonActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f); colors[ImGuiCol_Header] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_HeaderActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f); colors[ImGuiCol_Separator] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.95f); colors[ImGuiCol_CloseButton] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); colors[ImGuiCol_PlotLines] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); } void UserInterface::setupInputKeys() const { ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; } void UserInterface::setupStyle() const { ImGuiStyle& style = ImGui::GetStyle(); // Editor style style.FrameRounding = 6.0f; style.WindowRounding = 7.0f; style.ChildRounding = 0.0f; style.ScrollbarRounding = 9.0f; style.GrabRounding = 6.0f; style.PopupRounding = 16.0f; style.WindowPadding = { 8.0f, 8.0f }; style.FramePadding = { 4.0f, 3.0f }; style.TouchExtraPadding = { 0.0f, 0.0f }; style.ItemSpacing = { 8.0f, 4.0f }; style.ItemInnerSpacing = { 4.0f, 4.0f }; style.IndentSpacing = 24.0f; style.ScrollbarSize = 15.0f; style.GrabMinSize = 12.0f; style.WindowBorderSize = 1.0f; style.ChildBorderSize = 1.0f; style.PopupBorderSize = 1.0f; style.FrameBorderSize = 0.0f; style.WindowTitleAlign = { 0.0f, 0.5f }; style.ButtonTextAlign = { 0.5f, 0.5f }; } void UserInterface::setupUsersGuideText() { std::ifstream ug(kUsersGuideFilename); std::string temp{ std::istreambuf_iterator<char>(ug), std::istreambuf_iterator<char>() }; users_guide_text_ = temp; } void UserInterface::updateTopBar() { auto& core = Core::instance(); if (ImGui::BeginMainMenuBar()) { top_bar_height_ = ImGui::GetWindowSize().y; bottom_bar_height_ = top_bar_height_ + 8.0f; if (ImGui::BeginMenu("Application")) { if (ImGui::MenuItem("Quit", "ESC")) { core.window_.is_opened_ = false; } showLastItemDescriptionTooltip("Exit application and closes window"); ImGui::EndMenu(); } if (ImGui::BeginMenu("Editor")) { if (ImGui::MenuItem("Save Layout")) { ImGui::SaveDock(); log_.AddLog_I("Editor layout style saved."); } showLastItemDescriptionTooltip("Saves the editor layout in a configuration file.\n" "So next time that we execute the program, this last\n" "configuration saved will be loaded."); ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } } void UserInterface::updateEditorLayout() { auto& core = Core::instance(); ImVec2 editor_size = ImGui::GetIO().DisplaySize; editor_size.y -= top_bar_height_ + bottom_bar_height_; ImGui::SetWindowPos("UserInterface", { 0.0f, top_bar_height_ }); ImGui::SetWindowSize("UserInterface", editor_size); const ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove; if (ImGui::Begin("UserInterface", nullptr, window_flags)) { // dock layout by hard-coded or .ini file ImGui::BeginDockspace(); updateSceneDock(); updateScriptDock(); updateHierarchyDock(); updateUsersGuideDock(); /* if (ImGui::BeginDock("EditorConfig")) { ImGui::ShowStyleEditor(); } ImGui::EndDock(); */ if (ImGui::BeginDock("Log")) { log_.Draw("Wolfy2D log"); } ImGui::EndDock(); ImGui::EndDockspace(); } ImGui::End(); } void UserInterface::updateBottomBar() const { const ImVec2 display_size = ImGui::GetIO().DisplaySize; const ImGuiWindowFlags flags = ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings; ImGui::SetNextWindowPos({ 0.0f, display_size.y - bottom_bar_height_ }, ImGuiSetCond_Always); ImGui::SetNextWindowSize({ display_size.x, bottom_bar_height_ }, ImGuiSetCond_Always); ImGui::Begin("statusbar", nullptr, flags); ImGui::TextColored({ 202,81,0,255 }, "Wolfy2D & JMP - A Scripting Language for Game Engines"); ImGui::SameLine(); ImGui::Text(" "); ImGui::SameLine(); ImGui::Text("Author: Julio Marcelo Picardo Pena"); ImGui::SameLine(); ImGui::Text(" "); ImGui::SameLine(); ImGui::Text("Contact: juliomarcelopicardo@gmail.com"); ImGui::SameLine(); ImGui::Text(" "); ImGui::SameLine(); ImGui::Text("BSc in Computer Science for Games - Sheffield Hallam University"); ImGui::SameLine(); ImGui::End(); } void UserInterface::updateHierarchyDock() const { if (ImGui::BeginDock("Scene Hierarchy")) { auto& map = Core::instance().sprite_factory_; for (const auto& pair : map) { ImGui::PushID(&pair.second); if (ImGui::TreeNode(pair.first.c_str())) { auto& sprite = map[pair.first]; ImGui::Image((ImTextureID)sprite.textureID(), { 50.0f, 50.0f }); glm::vec2 temp = sprite.position(); if (ImGui::DragFloat2("Position", &temp.x)) { sprite.set_position(temp); } temp = sprite.size(); if (ImGui::DragFloat2("Size", &temp.x)) { sprite.set_size(temp); } temp.x = sprite.rotation(); if (ImGui::DragFloat("Rotation", &temp.x, 0.01f)) { sprite.set_rotation(temp.x); } ImGui::TreePop(); } ImGui::PopID(); } } ImGui::EndDock(); } void UserInterface::updateScriptDock() { auto& core = Core::instance(); std::string text = "Compiles and executes the existing code"; if (ImGui::BeginDock("JMP Scripting Language")) { if (ImGui::Button("Compile")) { log_.AddLog_I("Compiling and executing script..."); core.texture_factory_.clear(); core.sprite_factory_.clear(); core.machine_.reloadFromString(core.script_code_); core.machine_.runFunction("Init()"); } showLastItemDescriptionTooltip(text.c_str()); ImGui::SameLine(); if (ImGui::Button("Save")) { if (save_mode_ == 0) { ImGui::SetClipboardText(core.script_code_); log_.AddLog_I("Script copied to clipboard."); } else { std::ofstream file(kScriptFilename, std::ios_base::out); if (file.is_open()) { file << core.script_code_; } file.close(); // log std::string info = "Script saved into file: \""; info = info + kScriptFilename; info = info + '\"'; log_.AddLog_I(info); } } text = "Save mode: \nClipbard - Will copy the whole script text into the clipboard\nFile - Save and overwrite file \""; text = text + kScriptFilename; text = text + '\"'; showLastItemDescriptionTooltip(text.c_str()); ImGui::SameLine(); ImGui::Combo("##destination", (int*)&save_mode_, "Clipboard\0File\0"); ImGui::InputTextMultiline("", Core::instance().script_code_, SCRIPT_CODE_MAX_LENGTH, ImGui::GetContentRegionAvail()); } ImGui::EndDock(); } void UserInterface::updateUsersGuideDock() const { if (ImGui::BeginDock("User's Guide")) { ImGui::TextUnformatted(users_guide_text_.c_str()); } ImGui::EndDock(); } void UserInterface::updateSceneDock() const { if (ImGui::BeginDock("Scene")) { ImGui::Image((ImTextureID)Core::instance().window_.frame_buffer_.texture(), ImGui::GetContentRegionAvail(), ImVec2(0, 1), ImVec2(1, 0)); } ImGui::EndDock(); } void UserInterface::showLastItemDescriptionTooltip(const char* description) const { if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); ImGui::TextUnformatted(description); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } } }; /* W2D */
35.035714
140
0.632165
juliomarcelopicardo
199b46ae2e5d531d246a12762b8d9930fa3aafba
7,620
cpp
C++
Data Structures/Heaps/Fibonacci Heap.cpp
Rand0mUsername/Algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
2
2020-01-10T14:12:03.000Z
2020-05-28T19:12:21.000Z
Data Structures/Heaps/Fibonacci Heap.cpp
Rand0mUsername/algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
null
null
null
Data Structures/Heaps/Fibonacci Heap.cpp
Rand0mUsername/algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
1
2022-01-11T03:14:48.000Z
2022-01-11T03:14:48.000Z
// RandomUsername (Nikola Jovanovic) // Fibonacci Heap // Source: CLRS, Third Edition #include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <string> struct Node { Node* left; Node* right; Node* parent; Node* first_child; int key; int degree; bool marked; explicit Node(int key) { this -> key = key; this -> degree = 0; this -> parent = this -> first_child = NULL; this -> left = this -> right = this; this -> marked = false; } }; class FibonacciHeap { public: FibonacciHeap(); Node* FindMin(); void DeleteMin(); void Insert(Node* curr); void DecreaseKey(Node* curr, int new_key); void Merge(FibonacciHeap* h); int GetSize(); void Draw(std::string name); private: void LinkRootNodes(Node* top, Node* bottom); void MakeRootNode(Node* curr); void PrintToDot(Node* curr, std::ofstream& dot_file); Node* min_node; int size; }; FibonacciHeap::FibonacciHeap() { size = 0; min_node = NULL; } Node* FibonacciHeap::FindMin() { return min_node; } void FibonacciHeap::DeleteMin() { if (size == 0) { return; } if (size == 1) { delete min_node; min_node = NULL; size = 0; return; } Node* child = min_node -> first_child; int deg = min_node -> degree; for (int i = 0; i < deg; i++) { Node* next = child -> right; MakeRootNode(child); child = next; } int D = 2 * ceil(log2(size)); Node* tmp[D]; for (int i = 0; i < D; i++) { tmp[i] = NULL; } Node* curr = min_node -> right; while (curr != min_node) { Node* next = curr -> right; int deg = curr -> degree; while (tmp[deg] != NULL) { Node* other = tmp[deg]; if (curr -> key > other -> key) { std::swap(curr, other); } LinkRootNodes(curr, other); tmp[deg++] = NULL; } tmp[deg] = curr; curr = next; } delete min_node; // Rebuild the heap size--; Node* first; Node* last; first = last = min_node = NULL; for (int i = 0; i < D; i++) { if (tmp[i] != NULL) { if (first == NULL) { min_node = first = last = tmp[i]; } else { if (tmp[i] -> key < min_node -> key) { min_node = tmp[i]; } last -> right = tmp[i]; tmp[i] -> left = last; last = tmp[i]; } } } if (first != NULL) { last -> right = first; first -> left = last; } } void FibonacciHeap::Insert(Node* curr) { FibonacciHeap* unit_heap = new FibonacciHeap(); unit_heap -> min_node = curr; unit_heap -> size = 1; Merge(unit_heap); delete unit_heap; } void FibonacciHeap::DecreaseKey(Node* curr, int new_key) { curr -> key = new_key; Node* parent = curr -> parent; if (parent != NULL && curr -> key < parent -> key) { // Cut this child and update min node MakeRootNode(curr); curr -> marked = false; if (curr -> key < min_node -> key) { min_node = curr; } // Do a cascading cut curr = parent; while (curr != NULL && curr -> marked) { parent = curr -> parent; MakeRootNode(curr); curr -> marked = false; curr = parent; } if (curr != NULL && curr -> parent != NULL) { curr -> marked = true; } } else if (parent == NULL && curr -> key < min_node -> key) { min_node = curr; } } void FibonacciHeap::Merge(FibonacciHeap* other) { if (other -> size == 0) { return; } if (this -> size == 0) { this -> min_node = other -> min_node; } else { Node* this_right = this -> min_node -> right; Node* other_left = other -> min_node -> left; this -> min_node -> right = other -> min_node; other -> min_node -> left = this -> min_node; this_right -> left = other_left; other_left -> right = this_right; } this -> size += other -> size; } int FibonacciHeap::GetSize() { return size; } // Visualizes the heap using GraphViz. void FibonacciHeap::Draw(std::string name) { std::ofstream dot_file; dot_file.open(name + ".dot"); dot_file << "digraph{\n"; Node* root = min_node; if (root != NULL) { do { PrintToDot(root, dot_file); root = root -> right; } while (root != min_node); } dot_file << "}\n"; dot_file.close(); std::string command = "dot -Tpng " + name + ".dot -o " + name + ".png"; system(command.c_str()); } void FibonacciHeap::LinkRootNodes(Node* top, Node* bottom) { bottom -> left -> right = bottom -> right; bottom -> right -> left = bottom -> left; Node* child = top -> first_child; bottom -> parent = top; top -> first_child = bottom; bottom -> left = bottom -> right = NULL; if (child != NULL) { bottom -> right = child; child -> left = bottom; } top -> degree++; top -> marked = false; } void FibonacciHeap::MakeRootNode(Node* curr) { if (curr -> left != NULL) { curr -> left -> right = curr -> right; } if (curr -> right != NULL) { curr -> right -> left = curr -> left; } if (curr -> parent != NULL) { if (curr -> parent -> first_child == curr) { curr -> parent -> first_child = curr -> right; } curr -> parent -> degree--; } curr -> parent = NULL; Node* min_right = min_node -> right; curr -> right = min_right; min_right -> left = curr; curr -> left = min_node; min_node -> right = curr; } void FibonacciHeap::PrintToDot(Node* curr, std::ofstream& dot_file) { if (curr == NULL) { return; } dot_file << curr -> key << "[label=\"" << curr -> key << "\""; if (curr -> marked) { dot_file << " color=red fontcolor=red"; } dot_file << "];\n"; Node* child = curr -> first_child; if (child == NULL) { dot_file << "null_l_" << curr -> key << "[shape=point];\n"; dot_file << curr -> key << " -> " << "null_l_" << curr -> key << "\n"; } else { while (child != NULL) { PrintToDot(child, dot_file); dot_file << curr -> key << " -> " << child -> key << "\n"; child = child -> right; } } } int main() { FibonacciHeap* heap = new FibonacciHeap(); heap -> Insert(new Node(4)); heap -> DeleteMin(); heap -> DeleteMin(); heap -> Insert(new Node(4)); heap -> Insert(new Node(5)); heap -> Insert(new Node(16)); heap -> Insert(new Node(26)); heap -> Insert(new Node(7)); Node* n11 = new Node(11); heap -> Insert(n11); Node* n17 = new Node(17); heap -> Insert(n17); Node* n12 = new Node(12); heap -> Insert(n12); heap -> Insert(new Node(10)); Node* n99 = new Node(99); heap -> Insert(n99); heap -> Insert(new Node(33)); heap -> Insert(new Node(95)); heap -> Insert(new Node(14)); heap -> Insert(new Node(6)); heap -> Insert(new Node(9)); heap -> Insert(new Node(96)); heap -> Insert(new Node(19)); heap -> Insert(new Node(8)); heap -> Draw("fibheap_full"); heap -> DeleteMin(); std::cout << "Size: " << heap -> GetSize(); Node* min_node = heap -> FindMin(); if (min_node != NULL) { std::cout << " Min: " << min_node -> key << std::endl; } else { std::cout << " Empty" << std::endl; } heap -> Draw("fibheap_del"); heap -> DeleteMin(); std::cout << "Size: " << heap -> GetSize(); min_node = heap -> FindMin(); if (min_node != NULL) { std::cout << " Min: " << min_node -> key << std::endl; } else { std::cout << " Empty" << std::endl; } heap -> Draw("fibheap_del2"); heap -> DecreaseKey(n11, 3); heap -> DecreaseKey(n99, 0); heap -> DecreaseKey(n17, 2); heap -> DecreaseKey(n12, 1); // Cascade heap -> Draw("fibheap_dec"); heap -> DeleteMin(); heap -> DeleteMin(); heap -> DeleteMin(); heap -> DeleteMin(); heap -> DeleteMin(); heap -> Draw("fibheap_end"); return 0; }
25.065789
74
0.56168
Rand0mUsername
19a273935ae0662816c7a68f7d39f79db444aea3
7,301
hpp
C++
src/byl_avl_tree.hpp
superboy0712/toy_template_library
4b62a52bf0789472807206997253b0cc7cdd8102
[ "MIT" ]
null
null
null
src/byl_avl_tree.hpp
superboy0712/toy_template_library
4b62a52bf0789472807206997253b0cc7cdd8102
[ "MIT" ]
null
null
null
src/byl_avl_tree.hpp
superboy0712/toy_template_library
4b62a52bf0789472807206997253b0cc7cdd8102
[ "MIT" ]
null
null
null
// // Created by yulong on 3/31/17. // #ifndef BYL_TEMPLATE_LIBRARY_AVL_TREE_H #define BYL_TEMPLATE_LIBRARY_AVL_TREE_H #include "byl_bst.hpp" #include <cstddef> namespace byl { template<typename T> struct avl_tree; template<typename T> struct avl_node { typedef T value_type; typedef size_t size_type;; friend struct avl_tree<T>; typedef avl_node * node_ptr; node_ptr left, right, parent; T m_data; int height; size_type n_size; avl_node(const value_type& v = value_type(), int h = 0) : left(NULL), right(NULL), parent(NULL) , m_data(v), height(h), n_size(1) {} }; template<typename T> struct avl_tree : public bst<T, avl_node> { typedef T value_type; typedef bst<T, avl_node> base_tree; typedef avl_node<T> node_type; typedef avl_node<T> *node_pointer; typedef typename bst<T, avl_node>::size_type size_type; inline int max(int a, int b) { return (a > b) ? a : b; } inline int height(node_pointer p) { return p? p->height : (-1); } inline void update_height(node_pointer p) { p->height = 1 + max(height(p->left), height(p->right)); } void update_height_above(node_pointer p) { if(!p) return; while(p->parent) { update_height(p->parent); p = p->parent; } } inline int bal_fac(const node_pointer p) { return (height(p->left) - height(p->right)); } inline bool is_balenced(const node_pointer p) { int fac = bal_fac(p); return (-2 < fac && fac < 2); } inline node_pointer connect34( node_pointer a, node_pointer b, node_pointer c, node_pointer t0, node_pointer t1, node_pointer t2, node_pointer t3) { a->left = t0; if(t0) t0->parent = a; a->right = t1; if(t1) t1->parent = a; update_height(a); update_size(a); c->left = t2; if(t2) t2->parent = c; c->right = t3; if(t3) t3->parent = c; update_height(c); update_size(c); b->left = a; a->parent = b; b->right = c; c->parent = b; update_height(b); update_size(b); return b; } inline bool is_lchild(node_pointer p) { return (p->parent->left == p); } inline bool is_rchild(node_pointer p) { return (p->parent->right == p); } inline node_pointer rebalenced_at(node_pointer g, node_pointer p, node_pointer v) { // assert(v); if (is_lchild(p)) { if(is_lchild(v)) { p->parent = g->parent; return connect34(v, p, g, v->left, v->right, p->right, g->right); } else { v->parent = g->parent; return connect34(p, v, g, p->left, v->left, v->right, g->right); } } else { if(is_rchild(v)) { p->parent = g->parent; return connect34(g, p, v, g->left, p->left, v->left, v->right); } else { v->parent = g->parent; return connect34(g, v, p, g->left, v->left, v->right, p->right); } } } inline node_pointer *from_parent_to(node_pointer p) { return &((p == this->root()) ? this->m_dummy_super_root.left : ( (is_lchild(p)) ? p->parent->left : p->parent->right) ); } inline size_type size_of_node(node_pointer p) { return p ? p->n_size : 0; } inline void update_size(node_pointer p) { if(!p) return; p->n_size = size_of_node(p->left) + size_of_node(p->right) + 1; } inline void update_size_above(node_pointer p) { while (p->parent) { update_size(p->parent); p = p->parent; } } node_pointer insert(const value_type& val) { node_pointer *t, p; t = this->search(val, &p); if(*t) { (*t)->m_data = val; return *t; } *t = new node_type(val); (*t)->parent = p; this->m_size++; update_height(p); update_size(p); update_size_above(p); node_pointer v = *t; for (node_pointer g = p->parent; g && g!=&(this->m_dummy_super_root); v = p, p = g, g = g->parent) { if (!is_balenced(g)) { *from_parent_to(g) = rebalenced_at(g, p, v); break; } else { update_height(g); } } return *t; } inline node_pointer taller_child(node_pointer p) { return ( (height(p->left) > height(p->right)) ? p->left : ( (height(p->left) < height(p->right)) ? p->right : (is_lchild(p) ? p->left : p->right))); } bool remove(const value_type& val) { node_pointer *r, g; r = this->search(val, &g); if(!*r) return false; this->remove_at(r, &g); update_size(g); update_size_above(g); while (g && g!=&(this->m_dummy_super_root)) { update_height(g); if (!is_balenced(g)) { node_pointer p = taller_child(g); node_pointer v = taller_child(p); *from_parent_to(g) = rebalenced_at(g, p, v); } g = g->parent; } return true; } bool remove_by_rank(size_type rank) { node_pointer *r, g; r = this->select(rank, &g); if(!r || !*r) return false; this->remove_at(r, &g); update_size(g); update_size_above(g); while (g && g!=&(this->m_dummy_super_root)) { update_height(g); if (!is_balenced(g)) { node_pointer p = taller_child(g); node_pointer v = taller_child(p); *from_parent_to(g) = rebalenced_at(g, p, v); } g = g->parent; } return true; } inline node_pointer *select(size_type rank, node_pointer *parent) { if(rank >= this->m_size) return NULL; *parent = &(this->m_dummy_super_root); node_pointer* ret = &(this->m_dummy_super_root.left); size_t r = size_of_node((*ret)->left); while(r != rank) { if (rank < r) { *parent = *ret; ret = &(*ret)->left; r = r - size_of_node((*ret)->right) - 1; } else if (rank > r) { *parent = *ret; ret = &(*ret)->right; r = r + size_of_node((*ret)->left) + 1; } } return ret; } size_type rank(value_type &val) { node_pointer p = this->root(); size_t r = size_of_node(p->left); while(p) { if (p->m_data > val) { p = p->left; r = r - size_of_node(p? p->right : NULL) - 1; } else if (p->m_data < val) { p = p->right; r = r + size_of_node(p? p->left : NULL) + 1; } else { return r; } } return r; // if r = -1 or size, then seach failed } const value_type& operator [](size_type rank) { node_pointer *q, p; q = select(rank, &p); return (*q)->m_data; } }; }//namespace btl #endif //BYL_TEMPLATE_LIBRARY_AVL_TREE_H
31.200855
108
0.506506
superboy0712
19ac69b353212e5cb772c9447e2512f70e77bf4a
243
cpp
C++
24_qstackedwidget/src/pessoa.cpp
josersi/qt_cppmaster
62e8499c1f17463bd4209ac61ae4fc8d49da69e4
[ "MIT" ]
1
2018-09-01T05:57:29.000Z
2018-09-01T05:57:29.000Z
24_qstackedwidget/src/pessoa.cpp
josersi/qt_cppmaster
62e8499c1f17463bd4209ac61ae4fc8d49da69e4
[ "MIT" ]
null
null
null
24_qstackedwidget/src/pessoa.cpp
josersi/qt_cppmaster
62e8499c1f17463bd4209ac61ae4fc8d49da69e4
[ "MIT" ]
1
2019-09-26T01:45:10.000Z
2019-09-26T01:45:10.000Z
#include "pessoa.h" Pessoa::Pessoa(QObject *parent) : QObject(parent) { } QString Pessoa::getNome() const { return nome; } void Pessoa::setNome(const QString &value) { nome = value; emit nomeChanged(nome); }
12.789474
50
0.613169
josersi
30abe44edfcc28fa640af9703d47dcf0c8fc614e
600
cpp
C++
3D-TV/PerfTimer.cpp
TheByteKitchen/Kinect_client_server
47bd066199f5b112b476e4d34ad333a535baa314
[ "MS-PL" ]
null
null
null
3D-TV/PerfTimer.cpp
TheByteKitchen/Kinect_client_server
47bd066199f5b112b476e4d34ad333a535baa314
[ "MS-PL" ]
null
null
null
3D-TV/PerfTimer.cpp
TheByteKitchen/Kinect_client_server
47bd066199f5b112b476e4d34ad333a535baa314
[ "MS-PL" ]
null
null
null
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" #include "PerfTimer.h" // Initialize the resolution of the timer LARGE_INTEGER PerfTimer::m_freq = \ (QueryPerformanceFrequency(&PerfTimer::m_freq), PerfTimer::m_freq); // Calculate the overhead of the timer LONGLONG PerfTimer::m_overhead = PerfTimer::GetOverhead();
37.5
77
0.743333
TheByteKitchen
30acddda17fe21c4369a615ea1200d62f0b10f6d
2,174
cpp
C++
Engine/Platforms/Public/Tools/GPUThreadHelper.cpp
azhirnov/GraphicsGenFramework-modular
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
12
2017-12-23T14:24:57.000Z
2020-10-02T19:52:12.000Z
Engine/Platforms/Public/Tools/GPUThreadHelper.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
Engine/Platforms/Public/Tools/GPUThreadHelper.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' #include "Engine/Platforms/Public/Tools/GPUThreadHelper.h" namespace Engine { namespace PlatformTools { /* ================================================= FindGraphicsThread ================================================= */ ModulePtr GPUThreadHelper::FindGraphicsThread (GlobalSystemsRef gs) { using MsgList_t = ModuleMsg::MessageListFrom< GpuMsg::ThreadBeginFrame, GpuMsg::ThreadEndFrame, GpuMsg::SubmitCommands, GpuMsg::GetDeviceInfo, GpuMsg::GetGraphicsModules, GpuMsg::GetGraphicsSettings >; using EventList_t = ModuleMsg::MessageListFrom< GpuMsg::DeviceCreated, GpuMsg::DeviceBeforeDestroy >; return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >(); } /* ================================================= FindComputeThread ================================================= */ ModulePtr GPUThreadHelper::FindComputeThread (GlobalSystemsRef gs) { using MsgList_t = ModuleMsg::MessageListFrom< GpuMsg::SubmitCommands, GpuMsg::GetDeviceInfo, GpuMsg::GetGraphicsModules, GpuMsg::GetComputeSettings >; using EventList_t = ModuleMsg::MessageListFrom< GpuMsg::DeviceCreated, GpuMsg::DeviceBeforeDestroy >; return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >(); } /* ================================================= FindVRThread ================================================= */ ModulePtr GPUThreadHelper::FindVRThread (GlobalSystemsRef gs) { using MsgList_t = ModuleMsg::MessageListFrom< GpuMsg::ThreadBeginVRFrame, GpuMsg::ThreadEndVRFrame, GpuMsg::SubmitCommands, GpuMsg::GetVRDeviceInfo, GpuMsg::GetGraphicsModules, GpuMsg::GetGraphicsSettings >; using EventList_t = ModuleMsg::MessageListFrom< GpuMsg::DeviceCreated, GpuMsg::DeviceBeforeDestroy >; return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >(); } } // PlatformTools } // Engine
27.175
77
0.589236
azhirnov
30b4715024c575a744b186b209157ca94722c5af
456
cpp
C++
cpp/inifile/test.cpp
0382/util
b8163f52352341ae7872d95b7f18542f17a94633
[ "MIT" ]
null
null
null
cpp/inifile/test.cpp
0382/util
b8163f52352341ae7872d95b7f18542f17a94633
[ "MIT" ]
null
null
null
cpp/inifile/test.cpp
0382/util
b8163f52352341ae7872d95b7f18542f17a94633
[ "MIT" ]
null
null
null
#include "inifile.hpp" int main() { auto ini = util::inifile("test.ini"); if (!ini.good()) { std::cerr << ini.error() << std::endl; exit(-1); } std::cout << "default section: name = " << ini.get_string("name") << '\n'; ini.set_string("set", "string"); std::cout << "section1: test = " << ini.section("section1").get_int("test") << '\n'; std::cout << "\nshow all data:\n--------------\n"; ini.show(); }
25.333333
88
0.497807
0382
30bef042a86014e87ff42405dc8b3b8c1eb84f9c
974
hpp
C++
admin/dcpromo/exe/configurednsclientpage.hpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/dcpromo/exe/configurednsclientpage.hpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/dcpromo/exe/configurednsclientpage.hpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Copyright (C) 1997 Microsoft Corporation // // dns client configuration page // // 12-22-97 sburns #ifndef CONFIGUREDNSCLIENTPAGE_HPP_INCLUDED #define CONFIGUREDNSCLIENTPAGE_HPP_INCLUDED class ConfigureDnsClientPage : public DCPromoWizardPage { public: ConfigureDnsClientPage(); protected: virtual ~ConfigureDnsClientPage(); // Dialog overrides virtual bool OnNotify( HWND windowFrom, UINT_PTR controlIDFrom, UINT code, LPARAM lParam); virtual void OnInit(); // PropertyPage overrides virtual bool OnSetActive(); // DCPromoWizardPage overrides virtual int Validate(); private: // not defined; no copying allowed ConfigureDnsClientPage(const ConfigureDnsClientPage&); const ConfigureDnsClientPage& operator=(const ConfigureDnsClientPage&); }; #endif // CONFIGUREDNSCLIENTPAGE_HPP_INCLUDED
16.508475
75
0.664271
npocmaka
30c2cccfa2f3c1e5f3de472b340de4aafaedccca
22
cpp
C++
src/mjast_and.cpp
lucasalj/mjcompiler
4404e4ce25f009c60d9f93d0118f33bb1d56b2cf
[ "MIT" ]
null
null
null
src/mjast_and.cpp
lucasalj/mjcompiler
4404e4ce25f009c60d9f93d0118f33bb1d56b2cf
[ "MIT" ]
null
null
null
src/mjast_and.cpp
lucasalj/mjcompiler
4404e4ce25f009c60d9f93d0118f33bb1d56b2cf
[ "MIT" ]
null
null
null
#include <mjast_and.h>
22
22
0.772727
lucasalj
30c8bdffa3d58ca082d8be23f1bc689bfba89220
412
cpp
C++
compiler/crtp/foo/crtp.cpp
lijiansong/deep-learning
7c78061775e47785dfcc4088e93dc4368d16334f
[ "WTFPL" ]
4
2018-05-19T00:55:36.000Z
2020-08-30T23:31:26.000Z
compiler/crtp/foo/crtp.cpp
lijiansong/deep-learning
7c78061775e47785dfcc4088e93dc4368d16334f
[ "WTFPL" ]
null
null
null
compiler/crtp/foo/crtp.cpp
lijiansong/deep-learning
7c78061775e47785dfcc4088e93dc4368d16334f
[ "WTFPL" ]
null
null
null
// Curiously Recurring Template Pattern // static polymorphism #include <iostream> using namespace std; template <typename Child> struct Base { void interface() { static_cast<Child *>(this)->implementation(); } }; struct Derived : Base<Derived> { void implementation() { cerr << "Derived implementation\n"; } }; int main() { Derived d; d.interface(); // Prints "Derived implementation" }
17.166667
51
0.682039
lijiansong
30cf79f21e82a1d1ae95a5e7baa57f4321c29b03
17,711
cpp
C++
src/ringmesh/geomodel/tools/mesh_quality.cpp
ringmesh/RINGMesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
74
2017-10-26T15:40:23.000Z
2022-03-22T09:27:39.000Z
src/ringmesh/geomodel/tools/mesh_quality.cpp
ringmesh/ringmesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
45
2017-10-26T15:54:01.000Z
2021-01-27T10:16:34.000Z
src/ringmesh/geomodel/tools/mesh_quality.cpp
ringmesh/ringmesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
17
2018-03-27T11:31:24.000Z
2022-03-06T18:41:52.000Z
/* * Copyright (c) 2012-2018, Association Scientifique pour la Geologie et ses * Applications (ASGA). 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 ASGA 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 ASGA 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. * * http://www.ring-team.org * * RING Project * Ecole Nationale Superieure de Geologie - GeoRessources * 2 Rue du Doyen Marcel Roubault - TSA 70605 * 54518 VANDOEUVRE-LES-NANCY * FRANCE */ #include <algorithm> #include <geogram/basic/attributes.h> #include <ringmesh/geomodel/core/geomodel.h> #include <ringmesh/geomodel/core/geomodel_mesh_entity.h> #include <ringmesh/geomodel/tools/mesh_quality.h> #include <ringmesh/mesh/mesh_builder.h> #include <ringmesh/mesh/mesh_index.h> #include <ringmesh/mesh/volume_mesh.h> /*! * @author Benjamin Chauvin * This code is inspired from * http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html */ namespace { using namespace RINGMesh; /*! * @brief Computes the radius of the tetrahedron insphere. * * The tetrahedron insphere is the sphere inside the tetrahedron which * is tangent to each tetrahedron facet. * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return the radius of the tetrahedron insphere. */ double tetra_insphere_radius( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 ); double A1 = GEO::Geom::triangle_area( v0, v1, v2 ); double A2 = GEO::Geom::triangle_area( v1, v2, v3 ); double A3 = GEO::Geom::triangle_area( v2, v3, v0 ); double A4 = GEO::Geom::triangle_area( v3, v0, v1 ); ringmesh_assert( A1 + A2 + A3 + A4 > global_epsilon ); return ( 3 * tet_volume ) / ( A1 + A2 + A3 + A4 ); } /*! * @brief Tetrahedron quality based on the insphere and circumsphere radii. * * The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). * For more information, see * <a * href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html"> * TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a> * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return 3 * the insphere radius divided by the circumsphere radius. */ double tet_quality_insphere_radius_by_circumsphere_radius( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { const vec3 tetra_circum_center = GEO::Geom::tetra_circum_center( v0, v1, v2, v3 ); const double tetra_circum_radius = vec3( tetra_circum_center - v0 ).length(); ringmesh_assert( std::abs( tetra_circum_radius - ( tetra_circum_center - v1 ).length() ) < global_epsilon ); ringmesh_assert( std::abs( tetra_circum_radius - ( tetra_circum_center - v2 ).length() ) < global_epsilon ); ringmesh_assert( std::abs( tetra_circum_radius - ( tetra_circum_center - v3 ).length() ) < global_epsilon ); // insphere computation double in_radius = tetra_insphere_radius( v0, v1, v2, v3 ); return 3. * in_radius / tetra_circum_radius; } /*! * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return the maximum of the tetrahedron edge length. */ double max_tet_edge_length( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { std::initializer_list< double > edge_length{ ( v1 - v0 ).length(), ( v2 - v0 ).length(), ( v3 - v0 ).length(), ( v2 - v1 ).length(), ( v3 - v1 ).length(), ( v3 - v2 ).length() }; return std::max( edge_length ); } /*! * @brief Tetrahedron quality based on the insphere radius and the maximum * edge length. * * The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). * For more information see * Du, Q., and D. Wang, 2005, * The optimal centroidal Voronoi tessellations and the gersho's conjecture * in the three-dimensional space, * Computers & Mathematics with Applications, v. 49, no. 9, p. 1355-1373, * <a href="http://doi.org/10.1016/j.camwa.2004.12.008">doi</a>, * <a * href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html"> * TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a> * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return 2 * sqrt( 6 ) * the insphere radius divided by the maximum of the * tetrhedron edge length. */ double tet_quality_insphere_radius_by_max_edge_length( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double in_radius = tetra_insphere_radius( v0, v1, v2, v3 ); double edge_length = max_tet_edge_length( v0, v1, v2, v3 ); return 2 * std::sqrt( 6. ) * in_radius / edge_length; } /*! * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return the sum of the square tetrahedron edge length. */ double sum_square_edge_length( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double l1 = vec3( v1 - v0 ).length2(); double l2 = vec3( v2 - v0 ).length2(); double l3 = vec3( v3 - v0 ).length2(); double l4 = vec3( v2 - v1 ).length2(); double l5 = vec3( v3 - v1 ).length2(); double l6 = vec3( v3 - v2 ).length2(); return l1 + l2 + l3 + l4 + l5 + l6; } /*! * @brief Tetrahedron quality based on the tetrahedron volume and * the sum of the square edges. * * The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). * For more information see * <a * href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html"> * TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a> * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * * @return 12. * (3 * volume)^(2/3) / sum of the square edge. */ double tet_quality_volume_by_sum_square_edges( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { const double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 ); double sum_square_edge = sum_square_edge_length( v0, v1, v2, v3 ); ringmesh_assert( sum_square_edge > global_epsilon ); return 12. * std::pow( 3. * tet_volume, 2. / 3. ) / sum_square_edge; } /*! * @bried Computes the sinus of the half solid angle relatively to a * tetrahedron vertex. * @param[in] v0 first vertex of the tetrahedron. The solid angle is * computed * relatively to this vertex. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return the sinus of the half solid angle on the vertex \p v0. */ double sin_half_solid_angle( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 ); double l01 = ( v1 - v0 ).length(); double l02 = ( v2 - v0 ).length(); double l03 = ( v3 - v0 ).length(); double l12 = ( v2 - v1 ).length(); double l13 = ( v3 - v1 ).length(); double l23 = ( v3 - v2 ).length(); double denominator = ( l01 + l02 + l12 ) * ( l01 + l02 - l12 ) * ( l02 + l03 + l23 ) * ( l02 + l03 - l23 ) * ( l03 + l01 + l13 ) * ( l03 + l01 - l13 ); ringmesh_assert( denominator > global_epsilon_sq ); denominator = std::sqrt( denominator ); return 12 * tet_volume / denominator; } /*! * @brief Tetrahedron quality based on the solid angles. * * This metrics is based on the sinus of the half solid angle on each * vertex. It was shown on the literature that the minimum of the four * values provides an estimate of the tetrahedron quality. * For more information, see: * <a * href="http://people.eecs.berkeley.edu/~jrs/meshpapers/robnotes.pdf">robnotes.pdf</a> * p15, * Liu, A., and B. Joe, 1994, Relationship between tetrahedron shape * measures, * BIT, v. 34, no. 2, p. 268-287, <a * href="http://doi.org/10.1007/BF01955874">doi</a> and * <a * href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html"> * TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a> * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * * @return 1.5 * sqrt( 6 ) * the minimun of the sinus of the half * solid angles. 1.5 * sqrt( 6 ) is a factor to scale the metrics between * 0 and 1. * 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). */ double tet_quality_min_solid_angle( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double min_sin_half_solid_angle = std::min( std::min( std::min( sin_half_solid_angle( v0, v1, v2, v3 ), sin_half_solid_angle( v1, v0, v2, v3 ) ), sin_half_solid_angle( v2, v0, v1, v3 ) ), sin_half_solid_angle( v3, v0, v1, v2 ) ); return 1.5 * std::sqrt( 6. ) * min_sin_half_solid_angle; } /*! * @param[in] mesh_qual_mode mesh quality number. * @return the property name associated to the mesh quality number * \p mesh_qual_mode. */ std::string mesh_qual_mode_to_prop_name( MeshQualityMode mesh_qual_mode ) { std::string quality_name; switch( mesh_qual_mode ) { case INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS: quality_name = "INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS"; break; case INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH: quality_name = "INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH"; break; case VOLUME_BY_SUM_SQUARE_EDGE: quality_name = "VOLUME_BY_SUM_SQUARE_EDGE"; break; case MIN_SOLID_ANGLE: quality_name = "MIN_SOLID_ANGLE"; break; default: ringmesh_assert_not_reached; } ringmesh_assert( !quality_name.empty() ); return quality_name; } /*! * @brief Gets the quality for one tetrahedron. * * The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @param[in] mesh_qual_mode tetrahedron quality to get. * @return the tetrahedron quality. */ double get_tet_quality( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3, MeshQualityMode mesh_qual_mode ) { double quality = -1; switch( mesh_qual_mode ) { case INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS: quality = tet_quality_insphere_radius_by_circumsphere_radius( v0, v1, v2, v3 ); break; case INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH: quality = tet_quality_insphere_radius_by_max_edge_length( v0, v1, v2, v3 ); break; case VOLUME_BY_SUM_SQUARE_EDGE: quality = tet_quality_volume_by_sum_square_edges( v0, v1, v2, v3 ); break; case MIN_SOLID_ANGLE: quality = tet_quality_min_solid_angle( v0, v1, v2, v3 ); break; default: ringmesh_assert_not_reached; } ringmesh_assert( quality > -1 * global_epsilon && quality < 1 + global_epsilon ); return quality; } } // namespace namespace RINGMesh { void compute_prop_tet_mesh_quality( MeshQualityMode mesh_qual_mode, const GeoModel3D& geomodel ) { ringmesh_assert( geomodel.nb_regions() != 0 ); for( const auto& region : geomodel.regions() ) { ringmesh_assert( region.is_meshed() ); ringmesh_assert( region.is_simplicial() ); GEO::AttributesManager& reg_attr_mgr = region.cell_attribute_manager(); GEO::Attribute< double > attr( reg_attr_mgr, mesh_qual_mode_to_prop_name( mesh_qual_mode ) ); for( auto cell_itr : range( region.nb_mesh_elements() ) ) { attr[cell_itr] = get_tet_quality( region.mesh_element_vertex( { cell_itr, 0 } ), region.mesh_element_vertex( { cell_itr, 1 } ), region.mesh_element_vertex( { cell_itr, 2 } ), region.mesh_element_vertex( { cell_itr, 3 } ), mesh_qual_mode ); } } } double fill_mesh_with_low_quality_cells( MeshQualityMode mesh_qual_mode, double min_quality, const GeoModel3D& geomodel, VolumeMesh3D& output_mesh ) { ringmesh_assert( geomodel.nb_regions() != 0 ); auto mesh_builder = VolumeMeshBuilder3D::create_builder( output_mesh ); double min_qual_value{ max_float64() }; for( const auto& region : geomodel.regions() ) { ringmesh_assert( region.is_meshed() ); ringmesh_assert( region.is_simplicial() ); GEO::Attribute< double > quality_attribute( region.cell_attribute_manager(), mesh_qual_mode_to_prop_name( mesh_qual_mode ) ); for( auto cell_id : range( region.nb_mesh_elements() ) ) { if( quality_attribute[cell_id] < min_quality ) { auto first_new_vertex_id = output_mesh.nb_vertices(); for( auto v : range( 4 ) ) { mesh_builder->create_vertex( region.mesh_element_vertex( { cell_id, v } ) ); } auto new_cell_id = mesh_builder->create_cells( 1, CellType::TETRAHEDRON ); for( auto v_id : range( 4 ) ) { mesh_builder->set_cell_vertex( { new_cell_id, v_id }, first_new_vertex_id + v_id ); } if( quality_attribute[cell_id] < min_qual_value ) { min_qual_value = quality_attribute[cell_id]; } } } } return min_qual_value; } } // namespace RINGMesh
41.575117
97
0.611484
ringmesh
30cf9a1e4c280de211c6f47e1da4bb8d58ea336d
2,835
cpp
C++
primitive_roots_tests.cpp
Mirraz/number-theory
30f444f8b61cc5946d4615bafe237994d7836cbf
[ "MIT" ]
null
null
null
primitive_roots_tests.cpp
Mirraz/number-theory
30f444f8b61cc5946d4615bafe237994d7836cbf
[ "MIT" ]
null
null
null
primitive_roots_tests.cpp
Mirraz/number-theory
30f444f8b61cc5946d4615bafe237994d7836cbf
[ "MIT" ]
null
null
null
#include <assert.h> #include <stdio.h> #include <stdint.h> #include <inttypes.h> #include <math.h> #include "primitive_roots.h" #define main HIDE_main #define tests_suite HIDE_tests_suite #define test_max_primitive_root HIDE_test_max_primitive_root #include "mul_group_mod_tests.cpp" #undef main #undef tests_suite #undef test_max_primitive_root void test_is_primitive_root() { typedef uint_fast32_t num_type; typedef PrimitiveRoots<num_type, 9, ((num_type)1)<<31, uint_fast64_t> prrs_type; typedef prrs_type::canonic_factorizer_type cfzr_type; typedef cfzr_type::primes_array_type primes_array_type; // pi(2^16) = 6542 num_type primes[6542]; size_t primes_count = primes_array_type::fill_primes( primes, sizeof(primes) / sizeof(primes[0]), (num_type)UINT16_MAX + 1 ); assert(primes_count == sizeof(primes) / sizeof(primes[0])); cfzr_type cfzr(primes_array_type(primes, primes_count)); for (size_t idx=0; idx<sizeof(primes) / sizeof(primes[0]); ++idx) { num_type modulo = primes[idx]; prrs_type primitive_roots(cfzr, modulo); num_type min_root = 0; for (num_type i=1; i<modulo; ++i) { bool is_primitive_root = primitive_roots.is_primitive_root(i); if (is_primitive_root) {min_root = i; break;} } num_type max_root = 0; for (num_type i=modulo-1; i>=1; --i) { bool is_primitive_root = primitive_roots.is_primitive_root(i); if (is_primitive_root) {max_root = i; break;} } assert(min_root != 0); assert(max_root != 0); assert((modulo-1) % 4 != 0 || modulo-max_root == min_root); printf("%" PRIuFAST64 "\t %" PRIuFAST64 "\n", modulo, min_root); printf("%" PRIuFAST64 "\t-%" PRIuFAST64 "\n", modulo, modulo-max_root); printf("\n"); } } void test_max_primitive_root() { fill_myprimes(); fill_max_roots(); typedef uint_fast32_t num_type; typedef PrimitiveRoots<num_type, 9, ((num_type)1)<<31, uint_fast64_t> prrs_type; typedef prrs_type::canonic_factorizer_type cfzr_type; typedef cfzr_type::primes_array_type primes_array_type; // pi(2^16) = 6542 num_type primes[6542]; size_t primes_count = primes_array_type::fill_primes( primes, sizeof(primes) / sizeof(primes[0]), (num_type)UINT16_MAX + 1 ); assert(primes_count == sizeof(primes) / sizeof(primes[0])); cfzr_type cfzr(primes_array_type(primes, primes_count)); for (size_t idx=0; idx<sizeof(primes) / sizeof(primes[0]); ++idx) { num_type modulo = primes[idx]; prrs_type primitive_roots(cfzr, modulo); num_type max_root = 0; for (num_type i=modulo-1; i>=1; --i) { bool is_primitive_root = primitive_roots.is_primitive_root(i); if (is_primitive_root) {max_root = i; break;} } assert(max_root != 0); assert(max_root == myprimes[idx] - max_roots[idx]); } } void tests_suite() { //test_is_primitive_root(); test_max_primitive_root(); } int main() { tests_suite(); return 0; }
29.53125
81
0.722751
Mirraz
30d0ce1ea78572de8c984a5eaa443dd2aadc4520
4,446
cc
C++
stapl_release/benchmarks/kernels/jacobi_1d/jacobi_1d_mpi_omp.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/benchmarks/kernels/jacobi_1d/jacobi_1d_mpi_omp.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/benchmarks/kernels/jacobi_1d/jacobi_1d_mpi_omp.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ ////////////////////////////////////////////////////////////////////// /// @file /// Hybrid MPI+OpenMP implementation of http://www.mcs.anl.gov/research/projects/mpi/tutorial/mpiexmpl/src/jacobi/C/main.html ////////////////////////////////////////////////////////////////////// #include <iostream> #include <cfloat> #include <cmath> #include <vector> #include <mpi.h> #ifdef _OPENMP # include <omp.h> #endif template<typename T> class matrix { private: std::size_t m_nrows; std::size_t m_ncols; std::vector<T> m_data; public: matrix(std::size_t nrows, std::size_t ncols) : m_nrows(nrows), m_ncols(ncols), m_data(ncols * nrows) { } T const& operator()(std::size_t row, std::size_t ncol) const noexcept { return m_data[row * m_ncols + ncol]; } T& operator()(std::size_t row, std::size_t ncol) noexcept { return m_data[row * m_ncols + ncol]; } T const* operator[](std::size_t row) const noexcept { return &m_data[row * m_ncols]; } T* operator[](std::size_t row) noexcept { return &m_data[row * m_ncols]; } }; int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); MPI_Comm comm = MPI_COMM_WORLD; int rank = MPI_PROC_NULL, size = MPI_PROC_NULL; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); const std::size_t maxn = (argc < 2 ? 12 : std::atoi(argv[1])); if (maxn % size != 0) { std::cerr << "Incorrect size of " << maxn << std::endl; MPI_Abort( comm, 1 ); } /* xlocal[][0] is lower ghostpoints, xlocal[][maxn+2] is upper */ // top and bottom processes have one less row of interior points std::size_t i_first = 1; std::size_t i_last = maxn/size; if (rank == 0) i_first++; if (rank == size - 1) i_last--; // create data typedef matrix<double> matrix_type; matrix_type xlocal(maxn/size + 2 ,maxn); matrix_type xnew(maxn/size + 2, maxn); for (std::size_t i=1; i<=maxn/size; i++) for (std::size_t j=0; j<maxn; j++) xlocal[i][j] = rank; for (std::size_t j=0; j<maxn; j++) { xlocal[i_first-1][j] = -1; xlocal[i_last+1][j] = -1; } double gdiffnorm = DBL_MAX; double diffnorm = 0.0; int itcnt = 0; const double time = MPI_Wtime(); #pragma omp parallel firstprivate(itcnt) for (itcnt=0; itcnt<100 && gdiffnorm > 1.0e-3; ++itcnt) { # pragma omp master { /* Send up unless I'm at the top, then receive from below */ /* Note the use of xlocal[i] for &xlocal[i][0] */ if (rank < size - 1) MPI_Send(xlocal[maxn/size], maxn, MPI_DOUBLE, rank + 1, 0, comm); if (rank > 0) MPI_Recv(xlocal[0], maxn, MPI_DOUBLE, rank - 1, 0, comm, MPI_STATUS_IGNORE); /* Send down unless I'm at the bottom */ if (rank > 0) MPI_Send(xlocal[1], maxn, MPI_DOUBLE, rank - 1, 1, comm); if (rank < size - 1) MPI_Recv(xlocal[maxn/size+1], maxn, MPI_DOUBLE, rank + 1, 1, comm, MPI_STATUS_IGNORE); } #pragma omp barrier /* Compute new values (but not on boundary) */ # pragma omp for reduction(+:diffnorm) for (std::size_t i=i_first; i<=i_last; i++) { for (std::size_t j=1; j<maxn-1; j++) { xnew[i][j] = (xlocal[i][j+1] + xlocal[i][j-1] + xlocal[i+1][j] + xlocal[i-1][j]) / 4.0; diffnorm += (xnew[i][j] - xlocal[i][j]) * (xnew[i][j] - xlocal[i][j]); } } /* Only transfer the interior points */ # pragma omp for for (std::size_t i=i_first; i<=i_last; i++) { for (std::size_t j=1; j<maxn-1; j++) { xlocal[i][j] = xnew[i][j]; } } # pragma omp master { MPI_Allreduce(&diffnorm, &gdiffnorm, 1, MPI_DOUBLE, MPI_SUM, comm); diffnorm = 0.0; gdiffnorm = std::sqrt(gdiffnorm); } } const double elapsed = MPI_Wtime() - time; if (rank==0) std::cout << "jacobi_1d_mpi_omp " << size << ' ' #ifdef _OPENMP << omp_get_max_threads() << ' ' #else << 1 << ' ' #endif << elapsed << ' ' << itcnt << "\n"; MPI_Finalize(); return 0; }
28.318471
125
0.573324
parasol-ppl
30d264b409b79ef46efb5821f7ccf8183efb324c
3,943
cpp
C++
Source/Workbenches/PartDesign/feature_line.cpp
neonkingfr/wildogcad
6d9798daa672d3ab293579439f38bb279fa376c7
[ "BSD-3-Clause" ]
null
null
null
Source/Workbenches/PartDesign/feature_line.cpp
neonkingfr/wildogcad
6d9798daa672d3ab293579439f38bb279fa376c7
[ "BSD-3-Clause" ]
null
null
null
Source/Workbenches/PartDesign/feature_line.cpp
neonkingfr/wildogcad
6d9798daa672d3ab293579439f38bb279fa376c7
[ "BSD-3-Clause" ]
null
null
null
/*** Included Header Files ***/ #include <feature_line.h> #include <document.h> #include <feature_point.h> #include <tree_view.h> #include <line_layer.h> #include <feature_line_action.h> #include <feature_line_controller.h> /***********************************************~***************************************************/ WCFeatureLine::WCFeatureLine(WCFeature *creator, const std::string &name, WCFeaturePoint *p0, WCFeaturePoint *p1) : ::WCFeature(creator, name), _base(NULL), _p0(p0), _p1(p1) { //Make sure p0 and p1 are not null if ((p0 == NULL) || (p1 == NULL)) { CLOGGER_ERROR(WCLogManager::RootLogger(), "WCFeatureLine::WCFeatureLine - NULL points passed.\n"); //throw error return; } //Create the base line this->_base = new WCGeometricLine(p0->Base(), p1->Base()); this->_base->Retain(*this); //Retain both p0 and p1 this->_p0->Retain(*this); this->_p1->Retain(*this); //Check feature name if (this->_name == "") this->_name = this->_document->GenerateFeatureName(this); //Create event handler this->_controller = new WCFeatureLineController(this); //Create tree element and add into the tree (beneath the creator) this->_treeElement = new WCTreeElement(this->_document->TreeView(), this->_name, this->_controller, NULL); //Add p0 and p1 as a children in the tree view this->_treeElement->AddLastChild(this->_p0->TreeElement()); this->_treeElement->AddLastChild(this->_p1->TreeElement()); //Mark as closed this->_treeElement->IsOpen(false); //Add to the creator this->_creator->TreeElement()->AddLastChild(this->_treeElement); //Add into document this->_document->AddFeature(this); //Add to the lines layer this->_document->LinesLayer()->AddLine(this->_base); } WCFeatureLine::~WCFeatureLine() { //Remove the line from the layer this->_document->LinesLayer()->RemoveLine(this->_base); //Remove the line from the document this->_document->RemoveFeature(this); //Release and delete the base this->_base->Release(*this); delete this->_base; //Release the points this->_p0->Release(*this); this->_p1->Release(*this); } void WCFeatureLine::ReceiveNotice(WCObjectMsg msg, WCObject *sender) { //Just need to mark line layer as dirty this->_document->LinesLayer()->MarkDirty(); // CLOGGER_WARN(WCLogManager::RootLogger(), "WCFeatureLine::ReceiveNotice - Not yet implemented.\n"); } bool WCFeatureLine::Regenerate(void) { return false; } xercesc::DOMElement* WCFeatureLine::Serialize(xercesc::DOMDocument *document) { return NULL; } WCFeatureLine* WCFeatureLine::Deserialize(xercesc::DOMElement* obj) { return NULL; } bool WCFeatureLine::Validate(xercesc::DOMElement* obj) { return false; } /* WCVisualObject* WCFeatureLine::HitTest(const WCRay &ray, const WPFloat tolerance) { return NULL; } void WCFeatureLine::ApplyTransform(const WCMatrix4 &transform) { } void WCFeatureLine::ApplyTranslation(const WCVector4 &translation) { } */ void WCFeatureLine::Render(const GLuint defaultProg, const WCColor color) { //Make sure is visible if (!this->_isVisible) return; this->_base->Render(defaultProg, color); } /***********************************************~***************************************************/ WCFeatureLineAction* WCFeatureLine::ActionCreate(WCFeature *creator, const std::string lineName, WCFeaturePoint *p0, WCFeaturePoint *p1) { WCFeatureLineAction* action; action = new WCFeatureLineAction(creator, lineName, p0, p1); return action; } //WCFeatureLineAction* WCFeatureLine::ActionModify() { //} WCFeatureLineAction* WCFeatureLine::ActionDelete(WCFeatureLine *line) { return NULL; } /***********************************************~***************************************************/ std::ostream& operator<<(std::ostream& out, const WCFeatureLine &line) { out << "FeatureLine( " << &line << ")\n"; return out; } /***********************************************~***************************************************/
27.964539
138
0.652042
neonkingfr
30d3f168dd50e3f6162768d0f9b6d9bfcf56fc02
447
cpp
C++
Course 201809/homework/4/B2.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
Course 201809/homework/4/B2.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
Course 201809/homework/4/B2.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
#include <stdio.h> #include <math.h> int main() { int n1,n2,n,i; scanf("%d",&n); for (n1=2;n1<=n/2;n1++) { for (i=2;i<=sqrt(n1);i++) { if (n1%i==0) break; } if (i==(int)sqrt(n1)+1) { for (i=2,n2=n-n1;i<=sqrt(n2);i++) { if (n2%i==0) break; } if (i==(int)sqrt(n2)+1) printf("%d and %d\n",n1,n2); } } printf("\n"); return 0; }
13.96875
41
0.378076
Seizzzz
30d4c2054b988f10e08e7936105ba79a20ce2dfd
9,263
cpp
C++
maya/Workshop2017/src/BBoxCubeCmd.cpp
smoi23/sandbox
4d02a509c82b2ec3712f91bbc86cc5df37174396
[ "MIT" ]
null
null
null
maya/Workshop2017/src/BBoxCubeCmd.cpp
smoi23/sandbox
4d02a509c82b2ec3712f91bbc86cc5df37174396
[ "MIT" ]
null
null
null
maya/Workshop2017/src/BBoxCubeCmd.cpp
smoi23/sandbox
4d02a509c82b2ec3712f91bbc86cc5df37174396
[ "MIT" ]
null
null
null
/* * WorkshopCmd3.cpp * * Created on: May 15, 2017 * Author: Andreas Schuster * */ #include <stdio.h> #include <iostream> #include <maya/MPxCommand.h> #include <maya/MArgList.h> #include <maya/MStatus.h> #include <maya/MSyntax.h> #include <maya/MStringArray.h> #include <maya/MGlobal.h> #include <maya/MArgDatabase.h> #include <maya/MItSelectionList.h> #include <maya/MDagPath.h> #include <maya/MItMeshVertex.h> #include <maya/MPoint.h> #include <maya/MPointArray.h> #include <maya/MMatrix.h> #include <maya/MFnDagNode.h> #include <maya/MFnMesh.h> #include <maya/MItMeshPolygon.h> #include <maya/MItMeshEdge.h> #include <maya/MFnTransform.h> #include <maya/MFnMeshData.h> #include <maya/MFnTypedAttribute.h> #include <maya/MPlug.h> #include <maya/MBoundingBox.h> #include <maya/MFnSet.h> #include "BBoxCubeCmd.h" // #define kHelpFlag "-h" #define kHelpFlagLong "-help" // // #define kSizeFlag "s" #define kSizeFlagLong "size" MObject BBoxCubeCmd::m_meshTransform; MString BBoxCubeCmd::s_name("BBoxCube"); BBoxCubeCmd::BBoxCubeCmd(): m_doHelp(false), m_size(1.0), m_isQuery(false) { std::cout << "In BBoxCubeCmd::BBoxCubeCmd()" << std::endl; } BBoxCubeCmd::~BBoxCubeCmd() { std::cout << "In BBoxCubeCmd::~BBoxCubeCmd()" << std::endl; } MSyntax BBoxCubeCmd::newSyntax() { MSyntax syntax; std::cout << "In BBoxCubeCmd::BBoxCubeCmd()" << std::endl; // // syntax.enableQuery(true); syntax.enableEdit(false); syntax.useSelectionAsDefault(true); syntax.setObjectType(MSyntax::kSelectionList, 1); syntax.addFlag(kHelpFlag, kHelpFlagLong, MSyntax::kNoArg); syntax.addFlag(kSizeFlag, kSizeFlagLong, MSyntax::kDouble); return syntax; } MStatus BBoxCubeCmd::doIt(const MArgList &args) { MStatus stat = MS::kSuccess; std::cout << "In BBoxCubeCmd::doIt()" << std::endl; stat = parseArgs(args); if (m_doHelp) { MGlobal::displayInfo("Show help"); } else if (m_isQuery) { MString selectionString(""); MItSelectionList iter(m_selection); for (iter.reset(); !iter.isDone(); iter.next()) { MDagPath dagpath; iter.getDagPath(dagpath); selectionString += dagpath.fullPathName(); } MGlobal::displayInfo(selectionString); } else { if (m_selection.length() > 0) { stat = redoIt(); } else { MGlobal::displayError("Pass or select at least one polygon object."); } } return stat; } MStatus BBoxCubeCmd::redoIt() { std::cout << "In BBoxCubeCmd::redoIt()" << std::endl; MStatus stat; // start new buffers MPointArray vertexBuffer; MIntArray faceCount; MIntArray vertexIndex; MItSelectionList iter(m_selection, MFn::kTransform); for (iter.reset(); !iter.isDone(); iter.next()) { MDagPath dagpath; iter.getDagPath(dagpath); MGlobal::displayInfo(dagpath.fullPathName()); MMatrix dagMatrix = dagpath.inclusiveMatrix(); stat = dagpath.extendToShape(); if (stat == MS::kSuccess) { MFnDagNode fnDagNode(dagpath); MBoundingBox bbox = fnDagNode.boundingBox(); bbox.transformUsing(dagMatrix); addCubeFromBbox(vertexBuffer, faceCount, vertexIndex, bbox); } } MGlobal::displayInfo(MString("VertexBufferlength: ") + vertexBuffer.length()); // create place for the data MFnMeshData dataFn; MObject dataWrapper = dataFn.create(); // create the mesh from the mesh function set MFnMesh fnMesh; fnMesh.create(vertexBuffer.length(), faceCount.length(), vertexBuffer, faceCount, vertexIndex, dataWrapper, &stat); if (stat != MS::kSuccess) { MGlobal::displayError("Failed to create mesh: " + stat.errorString()); return stat; } // set normals to make the cube hard edged int numFaceVertices = faceCount.length() * 4; // assuming quads! MVectorArray normals(numFaceVertices); MIntArray faces(numFaceVertices); MIntArray vertices(numFaceVertices); MItMeshPolygon iterFace(dataWrapper); int idx = 0; for (iterFace.reset(); !iterFace.isDone(); iterFace.next()) { MIntArray vertexIds; iterFace.getVertices(vertexIds); //std::cout << "faceVertices count " << vertexIds.length() << std::endl; //std::cout << vertexIds[0] << " " << vertexIds[1] << " " << vertexIds[2] << " " << vertexIds[3] << std::endl; MVector faceNormal; iterFace.getNormal(faceNormal); //std::cout << "Face normal: " << faceNormal.x << " " << faceNormal.y << " " << faceNormal.z << std::endl; for (int i = 0; i < 4; i++) // assuming quads! { faces.set(iterFace.index(), idx * 4+i); vertices.set(vertexIds[i], idx * 4 + i); normals.set(faceNormal, idx * 4 + i); // fnMesh.setFaceVertexNormal(faceNormal, iterFace.index(), vertexIds[i]); // set normal for every face vertex separately } idx++; } fnMesh.setFaceVertexNormals(normals, faces, vertices); fnMesh.updateSurface(); MObject transformNode = dagModifier.createNode("mesh", MObject::kNullObj, &stat); if (stat != MS::kSuccess) { MGlobal::displayError("Failed to create transform: " + stat.errorString()); return stat; } dagModifier.doIt(); // Set the mesh node to use the geometry we created for it. setMeshData(transformNode, dataWrapper); // assign to shading group MSelectionList selectionList; stat = selectionList.add("initialShadingGroup"); if (stat == MS::kSuccess) { MObject shaderNode; selectionList.getDependNode(0, shaderNode); MFnSet setFn(shaderNode); MFnDagNode dagFn(transformNode); MObject mesh = dagFn.child(0); setFn.addMember(mesh); } return MS::kSuccess; } void BBoxCubeCmd::addCubeFromBbox(MPointArray &o_vertexBuffer, MIntArray &o_vertexCount, MIntArray &o_vertexIndex, MBoundingBox &i_bbox) { int offset = o_vertexBuffer.length(); // 8 vertices o_vertexBuffer.append(i_bbox.max()); o_vertexBuffer.append(MPoint(i_bbox.max().x, i_bbox.max().y, i_bbox.min().z)); o_vertexBuffer.append(MPoint(i_bbox.min().x, i_bbox.max().y, i_bbox.min().z)); o_vertexBuffer.append(MPoint(i_bbox.min().x, i_bbox.max().y, i_bbox.max().z)); o_vertexBuffer.append(i_bbox.min()); o_vertexBuffer.append(MPoint(i_bbox.max().x, i_bbox.min().y, i_bbox.min().z)); o_vertexBuffer.append(MPoint(i_bbox.max().x, i_bbox.min().y, i_bbox.max().z)); o_vertexBuffer.append(MPoint(i_bbox.min().x, i_bbox.min().y, i_bbox.max().z)); // every face has 4 vertices for (int i = 0; i < 6; i++) { o_vertexCount.append(4); } // face top o_vertexIndex.append(offset + 0); o_vertexIndex.append(offset + 1); o_vertexIndex.append(offset + 2); o_vertexIndex.append(offset + 3); // face front o_vertexIndex.append(offset + 0); o_vertexIndex.append(offset + 3); o_vertexIndex.append(offset + 7); o_vertexIndex.append(offset + 6); // face right o_vertexIndex.append(offset + 1); o_vertexIndex.append(offset + 0); o_vertexIndex.append(offset + 6); o_vertexIndex.append(offset + 5); // face left o_vertexIndex.append(offset + 3); o_vertexIndex.append(offset + 2); o_vertexIndex.append(offset + 4); o_vertexIndex.append(offset + 7); // face back o_vertexIndex.append(offset + 2); o_vertexIndex.append(offset + 1); o_vertexIndex.append(offset + 5); o_vertexIndex.append(offset + 4); // face bottom o_vertexIndex.append(offset + 4); o_vertexIndex.append(offset + 5); o_vertexIndex.append(offset + 6); o_vertexIndex.append(offset + 7); } MStatus BBoxCubeCmd::setMeshData(MObject transform, MObject dataWrapper) { MStatus st; // Get the mesh node. MFnDagNode dagFn(transform); MObject mesh = dagFn.child(0); // The mesh node has two geometry inputs: 'inMesh' and 'cachedInMesh'. // 'inMesh' is only used when it has an incoming connection, otherwise // 'cachedInMesh' is used. Unfortunately, the docs say that 'cachedInMesh' // is for internal use only and that changing it may render Maya // unstable. // // To get around that, we do the little dance below... // Use a temporary MDagModifier to create a temporary mesh attribute on // the node. MFnTypedAttribute tAttr; MObject tempAttr = tAttr.create("tempMesh", "tmpm", MFnData::kMesh); MDagModifier tempMod; st = tempMod.addAttribute(mesh, tempAttr); st = tempMod.doIt(); // Set the geometry data onto the temp attribute. dagFn.setObject(mesh); MPlug tempPlug = dagFn.findPlug(tempAttr); st = tempPlug.setValue(dataWrapper); // Use the temporary MDagModifier to connect the temp attribute to the // node's 'inMesh'. MPlug inMeshPlug = dagFn.findPlug("inMesh"); st = tempMod.connect(tempPlug, inMeshPlug); st = tempMod.doIt(); // Force the mesh to update by grabbing its output geometry. dagFn.findPlug("outMesh").asMObject(); // Undo the temporary modifier. st = tempMod.undoIt(); return st; } MStatus BBoxCubeCmd::undoIt() { std::cout << "In BBoxCubeCmd::undoIt()" << std::endl; dagModifier.undoIt(); return MS::kSuccess; } bool BBoxCubeCmd::isUndoable() const { std::cout << "In BBoxCubeCmd::isUndoable()" << std::endl; return !m_isQuery; } void* BBoxCubeCmd::creator() { std::cout << "In BBoxCubeCmd::creator()" << std::endl; return new BBoxCubeCmd(); } MStatus BBoxCubeCmd::parseArgs(const MArgList &args) { MStatus stat = MS::kSuccess; MArgDatabase argData(syntax(), args); m_doHelp = argData.isFlagSet(kHelpFlag); m_isQuery = argData.isQuery(); if (!m_isQuery) // only update selection if not in query mode { argData.getObjects(m_selection); } return stat; }
24.967655
136
0.703768
smoi23
30d61e145e98bb61d3e96be726741974debf1d6d
602
cpp
C++
replace_character.cpp
chandan9369/Recursion-backtracking-problems
360e5de72e23dfd4e3f343baa1e1abdfb801ccc3
[ "MIT" ]
null
null
null
replace_character.cpp
chandan9369/Recursion-backtracking-problems
360e5de72e23dfd4e3f343baa1e1abdfb801ccc3
[ "MIT" ]
null
null
null
replace_character.cpp
chandan9369/Recursion-backtracking-problems
360e5de72e23dfd4e3f343baa1e1abdfb801ccc3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void replace(char s[], char c1, char c2) { //base case if (s[0] == '\0') { return; } if (s[0] == c1) { s[0] = c2; } replace(s + 1, c1, c2); } int main() { char s[100]; cin >> s; char c1, c2; cout << "Enter character to be replaced : "; cin >> c1; cout << "Enter character with which you want to replace : "; cin >> c2; replace(s, c1, c2); cout << "After replacing character " << c1 << " with character" << c2 << "string we have new string : " << s << endl; return 0; }
21.5
121
0.501661
chandan9369
30d6d8f00f7fdc97dab807313fc63d794818aa5a
16,614
cpp
C++
modules/src/projectors/standardpipeline.cpp
phernst/ctl
f2369cf3141ff6a696219f99b09fd60c0ea12eac
[ "MIT" ]
null
null
null
modules/src/projectors/standardpipeline.cpp
phernst/ctl
f2369cf3141ff6a696219f99b09fd60c0ea12eac
[ "MIT" ]
null
null
null
modules/src/projectors/standardpipeline.cpp
phernst/ctl
f2369cf3141ff6a696219f99b09fd60c0ea12eac
[ "MIT" ]
null
null
null
#include "standardpipeline.h" #include "arealfocalspotextension.h" #include "detectorsaturationextension.h" #include "poissonnoiseextension.h" #include "raycasterprojector.h" #include "spectraleffectsextension.h" namespace CTL { DECLARE_SERIALIZABLE_TYPE(StandardPipeline) /*! * Constructs a StandardPipeline object and with the ApproximationPolicy \a policy. * * The default configuration enables spectral effects and Poisson noise simulation. */ StandardPipeline::StandardPipeline(ApproximationPolicy policy) : _projector(new OCL::RayCasterProjector) , _extAFS(new ArealFocalSpotExtension) , _extDetSat(new DetectorSaturationExtension) , _extPoisson(new PoissonNoiseExtension) , _extSpectral(new SpectralEffectsExtension) , _approxMode(policy) { _pipeline.setProjector(_projector); // configure extensions _extAFS->setDiscretization({ 3, 3 }); if(policy == ApproximationPolicy::Full_Approximation) _extAFS->enableLowExtinctionApproximation(); enableArealFocalSpot(false); enableDetectorSaturation(false); enablePoissonNoise(true); enableSpectralEffects(true); } StandardPipeline::~StandardPipeline() { // handover ownership to ProjectionPipeline member enableArealFocalSpot(true); enableDetectorSaturation(true); enablePoissonNoise(true); enableSpectralEffects(true); } /*! * \brief Sets the acquisition setup for the simulation to \a setup. * * Sets the acquisition setup for the simulation to \a setup. This needs to be done prior to calling * project(). */ void StandardPipeline::configure(const AcquisitionSetup& setup) { _pipeline.configure(setup); } /*! * \brief Creates projection data from \a volume. * * Creates projection data from \a volume using the current processing pipeline configuration of * this instance. Uses the last acquisition setup set by configure(). */ ProjectionData StandardPipeline::project(const VolumeData& volume) { return _pipeline.project(volume); } /*! * \brief Creates projection data from the composite volume \a volume. * * Creates projection data from the composite volume \a volume using the current processing pipeline * configuration of this instance. Uses the last acquisition setup set by configure(). */ ProjectionData StandardPipeline::projectComposite(const CompositeVolume& volume) { return _pipeline.projectComposite(volume); } /*! * Returns true if the application of the full processing pipeline is linear. */ bool StandardPipeline::isLinear() const { return _pipeline.isLinear(); } ProjectorNotifier* StandardPipeline::notifier() { return _pipeline.notifier(); } void StandardPipeline::fromVariant(const QVariant& variant) { AbstractProjector::fromVariant(variant); QVariantMap map = variant.toMap(); enableArealFocalSpot(false); enableDetectorSaturation(false); enablePoissonNoise(false); enableSpectralEffects(false); _pipeline.setProjector(SerializationHelper::parseProjector(map.value("projector"))); _extAFS->fromVariant(map.value("ext AFS")); _extDetSat->fromVariant(map.value("ext DetSat")); _extPoisson->fromVariant(map.value("ext Poisson")); _extSpectral->fromVariant(map.value("ext spectral")); _approxMode = ApproximationPolicy(map.value("approximation policy", int(Default_Approximation)).toInt()); enableArealFocalSpot(map.value("use areal focal spot").toBool()); enableDetectorSaturation(map.value("use detector saturation").toBool()); enablePoissonNoise(map.value("use poisson noise").toBool()); enableSpectralEffects(map.value("use spectral effects").toBool()); } QVariant StandardPipeline::toVariant() const { QVariantMap ret = AbstractProjector::toVariant().toMap(); ret.insert("#", "StandardPipeline"); ret.insert("use areal focal spot", _arealFSEnabled); ret.insert("use detector saturation", _detSatEnabled); ret.insert("use poisson noise", _poissonEnabled); ret.insert("use spectral effects", _spectralEffEnabled); ret.insert("approximation policy", _approxMode); ret.insert("projector", _projector->toVariant()); ret.insert("ext AFS", _extAFS->toVariant()); ret.insert("ext DetSat", _extDetSat->toVariant()); ret.insert("ext Poisson", _extPoisson->toVariant()); ret.insert("ext spectral", _extSpectral->toVariant()); return ret; } /*! * Enables/disables the simulation of areal focal spot effects, according to \a enable. */ void StandardPipeline::enableArealFocalSpot(bool enable) { if(enable == _arealFSEnabled) // no change return; if(enable) // insert AFS into pipeline (first position) _pipeline.insertExtension(posAFS(), _extAFS); else // remove AFS from pipeline (first position) _pipeline.releaseExtension(posAFS()); _arealFSEnabled = enable; } /*! * Enables/disables the simulation of detector saturation effects, according to \a enable. * * This only has an effect on the simulation if the detector component of the system passed with * the setup during configure() has a detector response model (see * AbstractDetector::setSaturationModel()). */ void StandardPipeline::enableDetectorSaturation(bool enable) { if(enable == _detSatEnabled) // no change return; if(enable) // insert det. sat. into pipeline (last position) _pipeline.appendExtension(_extDetSat); else // remove det. sat. from pipeline (last position) _pipeline.releaseExtension(_pipeline.nbExtensions() - 1u); _detSatEnabled = enable; } /*! * Enables/disables the simulation of Poisson noise, according to \a enable. */ void StandardPipeline::enablePoissonNoise(bool enable) { if(enable == _poissonEnabled) // no change return; if(enable) // insert Poisson into pipeline (after AFS and spectral) _pipeline.insertExtension(posPoisson(), _extPoisson); else // remove Poisson from pipeline (after AFS and spectral) _pipeline.releaseExtension(posPoisson()); _poissonEnabled = enable; } /*! * Enables/disables the simulation of spectral effects, according to \a enable. * * Spectral effects require full spectral information (see SpectralVolumeData) in the volume data * passed to project(). Otherwise, the spectral effects step will be skipped. * * Spectral detector response effects will be considered if a corresponding response model has been * set to the detector component (see AbstractDetector::setSpectralResponseModel()) of the system * passed with the setup during configure(). Note that trying to simulate settings with a spectral * response model in combination with volume data without full spectral information is not supported * and leads to an exception. */ void StandardPipeline::enableSpectralEffects(bool enable) { if(enable == _spectralEffEnabled) // no change return; if(enable) // insert spectral ext. into pipeline (after AFS) _pipeline.insertExtension(posSpectral(), _extSpectral); else // remove Poisson from pipeline (after AFS) _pipeline.releaseExtension(posSpectral()); _spectralEffEnabled = enable; } /*! * Returns a handle to the settings for the areal focal spot simulation. * * Areal focal spot settings are: * - setDiscretization(const QSize& discretization): sets the number of sampling * points for the subsampling of the areal focal spot to \a discretization (width x height) * [ default value: {3, 3} ] * - enableLowExtinctionApproximation(bool enable): sets the use of the linear approximation to * \a enable. [ default: \c false (\c true for StandardPipeline::Full_Approximation) ] * * Example: * \code * StandardPipeline pipe; * pipe.enableArealFocalSpot(); * pipe.settingsArealFocalSpot().setDiscretization( { 2, 2 } ); * \endcode * * \sa ArealFocalSpotExtension::setDiscretization() */ StandardPipeline::SettingsAFS StandardPipeline::settingsArealFocalSpot() { return { *_extAFS }; } /*! * Returns a handle to the settings for the detector saturation simulation. * * Detector saturation settings are: * - setSpectralSamples(uint nbSamples): sets the number of energy bins used to sample the spectrum * when processing intensity saturation to \a nbSamples [ default value: 0 (i.e. use sampling hint * of source component) ] * * Example: * \code * StandardPipeline pipe; * pipe.enableDetectorSaturation(); * pipe.settingsDetectorSaturation().setSpectralSamples(10); * \endcode * * \sa DetectorSaturationExtension::setIntensitySampling() */ StandardPipeline::SettingsDetectorSaturation StandardPipeline::settingsDetectorSaturation() { return { *_extDetSat }; } /*! * Returns a handle to the settings for the Poisson noise simulation. * * Poisson noise settings are: * - setFixedSeed(uint seed): sets a fixed seed for the pseudo random number generation [ default * value: not used] * - setRandomSeedMode(): (re-)enables the random seed mode, any fixed seed set will be ignored * until setFixedSeed() is called again [ default: random seed mode used ] * - setParallelizationMode(bool enabled): sets the use of parallelization to \a enabled [ default * value: true (i.e. parallelization enabled) ] * * Example: * \code * StandardPipeline pipe; * pipe.settingsPoissonNoise().setFixedSeed(1337); * pipe.settingsPoissonNoise().setParallelizationMode(false); * \endcode * * \sa PoissonNoiseExtension::setFixedSeed(), PoissonNoiseExtension::setRandomSeedMode(), * PoissonNoiseExtension::setParallelizationEnabled() */ StandardPipeline::SettingsPoissonNoise StandardPipeline::settingsPoissonNoise() { return { *_extPoisson }; } /*! * Returns a handle to the settings for the spectral effects simulation. * * Spectral effects settings are: * - setSamplingResolution(float energyBinWidth): sets the energy bin width used to sample the * spectrum to \a energyBinWidth (in keV) [ default value: 0 (i.e. resolution determined * automatically based on sampling hint of source component) ] * * Example: * \code * StandardPipeline pipe; * pipe.settingsSpectralEffects().setSamplingResolution(5.0f); * \endcode * * \sa SpectralEffectsExtension::setSpectralSamplingResolution() */ StandardPipeline::SettingsSpectralEffects StandardPipeline::settingsSpectralEffects() { return { *_extSpectral }; } /*! * Returns a handle to the settings for the ray caster projector. * * Ray caster settings are: * - setInterpolation(bool enabled): sets the use of interpolation in the OpenCL kernel to * \a enabled; disable interpolation when your OpenCL device does not have image support * [ default value: true (i.e. interpolation enabled) ] * - setRaysPerPixel(const QSize& sampling): sets the number of rays cast per pixel to \a sampling * (width x height) [ default value: {1, 1} ] * - setRaySampling(float sampling): sets the step length used to traverse the ray to \a sampling, * which is defined as the fraction of the length of a voxel in its shortest dimension [ default * value: 0.3 ] * - setVolumeUpSampling(uint upSamplingFactor): sets the factor for upsampling of the input volume * data to \a upSamplingFactor [ default value: 1 (i.e. no upsampling) ] * * Example: * \code * StandardPipeline pipe; * pipe.settingsRayCaster().setRaysPerPixel( { 2, 2 } ); * pipe.settingsRayCaster().setVolumeUpSampling(2); * \endcode * * \sa OCL::RayCasterProjector::settings() */ StandardPipeline::SettingsRayCaster StandardPipeline::settingsRayCaster() { return { *_projector }; } // ############### // private methods // ############### /*! * Returns the position of the areal focal spot extension in the standard pipeline. * This is defined to always be the first position (maximum efficiency). */ uint StandardPipeline::posAFS() const { return 0; } /*! * Returns the position of the detector saturation extension in the standard pipeline. * This is defined to always be the last position, as it is only accurate in this spot. */ uint StandardPipeline::posDetSat() const { return uint(_arealFSEnabled) + uint(_spectralEffEnabled) + uint(_poissonEnabled); } /*! * Returns the position of the Poisson noise extension in the standard pipeline. * Depending on whether the mode has been set to StandardPipeline::No_Approximation or not (i.e. * StandardPipeline::Full_Approximation or StandardPipeline::Default_Approximation), the * Poisson extension is placed before or after the spectral effects extension, respectively. */ uint StandardPipeline::posPoisson() const { return (_approxMode == No_Approximation) ? uint(_arealFSEnabled) : uint(_arealFSEnabled) + uint(_spectralEffEnabled); } /*! * Returns the position of the spectral effects extension in the standard pipeline. * Depending on whether the mode has been set to StandardPipeline::No_Approximation or not (i.e. * StandardPipeline::Full_Approximation or StandardPipeline::Default_Approximation), the * spectral effects extension is placed after or before the Poisson noise extension, respectively. */ uint StandardPipeline::posSpectral() const { return (_approxMode == No_Approximation) ? uint(_arealFSEnabled) + uint(_poissonEnabled) : uint(_arealFSEnabled); } void StandardPipeline::SettingsPoissonNoise::setFixedSeed(uint seed) { _ext.setFixedSeed(seed); } void StandardPipeline::SettingsPoissonNoise::setRandomSeedMode() { _ext.setRandomSeedMode(); } void StandardPipeline::SettingsPoissonNoise::setParallelizationMode(bool enabled) { _ext.setParallelizationEnabled(enabled); } void StandardPipeline::SettingsAFS::setDiscretization(const QSize& discretization) { _ext.setDiscretization(discretization); } void StandardPipeline::SettingsAFS::enableLowExtinctionApproximation(bool enable) { _ext.enableLowExtinctionApproximation(enable); } void StandardPipeline::SettingsDetectorSaturation::setSpectralSamples(uint nbSamples) { _ext.setIntensitySampling(nbSamples); } void StandardPipeline::SettingsSpectralEffects::setSamplingResolution(float energyBinWidth) { _ext.setSpectralSamplingResolution(energyBinWidth); } void StandardPipeline::SettingsRayCaster::setInterpolation(bool enabled) { _proj.settings().interpolate = enabled; } void StandardPipeline::SettingsRayCaster::setRaysPerPixel(const QSize& sampling) { _proj.settings().raysPerPixel[0] = static_cast<uint>(sampling.width()); _proj.settings().raysPerPixel[1] = static_cast<uint>(sampling.height()); } void StandardPipeline::SettingsRayCaster::setRaySampling(float sampling) { _proj.settings().raySampling = sampling; } void StandardPipeline::SettingsRayCaster::setVolumeUpSampling(uint upSamplingFactor) { _proj.settings().volumeUpSampling = upSamplingFactor; } /*! * \enum StandardPipeline::ApproximationPolicy * Enumeration for the approximation behavior in the standard pipeline. See Detailed Description * for more details. */ /*! \var StandardPipeline::ApproximationPolicy StandardPipeline::Full_Approximation, * Same configuration as in Default_Approximation setting. Additionally, a linearized approach is * used in the ArealFocalSpotExtension (if enabled). * Not suited in combination with a spectral detector response and inaccurate in case of high * extinction gradients (e.g. edges of highly absorbing material) in the projection images. */ /*! \var StandardPipeline::ApproximationPolicy StandardPipeline::Default_Approximation, * The default setting for the StandardPipeline. * Configuration in which Poisson noise addition is applied to final result of the spectral effects * simulation. Approximation with substantially increased computation speed. Not suited in * combination with a spectral detector response. */ /*! \var StandardPipeline::ApproximationPolicy StandardPipeline::No_Approximation * Configuration with spectral effects simulation wrapping Poisson noise addition for each energy * bin. Approximation-free but increased computation effort. Can be used in combination with a * spectral detector response. */ } // namespace CTL
36.117391
101
0.726255
phernst
30d8ff7f806b8df3c1432089cc2fa984b9b9120e
2,508
cpp
C++
Count_test.cpp
som-dev/Count
68caf6014ce067ac0e0129454db2c6b131f3380d
[ "MIT" ]
null
null
null
Count_test.cpp
som-dev/Count
68caf6014ce067ac0e0129454db2c6b131f3380d
[ "MIT" ]
null
null
null
Count_test.cpp
som-dev/Count
68caf6014ce067ac0e0129454db2c6b131f3380d
[ "MIT" ]
null
null
null
#include "DefineCounters.hpp" #include "gtest/gtest.h" namespace // anonymous { template <typename T> class CounterTest : public ::testing::Test { public: typedef Count::Counter<T> Counter; }; using CounterTestTypes = ::testing::Types< char, unsigned char, short, unsigned short, int, unsigned int, long int, unsigned long int, size_t>; TYPED_TEST_SUITE(CounterTest, CounterTestTypes); TYPED_TEST(CounterTest, Constructor) { std::string expectedCounterName = "Test Counter Name"; typename TestFixture::Counter counter(expectedCounterName); EXPECT_EQ(counter, 0); EXPECT_EQ(counter.Name(), expectedCounterName); } TYPED_TEST(CounterTest, PostIncrement) { typename TestFixture::Counter counter("Test"); EXPECT_EQ(counter++, 0); EXPECT_EQ(counter++, 1); EXPECT_EQ(counter++, 2); } TYPED_TEST(CounterTest, PreIncrement) { typename TestFixture::Counter counter("Test"); EXPECT_EQ(++counter, 1); EXPECT_EQ(++counter, 2); EXPECT_EQ(++counter, 3); } TYPED_TEST(CounterTest, operator_plus_equal) { typename TestFixture::Counter counter("Test"); EXPECT_EQ(counter += 10, 10); } TYPED_TEST(CounterTest, operator_assignment) { typename TestFixture::Counter counter("Test"); counter = 123; EXPECT_EQ(counter, 123); } DEFINE_COUNTERS(TestCounters, A, B, C, TestCounterD ); TEST(DefineCounters, ConstructorSizeName) { TestCounters counters; EXPECT_EQ(counters.Size(), 4); EXPECT_EQ(counters.get<TestCounters::A>(), 0); EXPECT_EQ(counters.get<TestCounters::B>(), 0); EXPECT_EQ(counters.get<TestCounters::C>(), 0); EXPECT_EQ(counters.get<TestCounters::C>(), 0); EXPECT_EQ(counters.get<TestCounters::A>().Name(), "A"); EXPECT_EQ(counters.get<TestCounters::B>().Name(), "B"); EXPECT_EQ(counters.get<TestCounters::C>().Name(), "C"); EXPECT_EQ(counters.get<TestCounters::TestCounterD>().Name(), "TestCounterD"); } DEFINE_COUNTERS(TestCountersForReset, A, B, C); TEST(DefineCounters, Reset) { TestCountersForReset counters; counters.get<counters.A>() = 10; counters.get<counters.B>() = 100; counters.get<counters.C>() = 1000; EXPECT_EQ(counters.get<counters.A>(), 10); EXPECT_EQ(counters.get<counters.B>(), 100); EXPECT_EQ(counters.get<counters.C>(), 1000); counters.Reset(); EXPECT_EQ(counters.get<counters.A>(), 0); EXPECT_EQ(counters.get<counters.B>(), 0); EXPECT_EQ(counters.get<counters.C>(), 0); } } // namespace anonymous
26.680851
81
0.689793
som-dev
30dd8562f1660168b8dfe9e37926033955f4dcb3
1,448
hpp
C++
test/include/nuschl/unittests/vector_printer.hpp
behlec/nuschl
35dbdd6dca8e59387623cc8a23f71324e07ea98c
[ "MIT" ]
null
null
null
test/include/nuschl/unittests/vector_printer.hpp
behlec/nuschl
35dbdd6dca8e59387623cc8a23f71324e07ea98c
[ "MIT" ]
null
null
null
test/include/nuschl/unittests/vector_printer.hpp
behlec/nuschl
35dbdd6dca8e59387623cc8a23f71324e07ea98c
[ "MIT" ]
null
null
null
#pragma once // clang-format off #include <boost/test/unit_test.hpp> #include <boost/test/test_tools.hpp> // clang-format on #include <nuschl/s_exp.hpp> #include <iostream> #include <vector> std::ostream &operator<<(std::ostream &os, const std::vector<int> &vec); std::ostream &operator<<(std::ostream &os, const std::vector<std::string> &vec); std::ostream &operator<<(std::ostream &os, const std::vector<std::vector<std::string>> &vec); std::ostream &operator<<(std::ostream &os, const std::vector<const nuschl::s_exp *> &vec); namespace boost { namespace test_tools { namespace tt_detail { template <> struct print_log_value<std::vector<int>> { void operator()(std::ostream &os, std::vector<int> const &vec) { ::operator<<(os, vec); } }; template <> struct print_log_value<std::vector<std::string>> { void operator()(std::ostream &os, std::vector<std::string> const &vec) { ::operator<<(os, vec); } }; template <> struct print_log_value<std::vector<std::vector<std::string>>> { void operator()(std::ostream &os, std::vector<std::vector<std::string>> const &vec) { ::operator<<(os, vec); } }; template <> struct print_log_value<std::vector<const nuschl::s_exp *>> { void operator()(std::ostream &os, std::vector<const nuschl::s_exp *> const &vec) { ::operator<<(os, vec); } }; } } }
27.846154
80
0.61326
behlec
30e549f21dcaeb32f35b09eac05118becd16f41b
1,842
cpp
C++
COCI/PATULJCI.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
1
2017-10-01T00:51:39.000Z
2017-10-01T00:51:39.000Z
COCI/PATULJCI.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
COCI/PATULJCI.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <fstream> #include <cstdlib> #include <cstring> #include <cstdio> #include <string> #include <vector> #include <cmath> #include <queue> #include <map> #include <set> using namespace std; int N,C,M; int cs[300001]; vector<int> cis[10001]; int cunt(int a,int b,int c) { return upper_bound(cis[c].begin(),cis[c].end(),b)-lower_bound(cis[c].begin(),cis[c].end(),a); } int tree[2000000]; void update(int node,int a,int b) { if(a > b) return; if(a == b) { tree[node] = cs[a]; return; } update(node*2, a, (a+b)/2); update(node*2+1, (a+b)/2+1, b); if(tree[node*2] == tree[node*2+1]) { tree[node] = tree[node*2]; } else { int c1 = cunt(a,b,tree[node*2]); int c2 = cunt(a,b,tree[node*2+1]); if(c1 > c2 && c1 > (b-a+1)/2) tree[node] = tree[node*2]; else if( c2 > c1 && c2 > (b-a+1)/2) tree[node] = tree[node*2+1]; else tree[node] = 0; } } int query(int node, int a,int b,int i,int j) { if( a > b || j < a || i > b) return 0; //printf("%d %d %d %d %d: %d\n",node, a,b,i,j,tree[node]); if( a>=i && b<=j ) return tree[node]; int c1 = query(node*2, a,(a+b)/2,i,j); int c2 = query(node*2+1, (a+b)/2+1,b,i,j); if(c1 == c2) { return c1; } else { //i - j int n1 = cunt(i,j,c1); int n2 = cunt(i,j,c2); if(n1 > n2 && n1 > (j-i+1)/2) return c1; else if( n2 > n1 && n2 > (j-i+1)/2) return c2; else return 0; } } int main() { scanf("%d%d",&N,&C); for(int i=1;i<=N;i++) { scanf("%d",cs+i); cis[cs[i]].push_back(i); } update(1,1,N); scanf("%d",&M); for(int i=0;i!=M;i++) { int a,b; scanf("%d%d",&a,&b); int c = query(1,1,N,a,b); if(!c) { cout << "no" << endl; } else { cout << "yes " << c << endl; } } return 0; }
19.1875
95
0.505972
zzh8829
30eed884d544b2307a3ba04a3e865cfebe277d50
1,028
cpp
C++
ui/logview.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
1
2022-02-23T03:15:54.000Z
2022-02-23T03:15:54.000Z
ui/logview.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
null
null
null
ui/logview.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
null
null
null
#include "uiinfra/logview.h" #include "ui_logview.h" #include <qevent.h> #include <qtimer.h> namespace inf::ui { static auto s_maxUpdateInterval = std::chrono::milliseconds(200); LogView::LogView(QWidget* parent) : QWidget(parent) , _ui(std::make_unique<Ui::LogView>()) , _timer(new QTimer(this)) { _ui->setupUi(this); connect(_timer, &QTimer::timeout, this, &LogView::updateView); } LogView::~LogView() = default; void LogView::setModel(QAbstractItemModel* model) { _ui->tableView->setModel(model); connect(model, &QAbstractItemModel::rowsInserted, this, [this]() { if (!_timer->isActive()) { updateView(); _timer->start(s_maxUpdateInterval); } }); } void LogView::resizeEvent(QResizeEvent* event) { _ui->tableView->horizontalHeader()->resizeSection(0, event->size().width()); QWidget::resizeEvent(event); } void LogView::updateView() { _timer->stop(); if (_ui->tableView->isVisible()) { _ui->tableView->scrollToBottom(); } } }
20.56
80
0.654669
VITObelgium
30f0492c13b7d0c77afdb5ff14fd3b37c0725986
32,079
cpp
C++
esl/economics/markets/walras/tatonnement.cpp
vishalbelsare/ESL
cea6feda1e588d5f441742dbb1e4c5479b47d357
[ "Apache-2.0" ]
37
2019-10-13T12:23:32.000Z
2022-03-19T10:40:29.000Z
esl/economics/markets/walras/tatonnement.cpp
vishalbelsare/ESL
cea6feda1e588d5f441742dbb1e4c5479b47d357
[ "Apache-2.0" ]
3
2020-03-20T04:44:06.000Z
2021-01-12T06:18:33.000Z
esl/economics/markets/walras/tatonnement.cpp
vishalbelsare/ESL
cea6feda1e588d5f441742dbb1e4c5479b47d357
[ "Apache-2.0" ]
10
2019-11-06T15:59:06.000Z
2021-08-09T17:28:24.000Z
/// \file tatonnement.hpp /// /// \brief Implements the tรขtonnement process (hill climbing), implemented as a /// numerical optimisation. /// /// \authors Maarten P. Scholl /// \date 2018-02-02 /// \copyright Copyright 2017-2019 The Institute for New Economic Thinking, /// Oxford Martin School, University of Oxford /// /// 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. /// /// You may obtain instructions to fulfill the attribution /// requirements in CITATION.cff /// #include <esl/economics/markets/walras/tatonnement.hpp> #include <gsl/gsl_vector.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_multiroots.h> #pragma warning(push, 0) // supress warnings in MSVC from external code #include <adept_source.h> #pragma warning(pop) #include <esl/economics/markets/quote.hpp> #include <esl/data/log.hpp> #include <esl/mathematics/variable.hpp> #include <esl/invalid_parameters.hpp> using esl::economics::markets::tatonnement::excess_demand_model; using esl::/*mathematics::*/variable; /// /// \brief C compatible callback for the minimizer to find the function value. /// /// \param variables /// \param params Pointer to the excess_demand_model instance /// extern "C" double c_minimizer_function_value ( const gsl_vector *variables , void *model) { auto *model_ = static_cast<excess_demand_model *>(model); assert(model_ && "parameter must be (excess_demand_model *)"); return model_->excess_demand_function_value(variables->data); } /// /// \req this function should store the vector result f(x,params) /// in f for argument x and parameters params, returning an appropriate /// error code if the function cannot be computed. /// /// extern "C" int multiroot_function_value_cb(const gsl_vector *x, void *params, gsl_vector *f) { auto *model_ = static_cast<excess_demand_model *>(params); assert(model_ && "parameter must be (excess_demand_model *)"); auto cb_ = model_->multiroot_function_value(x->data); for(size_t i = 0; i < cb_.size(); ++i){ gsl_vector_set(f, i, cb_[i]); } return GSL_SUCCESS; } #if !defined(ADEPT_VERSION) || !defined(ADEPT_NO_AUTOMATIC_DIFFERENTIATION) /// /// \brief C wrapper for minimization problem, gsl callback /// Return gradient of function with respect to each state variable x /// extern "C" void c_minimizer_function_gradient( const gsl_vector *x , void *params , gsl_vector *gradient) { auto *model_ = static_cast<excess_demand_model *>(params); assert(model_ && "parameter must be (excess_demand_model *)"); model_->minimizer_function_value_and_gradient(x->data, gradient->data); } /// /// \req this function should store the n-by-n matrix result /// J_{ij} = \partial f_i(x,\hbox{\it params}) / \partial x_j /// in J for argument x and parameters params, returning an appropriate /// error code if the function cannot be computed. /// /// extern "C" int multiroot_function_jacobian_cb(const gsl_vector * x, void * params, gsl_matrix * df) { auto *model_ = static_cast<excess_demand_model *>(params); assert(model_ && "parameter must be (excess_demand_model *)"); auto cb_ = model_->multiroot_function_value_and_gradient(x->data, df->data); return GSL_SUCCESS; } /// /// \brief C wrapper for minimization problem /// extern "C" void c_minimizer_function_value_and_gradient ( const gsl_vector *x , void *params , double *jacobian , gsl_vector *gradient ) { auto *model_ = static_cast<excess_demand_model *>(params); assert(model_ && "parameter must be (excess_demand_model *)"); *jacobian = model_->minimizer_function_value_and_gradient(x->data, gradient->data); } /// /// \brief /// extern "C" int multiroot_function_value_and_gradient_cb( const gsl_vector *x , void *params , gsl_vector *f , gsl_matrix *df ) { auto *model_ = static_cast<excess_demand_model *>(params); assert(model_ && "parameter must be (excess_demand_model *)"); auto cb_ = model_->multiroot_function_value_and_gradient(x->data, df->data); for(size_t i = 0; i < cb_.size(); ++i){ gsl_vector_set(f, i, cb_[i]); } return GSL_SUCCESS; } extern "C" double uniroot_function_value (double x, void *params) { auto *model_ = static_cast<excess_demand_model *>(params); assert(model_ && "parameter must be (excess_demand_model *)"); auto cb_ = model_->multiroot_function_value(&x); return cb_[0]; } extern "C" double uniroot_function_value_and_gradient (double x, void *params) { auto *model_ = static_cast<excess_demand_model *>(params); assert(model_ && "parameter must be (excess_demand_model *)"); double df = 0.; auto cb_ = model_->multiroot_function_value_and_gradient(&x, &df); return df; } extern "C" void uniroot_function_jacobian_cb ( double x , void *params , double *f , double *df) { auto *model_ = static_cast<excess_demand_model *>(params); assert(model_ && "parameter must be (excess_demand_model *)"); double jacobian_ = 0.; auto cb_ = model_->multiroot_function_value_and_gradient(&x, &jacobian_); *f = cb_[0]; if(!std::isfinite(jacobian_)){ jacobian_ = (x-1); } *df = jacobian_; } #endif /// /// \brief Callback for errors from the optimizer. /// \details We silence errors /// /// \param reason /// \param file /// \param line /// \param gsl_errno void handler ([[maybe_unused]] const char *reason, [[maybe_unused]] const char *file, [[maybe_unused]] int line, [[maybe_unused]] int gsl_errno) { } namespace esl::economics::markets::tatonnement { /// /// \brief Initializes a stack for automatic differentiation /// /// \param initial_quotes excess_demand_model::excess_demand_model( law::property_map<quote> initial_quotes) : quotes(initial_quotes) #if defined(ADEPT_VERSION) , stack_() #endif { } excess_demand_model::~excess_demand_model() = default; /// /// \brief The optimisation version of the market clearing problem, /// with automatic differentiation /// /// \param x /// \return adept::adouble excess_demand_model::demand_supply_mismatch(const adept::adouble *x) { std::map<identity<law::property>, std::tuple<quote, adept::adouble>> quote_scalars_; size_t n = 0; for(auto [k, v]: quotes) { quote_scalars_.emplace(*k, std::make_tuple(v, x[n])); ++n; } std::map<identity<law::property>, adept::adouble> terms_map; for(const auto &f : excess_demand_functions_) { auto demand_per_property_ = f->excess_demand(quote_scalars_); for(auto [k, v]: demand_per_property_) { if(terms_map.find(k) == terms_map.end()){ terms_map.emplace(k, v); }else{ (terms_map.find(k)->second) += v; } } } variable target_ = 0.0; for(auto [p, t] : terms_map) { (void)p; target_ += (pow(t, 2)); } //LOG(notice) << " clearing error " << target_.value() << std::endl; return target_; } /// /// \brief Root-finding version of the market clearing problem. /// /// \details Tries to set excess demand for all goods to zero, for all /// goods individually. /// \param x /// \return std::vector<variable> excess_demand_model::excess_demand(const variable *x) { std::map<identity<law::property>, std::tuple<quote, variable>> quote_scalars_; size_t n = 0; for(auto [k, v]: quotes) { quote_scalars_.emplace(*k, std::make_tuple(v, x[n])); ++n; } std::map<identity<law::property>, variable> terms_map; for(const auto &f : excess_demand_functions_) { auto demand_per_property_ = f->excess_demand(quote_scalars_); for(auto [k, ed]: demand_per_property_) { auto i = terms_map.emplace(k, variable(0.)); i.first->second += ed;//long_ + ed - short_; } } std::vector<variable> result_; for(auto [k, v]: quotes) { assert(terms_map.end() != terms_map.find(*k)); result_.push_back(terms_map.find(*k)->second); } return result_; } /// /// \brief Used to convert the optimization version of the problem back to /// machine double precision floats. /// Also uused when not using automatic differentiation. /// /// \param multipliers Price multipliers /// \return double excess_demand_model::excess_demand_function_value(const double *multipliers) { stack_.pause_recording(); for(unsigned int i = 0; i < active_.size(); ++i) { active_[i] = multipliers[i]; } double result = adept::value(demand_supply_mismatch(&active_[0])); stack_.continue_recording(); return result; } /// /// \brief Wraps the root finding problem (value only) /// /// \param x /// \return std::vector<double> excess_demand_model::multiroot_function_value(const double *multipliers) { stack_.pause_recording(); for(unsigned int i = 0; i < active_.size(); ++i) { active_[i] = multipliers[i]; } auto intermediate_ = excess_demand(&active_[0]); std::vector<double> result; for(const auto &v: intermediate_){ result.push_back(adept::value(v)); } stack_.continue_recording(); return result; } /// /// \brief wrapper for minimization problem, value and gradient /// /// \param x /// \param dJ_dx /// \return double excess_demand_model::minimizer_function_value_and_gradient(const double *multipliers, double *derivatives) { for(unsigned int i = 0; i < active_.size(); ++i) { active_[i] = multipliers[i]; } stack_.new_recording(); adept::adouble derivative_ = demand_supply_mismatch(&active_[0]); // in the minimization problem, the output is a single scalar derivative_.set_gradient(1.0); stack_.compute_adjoint(); adept::get_gradients(&active_[0], active_.size(), derivatives); return adept::value(derivative_); } /// /// \brief Root-finding version, value and gradient wrapper. /// /// \param multipliers Price multipliers /// \param jacobian output for jacobian matrix /// \return std::vector<double> excess_demand_model::multiroot_function_value_and_gradient ( const double *multipliers , double *jacobian ) { for(unsigned int i = 0; i < active_.size(); ++i) { active_[i] = multipliers[i]; } stack_.new_recording(); auto values_ = excess_demand(&active_[0]); stack_.independent(&active_[0], active_.size()); stack_.dependent(&values_[0], values_.size()); stack_.jacobian(jacobian); std::vector<double> result_; for(auto &v : values_) { result_.emplace_back(adept::value(v)); } return result_; } /// /// \brief Goes through the selected solution methods and applies them. /// /// \return numerical approximate multipliers for the quotes std::optional<std::map<identity<law::property>, double>> excess_demand_model::compute_clearing_quotes(size_t max_iterations) { if(methods.empty()){ const auto error_no_solvers_ = "no solution method specified"; LOG(errorlog) << error_no_solvers_ << std::endl; throw esl::invalid_parameters(error_no_solvers_); } for(auto method_: methods){ // for every method we try, we need to reset our variables active_.clear(); std::vector<identity<law::property>> mapping_index_; mapping_index_.reserve(quotes.size()); // initial values are the solutions at the previous time step, or // the initial values provided to the model if this is the first for(auto [k, v] : quotes) { (void) v; mapping_index_.emplace_back(*k); active_.emplace_back(1.0 ); } // root finding methods try to set excess demand to zero for // all properties traded in the market if (method_ == root){ // This compile time definition is here such that the library will still compile // when Adept is absent. #if defined(ADEPT_VERSION) && !defined(ADEPT_NO_AUTOMATIC_DIFFERENTIATION) // if there is only one property traded, we specialize with // algorithms that do well on univariate root finding if(1 == quotes.size()){ constexpr double absolute_tolerance = 1e-6; // capture previous error handler to restore later auto old_handler_ = gsl_set_error_handler (&handler); // solver and solver type const gsl_root_fdfsolver_type *solver_type_; gsl_root_fdfsolver *s; // the initial guess is 1 times the previous quote double xt = 1.; // the function structure with gradient and jacobian gsl_function_fdf target_; target_.f = &uniroot_function_value; target_.df = &uniroot_function_value_and_gradient; target_.fdf = &uniroot_function_jacobian_cb; target_.params = static_cast<void *>(this); // use steffenson's method // Newton algorithm with an Aitken "delta-squared" acceleration solver_type_ = gsl_root_fdfsolver_steffenson; s = gsl_root_fdfsolver_alloc (solver_type_); gsl_root_fdfsolver_set (s, &target_, xt); size_t iteration_ = 0; int status_; double best_quote_ = 1.0; double best_error_ = uniroot_function_value(best_quote_, this);//std::numeric_limits<double>::max(); do { ++iteration_; // perform one solver step status_ = gsl_root_fdfsolver_iterate(s); // store initial position to compute delta xt = gsl_root_fdfsolver_root(s); auto errors_ = uniroot_function_value(xt, this); if(abs(errors_) < abs(best_error_)){ best_error_ = errors_; best_quote_ = xt; } if(abs(errors_) < absolute_tolerance){ status_ = GSL_SUCCESS; break; } //status_ = gsl_root_test_delta (xt, x0, delta_absolute_tolerance, delta_relative_tolerance); } while (GSL_CONTINUE == status_ && iteration_ < max_iterations); if (GSL_SUCCESS == status_) { std::map<esl::identity<esl::law::property>, double> result_; // apply circuit breaker retro-actively best_quote_ = std::max(best_quote_, circuit_breaker.first); best_quote_ = std::min(best_quote_, circuit_breaker.second); result_.emplace(mapping_index_[0], best_quote_); gsl_root_fdfsolver_free (s); return result_; } gsl_root_fdfsolver_free (s); // reset the old error handler. gsl_set_error_handler(old_handler_); } else { // else, we solve for multiple roots at once // TODO: set adaptively constexpr double residual_tolerance = 1e-4; gsl_multiroot_function_fdf target_; target_.n = active_.size(); target_.f = &multiroot_function_value_cb; target_.df = &multiroot_function_jacobian_cb; target_.fdf = &multiroot_function_value_and_gradient_cb; target_.params = static_cast<void *>(this); gsl_vector *variables_ = gsl_vector_alloc(active_.size()); for (size_t i = 0; i < active_.size(); ++i) { // initial solution is 1.0 times previous prices gsl_vector_set(variables_, i, 1.); } // modified version of Powellโ€™s Hybrid method const gsl_multiroot_fdfsolver_type *solver_t_ = gsl_multiroot_fdfsolver_hybridsj; gsl_multiroot_fdfsolver *solver_ = gsl_multiroot_fdfsolver_alloc(solver_t_, active_.size()); gsl_multiroot_fdfsolver_set(solver_, &target_, variables_); int status = GSL_CONTINUE; for (size_t i = 0; i < max_iterations && GSL_CONTINUE == status; ++i) { status = gsl_multiroot_fdfsolver_iterate(solver_); if (GSL_SUCCESS != status) { break; } status = gsl_multiroot_test_residual(solver_->f, residual_tolerance); } if (GSL_SUCCESS == status) { std::map<esl::identity<law::property>, double> result_; auto solver_best_ = gsl_multiroot_fdfsolver_root(solver_); for (size_t i = 0; i < active_.size(); ++i) { auto scalar_ = gsl_vector_get(solver_best_, i); // apply circuit breaker scalar_ = std::min(scalar_, circuit_breaker.second); scalar_ = std::max(scalar_, circuit_breaker.first); result_.emplace(mapping_index_[i], scalar_); } gsl_multiroot_fdfsolver_free(solver_); gsl_vector_free(variables_); return result_; } gsl_multiroot_fdfsolver_free(solver_); gsl_vector_free(variables_); } #else constexpr double residual_tolerance = 1e-4; gsl_multiroot_function root_function; root_function.n = active_.size(); root_function.f = &multiroot_function_value_cb; //root_function.df = &multiroot_function_jacobian_cb; //root_function.fdf = &multiroot_function_value_and_gradient_cb; root_function.params = static_cast<void *>(this); gsl_vector *variables_ = gsl_vector_alloc(active_.size()); for(size_t i = 0; i < active_.size(); ++i) { gsl_vector_set(variables_, i, 1.0); } // Powell's Hybrid method, but with finite-difference approximation const gsl_multiroot_fsolver_type *solver_t_ = gsl_multiroot_fsolver_hybrids; gsl_multiroot_fsolver *solver_ = gsl_multiroot_fsolver_alloc(solver_t_, active_.size()); gsl_multiroot_fsolver_set (solver_, &root_function, variables_); int status = GSL_CONTINUE; for(size_t iter = 0; iter < max_iterations && GSL_CONTINUE == status; ++iter){ status = gsl_multiroot_fsolver_iterate (solver_); if (GSL_SUCCESS != status){ break; } status = gsl_multiroot_test_residual (solver_->f, residual_tolerance); } std::map<esl::identity<esl::law::property>, double> result_; for(size_t i = 0; i < active_.size(); ++i) { result_.emplace(mapping_index_[i], gsl_vector_get(solver_->x, i)); } gsl_multiroot_fsolver_free (solver_); gsl_vector_free(variables_); #endif continue; }else if (method_ == minimization){ // If Adept is absent #if !defined(ADEPT_VERSION) || !defined(ADEPT_NO_AUTOMATIC_DIFFERENTIATION) // TODO: set adaptively constexpr double initial_step_size = 1.0e-5; constexpr double line_search_tolerance = 1.0e-5; constexpr double converged_gradient_norm = 1.0e-4; constexpr double error_tolerance = 0.0001; // we use the vector Broyden-Fletcher-Goldfarb-Shanno algorithm const auto *minimizer_type = gsl_multimin_fdfminimizer_vector_bfgs2; gsl_multimin_function_fdf target_; target_.n = active_.size(); target_.f = c_minimizer_function_value; target_.df = c_minimizer_function_gradient; target_.fdf = c_minimizer_function_value_and_gradient; target_.params = static_cast<void *>(this); gsl_vector *x = gsl_vector_alloc(active_.size()); for(size_t i = 0; i < active_.size(); ++i) { // initial solution is 1.0 * previous quote gsl_vector_set(x, i, 1.0); } auto *minimizer = gsl_multimin_fdfminimizer_alloc(minimizer_type, active_.size()); gsl_multimin_fdfminimizer_set(minimizer, &target_, x, initial_step_size, line_search_tolerance); size_t iteration_ = 0; int status; do { ++iteration_; status = gsl_multimin_fdfminimizer_iterate(minimizer); std::vector<double> solution_; for(size_t param = 0; param < active_.size(); ++param){ solution_.push_back(gsl_vector_get (minimizer->x, param)); } auto error_ = excess_demand_function_value(&solution_[0]); if(error_ <= error_tolerance){ status = GSL_SUCCESS; break; } if(status != GSL_SUCCESS) { break; } status = gsl_multimin_test_gradient(minimizer->gradient, converged_gradient_norm); } while(GSL_CONTINUE == status && iteration_ < max_iterations); if(status == GSL_SUCCESS){ std::map<esl::identity<esl::law::property>, double> result_; for(size_t i = 0; i < active_.size(); ++i) { auto scalar_ = gsl_vector_get (minimizer->x, i); result_.insert({mapping_index_[i], scalar_}); } gsl_multimin_fdfminimizer_free(minimizer); gsl_vector_free(x); return result_; } gsl_multimin_fdfminimizer_free(minimizer); gsl_vector_free(x); #else LOG(errorlog) << "gradient-free minimizer failed after " << iteration_ << " iterations: " << gsl_strerror(status) << std::endl; #endif }else if (method_ == derivative_free_minimization) { // TODO: set adaptively auto initial_step_size = gsl_vector_alloc(active_.size()); constexpr double error_tolerance = 0.0001; // we use the vector Broyden-Fletcher-Goldfarb-Shanno algorithm const gsl_multimin_fminimizer_type *minimizer_type = gsl_multimin_fminimizer_nmsimplex2; //const auto *minimizer_type = gsl_multimin_fdfminimizer_vector_bfgs2; gsl_multimin_function target_; target_.n = active_.size(); target_.f = c_minimizer_function_value; //target_.df = c_minimizer_function_gradient; //target_.fdf = c_minimizer_function_value_and_gradient; target_.params = static_cast<void *>(this); gsl_vector *x = gsl_vector_alloc(active_.size()); for(size_t i = 0; i < active_.size(); ++i) { // initial solution is 1.0 * previous quote gsl_vector_set(x, i, 1.0); } auto *minimizer = gsl_multimin_fminimizer_alloc (minimizer_type, active_.size()); gsl_multimin_fminimizer_set (minimizer, &target_, x, initial_step_size //, line_search_tolerance ); size_t iteration_ = 0; int status; do { ++iteration_; status = gsl_multimin_fminimizer_iterate(minimizer); std::vector<double> solution_; for(size_t param = 0; param < active_.size(); ++param){ solution_.push_back(gsl_vector_get (minimizer->x, param)); } auto error_ = excess_demand_function_value(&solution_[0]); if(error_ <= error_tolerance){ status = GSL_SUCCESS; break; } if(status != GSL_SUCCESS) { break; } status = gsl_multimin_test_size (active_.size(), error_tolerance); //status = gsl_multimin_test_gradient(minimizer->gradient, // converged_gradient_norm); } while(GSL_CONTINUE == status && iteration_ < max_iterations); if(status == GSL_SUCCESS){ std::map<esl::identity<esl::law::property>, double> result_; for(size_t i = 0; i < active_.size(); ++i) { auto scalar_ = gsl_vector_get (minimizer->x, i); result_.insert({mapping_index_[i], scalar_}); } gsl_multimin_fminimizer_free(minimizer); gsl_vector_free(x); gsl_vector_free(initial_step_size); return result_; } gsl_multimin_fminimizer_free(minimizer); gsl_vector_free(x); gsl_vector_free(initial_step_size); }else if (method_ == derivative_free_root) { constexpr double residual_tolerance = 1e-4; gsl_multiroot_function root_function; root_function.n = active_.size(); root_function.f = &multiroot_function_value_cb; root_function.params = static_cast<void *>(this); constexpr auto start_multiplier_ = 1.0; std::vector<double> multipliers_; double best_residual_ = 0; gsl_vector *variables_ = gsl_vector_alloc(active_.size()); for(size_t i = 0; i < active_.size(); ++i) { gsl_vector_set(variables_, i, start_multiplier_); multipliers_.push_back(start_multiplier_); best_residual_ += abs(start_multiplier_); } // Powell's Hybrid method, but with finite-difference approximation const gsl_multiroot_fsolver_type *solver_t_ = gsl_multiroot_fsolver_hybrids; gsl_multiroot_fsolver *solver_ = gsl_multiroot_fsolver_alloc(solver_t_, active_.size()); gsl_multiroot_fsolver_set (solver_, &root_function, variables_); int status = GSL_CONTINUE; //LOG(trace) << "initial status = " << status << std::endl; for(size_t iter = 0; iter < max_iterations && GSL_CONTINUE == status; ++iter){ //LOG(trace) << "iter = " << iter << "/" << max_iterations<< std::endl; status = gsl_multiroot_fsolver_iterate (solver_); if (GSL_SUCCESS != status){ //LOG(trace) << "status = " << status << std::endl; break; } status = gsl_multiroot_test_residual (solver_->f, residual_tolerance); if(GSL_SUCCESS == status){ double residual_ = 0.; for(size_t i = 0; i < active_.size(); ++i) { residual_ += abs(gsl_vector_get(solver_->f, i)); } //LOG(trace) << "residual_" << residual_ << std::endl; if(residual_ < best_residual_) { best_residual_ = residual_; for(size_t i = 0; i < active_.size(); ++i) { multipliers_[i] = gsl_vector_get(solver_->x, i); //LOG(trace) << "updating multipliers_[" << i << "] " << multipliers_[i] << std::endl; } } break; } if(GSL_CONTINUE != status) { break; } double residual_ = 0.; for(size_t i = 0; i < active_.size(); ++i) { residual_ += abs(gsl_vector_get(solver_->f, i)); } //LOG(trace) << "residual_" << residual_ << std::endl; if(residual_ < best_residual_) { best_residual_ = residual_; for(size_t i = 0; i < active_.size(); ++i) { multipliers_[i] = gsl_vector_get(solver_->x, i); //LOG(trace) << "udating multipliers_[" << i << "] " << multipliers_[i] << std::endl; } } } //LOG(trace) << "final status = " << status << std::endl; std::map<esl::identity<esl::law::property>, double> result_; for(size_t i = 0; i < active_.size(); ++i) { //LOG(trace) << "outcome: " << multipliers_[i] << std::endl; result_.emplace(mapping_index_[i], multipliers_[i]); } gsl_multiroot_fsolver_free (solver_); gsl_vector_free(variables_); return result_; } } return std::nullopt; } } // namespace tatonnement
39.948941
120
0.547056
vishalbelsare
30f08690e448df39c2889d227793a0054a3f0339
842
cpp
C++
Depth-first Search/max-area-of-island.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Medium/max-area-of-island.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Medium/max-area-of-island.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: void findarea(vector<vector<int>>& grid,int r,int c,int &t) { grid[r][c]=0,t++; if(r+1<grid.size()&&grid[r+1][c]) findarea(grid,r+1,c,t); if(r-1>=0&&grid[r-1][c]) findarea(grid,r-1,c,t); if(c+1<grid[0].size()&&grid[r][c+1]) findarea(grid,r,c+1,t); if(c-1>=0&&grid[r][c-1]) findarea(grid,r,c-1,t); } int maxAreaOfIsland(vector<vector<int>>& grid) { int t,area=0; for(int i=0;i<grid.size();i++) { for(int j=0;j<grid[i].size();j++) { if(grid[i][j]) { t=0,findarea(grid,i,j,t); if(t>area) area=t; } } } return area; } };
26.3125
63
0.388361
PrakharPipersania
30f193a757d6a35bd19a711a276b02e2fcbfbcba
174
cpp
C++
address1.cpp
Biteliuying/address
d2ef3a79b214d5282e8307cde741a8938830d6b2
[ "Apache-2.0" ]
null
null
null
address1.cpp
Biteliuying/address
d2ef3a79b214d5282e8307cde741a8938830d6b2
[ "Apache-2.0" ]
1
2022-02-10T15:28:30.000Z
2022-02-10T15:28:30.000Z
address1.cpp
Biteliuying/address
d2ef3a79b214d5282e8307cde741a8938830d6b2
[ "Apache-2.0" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> int main() { char a,b; a = 'a'; b = 'b'; putchar(a); putchar('\n'); putchar(b); printf("\n%c\n%c", a,b); }
14.5
32
0.545977
Biteliuying
30f54b4f48d2376297310dd98ca85d87ff9407b5
1,359
tcc
C++
include/bits/sqlite_iterator.tcc
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
include/bits/sqlite_iterator.tcc
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
include/bits/sqlite_iterator.tcc
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
// // Copyright Sundeep S. Sangha 2013 - 2017. // 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 DATA_PATTERN_SQLITE_SQLITE_ITERATOR_TCC #define DATA_PATTERN_SQLITE_SQLITE_ITERATOR_TCC #include <iterator> #include <memory> namespace data_pattern_sqlite { template <typename T> sqlite_iterator_input<T>::sqlite_iterator_input ( sqlite_statement & _stmt ) : stmt (& _stmt) , temp () , got_var (false) , index (_stmt.index) {} template <typename T> sqlite_iterator_input<T>::sqlite_iterator_input ( sqlite_statement & _stmt , int _index ) : stmt (& _stmt) , temp () , got_var (false) , index (_index) {} template <typename T> template <typename U> sqlite_iterator_input<T>::sqlite_iterator_input ( sqlite_statement & _stmt , sqlite_iterator_input<U> const & _stmt2 ) : stmt (& _stmt) , temp () , got_var (false) , index (_stmt2.index) {} template <typename T> sqlite_iterator_input<T>::sqlite_iterator_input () : stmt (nullptr) , temp () , got_var(true) , index(-1) {} sqlite_iterator_output::sqlite_iterator_output ( sqlite_statement & _stmt ) : stmt (& _stmt) , index (1+_stmt.index) {} sqlite_iterator_output::sqlite_iterator_output () : stmt (nullptr) , index (-1) {} } /* data_pattern_sqlite */ #endif
18.875
61
0.721854
vashman
30f6a483bbbcea158e3a1f7db24adebe272959f3
584
cpp
C++
KM/03code/book/Thinking-In-C-resource-master/C09/c0905.cpp
wangcy6/weekly.github.io
f249bed5cf5a2b14d798ac33086cea0c1efe432e
[ "Apache-2.0" ]
10
2019-03-17T10:13:04.000Z
2021-03-03T03:23:34.000Z
KM/03code/book/Thinking-In-C-resource-master/C09/c0905.cpp
wangcy6/weekly.github.io
f249bed5cf5a2b14d798ac33086cea0c1efe432e
[ "Apache-2.0" ]
44
2018-12-14T02:35:47.000Z
2021-02-06T09:12:10.000Z
KM/03code/book/Thinking-In-C-resource-master/C09/c0905.cpp
wangcy6/weekly
f249bed5cf5a2b14d798ac33086cea0c1efe432e
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <ctime> inline int f1(int a, int b) { a++; a += b; b += a; return a + b; } int f2(int a, int b) { a++; a += b; b += a; return a + b; } int main(void) { clock_t t1, t2; printf("Calculating time...\n"); t1 = clock(); for (int i = 0; i < 10000000; i++) f1(100, 100); t1 = clock() - t1; printf("f1 take %ld clicks(%f seconds)\n", t1, ((float)t1)/CLOCKS_PER_SEC); t2 = clock(); for (int i = 0; i < 10000000; i++) f2(100, 100); t2 = clock() - t2; printf("f2 take %ld clicks(%f seconds)\n", t2, ((float)t2)/CLOCKS_PER_SEC); return 0; }
15.368421
76
0.55137
wangcy6
30fce0782844fc8a96e20fe088fe8cc794d2812c
3,890
cpp
C++
darkness-engine/src/tools/Process.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
6
2019-10-17T11:31:55.000Z
2022-02-11T08:51:20.000Z
darkness-engine/src/tools/Process.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
1
2020-08-11T09:01:29.000Z
2020-08-11T09:01:29.000Z
darkness-engine/src/tools/Process.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
1
2020-06-02T15:48:20.000Z
2020-06-02T15:48:20.000Z
#include "tools/Process.h" #include "tools/Debug.h" #include "tools/PathTools.h" #include "platform/Platform.h" #include <vector> namespace engine { Process::Process( const std::string& executable, const std::string& arguments, const std::string& workingDirectory, OnProcessMessage onMessage) : m_executable{ executable } , m_arguments{ arguments } , m_workingDirectory{ workingDirectory } , m_onMessage{ onMessage } { m_work = std::move( std::unique_ptr<std::thread, std::function<void(std::thread*)>>( new std::thread( // task [&]() { run(); }), // deleter [&](std::thread* ptr) { ptr->join(); delete ptr; })); } int readFromProcessPipe(HANDLE pipe, std::vector<char>& output) { DWORD bytesRead = 0; DWORD availableBytes = 0; char tmp = 0; PeekNamedPipe(pipe, &tmp, 1, NULL, &availableBytes, NULL); if (availableBytes == 0) return bytesRead; output.resize(availableBytes); if (!ReadFile(pipe, output.data(), static_cast<DWORD>(output.size()), &bytesRead, NULL)) ASSERT(false, "Could not read compilation output"); return bytesRead; } void Process::run() { //auto widePath = toWideString(m_executable); //auto wideParameters = toWideString(m_arguments); auto wideWorkingDirectory = toWideString(m_workingDirectory); SECURITY_ATTRIBUTES securityAttributes = {}; securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES); securityAttributes.bInheritHandle = TRUE; HANDLE readPipe, writePipe; CreatePipe(&readPipe, &writePipe, &securityAttributes, 0); PROCESS_INFORMATION processInfo = {}; STARTUPINFO startupInfo = {}; startupInfo.cb = sizeof(STARTUPINFO); startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; startupInfo.wShowWindow = SW_HIDE; startupInfo.hStdOutput = writePipe; startupInfo.hStdError = writePipe; // for some reason having executable as part of arguments works best auto starting = toWideString(m_executable + " " + m_arguments); std::vector<wchar_t> params(starting.size() + 1, 0); memcpy(&params[0], starting.data(), starting.size() * sizeof(wchar_t)); bool res = CreateProcess( NULL,//widePath.data(), params.data(), NULL, NULL, TRUE, 0, NULL, wideWorkingDirectory.data(), &startupInfo, &processInfo ); auto ut = toUtf8String(std::wstring(params.data())); ASSERT(res, "Failed to start process: %", ut.c_str()); std::vector<char> buffer; DWORD waitResult = WAIT_TIMEOUT; while (waitResult != WAIT_OBJECT_0) { waitResult = WaitForSingleObject(processInfo.hProcess, 100); if (waitResult == WAIT_ABANDONED) break; int bytesRead = readFromProcessPipe(readPipe, buffer); while (bytesRead > 0) { std::string currentMessage = std::string(buffer.data(), bytesRead); //LOG("%s", soFar.c_str()); if (m_onMessage) m_onMessage(currentMessage); bytesRead = readFromProcessPipe(readPipe, buffer); } } //if (processInfo.hProcess) // WaitForSingleObject(processInfo.hProcess, INFINITE); CloseHandle(readPipe); CloseHandle(writePipe); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); } }
32.689076
96
0.568638
Karmiska
a50234b69510521939af84a4e1bde78580e5c823
1,118
cpp
C++
DBServer/Main.cpp
Addision/EventServer
2fd13eb5440769da6fb19c6540fb25db09b8cc75
[ "MIT" ]
15
2020-04-22T04:32:12.000Z
2022-01-06T12:40:44.000Z
DBServer/Main.cpp
Addision/EventServer
2fd13eb5440769da6fb19c6540fb25db09b8cc75
[ "MIT" ]
1
2020-11-30T07:20:17.000Z
2020-11-30T07:20:17.000Z
DBServer/Main.cpp
Addision/EventServer
2fd13eb5440769da6fb19c6540fb25db09b8cc75
[ "MIT" ]
8
2020-04-21T02:15:04.000Z
2021-12-31T17:34:02.000Z
#include "DB.h" #include "JsonConfig.h" #include "Util.h" #include "LogUtil.h" #include "SePlatForm.h" #include <signal.h> bool bStopServer = false; void OnSignal(int sig) { switch (sig) { case SIGINT: case SIGTERM: #ifdef SF_PLATFORM_WIN case SIGBREAK: #else case SIGPIPE: #endif { CLOG_ERR << "Master Server Stop !!!, signal=" << sig << CLOG_END; bStopServer = true; break; } default: break; } } void OnHookSignal() { signal(SIGINT, OnSignal); signal(SIGTERM, OnSignal); #ifdef SF_PLATFORM_WIN signal(SIGBREAK, OnSignal); #else signal(SIGPIPE, OnSignal); #endif } int main() { OnHookSignal(); //server config g_pConfig.reset(new JsonConfig()); g_pConfig->Load(SERVER_CFG); g_pConfig->m_ServerConf = g_pConfig->m_Root["DBServer"]; std::cout << g_pConfig->m_ServerConf["NodeName"].asString() << std::endl; //mariadb config g_pConfig->m_dbConf = g_pConfig->m_Root["MariaDB"]; std::cout << g_pConfig->m_dbConf["uri"].asString() << std::endl; INIT_SFLOG("DBServer"); DB db; db.Init(); db.Start(); while (bStopServer == false) { sf_sleep(500); } db.Stop(); return 0; }
15.971429
74
0.678891
Addision
a502a181be3839ebda6aad9ff55c19e4a4eb8099
1,337
cpp
C++
shaders/src/sib_vector_switch.cpp
caron/sitoa
52a0a4b35f51bccb6223a8206d04b40edc80071c
[ "Apache-2.0" ]
34
2018-02-01T16:13:48.000Z
2021-07-16T07:37:47.000Z
shaders/src/sib_vector_switch.cpp
625002974/sitoa
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
[ "Apache-2.0" ]
72
2018-02-16T17:30:41.000Z
2021-11-22T11:41:45.000Z
shaders/src/sib_vector_switch.cpp
625002974/sitoa
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
[ "Apache-2.0" ]
15
2018-02-15T15:36:58.000Z
2021-04-14T03:54:25.000Z
/************************************************************************************************************************************ Copyright 2017 Autodesk, Inc. 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 <ai.h> AI_SHADER_NODE_EXPORT_METHODS(SIBVectorSwitchMethods); enum SIBVectorSwitchParams { p_vector1, p_vector2, p_input }; node_parameters { AiParameterVec ( "vector1", 0.0f, 0.0f, 0.0f ); AiParameterVec ( "vector2", 0.0f, 0.0f, 0.0f ); AiParameterBool( "input" , true ); } node_initialize{} node_update{} node_finish{} shader_evaluate { bool input = AiShaderEvalParamBool(p_input); sg->out.VEC() = AiShaderEvalParamVec(input ? p_vector2 : p_vector1); }
34.282051
134
0.60359
caron
a50d463ed9da3f14cd8ee894f64c8461bb2cb32e
4,983
cpp
C++
Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
1
2021-01-03T21:33:26.000Z
2021-01-03T21:33:26.000Z
Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
null
null
null
Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
1
2020-07-22T14:48:58.000Z
2020-07-22T14:48:58.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'basketview.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../Onket/basketview.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'basketview.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.14.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_BasketView_t { QByteArrayData data[9]; char stringdata0[113]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_BasketView_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_BasketView_t qt_meta_stringdata_BasketView = { { QT_MOC_LITERAL(0, 0, 10), // "BasketView" QT_MOC_LITERAL(1, 11, 18), // "returningRequested" QT_MOC_LITERAL(2, 30, 0), // "" QT_MOC_LITERAL(3, 31, 6), // "update" QT_MOC_LITERAL(4, 38, 16), // "updateFinalPrice" QT_MOC_LITERAL(5, 55, 11), // "removedItem" QT_MOC_LITERAL(6, 67, 4), // "Item" QT_MOC_LITERAL(7, 72, 21), // "on_btn_return_clicked" QT_MOC_LITERAL(8, 94, 18) // "on_btn_buy_clicked" }, "BasketView\0returningRequested\0\0update\0" "updateFinalPrice\0removedItem\0Item\0" "on_btn_return_clicked\0on_btn_buy_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_BasketView[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 6, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 44, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 3, 0, 45, 2, 0x0a /* Public */, 4, 0, 46, 2, 0x08 /* Private */, 5, 1, 47, 2, 0x08 /* Private */, 7, 0, 50, 2, 0x08 /* Private */, 8, 0, 51, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 6, 2, QMetaType::Void, QMetaType::Void, 0 // eod }; void BasketView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<BasketView *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->returningRequested(); break; case 1: _t->update(); break; case 2: _t->updateFinalPrice(); break; case 3: _t->removedItem((*reinterpret_cast< const Item(*)>(_a[1]))); break; case 4: _t->on_btn_return_clicked(); break; case 5: _t->on_btn_buy_clicked(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (BasketView::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&BasketView::returningRequested)) { *result = 0; return; } } } } QT_INIT_METAOBJECT const QMetaObject BasketView::staticMetaObject = { { QMetaObject::SuperData::link<QScrollArea::staticMetaObject>(), qt_meta_stringdata_BasketView.data, qt_meta_data_BasketView, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *BasketView::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *BasketView::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_BasketView.stringdata0)) return static_cast<void*>(this); return QScrollArea::qt_metacast(_clname); } int BasketView::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QScrollArea::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 6) qt_static_metacall(this, _c, _id, _a); _id -= 6; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 6) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 6; } return _id; } // SIGNAL 0 void BasketView::returningRequested() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } QT_WARNING_POP QT_END_MOC_NAMESPACE
30.950311
101
0.609874
IsfahanUniversityOfTechnology-CE2019-23
a50d528cc0ce030f6198e6d87f6ff351af11526d
898
hpp
C++
Examples/PuzzleGenerator/Generator.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
Examples/PuzzleGenerator/Generator.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
Examples/PuzzleGenerator/Generator.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
#ifndef Generator_hpp #define Generator_hpp #include "BFSSearcher.hpp" #include "DFSSearcher.hpp" #include <sstream> #include "Puzzle.hpp" /** * Success functor that checks if the node has the required depth */ struct BranchDepthCheck { private: int goalDepth; public: BranchDepthCheck(int goalDepth) : goalDepth(goalDepth) { } bool operator()(const Node<Puzzle>& node) const { return node.getBranchCost() >= goalDepth; } }; /** * A DFS searcher type that starts with an ordered board with its given size * and then a set number of moves on it. */ class Generator : public DFSSearcher<Puzzle, BranchDepthCheck> { public: typedef DFSSearcher<Puzzle, BranchDepthCheck> Super; public: Generator(int goalDepth); /** * Creates an ordered puzzle and then performs moves on it. */ shared_ptr<Puzzle> generate(int width, int height); }; #endif /* Generator_hpp */
17.607843
77
0.72049
jamesfer
a50e20287e54709ed9a8da4dc392d83a61834f4c
1,661
cpp
C++
GUI/test/alta_participante.cpp
bertilxi/Pegaso
41ddde19f203424d68e8ede3e47450bb22bee0f6
[ "MIT" ]
null
null
null
GUI/test/alta_participante.cpp
bertilxi/Pegaso
41ddde19f203424d68e8ede3e47450bb22bee0f6
[ "MIT" ]
null
null
null
GUI/test/alta_participante.cpp
bertilxi/Pegaso
41ddde19f203424d68e8ede3e47450bb22bee0f6
[ "MIT" ]
null
null
null
#include "alta_participante.h" #include "ui_alta_participante.h" #include "qpixmap.h" alta_participante::alta_participante(GUI *guiP, QWidget *parent) : QDialog(parent), ui(new Ui::alta_participante), gui(guiP) { ui->setupUi(this); QPixmap pix(":/images/Heros64.png"); ui->label_logo->setPixmap(pix); QRegExp nombre("[a-zA-Z0-9.-]*"); QValidator* nomValidator = new QRegExpValidator(nombre,this); ui->lineEdit->setValidator(nomValidator); // validador del email EmailValidator* emailValidator = new EmailValidator(this); ui->lineEdit_2->setValidator(emailValidator); } alta_participante::~alta_participante() { delete ui; } void alta_participante::on_pushButton_3_clicked() { this->close(); } EmailValidator::EmailValidator(QObject *parent) : QValidator(parent), m_validMailRegExp("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}"), m_intermediateMailRegExp("[a-z0-9._%+-]*@?[a-z0-9.-]*\\.?[a-z]*"){} QValidator::State EmailValidator::validate(QString &text, int &pos) const { Q_UNUSED(pos) fixup(text); if (m_validMailRegExp.exactMatch(text)) return Acceptable; if (m_intermediateMailRegExp.exactMatch(text)) return Intermediate; return Invalid; } void EmailValidator::fixup(QString &text) const { text = text.trimmed().toLower(); } void alta_participante::on_pushButton_2_clicked() { QString email = ui->lineEdit_2->text(); QString nombre = ui->lineEdit->text(); // tomar ruta de imagen QString imgUrl = ""; gui->handleAltaParticipante(NULL,nombre,email,imgUrl); } void alta_participante::on_pushButton_clicked() { }
21.571429
73
0.680915
bertilxi
a50e40c4d1c9fa60a110e1332f774ae56811c795
1,253
cc
C++
leetcode/leetcode_199.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
leetcode/leetcode_199.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
leetcode/leetcode_199.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void rightTree( TreeNode *root, int &depth, int cur_depth, vector<int> &result){ if (root) { if (depth < cur_depth) { depth += 1; result.push_back(root->val); } if (root->right){ rightTree(root->right, depth, cur_depth+1, result); } if (root->left) { rightTree(root->left, depth, cur_depth+1, result); } } } vector<int> rightSideView(TreeNode* root) { vector<int> result; if (root == nullptr) { return result; } int depth = 0; rightTree(root, depth, 1, result); return result; } int main( int argc, char *argv[] ) { TreeNode *root = new TreeNode(4); root->left = new TreeNode(3); root->left->left = new TreeNode(2); root->left->left->left = new TreeNode(1); root->right = new TreeNode(5); root->right->right = new TreeNode(6); /* TreeNode *root = new TreeNode(1); root->left = new TreeNode(2); */ auto vs = rightSideView(root); for (auto v : vs ){ cout << v << " "; } cout << endl; return 0; }
21.982456
80
0.581804
math715
a5115bd910e444bdcc0eac1e882e56b4acc3158c
541
cpp
C++
redfish-core/ut/stl_utils_test.cpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
96
2018-01-23T10:17:55.000Z
2022-03-22T08:49:41.000Z
redfish-core/ut/stl_utils_test.cpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
233
2018-08-06T05:55:44.000Z
2022-02-23T08:19:04.000Z
redfish-core/ut/stl_utils_test.cpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
97
2018-03-23T07:56:55.000Z
2022-03-16T15:51:48.000Z
#include "utils/stl_utils.hpp" #include <gmock/gmock.h> TEST(STLUtilesTest, RemoveDuplicates) { std::vector<std::string> strVec = {"s1", "s4", "s1", "s2", "", "s3", "s3"}; auto iter = redfish::stl_utils::firstDuplicate(strVec.begin(), strVec.end()); EXPECT_EQ(*iter, "s3"); redfish::stl_utils::removeDuplicate(strVec); EXPECT_EQ(strVec.size(), 5); EXPECT_EQ(strVec[0], "s1"); EXPECT_EQ(strVec[1], "s4"); EXPECT_EQ(strVec[2], "s2"); EXPECT_EQ(strVec[3], ""); EXPECT_EQ(strVec[4], "s3"); }
24.590909
79
0.608133
cjcain
a511af29e5823b82098463c7e263ab70f8e134a3
380
cpp
C++
UVA/11172-Relational Operator.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
UVA/11172-Relational Operator.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
UVA/11172-Relational Operator.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int participants,budget,hotles,weeks; int price, bed; int finalCost; bool isAvail = false; long long n,a,b; int main(int argc, char *argv[]) { scanf("%lld", &n); for (int i = 0; i<n; i++) { scanf("%lld%lld", &a,&b); if (a > b) { printf(">\n"); } else if (a < b) { printf("<\n"); } else { printf("=\n"); } } }
16.521739
37
0.544737
alielsokary
a51239ead5eda370a34e6c7386b21e83b4e009ea
1,402
cpp
C++
Lydsy/P1483 [HNOI2009]ๆขฆๅนปๅธƒไธ/P1483.cpp
Wycers/Codelib
86d83787aa577b8f2d66b5410e73102411c45e46
[ "MIT" ]
22
2018-08-07T06:55:10.000Z
2021-06-12T02:12:19.000Z
Lydsy/P1483 [HNOI2009]ๆขฆๅนปๅธƒไธ/P1483.cpp
Wycers/Codelib
86d83787aa577b8f2d66b5410e73102411c45e46
[ "MIT" ]
28
2020-03-04T23:47:22.000Z
2022-02-26T18:50:00.000Z
Lydsy/P1483 [HNOI2009]ๆขฆๅนปๅธƒไธ/P1483.cpp
Wycers/Codelib
86d83787aa577b8f2d66b5410e73102411c45e46
[ "MIT" ]
4
2019-11-09T15:41:26.000Z
2021-10-10T08:56:57.000Z
#include <cstdio> #include <algorithm> const int N = 100000 + 10; const int M = 1000000 + 10; using namespace std; int Read() { int x = 0;char ch = getchar(); while (ch < '0' || '9' < ch) ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + ch - 48,ch = getchar(); return x; } int c[N],next[N],f[M],head[M],s[M],st[M]; int n,m,cnt = 0; void Init() { n = Read();m = Read(); for (int i=1;i<=n;++i) { c[i] = Read(); f[c[i]] = c[i]; if (c[i] != c[i - 1]) ++cnt; if (!head[c[i]]) st[c[i]] = i; ++s[c[i]];next[i] = head[c[i]]; head[c[i]] = i; } } void Solve(int x,int y) { for (int i=head[x];i;i=next[i]) { if (c[i + 1] == y) --cnt; if (c[i - 1] == y) --cnt; } for (int i=head[x];i;i=next[i]) c[i] = y; next[st[x]] = head[y]; // head[y] = head[x]; s[y] += s[x]; head[x] = st[x] = s[x] = 0; } void Work() { int opt,x,y; while (m--) { opt = Read(); if (opt == 2) printf("%d\n",cnt); else { x = Read();y = Read(); if (x == y) continue; if (s[f[x]] > s[f[y]]) swap(f[x],f[y]); x = f[x];y = f[y]; if (!s[x]) continue; Solve(x,y); } } } int main() { Init(); Work(); return 0; }
19.746479
71
0.373752
Wycers
a5135f2bffbefb3b6ff81037e622c3307d690ae3
206
cpp
C++
lio/message.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
1
2021-01-23T09:24:35.000Z
2021-01-23T09:24:35.000Z
lio/message.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
null
null
null
lio/message.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
null
null
null
#include "message.h" #include "gmatrix.h" void MsgQueue::Send() { MSGQUEUE::iterator it = _queue.begin(); for(; it != _queue.end(); ++it) gmatrix::HandleMessage(*it); _queue.clear(); }
18.727273
43
0.601942
liuyuan185442111
a513c5c220b84956647261ac91202c4978e7b58f
280
cpp
C++
act_map_exp/src/planner_base_node.cpp
debugCVML/rpg_information_field
56f9ffba83aaee796502116e1cf651c5bc405bf6
[ "MIT" ]
149
2020-06-23T12:08:47.000Z
2022-03-31T08:18:52.000Z
act_map_exp/src/planner_base_node.cpp
debugCVML/rpg_information_field
56f9ffba83aaee796502116e1cf651c5bc405bf6
[ "MIT" ]
4
2020-08-28T07:51:15.000Z
2021-04-09T13:18:49.000Z
act_map_exp/src/planner_base_node.cpp
debugCVML/rpg_information_field
56f9ffba83aaee796502116e1cf651c5bc405bf6
[ "MIT" ]
34
2020-06-26T14:50:34.000Z
2022-03-04T06:45:55.000Z
#include "act_map_exp/planner_base.h" #include <rpg_common/main.h> RPG_COMMON_MAIN { ros::init(argc, argv, "planner_base"); ros::NodeHandle nh; ros::NodeHandle pnh("~"); act_map_exp::PlannerBase<act_map::GPTraceVoxel> planner(nh, pnh); ros::spin(); return 0; }
14.736842
67
0.689286
debugCVML
a5177f9b1d3d7b1d6c09f3b5c9e71a2a6adec0ca
486
hpp
C++
tinyraytracing/src/graphX/geometry/shapes/shpere.hpp
nicolaszordan/tinygrafX
5460b98459ec5e050ae6c0fb53de2f31c80243a9
[ "Unlicense" ]
null
null
null
tinyraytracing/src/graphX/geometry/shapes/shpere.hpp
nicolaszordan/tinygrafX
5460b98459ec5e050ae6c0fb53de2f31c80243a9
[ "Unlicense" ]
null
null
null
tinyraytracing/src/graphX/geometry/shapes/shpere.hpp
nicolaszordan/tinygrafX
5460b98459ec5e050ae6c0fb53de2f31c80243a9
[ "Unlicense" ]
null
null
null
// // graphX - geometry - shapes - sphere.hpp // #pragma once #include "Ishape.hpp" namespace graphX::geometry { struct Sphere : IShape { public: Sphere(const vec3f& center_, float radius_) : center{center_}, radius{radius_} { } public: bool ray_intersect(const vec3f& orig_, const vec3f& dir_, float& t0_, vec3f& N_) const override; public: vec3f center; float radius; }; } // namespace graphX::geometry
20.25
104
0.604938
nicolaszordan
a51a2cc5253a0e0355c9a1693576d8eb80a9f8bf
160
hxx
C++
code/temunt/interface/TemUnt/Direction.hxx
Angew/temple-untrap
bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc
[ "MIT" ]
1
2021-08-20T08:22:18.000Z
2021-08-20T08:22:18.000Z
code/temunt/interface/TemUnt/Direction.hxx
Angew/temple-untrap
bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc
[ "MIT" ]
null
null
null
code/temunt/interface/TemUnt/Direction.hxx
Angew/temple-untrap
bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc
[ "MIT" ]
null
null
null
#pragma once #include "TemUnt/Direction.hh" namespace TemUnt { enum class Direction { North = 0, South = 1, East = 2, West = 3 }; } //namespace TemUnt
9.411765
30
0.65
Angew
a51fb1c6f5dd006fdbb28730c2e30292906dfe38
32,750
cc
C++
physicalrobots/player/server/drivers/blobfinder/searchpattern/searchpattern.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
physicalrobots/player/server/drivers/blobfinder/searchpattern/searchpattern.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
physicalrobots/player/server/drivers/blobfinder/searchpattern/searchpattern.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* * Player - One Hell of a Robot Server * Copyright (C) 2000 Brian Gerkey et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /** @ingroup drivers */ /** @{ */ /** @defgroup driver_searchpattern searchpattern * @brief Pattern finder The searchpattern driver searches for given patern in the camera image. @par Compile-time dependencies - none @par Provides - @ref interface_blobfinder - (optionally) @ref interface_camera (thresholded image) @par Requires - @ref interface_camera @par Configuration requests - none @par Configuration file options - patterns (string array) - Default: Nothing! Explicit settings required. - Each string should contain one s-expression (a LISP-style list) which define one pattern; first element of a list is a 8-digit hex color value (0x prefixed): whenever given pattern is found it will be denoted by a blob of this color. - debug (integer) - Default: 0 - If it is set to non-zero, debug messages will be printed @par Properties - threshold (integer) - Default: 112 - Valid values: 0..255 - Luminance threshold used during thresholding see http://en.wikipedia.org/wiki/Thresholding_%28image_processing%29 - min_blob_pixels (integer) - Default: 16 - Valid values: greater than 0 - Minimal number of pixel for a blob to be considered as blob (used for noise elimination). - sleep_nsec (integer) - Default: 10000 - timespec value for additional nanosleep() @par Example @verbatim driver ( name "searchpattern" provides ["blobfinder:0"] requires ["camera:0"] patterns ["(0x00ff0000 (black (white (black) (black (white)))))" "(0x0000ff00 (black (white) (white (black))))"] threshold 112 min_blob_pixels 16 debug 1 ) @endverbatim @author Paul Osmialowski */ /** @} */ #include <libplayercore/playercore.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <pthread.h> #include <config.h> #if HAVE_JPEG #include <libplayerjpeg/playerjpeg.h> #endif #define EPS 0.000001 #define QUEUE_LEN 1 #define MAX_PATTERNS 10 #define MAX_DESCRIPTIONS (MAX_PATTERNS * 10) #define CHECK_TOKEN(str, token) (!(strncmp((str), (token), strlen(token)))) #define EAT_TOKEN(str, token, tmp) \ do \ { \ for (tmp = (token); (*(tmp)); (tmp)++, (str)++) \ { \ if ((*str) != (*tmp)) \ { \ str = NULL; \ break; \ } \ } \ } while (0) #define IS_HEX_DIGIT(chr) ((((chr) >= '0') && ((chr) <= '9')) || (((chr) >= 'A') && ((chr) <= 'F')) || (((chr) >= 'a') && ((chr) <= 'f'))) #define NO_PARENT -1 #define ERR_TOO_MANY_BLACKS -1 #define ERR_TOO_MANY_WHITES -2 #define ERR_TOO_MANY_PIXELS -3 class Searchpattern: public ThreadedDriver { public: // Constructor; need that Searchpattern(ConfigFile * cf, int section); virtual ~Searchpattern(); // Must implement the following methods. virtual int MainSetup(); virtual void MainQuit(); virtual void Main(); // This method will be invoked on each incoming message virtual int ProcessMessage(QueuePointer & resp_queue, player_msghdr * hdr, void * data); private: player_devaddr_t blobfinder_provided_addr, camera_provided_addr; player_devaddr_t camera_id; Device * camera; int publish_timg; uint32_t colors[MAX_PATTERNS]; struct pattern_description { int parent_id; int internals; unsigned char color; } descriptions[MAX_DESCRIPTIONS]; struct blob_struct { int minx, miny; int maxx, maxy; size_t pixels; int internals; int parent; unsigned char color; unsigned char in_use; } blobs[256]; size_t descNum; int numpatterns; int debug; int * _stack; int _sp; size_t _stack_size; size_t max_blob_pixels; int * blob_x; int * blob_y; unsigned char * buffer; size_t bufsize; size_t numresults; int * results; IntProperty threshold; IntProperty min_blob_pixels; IntProperty sleep_nsec; int find_pattern(const struct pattern_description * pattern, int id, int blob_parent) const; int searchpattern(unsigned char * area, int width, int height, int min_blob_pixels, const struct pattern_description * pattern, int * results); #define SEARCH_STACK_GUARD -1 #define SEARCH_STACK_PUSH(value) do \ { \ if ((this->_sp) == static_cast<int>(this->_stack_size)) PLAYER_ERROR("Stack overflow"); \ else this->_stack[(this->_sp)++] = (value); \ } while (0) #define SEARCH_STACK_POP() ((this->_sp) ? this->_stack[--(this->_sp)] : SEARCH_STACK_GUARD) #define SEARCH_STACK_WIPE() (this->_sp = 0) #define CHECK_PIXEL(line, x, y, blobnum) do \ { \ switch ((line)[x]) \ { \ case 0: \ case 255: \ if (this->blobs[blobnum].color == ((line)[x])) \ { \ SEARCH_STACK_PUSH(x); \ SEARCH_STACK_PUSH(y); \ ((line)[x]) = (blobnum); \ } \ break; \ default: \ if (((line)[x]) != (blobnum)) \ { \ if ((this->blobs[blobnum].parent) == NO_PARENT) \ { \ this->blobs[blobnum].parent = ((line)[x]); \ this->blobs[this->blobs[blobnum].parent].internals++; \ } else if (((line)[x]) != (this->blobs[blobnum].parent)) PLAYER_ERROR3("Internal error (multiple parents? %d %d) (color %d)", this->blobs[blobnum].parent, (line)[x], this->blobs[blobnum].color); \ } \ } \ } while (0) }; Searchpattern::Searchpattern(ConfigFile * cf, int section) : ThreadedDriver(cf, section, true, QUEUE_LEN), threshold("threshold", 112, false), min_blob_pixels("min_blob_pixels", 16, false), sleep_nsec("sleep_nsec", 10000, false) { const char * str; const char * tmp; char hexbuf[9]; int i, j, k, parent; memset(&(this->blobfinder_provided_addr), 0, sizeof(player_devaddr_t)); memset(&(this->camera_provided_addr), 0, sizeof(player_devaddr_t)); memset(&(this->camera_id), 0, sizeof(player_devaddr_t)); this->camera = NULL; this->publish_timg = 0; memset(this->colors, 0, sizeof this->colors); memset(this->descriptions, 0, sizeof this->descriptions); memset(this->blobs, 0, sizeof this->blobs); this->descNum = 0; this->numpatterns = 0; this->debug = 0; this->_stack = NULL; this->_sp = 0; this->_stack_size = 0; this->max_blob_pixels = 0; this->blob_x = NULL; this->blob_y = NULL; this->buffer = NULL; this->bufsize = 0; this->numresults = 0; this->results = NULL; if (cf->ReadDeviceAddr(&(this->blobfinder_provided_addr), section, "provides", PLAYER_BLOBFINDER_CODE, -1, NULL)) { this->SetError(-1); return; } if (this->AddInterface(this->blobfinder_provided_addr)) { this->SetError(-1); return; } if (cf->ReadDeviceAddr(&(this->camera_provided_addr), section, "provides", PLAYER_CAMERA_CODE, -1, NULL)) { this->publish_timg = 0; } else { if (this->AddInterface(this->camera_provided_addr)) { this->SetError(-1); return; } this->publish_timg = !0; } if (cf->ReadDeviceAddr(&(this->camera_id), section, "requires", PLAYER_CAMERA_CODE, -1, NULL) != 0) { this->SetError(-1); return; } this->debug = cf->ReadInt(section, "debug", 0); this->numpatterns = cf->GetTupleCount(section, "patterns"); if (!((this->numpatterns) > 0)) { PLAYER_ERROR("No patterns given"); this->SetError(-1); return; } if ((this->numpatterns) > MAX_PATTERNS) { PLAYER_ERROR("Too many paterns given"); this->SetError(-1); return; } j = (this->numpatterns); for (i = 0; i < (this->numpatterns); i++) { str = cf->ReadTupleString(section, "patterns", i, ""); if (!str) { PLAYER_ERROR1("NULL pattern %d", i); this->SetError(-1); return; } if (!(strlen(str) > 0)) { PLAYER_ERROR1("Empty pattern %d", i); this->SetError(-1); return; } if ((*str) != '(') { PLAYER_ERROR1("Syntax error in pattern %d (1)", i); this->SetError(-1); return; } str++; if ((*str) != '0') { PLAYER_ERROR1("Syntax error in pattern %d (2)", i); this->SetError(-1); return; } str++; if ((*str) != 'x') { PLAYER_ERROR1("Syntax error in pattern %d (3)", i); this->SetError(-1); return; } str++; for (k = 0; k < 8; k++, str++) { if (!IS_HEX_DIGIT(*str)) { PLAYER_ERROR1("Syntax error in pattern %d (4)", i); this->SetError(-1); return; } hexbuf[k] = (*str); } hexbuf[8] = '\0'; sscanf(hexbuf, "%x", &(this->colors[i])); if ((*str) != ' ') { PLAYER_ERROR1("Syntax error in pattern %d (5)", i); this->SetError(-1); return; } str++; if ((*str) != '(') { PLAYER_ERROR1("Syntax error in pattern %d (6)", i); this->SetError(-1); return; } str++; this->descriptions[i].parent_id = NO_PARENT; this->descriptions[i].internals = 0; if (CHECK_TOKEN(str, "black")) { this->descriptions[i].color = 0; EAT_TOKEN(str, "black", tmp); } else if (CHECK_TOKEN(str, "white")) { this->descriptions[i].color = 255; EAT_TOKEN(str, "white", tmp); } else { PLAYER_ERROR1("Syntax error in pattern %d (7)", i); this->SetError(-1); return; } if (!str) { PLAYER_ERROR("Internal error within the parser"); this->SetError(-1); return; } parent = i; for (;;) { if ((*str) == ')') { str++; if ((this->descriptions[parent].parent_id) == NO_PARENT) break; parent = (this->descriptions[parent].parent_id); continue; } if ((*str) != ' ') { PLAYER_ERROR1("Syntax error in pattern %d (8)", i); this->SetError(-1); return; } str++; if ((*str) != '(') { PLAYER_ERROR1("Syntax error in pattern %d (9)", i); this->SetError(-1); return; } str++; if (j >= MAX_DESCRIPTIONS) { PLAYER_ERROR("Pattern set too complex"); this->SetError(-1); return; } this->descriptions[parent].internals++; this->descriptions[j].parent_id = parent; this->descriptions[j].internals = 0; if (CHECK_TOKEN(str, "black")) { this->descriptions[j].color = 0; EAT_TOKEN(str, "black", tmp); } else if (CHECK_TOKEN(str, "white")) { this->descriptions[j].color = 255; EAT_TOKEN(str, "white", tmp); } else { PLAYER_ERROR1("Syntax error in pattern %d (10)", i); this->SetError(-1); return; } if (!str) { PLAYER_ERROR("Internal error within the parser"); this->SetError(-1); return; } parent = j; j++; } if ((*str) != ')') { PLAYER_ERROR1("Syntax error in pattern %d (11)", i); this->SetError(-1); return; } str++; if (*str) { PLAYER_ERROR1("Syntax error in pattern %d (12)", i); this->SetError(-1); return; } } if (this->debug) { PLAYER_WARN2("patterns: %d, descriptions = %d", this->numpatterns, j); for (i = 0; i < (this->numpatterns); i++) { PLAYER_WARN4("%d: key: 0x%08x internals: %d color: %s", i, this->colors[i], this->descriptions[i].internals, (this->descriptions[i].color) ? "white" : "black"); if ((this->descriptions[i].parent_id) != NO_PARENT) { PLAYER_ERROR1("Pattern integrity check failed for pattern %i", i); this->SetError(-1); return; } } for (; i < j; i++) { PLAYER_WARN4("%d: parent: %d internals: %d color: %s", i, this->descriptions[i].parent_id, this->descriptions[i].internals, (this->descriptions[i].color) ? "white" : "black"); if ((this->descriptions[i].parent_id) == NO_PARENT) { PLAYER_ERROR1("Pattern integrity check failed for pattern %i", i); this->SetError(-1); return; } } } this->descNum = j; if (!(this->RegisterProperty("threshold", &(this->threshold), cf, section))) { PLAYER_ERROR("Cannot register 'threshold' property"); this->SetError(-1); return; } if (((this->threshold.GetValue()) < 0) || ((this->threshold.GetValue()) > 255)) { PLAYER_ERROR("Invalid threshold value"); this->SetError(-1); return; } if (!(this->RegisterProperty("min_blob_pixels", &(this->min_blob_pixels), cf, section))) { PLAYER_ERROR("Cannot register 'min_blob_pixels' property"); this->SetError(-1); return; } if ((this->min_blob_pixels.GetValue()) <= 0) { PLAYER_ERROR("Invalid min_blob_pixels value"); this->SetError(-1); return; } if (!(this->RegisterProperty("sleep_nsec", &(this->sleep_nsec), cf, section))) { this->SetError(-1); return; } if ((this->sleep_nsec.GetValue()) < 0) { this->SetError(-1); return; } this->numresults = ((this->numpatterns) * 4); this->results = reinterpret_cast<int *>(malloc((this->numresults) * sizeof(int))); if (!(this->results)) { PLAYER_ERROR("Out of memory"); this->SetError(-1); return; } memset(this->results, 0, sizeof((this->numresults) * sizeof(int))); } Searchpattern::~Searchpattern() { if (this->results) free(this->results); this->results = NULL; if (this->_stack) free(this->_stack); this->_stack = NULL; if (this->blob_x) free(this->blob_x); this->blob_x = NULL; if (this->blob_y) free(this->blob_y); this->blob_y = NULL; if (this->buffer) free(this->buffer); this->buffer = NULL; } //////////////////////////////////////////////////////////////////////////////// // Set up the device. Return 0 if things go well, and -1 otherwise. int Searchpattern::MainSetup() { if (this->publish_timg) { if (Device::MatchDeviceAddress(this->camera_id, this->camera_provided_addr)) { PLAYER_ERROR("attempt to subscribe to self"); return -1; } } this->camera = deviceTable->GetDevice(this->camera_id); if (!this->camera) { PLAYER_ERROR("unable to locate suitable camera device"); return -1; } if (this->camera->Subscribe(this->InQueue) != 0) { PLAYER_ERROR("unable to subscribe to camera device"); this->camera = NULL; return -1; } return 0; } //////////////////////////////////////////////////////////////////////////////// // Shutdown the device void Searchpattern::MainQuit() { if (this->camera) this->camera->Unsubscribe(this->InQueue); this->camera = NULL; } void Searchpattern::Main() { struct timespec tspec; for (;;) { this->InQueue->Wait(); pthread_testcancel(); this->ProcessMessages(); pthread_testcancel(); tspec.tv_sec = 0; tspec.tv_nsec = this->sleep_nsec.GetValue(); if (tspec.tv_nsec > 0) { nanosleep(&tspec, NULL); pthread_testcancel(); } } } int Searchpattern::ProcessMessage(QueuePointer & resp_queue, player_msghdr * hdr, void * data) { int i, j, found; size_t area_width, area_height; double lum; size_t new_size = 0; size_t new_buf_size = 0; size_t ns = 0; player_camera_data_t * rawdata = NULL; player_camera_data_t * timg_output = NULL; player_blobfinder_data_t * output = NULL; unsigned char * ptr = NULL; unsigned char * ptr1 = NULL; unsigned char thresh = static_cast<unsigned char>(this->threshold.GetValue()); if (!hdr) { PLAYER_ERROR("NULL header"); return -1; } if (Message::MatchMessage(hdr, PLAYER_MSGTYPE_DATA, PLAYER_CAMERA_DATA_STATE, this->camera_id)) { if (!data) { PLAYER_ERROR("NULL data"); return -1; } rawdata = reinterpret_cast<player_camera_data_t *>(data); if ((static_cast<int>(rawdata->width) <= 0) || (static_cast<int>(rawdata->height) <= 0)) { return -1; } else { new_size = rawdata->width * rawdata->height; new_buf_size = new_size * 3; if ((this->bufsize) != new_buf_size) { if (this->_stack) free(this->_stack); this->_stack = NULL; if (this->blob_x) free(this->blob_x); this->blob_x = NULL; if (this->blob_y) free(this->blob_y); this->blob_y = NULL; if (this->buffer) free(this->buffer); this->buffer = NULL; this->bufsize = 0; this->_stack_size = 0; this->_sp = 0; this->max_blob_pixels = 0; } if (!(this->buffer)) { this->bufsize = 0; this->buffer = reinterpret_cast<unsigned char *>(malloc(new_buf_size)); if (!(this->buffer)) { PLAYER_ERROR("Out of memory"); return -1; } this->bufsize = new_buf_size; } if (!(this->_stack)) { this->_stack_size = 0; this->_sp = 0; ns = (new_size * 2); this->_stack = reinterpret_cast<int *>(malloc(ns * sizeof(int))); if (!(this->_stack)) { PLAYER_ERROR("Out of memory"); return -1; } this->_stack_size = ns; this->_sp = 0; } if (!(this->blob_x)) { this->blob_x = reinterpret_cast<int *>(malloc(new_size * sizeof(int))); if (!(this->blob_x)) { PLAYER_ERROR("Out of memory"); return -1; } } if (!(this->blob_y)) { this->blob_y = reinterpret_cast<int *>(malloc(new_size * sizeof(int))); if (!(this->blob_y)) { PLAYER_ERROR("Out of memory"); return -1; } } if ((this->blob_x) && (this->blob_y)) this->max_blob_pixels = new_size; else { PLAYER_ERROR("Internal error"); return -1; } switch (rawdata->compression) { case PLAYER_CAMERA_COMPRESS_RAW: switch (rawdata->bpp) { case 8: ptr = this->buffer; ptr1 = reinterpret_cast<unsigned char *>(rawdata->image); for (i = 0; i < static_cast<int>(rawdata->height); i++) { for (j = 0; j < static_cast<int>(rawdata->width); j++) { (*ptr) = ((*ptr1) >= thresh) ? 255 : 0; ptr++; ptr1++; } } break; case 24: ptr = this->buffer; ptr1 = reinterpret_cast<unsigned char *>(rawdata->image); for (i = 0; i < static_cast<int>(rawdata->height); i++) { for (j = 0; j < static_cast<int>(rawdata->width); j++) { lum = (0.299 * static_cast<double>(ptr1[0])) + (0.587 * static_cast<double>(ptr1[1])) + (0.114 * static_cast<double>(ptr1[2])); if (lum < EPS) lum = 0.0; if (lum > (255.0 - EPS)) lum = 255.0; (*ptr) = static_cast<unsigned char>(lum); (*ptr) = ((*ptr) >= thresh) ? 255 : 0; ptr++; ptr1 += 3; } } break; case 32: ptr = this->buffer; ptr1 = reinterpret_cast<unsigned char *>(rawdata->image); for (i = 0; i < static_cast<int>(rawdata->height); i++) { for (j = 0; j < static_cast<int>(rawdata->width); j++) { lum = (0.299 * static_cast<double>(ptr1[0])) + (0.587 * static_cast<double>(ptr1[1])) + (0.114 * static_cast<double>(ptr1[2])); if (lum < EPS) lum = 0.0; if (lum > (255.0 - EPS)) lum = 255.0; (*ptr) = static_cast<unsigned char>(lum); (*ptr) = ((*ptr) >= thresh) ? 255 : 0; ptr++; ptr1 += 4; } } break; default: PLAYER_WARN("unsupported image depth (not good)"); return -1; } break; #if HAVE_JPEG case PLAYER_CAMERA_COMPRESS_JPEG: jpeg_decompress(this->buffer, this->bufsize, rawdata->image, rawdata->image_count); ptr = this->buffer; ptr1 = this->buffer; for (i = 0; i < static_cast<int>(rawdata->height); i++) { for (j = 0; j < static_cast<int>(rawdata->width); j++) { lum = (0.299 * static_cast<double>(ptr1[0])) + (0.587 * static_cast<double>(ptr1[1])) + (0.114 * static_cast<double>(ptr1[2])); if (lum < EPS) lum = 0.0; if (lum > (255.0 - EPS)) lum = 255.0; (*ptr) = static_cast<unsigned char>(lum); (*ptr) = ((*ptr) >= thresh) ? 255 : 0; ptr++; ptr1 += 3; } } break; #endif default: PLAYER_WARN("unsupported compression scheme (not good)"); return -1; } if (this->publish_timg) { timg_output = reinterpret_cast<player_camera_data_t *>(malloc(sizeof(player_camera_data_t))); if (!timg_output) { PLAYER_ERROR("Out of memory"); return -1; } memset(timg_output, 0, sizeof(player_camera_data_t)); timg_output->bpp = 8; timg_output->compression = PLAYER_CAMERA_COMPRESS_RAW; timg_output->format = PLAYER_CAMERA_FORMAT_MONO8; timg_output->fdiv = rawdata->fdiv; timg_output->width = rawdata->width; timg_output->height = rawdata->height; timg_output->image_count = (rawdata->width * rawdata->height); timg_output->image = reinterpret_cast<uint8_t *>(malloc(timg_output->image_count)); if (!(timg_output->image)) { free(timg_output); PLAYER_ERROR("Out of memory"); return -1; } memcpy(timg_output->image, this->buffer, timg_output->image_count); this->Publish(this->camera_provided_addr, PLAYER_MSGTYPE_DATA, PLAYER_CAMERA_DATA_STATE, reinterpret_cast<void *>(timg_output), 0, &(hdr->timestamp), false); // copy = false // I assume that Publish() (with copy = false) freed those output data! timg_output = NULL; } found = searchpattern(this->buffer, rawdata->width, rawdata->height, this->min_blob_pixels.GetValue(), this->descriptions, this->results); if (found <= 0) { for (i = 0; i < static_cast<int>(this->numresults); i++) results[i] = -1; } if (this->debug) { switch (found) { case 0: PLAYER_WARN("Found nothing"); break; case ERR_TOO_MANY_BLACKS: PLAYER_ERROR("Searchpattern error: Too many blacks"); break; case ERR_TOO_MANY_WHITES: PLAYER_ERROR("Searchpattern error: Too many whites"); break; case ERR_TOO_MANY_PIXELS: PLAYER_ERROR("Searchpattern error: Too many whites"); break; default: if (found < 0) { PLAYER_ERROR1("Unknown error code %d", found); } else PLAYER_WARN1("Found %d", found); } for (i = 0; i < (this->numpatterns); i++) { PLAYER_WARN5("%d. %d %d - %d %d", i + 1, results[i * 4], results[(i * 4) + 1], results[(i * 4) + 2], results[(i * 4) + 3]); } PLAYER_WARN("=============="); } if (found < 0) found = 0; output = reinterpret_cast<player_blobfinder_data_t *>(malloc(sizeof(player_blobfinder_data_t))); if (!output) { PLAYER_ERROR("Out of memory"); return -1; } memset(output, 0, sizeof(player_blobfinder_data_t)); output->width = (rawdata->width); output->height = (rawdata->height); output->blobs_count = found; output->blobs = reinterpret_cast<player_blobfinder_blob_t *>(malloc(found * sizeof(player_blobfinder_blob_t))); if (!(output->blobs)) { free(output); PLAYER_ERROR("Out of memory"); return -1; } j = 0; for (i = 0; i < (this->numpatterns); i++) { if (!((results[i * 4] < 0) || (results[(i * 4) + 1] < 0) || (results[(i * 4) + 2] < 0) || (results[(i * 4) + 3] < 0))) { if (j >= found) { PLAYER_ERROR("Internal error: unexpected number of results"); return -1; } area_width = static_cast<size_t>(results[(i * 4) + 1] - results[i * 4]); area_height = static_cast<size_t>(results[(i * 4) + 3] - results[(i * 4) + 2]); memset(&(output->blobs[j]), 0, sizeof output->blobs[j]); output->blobs[j].id = i; output->blobs[j].color = this->colors[i]; output->blobs[j].area = (area_width * area_height); output->blobs[j].x = ((static_cast<unsigned>(results[i * 4])) + (area_width >> 1)); output->blobs[j].y = ((static_cast<unsigned>(results[(i * 4) + 2])) + (area_height >> 1)); output->blobs[j].left = results[i * 4]; output->blobs[j].right = results[(i * 4) + 1]; output->blobs[j].top = results[(i * 4) + 2]; output->blobs[j].bottom = results[(i * 4) + 3]; output->blobs[j].range = 0; j++; } } this->Publish(this->blobfinder_provided_addr, PLAYER_MSGTYPE_DATA, PLAYER_BLOBFINDER_DATA_BLOBS, reinterpret_cast<void *>(output), 0, &(hdr->timestamp), false); // copy = false // I assume that Publish() (with copy = false) freed those output data! output = NULL; } return 0; } return -1; } int Searchpattern::find_pattern(const struct pattern_description * pattern, int id, int blob_parent) const { int f, i, j, k; f = 0; for (i = 1; i < 255; i++) if ((this->blobs[i].in_use) && ((this->blobs[i].internals) == (pattern[id].internals))) { if (((pattern[id].parent_id) == NO_PARENT) && ((this->blobs[i].color) != (pattern[id].color))) continue; if ((blob_parent != NO_PARENT) && ((this->blobs[i].parent) != blob_parent)) continue; for (j = 0, k = 0; k < (pattern[id].internals); j++) if ((pattern[j].parent_id) == id) { k++; if ((this->find_pattern(pattern, j, i)) <= 0) return f; } if (f) return -1; f = i; } return f; } int Searchpattern::searchpattern(unsigned char * area, int width, int height, int min_blob_pixels, const struct pattern_description * pattern, int * results) { int i, j, k, x, y, mustcheck = 0; unsigned char blobnum = 0; int blackblobs = 0; int whiteblobs = 0; unsigned char * line; unsigned char * current_line; for (i = 0; i < 256; i++) (this->blobs[i].in_use) = 0; line = area + ((height - 1) * width); for (i = 0; i < width; i++) { area[i] = 0; line[i] = 0; } for (i = 1; i < (height - 1); i++) { line = area + (i * width); line[0] = 0; line[width - 1] = 0; } for (i = 0; i < height; i++) { current_line = area + (i * width); for (j = 0; j < width; j++) { switch (current_line[j]) { case 0: blobnum = blackblobs + 1; if (blobnum >= 128) { PLAYER_ERROR("Too many black blobs"); return ERR_TOO_MANY_BLACKS; } break; case 255: blobnum = 255 - (whiteblobs + 1); if (blobnum <= 127) { PLAYER_ERROR("Too many white blobs"); return ERR_TOO_MANY_WHITES; } break; default: blobnum = 0; } if (blobnum) { this->blobs[blobnum].pixels = 0; this->blobs[blobnum].minx = j; this->blobs[blobnum].maxx = j; this->blobs[blobnum].miny = i; this->blobs[blobnum].maxy = i; this->blobs[blobnum].parent = NO_PARENT; this->blobs[blobnum].internals = 0; this->blobs[blobnum].color = current_line[j]; mustcheck = !0; while (blobnum) { if ((current_line[j]) != (this->blobs[blobnum].color)) PLAYER_ERROR("Internal error, something has changed"); SEARCH_STACK_WIPE(); SEARCH_STACK_PUSH(j); SEARCH_STACK_PUSH(i); current_line[j] = blobnum; for (;;) { y = SEARCH_STACK_POP(); x = SEARCH_STACK_POP(); if ((x < 0) || (y < 0)) break; line = area + (y * width); if (y > 0) { line -= width; y--; if (x > 0) { x--; CHECK_PIXEL(line, x, y, blobnum); x++; } CHECK_PIXEL(line, x, y, blobnum); if (x < (width - 1)) { x++; CHECK_PIXEL(line, x, y, blobnum); x--; } line += width; y++; } if (y < (height - 1)) { line += width; y++; if (x > 0) { x--; CHECK_PIXEL(line, x, y, blobnum); x++; } CHECK_PIXEL(line, x, y, blobnum); if (x < (width - 1)) { x++; CHECK_PIXEL(line, x, y, blobnum); x--; } line -= width; y--; } if (x > 0) { x--; CHECK_PIXEL(line, x, y, blobnum); x++; } if (x < (width - 1)) { x++; CHECK_PIXEL(line, x, y, blobnum); x--; } if (x < (this->blobs[blobnum].minx)) this->blobs[blobnum].minx = x; if (x > (this->blobs[blobnum].maxx)) this->blobs[blobnum].maxx = x; if (y < (this->blobs[blobnum].miny)) this->blobs[blobnum].miny = y; if (y > (this->blobs[blobnum].maxy)) this->blobs[blobnum].maxy = y; this->blob_x[this->blobs[blobnum].pixels] = x; this->blob_y[this->blobs[blobnum].pixels] = y; (this->blobs[blobnum].pixels)++; if ((this->blobs[blobnum].pixels) >= (this->max_blob_pixels)) { PLAYER_ERROR("Blob too big"); return ERR_TOO_MANY_PIXELS; } } if (mustcheck) { mustcheck = 0; if (((this->blobs[blobnum].pixels) < static_cast<size_t>(min_blob_pixels)) && ((this->blobs[blobnum].parent) > 0)) { for (k = 0; k < static_cast<int>(this->blobs[blobnum].pixels); k++) { area[((this->blob_y[k]) * width) + (this->blob_x[k])] = this->blobs[this->blobs[blobnum].parent].color; } this->blobs[this->blobs[blobnum].parent].internals--; blobnum = (this->blobs[blobnum].parent); } else { if (!(this->blobs[blobnum].color)) blackblobs++; else whiteblobs++; this->blobs[blobnum].in_use = !0; blobnum = 0; } } else blobnum = 0; } } } } k = 0; for (i = 0; (pattern[i].parent_id) == NO_PARENT; i++) { results[i * 4] = -1; results[(i * 4) + 1] = -1; results[(i * 4) + 2] = -1; results[(i * 4) + 3] = -1; j = (this->find_pattern(pattern, i, NO_PARENT)); switch (j) { case -1: PLAYER_ERROR1("Too many occurences of pattern %d", i); break; case 0: break; default: results[i * 4] = (this->blobs[j].minx); results[(i * 4) + 1] = (this->blobs[j].maxx); results[(i * 4) + 2] = (this->blobs[j].miny); results[(i * 4) + 3] = (this->blobs[j].maxy); k++; } } return k; } Driver * Searchpattern_Init(ConfigFile * cf, int section) { // Create and return a new instance of this driver return reinterpret_cast<Driver *>(new Searchpattern(cf, section)); } //////////////////////////////////////////////////////////////////////////////// // a driver registration function void searchpattern_Register(DriverTable* table) { table->AddDriver("searchpattern", Searchpattern_Init); }
29.881387
208
0.543939
parasol-ppl
a526c90cfd414f0b7e8e693779b6674323672347
920
cc
C++
flecsi/utils/test/reflection.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
flecsi/utils/test/reflection.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
flecsi/utils/test/reflection.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
/*~-------------------------------------------------------------------------~~* * Copyright (c) 2014 Los Alamos National Security, LLC * All rights reserved. *~-------------------------------------------------------------------------~~*/ #include <cinchdevel.h> #include <flecsi/utils/reflection.h> struct test_type_t { declare_reflected((double)r1, (int)r2) }; // struct test_type_t using namespace flecsi::utils; DEVEL(reflection) { test_type_t t; t.r1 = 1.0; clog(info) << t.r1 << std::endl; clog(info) << reflection::num_variables<test_type_t>::value << std::endl; t.r1 = 2.0; clog(info) << reflection::variable<0>(t).get() << std::endl; } // DEVEL /*~------------------------------------------------------------------------~--* * Formatting options for vim. * vim: set tabstop=2 shiftwidth=2 expandtab : *~------------------------------------------------------------------------~--*/
27.058824
80
0.43913
manopapad
a528599a53644c4700efa428c3f8c495bb6285a4
44
cpp
C++
PolygonTriangulationC/Vertex.cpp
sbrodehl/cg-lab-1516
fc4a09679bbce502f59f66a581077417b39edb15
[ "MIT" ]
null
null
null
PolygonTriangulationC/Vertex.cpp
sbrodehl/cg-lab-1516
fc4a09679bbce502f59f66a581077417b39edb15
[ "MIT" ]
5
2016-03-16T09:43:19.000Z
2016-03-25T12:11:19.000Z
PolygonTriangulationC/Vertex.cpp
sbrodehl/cg-lab-1516
fc4a09679bbce502f59f66a581077417b39edb15
[ "MIT" ]
null
null
null
// // Created by clamber on 21.03.2016. //
8.8
36
0.590909
sbrodehl
a52f7fe7b8ba648cfe89fbb8bc15dd779ba0f115
5,779
cpp
C++
tests/test_file.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
4
2017-11-28T17:22:46.000Z
2022-03-17T07:47:19.000Z
tests/test_file.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
10
2017-10-04T01:20:25.000Z
2017-11-23T06:15:23.000Z
tests/test_file.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
1
2019-06-13T23:05:49.000Z
2019-06-13T23:05:49.000Z
#include "../stitch/file.h" #include "../testing/testing.h" #include <thread> #include <chrono> #include <iostream> #include <sstream> #include <cstring> #include <sys/types.h> #include <sys/stat.h> using namespace Stitch; using namespace std; using namespace Testing; static bool test_basic() { Test test; const string path("test.fifo"); { remove(path.c_str()); int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR); if (result == -1) { throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno)); } } int reps = 5; auto make_data = [](int rep) -> string { ostringstream s; s << "data"; for(int i = 0; i < rep; ++i) s << '.' << to_string(i+1); return s.str(); }; thread writer([&]() { File f(path, File::WriteOnly); uint32_t d = 0; for(int rep = 0; rep < reps; ++rep) { wait(f.write_ready()); printf("Write ready\n"); ++d; int c = f.write(&d, sizeof(d)); printf("Written %d\n", d); if (c != sizeof(d)) throw std::runtime_error("Failed write."); this_thread::sleep_for(chrono::milliseconds(250)); } }); thread reader([&]() { File f(path, File::ReadOnly); uint32_t expected = 0; for(int rep = 0; rep < reps; ++rep) { wait(f.read_ready()); printf("Read ready\n"); ++expected; uint32_t received = 0; int c = f.read(&received, sizeof(uint32_t)); printf("Read %d\n", received); if (c != sizeof(uint32_t)) throw std::runtime_error("Failed read."); test.assert("Received = " + to_string(expected), received == expected); } }); writer.join(); reader.join(); return test.success(); } static bool test_blocking_read() { Test test; const string path("test.fifo"); { remove(path.c_str()); int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR); if (result == -1) { throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno)); } } int reps = 5; auto make_data = [](int rep) -> string { ostringstream s; s << "data"; for(int i = 0; i < rep; ++i) s << '.' << to_string(i+1); return s.str(); }; thread writer([&]() { File f(path, File::WriteOnly); uint32_t d = 0; for(int rep = 0; rep < reps; ++rep) { wait(f.write_ready()); printf("Write ready\n"); ++d; int c = f.write(&d, sizeof(d)); printf("Written %d\n", d); if (c != sizeof(d)) throw std::runtime_error("Failed write."); this_thread::sleep_for(chrono::milliseconds(250)); } }); thread reader([&]() { File f(path, File::ReadOnly); vector<uint32_t> received(reps, 0); wait(f.read_ready()); printf("Read ready\n"); int c = f.read(&received[0], sizeof(uint32_t) * reps); printf("Read count = %d\n", c); if (c != sizeof(uint32_t) * reps) throw std::runtime_error("Failed read."); for(int rep = 0; rep < reps; ++rep) { auto & v = received[rep]; test.assert("Received = " + to_string(v), v == rep + 1); } }); writer.join(); reader.join(); return test.success(); } static bool test_nonblocking_read() { Test test; const string path("test.fifo"); { remove(path.c_str()); int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR); if (result == -1) { throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno)); } } int reps = 5; auto make_data = [](int rep) -> string { ostringstream s; s << "data"; for(int i = 0; i < rep; ++i) s << '.' << to_string(i+1); return s.str(); }; thread writer([&]() { File f(path, File::WriteOnly); uint32_t d = 0; for(int rep = 0; rep < reps; ++rep) { wait(f.write_ready()); printf("Write ready\n"); ++d; int c = f.write(&d, sizeof(d)); printf("Written %d\n", d); if (c != sizeof(d)) throw std::runtime_error("Failed write."); this_thread::sleep_for(chrono::milliseconds(250)); } }); thread reader([&]() { File f(path, File::ReadOnly, false); vector<uint32_t> received(reps, 0); int total_size = sizeof(uint32_t) * reps; int received_size = 0; char * dst = (char*) &received[0]; while(received_size < total_size) { wait(f.read_ready()); printf("Read ready\n"); int c = f.read(dst, total_size - received_size); if (c <= 0) throw std::runtime_error("Failed read."); printf("Read count = %d\n", c); received_size += c; dst += c; } for(int rep = 0; rep < reps; ++rep) { auto & v = received[rep]; assert("Received = " + to_string(v), v == rep + 1); } }); writer.join(); reader.join(); return test.success(); } Test_Set file_tests() { return { { "basic", test_basic }, { "blocking read", test_blocking_read }, { "nonblocking read", test_nonblocking_read }, }; }
19.791096
90
0.477072
adamelliot
a531999941aba44ec04c231ab80f563fbf87b381
6,732
cpp
C++
clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIPipelineBranchesitem.cpp
PankTrue/swaggy-jenkins
aca35a7cca6e1fcc08bd399e05148942ac2f514b
[ "MIT" ]
23
2017-08-01T12:25:26.000Z
2022-01-25T03:44:11.000Z
clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIPipelineBranchesitem.cpp
PankTrue/swaggy-jenkins
aca35a7cca6e1fcc08bd399e05148942ac2f514b
[ "MIT" ]
35
2017-06-14T03:28:15.000Z
2022-02-14T10:25:54.000Z
clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIPipelineBranchesitem.cpp
PankTrue/swaggy-jenkins
aca35a7cca6e1fcc08bd399e05148942ac2f514b
[ "MIT" ]
11
2017-08-31T19:00:20.000Z
2021-12-19T12:04:12.000Z
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * OpenAPI spec version: 1.1.1 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIPipelineBranchesitem.h" #include "OAIHelpers.h" #include <QJsonDocument> #include <QJsonArray> #include <QObject> #include <QDebug> namespace OpenAPI { OAIPipelineBranchesitem::OAIPipelineBranchesitem(QString json) { this->fromJson(json); } OAIPipelineBranchesitem::OAIPipelineBranchesitem() { this->init(); } OAIPipelineBranchesitem::~OAIPipelineBranchesitem() { } void OAIPipelineBranchesitem::init() { m_display_name_isSet = false; m_estimated_duration_in_millis_isSet = false; m_name_isSet = false; m_weather_score_isSet = false; m_latest_run_isSet = false; m_organization_isSet = false; m_pull_request_isSet = false; m_total_number_of_pull_requests_isSet = false; m__class_isSet = false; } void OAIPipelineBranchesitem::fromJson(QString jsonString) { QByteArray array (jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIPipelineBranchesitem::fromJsonObject(QJsonObject json) { ::OpenAPI::fromJsonValue(display_name, json[QString("displayName")]); ::OpenAPI::fromJsonValue(estimated_duration_in_millis, json[QString("estimatedDurationInMillis")]); ::OpenAPI::fromJsonValue(name, json[QString("name")]); ::OpenAPI::fromJsonValue(weather_score, json[QString("weatherScore")]); ::OpenAPI::fromJsonValue(latest_run, json[QString("latestRun")]); ::OpenAPI::fromJsonValue(organization, json[QString("organization")]); ::OpenAPI::fromJsonValue(pull_request, json[QString("pullRequest")]); ::OpenAPI::fromJsonValue(total_number_of_pull_requests, json[QString("totalNumberOfPullRequests")]); ::OpenAPI::fromJsonValue(_class, json[QString("_class")]); } QString OAIPipelineBranchesitem::asJson () const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIPipelineBranchesitem::asJsonObject() const { QJsonObject obj; if(m_display_name_isSet){ obj.insert(QString("displayName"), ::OpenAPI::toJsonValue(display_name)); } if(m_estimated_duration_in_millis_isSet){ obj.insert(QString("estimatedDurationInMillis"), ::OpenAPI::toJsonValue(estimated_duration_in_millis)); } if(m_name_isSet){ obj.insert(QString("name"), ::OpenAPI::toJsonValue(name)); } if(m_weather_score_isSet){ obj.insert(QString("weatherScore"), ::OpenAPI::toJsonValue(weather_score)); } if(latest_run.isSet()){ obj.insert(QString("latestRun"), ::OpenAPI::toJsonValue(latest_run)); } if(m_organization_isSet){ obj.insert(QString("organization"), ::OpenAPI::toJsonValue(organization)); } if(pull_request.isSet()){ obj.insert(QString("pullRequest"), ::OpenAPI::toJsonValue(pull_request)); } if(m_total_number_of_pull_requests_isSet){ obj.insert(QString("totalNumberOfPullRequests"), ::OpenAPI::toJsonValue(total_number_of_pull_requests)); } if(m__class_isSet){ obj.insert(QString("_class"), ::OpenAPI::toJsonValue(_class)); } return obj; } QString OAIPipelineBranchesitem::getDisplayName() const { return display_name; } void OAIPipelineBranchesitem::setDisplayName(const QString &display_name) { this->display_name = display_name; this->m_display_name_isSet = true; } qint32 OAIPipelineBranchesitem::getEstimatedDurationInMillis() const { return estimated_duration_in_millis; } void OAIPipelineBranchesitem::setEstimatedDurationInMillis(const qint32 &estimated_duration_in_millis) { this->estimated_duration_in_millis = estimated_duration_in_millis; this->m_estimated_duration_in_millis_isSet = true; } QString OAIPipelineBranchesitem::getName() const { return name; } void OAIPipelineBranchesitem::setName(const QString &name) { this->name = name; this->m_name_isSet = true; } qint32 OAIPipelineBranchesitem::getWeatherScore() const { return weather_score; } void OAIPipelineBranchesitem::setWeatherScore(const qint32 &weather_score) { this->weather_score = weather_score; this->m_weather_score_isSet = true; } OAIPipelineBranchesitemlatestRun OAIPipelineBranchesitem::getLatestRun() const { return latest_run; } void OAIPipelineBranchesitem::setLatestRun(const OAIPipelineBranchesitemlatestRun &latest_run) { this->latest_run = latest_run; this->m_latest_run_isSet = true; } QString OAIPipelineBranchesitem::getOrganization() const { return organization; } void OAIPipelineBranchesitem::setOrganization(const QString &organization) { this->organization = organization; this->m_organization_isSet = true; } OAIPipelineBranchesitempullRequest OAIPipelineBranchesitem::getPullRequest() const { return pull_request; } void OAIPipelineBranchesitem::setPullRequest(const OAIPipelineBranchesitempullRequest &pull_request) { this->pull_request = pull_request; this->m_pull_request_isSet = true; } qint32 OAIPipelineBranchesitem::getTotalNumberOfPullRequests() const { return total_number_of_pull_requests; } void OAIPipelineBranchesitem::setTotalNumberOfPullRequests(const qint32 &total_number_of_pull_requests) { this->total_number_of_pull_requests = total_number_of_pull_requests; this->m_total_number_of_pull_requests_isSet = true; } QString OAIPipelineBranchesitem::getClass() const { return _class; } void OAIPipelineBranchesitem::setClass(const QString &_class) { this->_class = _class; this->m__class_isSet = true; } bool OAIPipelineBranchesitem::isSet() const { bool isObjectUpdated = false; do{ if(m_display_name_isSet){ isObjectUpdated = true; break;} if(m_estimated_duration_in_millis_isSet){ isObjectUpdated = true; break;} if(m_name_isSet){ isObjectUpdated = true; break;} if(m_weather_score_isSet){ isObjectUpdated = true; break;} if(latest_run.isSet()){ isObjectUpdated = true; break;} if(m_organization_isSet){ isObjectUpdated = true; break;} if(pull_request.isSet()){ isObjectUpdated = true; break;} if(m_total_number_of_pull_requests_isSet){ isObjectUpdated = true; break;} if(m__class_isSet){ isObjectUpdated = true; break;} }while(false); return isObjectUpdated; } }
28.167364
112
0.738562
PankTrue
a531f88b830fa58c47ddcc7d015872bf18c81664
55,115
cc
C++
raft_impl.cc
dengoswei/craft
16c4d403c0b1819dc21258cc4cbff6ffb8bf6457
[ "Apache-2.0" ]
5
2015-12-10T02:28:33.000Z
2019-06-02T18:20:53.000Z
raft_impl.cc
dengoswei/craft
16c4d403c0b1819dc21258cc4cbff6ffb8bf6457
[ "Apache-2.0" ]
null
null
null
raft_impl.cc
dengoswei/craft
16c4d403c0b1819dc21258cc4cbff6ffb8bf6457
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <sstream> #include "raft_impl.h" #include "replicate_tracker.h" #include "time_utils.h" #include "hassert.h" #include "mem_utils.h" using namespace std; namespace { using namespace raft; inline void assert_role(const RaftImpl& raft_impl, RaftRole expected_role) { hassert(raft_impl.getRole() == expected_role, "expected role %d but %d", static_cast<int>(expected_role), static_cast<int>(raft_impl.getRole())); } inline void assert_term(RaftImpl& raft_impl, uint64_t term) { hassert(raft_impl.getTerm() == term, "expected term %" PRIu64 " but term %" PRIu64, raft_impl.getTerm(), term); } template <typename T> bool isMajority( T expected, const std::map<uint64_t, T>& votes, size_t peer_ids_size, const std::set<uint64_t>& old_peer_ids, const std::set<uint64_t>& new_peer_ids) { bool major = countMajor(expected, votes, peer_ids_size); if (true == old_peer_ids.empty() || false == major) { return major; } assert(false == old_peer_ids.empty()); assert(false == new_peer_ids.empty()); // joint consensus // raft paper: // Agreement(for elections and entry commitment) requires // seperate majorities from both the old and new configrations. if (false == countMajor(expected, votes, old_peer_ids)) { return false; } return countMajor(expected, votes, new_peer_ids); } std::vector<const Entry*> make_vec_entries(const raft::Message& msg) { vector<const Entry*> vec_entries(msg.entries_size(), nullptr); for (int idx = 0; idx < msg.entries_size(); ++idx) { vec_entries[idx] = &msg.entries(idx); assert(nullptr != vec_entries[idx]); } assert(vec_entries.size() == static_cast<size_t>(msg.entries_size())); return vec_entries; } std::vector<const Entry*> shrinkEntries(uint64_t conflict_index, const std::vector<const Entry*>& entries) { if (size_t(0) == entries.size() || 0ull == conflict_index) { return vector<const Entry*>{entries.begin(), entries.end()}; } assert(size_t(0) < entries.size()); assert(nullptr != entries[0]); uint64_t base_index = entries[0]->index(); assert(conflict_index >= base_index); size_t idx = conflict_index - base_index; if (idx >= entries.size()) { return vector<const Entry*>{}; } return vector<const Entry*>{entries.begin() + idx, entries.end()}; } inline uint64_t getBaseLogIndex(std::deque<std::unique_ptr<Entry>>& logs) { if (true == logs.empty()) { return 0ull; } assert(nullptr != logs.front()); assert(0ull < logs.front()->index()); return logs.front()->index(); } size_t truncateLogs( std::deque<std::unique_ptr<Entry>>& logs, uint64_t truncate_index) { uint64_t base_index = getBaseLogIndex(logs); size_t idx = truncate_index - base_index; if (idx >= logs.size()) { return size_t{0}; } size_t prev_size = logs.size(); logs.erase(logs.begin() + idx, logs.end()); return prev_size - logs.size(); } inline bool IsAGroupMember( const RaftImpl& raft_impl, uint64_t peer_id, bool check_current) { if (true == check_current) { return raft_impl.GetCurrentConfig().IsAGroupMember(peer_id); } return raft_impl.GetCommitedConfig().IsAGroupMember(peer_id); } inline bool IsAReplicateMember( const RaftImpl& raft_impl, uint64_t peer_id) { return raft_impl.GetCurrentConfig().IsAReplicateMember(peer_id); } int ApplyConfChange( const Entry& conf_entry, bool check_pending, ConfChange& conf_change, RaftConfig& raft_config) { if (EntryType::EntryConfChange != conf_entry.type()) { logerr("expectecd %d but conf_entry.type %d", static_cast<int>(EntryType::EntryConfChange), static_cast<int>(conf_entry.type())); return -1; } // 1. if (false == conf_change.ParseFromString(conf_entry.data())) { return -2; } raft_config.ApplyConfChange(conf_change, check_pending); return 0; } std::vector<std::unique_ptr<raft::Message>> batchBuildMsgApp(raft::RaftImpl& raft_impl) { vector<unique_ptr<Message>> vec_msg; const auto& replicate_group = raft_impl.GetCurrentConfig().GetReplicateGroup(); uint64_t last_log_index = raft_impl.getLastLogIndex(); for (auto peer_id : replicate_group) { auto msg = raft_impl.GetReplicateTracker().BuildMsgApp( last_log_index, peer_id, [&](uint64_t to, uint64_t next_index, size_t batch_size) { return raft_impl.buildMsgApp( to, next_index, batch_size); }); if (nullptr != msg) { vec_msg.emplace_back(move(msg)); } assert(nullptr == msg); } return vec_msg; } std::vector<std::unique_ptr<raft::Message>> batchBuildMsgHeartbeat(raft::RaftImpl& raft_impl) { vector<unique_ptr<Message>> vec_msg; const auto& replicate_group = raft_impl.GetCurrentConfig().GetReplicateGroup(); for (auto peer_id : replicate_group) { auto msg = raft_impl.GetReplicateTracker().BuildMsgHeartbeat( peer_id, [&](uint64_t to, uint64_t next_index, size_t /* */) { return raft_impl.buildMsgHeartbeat(to, next_index); }); if (nullptr != msg) { vec_msg.emplace_back(move(msg)); } assert(nullptr == msg); } return vec_msg; } } // namespace namespace raft { const uint64_t META_INDEX = 0ull; const size_t MAX_BATCH_SIZE = 10; namespace candidate { MessageType onTimeout( RaftImpl& raft_impl, std::chrono::time_point<std::chrono::system_clock> time_now); } // namespace candidate namespace follower { MessageType onTimeout( RaftImpl& raft_impl, std::chrono::time_point<std::chrono::system_clock> time_now) { assert_role(raft_impl, RaftRole::FOLLOWER); logdebug("selfid(follower) %" PRIu64 " term %" PRIu64, raft_impl.getSelfId(), raft_impl.getTerm()); // only timeout if selfid IsAGroupMember if (false == IsAGroupMember(raft_impl, raft_impl.getSelfId(), true)) { // don't have MsgVote right; raft_impl.updateActiveTime(time_now); return MessageType::MsgNull; } // raft paper: // Followers 5.2 // if election timeout elapses without receiving AppendEntries // RPC from current leader or granting vote to candidate: // convert to candidate raft_impl.becomeCandidate(); return MessageType::MsgVote; } MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg) { assert_role(raft_impl, RaftRole::FOLLOWER); assert_term(raft_impl, msg.term()); auto time_now = std::chrono::system_clock::now(); auto rsp_msg_type = MessageType::MsgNull; switch (msg.type()) { case MessageType::MsgVote: // valid check // 1. msg.from => is a valid group member in current config; // 2. selfid => is a valid group member in current config; if (false == IsAGroupMember(raft_impl, msg.from(), true) || false == IsAGroupMember( raft_impl, raft_impl.getSelfId(), true)) { logerr("NotAGroupMember: msg.to %" PRIu64 " msg.from %" PRIu64, msg.to(), msg.from()); break; } // candidate requestVote msg // // raft paper: 5.1 & 5.4 // if votedFor is null or candidateid, and candidate's log is // at least as up-to-date as receiver's log, grant vote // // MORE DETAIL: // - each server will vote for at most one candidate in a // given term, on a first-come-first-served basis; // - the voter denies its vote if its own log is more up-to-date // then that of the candidate. if (raft_impl.isUpToDate(msg.log_term(), msg.index())) { // CAN'T RESET vote_for_ if (0ull == raft_impl.getVoteFor()) { raft_impl.setVoteFor(false, msg.from()); raft_impl.assignStoreSeq(META_INDEX); } assert(0ull != raft_impl.getVoteFor()); } // check getVoteFor() != msg.from() => reject! rsp_msg_type = MessageType::MsgVoteResp; raft_impl.updateActiveTime(time_now); logdebug("selfid %" PRIu64 " handle MsgVote", raft_impl.getSelfId()); break; case MessageType::MsgHeartbeat: { // leader heart beat msg // => Heartbeat with same term always from active leader raft_impl.setLeader(false, msg.from()); assert(msg.from() == raft_impl.getLeader()); rsp_msg_type = MessageType::MsgHeartbeatResp; raft_impl.updateActiveTime(time_now); logdebug("selfid %" PRIu64 " recv heartbeat from leader %" PRIu64, raft_impl.getSelfId(), msg.from()); } break; case MessageType::MsgApp: { // leader appendEntry msg // => AppendEntries always from active leader! raft_impl.setLeader(false, msg.from()); assert(msg.from() == raft_impl.getLeader()); // auto vec_entries = make_vec_entries(msg); auto entries = make_vec_entries(msg); // auto entries = make_entries(vec_entries); assert(static_cast<size_t>( msg.entries_size()) == entries.size()); auto append_count = raft_impl.appendEntries( msg.index(), msg.log_term(), msg.commit(), entries); auto store_seq = 0 < append_count ? raft_impl.assignStoreSeq(msg.index() + 1ull) : 0ull; logdebug("selfid(follower) %" PRIu64 " index %" PRIu64 " term %" PRIu64 " log_term %" PRIu64 " entries_size %zu append_count %d" " store_seq %" PRIu64, raft_impl.getSelfId(), msg.index(), msg.term(), msg.log_term(), entries.size(), append_count, store_seq); raft_impl.updateActiveTime(time_now); rsp_msg_type = MessageType::MsgAppResp; // 0 == msg.entries_size() => indicate already up-to-date } break; default: logdebug("IGNORE: recv msg type %d", static_cast<int>(msg.type())); // TODO ?: MsgProp: redirect to leader ? break; } return rsp_msg_type; } } // namespace follower namespace candidate { MessageType onTimeout( RaftImpl& raft_impl, std::chrono::time_point<std::chrono::system_clock> time_now) { assert_role(raft_impl, RaftRole::CANDIDATE); logdebug("selfid(candidate) %" PRIu64 " term %" PRIu64, raft_impl.getSelfId(), raft_impl.getTerm()); assert(true == IsAGroupMember(raft_impl, raft_impl.getSelfId(), true)); // raft paper: // Candidates 5.2 // On conversion to candidate or election timeout elapse, // start election: raft_impl.beginVote(); raft_impl.updateActiveTime(time_now); return MessageType::MsgVote; } MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg) { assert_role(raft_impl, RaftRole::CANDIDATE); assert_term(raft_impl, msg.term()); auto rsp_msg_type = MessageType::MsgNull; switch (msg.type()) { case MessageType::MsgVoteResp: // valid check if (false == IsAGroupMember(raft_impl, msg.from(), true) || false == IsAGroupMember( raft_impl, raft_impl.getSelfId(), true)) { logerr("NotAGroupMember: msg.to %" PRIu64 " msg.from %" PRIu64, msg.to(), msg.from()); break; } // collect vote resp raft_impl.updateVote(msg.from(), !msg.reject()); if (raft_impl.isMajorVoteYes()) { // step as leader: TODO ? raft_impl.becomeLeader(); // => immidicate send out headbeat ? // raft paper: // Rules for Servers, Leaders: // upon election: send initial empty AppendEntries RPCs // (heartbeat) to each server; repeat during idle periods // to prevent election timeouts 5.2 rsp_msg_type = MessageType::MsgHeartbeat; } logdebug("selfid %" PRIu64 " handle MsgVoteResp", raft_impl.getSelfId()); break; default: logdebug("IGNORE: recv msg type %d", static_cast<int>(msg.type())); // TODO: ? break; } return rsp_msg_type; } } // namespace candidate namespace leader { MessageType onTimeout( RaftImpl& raft_impl, std::chrono::time_point<std::chrono::system_clock> time_now) { assert_role(raft_impl, RaftRole::LEADER); raft_impl.updateActiveTime(time_now); return MessageType::MsgNull; } MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg) { assert_role(raft_impl, RaftRole::LEADER); assert_term(raft_impl, msg.term()); auto rsp_msg_type = MessageType::MsgNull; // check msg.from switch (msg.type()) { case MessageType::MsgProp: { // client prop // auto vec_entries = make_vec_entries(msg); // auto entries = make_entries(vec_entries); auto entries = make_vec_entries(msg); assert(static_cast<size_t>( msg.entries_size()) == entries.size()); auto ret = raft_impl.checkAndAppendEntries(msg.index(), entries); if (0 != ret) { logerr("checkAndAppendEntries ret %d", ret); break; } assert(0ull < msg.index() + 1ull); auto store_seq = raft_impl.assignStoreSeq(msg.index() + 1ull); logdebug("selfid(leader) %" PRIu64 " MsgProp index %" PRIu64 " store_seq %" PRIu64 " entries_size %zu " "last_index %" PRIu64, raft_impl.getSelfId(), msg.index(), store_seq, entries.size(), raft_impl.getLastLogIndex()); rsp_msg_type = MessageType::MsgApp; } break; case MessageType::MsgAppResp: { if (false == IsAReplicateMember(raft_impl, msg.from())) { // not a replicate member now // => ignore this request logerr("selfid %" PRIu64 " recv MsgAppResp from NotAReplicateMember %" PRIu64, raft_impl.getSelfId(), msg.from()); break; } // collect appendEntry resp // TODO: update commited! bool update = raft_impl.updateReplicateState( msg.from(), msg.reject(), msg.reject_hint(), msg.index()); if (update) { rsp_msg_type = MessageType::MsgApp; } else { assert(false == msg.reject()); if (1ull == msg.index() && 0ull < raft_impl.getLastLogIndex()) { // MsgApp prode reach match_index == 0ull // && leader log isn't empty; rsp_msg_type = MessageType::MsgApp; } } logdebug("selfid(leader) %" PRIu64 " MsgAppResp msg.from %" PRIu64 " msg.index %" PRIu64 " update %d reject %d rsp_msg_type %d", raft_impl.getSelfId(), msg.from(), msg.index(), static_cast<int>(update), static_cast<int>(msg.reject()), static_cast<int>(rsp_msg_type)); } break; case MessageType::MsgHeartbeatResp: { if (false == IsAReplicateMember(raft_impl, msg.from())) { // not a replicate member now // => ignore this request logerr("selfid %" PRIu64 " recv MsgHeartbeatResp from " "NotAReplicateMember %" PRIu64, raft_impl.getSelfId(), msg.from()); break; } // collect heartbeat resp bool update = raft_impl.updateReplicateState( msg.from(), msg.reject(), msg.reject_hint(), msg.index()); if (true == update) { rsp_msg_type = MessageType::MsgHeartbeat; } // TODO: logdebug } break; case MessageType::MsgNull: { // check followers timeout ? assert(0ull == msg.from()); auto time_now = chrono::system_clock::now(); if (raft_impl.isHeartbeatTimeout(time_now)) { raft_impl.updateHeartbeatTime(time_now); rsp_msg_type = MessageType::MsgHeartbeat; } } break; default: logdebug("IGNORE: recv msg type %d", static_cast<int>(msg.type())); // TODO: ? break; } return rsp_msg_type; } } // namespace leader RaftImpl::RaftImpl( uint64_t logid, uint64_t selfid, const std::set<uint64_t>& peer_ids, int min_election_timeout, int max_election_timeout) : logid_(logid) , selfid_(selfid) , current_config_(selfid) , commited_config_(selfid) , rtimeout_(min_election_timeout, max_election_timeout) , election_timeout_(rtimeout_()) , active_time_(chrono::system_clock::now()) , hb_timeout_(min_election_timeout / 2) { assert(0 < min_election_timeout); assert(min_election_timeout <= max_election_timeout); // fake ? for (auto id : peer_ids) { ConfChange conf_change; conf_change.set_type(ConfChangeType::ConfChangeAddNode); conf_change.set_node_id(id); current_config_.ApplyConfChange(conf_change, false); commited_config_.ApplyConfChange(conf_change, false); } assert(false == current_config_.IsPending()); assert(false == commited_config_.IsPending()); assert(0 < election_timeout_.count()); assert(0 < hb_timeout_.count()); setRole(RaftRole::FOLLOWER); } RaftImpl::RaftImpl( uint64_t logid, uint64_t selfid, const std::set<uint64_t>& peer_ids, int min_election_timeout, int max_election_timeout, const std::deque<std::unique_ptr<Entry>>& entry_queue, uint64_t commited_index, const RaftState* raft_state) : logid_(logid) , selfid_(selfid) , current_config_(selfid) , commited_config_(selfid) , rtimeout_(min_election_timeout, max_election_timeout) , election_timeout_(rtimeout_()) , active_time_(chrono::system_clock::now()) , hb_timeout_(min_election_timeout / 2) { assert(0 < min_election_timeout); assert(min_election_timeout < max_election_timeout); for (auto id : peer_ids) { ConfChange conf_change; conf_change.set_type(ConfChangeType::ConfChangeAddNode); conf_change.set_node_id(id); current_config_.ApplyConfChange(conf_change, false); commited_config_.ApplyConfChange(conf_change, false); } assert(false == current_config_.IsPending()); assert(false == commited_config_.IsPending()); assert(0 < election_timeout_.count()); assert(0 < hb_timeout_.count()); setRole(RaftRole::FOLLOWER); uint64_t index = 0; uint64_t max_term = 0; uint64_t max_seq = 0; for (auto& entry : entry_queue) { assert(nullptr != entry); assert(entry->index() > index); assert(entry->index() >= commited_index); index = entry->index(); assert(max_term <= entry->term()); max_term = entry->term(); max_seq = max(max_seq, entry->seq()); if (EntryType::EntryConfChange == entry->type()) { applyCommitedConfEntry(*entry); // applyCommitedConfEntry ? } logs_.emplace_back( cutils::make_unique<Entry>(*entry)); assert(nullptr != logs_.back()); } assert(entry_queue.empty() == logs_.empty()); if (0 != commited_index) { assert(0 != index); assert(nullptr != raft_state); assert(true == isIndexInMem(commited_index)); } uint64_t vote_for = 0ull; if (nullptr != raft_state) { assert(commited_index >= raft_state->commit()); assert(max_term <= raft_state->term()); max_term = raft_state->term(); vote_for = raft_state->vote(); max_seq = max(max_seq, raft_state->seq()); } if (0 != max_term) { setTerm(max_term); } setVoteFor(true, vote_for); assert(getTerm() == max_term); assert(getVoteFor() == vote_for); commited_index_ = commited_index; store_seq_ = max_seq+1; } RaftImpl::~RaftImpl() = default; MessageType RaftImpl::CheckTerm(uint64_t msg_term) { // raft paper: rules for servers: 5.1 // => If RPC request or response contains term T > currentTerm: // set currentTerm = T, convert to follower; if (msg_term != term_) { if (msg_term > term_) { becomeFollower(msg_term); return MessageType::MsgNull; } assert(msg_term < term_); return MessageType::MsgInvalidTerm; } assert(msg_term == term_); return MessageType::MsgNull; } MessageType RaftImpl::CheckTimout( std::chrono::time_point<std::chrono::system_clock> time_now) { if (active_time_ + election_timeout_ < time_now) { // TIME OUT: assert(nullptr != timeout_handler_); return timeout_handler_(*this, time_now); } return MessageType::MsgNull; } MessageType RaftImpl::step(const Message& msg) { assert(msg.logid() == logid_); assert(msg.to() == selfid_); // 1. check term auto rsp_msg_type = CheckTerm(msg.term()); if (MessageType::MsgNull != rsp_msg_type) { assert(MessageType::MsgInvalidTerm == rsp_msg_type); return rsp_msg_type; } assert(msg.term() == term_); // 2. check timeout // ! IMPORTANT ! // if setTerm => false == CheckTimeout rsp_msg_type = CheckTimout(chrono::system_clock::now()); if (MessageType::MsgNull != rsp_msg_type) { assert(MessageType::MsgVote == rsp_msg_type); return rsp_msg_type; } // 3. step message return step_handler_(*this, msg); } std::vector<std::unique_ptr<Message>> RaftImpl::produceRsp( const Message& req_msg, MessageType rsp_msg_type) { assert(req_msg.logid() == logid_); assert(req_msg.to() == selfid_); vector<unique_ptr<Message>> vec_msg; if (MessageType::MsgNull == rsp_msg_type) { return vec_msg; } Message msg_template; msg_template.set_type(rsp_msg_type); msg_template.set_logid(logid_); msg_template.set_from(selfid_); msg_template.set_term(term_); msg_template.set_to(req_msg.from()); switch (rsp_msg_type) { case MessageType::MsgVote: // raft paper: // RequestVote RPC Arguments: // - term // - candidicateId // - lastLogIndex // - lastLogTerm msg_template.set_index(getLastLogIndex()); msg_template.set_log_term(getLastLogTerm()); vec_msg = current_config_.BroadcastGroupMsg(msg_template); logdebug("MsgVote term %" PRIu64 " candidate %" PRIu64 " lastLogIndex %" PRIu64 " lastLogTerm %" PRIu64 " vec_msg.size %zu", term_, selfid_, msg_template.index(), msg_template.log_term(), vec_msg.size()); break; case MessageType::MsgVoteResp: { // raft paper: // RequestVote RPC Results: // - term // - voteGranted assert(0ull != req_msg.from()); vec_msg.emplace_back(cutils::make_unique<Message>(msg_template)); auto& rsp_msg = vec_msg.back(); assert(nullptr != rsp_msg); rsp_msg->set_reject(req_msg.from() != getVoteFor()); logdebug("MsgVoteResp term %" PRIu64 " req_msg.from %" PRIu64 " getVoteFor %" PRIu64 " reject %d", term_, req_msg.from(), getVoteFor(), static_cast<int>(rsp_msg->reject())); } break; case MessageType::MsgApp: { assert(nullptr != replicate_states_); // req_msg.type() == MessageType::MsgProp if (0ull == req_msg.from()) { vec_msg = batchBuildMsgApp(*this); logdebug("MsgApp BatchBuildMsgAppUpToDate " "vec_msg.size %zu", vec_msg.size()); } else { assert(0ull != req_msg.from()); // catch-up mode maybe assert(MessageType::MsgAppResp == req_msg.type()); auto rsp_msg = replicate_states_->BuildMsgApp( getLastLogIndex(), req_msg.from(), [&](uint64_t to, uint64_t next_index, size_t batch_size) { return buildMsgApp(to, next_index, batch_size); }); if (nullptr != rsp_msg) { logdebug("MsgApp from %" PRIu64 " to %" PRIu64 " index %" PRIu64 " log_term %" PRIu64, rsp_msg->from(), rsp_msg->to(), rsp_msg->index(), rsp_msg->log_term()); if (0 != rsp_msg->entries_size() || !isPeerUpToDate(req_msg.commit())) { vec_msg.emplace_back(move(rsp_msg)); assert(size_t{1} == vec_msg.size()); } else { logdebug("INGORE: peer_id %" PRIu64 " rsp_msg->entries_size %d" " req_msg.commit %" PRIu64 " commited_index_ %" PRIu64, req_msg.from(), rsp_msg->entries_size(), req_msg.commit(), getCommitedIndex()); } // else => ignore } logdebug("MsgApp selfid %" PRIu64 " req_msg.from %" PRIu64 " req_msg.index %" PRIu64 " vec_msg.size %zu", selfid_, req_msg.from(), req_msg.index(), vec_msg.size()); } } break; case MessageType::MsgAppResp: { // req_msg.type() == MessageType::MsgApp // raft paper: // AppendEntries RPC, Results: // - reply false if term < currentTerm // - reply false if log don't contain an entry at prevLogIndex // whose term matchs prevLogTerm assert(0ull != req_msg.from()); vec_msg.emplace_back(cutils::make_unique<Message>(msg_template)); auto& rsp_msg = vec_msg.back(); assert(nullptr != rsp_msg); // TODO: reject hint ? rsp_msg->set_reject(!isMatch(req_msg.index(), req_msg.log_term())); if (false == rsp_msg->reject()) { // set index to next_index if (0 < req_msg.entries_size()) { rsp_msg->set_index( req_msg.entries( req_msg.entries_size() - 1).index() + 1ull); } else { rsp_msg->set_index(req_msg.index() + 1ull); } } rsp_msg->set_commit(getCommitedIndex()); logdebug("MsgAppResp term %" PRIu64 " req_msg.from(leader) %" PRIu64 " prev_index %" PRIu64 " prev_log_term %" PRIu64 " entries_size %d reject %d next_index %" PRIu64, term_, req_msg.from(), req_msg.index(), req_msg.log_term(), req_msg.entries_size(), static_cast<int>(rsp_msg->reject()), rsp_msg->index()); } break; case MessageType::MsgHeartbeat: { assert(nullptr != replicate_states_); // TODO: // better way to probe the next_indexes_ & match_indexes_ // // MsgHeartbeat => empty AppendEntries RPCs if (MessageType::MsgHeartbeatResp == req_msg.type()) { // 1 : 1 assert(MessageType::MsgHeartbeatResp == req_msg.type()); assert(true == req_msg.reject()); auto hb_msg = replicate_states_->BuildMsgHeartbeat( req_msg.from(), [&](uint64_t to, uint64_t next_index, size_t /* */) { return buildMsgHeartbeat(to, next_index); }); if (nullptr != hb_msg) { vec_msg.emplace_back(move(hb_msg)); } assert(nullptr == hb_msg); } else { // broad cast vec_msg = batchBuildMsgHeartbeat(*this); } } break; case MessageType::MsgHeartbeatResp: { // rsp to leader assert(req_msg.from() == getLeader()); vec_msg.emplace_back(cutils::make_unique<Message>(msg_template)); auto& rsp_msg = vec_msg.back(); assert(nullptr != rsp_msg); rsp_msg->set_reject(!isMatch(req_msg.index(), req_msg.log_term())); if (false == rsp_msg->reject()) { rsp_msg->set_index(req_msg.index() + 1ull); } logdebug("MsgHeartbeatResp term %" PRIu64 " req_msg.from(leader) %" PRIu64 " prev_index %" PRIu64 " prev_log_term %" PRIu64 " reject %d next_index %" PRIu64 , term_, req_msg.from(), req_msg.index(), req_msg.log_term(), static_cast<int>(rsp_msg->reject()), rsp_msg->index()); } break; case MessageType::MsgNull: // DO NOTHING ? break; case MessageType::MsgInvalidTerm: logdebug("MsgInvalidTerm selfid %" PRIu64 " role %d term_ %" PRIu64 " msg.from %" PRIu64 " msg.term %" PRIu64, getSelfId(), static_cast<int>(getRole()), getTerm(), req_msg.from(), req_msg.term()); // TODO: rsp with ? break; default: hassert(false, "invalid rsp_msg_type %d", static_cast<int>(rsp_msg_type)); break; } return vec_msg; } std::unique_ptr<Message> RaftImpl::buildMsgApp( uint64_t peer_id, uint64_t index, size_t max_batch_size) { // raft paper // AppendEntries RPC Arguments: // - leader term // - leader id // - prevLogIndex // - prevLogTerm // - entries[] // - leaderCommit assert(size_t{0} <= max_batch_size); assert(0ull < index); auto app_msg = cutils::make_unique<Message>(); assert(nullptr != app_msg); app_msg->set_type(MessageType::MsgApp); app_msg->set_logid(logid_); app_msg->set_term(term_); app_msg->set_from(selfid_); app_msg->set_to(peer_id); app_msg->set_commit(commited_index_); uint64_t base_index = 0ull; uint64_t last_index = 0ull; tie(base_index, last_index) = getInMemIndex(); logdebug("selfid %" PRIu64 " leader_id %" PRIu64 " index %" PRIu64 " base_index %" PRIu64 " last_index %" PRIu64 " logs_.size %zu max_batch_size %zu", selfid_, leader_id_, index, base_index, last_index, logs_.size(), max_batch_size); if (index < base_index || index > last_index + 1ull) { if (index < base_index) { // report: not in mem // => or submit a catch-up job ? // => catch-up to commited_index point ? // => which will read log from db directly ?? ids_not_in_mem_.insert(peer_id); } return nullptr; } assert(size_t{0} <= last_index - index + 1ull); app_msg->set_index(index - 1ull); app_msg->set_log_term(getLogTerm(index - 1ull)); app_msg->set_commit(commited_index_); assert(size_t{0} <= last_index - index + 1ull); max_batch_size = min<size_t>( max_batch_size, last_index - index + 1ull); for (auto i = size_t{0}; i < max_batch_size; ++i) { auto entry = app_msg->add_entries(); assert(nullptr != entry); *entry = *logs_[index + i - base_index]; } assert(max_batch_size == static_cast<size_t>(app_msg->entries_size())); logdebug("selfid %" PRIu64 " peer_id %" PRIu64 " index %" PRIu64 " max_batch_size %zu", getSelfId(), peer_id, index, max_batch_size); return app_msg; } std::unique_ptr<Message> RaftImpl::buildMsgHeartbeat( uint64_t peer_id, uint64_t next_index) const { assert(0ull < next_index); auto hb_msg = cutils::make_unique<Message>(); assert(nullptr != hb_msg); hb_msg->set_type(MessageType::MsgHeartbeat); hb_msg->set_logid(logid_); hb_msg->set_term(term_); hb_msg->set_from(selfid_); hb_msg->set_to(peer_id); // heartbeat uint64_t base_index = 0ull; uint64_t last_index = 0ull; tie(base_index, last_index) = getInMemIndex(); next_index = max(base_index + 1, next_index); next_index = min(last_index + 1, next_index); hb_msg->set_index(next_index - 1ull); hb_msg->set_log_term(getLogTerm(next_index - 1ull)); hb_msg->set_commit(commited_index_); return hb_msg; } bool RaftImpl::isUpToDate( uint64_t peer_log_term, uint64_t peer_max_index) { // raft paper // 5.4.1 Election restriction // raft determines which of two logs is more up-to-date by // comparing the index and term of the last entries in the logs. // - If the logs have last entries with different terms, then the log // with the later term is more up-to-date; // - If the logs end with the same term, then whichever log is longer // is more up-to-date. uint64_t log_term = getLastLogTerm(); if (peer_log_term > log_term) { return true; } assert(peer_log_term <= log_term); if (peer_log_term == log_term) { return peer_max_index >= getLastLogIndex(); } // else return false; } int RaftImpl::appendLogs(const std::vector<const Entry*>& entries) { if (size_t(0) == entries.size()) { return 0; // do nothing; } assert(nullptr != entries[0]); uint64_t base_index = entries[0]->index(); auto truncate_size = truncateLogs(logs_, base_index); if (size_t{0} < truncate_size) { logerr("INFO selfid %" PRIu64 " truncate_size %zu", getSelfId(), truncate_size); assert(0 == reconstructCurrentConfig()); // reset currentConfig; } uint64_t last_index = getLastLogIndex(); assert(last_index + 1 == base_index); for (size_t idx = 0; idx < entries.size(); ++idx) { assert(nullptr != entries[idx]); if (EntryType::EntryConfChange == entries[idx]->type()) { applyCommitedConfEntry(*entries[idx]); } logs_.emplace_back(cutils::make_unique<Entry>(*entries[idx])); assert(nullptr != logs_.back()); } return entries.size(); } int RaftImpl::appendEntries( uint64_t prev_log_index, uint64_t prev_log_term, uint64_t leader_commited_index, const std::vector<const Entry*>& entries) { assert_role(*this, RaftRole::FOLLOWER); assert(leader_commited_index >= commited_index_); if (!isMatch(prev_log_index, prev_log_term)) { return -1; } // match // raft paper: // - If an existing entry conflicts with a new one(same index but // different terms), delete the existing entry and all that follow it // - Append any new entries not already in the log uint64_t conflict_index = findConflict(entries); assert(0ull == conflict_index || commited_index_ < conflict_index); auto new_entries = shrinkEntries(conflict_index, entries); int append_count = appendLogs(new_entries); updateFollowerCommitedIndex(leader_commited_index); return append_count; } int RaftImpl::checkAndAppendEntries( uint64_t prev_log_index, const std::vector<const Entry*>& entries) { assert_role(*this, RaftRole::LEADER); assert(nullptr != replicate_states_); uint64_t last_index = getLastLogIndex(); if (prev_log_index != last_index) { return -1; } // max length control ? for (size_t idx = 0; idx < entries.size(); ++idx) { assert(nullptr != entries[idx]); // apply conf change before push entries into logs_ if (EntryType::EntryConfChange == entries[idx]->type()) { assert(size_t{1} == entries.size()); assert(size_t{0} == idx); // applyConfChange: auto ret = applyUnCommitedConfEntry(*entries[idx]); if (0 != ret) { // drop conf change request logerr("applyUnCommitedConfEntry ret %d", ret); return -2; } } logs_.emplace_back( cutils::make_unique<Entry>(*entries[idx])); assert(nullptr != logs_.back()); logs_.back()->set_term(term_); logs_.back()->set_index(last_index + 1ull + idx); } replicate_states_->UpdateSelfState(getLastLogIndex()); logdebug("selfid %" PRIu64 " last_index %" PRIu64 " logs_size %zu", selfid_, getLastLogIndex(), logs_.size()); // TODO: find a way to store logs_ to disk return 0; } void RaftImpl::setRole(RaftRole new_role) { logdebug("selfid %" PRIu64 " change role_ %d new_role %d", selfid_, static_cast<int>(role_), static_cast<int>(new_role)); role_ = new_role; switch (role_) { case RaftRole::FOLLOWER: timeout_handler_ = ::raft::follower::onTimeout; step_handler_ = ::raft::follower::onStepMessage; break; case RaftRole::CANDIDATE: timeout_handler_ = ::raft::candidate::onTimeout; step_handler_ = ::raft::candidate::onStepMessage; break; case RaftRole::LEADER: timeout_handler_ = ::raft::leader::onTimeout; step_handler_ = ::raft::leader::onStepMessage; break; } return ; } void RaftImpl::setTerm(uint64_t new_term) { logdebug("selfid %" PRIu64 " role %d change current term %" PRIu64 " new_term %" PRIu64, selfid_, static_cast<int>(role_), term_, new_term); assert(term_ < new_term); term_ = new_term; return ; } void RaftImpl::setVoteFor(bool reset, uint64_t candidate) { logdebug("selfid_ %" PRIu64 " reset %d vote_for_ %" PRIu64 " to candidate %" PRIu64, selfid_, static_cast<int>(reset), vote_for_, candidate); if (true == reset || 0ull == vote_for_) { vote_for_ = candidate; } } uint64_t RaftImpl::assignStoreSeq(uint64_t index) { auto seq = ++store_seq_; if (0ull == index) { pending_meta_seq_ = seq; } else { pending_log_idx_ = 0ull == pending_log_idx_ ? index : min(pending_log_idx_, index); pending_log_seq_ = seq; } // logdebug("selfid %" PRIu64 " index %" PRIu64 // " pending_meta_seq_ %" PRIu64 // " pending_log_idx_ %" PRIu64 " pending_log_seq_ %" PRIu64, // getSelfId(), index, pending_meta_seq_, // pending_log_idx_, pending_log_seq_); return seq; } std::tuple<uint64_t, uint64_t, uint64_t> RaftImpl::getStoreSeq() const { logdebug("selfid %" PRIu64 " pending_meta_seq_ %" PRIu64 " pending_log_idx_ %" PRIu64 " pending_log_seq_ %" PRIu64, getSelfId(), pending_meta_seq_, pending_log_idx_, pending_log_seq_); return make_tuple( pending_meta_seq_, pending_log_idx_, pending_log_seq_); } void RaftImpl::commitedStoreSeq( uint64_t meta_seq, uint64_t log_idx, uint64_t log_seq) { logdebug("selfid %" PRIu64 " meta_seq %" PRIu64 " log_idx %" PRIu64 " log_seq %" PRIu64 " pending_meta_seq_ %" PRIu64 " pending_log_idx_ %" PRIu64 " pending_log_seq_ %" PRIu64, getSelfId(), meta_seq, log_idx, log_seq, pending_meta_seq_, pending_log_idx_, pending_log_seq_); if (meta_seq == pending_meta_seq_) { pending_meta_seq_ = 0ull; // reset } if (log_idx == pending_log_idx_ && log_seq == pending_log_seq_) { pending_log_idx_ = 0ull; pending_log_seq_ = 0ull; } } void RaftImpl::updateActiveTime( std::chrono::time_point<std::chrono::system_clock> time_now) { { auto at_str = cutils::format_time(active_time_); auto time_str = cutils::format_time(time_now); // logdebug("selfid %" PRIu64 " update active_time_ %s " // "to time_now %s", // getSelfId(), at_str.c_str(), time_str.c_str()); } active_time_ = time_now; } uint64_t RaftImpl::getLastLogIndex() const { auto t = getInMemIndex(); return get<1>(t); } uint64_t RaftImpl::getLastLogTerm() const { if (true == logs_.empty()) { assert(0ull == commited_index_); return 0ull; } assert(nullptr != logs_.back()); assert(term_ >= logs_.back()->term()); return logs_.back()->term(); } uint64_t RaftImpl::getBaseLogTerm() const { if (true == logs_.empty()) { assert(0ull == commited_index_); return 0ull; } assert(nullptr != logs_.front()); assert(0ull != logs_.front()->term()); assert(term_ >= logs_.front()->term()); return logs_.front()->term(); } std::tuple<uint64_t, uint64_t> RaftImpl::getInMemIndex() const { if (true == logs_.empty()) { assert(0ull == commited_index_); return make_tuple(0ull, 0ull); } assert(nullptr != logs_.front()); assert(0ull < logs_.front()->index()); assert(0ull == commited_index_ || commited_index_ >= logs_.front()->index()); assert(nullptr != logs_.back()); assert(logs_.back()->index() == logs_.front()->index() + logs_.size() - 1ull); return make_tuple(logs_.front()->index(), logs_.back()->index()); } uint64_t RaftImpl::getBaseLogIndex() const { auto t = getInMemIndex(); return get<0>(t); } const Entry* RaftImpl::getLogEntry(uint64_t log_index) const { if (0ull == log_index) { return nullptr; } assert(0ull < log_index); auto base_index = 0ull; auto last_index = 0ull; tie(base_index, last_index) = getInMemIndex(); if (log_index < base_index || log_index > last_index) { return nullptr; } assert(false == logs_.empty()); size_t idx = log_index - base_index; assert(0 <= idx && idx < logs_.size()); assert(nullptr != logs_[idx]); assert(log_index == logs_[idx]->index()); assert(0 < logs_[idx]->term()); return logs_[idx].get(); } std::vector<std::unique_ptr<raft::Entry>> RaftImpl::getLogEntriesAfter(uint64_t log_index) const { vector<unique_ptr<Entry>> vec_entries; uint64_t base_index = 0ull; uint64_t last_index = 0ull; tie(base_index, last_index) = getInMemIndex(); assert(base_index <= log_index + 1ull); if (log_index >= last_index) { return vec_entries; } assert(0ull < last_index - log_index); vec_entries.reserve(last_index - log_index); for (; log_index < last_index; ++log_index) { auto index = log_index + 1; auto entry = getLogEntry(index); assert(nullptr != entry); assert(index == entry->index()); vec_entries.emplace_back( cutils::make_unique<Entry>(*entry)); assert(nullptr != vec_entries.back()); vec_entries.back()->set_seq(pending_log_seq_); } return vec_entries; } std::unique_ptr<raft::RaftState> RaftImpl::getCurrentRaftState() const { auto hs = cutils::make_unique<RaftState>(); assert(nullptr != hs); hs->set_term(term_); hs->set_vote(vote_for_); hs->set_commit(commited_index_); hs->set_seq(pending_meta_seq_); return hs; } uint64_t RaftImpl::getLogTerm(uint64_t log_index) const { const auto entry = getLogEntry(log_index); if (nullptr == entry) { return 0ull; } return entry->term(); } bool RaftImpl::isIndexInMem(uint64_t log_index) const { return getBaseLogIndex() <= log_index; } void RaftImpl::beginVote() { assert_role(*this, RaftRole::CANDIDATE); // start election: // - increment currentTerm // - vote for self // - reset election timer // - send requestVote RPCs to all other servers setTerm(term_ + 1); // aka inc term setVoteFor(true, selfid_); assignStoreSeq(META_INDEX); // reset vote_resps_.clear(); vote_resps_[selfid_] = true; return ; } void RaftImpl::updateVote(uint64_t peer_id, bool current_rsp) { // current_rsp: // - true: vote yes; // - false: vote no; assert_role(*this, RaftRole::CANDIDATE); if (vote_resps_.end() == vote_resps_.find(peer_id)) { vote_resps_[peer_id] = current_rsp; return ; } bool prev_rsp = vote_resps_[peer_id]; logerr("peer_id %" PRIu64 " prev_rsp %d current_rsp %d", peer_id, static_cast<int>(prev_rsp), static_cast<int>(current_rsp)); // assert ? return ; } bool RaftImpl::isMajorVoteYes() const { assert_role(*this, RaftRole::CANDIDATE); return current_config_.IsMajorVoteYes(vote_resps_); } bool RaftImpl::isMatch(uint64_t log_index, uint64_t log_term) const { assert_role(*this, RaftRole::FOLLOWER); if (0ull == log_index) { assert(0ull == log_term); return true; // always } assert(0ull < log_index); assert(0ull < log_term); const uint64_t local_log_term = getLogTerm(log_index); if (local_log_term == log_term) { return true; } if (log_index <= commited_index_) { assert(0ull == local_log_term); return true; } assert(0ull == local_log_term || log_index <= getLastLogIndex()); return false; } void RaftImpl::updateLeaderCommitedIndex(uint64_t new_commited_index) { assert_role(*this, RaftRole::LEADER); assert(commited_index_ < new_commited_index); logdebug("selfid(leader) %" PRIu64 " commited_index_ %" PRIu64 " new_commited_index %" PRIu64, selfid_, commited_index_, new_commited_index); commited_index_ = new_commited_index; } void RaftImpl::updateFollowerCommitedIndex(uint64_t leader_commited_index) { assert_role(*this, RaftRole::FOLLOWER); assert(commited_index_ <= leader_commited_index); const uint64_t last_index = getLastLogIndex(); logdebug("selfid %" PRIu64 " commited_index_ %" PRIu64 " last_index %" PRIu64 " leader_commited_index %" PRIu64, selfid_, commited_index_, last_index, leader_commited_index); // if leaderCommit > commitIndex, // set commitIndex = min(leaderCommit, index of last new entry) commited_index_ = min(leader_commited_index, last_index); return ; } uint64_t RaftImpl::findConflict(const std::vector<const Entry*>& entries) const { if (size_t{0} == entries.size() || true == logs_.empty()) { return 0ull; } assert(size_t{0} < entries.size()); assert(false == logs_.empty()); for (size_t idx = 0; idx < entries.size(); ++idx) { assert(nullptr != entries[idx]); if (!isMatch(entries[idx]->index(), entries[idx]->term())) { return entries[idx]->index(); } } return entries[entries.size() -1]->index() + 1ull; } bool RaftImpl::updateReplicateState( uint64_t peer_id, bool reject, uint64_t reject_hint, uint64_t peer_next_index) { assert_role(*this, RaftRole::LEADER); assert(nullptr != replicate_states_); bool update = replicate_states_->UpdateReplicateState( peer_id, reject, reject_hint, peer_next_index); if (true == update) { auto new_commited_index = 0ull == peer_next_index ? 0ull : peer_next_index - 1ull; if (getTerm() == getLogTerm(new_commited_index) && new_commited_index > getCommitedIndex()) { if (current_config_.IsMajorCommited( new_commited_index, replicate_states_->peekMatchIndexes())) { updateLeaderCommitedIndex(new_commited_index); } } } return update; } void RaftImpl::becomeFollower(uint64_t term) { if (nullptr != replicate_states_) { replicate_states_.reset(); } assert(nullptr == replicate_states_); setRole(RaftRole::FOLLOWER); term = 0ull == term ? term_ + 1ull : term; assert(term_ < term); setTerm(term); setLeader(true, 0ull); setVoteFor(true, 0ull); // reset vote_for_ assignStoreSeq(META_INDEX); // new follower => will not timeout immidiate; resetElectionTimeout(); updateActiveTime(chrono::system_clock::now()); // TODO ?? return ; } void RaftImpl::becomeCandidate() { assert(nullptr == replicate_states_); setRole(RaftRole::CANDIDATE); setLeader(true, 0ull); // raft paper // Candidates 5.2 // On conversion to candidate or election timeout elapse, // start election: // - inc term // - set vote for // - assign store seq beginVote(); resetElectionTimeout(); updateActiveTime(chrono::system_clock::now()); return ; } void RaftImpl::becomeLeader() { setRole(RaftRole::LEADER); // raft paper // State // nextIndex[] // for each server, index of the next log entry to send to that // server(initialized to leader last log index + 1) // matchIndex[] // for each server, index of highest log entry known to be // replicated on server(initailzed to 0, increases monotonically) setLeader(false, selfid_); assert(selfid_ == leader_id_); assert(nullptr == replicate_states_); replicate_states_ = current_config_.CreateReplicateTracker(getLastLogIndex(), MAX_BATCH_SIZE); assert(nullptr != replicate_states_); makeHeartbeatTimeout(chrono::system_clock::now()); return ; } void RaftImpl::setLeader(bool reset, uint64_t leader_id) { logdebug("selfid_ %" PRIu64 " reset %d leader_id_ %" PRIu64 " to leader_id %" PRIu64, selfid_, static_cast<int>(reset), leader_id_, leader_id); if (true == reset || 0ull == leader_id_) { leader_id_ = leader_id; } } bool RaftImpl::isHeartbeatTimeout( std::chrono::time_point< std::chrono::system_clock> time_now) { return hb_time_ + hb_timeout_ < time_now; } void RaftImpl::updateHeartbeatTime( std::chrono::time_point< std::chrono::system_clock> next_hb_time) { { auto hb_str = cutils::format_time(hb_time_); auto next_hb_str = cutils::format_time(next_hb_time); logdebug("selfid %" PRIu64 " update hb_time_ %s to next_hb_time %s", getSelfId(), hb_str.c_str(), next_hb_str.c_str()); } hb_time_ = next_hb_time; } void RaftImpl::makeElectionTimeout( std::chrono::time_point<std::chrono::system_clock> tp) { tp -= chrono::milliseconds{getElectionTimeout() + 1}; updateActiveTime(tp); } void RaftImpl::makeHeartbeatTimeout( std::chrono::time_point<std::chrono::system_clock> tp) { tp -= chrono::milliseconds{getHeartbeatTimeout() + 1}; updateHeartbeatTime(tp); } std::unique_ptr<raft::RaftState> RaftImpl::getPendingRaftState() const { if (0ull == pending_meta_seq_) { return nullptr; } return getCurrentRaftState(); } std::vector<std::unique_ptr<raft::Entry>> RaftImpl::getPendingLogEntries() const { if (0ull == pending_log_idx_) { assert(0ull == pending_log_seq_); return vector<unique_ptr<Entry>>{}; } assert(0ull < pending_log_idx_); assert(0ull < pending_log_seq_); return getLogEntriesAfter(pending_log_idx_ - 1ull); } void RaftImpl::resetElectionTimeout() { int next_election_timeout = rtimeout_(); assert(0 < next_election_timeout); logdebug("election_timeout_ %d next_election_timeout %d", static_cast<int>(election_timeout_.count()), next_election_timeout); election_timeout_ = chrono::milliseconds{next_election_timeout}; } bool RaftImpl::isPeerUpToDate(uint64_t peer_commited_index) const { assert(peer_commited_index <= commited_index_); return peer_commited_index == commited_index_; } void RaftImpl::assertNoPending() const { assert(RaftRole::LEADER == getRole()); assert(nullptr != replicate_states_); for (const auto& id_pending : replicate_states_->peekPendingState()) { if (getSelfId() == id_pending.first) { continue; } assert(false == id_pending.second); } } int RaftImpl::applyUnCommitedConfEntry(const Entry& conf_entry) { ConfChange conf_change; auto ret = ApplyConfChange( conf_entry, true, conf_change, current_config_); if (0 != ret) { return ret; } // 3. if (nullptr == replicate_states_) { return 0; } assert(RaftRole::LEADER == getRole()); replicate_states_->ApplyConfChange(conf_change, getLastLogIndex()); return 0; } int RaftImpl::applyCommitedConfEntry(const Entry& conf_entry) { ConfChange conf_change; return ApplyConfChange( conf_entry, false, conf_change, commited_config_); } int RaftImpl::reconstructCurrentConfig() { assert(RaftRole::FOLLOWER == getRole()); current_config_ = commited_config_; auto last_index = getLastLogIndex(); for (auto index = getCommitedIndex() + 1ull; index <= last_index; ++index) { auto entry = getLogEntry(index); assert(nullptr != entry); ConfChange conf_change; auto ret = ApplyConfChange( *entry, true, conf_change, current_config_); if (0 != ret) { return ret; } assert(0 == ret); } return 0; } } // namespace raft
31.015757
82
0.589749
dengoswei
a53314e22a638de0302a218fb6db0734a3235269
364
cpp
C++
headers/main/bw_encode.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
headers/main/bw_encode.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
headers/main/bw_encode.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
#include "../algorithms/sorting.h" #include "../tools/_fasta.h" int main (int argc, char * const argv[]) { if (argc != 3) { cout << "Encode a genome's fasta sequences using the Burrows-Wheeler algorithm." << endl; cout << "Usage: ./burrows_wheeler /infile.fa /outfile.fa" << endl; exit(0); } ReadSlam::FastA::Genome g; g.bw_encode(argv[1], argv[2]); }
24.266667
91
0.645604
SamBuckberry
a53361e4645143c7ce4a6fb44ce50adbc3a85dd6
2,148
cpp
C++
apps/xcomp/src/XCConfig.cpp
gugenstudio/Xcomp
b8c572ec618fa157c4ed07845b87d0ced21b2dd5
[ "MIT" ]
1
2022-02-18T11:55:57.000Z
2022-02-18T11:55:57.000Z
apps/xcomp/src/XCConfig.cpp
gugenstudio/xComp
b8c572ec618fa157c4ed07845b87d0ced21b2dd5
[ "MIT" ]
null
null
null
apps/xcomp/src/XCConfig.cpp
gugenstudio/xComp
b8c572ec618fa157c4ed07845b87d0ced21b2dd5
[ "MIT" ]
null
null
null
//================================================================== /// XCConfig.cpp /// /// Created by Davide Pasca - 2022/01/21 /// See the file "license.txt" that comes with this project for /// copyright info. //================================================================== #include "GTVersions.h" #include "XCConfig.h" //================================================================== void XCConfig::Serialize( SerialJS &v_ ) const { v_.MSerializeObjectStart(); SerializeMember( v_, "cfg_savedVer", DStr(GTV_SUITE_VERSION) ); SERIALIZE_THIS_MEMBER( v_, cfg_scanDir ); SERIALIZE_THIS_MEMBER( v_, cfg_scanDirHist ); SERIALIZE_THIS_MEMBER( v_, cfg_saveDir ); SERIALIZE_THIS_MEMBER( v_, cfg_ctrlPanButton ); SERIALIZE_THIS_MEMBER( v_, cfg_dispAutoFit ); SERIALIZE_THIS_MEMBER( v_, cfg_imsConfig ); v_.MSerializeObjectEnd(); } void XCConfig::Deserialize( DeserialJS &v_ ) { DESERIALIZE_THIS_MEMBER( v_, cfg_savedVer ); DESERIALIZE_THIS_MEMBER( v_, cfg_scanDir ); DESERIALIZE_THIS_MEMBER( v_, cfg_scanDirHist ); DESERIALIZE_THIS_MEMBER( v_, cfg_saveDir ); DESERIALIZE_THIS_MEMBER( v_, cfg_ctrlPanButton ); DESERIALIZE_THIS_MEMBER( v_, cfg_dispAutoFit ); DESERIALIZE_THIS_MEMBER( v_, cfg_imsConfig ); // remove empty or unreachable directories for (auto it=cfg_scanDirHist.begin(); it != cfg_scanDirHist.end();) { if ( it->empty() || !FU_DirectoryExists( *it ) ) it = cfg_scanDirHist.erase( it ); else ++it; } } //================================================================== bool XCConfig::AddScanDirToHistory() { auto &v = cfg_scanDirHist; if ( !cfg_scanDir.empty() && v.end() == std::find( v.begin(), v.end(), cfg_scanDir ) ) { // erase the oldest, if there are too many entries if ( v.size() >= 10 ) v.erase( v.begin() ); // append the new one v.push_back( cfg_scanDir ); return true; } return false; }
33.5625
71
0.533985
gugenstudio
a5341057111530e24eeb851aa8f9fe420ae62ddd
16,339
cpp
C++
libcsvsqldb/sql_lexer.cpp
fuersten/csvsqldb
1b766ddf253805e31f9840cd3081cba559018a06
[ "BSD-3-Clause" ]
5
2015-09-10T08:53:41.000Z
2020-05-30T18:42:20.000Z
libcsvsqldb/sql_lexer.cpp
fuersten/csvsqldb
1b766ddf253805e31f9840cd3081cba559018a06
[ "BSD-3-Clause" ]
20
2015-09-29T16:16:07.000Z
2021-06-13T08:08:05.000Z
libcsvsqldb/sql_lexer.cpp
fuersten/csvsqldb
1b766ddf253805e31f9840cd3081cba559018a06
[ "BSD-3-Clause" ]
3
2015-09-09T22:51:44.000Z
2020-11-11T13:19:42.000Z
// // sql_lexer.h // csv db // // BSD 3-Clause License // Copyright (c) 2015, Lars-Christian Fรผrstenberg // 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. // #include "sql_lexer.h" #include "base/logging.h" #include "base/string_helper.h" namespace csvsqldb { std::string tokenToString(eToken token) { switch(static_cast<csvsqldb::lexer::eToken>(token)) { case csvsqldb::lexer::UNDEFINED: return "UNDEFINED"; case csvsqldb::lexer::NEWLINE: return "NEWLINE"; case csvsqldb::lexer::WHITESPACE: return "WHITESPACE"; case csvsqldb::lexer::EOI: return "EOI"; } switch(token) { case TOK_NONE: return "TOK_NONE"; case TOK_IDENTIFIER: return "identifier"; case TOK_QUOTED_IDENTIFIER: return "quoted identifier"; case TOK_CONST_STRING: return "string constant"; case TOK_CONST_INTEGER: return "integer constant"; case TOK_CONST_BOOLEAN: return "boolean constant"; case TOK_CONST_DATE: return "date constant"; case TOK_CONST_REAL: return "real constant"; case TOK_CONST_CHAR: return "char constant"; case TOK_DOT: return "."; case TOK_DESCRIBE: return "DESCRIBE"; case TOK_AST: return "AST"; case TOK_SMALLER: return "<"; case TOK_GREATER: return ">"; case TOK_EQUAL: return "="; case TOK_NOTEQUAL: return "<>"; case TOK_GREATEREQUAL: return ">="; case TOK_SMALLEREQUAL: return "<="; case TOK_CONCAT: return "||"; case TOK_ADD: return "+"; case TOK_SUB: return "-"; case TOK_DIV: return "/"; case TOK_MOD: return "%"; case TOK_ASTERISK: return "*"; case TOK_COMMA: return ","; case TOK_SEMICOLON: return ";"; case TOK_LEFT_PAREN: return "("; case TOK_RIGHT_PAREN: return ")"; case TOK_COMMENT: return "comment"; case TOK_UNION: return "UNION"; case TOK_INTERSECT: return "INTERSECT"; case TOK_EXCEPT: return "EXCEPT"; case TOK_SELECT: return "SELECT"; case TOK_AS: return "AS"; case TOK_ALL: return "ALL"; case TOK_CAST: return "CAST"; case TOK_DISTINCT: return "DISTINCT"; case TOK_FROM: return "FROM"; case TOK_WHERE: return "WHERE"; case TOK_ON: return "ON"; case TOK_USING: return "USING"; case TOK_NATURAL: return "NATURAL"; case TOK_LEFT: return "LEFT"; case TOK_RIGHT: return "RIGHT"; case TOK_INNER: return "INNER"; case TOK_OUTER: return "OUTER"; case TOK_CROSS: return "CROSS"; case TOK_FULL: return "FULL"; case TOK_JOIN: return "JOIN"; case TOK_LIKE: return "LIKE"; case TOK_AND: return "AND"; case TOK_OR: return "OR"; case TOK_NOT: return "NOT"; case TOK_IS: return "IS"; case TOK_NULL: return "NULL"; case TOK_BETWEEN: return "BETWEEN"; case TOK_IN: return "IN"; case TOK_EXISTS: return "EXISTS"; case TOK_GROUP: return "GROUP"; case TOK_ORDER: return "ORDER"; case TOK_BY: return "BY"; case TOK_COLLATE: return "COLLATE"; case TOK_ASC: return "ASC"; case TOK_DESC: return "DESC"; case TOK_HAVING: return "HAVING"; case TOK_LIMIT: return "LIMIT"; case TOK_OFFSET: return "OFFSET"; case TOK_CREATE: return "CREATE"; case TOK_TABLE: return "TABLE"; case TOK_IF: return "IF"; case TOK_CONSTRAINT: return "CONSTRAINT"; case TOK_PRIMARY: return "PRIMARY"; case TOK_KEY: return "KEY"; case TOK_UNIQUE: return "UNIQUE"; case TOK_DEFAULT: return "DEFAULT"; case TOK_CHECK: return "CHECK"; case TOK_BOOL: return "BOOLEAN"; case TOK_INT: return "INTEGER"; case TOK_REAL: return "REAL"; case TOK_STRING: return "STRING"; case TOK_CHAR: return "CHARACTER"; case TOK_DATE: return "DATE"; case TOK_TIME: return "TIME"; case TOK_TIMESTAMP: return "TIMESTAMP"; case TOK_ALTER: return "ALTER"; case TOK_COLUMN: return "COLUMN"; case TOK_DROP: return "DROP"; case TOK_ADD_KEYWORD: return "ADD"; case TOK_SUM: return "SUM"; case TOK_COUNT: return "COUNT"; case TOK_AVG: return "AVG"; case TOK_MAX: return "MAX"; case TOK_MIN: return "MIN"; case TOK_CURRENT_DATE: return "CURRENT_DATE"; case TOK_CURRENT_TIME: return "CURRENT_TIME"; case TOK_CURRENT_TIMESTAMP: return "CURRENT_TIMESTAMP"; case TOK_VARYING: return "VARYING"; case TOK_EXTRACT: return "EXTRACT"; case TOK_SECOND: return "SECOND"; case TOK_MINUTE: return "MINUTE"; case TOK_HOUR: return "HOUR"; case TOK_YEAR: return "YEAR"; case TOK_MONTH: return "MONTH"; case TOK_DAY: return "DAY"; case TOK_EXPLAIN: return "EXPLAIN"; case TOK_SHOW: return "SHOW"; case TOK_MAPPING: return "MAPPING"; case TOK_EXEC: return "EXEC"; case TOK_ARBITRARY: return "ARBITRARY"; } throw std::runtime_error("just to make VC2013 happy"); } SQLLexer::SQLLexer(const std::string& input) : _lexer(std::bind(&SQLLexer::inspectToken, this, std::placeholders::_1)) { initDefinitions(); initKeywords(); _lexer.setInput(input); } void SQLLexer::setInput(const std::string& input) { _lexer.setInput(input); } void SQLLexer::initDefinitions() { _lexer.addDefinition("bool", R"([tT][rR][uU][eE])", TOK_CONST_BOOLEAN); _lexer.addDefinition("bool", R"([fF][aA][lL][sS][eE])", TOK_CONST_BOOLEAN); _lexer.addDefinition("bool", R"([uU][nN][kK][nN][oO][wW][nN])", TOK_CONST_BOOLEAN); _lexer.addDefinition("identifier", R"([_a-zA-Z][_a-zA-Z0-9]*)", TOK_IDENTIFIER); _lexer.addDefinition("quoted identifier", R"(\"([^\"]*)\")", TOK_QUOTED_IDENTIFIER); _lexer.addDefinition("char", R"('([^'])')", TOK_CONST_CHAR); _lexer.addDefinition("string", R"('([^']*)')", TOK_CONST_STRING); _lexer.addDefinition("concat", R"(\|\|)", TOK_CONCAT); _lexer.addDefinition("add", R"(\+)", TOK_ADD); _lexer.addDefinition("comment", R"(--([^\r\n]*))", TOK_COMMENT); _lexer.addDefinition("sub", R"(-)", TOK_SUB); _lexer.addDefinition("point", R"(\.)", TOK_DOT); _lexer.addDefinition("real", R"((?:0|[1-9]\d*)\.\d+)", TOK_CONST_REAL); _lexer.addDefinition("integer", R"(0|[1-9]\d*)", TOK_CONST_INTEGER); _lexer.addDefinition("string", R"('([^']*)')", TOK_CONST_STRING); _lexer.addDefinition("equal", R"(=)", TOK_EQUAL); _lexer.addDefinition("greater equal", R"(>=)", TOK_GREATEREQUAL); _lexer.addDefinition("smaller equal", R"(<=)", TOK_SMALLEREQUAL); _lexer.addDefinition("notequal", R"(<>)", TOK_NOTEQUAL); _lexer.addDefinition("smaller", R"(<)", TOK_SMALLER); _lexer.addDefinition("greater", R"(>)", TOK_GREATER); _lexer.addDefinition("comma", R"(,)", TOK_COMMA); _lexer.addDefinition("semicolon", R"(;)", TOK_SEMICOLON); _lexer.addDefinition("asterisk", R"(\*)", TOK_ASTERISK); _lexer.addDefinition("left_paren", R"(\()", TOK_LEFT_PAREN); _lexer.addDefinition("right_paren", R"(\))", TOK_RIGHT_PAREN); _lexer.addDefinition("comment", R"(/\*((.|[\r\n])*?)\*/)", TOK_COMMENT); _lexer.addDefinition("div", R"(/)", TOK_DIV); _lexer.addDefinition("mod", R"(%)", TOK_MOD); } void SQLLexer::initKeywords() { _keywords["UNION"] = eToken(TOK_UNION); _keywords["SELECT"] = eToken(TOK_SELECT); _keywords["FROM"] = eToken(TOK_FROM); _keywords["WHERE"] = eToken(TOK_WHERE); _keywords["USING"] = eToken(TOK_USING); _keywords["INTERSECT"] = eToken(TOK_INTERSECT); _keywords["EXCEPT"] = eToken(TOK_EXCEPT); _keywords["AS"] = eToken(TOK_AS); _keywords["ALL"] = eToken(TOK_ALL); _keywords["CAST"] = eToken(TOK_CAST); _keywords["DISTINCT"] = eToken(TOK_DISTINCT); _keywords["ON"] = eToken(TOK_ON); _keywords["NATURAL"] = eToken(TOK_NATURAL); _keywords["LEFT"] = eToken(TOK_LEFT); _keywords["RIGHT"] = eToken(TOK_RIGHT); _keywords["INNER"] = eToken(TOK_INNER); _keywords["OUTER"] = eToken(TOK_OUTER); _keywords["CROSS"] = eToken(TOK_CROSS); _keywords["FULL"] = eToken(TOK_FULL); _keywords["JOIN"] = eToken(TOK_JOIN); _keywords["LIKE"] = eToken(TOK_LIKE); _keywords["AND"] = eToken(TOK_AND); _keywords["OR"] = eToken(TOK_OR); _keywords["NOT"] = eToken(TOK_NOT); _keywords["IS"] = eToken(TOK_IS); _keywords["NULL"] = eToken(TOK_NULL); _keywords["BETWEEN"] = eToken(TOK_BETWEEN); _keywords["IN"] = eToken(TOK_IN); _keywords["EXISTS"] = eToken(TOK_EXISTS); _keywords["GROUP"] = eToken(TOK_GROUP); _keywords["ORDER"] = eToken(TOK_ORDER); _keywords["BY"] = eToken(TOK_BY); _keywords["COLLATE"] = eToken(TOK_COLLATE); _keywords["ASC"] = eToken(TOK_ASC); _keywords["DESC"] = eToken(TOK_DESC); _keywords["HAVING"] = eToken(TOK_HAVING); _keywords["LIMIT"] = eToken(TOK_LIMIT); _keywords["OFFSET"] = eToken(TOK_OFFSET); _keywords["CREATE"] = eToken(TOK_CREATE); _keywords["TABLE"] = eToken(TOK_TABLE); _keywords["IF"] = eToken(TOK_IF); _keywords["BOOLEAN"] = eToken(TOK_BOOL); _keywords["BOOL"] = eToken(TOK_BOOL); _keywords["INT"] = eToken(TOK_INT); _keywords["INTEGER"] = eToken(TOK_INT); _keywords["REAL"] = eToken(TOK_REAL); _keywords["FLOAT"] = eToken(TOK_REAL); _keywords["DOUBLE"] = eToken(TOK_REAL); _keywords["VARCHAR"] = eToken(TOK_STRING); _keywords["CHAR"] = eToken(TOK_CHAR); _keywords["CHARACTER"] = eToken(TOK_CHAR); _keywords["DATE"] = eToken(TOK_DATE); _keywords["TIME"] = eToken(TOK_TIME); _keywords["TIMESTAMP"] = eToken(TOK_TIMESTAMP); _keywords["CONSTRAINT"] = eToken(TOK_CONSTRAINT); _keywords["PRIMARY"] = eToken(TOK_PRIMARY); _keywords["KEY"] = eToken(TOK_KEY); _keywords["UNIQUE"] = eToken(TOK_UNIQUE); _keywords["DEFAULT"] = eToken(TOK_DEFAULT); _keywords["CHECK"] = eToken(TOK_CHECK); _keywords["ALTER"] = eToken(TOK_ALTER); _keywords["COLUMN"] = eToken(TOK_COLUMN); _keywords["DROP"] = eToken(TOK_DROP); _keywords["ADD"] = eToken(TOK_ADD_KEYWORD); _keywords["SUM"] = eToken(TOK_SUM); _keywords["COUNT"] = eToken(TOK_COUNT); _keywords["AVG"] = eToken(TOK_AVG); _keywords["MAX"] = eToken(TOK_MAX); _keywords["MIN"] = eToken(TOK_MIN); _keywords["CURRENT_DATE"] = eToken(TOK_CURRENT_DATE); _keywords["CURRENT_TIME"] = eToken(TOK_CURRENT_TIME); _keywords["CURRENT_TIMESTAMP"] = eToken(TOK_CURRENT_TIMESTAMP); _keywords["VARYING"] = eToken(TOK_VARYING); _keywords["DESCRIBE"] = eToken(TOK_DESCRIBE); _keywords["AST"] = eToken(TOK_AST); _keywords["EXTRACT"] = eToken(TOK_EXTRACT); _keywords["SECOND"] = eToken(TOK_SECOND); _keywords["MINUTE"] = eToken(TOK_MINUTE); _keywords["HOUR"] = eToken(TOK_HOUR); _keywords["YEAR"] = eToken(TOK_YEAR); _keywords["MONTH"] = eToken(TOK_MONTH); _keywords["DAY"] = eToken(TOK_DAY); _keywords["EXPLAIN"] = eToken(TOK_EXPLAIN); _keywords["SHOW"] = eToken(TOK_SHOW); _keywords["MAPPING"] = eToken(TOK_MAPPING); _keywords["EXEC"] = eToken(TOK_EXEC); _keywords["ARBITRARY"] = eToken(TOK_ARBITRARY); } void SQLLexer::inspectToken(csvsqldb::lexer::Token& token) { CSVSQLDB_CLASSLOG(SQLLexer, 2, "Intercepted : " << token._value); if(token._token == TOK_IDENTIFIER) { Keywords::const_iterator iter = _keywords.find(csvsqldb::toupper(token._value)); if(iter != _keywords.end()) { token._token = iter->second; CSVSQLDB_CLASSLOG(SQLLexer, 2, "Intercepted : adapted token"); } } } csvsqldb::lexer::Token SQLLexer::next() { csvsqldb::lexer::Token tok = _lexer.next(); while(tok._token == TOK_COMMENT) { tok = _lexer.next(); } return tok; } }
37.134091
98
0.53461
fuersten
a536ed610414892db435e13ee5d94da23e0df509
3,828
hpp
C++
rosidl_typesupport_introspection_tests/include/rosidl_typesupport_introspection_tests/libraries.hpp
tsungchent/rosidl
caef9b8f820dfcb16e6a2df9118c5669cc816642
[ "Apache-2.0" ]
1
2022-02-28T21:29:46.000Z
2022-02-28T21:29:46.000Z
rosidl_typesupport_introspection_tests/include/rosidl_typesupport_introspection_tests/libraries.hpp
tsungchent/rosidl
caef9b8f820dfcb16e6a2df9118c5669cc816642
[ "Apache-2.0" ]
null
null
null
rosidl_typesupport_introspection_tests/include/rosidl_typesupport_introspection_tests/libraries.hpp
tsungchent/rosidl
caef9b8f820dfcb16e6a2df9118c5669cc816642
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 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. #ifndef ROSIDL_TYPESUPPORT_INTROSPECTION_TESTS__LIBRARIES_HPP_ #define ROSIDL_TYPESUPPORT_INTROSPECTION_TESTS__LIBRARIES_HPP_ #include <rcutils/macros.h> namespace rosidl_typesupport_introspection_tests { /// A literal type to hold message symbols. struct MessageTypeSupportSymbolRecord { const char * symbol; }; /// A literal type to hold service symbols. struct ServiceTypeSupportSymbolRecord { const char * symbol; const MessageTypeSupportSymbolRecord request; const MessageTypeSupportSymbolRecord response; }; /// A literal type to hold action symbols. struct ActionTypeSupportSymbolRecord { const char * symbol; const MessageTypeSupportSymbolRecord feedback; const MessageTypeSupportSymbolRecord feedback_message; const MessageTypeSupportSymbolRecord result; const MessageTypeSupportSymbolRecord goal; const ServiceTypeSupportSymbolRecord send_goal; const ServiceTypeSupportSymbolRecord get_result; }; /// Makes a MessageTypeSupportSymbolRecord literal for a message. #define MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, interface_type, message_name) \ {RCUTILS_STRINGIFY( \ ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME( \ typesupport_name, package_name, interface_type, message_name))} /// Makes a MessageTypeSupportSymbolRecord literal for a service. #define SERVICE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, interface_type, service_name) \ {RCUTILS_STRINGIFY( \ ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME( \ typesupport_name, package_name, interface_type, service_name)), \ MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, \ interface_type, RCUTILS_JOIN(service_name, _Request)), \ MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, \ interface_type, RCUTILS_JOIN(service_name, _Response))} /// Makes a MessageTypeSupportSymbolRecord literal for an action. #define ACTION_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, interface_type, action_name) \ {RCUTILS_STRINGIFY( \ ROSIDL_TYPESUPPORT_INTERFACE__ACTION_SYMBOL_NAME( \ typesupport_name, package_name, interface_type, action_name)), \ MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, \ interface_type, RCUTILS_JOIN(action_name, _Feedback)), \ MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, \ interface_type, RCUTILS_JOIN(action_name, _FeedbackMessage)), \ MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, \ interface_type, RCUTILS_JOIN(action_name, _Result)), \ MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, \ interface_type, RCUTILS_JOIN(action_name, _Goal)), \ SERVICE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, \ interface_type, RCUTILS_JOIN(action_name, _SendGoal)), \ SERVICE_TYPESUPPORT_SYMBOL_RECORD( \ typesupport_name, package_name, \ interface_type, RCUTILS_JOIN(action_name, _GetResult))} } // namespace rosidl_typesupport_introspection_tests #endif // ROSIDL_TYPESUPPORT_INTROSPECTION_TESTS__LIBRARIES_HPP_
39.463918
75
0.785005
tsungchent
a536f2d5e320c70a40fa940527f46bc4c9407327
10,256
cpp
C++
11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp
EatAllBugs/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
14
2021-09-01T14:25:45.000Z
2022-02-21T08:49:57.000Z
11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
null
null
null
11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
3
2021-10-10T00:58:29.000Z
2022-01-23T13:16:09.000Z
/******************************************************** Stanford Driving Software Copyright (c) 2011 Stanford University 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. * The names of the contributors may not 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 <iostream> #include <global.h> #include <textureCache.h> #include <imageryServer.h> #include <imagery_proj.h> namespace vlr { TextureCache::TextureCache(const std::string& imagery_root, uint64_t max_images) : comp_refs_(image_), version_num_(0), max_images_(max_images), imagery_root_(imagery_root), last_grayscale_(false), current_reference_(0), stop_thread_(false) { for (uint64_t i = 0; i < max_images_; i++) { image_.push_back(new TimedImage); } pthread_create(&loader_thread_id_, NULL, threadCBWrapper<TextureCache, &TextureCache::loaderThread>, this); } TextureCache::~TextureCache() { stop_thread_ = true; pthread_join(loader_thread_id_, NULL); for (uint64_t i = 0; i < max_images_; i++) { delete image_[i]; } } bool TextureCache::sameId(TileId& id1, TileId& id2) { if (id1.type != id2.type) return false; if (id1.x != id2.x) return false; if (id1.y != id2.y) return false; if (id1.res != id2.res) return false; if (id1.zone != id2.zone) return false; return true; } uint64_t TextureCache::lookup(TileId id) { /* locate image in cache */ bool found = false; uint64_t which = 0; for (uint64_t i = 0; i < max_images_; i++) { if (image_[i]->state != UNINITIALIZED && sameId(image_[i]->id, id)) { which = i; found = true; break; } } if (found) { // image is in cache image_[which]->last_reference = current_reference_; current_reference_++; return which; } // image is not in cache // find unused or oldest used image; TODO: optimize search for (uint64_t i = 0; i < max_images_; i++) { if (image_[i]->state == UNINITIALIZED) { found = true; which = i; break; } else if (image_[i]->state == READY && (!found || (found && image_[i]->last_reference < image_[which]->last_reference))) { found = true; which = i; } } if (found) { if (image_[which]->state == READY) { if (image_[which]->image != NULL) { delete image_[which]->image; image_[which]->image = NULL; } } image_[which]->exists = true; image_[which]->last_reference = current_reference_; image_[which]->id = id; image_[which]->state = REQUESTED; current_reference_++; return which; } else { throw VLRException("Image list has no empty spots. This shouldn't happen."); } } void TextureCache::resetCounters() { static std::vector<int64_t> id; if (id.size() != max_images_) { id.resize(max_images_); } for (uint64_t i = 0; i < max_images_; i++) {id[i] = i;} sort(id.begin(), id.end(), comp_refs_); for (uint64_t i = 0; i < max_images_; i++) { image_[id[i]]->last_reference = i; } current_reference_ = max_images_ + 1; } void TextureCache::syncTexture(uint64_t i) { TimedImage& image = *image_[i]; if (image.state == READY && image.needs_sync) { image.needs_sync = false; if (image.image == NULL) return; image.texture.updateFromImage(*image.image); delete image.image; image.image = NULL; } } bool TextureCache::syncCache() { static int32_t count = 0; if (count > 10) { // ?!? resetCounters(); count = 0; } count++; bool needs_sync = false; for (uint64_t i = 0; i < max_images_; i++) if (image_[i]->needs_sync) { needs_sync = true; break; } if (needs_sync) { for (uint64_t i = 0; i < max_images_; i++) { if (image_[i]->needs_sync) { syncTexture(i); } } return true; } return false; } Texture* TextureCache::get(const std::string& detected_subdir, TileId& id, int priority, ImageState_t& state) { // std:: cout << "detected_subdir: " << detected_subdir << std::endl; // std:: cout << "imagery_root_: " << imagery_root_ << std::endl; // std:: cout << "Requested tile id with type " << id.type << "; x, y: " << id.x << ", " << id.y << "; res: " << id.res << "; zone: "<< id.zone << std::endl; if(!detected_subdir.empty() && detected_subdir_ != detected_subdir) { detected_subdir_ = detected_subdir; } uint64_t i = 0; try { i = lookup(id); } catch(vlr::Ex<>& e) { std::cout << e.what() << std::endl; state = UNINITIALIZED; return NULL; } if (priority && image_[i]->state == READY) {syncTexture(i);} image_[i]->last_reference = current_reference_; current_reference_++; if (image_[i]->state != UNINITIALIZED && image_[i]->exists) { state = image_[i]->state; last_grayscale_ = image_[i]->grayscale; return &image_[i]->texture; } state = UNINITIALIZED; return NULL; } size_t curl_callback(void* ptr, size_t size, size_t nmemb, void* data) { std::vector<uint8_t>* mem = static_cast<std::vector<uint8_t>*>(data); size_t realsize = size * nmemb; mem->resize(mem->size() + realsize + 1); // +1 to have a final zero element memcpy(&((*mem)[mem->size()]), ptr, realsize); return realsize; } void* TextureCache::loaderThread() { char server_name[200], filename[200], whole_filename[200]; int server_port; char *mark, *mark2; #ifdef HAVE_LIBCURL CURLcode curl_return; /* init the curl session */ curl_global_init(CURL_GLOBAL_ALL); CURL* curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, curl_callback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&curl_buf_); curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 1); curl_easy_setopt(curl_handle, CURLOPT_FAILONERROR, 1); curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1); #endif sleep(1); // ?!? while (!stop_thread_) { for (uint64_t i = 0; i < max_images_; i++) { if (image_[i]->state == REQUESTED) { if (version_num_ != 2) { if (image_[i]->id.type == Imagery::COLOR) dgc_terra_color_tile_filename(image_[i]->id, filename, version_num_); else if (image_[i]->id.type == Imagery::TOPO) dgc_terra_topo_tile_filename(image_[i]->id, filename, version_num_); else if (image_[i]->id.type == Imagery::LASER) dgc_laser_tile_filename(image_[i]->id, filename, version_num_); else if (image_[i]->id.type == Imagery::GSAT) dgc_gmaps_tile_filename(image_[i]->id, filename); else if (image_[i]->id.type == Imagery::DARPA) dgc_darpa_tile_filename(image_[i]->id, filename, version_num_); else if (image_[i]->id.type == Imagery::BW) dgc_terra_bw_tile_filename(image_[i]->id, filename); if (version_num_ == 0) { sprintf(whole_filename, "%s/%s/%s", imagery_root_.c_str(), detected_subdir_.c_str(), filename); } else if (version_num_ == 1) { sprintf(whole_filename, "%s/%s", imagery_root_.c_str(), filename); } } switch (version_num_) { case 0: if (dgc::dgc_file_exists(whole_filename)) { image_[i]->image = new cv::Mat; *image_[i]->image = cv::imread(whole_filename, CV_LOAD_IMAGE_ANYCOLOR); } else { image_[i]->image = NULL; } break; case 1: #ifdef HAVE_LIBCURL /* handle http queries with libcurl */ curl_easy_setopt(curl_handle, CURLOPT_URL, whole_filename); curl_return = curl_easy_perform(curl_handle); if(stop_thread_) {return NULL;} // ?!? if(curl_return == 0) { image_[i]->image = cv::imdecode(cv::Mat(curl_buf_, false), CV_LOAD_IMAGE_ANYCOLOR); } curl_buf_.clear(); #else image_[i]->image = new cv::Mat; *image_[i]->image = cv::imread(whole_filename, CV_LOAD_IMAGE_ANYCOLOR); #endif break; case 2: strcpy(server_name, imagery_root_.c_str() + 6); if ((mark = strchr(server_name, ':')) != NULL) { server_port = strtol(mark + 1, &mark2, 10); *mark = '\0'; } else { server_port = 3000; if ((mark = strchr(server_name, '/')) != NULL) *mark = '\0'; } image_[i]->image = img_server_.getImage(server_name, server_port, image_[i]->id); break; } if (!image_[i]->image) { image_[i]->exists = false; } else { image_[i]->grayscale = (image_[i]->image->channels() == 1); } image_[i]->needs_sync = true; image_[i]->state = READY; } } usleep(10000); } return NULL; } } // namespace vlr
30.984894
158
0.621002
EatAllBugs
a537453ebe8afbcecef93c2edf6967138dd7c11d
1,899
hxx
C++
session/KAutoLogon.hxx
Peter2121/kts
fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a
[ "BSD-3-Clause" ]
null
null
null
session/KAutoLogon.hxx
Peter2121/kts
fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a
[ "BSD-3-Clause" ]
null
null
null
session/KAutoLogon.hxx
Peter2121/kts
fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <algorithm> #include "..\shared\KTrace.hxx" #include "..\shared\Kini.hxx" #include "..\shared\KSlre.hxx" class KAutoLogon { private: /*============================================================================== * var *=============================================================================*/ struct Pattern { std::string address; std::string username; std::string password; std::string domain; }; std::vector < Pattern > patterns; public: /*============================================================================== * load from file *=============================================================================*/ void Load( std::string file ) { ktrace_in( ); ktrace( "KAutoLogon::Load( " << file << " )" ); KIni ini; ini.File( file ); for( unsigned i = 0; i < 1024; i++ ) { Pattern p; std::stringstream s; s << "address" << i; if( !ini.GetKey( "KAutoLogon", s.str( ), p.address, "eof" ) ) break; s.str( "" ); s << "username" << i; ini.GetKey( "KAutoLogon", s.str( ), p.username ); s.str( "" ); s << "password" << i; ini.GetKey( "KAutoLogon", s.str( ), p.password ); s.str( "" ); s << "domain" << i; ini.GetKey( "KAutoLogon", s.str( ), p.domain ); this->patterns.push_back( p ); } } bool GetAutoCredentials( const std::string& ipaddress, std::string& username, std::string& password, std::string& domain ) { ktrace_in( ); ktrace( "KAutoLogon::GetAutoCredentials( " << ipaddress << ", <out> )" ); for( unsigned i = 0; i < this->patterns.size( ); i++ ) { KSlre kslre; if(kslre.Match(ipaddress, patterns[i].address)) { username = patterns[i].username; password = patterns[i].password; domain = patterns[i].domain; return true; } } return false; } };
23.7375
124
0.460242
Peter2121
a539d799a6c38157168ce01558691874c43f1187
1,216
cpp
C++
src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp
Armanimani/Game-Engine
8087cd999f7264488d24a5dc5571b659347a49dd
[ "MIT" ]
null
null
null
src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp
Armanimani/Game-Engine
8087cd999f7264488d24a5dc5571b659347a49dd
[ "MIT" ]
1
2017-04-05T01:40:02.000Z
2017-04-05T07:36:55.000Z
src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp
Armanimani/Game-Engine
8087cd999f7264488d24a5dc5571b659347a49dd
[ "MIT" ]
null
null
null
#include "SingnedDistanceOutlineTextShader.h" void SignedDistanceOutlineTextShader::loadAllToUniform(const std::shared_ptr<GUITextModel> model) { SignedDistanceTextShader::loadAllToUniform(model); loadToUniform(location_outlineColor, model->getMaterial()->getProperties().color2); loadToUniform(location_outlineWidth, model->getMaterial()->getProperties().fontOutlineWidth); loadToUniform(location_outlineEdge, model->getMaterial()->getProperties().fontOutlineEdge); loadToUniform(location_outlineOffsetX, model->getMaterial()->getProperties().fontOutlineOffsetX); loadToUniform(location_outlineOffsetY, model->getMaterial()->getProperties().fontOutlineOffsetY); } void SignedDistanceOutlineTextShader::getAllUniformLocations() { SignedDistanceTextShader::getAllUniformLocations(); std::string temp; temp = "matOutlineColor"; location_outlineColor = getUniformLocation(temp); temp = "matOutlineWidth"; location_outlineWidth = getUniformLocation(temp); temp = "matOutlineEdge"; location_outlineEdge = getUniformLocation(temp); temp = "matOutlineOffsetX"; location_outlineOffsetX = getUniformLocation(temp); temp = "matOutlineOffsetY"; location_outlineOffsetY = getUniformLocation(temp); }
34.742857
98
0.817434
Armanimani
a53a645d257e0e8c8f80c93d96c20b152697713a
4,263
hpp
C++
src/graph/include/graph/breadth_first_search.hpp
SkyterX/rpclass
5e80ec4e0b876eb498351bcf7d6f5983fe5c7934
[ "Apache-2.0" ]
null
null
null
src/graph/include/graph/breadth_first_search.hpp
SkyterX/rpclass
5e80ec4e0b876eb498351bcf7d6f5983fe5c7934
[ "Apache-2.0" ]
null
null
null
src/graph/include/graph/breadth_first_search.hpp
SkyterX/rpclass
5e80ec4e0b876eb498351bcf7d6f5983fe5c7934
[ "Apache-2.0" ]
null
null
null
#pragma once #include <queue> #include <graph/graph.hpp> #include <graph/properties.hpp> #include <graph/static_graph.hpp> namespace graph { template <typename ColorMapTag, typename V, typename E> struct GenerateBFSGraph {}; template <typename ColorMapTag, typename... P1s, typename... P2s> struct GenerateBFSGraph<ColorMapTag, Properties<P1s...>, Properties<P2s...>> { using type = StaticGraph<Properties<Property<ColorMapTag, char>, P1s...>, Properties<P2s...>>; }; template <typename Graph, typename ColorMap> struct DefaultBFSVisitor { //is invoked on every vertex before the start of the search. void initialize_vertex(const typename graph_traits<Graph>::vertex_descriptor& v, Graph&) { graph::put(color, v, typename property_traits<ColorMap>::value_type(0)); }; // is invoked in each vertex as it is removed from the queue. void examine_vertex(const typename graph_traits<Graph>::vertex_descriptor&, Graph&) {}; //is invoked on every out - edge of each vertex immediately after the vertex // is removed from the queue. void examine_edge(const typename graph_traits<Graph>::edge_descriptor&, Graph& g) {}; // is invoked(in addition to examine_edge()) if the edge is a tree edge. // The target vertex of edge e is discovered at this time. void tree_edge(const typename graph_traits<Graph>::edge_descriptor&, Graph& g) {}; // is invoked the first time the algorithm encounters vertex u. // All vertices closer to the source vertex have been discovered, // and vertices further from the source have not yet been discovered. void discover_vertex(const typename graph_traits<Graph>::vertex_descriptor&, Graph&) {}; //is invoked(in addition to examine_edge()) if the edge is not a tree edge. void non_tree_edge(const typename graph_traits<Graph>::edge_descriptor&, Graph&) {}; // is invoked(in addition to non_tree_edge()) if the target vertex is colored // gray at the time of examination.The color gray indicates that the vertex // is currently in the queue. void gray_target(const typename graph_traits<Graph>::edge_descriptor&, Graph&) {}; // is invoked(in addition to non_tree_edge()) if the target vertex is colored // black at the time of examination.The color black indicates that the vertex // is no longer in the queue. void black_target(const typename graph_traits<Graph>::edge_descriptor&, Graph&) {}; // is invoked after all of the out edges of u have been examined and all of // the adjacent vertices have been discovered. void finish_vertex(const typename graph_traits<Graph>::vertex_descriptor&, Graph&) {}; DefaultBFSVisitor(ColorMap& color) :color(color) {}; DefaultBFSVisitor(ColorMap&& color) :color(color) {}; ColorMap color; }; template <class Graph, class ColorMap, class BFSVisitor = DefaultBFSVisitor<Graph, ColorMap>> void breadth_first_search(Graph& graph, const typename graph_traits<Graph>::vertex_descriptor& s, ColorMap& color, BFSVisitor visitor = BFSVisitor{}) { typename property_traits<ColorMap>::value_type white = 0; typename property_traits<ColorMap>::value_type grey = 1; typename property_traits<ColorMap>::value_type black = 2; if (graph::get(color, s) != white) return; std::queue<typename graph_traits<Graph>::vertex_descriptor> vQueue; auto vRange = vertices(graph); for (auto vIt = vRange.first; vIt != vRange.second; ++vIt) { visitor.initialize_vertex(*vIt, graph); } vQueue.push(s); while (!vQueue.empty()) { auto src = vQueue.front(); visitor.examine_vertex(src, graph); auto outRange = out_edges(src, graph); graph::put(color, src, black); for (auto outIt = outRange.first; outIt != outRange.second; ++outIt) { auto e = *outIt; auto tgt = target(e, graph); visitor.examine_edge(e, graph); if (graph::get(color, tgt) == white) { visitor.discover_vertex(tgt, graph); visitor.tree_edge(e, graph); graph::put(color, tgt, grey); vQueue.push(tgt); } else if (graph::get(color, tgt) == grey) visitor.gray_target(e, graph); else visitor.black_target(e, graph); }; visitor.finish_vertex(src, graph); vQueue.pop(); } }; }
36.435897
96
0.703964
SkyterX
a53bcff7875e40227554a2f5c083863f61245ec9
6,622
cpp
C++
test/unittest/step_tileset_test.cpp
albin-johansson/step
f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab
[ "MIT" ]
4
2020-06-05T11:56:11.000Z
2020-11-13T14:49:06.000Z
test/unittest/step_tileset_test.cpp
albin-johansson/step
f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab
[ "MIT" ]
8
2020-05-23T09:35:03.000Z
2020-06-20T22:15:02.000Z
test/unittest/step_tileset_test.cpp
albin-johansson/step
f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab
[ "MIT" ]
null
null
null
#include "step_tileset.hpp" #include <doctest.h> #include <string_view> #include "step_exception.hpp" #include "step_test_utils.h" using namespace step; inline static constexpr std::string_view prefix = "resource/tileset/"; TEST_SUITE("Tileset") { TEST_CASE("Parsing external tileset") { const auto tileset = tileset::external( prefix, 4_gid, "tileset_data_for_external_tileset.json"); CHECK(tileset->columns() == 32); CHECK(tileset->first_gid() == 4_gid); CHECK(tileset->source() == "tileset_data_for_external_tileset.json"); CHECK(tileset->image() == "../terrain.png"); CHECK(tileset->image_width() == 1024); CHECK(tileset->image_height() == 768); CHECK(tileset->margin() == 18); CHECK(tileset->name() == "external_tileset"); CHECK(tileset->spacing() == 7); CHECK(tileset->tile_count() == 1024); CHECK(tileset->tile_width() == 64); CHECK(tileset->tile_height() == 32); CHECK(tileset->json_version() == 1.2); CHECK(tileset->tiled_version() == "1.3.4"); CHECK(!tileset->get_grid()); CHECK(!tileset->get_tile_offset()); } TEST_CASE("Parsing embedded tileset") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/embedded_tileset.json")); CHECK(tileset->first_gid() == 7_gid); CHECK(tileset->columns() == 48); CHECK(tileset->source() == ""); CHECK(tileset->image() == "sam/is/the/hero.png"); CHECK(tileset->image_width() == 1270); CHECK(tileset->image_height() == 960); CHECK(tileset->margin() == 77); CHECK(tileset->name() == "embedded_tileset"); CHECK(tileset->tile_count() == 63); CHECK(tileset->spacing() == 82); CHECK(tileset->tile_width() == 55); CHECK(tileset->tile_height() == 27); CHECK(tileset->background_color() == color{"#12345678"}); CHECK(tileset->transparent_color() == color{"#CCDDEEFF"}); CHECK(tileset->json_version() == 1.2); CHECK(tileset->tiled_version() == "1.3.4"); SUBCASE("Parsing grid") { const auto grid = tileset->get_grid(); REQUIRE(grid); CHECK(grid->get_orientation() == grid::orientation::isometric); CHECK(grid->width() == 48); CHECK(grid->height() == 64); } SUBCASE("Parsing tile offset") { const auto tileOffset = tileset->get_tile_offset(); REQUIRE(tileOffset); CHECK(tileOffset->x() == 1574); CHECK(tileOffset->y() == 753); } SUBCASE("Parsing terrains") { const auto& terrains = tileset->terrains(); REQUIRE(terrains.size() == 3); const auto& firstTerrain = terrains.at(0); CHECK(firstTerrain.name() == "ground"); CHECK(firstTerrain.tile() == 4_lid); { REQUIRE(firstTerrain.get_properties()->amount() != 0); const auto property = firstTerrain.get_properties()->get("foo"); CHECK(property.name() == "foo"); REQUIRE(property.get_type() == property::type::boolean); CHECK(property.get<bool>()); } const auto& secondTerrain = terrains.at(1); CHECK(secondTerrain.name() == "chasm"); CHECK(secondTerrain.tile() == 12_lid); const auto& thirdTerrain = terrains.at(2); CHECK(thirdTerrain.name() == "cliff"); CHECK(thirdTerrain.tile() == 36_lid); } } TEST_CASE("Tileset with properties") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/with_properties.json")); const auto* properties = tileset->get_properties(); REQUIRE(properties); REQUIRE(properties->amount() == 2); const auto& firstProperty = properties->get("aFloat"); CHECK(firstProperty.name() == "aFloat"); CHECK(firstProperty.get_type() == property::type::floating); CHECK(firstProperty.get<float>() == 7.5f); const auto& secondProperty = properties->get("aString"); CHECK(secondProperty.name() == "aString"); CHECK(secondProperty.get_type() == property::type::string); CHECK(secondProperty.get<std::string>() == "Hello"); } TEST_CASE("Tileset with tiles") { SUBCASE("Check first tile") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/with_tiles.json")); const auto& tiles = tileset->tiles(); REQUIRE(tiles.size() == 2); const auto& tile = tiles.at(0); CHECK(tile.id() == 187_lid); SUBCASE("Animation") { const auto animation = tile.get_animation(); REQUIRE(animation); CHECK(animation->num_frames() == 3); const auto& frames = animation->frames(); for (int i = 0; i < 3; ++i) { CHECK(frames.at(i).duration() == 900); CHECK(frames.at(i).tile_id() == 187_lid + local_id{i}); } } SUBCASE("Properties") { const auto* properties = tile.get_properties(); REQUIRE(properties); REQUIRE(properties->amount() == 1); const auto& property = properties->get("name"); CHECK(property.name() == "name"); CHECK(property.get_type() == property::type::string); CHECK(property.get<std::string>() == "waterTile"); } } SUBCASE("Check second tile") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/with_tiles.json")); auto& tiles = tileset->tiles(); REQUIRE(tiles.size() == 2); const auto& tile = tiles.at(1); CHECK(tile.id() == 370_lid); SUBCASE("Properties") { const auto properties = tile.get_properties(); REQUIRE(properties->amount() == 2); const auto& firstProperty = properties->get("coolness"); CHECK(firstProperty.name() == "coolness"); REQUIRE(firstProperty.get_type() == property::type::integer); CHECK(firstProperty.get<int>() == 9000); const auto& secondProperty = properties->get("frodo"); CHECK(secondProperty.name() == "frodo"); REQUIRE(secondProperty.get_type() == property::type::string); CHECK(secondProperty.get<std::string>() == "sandTile"); } } } TEST_CASE("Embedded tileset without explicit first GID") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/embedded_tileset_no_gid.json")); CHECK(tileset->first_gid() == 1_gid); } TEST_CASE("Tileset missing type attribute") { CHECK_THROWS_WITH_AS(tileset::embedded(detail::parse_json( "resource/tileset/tileset_wrong_type.json")), "Tileset \"type\" must be \"tileset\"!", step_exception); } }
31.836538
77
0.609333
albin-johansson
a53d3078d6e68e6aca1bc30353ac37d5efc991bf
1,410
cpp
C++
sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The general purpose cross platform C/C++ framework // // S x A c c e l e r a t e // // Home: https://www.sxlib.de // License: Apache 2 // Authors: see src/AUTHORS // // --------------------------------------------------------------------------- #include <SxDemo4Parser.h> SxDemo4Parser::SxDemo4Parser () : SxParserBase (), SxDemo4Ast () { SX_TRACE (); ssize_t rootId = 0; push (rootId); } SxDemo4Parser::~SxDemo4Parser () { // empty } void SxDemo4Parser::push (ssize_t id) { SX_TRACE (); stack.append (id); } SxDemo4AstNode &SxDemo4Parser::pop () { SX_TRACE (); SX_CHECK (errors.getSize() > 0 || stack.getSize() > 0); ssize_t id = stack.last (); stack.removeLast (); return *(ast.begin(sx::Forward, id)); } SxDemo4AstNode &SxDemo4Parser::getCurrent () { SX_TRACE (); return *(ast.begin(sx::Forward, stack.last())); } SxDemo4AstNode &SxDemo4Parser::getParent () { SX_TRACE (); ssize_t i = stack.getSize()-2; if (i >= 0) return *(ast.begin(sx::Forward, stack(i))); else return *(ast.begin(sx::Forward, 0)); // top level } int SxDemo4Parser_parse (SxDemo4Parser *); // defined by LEX int SxDemo4Parser::parse () { return SxDemo4Parser_parse (this); // enter LEX }
21.363636
78
0.521986
ashtonmv
a53d6c0c94a22872150b79b2baf203f7c9f35780
2,582
hpp
C++
openbmc_modules/phosphor-ipmi-blobs/example/example.hpp
Eyerunmyden/HWMgmt-MegaRAC-OpenEdition
72b03e9fc6e2a13184f1c57b8045b616db9b0a6d
[ "Apache-2.0", "MIT" ]
14
2021-11-04T07:47:37.000Z
2022-03-21T10:10:30.000Z
openbmc_modules/phosphor-ipmi-blobs/example/example.hpp
Eyerunmyden/HWMgmt-MegaRAC-OpenEdition
72b03e9fc6e2a13184f1c57b8045b616db9b0a6d
[ "Apache-2.0", "MIT" ]
null
null
null
openbmc_modules/phosphor-ipmi-blobs/example/example.hpp
Eyerunmyden/HWMgmt-MegaRAC-OpenEdition
72b03e9fc6e2a13184f1c57b8045b616db9b0a6d
[ "Apache-2.0", "MIT" ]
6
2021-11-02T10:56:19.000Z
2022-03-06T11:58:20.000Z
#pragma once #include <blobs-ipmid/blobs.hpp> #include <memory> #include <string> #include <unordered_map> #include <vector> #ifdef __cplusplus extern "C" { #endif /** * This method must be declared as extern C for blob manager to lookup the * symbol. */ std::unique_ptr<blobs::GenericBlobInterface> createHandler(); #ifdef __cplusplus } #endif namespace blobs { constexpr int kBufferSize = 1024; struct ExampleBlob { ExampleBlob() = default; ExampleBlob(uint16_t id, uint16_t flags) : sessionId(id), flags(flags), state(StateFlags::open_read | StateFlags::open_write), length(0) { } /* The blob handler session id. */ uint16_t sessionId; /* The flags passed into open. */ uint16_t flags; /* The current state. */ uint16_t state; /* The buffer is a fixed size, but length represents the number of bytes * expected to be used contiguously from offset 0. */ uint32_t length; /* The staging buffer. */ uint8_t buffer[kBufferSize]; }; class ExampleBlobHandler : public GenericBlobInterface { public: /* We want everything explicitly default. */ ExampleBlobHandler() = default; ~ExampleBlobHandler() = default; ExampleBlobHandler(const ExampleBlobHandler&) = default; ExampleBlobHandler& operator=(const ExampleBlobHandler&) = default; ExampleBlobHandler(ExampleBlobHandler&&) = default; ExampleBlobHandler& operator=(ExampleBlobHandler&&) = default; bool canHandleBlob(const std::string& path) override; std::vector<std::string> getBlobIds() override; bool deleteBlob(const std::string& path) override; bool stat(const std::string& path, BlobMeta* meta) override; bool open(uint16_t session, uint16_t flags, const std::string& path) override; std::vector<uint8_t> read(uint16_t session, uint32_t offset, uint32_t requestedSize) override; bool write(uint16_t session, uint32_t offset, const std::vector<uint8_t>& data) override; bool writeMeta(uint16_t session, uint32_t offset, const std::vector<uint8_t>& data) override; bool commit(uint16_t session, const std::vector<uint8_t>& data) override; bool close(uint16_t session) override; bool stat(uint16_t session, BlobMeta* meta) override; bool expire(uint16_t session) override; constexpr static char supportedPath[] = "/dev/fake/command"; private: ExampleBlob* getSession(uint16_t id); std::unordered_map<uint16_t, ExampleBlob> sessions; }; } // namespace blobs
28.065217
77
0.691712
Eyerunmyden
a53da97f92c9b880a510e5ab6779e4f1cb5b9316
2,706
cc
C++
src/third_party/abseil-cpp/absl/base/internal/strerror_test.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
6
2020-02-12T20:46:41.000Z
2021-04-14T17:48:54.000Z
src/third_party/abseil-cpp/absl/base/internal/strerror_test.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
54
2020-06-23T17:34:04.000Z
2022-03-31T02:04:06.000Z
src/third_party/abseil-cpp/absl/base/internal/strerror_test.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
12
2020-07-14T23:59:57.000Z
2022-03-22T09:59:18.000Z
// Copyright 2020 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "absl/base/internal/strerror.h" #include <atomic> #include <cerrno> #include <cstdio> #include <cstring> #include <string> #include <thread> // NOLINT(build/c++11) #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/match.h" namespace { using ::testing::AnyOf; using ::testing::Eq; TEST(StrErrorTest, ValidErrorCode) { errno = ERANGE; EXPECT_THAT(absl::base_internal::StrError(EDOM), Eq(strerror(EDOM))); EXPECT_THAT(errno, Eq(ERANGE)); } TEST(StrErrorTest, InvalidErrorCode) { errno = ERANGE; EXPECT_THAT(absl::base_internal::StrError(-1), AnyOf(Eq("No error information"), Eq("Unknown error -1"))); EXPECT_THAT(errno, Eq(ERANGE)); } TEST(StrErrorTest, MultipleThreads) { // In this test, we will start up 2 threads and have each one call // StrError 1000 times, each time with a different errnum. We // expect that StrError(errnum) will return a string equal to the // one returned by strerror(errnum), if the code is known. Since // strerror is known to be thread-hostile, collect all the expected // strings up front. const int kNumCodes = 1000; std::vector<std::string> expected_strings(kNumCodes); for (int i = 0; i < kNumCodes; ++i) { expected_strings[i] = strerror(i); } std::atomic_int counter(0); auto thread_fun = [&]() { for (int i = 0; i < kNumCodes; ++i) { ++counter; errno = ERANGE; const std::string value = absl::base_internal::StrError(i); // Only the GNU implementation is guaranteed to provide the // string "Unknown error nnn". POSIX doesn't say anything. if (!absl::StartsWith(value, "Unknown error ")) { EXPECT_THAT(absl::base_internal::StrError(i), Eq(expected_strings[i])); } EXPECT_THAT(errno, Eq(ERANGE)); } }; const int kNumThreads = 100; std::vector<std::thread> threads; for (int i = 0; i < kNumThreads; ++i) { threads.push_back(std::thread(thread_fun)); } for (auto& thread : threads) { thread.join(); } EXPECT_THAT(counter, Eq(kNumThreads * kNumCodes)); } } // namespace
31.103448
79
0.684405
rhencke
a53ea9be9c6f82a33b219a687dcdb2d0d3cb7486
1,435
hh
C++
src/transform/vector/vector4.hh
CompaqDisc/libtransform
db9dcbc39cd7d3af904c1bc2131544c1908522e1
[ "MIT" ]
null
null
null
src/transform/vector/vector4.hh
CompaqDisc/libtransform
db9dcbc39cd7d3af904c1bc2131544c1908522e1
[ "MIT" ]
null
null
null
src/transform/vector/vector4.hh
CompaqDisc/libtransform
db9dcbc39cd7d3af904c1bc2131544c1908522e1
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "vector.hh" namespace transform { template <class T> class Vector4 : public Vector<4, T> { private: typedef Vector<4, T> super; public: Vector4() : super() {} // default construct Vector4(const T x, const T y, const T z, const T w); // member construct Vector4(const Vector4<T>& v) : super(v) {} // copy construct Vector4(const Vector<4, T>& v) : super(v) {} // copy construct from superclass template <class U> Vector4(const Vector4<U>& v) // convert construct { this->_v[0] = v[0]; this->_v[1] = v[1]; this->_v[2] = v[2]; this->_v[3] = v[3]; } template <class U> Vector4(const Vector<4, U>& v) // convert construct { this->_v[0] = v[0]; this->_v[1] = v[1]; this->_v[2] = v[2]; this->_v[3] = v[3]; } // members T& x = this->_v[0]; T& y = this->_v[1]; T& z = this->_v[2]; T& w = this->_v[3]; T& r = this->_v[0]; T& g = this->_v[1]; T& b = this->_v[2]; T& a = this->_v[3]; // utility Vector4<T>& set(const T x, const T y, const T z, const T w); }; } using transform::Vector4; template <class T> Vector4<T>::Vector4(T x, T y, T z, T w) { this->_v[0] = x; this->_v[1] = y; this->_v[2] = z; this->_v[3] = w; } template <class T> Vector4<T>& Vector4<T>::set(const T x, const T y, const T z, const T w) { this->_v[0] = x; this->_v[1] = y; this->_v[2] = z; this->_v[3] = w; return *this; }
19.133333
82
0.552613
CompaqDisc
a54038616b95c435f358914cdf01cdeeee72e878
22,450
cpp
C++
platform/mt6592/hardware/audio/aud_drv/AudioPlatformDevice.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
platform/mt6592/hardware/audio/aud_drv/AudioPlatformDevice.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
platform/mt6592/hardware/audio/aud_drv/AudioPlatformDevice.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
#include "AudioPlatformDevice.h" #include "AudioAnalogType.h" #include "audio_custom_exp.h" #define LOG_TAG "AudioPlatformDevice" #ifndef ANDROID_DEFAULT_CODE #include <cutils/xlog.h> #ifdef ALOGE #undef ALOGE #endif #ifdef ALOGW #undef ALOGW #endif ALOGI #undef ALOGI #ifdef ALOGD #undef ALOGD #endif #ifdef ALOGV #undef ALOGV #endif #define ALOGE XLOGE #define ALOGW XLOGW #define ALOGI XLOGI #define ALOGD XLOGD #define ALOGV XLOGV #else #include <utils/Log.h> #endif namespace android { status_t AudioPlatformDevice::InitCheck() { ALOGD("InitCheck"); return NO_ERROR; } AudioPlatformDevice::AudioPlatformDevice() { ALOGD("AudioPlatformDevice constructor"); mAudioAnalogReg = NULL; mAudioAnalogReg = AudioAnalogReg::getInstance(); if (!mAudioAnalogReg) { ALOGW("mAudioAnalogReg = %p", mAudioAnalogReg); } // init analog part. for (int i = 0; i < AudioAnalogType::DEVICE_MAX; i++) { memset((void *)&mBlockAttribute[i], 0, sizeof(AnalogBlockAttribute)); } for (int i = 0; i < AudioAnalogType::VOLUME_TYPE_MAX; i++) { memset((void *)&mVolumeAttribute[i], 0, sizeof(AnalogVolumeAttribute)); } mHpRightDcCalibration = mHpLeftDcCalibration = 0; } /** * a basic function for SetAnalogGain for different Volume Type * @param VoleumType value want to set to analog volume * @param volume function of analog gain , value between 0 ~ 255 * @return status_t */ status_t AudioPlatformDevice::SetAnalogGain(AudioAnalogType::VOLUME_TYPE VoleumType, int volume) { ALOGD("SetAnalogGain VOLUME_TYPE = %d volume = %d ", VoleumType, volume); return NO_ERROR; } /** * a basic function fo SetAnalogMute, if provide mute function of hardware. * @param VoleumType value want to set to analog volume * @param mute of volume type * @return status_t */ status_t AudioPlatformDevice::SetAnalogMute(AudioAnalogType::VOLUME_TYPE VoleumType, bool mute) { ALOGD("AudioPlatformDevice SetAnalogMute VOLUME_TYPE = %d mute = %d ", VoleumType, mute); return NO_ERROR; } status_t AudioPlatformDevice::SetFrequency(AudioAnalogType::DEVICE_SAMPLERATE_TYPE DeviceType, unsigned int frequency) { ALOGD("AudioPlatformDevice SetFrequency"); mBlockSampleRate[DeviceType] = frequency; return NO_ERROR; } uint32 AudioPlatformDevice::GetDLFrequency(unsigned int frequency) { ALOGD("AudioPlatformDevice GetDLFrequency = %d", frequency); uint32 Reg_value = 0; switch (frequency) { case 8000: Reg_value = 0; break; case 11025: Reg_value = 1; break; case 12000: Reg_value = 2; break; case 16000: Reg_value = 4; break; case 22050: Reg_value = 5; break; case 24000: Reg_value = 6; break; case 32000: Reg_value = 8; break; case 44100: Reg_value = 9; break; case 48000: Reg_value = 10; default: ALOGW("GetDLFrequency with frequency = %d", frequency); } return Reg_value; } uint32 AudioPlatformDevice::GetULFrequency(unsigned int frequency) { ALOGD("AudioPlatformDevice GetULFrequencyGroup = %d", frequency); uint32 Reg_value = 0; switch (frequency) { case 8000: case 16000: case 32000: Reg_value = 0x0; break; case 48000: Reg_value = 0x1; default: ALOGW("GetULFrequency with frequency = %d", frequency); } ALOGD("AudioPlatformDevice GetULFrequencyGroup Reg_value = %d", Reg_value); return Reg_value; } uint32 AudioPlatformDevice::GetDLNewIFFrequency(unsigned int frequency) { ALOGD("AudioPlatformDevice ApplyDLNewIFFrequency ApplyDLNewIFFrequency = %d", frequency); uint32 Reg_value = 0; switch (frequency) { case 8000: Reg_value = 0; break; case 11025: Reg_value = 1; break; case 12000: Reg_value = 2; break; case 16000: Reg_value = 3; break; case 22050: Reg_value = 4; break; case 24000: Reg_value = 5; break; case 32000: Reg_value = 6; break; case 44100: Reg_value = 7; break; case 48000: Reg_value = 8; default: ALOGW("ApplyDLNewIFFrequency with frequency = %d", frequency); } return Reg_value; } uint32 AudioPlatformDevice::GetULNewIFFrequency(unsigned int frequency) { ALOGD("AudioPlatformDevice GetULNewIFFrequency ApplyULNewIFFrequency = %d", frequency); uint32 Reg_value = 0; switch (frequency) { case 8000: case 16000: case 32000: Reg_value = 1; break; case 48000: Reg_value = 3; default: ALOGW("GetULNewIFFrequency with frequency = %d", frequency); } ALOGD("AudioPlatformDevice GetULNewIFFrequency Reg_value = %d", Reg_value); return Reg_value; } status_t AudioPlatformDevice::TopCtlChangeTrigger(void) { uint32_t top_ctrl_status_now = mAudioAnalogReg->GetAnalogReg(ABB_AFE_CON11); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON11, ((top_ctrl_status_now & 0x0001) ? 0 : 1) << 8, 0x0100); return NO_ERROR; } status_t AudioPlatformDevice::DCChangeTrigger(void) { uint32_t dc_status_now = mAudioAnalogReg->GetAnalogReg(0x4016); mAudioAnalogReg->SetAnalogReg(0x4016, ((dc_status_now & 0x0002) ? 0 : 1) << 9, 0x0200); return NO_ERROR; } bool AudioPlatformDevice::GetDownLinkStatus(void) { for (int i = 0; i <= AudioAnalogType::DEVICE_2IN1_SPK; i++) { if (mBlockAttribute[i].mEnable == true) { ALOGD("GetDownLinkStatus True : i = %d DeviceType = %s", i, kAudioAnalogDeviceTypeName[i]); return true; } } return false; } bool AudioPlatformDevice::GetULinkStatus(void) { for (int i = AudioAnalogType::DEVICE_2IN1_SPK; i <= AudioAnalogType::DEVICE_IN_DIGITAL_MIC; i++) { if (mBlockAttribute[i].mEnable == true) { ALOGD("GetULinkStatus True : i = %d DeviceType = %s", i, kAudioAnalogDeviceTypeName[i]); return true; } } return false; } /** * a basic function fo AnalogOpen, open analog power * @param DeviceType analog part power * @return status_t */ status_t AudioPlatformDevice::AnalogOpen(AudioAnalogType::DEVICE_TYPE DeviceType) { ALOGD("AudioPlatformDevice AnalogOpen DeviceType = %s ", kAudioAnalogDeviceTypeName[DeviceType]); uint32 ulFreq, dlFreq; mLock.lock(); if (mBlockAttribute[DeviceType].mEnable == true) { ALOGW("AudioPlatformDevice AnalogOpen bypass with DeviceType = %d", DeviceType); mLock.unlock(); return NO_ERROR;; } mBlockAttribute[DeviceType].mEnable = true; // here to open pmic digital part ulFreq = GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]); dlFreq = GetDLFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]); switch (DeviceType) { case AudioAnalogType::DEVICE_OUT_EARPIECER: case AudioAnalogType::DEVICE_OUT_EARPIECEL: #if 0 mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1 , GetDLFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]), 0x000f); mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG0 , GetDLNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]) << 12, 0xf000); TopCtlChangeTrigger(); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON5 , 0x28, 0x003f); //Use Default SDM Gain 0x28/0x3f = 0.63 mAudioAnalogReg->SetAnalogReg(ABB_AFE_TOP_CON0 , 0, 0xffff); //Use Normal Path mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON2 , 0, 0xffff); //Use Normal Path mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0 , 1, 0x0001); //Enable DL path TopCtlChangeTrigger(); #else mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG0, GetDLNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]) << 12 | 0x330, 0xffff); // config up8x_rxif mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1, dlFreq, 0x000f); // DL sampling rate TopCtlChangeTrigger(); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0001, 0x0001); // turn on DL #endif break; case AudioAnalogType::DEVICE_OUT_HEADSETR: case AudioAnalogType::DEVICE_OUT_HEADSETL: #if 0 mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1 , GetDLFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]), 0x000f); mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG0 , GetDLNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]) << 12, 0xf000); TopCtlChangeTrigger(); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON5 , 0x28, 0x003f); //Use Default SDM Gain 0x28/0x3f = 0.63 mAudioAnalogReg->SetAnalogReg(ABB_AFE_TOP_CON0 , 0, 0xffff); //Use Normal Path mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON2 , 0, 0xffff); //Use Normal Path mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0 , 1, 0x0001); //Enable DL path TopCtlChangeTrigger(); #else mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG0, GetDLNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]) << 12 | 0x330, 0xffff); // config up8x_rxif mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1, dlFreq, 0x000f); // DL sampling rate //DC compensation setting ALOGD("AnalogOpen mHpRightDcCalibration [0x%x] mHpLeftDcCalibration [0x%x]", mHpRightDcCalibration, mHpLeftDcCalibration); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON3, mHpLeftDcCalibration, 0xffff); // LCH cpmpensation value mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON4, mHpRightDcCalibration, 0xffff); // RCH cpmpensation value mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON10, 0x0001, 0x0001); // enable DC cpmpensation DCChangeTrigger();//Trigger DC compensation TopCtlChangeTrigger(); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0001, 0x0001); // turn on DL #endif break; case AudioAnalogType::DEVICE_OUT_SPEAKERR: case AudioAnalogType::DEVICE_OUT_SPEAKERL: #ifdef USING_EXTAMP_HP mLock.unlock(); AnalogOpen(AudioAnalogType::DEVICE_OUT_HEADSETR); mLock.lock(); #else mLock.unlock(); AnalogOpen(AudioAnalogType::DEVICE_OUT_EARPIECER); mLock.lock(); #endif break; case AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_R: case AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_L: mLock.unlock(); AnalogOpen(AudioAnalogType::DEVICE_OUT_HEADSETR); mLock.lock(); break; case AudioAnalogType::DEVICE_IN_ADC1: case AudioAnalogType::DEVICE_IN_ADC2: ALOGD("AudioPlatformDevice::DEVICE_IN_ADC2:"); #if 0 mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1 , GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 4, 0x0010); mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG2, 0x302F | (GetULNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 10), 0xffff); // config UL up8x_rxif adc voice mode TopCtlChangeTrigger(); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0 , 0x02, 0x0002); //Enable UL path TopCtlChangeTrigger(); #else mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG2, 0x302F | (GetULNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 10), 0xffff); // config UL up8x_rxif adc voice mode mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1, GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 4, 0x0010); // UL sampling rate TopCtlChangeTrigger(); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0002, 0x0002); // turn on UL #endif break; case AudioAnalogType::DEVICE_IN_DIGITAL_MIC: #if 0 mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1 , GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]), 0x0010); mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG2, 0x302F | (GetULNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 10), 0xffff); // config UL up8x_rxif adc voice mode TopCtlChangeTrigger(); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON9 , 0x0011, 0x0011); // enable digital mic, 3.25M clock rate mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0 , 0x02, 0x0002); //Enable UL path TopCtlChangeTrigger(); #else mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG2, 0x302F | (GetULNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 10), 0xffff); // config UL up8x_rxif adc voice mode mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1, GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 4, 0x0010); // UL sampling rate TopCtlChangeTrigger(); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON9, 0x0011, 0x0011); // enable digital mic, 3.25M clock rate mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0002, 0x0002); // turn on UL #endif break; case AudioAnalogType::DEVICE_2IN1_SPK: if (IsAudioSupportFeature(AUDIO_SUPPORT_2IN1_SPEAKER)) { mLock.unlock(); AnalogOpen(AudioAnalogType::DEVICE_OUT_EARPIECER); mLock.lock(); } break; } mLock.unlock(); return NO_ERROR; } status_t AudioPlatformDevice::AnalogOpenForAddSPK(AudioAnalogType::DEVICE_TYPE DeviceType) { ALOGD("AudioPlatformDevice AnalogOpenForAddSPK DeviceType = %s ", kAudioAnalogDeviceTypeName[DeviceType]); // uint32 ulFreq, dlFreq; mLock.lock(); mBlockAttribute[AudioAnalogType::DEVICE_OUT_HEADSETR].mEnable = false; mBlockAttribute[AudioAnalogType::DEVICE_OUT_HEADSETL].mEnable = false; mBlockAttribute[AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_R].mEnable = true; mLock.unlock(); return NO_ERROR; } status_t AudioPlatformDevice::AnalogCloseForSubSPK(AudioAnalogType::DEVICE_TYPE DeviceType) { ALOGD("AudioPlatformDevice AnalogCloseForSubSPK DeviceType = %s", kAudioAnalogDeviceTypeName[DeviceType]); mLock.lock(); mBlockAttribute[AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_R].mEnable = false; mBlockAttribute[AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_L].mEnable = false; mBlockAttribute[AudioAnalogType::DEVICE_OUT_HEADSETR].mEnable = true; mLock.unlock(); return NO_ERROR; } /** * a basic function fo AnalogClose, ckose analog power * @param DeviceType analog part power * @return status_t */ status_t AudioPlatformDevice::AnalogClose(AudioAnalogType::DEVICE_TYPE DeviceType) { ALOGD("AudioPlatformDevice AnalogClose DeviceType = %s", kAudioAnalogDeviceTypeName[DeviceType]); mLock.lock(); mBlockAttribute[DeviceType].mEnable = false; // here to open pmic digital part switch (DeviceType) { case AudioAnalogType::DEVICE_OUT_EARPIECER: case AudioAnalogType::DEVICE_OUT_EARPIECEL: mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0000, 0x0001); // turn off DL // TopCtlChangeTrigger(); break; case AudioAnalogType::DEVICE_OUT_HEADSETR: case AudioAnalogType::DEVICE_OUT_HEADSETL: mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0000, 0x0001); // turn off DL TopCtlChangeTrigger(); ALOGD("AnalogClose Reset mHpRightDcCalibration/mHpLeftDcCalibration from [0x%x] [0x%x]", mHpRightDcCalibration, mHpLeftDcCalibration); mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON3, 0, 0xffff); // LCH cancel DC mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON4, 0, 0xffff); // RCH cancel DC mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON10, 0x0000, 0x0001); // enable DC cpmpensation DCChangeTrigger();//Trigger DC compensation break; case AudioAnalogType::DEVICE_OUT_SPEAKERR: case AudioAnalogType::DEVICE_OUT_SPEAKERL: #ifdef USING_EXTAMP_HP mLock.unlock(); AnalogClose(AudioAnalogType::DEVICE_OUT_HEADSETR); mLock.lock(); #else mLock.unlock(); AnalogClose(AudioAnalogType::DEVICE_OUT_EARPIECER); mLock.lock(); #endif break; case AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_R: case AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_L: mLock.unlock(); AnalogClose(AudioAnalogType::DEVICE_OUT_HEADSETR); mLock.lock(); break; case AudioAnalogType::DEVICE_IN_ADC1: case AudioAnalogType::DEVICE_IN_ADC2: mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0000, 0x0002); // turn off UL // TopCtlChangeTrigger(); break; case AudioAnalogType::DEVICE_IN_DIGITAL_MIC: mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON9, 0x0000, 0x0010); // disable digital mic mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0000, 0x0002); // turn off UL // TopCtlChangeTrigger(); break; case AudioAnalogType::DEVICE_2IN1_SPK: if (IsAudioSupportFeature(AUDIO_SUPPORT_2IN1_SPEAKER)) { mLock.unlock(); AnalogClose(AudioAnalogType::DEVICE_OUT_EARPIECER); mLock.lock(); } break; } if (!GetDownLinkStatus() && !GetULinkStatus()) { mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_SET, 0x0100, 0x0100); // AUD 26M clock power down ALOGD("AudioPlatformDevice AnalogClose Power Down TOP_CKPDN1_SET"); } else { ALOGD("AudioPlatformDevice AnalogClose No Power Down TOP_CKPDN1_SET"); } mLock.unlock(); return NO_ERROR; } /** * a basic function fo select mux of device type, not all device may have mux * if select a device with no mux support , report error. * @param DeviceType analog part * @param MuxType analog mux selection * @return status_t */ status_t AudioPlatformDevice::AnalogSetMux(AudioAnalogType::DEVICE_TYPE DeviceType, AudioAnalogType::MUX_TYPE MuxType) { ALOGD("AAudioPlatformDevice nalogSetMux DeviceType = %s MuxType = %s", kAudioAnalogDeviceTypeName[DeviceType], kAudioAnalogMuxTypeName[MuxType]); return NO_ERROR; } /** * a function for setParameters , provide wide usage of analog control * @param command1 * @param command2 * @param data * @return status_t */ status_t AudioPlatformDevice::setParameters(int command1 , int command2 , unsigned int data) { return NO_ERROR; } /** * a function for setParameters , provide wide usage of analog control * @param command1 * @param data * @return status_t */ status_t AudioPlatformDevice::setParameters(int command1 , void *data) { return NO_ERROR; } /** * a function fo getParameters , provide wide usage of analog control * @param command1 * @param command2 * @param data * @return copy_size */ int AudioPlatformDevice::getParameters(int command1 , int command2 , void *data) { return 0; } //static const uint32_t kFadeSamples[4] = {4096, 2048, 1024, 512}; status_t AudioPlatformDevice::FadeOutDownlink(uint16_t sample_rate) { #if 0 const uint16_t fade_unit_index = 3; // Set gain speed: bit[9:10] = 0x3 => FadeSamples/sample_rate (sec) uint32_t time_ms = (kFadeSamples[fade_unit_index] * 1000) / sample_rate; mAudioAnalogReg->SetAnalogReg(0x4004, fade_unit_index << 9, 3 << 9); // Set ch1 & ch2 fade type: bit[3:4] = 0x3 => fade out mAudioAnalogReg->SetAnalogReg(0x4004, 3 << 3, 3 << 3); // Mute function of ch1 & ch2: bit[11:12] = 0x0 => Enable mAudioAnalogReg->SetAnalogReg(0x4004, 0 << 11, 3 << 11); // Sleep usleep(time_ms * 1000); #endif return NO_ERROR; } status_t AudioPlatformDevice::FadeInDownlink(uint16_t sample_rate) { #if 0 const uint16_t fade_unit_index = 3; // Set gain speed: bit[9:10] = 0x3 => FadeSamples/sample_rate (sec) uint32_t time_ms = (kFadeSamples[fade_unit_index] * 1000) / sample_rate; mAudioAnalogReg->SetAnalogReg(0x4004, fade_unit_index << 9, 3 << 9); // Set ch1 & ch2 fade type: bit[3:4] = 0x0 => fade in mAudioAnalogReg->SetAnalogReg(0x4004, 0 << 3, 3 << 3); // Sleep usleep(time_ms * 1000); // Mute function of ch1 & ch2: bit[11:12] = 0x3 => Disable mAudioAnalogReg->SetAnalogReg(0x4004, 3 << 11, 3 << 11); #endif return NO_ERROR; } status_t AudioPlatformDevice::SetDcCalibration(AudioAnalogType::DEVICE_TYPE DeviceType, int dc_cali_value) { ALOGD("SetDcCalibration Type[%d] value[0x%x]", DeviceType, dc_cali_value); switch (DeviceType) { case AudioAnalogType::DEVICE_OUT_HEADSETR: mHpRightDcCalibration = dc_cali_value; break; case AudioAnalogType::DEVICE_OUT_HEADSETL: mHpLeftDcCalibration = dc_cali_value; break; default: break; } ALOGD("SetDcCalibration mHpRightDcCalibration [0x%x] mHpLeftDcCalibration [0x%x]", mHpRightDcCalibration, mHpLeftDcCalibration); return NO_ERROR; } }
36.863711
197
0.671448
touxiong88
a54540bdad511b2641bac5b0129de33591cace4e
4,347
cpp
C++
ProtoTcpClient/CmdLineExec.cpp
EvanGertis/Dev_RisLib
1aa185d1092bd703a0867bcc36106886baea3454
[ "MIT" ]
null
null
null
ProtoTcpClient/CmdLineExec.cpp
EvanGertis/Dev_RisLib
1aa185d1092bd703a0867bcc36106886baea3454
[ "MIT" ]
null
null
null
ProtoTcpClient/CmdLineExec.cpp
EvanGertis/Dev_RisLib
1aa185d1092bd703a0867bcc36106886baea3454
[ "MIT" ]
1
2019-03-28T15:09:48.000Z
2019-03-28T15:09:48.000Z
#include "stdafx.h" #include "procoTcpSettings.h" #include "procoMsg.h" #include "procoMsgHelper.h" #include "procoClientThread.h" #include "CmdLineExec.h" using namespace ProtoComm; //****************************************************************************** //****************************************************************************** //****************************************************************************** CmdLineExec::CmdLineExec() { } void CmdLineExec::reset() { } //****************************************************************************** //****************************************************************************** //****************************************************************************** void CmdLineExec::execute(Ris::CmdLineCmd* aCmd) { if (aCmd->isCmd("TP")) gClientThread->mTPFlag = aCmd->argBool(1); if (aCmd->isCmd("TX")) executeTx(aCmd); if (aCmd->isCmd("ECHO")) executeEcho(aCmd); if (aCmd->isCmd("DATA")) executeData(aCmd); if (aCmd->isCmd("GO1")) executeGo1(aCmd); if (aCmd->isCmd("GO2")) executeGo2(aCmd); if (aCmd->isCmd("T1")) executeTest1(aCmd); if (aCmd->isCmd("Parms")) executeParms(aCmd); } //****************************************************************************** //****************************************************************************** //****************************************************************************** void CmdLineExec::executeTx (Ris::CmdLineCmd* aCmd) { gClientThread->sendTestMsg(); } //****************************************************************************** //****************************************************************************** //****************************************************************************** void CmdLineExec::executeEcho(Ris::CmdLineCmd* aCmd) { aCmd->setArgDefault(1, 0); int tNumWords = aCmd->argInt(1); ProtoComm::EchoRequestMsg* tMsg = new ProtoComm::EchoRequestMsg; MsgHelper::initialize(tMsg, tNumWords); gClientThread->sendMsg(tMsg); } //****************************************************************************** //****************************************************************************** //****************************************************************************** void CmdLineExec::executeData(Ris::CmdLineCmd* aCmd) { ProtoComm::DataMsg* tMsg = new ProtoComm::DataMsg; MsgHelper::initialize(tMsg); gClientThread->sendMsg(tMsg); } //****************************************************************************** //****************************************************************************** //****************************************************************************** void CmdLineExec::executeGo1(Ris::CmdLineCmd* aCmd) { aCmd->setArgDefault(1, 1); ProtoComm::TestMsg* tMsg = new ProtoComm::TestMsg; gClientThread->sendMsg(tMsg); } //****************************************************************************** //****************************************************************************** //****************************************************************************** void CmdLineExec::executeGo2(Ris::CmdLineCmd* aCmd) { aCmd->setArgDefault(1,1); int tN = aCmd->argInt(1); for (int i=0;i<tN;i++) { ProtoComm::EchoRequestMsg* tMsg = new ProtoComm::EchoRequestMsg; gClientThread->sendMsg(tMsg); gClientThread->threadSleep(10); } } //****************************************************************************** //****************************************************************************** //****************************************************************************** void CmdLineExec::executeTest1(Ris::CmdLineCmd* aCmd) { } //****************************************************************************** //****************************************************************************** //****************************************************************************** void CmdLineExec::executeParms(Ris::CmdLineCmd* aCmd) { ProtoComm::gTcpSettings.show(); } //****************************************************************************** //****************************************************************************** //******************************************************************************
34.228346
80
0.296526
EvanGertis
a54d3255d9b64c01987dcbf06a6bf5a4e3af694a
2,205
cpp
C++
src/DashboardLayout.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
src/DashboardLayout.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
src/DashboardLayout.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
#include "DashboardLayout.h" void DashboardLayout::Setup(){ switch(layoutID){ case LAYOUT_SINGLE: Serial.println("use default single widget dashboard"); widget[0] = new DashboardWidget(Int2(10,10),Int2(470,310),GAUGE_TYPE_BAR,INPUT_ANALOG1); widgetCount = 1; break; case LAYOUT_SIDE_BY_SIDE: Serial.println("use double widget dashboard"); widget[0] = new DashboardWidget(Int2(10,10),Int2(235,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1); widget[1] = new DashboardWidget(Int2(245,10),Int2(470,310),GAUGE_TYPE_BAR,INPUT_ANALOG1); widgetCount = 2; break; case LAYOUT_QUADS: Serial.println("use quad widget dashboard"); widget[0] = new DashboardWidget(Int2(10,10),Int2(235,155),GAUGE_TYPE_EMPTY,INPUT_ANALOG1); widget[1] = new DashboardWidget(Int2(245,10),Int2(470,155),GAUGE_TYPE_BAR,INPUT_ANALOG1); widget[2] = new DashboardWidget(Int2(10,165),Int2(235,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1); widget[3] = new DashboardWidget(Int2(245,165),Int2(470,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1); widgetCount = 4; break; } } DashboardLayout::DashboardLayout(int layoutID) : layoutID(layoutID), editWidgetIndex(-1){ Setup(); //stuff in the layout } DashboardLayout::~DashboardLayout(){ int i = widgetCount; while(i --> 0){ delete widget[i]; } } void DashboardLayout::Update(){ if(Button::CheckForScreenHolding()){ Serial.println("check for button"); int i = widgetCount; while(i --> 0){ if(widget[i]->Holding()){ editWidgetIndex = i; Serial.println("edit widget"); return; } } } } void DashboardLayout::Redraw(){ int i=widgetCount; while(i --> 0){ widget[i]->Redraw(); } } void DashboardLayout::Draw(){ int i=widgetCount; while(i --> 0){ widget[i]->Draw(); } } bool DashboardLayout::ShouldEditWidget(){ return editWidgetIndex > -1; } DashboardWidget* DashboardLayout::EditWidget(){ int ind = editWidgetIndex; editWidgetIndex = -1; return widget[ind]; }
25.639535
100
0.623583
00steve
a5547fdf56655ca4bf73afa96bd8cb653764d9c2
598
cpp
C++
pointer_main.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
1
2019-03-29T21:07:37.000Z
2019-03-29T21:07:37.000Z
pointer_main.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
null
null
null
pointer_main.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; bool printArray(string* arr, int length){ if(arr == NULL){ return false; } for(int i = 0; i < length; i++){ cout << arr[i] << endl; } return true; } int main() { string arrMonth[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; string* pMonth = NULL; pMonth = arrMonth; cout << printArray(pMonth, sizeof(arrMonth) / sizeof(*arrMonth)) << endl; return 0; } /* >> Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 1 Process finished with exit code 0 */
13
111
0.560201
zhichengMLE
a559a8d25755123fb6296d027efb72d08bb91b83
9,590
hpp
C++
src/Serialize.hpp
Mercerenies/latitude
29b1697f1f615d52480197a52e20ff8c1872f07d
[ "MIT" ]
3
2021-09-02T18:19:25.000Z
2021-12-26T23:33:32.000Z
src/Serialize.hpp
Mercerenies/latitude
29b1697f1f615d52480197a52e20ff8c1872f07d
[ "MIT" ]
45
2017-11-28T15:13:59.000Z
2022-02-19T18:45:46.000Z
src/Serialize.hpp
Mercerenies/proto-lang
29b1697f1f615d52480197a52e20ff8c1872f07d
[ "MIT" ]
null
null
null
//// Copyright (c) 2018 Silvio Mayolo //// See LICENSE.txt for licensing details #ifndef SERIALIZE_HPP #define SERIALIZE_HPP #include "Instructions.hpp" #include "Assembler.hpp" /// \file /// /// \brief Serialization structures and helpers. /// serialize_t, on its own, is an incomplete type. Any type which is /// serializable should implement a partial specialization of /// serialize_t for its particular type. The specialization should /// define, publicly, a typedef and two methods. /// /// * `using type = ...` should be defined to be the type parameter /// `T`. /// /// * `void serialize(const type&, OutputIterator&)` should, for any /// output iterator type, serialize a value of the type to the /// iterator. /// /// * `type deserialize(InputIterator&)` should, for any input /// iterator type, deserialize a value of the type to out of the /// iterator. /// /// Serializers are allowed to assume the iterators are valid and, in /// the input case, that the iterator contains a value of the /// appropriate type. Additionally, if the type is small (such as an /// arithmetic type), serializers may replace `const type&` with /// simply `type`. template <typename T> struct serialize_t; template <> struct serialize_t<long> { using type = long; template <typename OutputIterator> void serialize(type arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<char> { using type = char; template <typename OutputIterator> void serialize(type arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<Reg> { using type = Reg; template <typename OutputIterator> void serialize(type arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<Instr> { using type = Instr; template <typename OutputIterator> void serialize(type arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<std::string> { using type = std::string; template <typename OutputIterator> void serialize(const type& arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<FunctionIndex> { using type = FunctionIndex; template <typename OutputIterator> void serialize(const type& arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<AssemblerLine> { using type = AssemblerLine; template <typename OutputIterator> void serialize(const type& arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; /// Serializes the argument into the output iterator. /// /// \pre A partial specialization `serialize_t<T>` must be in scope /// \param arg the value to serialize /// \param iter an output iterator template <typename T, typename OutputIterator> void serialize(const T& arg, OutputIterator& iter); /// Deserializes a value of the given type from the iterator. /// /// \pre A partial specialization `serialize_t<T>` must be in scope /// \param iter an input iterator /// \return the value template <typename T, typename InputIterator> T deserialize(InputIterator& iter); /// Serializes the value within the variant structure. The /// serialization does not mark which variant was saved, so the value /// must be deserialized with ::deserialize<T> (for the appropriate type /// `T`). /// /// \pre A partial specialization `serialize_t<T>` must be in scope, /// for each `T` in `Ts...` /// \param arg the variant /// \param iter an output iterator template <typename OutputIterator, typename... Ts> void serializeVariant(const boost::variant<Ts...>& arg, OutputIterator& iter); // ---- template <typename OutputIterator> auto serialize_t<long>::serialize(type arg, OutputIterator& iter) const -> void { long val1 = arg; if (val1 < 0) *iter++ = 0xFF; else *iter++ = 0x00; val1 = abs(val1); for (int i = 0; i < 4; i++) { *iter++ = (unsigned char)(val1 % 256); val1 /= 256; } } template <typename InputIterator> auto serialize_t<long>::deserialize(InputIterator& iter) const -> type { int sign = 1; if (*iter > 0) sign *= -1; ++iter; long value = 0; long pow = 1; for (int i = 0; i < 4; i++) { value += pow * (long)(*iter); ++iter; pow <<= 8; } return sign * value; } template <typename OutputIterator> auto serialize_t<char>::serialize(type arg, OutputIterator& iter) const -> void { *iter++ = (unsigned char)arg; } template <typename InputIterator> auto serialize_t<char>::deserialize(InputIterator& iter) const -> type { char ch = *iter; ++iter; return ch; } template <typename OutputIterator> auto serialize_t<Reg>::serialize(type arg, OutputIterator& iter) const -> void { *iter++ = (unsigned char)arg; } template <typename InputIterator> auto serialize_t<Reg>::deserialize(InputIterator& iter) const -> type { unsigned char ch = *iter; ++iter; return (Reg)ch; } template <typename OutputIterator> auto serialize_t<Instr>::serialize(type arg, OutputIterator& iter) const -> void { *iter++ = (unsigned char)arg; } template <typename InputIterator> auto serialize_t<Instr>::deserialize(InputIterator& iter) const -> type { unsigned char ch = *iter; ++iter; return (Instr)ch; } template <typename OutputIterator> auto serialize_t<std::string>::serialize(const type& arg, OutputIterator& iter) const -> void { for (char ch : arg) { if (ch == 0) { *iter++ = '\0'; *iter++ = '.'; } else { *iter++ = ch; } } *iter++ = '\0'; *iter++ = '\0'; } template <typename InputIterator> auto serialize_t<std::string>::deserialize(InputIterator& iter) const -> type { std::string str; unsigned char ch; while (true) { ch = *iter; ++iter; if (ch == '\0') { ch = *iter; ++iter; if (ch == '.') str += '\0'; else if (ch == '\0') break; } else { str += ch; } } return str; } template <typename OutputIterator> auto serialize_t<FunctionIndex>::serialize(const type& arg, OutputIterator& iter) const -> void { // No need for a sign bit; this is an index so it's always nonnegative int val1 = arg.index; for (int i = 0; i < 4; i++) { *iter++ = (unsigned char)(val1 % 256); val1 /= 256; } } template <typename InputIterator> auto serialize_t<FunctionIndex>::deserialize(InputIterator& iter) const -> type { int value = 0; int pow = 1; for (int i = 0; i < 4; i++) { value += pow * (long)(*iter); ++iter; pow <<= 8; } return { value }; } template <typename OutputIterator> auto serialize_t<AssemblerLine>::serialize(const type& instr, OutputIterator& iter) const -> void { ::serialize<Instr>(instr.getCommand(), iter); for (const auto& arg : instr.arguments()) { serializeVariant(arg, iter); } } /// \cond template <typename InputIterator> struct _AsmArgDeserializeVisitor { InputIterator& iter; template <typename T> RegisterArg operator()(Proxy<T>) { return deserialize<T>(iter); } }; /// \endcond template <typename InputIterator> auto serialize_t<AssemblerLine>::deserialize(InputIterator& iter) const -> type { Instr instr = ::deserialize<Instr>(iter); AssemblerLine instruction { instr }; _AsmArgDeserializeVisitor<InputIterator> visitor { iter }; for (const auto& arg : getAsmArguments(instr)) { instruction.addRegisterArg(callOnAsmArgType(visitor, arg)); } return instruction; } /// Serializes the object into the given output iterator. There must /// be a compatible specialization of `serialize_t` of the form /// `serialize_t<T>`. /// /// \tparam T the object type /// \tparam OutputIterator the type of the output iterator /// \param arg the object to serialize /// \param iter the output iterator template <typename T, typename OutputIterator> void serialize(const T& arg, OutputIterator& iter) { serialize_t<T>().serialize(arg, iter); } /// Deserializes an object of the given type from the input iterator. /// /// \tparam T the object type /// \tparam InputIterator the type of the input iterator /// \param iter the input iterator /// \return the object template <typename T, typename InputIterator> T deserialize(InputIterator& iter) { return serialize_t<T>().deserialize(iter); } /// \cond template <typename OutputIterator> struct _VariantSerializeVisitor : boost::static_visitor<void> { OutputIterator& iter; _VariantSerializeVisitor(OutputIterator& iter) : iter(iter) {} template <typename T> void operator()(const T& arg) { serialize(arg, iter); } }; /// \endcond template <typename OutputIterator, typename... Ts> void serializeVariant(const boost::variant<Ts...>& arg, OutputIterator& iter) { _VariantSerializeVisitor<OutputIterator> visitor { iter }; boost::apply_visitor(visitor, arg); } #endif // SERIALIZE_HPP
26.862745
99
0.665485
Mercerenies
a55a285e827647b249f13c23efeff1dc550898ef
3,208
cpp
C++
CCC/ccc04s5.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
CCC/ccc04s5.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
CCC/ccc04s5.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define MM 102 int dp[MM][MM][3],arr[MM][MM]; //moved up, down, right char c; int main(){ while(1){ int m,n; scanf("%d%d",&m,&n); if(m == 0) break; for(int i = m; i > 0; i--){ scanf("%c",&c); //nl for(int j = 1; j <= n; j++){ scanf("%c",&c); if(c == '*'){ arr[i][j] = -1; }else if(c == '.'){ arr[i][j] = 0; }else{ arr[i][j] = c-'0'; } //printf("%d ",arr[i][j]); } //printf("\n"); } memset(dp,-1,sizeof(dp)); dp[1][1][2] = max(0, arr[1][1]); for(int j = 1; j <= n; j++){ for(int i = m; i > 0; i--){ if(arr[i][j] == -1) continue; if(dp[i][j-1][2] != -1) dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][2] + arr[i][j]); if(dp[i][j-1][1] != -1) dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][1] + arr[i][j]); if(dp[i][j-1][0] != -1) dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][0] + arr[i][j]); //down if(dp[i-1][j][1] != -1) dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][1] + arr[i][j]); if(dp[i-1][j][2] != -1) dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][2] + arr[i][j]); //up if(dp[i+1][j][0] != -1) dp[i][j][0] = max(dp[i][j][0], dp[i+1][j][0] + arr[i][j]); if(dp[i+1][j][2] != -1) dp[i][j][0] = max(dp[i][j][0], dp[i+1][j][2] + arr[i][j]); } for(int i = 1; i <= m; i++){ if(arr[i][j] == -1) continue; if(dp[i][j-1][2] != -1) dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][2] + arr[i][j]); if(dp[i][j-1][1] != -1) dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][1] + arr[i][j]); if(dp[i][j-1][0] != -1) dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][0] + arr[i][j]); //down if(dp[i-1][j][1] != -1) dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][1] + arr[i][j]); if(dp[i-1][j][2] != -1) dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][2] + arr[i][j]); //up if(dp[i+1][j][0] != -1) dp[i][j][0] = max(dp[i][j][0], dp[i+1][j][0] + arr[i][j]); if(dp[i+1][j][2] != -1) dp[i][j][0] = max(dp[i][j][0], dp[i+1][j][2] + arr[i][j]); } } printf("%d\n",max(max(dp[1][n][0],dp[1][n][1]),dp[1][n][2])); #ifdef def for(int i = m; i > 0; i--){ for(int j = 1; j <= n; j++){ printf("%d ",max(max(dp[i][j][0],dp[i][j][1]),dp[i][j][2])); } printf("\n"); } #endif } return 0; }
36.873563
79
0.275561
crackersamdjam
a222d9ab01460056f957119aaeb4bd94ebf3684e
29,324
cpp
C++
src/Image.cpp
i-saint/glSpriteFont
8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1
[ "Unlicense" ]
2
2015-11-07T11:31:55.000Z
2021-04-16T15:20:44.000Z
src/Image.cpp
i-saint/glSpriteFont
8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1
[ "Unlicense" ]
null
null
null
src/Image.cpp
i-saint/glSpriteFont
8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1
[ "Unlicense" ]
1
2020-06-09T10:45:28.000Z
2020-06-09T10:45:28.000Z
๏ปฟ#include "stdafx.h" #include "Image.h" #ifdef __ist_with_gli__ #include "gli/gli.hpp" #include "gli/gtx/loader.hpp" #endif // __ist_with_gli__ namespace ist { struct BMPHEAD { char B; char M; int32 file_size; int16 reserve1; int16 reserve2; int32 offset; BMPHEAD() { memset(this, 0, sizeof(*this)); B = 'B'; M = 'M'; offset = 54; } }; struct BMPINFOHEAD { int32 header_size; int32 width; int32 height; int16 plane; int16 bits; int32 compression; int32 comp_image_size; int32 x_resolution; int32 y_resolution; int32 pallete_num; int32 important_pallete_num; BMPINFOHEAD() { memset(this, 0, sizeof(*this)); header_size=sizeof(*this); plane = 1; bits = 24; } }; struct TGAHEAD { uint8 No_ID; uint8 CMap_Type; uint8 image_type; uint8 CMap_Spec[5]; int16 Ox; int16 Oy; int16 width; int16 height; uint8 pixel; uint8 IDesc_Type; TGAHEAD() { memset(this, 0, sizeof(*this)); pixel = 32; IDesc_Type = 8; } }; Image::FileType GetFileTypeByFileHeader(IBinaryStream &f) { char m[4]; f >> m; f.setReadPos(0); if(m[0]=='B' && m[1]=='M') { return Image::FileType_BMP; } if(m[1]=='P' && m[2]=='N' && m[3]=='G') { return Image::FileType_PNG; } if(m[0]=='D' && m[1]=='D' && m[2]=='S') { return Image::FileType_DDS; } if(m[0]==0xff && m[1]==0xd8) { return Image::FileType_JPG; } { // tga ใฏ magic code ใŒใชใ„ใฎใงใ€ใใ‚Œใฃใฝใ„ๅ€คใŒๅ…ฅใฃใฆใ‚‹ใ‹ใงๅˆคๆ–ญ TGAHEAD tga; f.read(&tga, sizeof(tga)); f.setReadPos(0); if( (tga.image_type==2 || tga.image_type==10) && tga.Ox==0 && tga.Oy==0 && (tga.pixel==32 || tga.pixel==24)) { return Image::FileType_TGA; } } return Image::FileType_Unknown; } Image::FileType GetFileTypeByExtention(const char *path) { uint32 len = strlen(path); if(len<5) { return Image::FileType_Unknown; } if(strncmp(&path[len-3], "bmp", 3)==0) { return Image::FileType_BMP; } if(strncmp(&path[len-3], "tga", 3)==0) { return Image::FileType_TGA; } if(strncmp(&path[len-3], "png", 3)==0) { return Image::FileType_PNG; } if(strncmp(&path[len-3], "jpg", 3)==0) { return Image::FileType_JPG; } if(strncmp(&path[len-3], "dds", 3)==0) { return Image::FileType_DDS; } return Image::FileType_Unknown; } bool Image::load(const char *path, const IOConfig &conf) { FileStream f(path, "rb"); if(!f.isOpened()) { return false; } IOConfig c = conf; if(c.getFileType()==FileType_Auto) { c.setFileType( GetFileTypeByExtention(path) ); } return load(f, c); } bool Image::load(IBinaryStream &f, const IOConfig &conf) { clear(); FileType ft = conf.getFileType(); if(ft==FileType_Auto) { ft = GetFileTypeByFileHeader(f); } switch(ft) { case FileType_BMP: return loadBMP(f, conf); case FileType_TGA: return loadTGA(f, conf); case FileType_PNG: return loadPNG(f, conf); case FileType_JPG: return loadJPG(f, conf); case FileType_DDS: return loadDDS(f, conf); } istPrint("่ช่ญ˜ใงใใชใ„ใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆใŒๆŒ‡ๅฎšใ•ใ‚Œใพใ—ใŸใ€‚\n"); return false; } bool Image::save(const char *path, const IOConfig &conf) const { FileStream f(path, "wb"); if(!f.isOpened()) { return false; } IOConfig c = conf; if(c.getFileType()==FileType_Auto) { c.setFileType(GetFileTypeByExtention(path)); } return save(f, c); } bool Image::save(IBinaryStream &f, const IOConfig &conf) const { switch(conf.getFileType()) { case FileType_BMP: return saveBMP(f, conf); case FileType_TGA: return saveTGA(f, conf); case FileType_PNG: return savePNG(f, conf); case FileType_JPG: return saveJPG(f, conf); case FileType_DDS: return saveDDS(f, conf); } istPrint(L"่ช่ญ˜ใงใใชใ„ใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆใŒๆŒ‡ๅฎšใ•ใ‚Œใพใ—ใŸใ€‚\n"); return false; } static RGBA_8U Read1Pixel(IBinaryStream &bf) { RGBA_8U t; bf >> t.b >> t.g >> t.r >> t.a; return t; } // BMP bool Image::loadBMP(IBinaryStream &bf, const IOConfig &conf) { BMPHEAD head; BMPINFOHEAD infohead; bf >> head.B >> head.M; if(head.B!='B' || head.M!='M') { return false; } bf >> head.file_size >> head.reserve1 >> head.reserve2 >> head.offset; bf >> infohead.header_size >> infohead.width >> infohead.height >> infohead.plane >> infohead.bits >> infohead.compression >> infohead.comp_image_size >> infohead.x_resolution >> infohead.y_resolution >> infohead.pallete_num >> infohead.important_pallete_num; if(infohead.bits!=24 && infohead.bits!=32) { istPrint(L"bmp ใฏ็พๅœจ 24bit ใ‹ 32bit ใ—ใ‹ๅฏพๅฟœใ—ใฆใ„ใพใ›ใ‚“ใ€‚\n"); return false; } resize<RGBA_8U>(infohead.width, infohead.height); if(infohead.bits==24) { for(int32 yi=(int32)height()-1; yi>=0; --yi) { for(int32 xi=0; xi<(int32)width(); ++xi) { RGBA_8U& c = get<RGBA_8U>(yi, xi); bf >> c.b >> c.g >> c.r; c.a = 255; } } } else if(infohead.bits==32) { for(int32 yi=(int32)height()-1; yi>=0; --yi) { for(int32 xi=0; xi<(int32)width(); ++xi) { RGBA_8U& c = get<RGBA_8U>(yi, xi); bf >> c.b >> c.g >> c.r >> c.a; } } } return true; } bool Image::saveBMP(IBinaryStream &bf, const IOConfig &conf) const { BMPHEAD head; BMPINFOHEAD infohead; head.file_size = sizeof(BMPHEAD)+sizeof(BMPINFOHEAD)+width()*height()*3; infohead.width = width(); infohead.height = height(); bf << head.B << head.M << head.file_size << head.reserve1 << head.reserve2 << head.offset; bf << infohead.header_size << infohead.width << infohead.height << infohead.plane << infohead.bits << infohead.compression << infohead.comp_image_size << infohead.x_resolution << infohead.y_resolution << infohead.pallete_num << infohead.important_pallete_num; for(int32 yi=(int32)height()-1; yi>=0; --yi) { for(int32 xi=0; xi<(int32)width(); ++xi) { const RGBA_8U& c = get<RGBA_8U>(yi, xi); bf << c.b << c.g << c.r; } } return true; } // TGA bool Image::loadTGA(IBinaryStream &bf, const IOConfig &conf) { TGAHEAD head; bf >> head.No_ID >> head.CMap_Type >> head.image_type >> head.CMap_Spec >> head.Ox >> head.Oy >> head.width >> head.height >> head.pixel >> head.IDesc_Type; if(head.pixel!=32) { istPrint("32bit ใƒ‡ใƒผใ‚ฟใ—ใ‹ๅฏพๅฟœใ—ใฆใ„ใพใ›ใ‚“ใ€‚\n"); return false; } resize<RGBA_8U>(head.width, head.height); for(int32 yi=(int32)height()-1; yi>=0; --yi) { if(head.image_type==2) { for(int32 xi=0; xi<(int32)width(); xi++) { get<RGBA_8U>(yi, xi) = Read1Pixel(bf); } } else if(head.image_type==10) { uint32 loaded = 0; while(loaded<width()) { uint8 dist = 0; bf >> dist; if( dist<0x80) { for(int32 xi=0; xi<dist+1; ++xi, ++loaded) { get<RGBA_8U>(yi, loaded) = Read1Pixel(bf); } } else { RGBA_8U t = Read1Pixel(bf); for(int32 xi=0x80; xi<dist+1; ++xi, ++loaded) { get<RGBA_8U>(yi, loaded) = t; } } } } } return true; } class TGACompress { public: TGACompress() {} const stl::vector<uint8>& getCompressedData() const { return m_comp_pixel; } void compress(const RGBA_8U *start, int32 width) { stl::vector<RGBA_8U> same, diff; for(int32 i=0; i!=width; ++i, ++start) { const RGBA_8U *ip=start; ++ip; RGBA_8U dist=*start; if( i+1!=width && dist==*ip && same.size()<0x79 ) { same.push_back(dist); if(diff.size()!=0) { writeDifferentData(diff); } } else { if(same.size()>0x00) { writeSameData(same); } else { diff.push_back(dist); if(diff.size()==0x79 ) { writeDifferentData(diff); } } } } if(same.size()!=0x00) { writeSameData(same); } else if(diff.size()!=0) { writeDifferentData(diff); } } private: void writeSameData(stl::vector<RGBA_8U> &temp_pixel) { m_comp_pixel.push_back( temp_pixel.size()+0x80 ); m_comp_pixel.push_back( temp_pixel[0].b ); m_comp_pixel.push_back( temp_pixel[0].g ); m_comp_pixel.push_back( temp_pixel[0].r ); m_comp_pixel.push_back( temp_pixel[0].a ); temp_pixel.clear(); } void writeDifferentData(stl::vector<RGBA_8U> &temp_pixel) { m_comp_pixel.push_back( temp_pixel.size()-1 ); for(int32 d=0; d<(int32)temp_pixel.size(); d++) { m_comp_pixel.push_back( temp_pixel[d].b ); m_comp_pixel.push_back( temp_pixel[d].g ); m_comp_pixel.push_back( temp_pixel[d].r ); m_comp_pixel.push_back( temp_pixel[d].a ); } temp_pixel.clear(); } private: stl::vector<uint8> m_comp_pixel; }; bool Image::saveTGA(IBinaryStream &bf, const Image::IOConfig &conf) const { TGAHEAD head; head.width = width(); head.height = height(); head.image_type = 10; bf << head.No_ID << head.CMap_Type << head.image_type << head.CMap_Spec << head.Ox << head.Oy << head.width << head.height << head.pixel << head.IDesc_Type; { TGACompress comp; for(int32 yi=(int32)height()-1; yi>=0; --yi) { comp.compress(&get<RGBA_8U>(yi, 0), width()); } const stl::vector<uint8>& data = comp.getCompressedData(); bf.write(&data[0], data.size()); } return true; } // PNG #ifdef __ist_with_png__ namespace { void png_streambuf_read(png_structp png_ptr, png_bytep data, png_size_t length) { IBinaryStream *f = reinterpret_cast<IBinaryStream*>(png_get_io_ptr(png_ptr)); f->read(data, length); } void png_streambuf_write(png_structp png_ptr, png_bytep data, png_size_t length) { IBinaryStream *f = reinterpret_cast<IBinaryStream*>(png_get_io_ptr(png_ptr)); f->write(data, length); } void png_streambuf_flush(png_structp png_ptr) { } } // namespace #endif // __ist_with_png__ bool Image::loadPNG(IBinaryStream &f, const IOConfig &conf) { #ifdef __ist_with_png__ png_structp png_ptr = ::png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); if(png_ptr==0) { istPrint("ๅคฑๆ•—: png_create_read_struct() ใŒ null ใ‚’่ฟ”ใ—ใพใ—ใŸใ€‚\n"); return false; } png_infop info_ptr = ::png_create_info_struct(png_ptr); if(info_ptr==0) { ::png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); istPrint("ๅคฑๆ•—: png_create_info_struct() ใŒ null ใ‚’่ฟ”ใ—ใพใ—ใŸใ€‚\n"); return false; } ::png_set_read_fn(png_ptr, &f, png_streambuf_read); png_uint_32 w, h; int32 bit_depth, color_type, interlace_type; ::png_read_info(png_ptr, info_ptr); ::png_get_IHDR(png_ptr, info_ptr, &w, &h, &bit_depth, &color_type, &interlace_type, NULL, NULL); resize<RGBA_8U>(w, h); ::png_set_strip_16(png_ptr); ::png_set_packing(png_ptr); if(color_type==PNG_COLOR_TYPE_PALETTE) { ::png_set_palette_to_rgb(png_ptr); } if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth<8) { ::png_set_expand_gray_1_2_4_to_8(png_ptr); } if(::png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { ::png_set_tRNS_to_alpha(png_ptr); } ::png_read_update_info(png_ptr, info_ptr); // ่ชญใฟ่พผใฟ stl::vector<png_bytep> row_pointers(height()); for(int32 row=0; row<(int32)height(); ++row) { row_pointers[row] = (png_bytep)png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); } png_read_image(png_ptr, &row_pointers[0]); for(int32 yi=0; yi<(int32)height(); ++yi) { for(int32 xi=0; xi<(int32)width(); ++xi) { RGBA_8U& c = get<RGBA_8U>(yi, xi); if(color_type==PNG_COLOR_TYPE_RGB_ALPHA) { c.r = row_pointers[yi][xi*4+0]; c.g = row_pointers[yi][xi*4+1]; c.b = row_pointers[yi][xi*4+2]; c.a = row_pointers[yi][xi*4+3]; } else if(color_type==PNG_COLOR_TYPE_RGB) { c.r = row_pointers[yi][xi*3+0]; c.g = row_pointers[yi][xi*3+1]; c.b = row_pointers[yi][xi*3+2]; c.a = 255; } } } for(int32 row=0; row<(int32)height(); ++row) { png_free(png_ptr, row_pointers[row]); } png_read_end(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return true; #else istPrint("ๅคฑๆ•—: png ไฝฟ็”จใ‚’็„กๅŠนๅŒ–ใ—ใŸ่จญๅฎšใงใƒ“ใƒซใƒ‰ใ•ใ‚Œใฆใ„ใพใ™ใ€‚\n"); return false; #endif // __ist_with_png__ } bool Image::savePNG(IBinaryStream &f, const Image::IOConfig &conf) const { #ifdef __ist_with_png__ png_structp png_ptr = ::png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); if(png_ptr==0) { istPrint("ๅคฑๆ•—: png_create_write_struct() ใŒ null ใ‚’่ฟ”ใ—ใพใ—ใŸใ€‚"); return false; } png_infop info_ptr = ::png_create_info_struct(png_ptr); if(info_ptr==0) { ::png_destroy_write_struct(&png_ptr, NULL); istPrint("ๅคฑๆ•—: png_create_info_struct() ใŒ null ใ‚’่ฟ”ใ—ใพใ—ใŸใ€‚"); return false; } ::png_set_write_fn(png_ptr, &f, png_streambuf_write, png_streambuf_flush); ::png_set_IHDR(png_ptr, info_ptr, width(), height(), 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); ::png_write_info(png_ptr, info_ptr); Image tmp(*this); stl::vector<png_bytep> row_pointers(height()); for(int32 yi=0; yi<(int32)height(); ++yi) { row_pointers[yi] = tmp.get<RGBA_8U>(yi, 0).v; } ::png_write_image(png_ptr, &row_pointers[0]); ::png_write_end(png_ptr, info_ptr); ::png_destroy_write_struct(&png_ptr, &info_ptr); return true; #else istPrint("ๅคฑๆ•—: png ไฝฟ็”จใ‚’็„กๅŠนๅŒ–ใ—ใŸ่จญๅฎšใงใƒ“ใƒซใƒ‰ใ•ใ‚Œใฆใ„ใพใ™ใ€‚"); return false; #endif // __ist_with_png__ } // JPG #ifdef __ist_with_jpeg__ namespace { struct my_error_mgr { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; typedef struct my_error_mgr * my_error_ptr; void my_error_exit(j_common_ptr cinfo) { my_error_ptr myerr = (my_error_ptr) cinfo->err; (*cinfo->err->output_message)(cinfo); longjmp(myerr->setjmp_buffer, 1); } typedef struct { struct jpeg_source_mgr pub; /* public fields */ IBinaryStream *infile; /* source stream */ JOCTET * buffer; /* start of buffer */ boolean start_of_file; /* have we gotten any data yet? */ } my_source_mgr; typedef my_source_mgr * my_src_ptr; #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */ typedef struct { struct jpeg_destination_mgr pub; /* public fields */ IBinaryStream * outfile; /* target stream */ JOCTET * buffer; /* start of buffer */ } my_destination_mgr; typedef my_destination_mgr * my_dest_ptr; #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */ #define SIZEOF(object) ((size_t) sizeof(object)) void init_streambuf_source (j_decompress_ptr cinfo) { my_src_ptr src = (my_src_ptr) cinfo->src; src->start_of_file = TRUE; } boolean fill_streambuf_input_buffer (j_decompress_ptr cinfo) { my_src_ptr src = (my_src_ptr) cinfo->src; size_t nbytes; nbytes = src->infile->read(src->buffer, INPUT_BUF_SIZE); if (nbytes <= 0) { if (src->start_of_file) /* Treat empty input file as fatal error */ ERREXIT(cinfo, JERR_INPUT_EMPTY); WARNMS(cinfo, JWRN_JPEG_EOF); /* Insert a fake EOI marker */ src->buffer[0] = (JOCTET) 0xFF; src->buffer[1] = (JOCTET) JPEG_EOI; nbytes = 2; } src->pub.next_input_byte = src->buffer; src->pub.bytes_in_buffer = nbytes; src->start_of_file = FALSE; return TRUE; } void skip_input_data (j_decompress_ptr cinfo, long num_bytes) { struct jpeg_source_mgr * src = cinfo->src; if (num_bytes > 0) { while (num_bytes > (long) src->bytes_in_buffer) { num_bytes -= (long) src->bytes_in_buffer; (void) (*src->fill_input_buffer) (cinfo); } src->next_input_byte += (size_t) num_bytes; src->bytes_in_buffer -= (size_t) num_bytes; } } void term_source (j_decompress_ptr cinfo) { } void jpeg_streambuf_src (j_decompress_ptr cinfo, IBinaryStream &streambuf) { my_src_ptr src; if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_source_mgr)); src = (my_src_ptr) cinfo->src; src->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, INPUT_BUF_SIZE * SIZEOF(JOCTET)); } src = (my_src_ptr) cinfo->src; src->pub.init_source = init_streambuf_source; src->pub.fill_input_buffer = fill_streambuf_input_buffer; src->pub.skip_input_data = skip_input_data; src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ src->pub.term_source = term_source; src->infile = &streambuf; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.next_input_byte = NULL; /* until buffer loaded */ } void init_streambuf_destination (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; /* Allocate the output buffer --- it will be released when done with image */ dest->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, OUTPUT_BUF_SIZE * SIZEOF(JOCTET)); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; } boolean empty_streambuf_output_buffer (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; if (dest->outfile->write(dest->buffer, OUTPUT_BUF_SIZE) != (size_t) OUTPUT_BUF_SIZE) ERREXIT(cinfo, JERR_FILE_WRITE); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; return TRUE; } void term_destination (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; /* Write any data remaining in the buffer */ if (datacount > 0) { if (dest->outfile->write(dest->buffer, datacount) != datacount) ERREXIT(cinfo, JERR_FILE_WRITE); } } void jpeg_streambuf_dest (j_compress_ptr cinfo, std::streambuf& outfile) { my_dest_ptr dest; if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_destination_mgr)); } dest = (my_dest_ptr) cinfo->dest; dest->pub.init_destination = init_streambuf_destination; dest->pub.empty_output_buffer = empty_streambuf_output_buffer; dest->pub.term_destination = term_destination; dest->outfile = &outfile; } } // namespace #endif // __ist_with_jpeg__ bool Image::loadJPG(IBinaryStream &f, const IOConfig &conf) { clear(); #ifdef __ist_with_jpeg__ jpeg_decompress_struct cinfo; my_error_mgr jerr; JSAMPARRAY buffer; int32 row_stride; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = my_error_exit; if(setjmp(jerr.setjmp_buffer)) { jpeg_destroy_decompress(&cinfo); return false; } jpeg_create_decompress(&cinfo); jpeg_streambuf_src(&cinfo, f); jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); row_stride = cinfo.output_width * cinfo.output_components; buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); resize(cinfo.image_width, cinfo.image_height); uint32 pix_count = 0; while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, buffer, 1); for(int32 i=0; i<(int32)row_stride/3; ++i) { RGBA_8U col(buffer[0][i*3+0], buffer[0][i*3+1], buffer[0][i*3+2], 255); at(pix_count) = col; ++pix_count; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); return true; #else istPrint("ๅคฑๆ•—: jpg ไฝฟ็”จใ‚’็„กๅŠนๅŒ–ใ—ใŸ่จญๅฎšใงใƒ“ใƒซใƒ‰ใ•ใ‚Œใฆใ„ใพใ™ใ€‚"); return false; #endif // __ist_with_jpeg__ } bool Image::saveJPG(IBinaryStream &f, const IOConfig &conf) const { #ifdef __ist_with_jpeg__ jpeg_compress_struct cinfo; jpeg_error_mgr jerr; JSAMPROW row_pointer[1]; int32 row_stride; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_streambuf_dest(&cinfo, f); cinfo.image_width = width(); cinfo.image_height = height(); cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, conf.getJpgQuality(), TRUE); jpeg_start_compress(&cinfo, TRUE); row_stride = cinfo.image_width*3; uint8 *buf = new uint8[width()*height()*3]; for(int32 i=0; i<(int32)width()*(int32)height(); ++i) { buf[i*3+0] = at(i).r; buf[i*3+1] = at(i).g; buf[i*3+2] = at(i).b; } while (cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = &buf[cinfo.next_scanline * row_stride]; jpeg_write_scanlines(&cinfo, row_pointer, 1); } delete[] buf; jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); return true; #else // __ist_with_jpeg__ istPrint("ๅคฑๆ•—: jpg ไฝฟ็”จใ‚’็„กๅŠนๅŒ–ใ—ใŸ่จญๅฎšใงใƒ“ใƒซใƒ‰ใ•ใ‚Œใฆใ„ใพใ™ใ€‚"); return false; #endif // __ist_with_jpeg__ } } // namespace ist #ifdef __ist_with_gli__ namespace gli { namespace gtx { namespace loader_dds10{ namespace detail { // gli ใซใฏ std::string ใ‚’ๅผ•ๆ•ฐใซใจใ‚‹ใ‚„ใคใ—ใ‹ใชใ„ใฎใงใ€ใ‚นใƒˆใƒชใƒผใƒ ็‰ˆใ‚’ใ‚ณใƒ”ใƒšๆ”นๅค‰ๅฎŸ่ฃ…ใ—ใพใ™ใ€‚ๅ‚่€ƒ: loadDDS10() inline texture2D loadDDS10_ex( ist::IBinaryStream &bin ) { loader_dds9::detail::ddsHeader HeaderDesc; detail::ddsHeader10 HeaderDesc10; char Magic[4]; //* Read magic number and check if valid .dds file bin.read((char*)&Magic, sizeof(Magic)); assert(strncmp(Magic, "DDS ", 4) == 0); // Get the surface descriptor bin.read(&HeaderDesc, sizeof(HeaderDesc)); if(HeaderDesc.format.flags & loader_dds9::detail::GLI_DDPF_FOURCC && HeaderDesc.format.fourCC == loader_dds9::detail::GLI_FOURCC_DX10) bin.read(&HeaderDesc10, sizeof(HeaderDesc10)); loader_dds9::detail::DDLoader Loader; if(HeaderDesc.format.fourCC == loader_dds9::detail::GLI_FOURCC_DX10) Loader.Format = detail::format_dds2gli_cast(HeaderDesc10.dxgiFormat); else if(HeaderDesc.format.flags & loader_dds9::detail::GLI_DDPF_FOURCC) Loader.Format = detail::format_fourcc2gli_cast(HeaderDesc.format.fourCC); else { switch(HeaderDesc.format.bpp) { case 8: Loader.Format = R8U; break; case 16: Loader.Format = RG8U; break; case 24: Loader.Format = RGB8U; break; case 32: Loader.Format = RGBA8U; break; } } Loader.BlockSize = size(image(texture2D::dimensions_type(0), Loader.Format), BLOCK_SIZE); Loader.BPP = size(image(texture2D::dimensions_type(0), Loader.Format), BIT_PER_PIXEL); std::size_t Width = HeaderDesc.width; std::size_t Height = HeaderDesc.height; gli::format Format = Loader.Format; std::streamoff Curr = bin.getReadPos(); bin.setReadPos(0, ist::IBinaryStream::Seek_End); std::streamoff End = bin.getReadPos(); bin.setReadPos(Curr); std::vector<glm::byte> Data(std::size_t(End - Curr), 0); std::size_t Offset = 0; bin.read(&Data[0], std::streamsize(Data.size())); //texture2D Image(glm::min(MipMapCount, Levels));//SurfaceDesc.mipMapLevels); std::size_t MipMapCount = (HeaderDesc.flags & loader_dds9::detail::GLI_DDSD_MIPMAPCOUNT) ? HeaderDesc.mipMapLevels : 1; //if(Loader.Format == DXT1 || Loader.Format == DXT3 || Loader.Format == DXT5) // MipMapCount -= 2; texture2D Image(MipMapCount); for(std::size_t Level = 0; Level < Image.levels() && (Width || Height); ++Level) { Width = glm::max(std::size_t(Width), std::size_t(1)); Height = glm::max(std::size_t(Height), std::size_t(1)); std::size_t MipmapSize = 0; if((Loader.BlockSize << 3) > Loader.BPP) MipmapSize = ((Width + 3) >> 2) * ((Height + 3) >> 2) * Loader.BlockSize; else MipmapSize = Width * Height * Loader.BlockSize; std::vector<glm::byte> MipmapData(MipmapSize, 0); memcpy(&MipmapData[0], &Data[0] + Offset, MipmapSize); texture2D::dimensions_type Dimensions(Width, Height); Image[Level] = texture2D::image(Dimensions, Format, MipmapData); Offset += MipmapSize; Width >>= 1; Height >>= 1; } return Image; } } // detail } // loader_dds10 } // namespace gtx } // namespace gli #endif // __ist_with_gli__ namespace ist { bool Image::loadDDS( IBinaryStream &f, const IOConfig &conf ) { #ifdef __ist_with_gli__ gli::texture2D tex = gli::gtx::loader_dds10::detail::loadDDS10_ex(f); ivec2 dim = ivec2(tex[0].dimensions().x, tex[0].dimensions().y); switch(tex.format()) { case gli::R8U: setup(IF_R8U, dim.x, dim.y, tex[0].capacity()); break; case gli::R8I: setup(IF_R8I, dim.x, dim.y, tex[0].capacity()); break; case gli::R32F: setup(IF_R32F, dim.x, dim.y, tex[0].capacity()); break; case gli::RG8U: setup(IF_RG8U, dim.x, dim.y, tex[0].capacity()); break; case gli::RG8I: setup(IF_RG8I, dim.x, dim.y, tex[0].capacity()); break; case gli::RG32F: setup(IF_RG32F, dim.x, dim.y, tex[0].capacity()); break; case gli::RGB8U: setup(IF_RGB8U, dim.x, dim.y, tex[0].capacity()); break; case gli::RGB8I: setup(IF_RGB8I, dim.x, dim.y, tex[0].capacity()); break; case gli::RGB32F: setup(IF_RGB32F, dim.x, dim.y, tex[0].capacity()); break; case gli::RGBA8U: setup(IF_RGBA8U, dim.x, dim.y, tex[0].capacity()); break; case gli::RGBA8I: setup(IF_RGBA8I, dim.x, dim.y, tex[0].capacity()); break; case gli::RGBA32F: setup(IF_RGBA32F, dim.x, dim.y, tex[0].capacity()); break; case gli::DXT1: setup(IF_RGBA_DXT1, dim.x, dim.y, tex[0].capacity()); break; case gli::DXT3: setup(IF_RGBA_DXT3, dim.x, dim.y, tex[0].capacity()); break; case gli::DXT5: setup(IF_RGBA_DXT5, dim.x, dim.y, tex[0].capacity()); break; default: return false; } memcpy(data(), tex[0].data(), tex[0].capacity()); return true; #endif // __ist_with_gli__ return false; } bool Image::saveDDS( IBinaryStream &f, const IOConfig &conf ) const { istPrint("ๆœชๅฎŸ่ฃ…"); return false; } } // namespace ist
28.805501
139
0.572228
i-saint
a22992aa915dd06e962163704b713c016925eb26
2,215
cpp
C++
tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
30
2018-03-05T17:35:29.000Z
2022-03-17T18:59:34.000Z
tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
2
2016-05-26T04:47:13.000Z
2019-02-15T05:17:43.000Z
tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
5
2019-02-15T05:09:22.000Z
2021-04-14T12:10:16.000Z
#include "__zz_cib_StlDependencyTest-decl.h" #include "__zz_cib_StlDependencyTest-export.h" #include "__zz_cib_StlDependencyTest-ids.h" #include "__zz_cib_StlDependencyTest-mtable.h" namespace __zz_cib_ { namespace __zz_cib_Class263 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }} namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class258 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class257 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class260 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class259 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} namespace __zz_cib_ { namespace __zz_cib_Class261 { namespace __zz_cib_Class262 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} extern "C" __zz_cib_export const __zz_cib_::__zz_cib_MethodTable* __zz_cib_decl __zz_cib_StlDependencyTestGetMethodTable(std::uint32_t classId) { switch(classId) { case __zz_cib_::__zz_cib_ids::__zz_cib_Class263::__zz_cib_classId: return __zz_cib_::__zz_cib_Class263::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class258::__zz_cib_classId: return __zz_cib_::__zz_cib_Class256::__zz_cib_Class258::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class257::__zz_cib_classId: return __zz_cib_::__zz_cib_Class256::__zz_cib_Class257::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class260::__zz_cib_classId: return __zz_cib_::__zz_cib_Class256::__zz_cib_Class260::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class259::__zz_cib_classId: return __zz_cib_::__zz_cib_Class256::__zz_cib_Class259::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class261::__zz_cib_Class262::__zz_cib_classId: return __zz_cib_::__zz_cib_Class261::__zz_cib_Class262::__zz_cib_GetMethodTable(); default: return nullptr; } }
67.121212
140
0.832957
satya-das
a22ae189aaa5767f514c0572455824bc70973c43
3,128
cc
C++
Pulse/src/InputStream.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2019-07-29T04:07:29.000Z
2019-07-29T04:07:29.000Z
Pulse/src/InputStream.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
Pulse/src/InputStream.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2020-03-04T17:13:04.000Z
2020-03-04T17:13:04.000Z
/* * Copyright (C) 2021 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/pulse/InputStream> #include <cc/Format> #include <cc/DEBUG> #include <pulse/stream.h> #include <cassert> namespace cc::pulse { struct InputStream::State: public Object::State { State(const Context &context, const String &name, int sampleRate, int channelCount): context_{context}, name_{name} { if (name_.count() == 0) { name_ = Format{"input_%%_%%"} << sampleRate << channelCount; } sampleSpec_.format = PA_SAMPLE_S16NE; sampleSpec_.rate = sampleRate; sampleSpec_.channels = channelCount; stream_ = pa_stream_new(context_, name_, &sampleSpec_, nullptr); pa_stream_set_state_callback(stream_, &stateChanged, this); pa_stream_set_read_callback(stream_, &incoming, this); } ~State() { if (stream_) { pa_stream_unref(stream_); } } static void stateChanged(pa_stream *stream, void *userData) { static_cast<State *>(userData)->stateChanged(pa_stream_get_state(stream)); } void stateChanged(pa_stream_state newState) { // CC_INSPECT(newState); if (newState == PA_STREAM_READY && onReady_) onReady_(); } static void incoming(pa_stream *stream, size_t fill, void *userData) { static_cast<State *>(userData)->incoming(fill); } void incoming(size_t fill) { if (sample_) { const void *data = nullptr; CC_PULSE(pa_stream_peek(stream_, &data, &fill)); if (data != nullptr && fill > 0 && sample_) { wrapping_.wrapAround(const_cast<void *>(data), fill); sample_(wrapping_); } if (fill > 0) { CC_PULSE(pa_stream_drop(stream_)); } } } void connect(const String &target, Fun<void()> &&ready) { if (ready) { onReady_ = move(ready); } const char *device = nullptr; if (target.count() > 0) device = target; CC_PULSE( pa_stream_connect_record(stream_, device, nullptr, PA_STREAM_NOFLAGS) ); } Context context_; pa_stream *stream_ { nullptr }; pa_sample_spec sampleSpec_ {}; String name_; Fun<void()> onReady_; Fun<void(const Bytes &data)> sample_; Bytes wrapping_; }; InputStream::InputStream(const Context &context, int sampleRate, int channelCount): Object{new State{context, {}, sampleRate, channelCount}} {} int InputStream::sampleRate() const { return me().sampleSpec_.rate; } void InputStream::incoming(Fun<void(const Bytes &data)> &&sample) { me().sample_ = move(sample); } void InputStream::connect(const String &target, Fun<void()> &&ready) { me().connect(target, move(ready)); } InputStream::State &InputStream::me() { return Object::me.as<State>(); } const InputStream::State &InputStream::me() const { return Object::me.as<State>(); } } // namespace cc::pulse
24.4375
88
0.609655
frankencode