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
e80a9802a6da3e55f48cc892d3fb160a30b62aa7
544
cpp
C++
polymorphism/crtp/crtp.cpp
google/cpp-from-the-sky-down
10c8d16e877796f2906bedbd3a66fb6469b3a211
[ "Apache-2.0" ]
219
2018-08-15T22:01:07.000Z
2022-03-23T11:46:54.000Z
polymorphism/crtp/crtp.cpp
sthagen/cpp-from-the-sky-down
72114a17a659e5919b4cbe3363e35c04f833d9d9
[ "Apache-2.0" ]
5
2018-09-11T06:15:28.000Z
2022-01-05T15:27:31.000Z
polymorphism/crtp/crtp.cpp
sthagen/cpp-from-the-sky-down
72114a17a659e5919b4cbe3363e35c04f833d9d9
[ "Apache-2.0" ]
27
2018-09-11T06:14:40.000Z
2022-03-20T09:46:14.000Z
#include <iostream> #include <vector> template<typename Child> struct shape { void draw()const { std::cout << "Preparing screen\n"; static_cast<const Child*>(this)->draw_implementation(); } }; struct square : shape<square> { void draw_implementation() const { std::cout << "square::draw\n"; } }; struct circle : shape<circle> { void draw_implementation()const { std::cout << "circle::draw\n"; } }; template<typename Shape> void draw(const Shape& shape) { shape.draw(); } int main() { circle c; square s; draw(c); draw(s); }
16.484848
68
0.665441
google
e80e829eed92f0153300cb9a252f84846b85801d
1,561
cpp
C++
c/src/algorithm/sunday.cpp
jc1995wade/dwadelib
06fa17e4687f6a1cd8503d5804c49ca924f9cfb7
[ "Apache-2.0" ]
2
2020-04-15T15:04:21.000Z
2022-03-30T06:22:00.000Z
c/src/algorithm/sunday.cpp
jc1995wade/dwadelib
06fa17e4687f6a1cd8503d5804c49ca924f9cfb7
[ "Apache-2.0" ]
null
null
null
c/src/algorithm/sunday.cpp
jc1995wade/dwadelib
06fa17e4687f6a1cd8503d5804c49ca924f9cfb7
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> int * getStep(int *step, char *a, char *b) { int i, sublen; for (i=0; i<256; i++) { step[i] = strlen(b) + 1; } sublen = strlen(b); for (i=0; i<sublen; i++) { step[b[i]] = sublen - i; } return step; } int sundaySearch(char *mainstr, char *substr, int *step) { int i=0,j=0; int temp; int mainlen=strlen(mainstr); int sublen=strlen(substr); while (i<mainlen){ temp = i; while (j<sublen){ if (mainstr[i]==substr[j]){ i++; j++; continue; } else { i = temp + step[mainstr[temp+sublen]]; if (i+sublen>mainlen) return -1; j=0; break; } } if (j==sublen) return temp; } } int main(int argc, char *argv[]) { int ret; char a[]="LESSONS TEARNED IN SOFTWARE TE"; char b[]="SOFTWsdjfARE"; int step[256]; FILE *fp = NULL; char *fret = NULL; int i = 0; char line[1024]; access(argv[1], F_OK|W_OK); printf("argv[1]=%s\n", argv[1]); fp = fopen(argv[1], "r"); if (NULL == fp) { printf("Error opening file.\n"); return -1; } do { memset(line, 0, sizeof(line)); fret = fgets(line, sizeof(line), fp); printf("%d %s", i++, line); } while(fret); getStep(step, a, b); ret = sundaySearch(a, b, step); printf("ret=%d\n", ret); fclose(fp); return 0; }
19.036585
56
0.497758
jc1995wade
e8113bbda77d9398b18189514ce6c1cda9b48fb6
2,873
hpp
C++
src/gdx-cpp/graphics/glutils/ShapeRenderer.hpp
aevum/libgdx-cpp
88603a59af4d915259a841e13ce88f65c359f0df
[ "Apache-2.0" ]
77
2015-01-28T17:21:49.000Z
2022-02-17T17:59:21.000Z
src/gdx-cpp/graphics/glutils/ShapeRenderer.hpp
aevum/libgdx-cpp
88603a59af4d915259a841e13ce88f65c359f0df
[ "Apache-2.0" ]
5
2015-03-22T23:14:54.000Z
2020-09-18T13:26:03.000Z
src/gdx-cpp/graphics/glutils/ShapeRenderer.hpp
aevum/libgdx-cpp
88603a59af4d915259a841e13ce88f65c359f0df
[ "Apache-2.0" ]
24
2015-02-12T04:34:37.000Z
2021-06-19T17:05:23.000Z
/* Copyright 2011 Aevum Software aevum @ aevumlab.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @author Victor Vicente de Carvalho victor.carvalho@aevumlab.com @author Ozires Bortolon de Faria ozires@aevumlab.com */ #ifndef GDX_CPP_GRAPHICS_GLUTILS_SHAPERENDERER_HPP_ #define GDX_CPP_GRAPHICS_GLUTILS_SHAPERENDERER_HPP_ #include "ImmediateModeRenderer.hpp" #include "gdx-cpp/graphics/Color.hpp" #include "gdx-cpp/math/Matrix4.hpp" namespace gdx { class ImmediateModeRenderer; class ShapeRenderer { public: class ShapeType { public: const static ShapeType Point; const static ShapeType Line; const static ShapeType Rectangle; const static ShapeType FilledRectangle; const static ShapeType Box; int getGlType () const; bool operator==(const ShapeType& other) const { return this == &other; } bool operator!=(const ShapeType& other) const { return this != &other; } private: int glType; ShapeType(int glType) ; }; int getGlType (); void setColor (const Color& color); void setColor (float r,float g,float b,float a); void setProjectionMatrix (const Matrix4& matrix); void setTransformMatrix (const Matrix4& matrix); void identity (); void translate (float x,float y,float z); void rotate (float axisX,float axisY,float axisZ,float angle); void scale (float scaleX,float scaleY,float scaleZ); void begin (const ShapeType& type); void point (float x,float y,float z); void line (float x,float y,float z,float x2,float y2,float z2); void line (float x,float y,float x2,float y2); void rect (float x,float y,float width,float height); void filledRect (float x,float y,float width,float height); void box (float x,float y,float z,float width,float height,float depth); void end (); void dispose (); ShapeRenderer (); virtual ~ShapeRenderer(); protected: ImmediateModeRenderer* renderer; bool matrixDirty; Matrix4 projView; Matrix4 transform; Matrix4 combined; Matrix4 tmp; Color color; const ShapeType* currType; private: void checkDirty (); void checkFlush (int newVertices); int glType ; }; } // namespace gdx #endif // GDX_CPP_GRAPHICS_GLUTILS_SHAPERENDERER_HPP_
29.618557
76
0.693352
aevum
e81623645f421694a44219a552a36c088809f45a
1,679
cpp
C++
halide/box-blur-across-arch/box-blur.cpp
rileyweber13/learning-sandbox
668c13daf8620826cc674f4deacbddff3c477d92
[ "MIT" ]
null
null
null
halide/box-blur-across-arch/box-blur.cpp
rileyweber13/learning-sandbox
668c13daf8620826cc674f4deacbddff3c477d92
[ "MIT" ]
4
2019-11-15T16:36:04.000Z
2021-02-01T20:28:17.000Z
halide/box-blur-across-arch/box-blur.cpp
rileyweber13/learning-sandbox
668c13daf8620826cc674f4deacbddff3c477d92
[ "MIT" ]
null
null
null
#include "Halide.h" #include "halide_image_io.h" #include <iostream> #include <string> using namespace Halide; using namespace Halide::Tools; using namespace std; void blur_image(string input_filename, string output_filename){ // taken from halide tutorial 7, available at // https://github.com/halide/Halide/blob/master/tutorial/lesson_07_multi_stage_pipelines.cpp Var x("x"), y("y"), c("c"); { Buffer<uint8_t> input = load_image(input_filename); Func input_16("input_16"); input_16(x, y, c) = cast<uint16_t>(input(x, y, c)); Func blur_x("blur_x"); blur_x(x, y, c) = (input_16(x-1, y, c) + 2 * input_16(x, y, c) + input_16(x+1, y, c)) / 4; Func blur_y("blur_y"); blur_y(x, y, c) = (blur_x(x, y-1, c) + 2 * blur_x(x, y, c) + blur_x(x, y+1, c)) / 4; Func output("output"); output(x, y, c) = cast<uint8_t>(blur_y(x, y, c)); Buffer<uint8_t> result(input.width()-2, input.height()-2, 3); result.set_min(1, 1); output.realize(result); save_image(result, output_filename); } } int main(int argc, char **argv) { if (argc < 2) { cout << "usage: " << argv[0] << " path/to/image-to-blur" << endl; return 1; } string input_filename = argv[1]; std::size_t dot_i = input_filename.find_last_of("."); string ext = input_filename.substr(dot_i, input_filename.size()); string output_filename = input_filename.substr(0, dot_i) + "-output" + ext; blur_image(input_filename, output_filename); cout << "blurred image " << input_filename << " and output to " << output_filename << endl; return 0; }
28.457627
94
0.606313
rileyweber13
e81c02646867d6da4a89210f6d311d383264ef7f
2,561
cc
C++
felicia/core/master/tool/topic_publish_command_dispatcher.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
17
2018-10-28T13:58:01.000Z
2022-03-22T07:54:12.000Z
felicia/core/master/tool/topic_publish_command_dispatcher.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
2
2018-11-09T04:15:58.000Z
2018-11-09T06:42:57.000Z
felicia/core/master/tool/topic_publish_command_dispatcher.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
5
2019-10-31T06:50:05.000Z
2022-03-22T07:54:30.000Z
// Copyright (c) 2019 The Felicia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "felicia/core/master/tool/topic_publish_command_dispatcher.h" #include "felicia/core/master/master_proxy.h" #include "felicia/core/node/dynamic_publishing_node.h" #include "felicia/core/thread/main_thread.h" namespace felicia { namespace { class DynamicPublisherDelegate : public DynamicPublishingNode::Delegate { public: DynamicPublisherDelegate(const std::string& message_type, const std::string& topic, const std::string& channel_type, const std::string& message, int64_t interval) : message_type_(message_type), topic_(topic), message_(message), delay_(base::TimeDelta::FromMilliseconds(interval)) { ChannelDef::Type_Parse(channel_type, &channel_type_); } void OnDidCreate(DynamicPublishingNode* node) override { node_ = node; communication::Settings settings; settings.is_dynamic_buffer = true; node_->RequestPublish(message_type_, topic_, channel_type_, settings); } void OnError(Status s) override { NOTREACHED() << s; } void OnRequestPublish(Status s) override { CHECK(s.ok()) << s; PublishMessageFromJson(); } void PublishMessageFromJson() { node_->PublishMessageFromJson(message_); MainThread& main_thread = MainThread::GetInstance(); main_thread.PostDelayedTask( FROM_HERE, base::BindOnce(&DynamicPublisherDelegate::PublishMessageFromJson, base::Unretained(this)), delay_); } private: std::string message_type_; std::string topic_; ChannelDef::Type channel_type_; std::string message_; base::TimeDelta delay_; DynamicPublishingNode* node_; }; } // namespace TopicPublishCommandDispatcher::TopicPublishCommandDispatcher() = default; void TopicPublishCommandDispatcher::Dispatch( const TopicPublishFlag& delegate) const { MasterProxy& master_proxy = MasterProxy::GetInstance(); auto dynamic_publisher_delegate = std::make_unique<DynamicPublisherDelegate>( delegate.message_type_flag()->value(), delegate.topic_flag()->value(), delegate.channel_type_flag()->value(), delegate.message_flag()->value(), delegate.interval_flag()->value()); NodeInfo node_info; master_proxy.RequestRegisterNode<DynamicPublishingNode>( node_info, std::move(dynamic_publisher_delegate)); } } // namespace felicia
31.231707
79
0.711831
chokobole
e81ec3c4d0aeb319af81acb7fd418a3da15970d9
9,666
cpp
C++
examples/rapidxml_example.cpp
zlecky/gamecell
309c4e094ed214f79183429e2d2ae9a1464f9b45
[ "MIT" ]
null
null
null
examples/rapidxml_example.cpp
zlecky/gamecell
309c4e094ed214f79183429e2d2ae9a1464f9b45
[ "MIT" ]
null
null
null
examples/rapidxml_example.cpp
zlecky/gamecell
309c4e094ed214f79183429e2d2ae9a1464f9b45
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <iostream> #include <string> #include <cmath> #include "rapidxml/rapidxml.hpp" #include "rapidxml/rapidxml_utils.hpp" #include "rapidxml/rapidxml_print.hpp" namespace { void write_doc_to_xml(const std::string& file, rapidxml::xml_document<>& doc) { // write it into xml file. std::string content; rapidxml::print(std::back_inserter(content), doc, 0); std::cout << content << std::endl; std::fstream out(file, std::ios::out | std::ios::trunc); out << content; out.close(); } void create_xml(const std::string& file) { rapidxml::xml_document<> doc; // declaration node by "node_declaration". { auto declaration = doc.allocate_node(rapidxml::node_declaration); declaration->append_attribute(doc.allocate_attribute("version", "1.0")); declaration->append_attribute(doc.allocate_attribute("encoding", "utf-8")); doc.append_node(declaration); } // declaration node by "node_pi" { auto declaration = doc.allocate_node(rapidxml::node_pi, doc.allocate_string(R"(xml version="1.0" encoding="utf-8")")); doc.append_node(declaration); } // node comment { auto comment = doc.allocate_node(rapidxml::node_comment, nullptr, "RapidXml很好用哟!"); doc.append_node(comment); } // node element called "root" auto root = doc.allocate_node(rapidxml::node_element, "config"); doc.append_node(root); // node element called "srv" auto srv = doc.allocate_node(rapidxml::node_element, "srv"); { // node comment of "srv" { auto comment = doc.allocate_node(rapidxml::node_comment, nullptr, "服务器配置"); srv->append_node(comment); } // node element called "item" without value { auto item = doc.allocate_node(rapidxml::node_element, "item"); item->append_attribute(doc.allocate_attribute("id", "1")); item->append_attribute(doc.allocate_attribute("ip", "127.0.0.1")); item->append_attribute(doc.allocate_attribute("port", "8081")); srv->append_node(item); } // node element called "item" with value { auto item = doc.allocate_node(rapidxml::node_element, "item", "2"); item->append_attribute(doc.allocate_attribute("id", "2")); item->append_attribute(doc.allocate_attribute("ip", "127.0.0.1")); item->append_attribute(doc.allocate_attribute("port", "8082")); srv->append_node(item); } // the right way to append attribute in loops for (size_t i = 3; i <= 10; ++i) { auto item = doc.allocate_node(rapidxml::node_element, "item", nullptr); auto id_attr_val = doc.allocate_string(std::to_string(i).data()); auto port_attr_val = doc.allocate_string(std::to_string(i + 8080).data()); item->append_attribute(doc.allocate_attribute("id", id_attr_val)); item->append_attribute(doc.allocate_attribute("ip", "127.0.0.1")); item->append_attribute(doc.allocate_attribute("port", port_attr_val)); srv->append_node(item); } // The following way is wrong, because the ownership of strings. As follows: // Nodes and attributes produced by RapidXml do not own their name and value strings. // They merely hold the pointers to them. // Care must be taken to ensure that lifetime of the string passed is at least as long as lifetime of the node/attribute. // The easiest way to achieve it is to allocate the string from memory_pool owned by the document. // Use memory_pool::allocate_string() function for this purpose. // It's done this way for speed, but this feels like an car crash waiting to happen. /* for (size_t i = 11; i <= 12; ++i) { auto item = doc.allocate_node(rapidxml::node_element, "item", nullptr); item->append_attribute(doc.allocate_attribute("id", std::to_string(i).data())); item->append_attribute(doc.allocate_attribute("ip", "127.0.0.1")); item->append_attribute(doc.allocate_attribute("port", std::to_string(i + 8080).data())); srv->append_node(item); } */ } // append node element "srv" to "config" root->append_node(srv); write_doc_to_xml(file, doc); } void traverse_doc(rapidxml::xml_document<>& doc) { // traverse doc, then print auto config = doc.first_node("config"); for (auto srv = config->first_node("srv"); srv != nullptr; srv = srv->next_sibling()) { for (auto item = srv->first_node("item"); item != nullptr; item = item->next_sibling()) { std::cout << "<" << item->name() << " "; for (auto attr = item->first_attribute(); attr != nullptr; attr = attr->next_attribute()) { std::cout << attr->name() << "=\"" << attr->value() << "\" "; } if (item->first_node() != nullptr) { std::cout << ">" << item->value() << "</" << item->name() << ">"; } else { std::cout << "/>"; } std::cout << std::endl; } } } void read_xml_by_file(const std::string& file) { rapidxml::file<> fd(file.data()); rapidxml::xml_document<> doc; doc.parse<0>(fd.data()); traverse_doc(doc); } void read_xml_by_stream(const std::string& file) { std::ifstream in(file, std::ios::in); char buf[2048] = {0}; in.read(buf, 2048); rapidxml::xml_document<> doc; doc.parse<0>(buf); traverse_doc(doc); } void modify_xml_node_attr(const std::string& file) { rapidxml::file<> fd(file.data()); rapidxml::xml_document<> doc; doc.parse<rapidxml::parse_no_data_nodes>(fd.data()); auto root = doc.first_node(); auto srv = root->first_node("srv"); for (auto item = srv->first_node("item"); item != nullptr; item = item->next_sibling()) { auto id = item->first_attribute("id"); if (id != nullptr) { if (2 == std::strtol(id->value(), nullptr, 10)) { item->value("Yeah, find it!"); auto ip = item->first_attribute("ip"); if (ip != nullptr) { ip->value("192.168.1.1"); } } } } write_doc_to_xml(file, doc); } void remove_xml_node_attr(const std::string& file) { rapidxml::file<> fd(file.data()); rapidxml::xml_document<> doc; doc.parse<rapidxml::parse_no_data_nodes>(fd.data()); auto root = doc.first_node(); auto srv = root->first_node("srv"); // remove first and last node of "srv" srv->remove_first_node(); srv->remove_last_node(); for (auto item = srv->first_node("item"); item != nullptr; item = item->next_sibling()) { auto id = item->first_attribute("id"); if (id != nullptr) { // remove 2th node's attrs if (2 == std::strtol(id->value(), nullptr, 10)) item->remove_all_attributes(); else if (3 == std::strtol(id->value(), nullptr, 10)) { // remove 3th node's first attr item->remove_first_attribute(); // remove 3th node's last attr item->remove_last_attribute(); // remove 3th node's sub nodes item->remove_all_nodes(); } } } write_doc_to_xml(file, doc); } void insert_xml_node_attr(const std::string& file) { rapidxml::file<> fd(file.data()); rapidxml::xml_document<> doc; doc.parse<rapidxml::parse_no_data_nodes>(fd.data()); auto root = doc.first_node(); auto srv = root->first_node("srv"); for (auto item = srv->first_node("item"); item != nullptr; item = item->next_sibling()) { auto id = item->first_attribute("id"); if (id != nullptr) { // insert new "item" before 2th "item" if (2 == std::strtol(id->value(), nullptr, 10)) { auto new_item = doc.allocate_node(rapidxml::node_element, "item", "11"); // new "item" some attrs new_item->append_attribute(doc.allocate_attribute("id", doc.allocate_string(std::to_string(11).data()))); new_item->append_attribute(doc.allocate_attribute("ip", "192.168.0.1")); new_item->append_attribute(doc.allocate_attribute("port", doc.allocate_string(std::to_string(11 + 8080).data()))); root->insert_node(item, new_item); } } } write_doc_to_xml(file, doc); } } int main() { const std::string file("data/rapidxml.xml"); //create_xml(file); //read_xml_by_file(file); //read_xml_by_stream(file); //modify_xml_node_attr(file); //remove_xml_node_attr(file); insert_xml_node_attr(file); return 0; }
35.667897
134
0.545003
zlecky
e8205f2d64eea0c48d1c378993430260508df213
2,841
cpp
C++
src/Framework/Entities/Components/MeshComponent.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
src/Framework/Entities/Components/MeshComponent.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
src/Framework/Entities/Components/MeshComponent.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
#include "Entities/BaseEntity.h" #include "Entities/ComponentTypeEnum.h" #include "Base.h" #include "Game/Game.h" #include "Assets/AssetManager.h" #include "Maths/Matrix4.h" #include "MeshComponent.h" #include "StringUtils.h" #include "TransformComponent.h" #include "Game/MeshRendererGameComponent.h" namespace CasaEngine { /** * */ MeshComponent::MeshComponent(BaseEntity* pEntity_) : Component(pEntity_, MODEL_3D), m_pModel(nullptr), m_pTransform(nullptr), m_pModelRenderer(nullptr), m_pProgram(nullptr) { } /** * */ MeshComponent::~MeshComponent() { } /** * */ void MeshComponent::Initialize() { m_pTransform = GetEntity()->GetComponentMgr()->GetComponent<TransformComponent>(); CA_ASSERT(m_pTransform != nullptr, "MeshComponent::Initialize() can't find the TransformComponent. Please add it before add a MeshComponent"); m_pModelRenderer = Game::Instance().GetGameComponent<MeshRendererGameComponent>(); CA_ASSERT(m_pModelRenderer != nullptr, "MeshComponent::Initialize() can't find the MeshRendererGameComponent."); } /** * */ Mesh *MeshComponent::GetModel() const { return m_pModel; } /** * */ void MeshComponent::SetModel(Mesh *val) { m_pModel = val; } /** * */ Program *MeshComponent::GetEffect() const { return m_pProgram; } /** * */ void MeshComponent::SetProgram(Program *pVal_) { m_pProgram = pVal_; } /** * */ void MeshComponent::Update(const GameTime& /*gameTime_*/) { } /** * */ void MeshComponent::Draw() { CA_ASSERT(m_pModel != nullptr, "MeshComponent::Draw() : m_pModel is nullptr"); CA_ASSERT(m_pModelRenderer != nullptr, "MeshComponent::Draw() : m_pModelRenderer is nullptr"); Matrix4 mat = m_pTransform->GetWorldMatrix(); m_pModelRenderer->AddModel(m_pModel, mat, m_pProgram); } /** * */ /*void MeshComponent::HandleEvent(const Event* pEvent_) { }*/ /** * */ void MeshComponent::Write(std::ostream& /*os*/) const { } /** * */ void MeshComponent::Read (std::ifstream& /*is*/) { } /** * Editor */ void MeshComponent::ShowDebugWidget() { /* const ImGuiStyle& style = ImGui::GetStyle(); if (ImGui::CollapsingHeader("Static Mesh")) { ImGui::Text("TODO thumbnail"); } if (ImGui::CollapsingHeader("Materials")) { const float widgetWidth = 50.0f; Material *pMat = m_pModel->GetMaterial(); ImGui::PushItemWidth(widgetWidth); ImGui::Text("Texture 0"); ImGui::SameLine(0, style.ItemInnerSpacing.x); ImGui::PushItemWidth(widgetWidth); ImGui::Text("TODO thumbnail"); ImGui::PushItemWidth(widgetWidth); ImGui::Text("Texture 0 rep"); ImGui::SameLine(0, style.ItemInnerSpacing.x); ImGui::PushItemWidth(widgetWidth); ImGui::DragFloat("U", &pMat->m_Texture0Repeat.x, 0.01f); ImGui::SameLine(0, style.ItemInnerSpacing.x); ImGui::PushItemWidth(widgetWidth); ImGui::DragFloat("V", &pMat->m_Texture0Repeat.y, 0.01f); } */ } }
18.095541
143
0.698698
xcasadio
e82374536f7a46934b251770f446679b13c4779b
2,962
cpp
C++
src/sdb/sdbexception.cpp
raghunayak/libaws
e62cbf2887e7b4177ff72df2e50468ab228edfac
[ "Apache-2.0" ]
null
null
null
src/sdb/sdbexception.cpp
raghunayak/libaws
e62cbf2887e7b4177ff72df2e50468ab228edfac
[ "Apache-2.0" ]
null
null
null
src/sdb/sdbexception.cpp
raghunayak/libaws
e62cbf2887e7b4177ff72df2e50468ab228edfac
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008 28msec, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include <libaws/sdbexception.h> #include "sdb/sdbresponse.h" namespace aws { SDBException::SDBException(const QueryErrorResponse& aError) { theErrorMessage = aError.getErrorMessage(); theOrigErrorCode = aError.getErrorCode(); theErrorCode = parseError(theOrigErrorCode); theRequestId = aError.getRequestId(); } SDBException::~SDBException() throw() { } const char* SDBException::what() const throw() { std::stringstream lTmp; lTmp << "Code:" << theOrigErrorCode << " Message:" << theErrorMessage << " RequestId:" << theRequestId; lTmp.str().c_str(); return lTmp.str().c_str(); } SDBException::ErrorCode SDBException::parseError(const std::string& aString) { return SDBException::Unknown; } CreateDomainException::CreateDomainException(const QueryErrorResponse& aError) : SDBException(aError) { } CreateDomainException::~CreateDomainException() throw() { } ListDomainsException::ListDomainsException(const QueryErrorResponse& aError) : SDBException(aError) { } ListDomainsException::~ListDomainsException() throw() { } DeleteDomainException::DeleteDomainException(const QueryErrorResponse& aError) : SDBException(aError) { } DeleteDomainException::~DeleteDomainException() throw() { } DomainMetadataException::DomainMetadataException(const QueryErrorResponse& aError) : SDBException(aError) { } DomainMetadataException::~DomainMetadataException() throw() { } PutAttributesException::PutAttributesException(const QueryErrorResponse& aError) : SDBException(aError) { } PutAttributesException::~PutAttributesException() throw() { } BatchPutAttributesException::BatchPutAttributesException(const QueryErrorResponse& aError) : SDBException(aError) { } BatchPutAttributesException::~BatchPutAttributesException() throw() { } DeleteAttributesException::DeleteAttributesException( const QueryErrorResponse& aError) : SDBException(aError) { } DeleteAttributesException::~DeleteAttributesException() throw() { } GetAttributesException::GetAttributesException( const QueryErrorResponse& aError) : SDBException(aError) { } GetAttributesException::~GetAttributesException() throw() { } QueryException::QueryException( const QueryErrorResponse& aError) : SDBException(aError) { } QueryException::~QueryException() throw() { } } /* namespace aws */
26.212389
105
0.753545
raghunayak
e8238e722daf2da016a799333e05fab06d5629d1
1,296
hpp
C++
src/app/widgets/hex_view.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
null
null
null
src/app/widgets/hex_view.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
2
2021-04-01T21:31:55.000Z
2021-04-06T07:35:04.000Z
src/app/widgets/hex_view.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
null
null
null
#pragma once #include <QTextEdit> #include "../utils/general.hpp" namespace app { class HexView final : public QAbstractScrollArea { Q_OBJECT public: explicit HexView(QWidget* parent); ~HexView() override = default; void setData(uint32_t addressOffset, QByteArray newData); void reset(); void updateViewport(); public: RESTRICT_COPY(HexView); protected: void paintEvent(QPaintEvent* event) override; void keyPressEvent(QKeyEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void mousePressEvent(QMouseEvent* event) override; private: void init(); auto fullSize() const -> QSize; void resetSelection(int position); void setSelection(int position); void ensureVisible(); void setCursorPosition(int position); auto cursorPosition(const QPoint& position) -> int; uint32_t m_addressOffset = 0; std::optional<QByteArray> m_data{}; int m_bytesPerLine = 16; int m_addressCharacterCount = 8; int m_positionAddress = 0; int m_positionHex = 0; int m_positionAscii = 0; int m_characterWidth = 0; int m_characterHeight = 0; int m_selectionBegin = 0; int m_selectionEnd = 0; int m_selectionInit = 0; int m_cursorPosition = 0; }; } // namespace app
22.344828
61
0.698302
Rexagon
e82566042e055fb3cd4de8673fd2a6eb4a0e2bd8
3,013
hpp
C++
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/ConsoleFmt/ConsoleFmt.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/ConsoleFmt/ConsoleFmt.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/ConsoleFmt/ConsoleFmt.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2014 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef SSVU_CORE_CONSOLEFMT #define SSVU_CORE_CONSOLEFMT namespace ssvu { namespace Console { /// @brief Number of styles. constexpr SizeT styleCount{13}; /// @brief Number of colors. constexpr SizeT colorCount{16}; /// @brief Enum class representing all the possible styles. enum class Style : int { None = 0, Bold = 1, Dim = 2, Underline = 3, Blink = 4, ReverseFGBG = 5, Hidden = 6, ResetBold = 7, ResetDim = 8, ResetUnderline = 9, ResetBlink = 10, ResetReverse = 11, ResetHidden = 12 }; /// @brief Enum class representing all the possible colors. enum class Color : int { Default = 0, Black = 1, Red = 2, Green = 3, Yellow = 4, Blue = 5, Magenta = 6, Cyan = 7, LightGray = 8, DarkGray = 9, LightRed = 10, LightGreen = 11, LightYellow = 12, LightBlue = 13, LightMagenta = 14, LightCyan = 15, LightWhite = 16 }; } } // Depending on the OS, the correct implementation file is included. #if defined(SSVU_OS_LINUX) #include "SSVUtils/Core/ConsoleFmt/Internal/ConsoleFmtImplUnix.hpp" #elif defined(SSVU_OS_WINDOWS) #include "SSVUtils/Core/ConsoleFmt/Internal/ConsoleFmtImplWin.hpp" #else #include "SSVUtils/Core/ConsoleFmt/Internal/ConsoleFmtImplNull.hpp" #endif namespace ssvu { namespace Console { /// @brief Returns a format string that resets the current formatting. inline const auto& resetFmt() noexcept { return Internal::getStrResetFmt(); } /// @brief Returns a format string that sets the current style. /// @param mStyle Desired style. (ssvu::Console::Style member) inline const auto& setStyle(Style mStyle) noexcept { return Internal::getStrStyle(mStyle); } /// @brief Returns a format string that sets the current foreground color. /// @param mStyle Desired color. (ssvu::Console::Color member) inline const auto& setColorFG(Color mColor) noexcept { return Internal::getStrColorFG(mColor); } /// @brief Returns a format string that sets the current background color. /// @param mStyle Desired color. (ssvu::Console::Color member) inline const auto& setColorBG(Color mColor) noexcept { return Internal::getStrColorBG(mColor); } /// @brief Returns a format string that clears the console window. inline const auto& clear() noexcept { return Internal::getStrClear(); } /// @brief Returns true if valid console information is available. inline bool isInfoValid() noexcept { return Internal::isInfoValid(); } namespace Info { /// @brief Returns then number of columns of the console screen. inline SizeT getColumnCount() noexcept { return Internal::Info::getColumnCount(); } /// @brief Returns then number of rows of the console screen. inline SizeT getRowCount() noexcept { return Internal::Info::getRowCount(); } } } } #endif
28.158879
98
0.689346
questor
e82a1c5555a09c8b60d36c37239e3a96bcd7d380
1,967
hpp
C++
search/search_engine.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
1
2019-01-11T05:02:05.000Z
2019-01-11T05:02:05.000Z
search/search_engine.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
null
null
null
search/search_engine.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
1
2019-08-09T21:21:09.000Z
2019-08-09T21:21:09.000Z
#pragma once #include "params.hpp" #include "result.hpp" #include "search_query_factory.hpp" #include "geometry/rect2d.hpp" #include "coding/reader.hpp" #include "base/mutex.hpp" #include "std/unique_ptr.hpp" #include "std/string.hpp" #include "std/function.hpp" #include "std/atomic.hpp" class Index; namespace search { class Query; class EngineData; class Engine { typedef function<void (Results const &)> SearchCallbackT; public: typedef Index IndexType; // Doesn't take ownership of @pIndex. Takes ownership of pCategories Engine(IndexType const * pIndex, Reader * pCategoriesR, ModelReaderPtr polyR, ModelReaderPtr countryR, string const & locale, unique_ptr<SearchQueryFactory> && factory); ~Engine(); void SupportOldFormat(bool b); void PrepareSearch(m2::RectD const & viewport); bool Search(SearchParams const & params, m2::RectD const & viewport); string GetCountryFile(m2::PointD const & pt); string GetCountryCode(m2::PointD const & pt); int8_t GetCurrentLanguage() const; private: template <class T> string GetCountryNameT(T const & t); public: string GetCountryName(m2::PointD const & pt); string GetCountryName(string const & id); bool GetNameByType(uint32_t type, int8_t lang, string & name) const; m2::RectD GetCountryBounds(string const & file) const; void ClearViewportsCache(); void ClearAllCaches(); private: static const int RESULTS_COUNT = 30; void SetRankPivot(SearchParams const & params, m2::RectD const & viewport, bool viewportSearch); void SetViewportAsync(m2::RectD const & viewport); void SearchAsync(); void EmitResults(SearchParams const & params, Results & res); threads::Mutex m_searchMutex, m_updateMutex; atomic_flag m_isReadyThread; SearchParams m_params; m2::RectD m_viewport; unique_ptr<Query> m_pQuery; unique_ptr<SearchQueryFactory> m_pFactory; unique_ptr<EngineData> const m_pData; }; } // namespace search
23.141176
100
0.737163
bowlofstew
e82f4a12e54a57a96ed43b5bab19981b6d0f88c5
1,123
cpp
C++
data/dailyCodingProblem987.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem987.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem987.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Given an array of numbers and an index i, return the index of the nearest larger number of the number at index i, where distance is measured in array indices. For example, given [4, 1, 3, 5, 6] and index 0, you should return 3. If two distances to larger numbers are the equal, then return any one of them. If the array at i doesn't have a nearest larger integer, then return null. Follow-up: If you can preprocess the array, can you do this in constant time? */ int closestDistance(int arr[], int n, int index){ int left = index, right = index; while(left > 0 || right < n-1){ left--; right++; if(left >= 0 && arr[left] > arr[index]) return left; if(right < n && arr[right] > arr[index]) return right; } return -1; } // main function int main(){ int arr[] = {4, 1, 3, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); cout << closestDistance(arr, n, 0) << "\n"; cout << closestDistance(arr, n, 1) << "\n"; cout << closestDistance(arr, n, 2) << "\n"; cout << closestDistance(arr, n, 3) << "\n"; cout << closestDistance(arr, n, 4) << "\n"; return 0; }
28.075
96
0.647373
vidit1999
e83283e63ec6602d7edfa256e4288b4ee4cc5634
9,619
cpp
C++
TAO/examples/CSD_Strategy/ThreadPool5/ServerApp.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/examples/CSD_Strategy/ThreadPool5/ServerApp.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/examples/CSD_Strategy/ThreadPool5/ServerApp.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: ServerApp.cpp 84563 2009-02-23 08:13:54Z johnnyw $ #include "ServerApp.h" #include "OrbTask.h" #include "FooServantList.h" #include "ClientTask.h" #include "OrbShutdownTask.h" #include "ace/Get_Opt.h" #include "tao/CSD_ThreadPool/CSD_TP_Strategy.h" #include "tao/Intrusive_Ref_Count_Handle_T.h" // To force static load the service. #include "tao/PI/PI.h" #include "tao/CSD_ThreadPool/CSD_ThreadPool.h" ServerApp::ServerApp() : ior_filename_(ACE_TEXT("foo")), num_servants_(1), num_csd_threads_ (1), num_clients_(1), num_orb_threads_ (1), collocated_test_ (0), servant_to_deactivate_ (-1) { } ServerApp::~ServerApp() { } int ServerApp::run (int argc, ACE_TCHAR* argv[]) { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); // Parse the command-line args for this application. // * Raises -1 if problems are encountered. // * Returns 1 if the usage statement was explicitly requested. // * Returns 0 otherwise. int result = this->parse_args (argc, argv); if (result != 0) { return result; } TheOrbShutdownTask::instance()->orb (orb.in ()); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); if (CORBA::is_nil(obj.in())) { ACE_ERROR((LM_ERROR, "(%P|%t) Failed to resolve initial ref for 'RootPOA'.\n")); throw TestException(); } PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in()); if (CORBA::is_nil(root_poa.in())) { ACE_ERROR((LM_ERROR, "(%P|%t) Failed to narrow obj ref to POA interface.\n")); throw TestException(); } PortableServer::POAManager_var poa_manager = root_poa->the_POAManager(); // Create the child POA. CORBA::PolicyList policies(1); policies.length(1); policies[0] = root_poa->create_id_assignment_policy(PortableServer::USER_ID); PortableServer::POA_var child_poa = root_poa->create_POA("ChildPoa", poa_manager.in(), policies); if (CORBA::is_nil(child_poa.in())) { ACE_ERROR((LM_ERROR, "(%P|%t) ERROR [ServerApp::run()]: " "Failed to create the child POA.\n")); throw TestException(); } policies[0]->destroy (); // Create the thread pool servant dispatching strategy object, and // hold it in a (local) smart pointer variable. TAO_Intrusive_Ref_Count_Handle<TAO::CSD::TP_Strategy> csd_tp_strategy = new TAO::CSD::TP_Strategy(); csd_tp_strategy->set_num_threads(this->num_csd_threads_); // Tell the strategy to apply itself to the child poa. if (csd_tp_strategy->apply_to(child_poa.in()) == false) { ACE_ERROR((LM_ERROR, "(%P|%t) ERROR [ServerApp::run()]: " "Failed to apply custom dispatching strategy to child poa.\n")); throw TestException(); } FooServantList servants(this->ior_filename_.c_str(), this->num_servants_, this->num_clients_, this->collocated_test_, this->servant_to_deactivate_, orb.in()); // Activate the POA Manager before start the ClientTask thread so that // we do not need coordinate the ClientTask and main thread for the // collocated test. poa_manager->activate(); servants.create_and_activate(orb.in (), child_poa.in()); ACE_DEBUG((LM_DEBUG, "(%P|%t) ServerApp is ready.\n")); // If the num_orb_threads_ is exactly one, then just use the current // (mainline) thread to run the ORB event loop. if (this->num_orb_threads_ == 1) { // Since the num_orb_threads_ is exactly one, we just use the current // (mainline) thread to run the ORB event loop. orb->run(); } else { // The num_orb_threads_ is greater than 1, so we will use an OrbTask // (active object) to run the ORB event loop in (num_orb_threads_ - 1) // threads. We use the current (mainline) thread as the other thread // running the ORB event loop. OrbTask orb_task(orb.in(), this->num_orb_threads_ - 1); // Activate the OrbTask worker threads if (orb_task.open() != 0) { ACE_ERROR((LM_ERROR, "(%P|%t) Failed to open the OrbTask.\n")); throw TestException(); } // This will use the current (mainline) thread to run the ORB event loop. orb->run(); // Now that the current thread has unblocked from running the orb, // make sure to wait for all of the worker threads to complete. orb_task.wait(); } ACE_DEBUG((LM_DEBUG, "(%P|%t) ServerApp is waiting for OrbShutdownTask.\n")); TheOrbShutdownTask::instance()->wait (); // Sleep for 2 second to let the done() two-way call complete // before cleanup. ACE_OS::sleep (2); if (collocated_test_) { servants.collocated_client ()->wait (); } ACE_DEBUG((LM_DEBUG, "(%P|%t) ServerApp is destroying the Root POA.\n")); // Tear-down the root poa and orb. root_poa->destroy(1, 1); ACE_DEBUG((LM_DEBUG, "(%P|%t) ServerApp is destroying the ORB.\n")); orb->destroy(); ACE_DEBUG((LM_DEBUG, "(%P|%t) ServerApp has completed running successfully.\n")); return 0; } int ServerApp::parse_args(int argc, ACE_TCHAR* argv[]) { this->exe_name_ = argv[0]; ACE_Get_Opt get_opts(argc, argv, ACE_TEXT("p:s:c:t:l:d:n:")); int c; int tmp; while ((c = get_opts()) != -1) { int parse_error = 0; switch (c) { case 'p': this->ior_filename_ = get_opts.opt_arg(); break; case 's': tmp = ACE_OS::atoi(get_opts.opt_arg()); if (tmp < 1) { ACE_ERROR((LM_ERROR, "(%P|%t) Error. -s must be followed by an integer " "value greater than 0.\n")); parse_error = 1; } this->num_servants_ = tmp; break; case 'c': tmp = ACE_OS::atoi(get_opts.opt_arg()); if (tmp < 1) { ACE_ERROR((LM_ERROR, "(%P|%t) Error. -c must be followed by an integer " "value greater than 0.\n")); parse_error = 1; } this->num_clients_ = tmp; break; case 't': tmp = ACE_OS::atoi(get_opts.opt_arg()); if (tmp < 1) { ACE_ERROR((LM_ERROR, "(%P|%t) Error. -t must be followed by an integer " "value greater than 0.\n")); parse_error = 1; } this->num_orb_threads_ = tmp; break; case 'n': tmp = ACE_OS::atoi(get_opts.opt_arg()); if (tmp < 1) { ACE_ERROR((LM_ERROR, "(%P|%t) Error. -n must be followed by an integer " "value greater than 0.\n")); parse_error = 1; } this->num_csd_threads_ = tmp; break; case 'l': tmp = ACE_OS::atoi(get_opts.opt_arg()); if (tmp < 0) { ACE_ERROR((LM_ERROR, "(%P|%t) Error. -l must be followed by an integer " "value greater than -1.\n")); parse_error = 1; } this->collocated_test_ = tmp; break; case 'd': tmp = ACE_OS::atoi(get_opts.opt_arg()); if (tmp < 0) { ACE_ERROR((LM_ERROR, "(%P|%t) Error. -d must be followed by an integer " "value >= 0.\n")); parse_error = 1; } this->servant_to_deactivate_ = tmp; break; case '?': this->usage_statement(); return 1; default: this->usage_statement(); return -1; } if (parse_error != 0) { this->usage_statement(); return parse_error; } } // The deadlock will happen with the collocated callback test // when we have one working thread, so create at least one more // working thread would resolve the deadlock. if (this->collocated_test_ == 1 && this->num_csd_threads_ == 1) { ACE_ERROR((LM_ERROR, "(%P|%t) Error. The num_csd_threads_ should be " ">= 1.\n")); return -1; } return 0; } void ServerApp::usage_statement() { ACE_ERROR((LM_ERROR, "(%P|%t) usage: %s\n" "\t[-p <ior_filename_prefix>]\n" "\t[-s <num_servants>]\n" "\t[-c <num_clients>]\n" "\t[-n <num_csd_threads>]\n" "\t[-t <num_orb_threads>]\n" "\t[-l <collocation_test>]\n" "\t[-d <servant_to_deactivate>]\n" "Default ior_filename_prefix is 'foo'.\n" "Default num_servants is 1.\n" "Default num_clients is 1.\n" "Default num_orb_threads is 1.\n" "Default collocation_test flag is 0.\n" "Default servant_to_deactivate is -1 means not deactivate servant.\n" " 0 means deactivate all servant.\n" " >0 means the index (servant_to_deactivate-1) of the servant in the servant list.\n", this->exe_name_.c_str ())); }
28.291176
102
0.544027
cflowe
e832d4fb2d0fe78dc887506718cabdfaeda2dd4b
503
cpp
C++
JammaLib/src/actions/DoubleAction.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
JammaLib/src/actions/DoubleAction.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
JammaLib/src/actions/DoubleAction.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
#include "DoubleAction.h" using namespace actions; using base::ActionSender; using base::ActionReceiver; DoubleAction::DoubleAction(double value) : _value(value), Action() { } DoubleAction::~DoubleAction() { } double DoubleAction::Value() const { return _value; } DoubleActionUndo::DoubleActionUndo(double value, std::weak_ptr<ActionSender> sender) : _value(value), ActionUndo(sender) { } DoubleActionUndo::~DoubleActionUndo() { } double DoubleActionUndo::Value() const { return _value; }
13.594595
48
0.747515
malisimo
e83551b6fccba0088ef3735bd74e8ac99ca171e6
287
cc
C++
material.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
material.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
material.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
#include "material.hpp" Material::Material(float r, float g, float b, int computeColorType): computeColorType(computeColorType){ color[0] = r; color[1] = g; color[2] = b; } int Material::getComputeColorType(){ return computeColorType; } float* Material::GetColor(){ return color; }
22.076923
104
0.724739
KXue
e838091afc5d9e4b405895d692f78c1121b5c18a
15,878
cpp
C++
Visual Studio/Others/Calculateur d'adresses IP/IP_CalculatorDlg.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
1
2022-03-22T14:41:15.000Z
2022-03-22T14:41:15.000Z
Visual Studio/Others/Calculateur d'adresses IP/IP_CalculatorDlg.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
Visual Studio/Others/Calculateur d'adresses IP/IP_CalculatorDlg.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
// IP_CalculatorDlg.cpp : implementation file // #include "stdafx.h" #include "IP_Calculator.h" #include "IP_CalculatorDlg.h" #include "IP_Properties.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CIP_CalculatorDlg dialog CIP_CalculatorDlg::CIP_CalculatorDlg(CWnd* pParent /*=NULL*/) : CDialog(CIP_CalculatorDlg::IDD, pParent) { //{{AFX_DATA_INIT(CIP_CalculatorDlg) m_strIP1 = _T(""); m_strIP2 = _T(""); m_strIP3 = _T(""); m_strIP4 = _T(""); m_strBit = _T(""); m_strUserP = _T(""); m_strUserSR = _T(""); m_strMask1 = _T(""); m_strMask2 = _T(""); m_strMask3 = _T(""); m_strMask4 = _T(""); m_strMaxP = _T(""); m_strMaxSR = _T(""); m_strPas = _T(""); m_strPlage1 = _T(""); m_strPlage2 = _T(""); m_strNbBitsP = _T(""); m_strNbBitsSR = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CIP_CalculatorDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CIP_CalculatorDlg) DDX_Control(pDX, IDC_NBBITSSR, m_ctrlNbBitsSR); DDX_Control(pDX, IDC_NBBITSP, m_ctrlNbBitsP); DDX_Control(pDX, IDC_PLAGE2, m_ctrlPlage2); DDX_Control(pDX, IDC_PLAGE1, m_ctrlPlage1); DDX_Control(pDX, IDC_PAS, m_ctrlPas); DDX_Control(pDX, IDC_MAXSR, m_ctrlMaxSR); DDX_Control(pDX, IDC_MAXP, m_ctrlMaxP); DDX_Control(pDX, IDC_MASK4, m_ctrlMask4); DDX_Control(pDX, IDC_MASK3, m_ctrlMask3); DDX_Control(pDX, IDC_MASK2, m_ctrlMask2); DDX_Control(pDX, IDC_MASK1, m_ctrlMask1); DDX_Control(pDX, IDC_USERSR, m_ctrlUserSR); DDX_Control(pDX, IDC_USERP, m_ctrlUserP); DDX_Control(pDX, IDC_NBBITS, m_ctrlBit); DDX_Control(pDX, IDC_IP4, m_ctrlIP4); DDX_Control(pDX, IDC_IP3, m_ctrlIP3); DDX_Control(pDX, IDC_IP2, m_ctrlIP2); DDX_Control(pDX, IDC_IP1, m_ctrlIP1); DDX_Text(pDX, IDC_IP1, m_strIP1); DDX_Text(pDX, IDC_IP2, m_strIP2); DDX_Text(pDX, IDC_IP3, m_strIP3); DDX_Text(pDX, IDC_IP4, m_strIP4); DDX_Text(pDX, IDC_NBBITS, m_strBit); DDX_Text(pDX, IDC_USERP, m_strUserP); DDX_Text(pDX, IDC_USERSR, m_strUserSR); DDX_Text(pDX, IDC_MASK1, m_strMask1); DDX_Text(pDX, IDC_MASK2, m_strMask2); DDX_Text(pDX, IDC_MASK3, m_strMask3); DDX_Text(pDX, IDC_MASK4, m_strMask4); DDX_Text(pDX, IDC_MAXP, m_strMaxP); DDX_Text(pDX, IDC_MAXSR, m_strMaxSR); DDX_Text(pDX, IDC_PAS, m_strPas); DDX_Text(pDX, IDC_PLAGE1, m_strPlage1); DDX_Text(pDX, IDC_PLAGE2, m_strPlage2); DDX_Text(pDX, IDC_NBBITSP, m_strNbBitsP); DDX_Text(pDX, IDC_NBBITSSR, m_strNbBitsSR); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CIP_CalculatorDlg, CDialog) //{{AFX_MSG_MAP(CIP_CalculatorDlg) ON_WM_SYSCOMMAND() ON_WM_DESTROY() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_RESET, OnReset) ON_EN_CHANGE(IDC_IP1, OnChangeIp1) ON_EN_CHANGE(IDC_IP2, OnChangeIp2) ON_EN_CHANGE(IDC_IP3, OnChangeIp3) ON_EN_CHANGE(IDC_IP4, OnChangeIp4) ON_EN_CHANGE(IDC_NBBITS, OnChangeNbbits) ON_EN_CHANGE(IDC_USERP, OnChangeUserp) ON_EN_CHANGE(IDC_USERSR, OnChangeUsersr) ON_BN_CLICKED(IDC_CALCULATE, OnCalculate) ON_EN_KILLFOCUS(IDC_NBBITS, OnKillfocusNbbits) ON_BN_CLICKED(IDC_OPTIONS, OnOptions) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CIP_CalculatorDlg message handlers BOOL CIP_CalculatorDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here m_ctrlIP1.SetLimitText(3); m_ctrlIP2.SetLimitText(3); m_ctrlIP3.SetLimitText(3); m_ctrlIP4.SetLimitText(3); m_ctrlBit.SetLimitText(2); m_ctrlUserP.SetLimitText(10); m_ctrlUserSR.SetLimitText(10); m_ctrlMask1.SetLimitText(3); m_ctrlMask2.SetLimitText(3); m_ctrlMask3.SetLimitText(3); m_ctrlMask4.SetLimitText(3); m_ctrlMaxP.SetLimitText(10); m_ctrlMaxSR.SetLimitText(10); m_ctrlPas.SetLimitText(2); return TRUE; // return TRUE unless you set the focus to a control } void CIP_CalculatorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } void CIP_CalculatorDlg::OnDestroy() { WinHelp(0L, HELP_QUIT); CDialog::OnDestroy(); } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CIP_CalculatorDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CIP_CalculatorDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CIP_CalculatorDlg::OnReset() { // TODO: Add your control notification handler code here m_strIP1 = _T(""); m_strIP2 = _T(""); m_strIP3 = _T(""); m_strIP4 = _T(""); m_strBit = _T(""); m_strUserP = _T(""); m_strUserSR = _T(""); m_strMask1 = _T(""); m_strMask2 = _T(""); m_strMask3 = _T(""); m_strMask4 = _T(""); m_strMaxP = _T(""); m_strMaxSR = _T(""); m_strPas = _T(""); m_strPlage1 = _T(""); m_strPlage2 = _T(""); m_strNbBitsP=_T(""); m_strNbBitsSR=_T(""); m_ctrlIP1.SetWindowText(_T("")); m_ctrlIP2.SetWindowText(_T("")); m_ctrlIP3.SetWindowText(_T("")); m_ctrlIP4.SetWindowText(_T("")); m_ctrlBit.SetWindowText(_T("")); m_ctrlUserP.SetWindowText(_T("")); m_ctrlUserSR.SetWindowText(_T("")); m_ctrlMask1.SetWindowText(_T("")); m_ctrlMask2.SetWindowText(_T("")); m_ctrlMask3.SetWindowText(_T("")); m_ctrlMask4.SetWindowText(_T("")); m_ctrlMaxP.SetWindowText(_T("")); m_ctrlMaxSR.SetWindowText(_T("")); m_ctrlPas.SetWindowText(_T("")); m_ctrlNbBitsP.SetWindowText(_T("")); m_ctrlNbBitsSR.SetWindowText(_T("")); m_ctrlPlage1.SetWindowText(_T("")); m_ctrlPlage2.SetWindowText(_T("")); IP_Adr.IP_Reset(); } void CIP_CalculatorDlg::OnChangeIp1() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlIP1.GetWindowText(m_strIP1); DWORD Result=ConvertStringToDWORD(m_strIP1); if (Result>255) { m_strIP1=_T("255"); m_ctrlIP1.SetWindowText(m_strIP1); Result=255; } IP_Adr.SetIP1(Result); } void CIP_CalculatorDlg::OnChangeIp2() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlIP2.GetWindowText(m_strIP2); DWORD Result=ConvertStringToDWORD(m_strIP2); if (Result>255) { m_strIP2=_T("255"); m_ctrlIP2.SetWindowText(m_strIP2); Result=255; } IP_Adr.SetIP2(Result); } void CIP_CalculatorDlg::OnChangeIp3() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlIP3.GetWindowText(m_strIP3); DWORD Result=ConvertStringToDWORD(m_strIP3); if (Result>255) { m_strIP3=_T("255"); m_ctrlIP3.SetWindowText(m_strIP3); Result=255; } IP_Adr.SetIP3(Result); } void CIP_CalculatorDlg::OnChangeIp4() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlIP4.GetWindowText(m_strIP4); DWORD Result=ConvertStringToDWORD(m_strIP4); if (Result>255) { m_strIP4=_T("255"); m_ctrlIP4.SetWindowText(m_strIP4); Result=255; } IP_Adr.SetIP4(Result); } void CIP_CalculatorDlg::OnChangeNbbits() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlBit.GetWindowText(m_strBit); DWORD Result=ConvertStringToDWORD(m_strBit); IP_Adr.SetBitMask(Result); } void CIP_CalculatorDlg::OnChangeUserp() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlUserP.GetWindowText(m_strUserP); if (m_strUserP.GetLength()==10) { CString FirstEntry=m_strUserP.GetAt(0); CString LastEntry=m_strUserP.GetAt(9); DWORD FirstNumber=ConvertStringToDWORD(FirstEntry); DWORD LastNumber=ConvertStringToDWORD(LastEntry); DWORD Entry=ConvertStringToDWORD(m_strUserP); if (LastNumber>2 || FirstNumber>1) { m_strUserP=_T("1073741822"); m_ctrlUserP.SetWindowText(m_strUserP); } else if (Entry>1073741822) { m_strUserP=_T("1073741822"); m_ctrlUserP.SetWindowText(m_strUserP); } } IP_Adr.SetNbPostes(ConvertStringToDWORD(m_strUserP)); } void CIP_CalculatorDlg::OnChangeUsersr() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlUserSR.GetWindowText(m_strUserSR); if (m_strUserSR.GetLength()==10) { CString FirstEntry=m_strUserSR.GetAt(0); CString LastEntry=m_strUserSR.GetAt(9); DWORD FirstNumber=ConvertStringToDWORD(FirstEntry); DWORD LastNumber=ConvertStringToDWORD(LastEntry); DWORD Entry=ConvertStringToDWORD(m_strUserSR); if (LastNumber>2 || FirstNumber>1) { m_strUserSR=_T("1073741822"); m_ctrlUserSR.SetWindowText(m_strUserSR); } else if (Entry>1073741822) { m_strUserSR=_T("1073741822"); m_ctrlUserSR.SetWindowText(m_strUserSR); } } IP_Adr.SetNbReseaux(ConvertStringToDWORD(m_strUserSR)); } void CIP_CalculatorDlg::OnCalculate() { // TODO: Add your control notification handler code here IP_Adr.IP_Calculate(); m_ctrlBit.SetWindowText(IP_Adr.strBit); m_ctrlIP1.SetWindowText(IP_Adr.strIP1); m_ctrlIP2.SetWindowText(IP_Adr.strIP2); m_ctrlIP3.SetWindowText(IP_Adr.strIP3); m_ctrlIP4.SetWindowText(IP_Adr.strIP4); m_ctrlMask1.SetWindowText(IP_Adr.str_Mask1); m_ctrlMask2.SetWindowText(IP_Adr.str_Mask2); m_ctrlMask3.SetWindowText(IP_Adr.str_Mask3); m_ctrlMask4.SetWindowText(IP_Adr.str_Mask4); m_ctrlMaxP.SetWindowText(IP_Adr.strMaxP); m_ctrlNbBitsP.SetWindowText(IP_Adr.strNbBitsP); m_ctrlMaxSR.SetWindowText(IP_Adr.strMaxSR); m_ctrlNbBitsSR.SetWindowText(IP_Adr.strNbBitsSR); m_ctrlPas.SetWindowText(IP_Adr.strPas); m_ctrlPlage1.SetWindowText(IP_Adr.str_Plage1); m_ctrlPlage2.SetWindowText(IP_Adr.str_Plage2); m_ctrlUserP.SetWindowText(IP_Adr.str_UserP); m_ctrlUserSR.SetWindowText(IP_Adr.str_UserSR); IP_Adr.IP_Flush(); m_strIP1 = _T(""); m_strIP2 = _T(""); m_strIP3 = _T(""); m_strIP4 = _T(""); m_strBit = _T(""); m_strUserP = _T(""); m_strUserSR = _T(""); m_strMask1 = _T(""); m_strMask2 = _T(""); m_strMask3 = _T(""); m_strMask4 = _T(""); m_strMaxP = _T(""); m_strMaxSR = _T(""); m_strPas = _T(""); m_strPlage1 = _T(""); m_strPlage2 = _T(""); m_strNbBitsP=_T(""); m_strNbBitsSR=_T(""); } void CIP_CalculatorDlg::OnKillfocusNbbits() { // TODO: Add your control notification handler code here DWORD Bit=IP_Adr.GetBitMask(); m_ctrlBit.GetWindowText(m_strBit); DWORD Result=ConvertStringToDWORD(m_strBit); if (Result!=Bit) { m_strBit.Format(_T("%d"), Bit); m_ctrlBit.SetWindowText(m_strBit); } } void CIP_CalculatorDlg::OnOptions() { // TODO: Add your control notification handler code here CIP_Properties Options(IP_Adr.GetUnlock()); if (Options.DoModal()==IDOK) { if (Options.m_boolBitMaskEntry==TRUE) { IP_SetWarning(War_UnlockMask); IP_Adr.SetUnlock(TRUE); } else IP_Adr.SetUnlock(FALSE); } }
28.053004
77
0.659466
Jeanmilost
e83c52514866dc6a83663fc12008a7ea911212b2
4,785
cpp
C++
src/Chronicles/entity/item.cpp
gregtour/chronicles-game
813a33c6d484bff59f210d81a3252bef2e0d3ea2
[ "CC0-1.0" ]
1
2015-04-28T15:12:14.000Z
2015-04-28T15:12:14.000Z
src/Chronicles/entity/item.cpp
gregtour/chronicles-game
813a33c6d484bff59f210d81a3252bef2e0d3ea2
[ "CC0-1.0" ]
null
null
null
src/Chronicles/entity/item.cpp
gregtour/chronicles-game
813a33c6d484bff59f210d81a3252bef2e0d3ea2
[ "CC0-1.0" ]
null
null
null
#include "item.h" #include "../../engine/engine.h" #include "../main.h" #include <string> #include <sstream> #include "particles/spark.h" CItem::CItem() { #ifdef LOW_RESOLUTION_TEXTURES mTexture = CManagedTexture::Load( &gResourceManager, "data/low/crate.bmp" ); #else mTexture = CManagedTexture::Load( &gResourceManager, "data/crate.bmp" ); #endif } CItem::~CItem() { CManagedTexture::Unload( &gResourceManager, mTexture ); } void CItem::Update( float dt ) { }; void CItem::Render() { { float mX = mObject->GetPosition().x; float mZ = mObject->GetPosition().y; float x, y, z; gCamera->GetPosition( &x, &y, &z ); if ( ((x-mX)*(x-mX) + (z-mZ)*(z-mZ)) > VIEW_DISTANCE_SQUARED ) return; } gLevel->Light( mObject->GetPosition() ); glEnable( GL_TEXTURE_2D ); mTexture->BindTexture(); float r = ((CPCircle*)mObject)->GetRadius() * 0.9f; glTranslatef( mObject->GetPosition().x, r, mObject->GetPosition().y ); /* Temporary Code, Draw A Cube as a Placeholder */ glBegin(GL_QUADS); // Draw The Cube Using quads glColor3f( 0.7f, 0.7f, 0.7f ); glNormal3f( 0.0f, 1.0f, 0.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r, r,-r); // Top Right Of The Quad (Top) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r, r,-r); // Top Left Of The Quad (Top) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r, r, r); // Bottom Left Of The Quad (Top) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r, r, r); // Bottom Right Of The Quad (Top) // glColor3f(1.0f,0.5f,0.0f); // Color Orange glNormal3f( 0.0f, -1.0f, 0.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r,-r, r); // Top Right Of The Quad (Bottom) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r,-r, r); // Top Left Of The Quad (Bottom) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r,-r,-r); // Bottom Left Of The Quad (Bottom) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r,-r,-r); // Bottom Right Of The Quad (Bottom) // glColor3f(1.0f,0.0f,0.0f); // Color Red glNormal3f( 0.0f, 0.0f, 1.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r, r, r); // Top Right Of The Quad (Front) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r, r, r); // Top Left Of The Quad (Front) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r,-r, r); // Bottom Left Of The Quad (Front) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r,-r, r); // Bottom Right Of The Quad (Front) // glColor3f(1.0f,1.0f,0.0f); // Color Yellow glNormal3f( 0.0f, 0.0f, -1.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r,-r,-r); // Top Right Of The Quad (Back) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r,-r,-r); // Top Left Of The Quad (Back) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r, r,-r); // Bottom Left Of The Quad (Back) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r, r,-r); // Bottom Right Of The Quad (Back) /// glColor3f(0.0f,0.0f,1.0f); // Color Blue glNormal3f( -1.0f, 0.0f, 0.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f(-r, r, r); // Top Right Of The Quad (Left) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r, r,-r); // Top Left Of The Quad (Left) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r,-r,-r); // Bottom Left Of The Quad (Left) glTexCoord2f( 0.0f, 1.0f ); glVertex3f(-r,-r, r); // Bottom Right Of The Quad (Left) // glColor3f(1.0f,0.0f,1.0f); // Color Violet glNormal3f( 1.0f, 0.0f, 0.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r, r,-r); // Top Right Of The Quad (Right) glTexCoord2f( 1.0f, 0.0f ); glVertex3f( r, r, r); // Top Left Of The Quad (Right) glTexCoord2f( 1.0f, 1.0f ); glVertex3f( r,-r, r); // Bottom Left Of The Quad (Right) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r,-r,-r); // Bottom Right Of The Quad (Right) glEnd(); // End Drawing The Cube glDisable( GL_TEXTURE_2D ); }; void CItem::Hit( IPhysicalObj* by, float force ) { SVector v; mObject->GetPosition().Difference( &by->GetPhysicalObject()->GetPosition(), &v ); SPoint pointOfContact = mObject->GetPosition(); v.Scale( -0.5f ); pointOfContact.Translate( &v ); gEntities.Add( new CSpark( pointOfContact.x, 3.0f, pointOfContact.y, 1.0f, 1.0f, 1.0f, 2.0f, 1, 4.4f, 15.0f, "data/wood.bmp" ) ); v.Flip(); v.Normalize(); v.Scale( force * by->GetPhysicalObject()->GetMass() / mObject->GetMass() ); mObject->SetVelocity( &v ); } void CItem::LogState() { std::string state; if ( mObject ) { std::stringstream stream; stream << "X: " << mObject->GetPosition().x << " Y: " << mObject->GetPosition().y << " XSP: " << mObject->GetVelocity().x << " YSP " << mObject->GetVelocity().y; state = stream.str(); } else { state = "No Physical Existance"; } gLog.LogItem( new CLogMessage( state ) ); }
29.720497
99
0.597492
gregtour
e83e4cfc9d55a52aef101d9e4b082195740796cf
2,052
cpp
C++
Pandemic/Sources/Markers.cpp
prince-chrismc/Pandemic
7f25b4c3af9451f16c50230a643db496a768f393
[ "MIT" ]
null
null
null
Pandemic/Sources/Markers.cpp
prince-chrismc/Pandemic
7f25b4c3af9451f16c50230a643db496a768f393
[ "MIT" ]
15
2017-03-17T20:06:19.000Z
2017-10-16T21:31:32.000Z
Pandemic/Sources/Markers.cpp
prince-chrismc/Pandemic
7f25b4c3af9451f16c50230a643db496a768f393
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2017 Chris McArthur, prince.chrismc(at)gmail(dot)com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Markers.h" InfectionRate::Builder& InfectionRate::Builder::ParseInfectionRate(std::string loaded) { switch (loaded.at(0)) { case '0': m_Position = 0; break; case '1': m_Position = 1; break; case '2': m_Position = 2; break; case '3': m_Position = 3; break; case '4': m_Position = 4; break; case '5': m_Position = 5; break; case '6': m_Position = 6; break; default: m_Position = 0; break; } return *this; } OutbreakMarker::Builder& OutbreakMarker::Builder::ParseOutbreakMarker(std::string loaded) { switch (loaded.at(0)) { case '0': m_Position = 0; break; case '1': m_Position = 1; break; case '2': m_Position = 2; break; case '3': m_Position = 3; break; case '4': m_Position = 4; break; case '5': m_Position = 5; break; case '6': m_Position = 6; break; case '7': m_Position = 7; break; default: m_Position = 0; break; } return *this; }
21.829787
89
0.71345
prince-chrismc
e83ed40c166d0e8869269544d9cdf9e547d9491d
2,518
cc
C++
ash/system/tracing_notification_controller.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ash/system/tracing_notification_controller.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ash/system/tracing_notification_controller.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/tracing_notification_controller.h" #include "ash/public/cpp/ash_features.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/model/system_tray_model.h" #include "ui/base/l10n/l10n_util.h" #include "ui/message_center/message_center.h" #include "ui/message_center/public/cpp/notification.h" using message_center::MessageCenter; using message_center::Notification; namespace ash { namespace { const char kNotifierId[] = "ash.tracing"; } // namespace // static const char TracingNotificationController::kNotificationId[] = "chrome://slow"; TracingNotificationController::TracingNotificationController() : model_(Shell::Get()->system_tray_model()->tracing()) { DCHECK(features::IsSystemTrayUnifiedEnabled()); model_->AddObserver(this); OnTracingModeChanged(); } TracingNotificationController::~TracingNotificationController() { model_->RemoveObserver(this); } void TracingNotificationController::OnTracingModeChanged() { // Return if the state doesn't change. if (was_tracing_ == model_->is_tracing()) return; if (model_->is_tracing()) CreateNotification(); else RemoveNotification(); was_tracing_ = model_->is_tracing(); } void TracingNotificationController::CreateNotification() { // TODO(tetsui): Update resource strings according to UX. std::unique_ptr<Notification> notification = Notification::CreateSystemNotification( message_center::NOTIFICATION_TYPE_SIMPLE, kNotificationId, l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_TRACING), base::string16() /* message */, gfx::Image(), base::string16() /* display_source */, GURL(), message_center::NotifierId( message_center::NotifierId::SYSTEM_COMPONENT, kNotifierId), message_center::RichNotificationData(), nullptr, kSystemMenuTracingIcon, message_center::SystemNotificationWarningLevel::NORMAL); notification->set_pinned(true); MessageCenter::Get()->AddNotification(std::move(notification)); } void TracingNotificationController::RemoveNotification() { message_center::MessageCenter::Get()->RemoveNotification(kNotificationId, false /* by_user */); } } // namespace ash
32.701299
80
0.727164
zipated
e83f3a74126459b24d57a9a5d57ab38fa32ac0e0
2,470
cpp
C++
mainapp/Classes/Common/Components/RawTouchBody.cpp
JaagaLabs/GLEXP-Team-KitkitSchool
f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0
[ "Apache-2.0" ]
45
2019-05-16T20:49:31.000Z
2021-11-05T21:40:54.000Z
mainapp/Classes/Common/Components/RawTouchBody.cpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
123
2019-05-28T14:03:04.000Z
2019-07-12T04:23:26.000Z
pehlaschool/Classes/Common/Components/RawTouchBody.cpp
maqsoftware/Pehla-School-Hindi
61aeae0f1d91952b44eaeaff5d2f6ec1d5aa3c43
[ "Apache-2.0" ]
29
2019-05-16T17:49:26.000Z
2021-12-30T16:36:24.000Z
// // RawTouchBody.cpp on Aug 16, 2016 // TodoSchool // // Copyright (c) 2016 Enuma, Inc. All rights reserved. // See LICENSE.md for more details. // #include "RawTouchBody.h" using namespace std; RawTouchBody::RawTouchBody() : Listener(nullptr) { } bool RawTouchBody::init() { if (!Super::init()) { return false; } setName(defaultName()); return true; } string RawTouchBody::defaultName() { return "RawTouchBody"; } void RawTouchBody::onEnter() { auto Owner = getOwner(); if (!Owner) { return; } Listener = ([&] { auto It = EventListenerTouchOneByOne::create(); It->setSwallowTouches(true); It->onTouchBegan = [this](Touch* T, Event* E) { auto Owner = getOwner(); if (!Owner || !OnTouchDidBegin) { // NB(xenosoz, 2016): Catch the event even if the proper handler isn't installed (yet). const bool CATCH_THE_EVENT = true; return CATCH_THE_EVENT; } Owner->retain(); bool R = false; for (bool B : OnTouchDidBegin(T, E)) R = R || B; Owner->release(); return R; }; It->onTouchMoved = [this](Touch* T, Event* E) { auto Owner = getOwner(); if (!Owner || !OnTouchDidMove) { return; } Owner->retain(); OnTouchDidMove(T, E); Owner->release(); }; It->onTouchEnded = [this](Touch* T, Event* E) { auto Owner = getOwner(); if (!Owner || !OnTouchDidEnd) { return; } Owner->retain(); OnTouchDidEnd(T, E); Owner->release(); }; It->onTouchCancelled = [this](Touch* T, Event* E) { auto Owner = getOwner(); if (!Owner || !OnTouchDidCancel) { return; } Owner->retain(); OnTouchDidCancel(T, E); Owner->release(); }; auto Dispatcher = Owner->getEventDispatcher(); if (Dispatcher) Dispatcher->addEventListenerWithSceneGraphPriority(It, Owner); return It; }()); } void RawTouchBody::onExit() { auto Owner = getOwner(); if (!Owner) { return; } auto Dispatcher = Owner->getEventDispatcher(); if (Dispatcher) Dispatcher->removeEventListener(Listener); Listener = nullptr; }
24.7
103
0.516599
JaagaLabs
e83f40a8a2af17a5c25da13f190872a94202a862
1,912
cpp
C++
example/example.cpp
bobsayshilol/tser
5d7bd971bbf8837f3d4d67005565b21a1ede8bfd
[ "BSL-1.0" ]
null
null
null
example/example.cpp
bobsayshilol/tser
5d7bd971bbf8837f3d4d67005565b21a1ede8bfd
[ "BSL-1.0" ]
null
null
null
example/example.cpp
bobsayshilol/tser
5d7bd971bbf8837f3d4d67005565b21a1ede8bfd
[ "BSL-1.0" ]
null
null
null
// Licensed under the Boost License <https://opensource.org/licenses/BSL-1.0>. // SPDX-License-Identifier: BSL-1.0 #include <cassert> #include <optional> #include <tser/tser.hpp> enum class Item : char { NONE = 0, RADAR = 'R', TRAP = 'T', ORE = 'O' }; namespace x { struct Point { DEFINE_SERIALIZABLE(Point,x,y) int x = 0, y = 0; }; } struct Robot { DEFINE_SERIALIZABLE(Robot,point,item) x::Point point; std::optional<Item> item; }; int main() { auto robot = Robot{ x::Point{3,4}, Item::RADAR }; std::cout << robot << '\n'; // prints { "Robot": {"point" : { "Point": {"x" : 3, "y" : 4}}, "item" : R}} std::cout << Robot() << '\n'; // prints { "Robot": {"point" : { "Point": {"x" : 3, "y" : 4}}, "item" : {null}}} tser::BinaryArchive ba; ba.save(robot); std::cout << ba; //prints BggBUg to the console via base64 encoding (base64 means only printable characters are used) //this way it's quickly possible to log entire objects to the console or logfiles //due to varint encoding only 6 printable characters are needed, although the struct is 12 bytes in size //e.g. a size_t in the range of 0-127 will only take 1 byte (before the base 64 encoding) } void test() { //if we construct BinaryArchive with a string it will decode it and initialized it's internal buffer with it //so it's basically one or two lines of code to load a complex object into a test and start using it tser::BinaryArchive ba2("BggBUg"); auto loadedRobot = ba2.load<Robot>(); auto robot = Robot{ x::Point{3,4}, Item::RADAR }; //all the comparision operators are implemented, so I could directly use std::set<Robot> bool areEqual = (robot == loadedRobot) && !(robot != loadedRobot) && !(robot < loadedRobot); (void)areEqual; std::cout << loadedRobot; //prints{ "Robot": {"point" : { "Point": {"x" : 3, "y" : 4}}, "item" : R} } }
39.833333
121
0.630753
bobsayshilol
e84050b7842f238712585081c2b3e9f79308eeac
1,234
cpp
C++
src/ecs/components/CurseComponent.cpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
null
null
null
src/ecs/components/CurseComponent.cpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
12
2019-05-22T12:22:44.000Z
2019-06-15T17:31:04.000Z
src/ecs/components/CurseComponent.cpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
1
2019-06-18T12:57:58.000Z
2019-06-18T12:57:58.000Z
/* ** EPITECH PROJECT, 2019 ** bomberman ** File description: ** CurseComponent.cpp */ #include <iostream> #include "CurseComponent.hpp" #include "../Exceptions.hpp" ECS::CurseComponent::CurseComponent(Sound::SoundSystem &soundSystem): Component("Curse"), soundSystem(soundSystem), effect(NONE), timeLeft(0) {} ECS::CurseComponent::CurseComponent(unsigned id, ECS::Ressources &ressources, std::istream &stream): CurseComponent(ressources.soundSystem) { unsigned tmp; std::string terminator; stream >> tmp; this->effect = static_cast<CurseEffect>(tmp); stream >> this->timeLeft; stream >> terminator; if (terminator != "EndOfComponent") throw InvalidSerializedStringException("The component terminator was not found"); } bool ECS::CurseComponent::giveCurse(CurseEffect eff, int time, bool force, bool playSound) { if (this->timeLeft > 0 && !force) return false; this->effect = eff; this->timeLeft = time; if (playSound) this->soundSystem.playSound("skull"); return true; } std::ostream& ECS::CurseComponent::serialize(std::ostream &stream) const { return stream << this->effect << " " << this->timeLeft << " " << "EndOfComponent"; }
25.708333
100
0.679092
Gegel85
e840ec70db85f7c504f638759011e6799d264b1d
1,485
hpp
C++
framework/renderer.hpp
Montag55/Das-raytracer
356eac6a2ad6fe4f09015a94df9bbafe490f9585
[ "MIT" ]
null
null
null
framework/renderer.hpp
Montag55/Das-raytracer
356eac6a2ad6fe4f09015a94df9bbafe490f9585
[ "MIT" ]
null
null
null
framework/renderer.hpp
Montag55/Das-raytracer
356eac6a2ad6fe4f09015a94df9bbafe490f9585
[ "MIT" ]
null
null
null
#ifndef BUW_RENDERER_HPP #define BUW_RENDERER_HPP #include "color.hpp" #include "pixel.hpp" #include "ppmwriter.hpp" #include <string> #include <glm/glm.hpp> #include "scene.hpp" #include "hit.hpp" #include "ray.hpp" class Renderer { public: Renderer(Scene const& scene, unsigned int width, unsigned int height, std::string const& ofile); void render(); void write(Pixel const& p); Hit ohit(glm::mat4x4 const& trans_mat, Ray const& ray) const; Color raytrace(Ray const& ray, unsigned int depth); Color render_antialiase(Ray rayman, float antialiase_faktor, unsigned int depth); Color tonemap(Color tempcolor); void reflectedlight(Color & clr, Hit const& Hitze, Ray const& ray, unsigned int depth); void ambientlight(Color & clr, Color const& ka); void pointlight(Color & clr, std::shared_ptr<Light> const& light, Hit const& Hitze, Ray const& ray); void diffuselight(Color & clr, Hit const& Hitze, std::shared_ptr<Light> const& light, Ray const& raylight); void specularlight(Color & clr, Hit const& Hitze, std::shared_ptr<Light> const& light, Ray const& raylight, Ray const& ray); void refractedlight(Color & clr, Hit const& Hitze, Ray const& ray, unsigned int depth); inline std::vector<Color> const& colorbuffer() const { return m_colorbuffer; } private: Scene m_scene; unsigned int m_width; unsigned int m_height; std::vector<Color> m_colorbuffer; std::string m_outfile; PpmWriter m_ppm; }; #endif // #ifndef BUW_RENDERER_HPP
32.282609
127
0.731313
Montag55
e84142438f26ecbc346c8d53dbba0b938e61eea8
11,594
cpp
C++
vpp/vaapipostprocess_scaler_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
89
2015-01-09T10:31:13.000Z
2018-01-18T12:48:21.000Z
vpp/vaapipostprocess_scaler_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
626
2015-01-12T00:01:26.000Z
2018-01-23T18:58:58.000Z
vpp/vaapipostprocess_scaler_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
104
2015-01-12T04:02:09.000Z
2017-12-28T08:27:42.000Z
/* * Copyright 2016 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // // The unittest header must be included before va_x11.h (which might be included // indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers // define 'Bool' and 'None' preprocessor types. Gtest uses the same names // to define some struct placeholders. Thus, this creates a compile conflict // if X defines them before gtest. Hence, the include order requirement here // is the only fix for this right now. // // See bug filed on gtest at https://github.com/google/googletest/issues/371 // for more details. // #include "common/factory_unittest.h" // primary header #include "vaapipostprocess_scaler.h" #include "common/log.h" #include "vaapi/vaapidisplay.h" #include "vaapi/VaapiUtils.h" namespace YamiMediaCodec { typedef void (*VppTestFunction)(VaapiPostProcessScaler& scaler, const SharedPtr<VideoFrame>& src, const SharedPtr<VideoFrame>& dest); struct FrameDestroyer { FrameDestroyer(DisplayPtr display) : m_display(display) { } void operator()(VideoFrame* frame) { VASurfaceID id = (VASurfaceID)frame->surface; checkVaapiStatus(vaDestroySurfaces(m_display->getID(), &id, 1), "vaDestroySurfaces"); delete frame; } private: DisplayPtr m_display; }; //TODO: refact it with decoder base SharedPtr<VideoFrame> createVideoFrame(const DisplayPtr& display, uint32_t width, uint32_t height, uint32_t fourcc) { SharedPtr<VideoFrame> frame; VASurfaceAttrib attrib; attrib.flags = VA_SURFACE_ATTRIB_SETTABLE; attrib.type = VASurfaceAttribPixelFormat; attrib.value.type = VAGenericValueTypeInteger; attrib.value.value.i = fourcc; uint32_t rtformat; if (fourcc == VA_FOURCC_BGRX || fourcc == VA_FOURCC_BGRA) { rtformat = VA_RT_FORMAT_RGB32; ERROR("rgb32"); } else { rtformat = VA_RT_FORMAT_YUV420; } VASurfaceID id; VAStatus status = vaCreateSurfaces(display->getID(), rtformat, width, height, &id, 1, &attrib, 1); if (status != VA_STATUS_SUCCESS) { ERROR("create surface failed fourcc = %d", fourcc); return frame; } frame.reset(new VideoFrame, FrameDestroyer(display)); memset(frame.get(), 0, sizeof(VideoFrame)); frame->surface = (intptr_t)id; return frame; } class VaapiPostProcessScalerTest : public FactoryTest<IVideoPostProcess, VaapiPostProcessScaler> { public: static void checkFilter(const VaapiPostProcessScaler& scaler, VppParamType type) { if (type == VppParamTypeDenoise) { EXPECT_TRUE(bool(scaler.m_denoise.filter)); } else if (type == VppParamTypeSharpening) { EXPECT_TRUE(bool(scaler.m_sharpening.filter)); } } static void checkColorBalanceFilter(VaapiPostProcessScaler& scaler, VppColorBalanceMode mode) { if (COLORBALANCE_NONE != mode) { EXPECT_TRUE(bool(scaler.m_colorBalance[mode].filter)); } } protected: /* invoked by gtest before the test */ virtual void SetUp() { return; } /* invoked by gtest after the test */ virtual void TearDown() { return; } static void checkFilterCaps(VaapiPostProcessScaler& scaler, VAProcFilterType filterType, int32_t minLevel, int32_t maxLevel, int32_t level) { SharedPtr<VAProcFilterCap> caps; float value; EXPECT_TRUE(scaler.mapToRange(value, level, minLevel, maxLevel, filterType, caps)); ASSERT_TRUE(bool(caps)); EXPECT_LT(caps->range.min_value, caps->range.max_value); EXPECT_LE(caps->range.min_value, value); EXPECT_LE(value, caps->range.max_value); } static void checkMapToRange() { float value; VaapiPostProcessScaler scaler; EXPECT_TRUE(scaler.mapToRange(value, 0, 64, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX)); EXPECT_FLOAT_EQ(0, value); EXPECT_TRUE(scaler.mapToRange(value, 0, 64, DENOISE_LEVEL_MAX, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX)); EXPECT_FLOAT_EQ(64, value); EXPECT_FALSE(scaler.mapToRange(value, 0, 64, DENOISE_LEVEL_NONE, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX)); NativeDisplay nDisplay; memset(&nDisplay, 0, sizeof(nDisplay)); ASSERT_EQ(YAMI_SUCCESS, scaler.setNativeDisplay(nDisplay)); checkFilterCaps(scaler, VAProcFilterNoiseReduction, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX, DENOISE_LEVEL_MIN); checkFilterCaps(scaler, VAProcFilterNoiseReduction, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX, DENOISE_LEVEL_MAX); checkFilterCaps(scaler, VAProcFilterSharpening, SHARPENING_LEVEL_MIN, SHARPENING_LEVEL_MAX, SHARPENING_LEVEL_MIN); checkFilterCaps(scaler, VAProcFilterSharpening, SHARPENING_LEVEL_MIN, SHARPENING_LEVEL_MAX, SHARPENING_LEVEL_MAX); } static void vppTest(VppTestFunction func) { NativeDisplay nDisplay; memset(&nDisplay, 0, sizeof(nDisplay)); VaapiPostProcessScaler scaler; ASSERT_EQ(YAMI_SUCCESS, scaler.setNativeDisplay(nDisplay)); SharedPtr<VideoFrame> src = createVideoFrame(scaler.m_display, 320, 240, YAMI_FOURCC_NV12); SharedPtr<VideoFrame> dest = createVideoFrame(scaler.m_display, 480, 272, YAMI_FOURCC_NV12); ASSERT_TRUE(src && dest); func(scaler, src, dest); } }; #define VAAPIPOSTPROCESS_SCALER_TEST(name) \ TEST_F(VaapiPostProcessScalerTest, name) VAAPIPOSTPROCESS_SCALER_TEST(Factory) { FactoryKeys mimeTypes; mimeTypes.push_back(YAMI_VPP_SCALER); doFactoryTest(mimeTypes); } VAAPIPOSTPROCESS_SCALER_TEST(mapToRange) { checkMapToRange(); } template <class P> void VppSetParams(VaapiPostProcessScaler& scaler, const SharedPtr<VideoFrame>& src, const SharedPtr<VideoFrame>& dest, P& params, int32_t& value, int32_t min, int32_t max, int32_t none, VppParamType type) { memset(&params, 0, sizeof(P)); params.size = sizeof(P); value = min; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(type, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); value = max; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(type, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); value = none; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(type, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); value = (min + max) / 2; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(type, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); VaapiPostProcessScalerTest::checkFilter(scaler, type); } void VppColorBalanceSetParams(VaapiPostProcessScaler& scaler, const SharedPtr<VideoFrame>& src, const SharedPtr<VideoFrame>& dest, VppColorBalanceMode mode) { VPPColorBalanceParameter params; memset(&params, 0, sizeof(params)); params.size = sizeof(params); if (COLORBALANCE_COUNT == mode) { params.mode = mode; EXPECT_EQ(YAMI_UNSUPPORTED, scaler.setParameters(VppParamTypeColorBalance, &params)); return; } if (COLORBALANCE_NONE == mode) { params.mode = mode; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); return; } params.mode = mode; params.level = COLORBALANCE_LEVEL_MIN; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); params.mode = mode; params.level = COLORBALANCE_LEVEL_MAX; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); params.mode = mode; params.level = COLORBALANCE_LEVEL_NONE; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); params.mode = mode; params.level = COLORBALANCE_LEVEL_MIN - 10; EXPECT_EQ(YAMI_DRIVER_FAIL, scaler.setParameters(VppParamTypeColorBalance, &params)); params.mode = mode; params.level = COLORBALANCE_LEVEL_MAX + 10; EXPECT_EQ(YAMI_DRIVER_FAIL, scaler.setParameters(VppParamTypeColorBalance, &params)); params.mode = mode; params.level = (COLORBALANCE_LEVEL_MIN + COLORBALANCE_LEVEL_MAX) / 2; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); VaapiPostProcessScalerTest::checkColorBalanceFilter(scaler, mode); } void VppDenoise(VaapiPostProcessScaler& scaler, const SharedPtr<VideoFrame>& src, const SharedPtr<VideoFrame>& dest) { VPPDenoiseParameters params; VppSetParams(scaler, src, dest, params, params.level, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX, DENOISE_LEVEL_NONE, VppParamTypeDenoise); } VAAPIPOSTPROCESS_SCALER_TEST(Denoise) { vppTest(VppDenoise); } void VppSharpening(VaapiPostProcessScaler& scaler, const SharedPtr<VideoFrame>& src, const SharedPtr<VideoFrame>& dest) { VPPSharpeningParameters params; VppSetParams(scaler, src, dest, params, params.level, SHARPENING_LEVEL_MIN, SHARPENING_LEVEL_MAX, SHARPENING_LEVEL_NONE, VppParamTypeSharpening); } VAAPIPOSTPROCESS_SCALER_TEST(Sharpening) { vppTest(VppSharpening); } void VppDeinterlace(VaapiPostProcessScaler& scaler, const SharedPtr<VideoFrame>& src, const SharedPtr<VideoFrame>& dest) { VPPDeinterlaceParameters params; memset(&params, 0, sizeof(params)); params.size = sizeof(params); params.mode = DEINTERLACE_MODE_BOB; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeDeinterlace, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); params.mode = DEINTERLACE_MODE_NONE; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeDeinterlace, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); params.mode = DEINTERLACE_MODE_WEAVE; EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeDeinterlace, &params)); EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); } VAAPIPOSTPROCESS_SCALER_TEST(Deinterlace) { vppTest(VppDeinterlace); } void VppColorBalance(VaapiPostProcessScaler& scaler, const SharedPtr<VideoFrame>& src, const SharedPtr<VideoFrame>& dest) { VppParamWireframe wireFrameParams; EXPECT_EQ(YAMI_INVALID_PARAM, scaler.setParameters(VppParamTypeColorBalance, &wireFrameParams)); VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_NONE); VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_HUE); VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_SATURATION); VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_BRIGHTNESS); VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_CONTRAST); VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_COUNT); } VAAPIPOSTPROCESS_SCALER_TEST(Colorbalance) { vppTest(VppColorBalance); } }
34.608955
130
0.727273
genisysram
e84314662841bfc5ff1becb4c52ec4f15c329cf7
3,924
cc
C++
modules/external_packages/src/alien/kernels/petsc/data_structure/PETScMatrix.cc
cedricga91/alien_legacy_plugins-1
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
4
2021-12-02T09:06:38.000Z
2022-01-10T14:22:35.000Z
modules/external_packages/src/alien/kernels/petsc/data_structure/PETScMatrix.cc
cedricga91/alien_legacy_plugins-1
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
null
null
null
modules/external_packages/src/alien/kernels/petsc/data_structure/PETScMatrix.cc
cedricga91/alien_legacy_plugins-1
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
7
2021-11-23T14:50:58.000Z
2022-03-17T13:23:07.000Z
#include "PETScMatrix.h" /* Author : havep at Wed Jul 18 14:46:45 2012 * Generated by createNew */ #include "petscmat.h" #include <alien/kernels/petsc/data_structure/PETScVector.h> #include <alien/kernels/petsc/PETScBackEnd.h> #include <alien/kernels/petsc/data_structure/PETScInternal.h> #include <alien/core/impl/MultiMatrixImpl.h> /*---------------------------------------------------------------------------*/ namespace Alien { /*---------------------------------------------------------------------------*/ PETScMatrix::PETScMatrix(const MultiMatrixImpl* multi_impl) : IMatrixImpl(multi_impl, AlgebraTraits<BackEnd::tag::petsc>::name()) , m_internal(nullptr) { const auto& row_space = multi_impl->rowSpace(); const auto& col_space = multi_impl->colSpace(); if (row_space.size() != col_space.size()) throw Arccore::FatalErrorException("MTL matrix must be square"); } /*---------------------------------------------------------------------------*/ PETScMatrix::~PETScMatrix() { delete m_internal; } /*---------------------------------------------------------------------------*/ bool PETScMatrix::initMatrix(const int local_size, const int local_offset, const int global_size, Arccore::ConstArrayView<Arccore::Integer> diag_lineSizes, Arccore::ConstArrayView<Arccore::Integer> offdiag_lineSizes, const bool parallel) { int ierr = 0; // code d'erreur de retour if (m_internal) { delete m_internal; } m_internal = new MatrixInternal(parallel); Arccore::Integer max_diag_size = 0, max_offdiag_size = 0; // -- Matrix -- #ifdef PETSC_HAVE_MATVALID PetscTruth valid_flag; ierr += MatValid(m_internal->m_internal, &valid_flag); if (valid_flag == PETSC_TRUE) return (ierr == 0); #endif /* PETSC_HAVE_MATVALID */ ierr += MatCreate(PETSC_COMM_WORLD, &m_internal->m_internal); ierr += MatSetSizes( m_internal->m_internal, local_size, local_size, global_size, global_size); ierr += MatSetType(m_internal->m_internal, m_internal->m_type); if (parallel) { // Use parallel structures ierr += MatMPIAIJSetPreallocation(m_internal->m_internal, max_diag_size, diag_lineSizes.unguardedBasePointer(), max_offdiag_size, offdiag_lineSizes.unguardedBasePointer()); } else { // Use sequential structures ierr += MatSeqAIJSetPreallocation( m_internal->m_internal, max_diag_size, diag_lineSizes.unguardedBasePointer()); } // Offsets are implicit with PETSc, we can to check that // they are compatible with the expected behaviour PetscInt low; ierr += MatGetOwnershipRange(m_internal->m_internal, &low, PETSC_NULL); if (low != local_offset) return false; return (ierr == 0); } /*---------------------------------------------------------------------------*/ bool PETScMatrix::addMatrixValues( const int row, const int ncols, const int* cols, const Arccore::Real* values) { int ierr = MatSetValues(m_internal->m_internal, 1, &row, ncols, cols, values, ADD_VALUES); return (ierr == 0); } /*---------------------------------------------------------------------------*/ bool PETScMatrix::setMatrixValues( const int row, const int ncols, const int* cols, const Arccore::Real* values) { int ierr = MatSetValues(m_internal->m_internal, 1, &row, ncols, cols, values, INSERT_VALUES); return (ierr == 0); } /*---------------------------------------------------------------------------*/ bool PETScMatrix::assemble() { int ierr = 0; ierr += MatAssemblyBegin(m_internal->m_internal, MAT_FINAL_ASSEMBLY); ierr += MatAssemblyEnd(m_internal->m_internal, MAT_FINAL_ASSEMBLY); return (ierr == 0); } /*---------------------------------------------------------------------------*/ } // namespace Alien /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ //#pragma clang diagnostic pop
31.645161
88
0.579001
cedricga91
e8478ad4a2fc4afe2d3df14414bc84c4fec3ada9
3,207
cpp
C++
vendor/ZMQ/tests/test_stream_exceeds_buffer.cpp
theKAKAN/SqMod
0c4c78da6e5f2741b0f65215fe08b84232a02fec
[ "MIT" ]
10
2018-06-12T17:56:02.000Z
2020-04-06T12:02:16.000Z
vendor/ZMQ/tests/test_stream_exceeds_buffer.cpp
theKAKAN/SqMod
0c4c78da6e5f2741b0f65215fe08b84232a02fec
[ "MIT" ]
45
2016-06-19T09:31:22.000Z
2020-04-16T08:54:13.000Z
vendor/ZMQ/tests/test_stream_exceeds_buffer.cpp
theKAKAN/SqMod
0c4c78da6e5f2741b0f65215fe08b84232a02fec
[ "MIT" ]
16
2016-07-07T06:48:35.000Z
2020-05-24T09:43:52.000Z
/* Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <string.h> SETUP_TEARDOWN_TESTCONTEXT void test_stream_exceeds_buffer () { const int msgsize = 8193; char sndbuf[msgsize] = "\xde\xad\xbe\xef"; unsigned char rcvbuf[msgsize]; char my_endpoint[MAX_SOCKET_STRING]; int server_sock = bind_socket_resolve_port ("127.0.0.1", "0", my_endpoint); void *zsock = test_context_socket (ZMQ_STREAM); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (zsock, my_endpoint)); int client_sock = TEST_ASSERT_SUCCESS_RAW_ERRNO (accept (server_sock, NULL, NULL)); TEST_ASSERT_SUCCESS_RAW_ERRNO (close (server_sock)); TEST_ASSERT_EQUAL_INT (msgsize, send (client_sock, sndbuf, msgsize, 0)); zmq_msg_t msg; zmq_msg_init (&msg); int rcvbytes = 0; while (rcvbytes == 0) // skip connection notification, if any { TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&msg, zsock, 0)); // peerid TEST_ASSERT_TRUE (zmq_msg_more (&msg)); rcvbytes = TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&msg, zsock, 0)); TEST_ASSERT_FALSE (zmq_msg_more (&msg)); } // for this test, we only collect the first chunk // since the corruption already occurs in the first chunk memcpy (rcvbuf, zmq_msg_data (&msg), zmq_msg_size (&msg)); zmq_msg_close (&msg); test_context_socket_close (zsock); close (client_sock); TEST_ASSERT_GREATER_OR_EQUAL (4, rcvbytes); // notice that only the 1st byte gets corrupted TEST_ASSERT_EQUAL_UINT (0xef, rcvbuf[3]); TEST_ASSERT_EQUAL_UINT (0xbe, rcvbuf[2]); TEST_ASSERT_EQUAL_UINT (0xad, rcvbuf[1]); TEST_ASSERT_EQUAL_UINT (0xde, rcvbuf[0]); } int main () { UNITY_BEGIN (); RUN_TEST (test_stream_exceeds_buffer); return UNITY_END (); }
35.241758
79
0.720299
theKAKAN
e848d5692fdcd65984e89793ebd611ed9f7627f7
1,516
hpp
C++
headers/permutations.hpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
headers/permutations.hpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
headers/permutations.hpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
#ifndef __EULER_PERMUTATIONS_INCLUDED_ #define __EULER_PERMUTATIONS_INCLUDED_ #include <string> #include <utility> #include <algorithm> #include <climits> #include "types.hpp" namespace euler { bool nextPermutation(std::string& n) { // 1. Find largest x s.t. P[x]<P[x+1] int x = -1; for (int i = n.length() - 2; i >= 0; i--) { if (n[i] < n[i + 1]) { x = i; break; } } // 1a. If there is no such x, then this was the last permutation. if (x == -1) { return false; } // 2. Find largest y s.t. P[x]<P[y] int y = -1; for (int i = n.length() - 1; i >= 0; i--) { if (n[x] < n[i]) { y = i; break; } } // 3. Swap P[x] and P[y] std::swap(n[x], n[y]); // 4. Reverse P[x+1]..P[n] std::reverse(n.begin() + x + 1, n.end()); return true; } template <class T> bool nextPermutation(T& n) { std::string permutation = std::to_string(n); bool retVal = nextPermutation(permutation); n = toInt<T>(permutation); return retVal; } bool isPermutation(const std::string& a, const std::string& b) { unsigned char charsA[UCHAR_MAX] = {0}, charsB[UCHAR_MAX] = {0}; for (auto c : a) { charsA[(unsigned char)c]++; } for (auto c : b) { charsB[(unsigned char)c]++; } for (int i = 0; i < UCHAR_MAX; i++) { if (charsA[i] != charsB[i]) { return false; } } return true; } bool isPermutation(int a, int b) { return isPermutation(std::to_string(a), std::to_string(b)); } } #endif // __EULER_PERMUTATIONS_INCLUDED_
18.95
67
0.574538
DouglasSherk
e84ac2b511865e84a1a899443b0702db763b0b3b
3,795
cc
C++
stapl_release/test/containers/heap/heap_view.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/test/containers/heap/heap_view.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/test/containers/heap/heap_view.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. */ #include <stapl/containers/array/array.hpp> #include <stapl/containers/heap/heap.hpp> #include <stapl/algorithms/algorithm.hpp> #include <stapl/views/array_view.hpp> #include <stapl/views/heap_view.hpp> #include "../../test_report.hpp" using namespace stapl; using namespace std; template <typename C, typename It> void print(C c) { cout << get_location_id() <<"] " ; for (It it = c.begin(); it != c.end(); ++it) cout << *it << ", " ; } stapl::exit_code stapl_main(int argc, char* argv[]) { typedef heap_base_container<size_t,std::less<size_t>, heap_base_container_traits <size_t,std::less<size_t> > > bc_type; typedef bc_type::value_type value_type; typedef balanced_partition< indexed_domain<size_t> > partitioner_type; typedef mapper<size_t> mapper_type; typedef heap_traits<size_t, std::less<size_t>, partitioner_type, mapper_type> heap_traits_type; typedef heap<size_t, std::less<size_t>, partitioner_type, mapper_type, heap_traits_type> heap_type; typedef heap_view<heap_type> heap_view_type; typedef heap_view<heap_type>::iterator heap_view_iterator; if (argc < 2) { std::cerr << "usage: exe n (n > 2)" << std::endl; exit(1); } size_t n = atol(argv[1]); bool passed = true; stapl::array<size_t> parray(n); stapl::array_view<stapl::array<size_t> > v(parray); for (size_t i=0; i < n ; ++i) parray[i] = n-i; heap_type heap_empty; heap_type heap1(v); heap_type heap3(v); heap_view_type heap_view_full(heap1); heap_view_type heap_view_full_copy(heap1); heap_view_type heap_view_full2(heap3); heap_view_type heap_view_empty(heap_empty); heap_view_type heap_view_make(heap_empty); STAPL_TEST_REPORT(passed,"Testing constructors"); passed = true; int count =0; for (heap_view_iterator it = heap_view_full.begin(); it != heap_view_full.end(); ++it) { ++count; } n = n + count*0; //Fool compiler warning ... count useless STAPL_TEST_REPORT(passed,"Testing global iteration"); passed = true; if (heap_view_full.size() != n) passed = false; STAPL_TEST_REPORT(passed,"Testing size"); passed = true; if (heap_view_full.top() != stapl::max_value(v,std::less<size_t>())) passed = false; STAPL_TEST_REPORT(passed,"Testing top"); passed = true; if (heap_view_full.empty() || !heap_view_empty.empty()) passed = false; STAPL_TEST_REPORT(passed,"Testing empty"); passed = true; heap_view_empty.push((rand() % 10) + 10); if (heap_view_empty.size() == 0) passed = false; heap_view_empty.push(5); heap_view_empty.push(50); if (heap_view_empty.top() != 50) passed = false; STAPL_TEST_REPORT(passed,"Testing push"); passed = true; value_type keep = heap_view_full.top(); if (heap_view_full.pop() != keep) passed = false; if (heap_view_full.pop() == keep) passed = false; STAPL_TEST_REPORT(passed,"Testing pop"); passed = true; heap_view_make.make(v); if (!heap_view_make.is_heap() || heap_view_make.size() != (v.size() + get_num_locations()*3) || heap_view_make.top() != stapl::max_value(v,std::less<size_t>())) passed = false; STAPL_TEST_REPORT(passed,"Testing make(view)"); return EXIT_SUCCESS; }
30.853659
77
0.655336
parasol-ppl
e84c4df6e679a44c7a091eac3534e0115d1dc8cb
523
cpp
C++
mainRun.cpp
LvWenHan/lwh
7f7a219623433e5c06cecbaab72b3cd658e1b94b
[ "Apache-2.0" ]
2
2021-03-20T04:25:41.000Z
2021-03-20T06:52:36.000Z
mainRun.cpp
LvWenHan/lwh
7f7a219623433e5c06cecbaab72b3cd658e1b94b
[ "Apache-2.0" ]
null
null
null
mainRun.cpp
LvWenHan/lwh
7f7a219623433e5c06cecbaab72b3cd658e1b94b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main(){ int a, b, t,sumA = 0,i = 1; cin >> a >> b >> t; // sumA += a; while(true) { if (sumA + a >= t) { //xxx } if (b * i + b >= t) { //xx } } for(;!(sumA + a >= t || b * i + b >= t);i++){ if(sumA <= b * i){ sumA += a; } cout << sumA << ' ' << b * i << endl; } if(sumA == b * i){ cout << "tongshi" << endl; } else if((t - sumA) > b * i){ cout << "tuzi" << endl; } else{ cout << "wugui" << endl; } return 0; }
14.135135
46
0.414914
LvWenHan
e84fcb0f450d6c2671513615d0c92097e748bdd6
426
cpp
C++
llvm-7.0.0.src/tools/clang/test/CodeGenCXX/override-bit-field-layout.cpp
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
115
2018-02-01T18:56:44.000Z
2022-03-21T13:23:00.000Z
llvm-7.0.0.src/tools/clang/test/CodeGenCXX/override-bit-field-layout.cpp
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
51
2019-10-23T11:55:08.000Z
2021-12-21T06:32:11.000Z
llvm-7.0.0.src/tools/clang/test/CodeGenCXX/override-bit-field-layout.cpp
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
55
2018-02-01T07:11:49.000Z
2022-03-04T01:20:23.000Z
// RUN: %clang_cc1 -w -fdump-record-layouts-simple -foverride-record-layout=%S/Inputs/override-bit-field-layout.layout %s | FileCheck %s // CHECK: Type: struct S1 // CHECK: FieldOffsets: [0, 11] struct S1 { short a : 3; short b : 5; }; // CHECK: Type: struct S2 // CHECK: FieldOffsets: [64] struct S2 { virtual ~S2() = default; short a : 3; }; void use_structs() { S1 s1s[sizeof(S1)]; S2 s2s[sizeof(S2)]; }
20.285714
136
0.63615
sillywalk
e8564601e804a4e213b9d08e0b77a3bcde4722e6
4,318
hpp
C++
gamess/libqc/src/distributed/slice.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
gamess/libqc/src/distributed/slice.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
gamess/libqc/src/distributed/slice.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
#ifndef _DISTRIBUTED_SLICE_HPP_ #define _DISTRIBUTED_SLICE_HPP_ #include <boost/utility.hpp> #include "util/slice.hpp" namespace distributed { namespace slice { template<typename T> struct range { typedef T index_type; typedef std::vector<index_type> index_vector; typedef size_t size_type; template<typename U, size_t N> range(const U (&from)[N], const U (&to)[N]) : from_(to_vector(from)), to_(to_vector(to)) {} index_type* c_from() const { return c_array(from_); } index_type* c_to() const { return c_array(to_); } template<typename U, size_t N> static index_vector to_vector(const U (&index)[N]) { index_vector v(N); std::copy(index, index + N, v.begin()); return v; } const index_vector& from() const { return from_; } const index_vector& to() const { return to_; } size_type size(index_type i) const { return to_[i] - from_[i] + 1; } private: const index_vector from_, to_; static index_type* c_array(const index_vector &v) { return const_cast< index_type*>(&v[0]); } }; template<class Array> struct operators { typedef typename Array::value_type value_type; typedef typename Array::pointer pointer; typedef typename Array::const_pointer const_pointer; typedef typename Array::index_type index_type; typedef range<index_type> range_type; operators(Array &A, const range_type &range) : A_(A), range_(range) {} void operator=(value_type t) { if (t == value_type(0)) apply(&Array::zeroPatch); else apply(&Array::fillPatch, t); } void operator+=(value_type t) { apply(&Array::addConstantPatch, t); } void operator-=(value_type t) { operator+=(-t); } void operator*=(value_type t) { apply(&Array::scalePatch, t); } void operator/=(value_type t) { operator*=(value_type(1)/t); } protected: void assign(const_pointer p, const index_type *ld) { A_.put(from(), to(), const_cast<pointer>(p), const_cast<index_type*>(ld)); } template<class F> void apply(F f) { (A_.*f)(from(), to()); } template<class F> void apply(F f, value_type v) { (A_.*f)(from(), to(), &v); } private: Array &A_; const range_type &range_; index_type* from() const { return range_.c_from(); } index_type* to() const { return range_.c_to(); } }; } template<typename T, size_t M, class Array = distributed::array_base<T> > struct array_slice : slice::range<typename Array::index_type>, slice::operators<Array> { typedef slice::range<typename Array::index_type> range_base; typedef slice::operators<Array> operators_base; template<typename U, size_t N> array_slice(Array &A, const U (&from)[N], const U (&to)[N]) : range_base(from, to), operators_base(A, *this) {} template<typename U, size_t N> array_slice(Array &A, const boost::array<U,N> &from, const boost::array<U,N> &to) : range_base(from.elems, to.elems), operators_base(A, *this) {} using operators_base::operator=; }; template<typename T, class Array> struct array_slice<T, 2, Array> : slice::range<typename Array::index_type>, slice::operators<Array> { typedef size_t size_type; typedef typename Array::index_type index_type; typedef typename Array::const_pointer const_pointer; typedef slice::range<index_type> range; typedef slice::operators<Array> operators_base; template<typename U, size_t N> array_slice(Array &A, const U (&from)[N], const U (&to)[N]) : range(from, to), operators_base(A, *this), N_(N) {} template<typename U, size_t N> array_slice(Array &A, const boost::array<U,N> &from, const boost::array<U,N> &to) : range(from.elems, to.elems), operators_base(A, *this), N_(N) {} using operators_base::operator=; template<class E> void operator=(const ublas::matrix_expression<E> &AE) { assert(size1() == AE().size1()); assert(size2() == AE().size2()); const_pointer p = ublas::matrix<T>(AE()).data().begin(); index_type ld[N_]; for (XRANGE(i, N_)) { ld[i] = range::to()[i] - range::from()[i] - 1; } operators_base::assign(p, ld); } size_type size1() const { return this->size(0); } size_type size2() const { return this->size(1); } private: const size_t N_; }; } #endif /* _DISTRIBUTED_SLICE_HPP_ */
31.064748
82
0.656786
andremirt
e85698e645281a827f2098348550bbb3389e507e
271
cpp
C++
library/Methods/Maths/combinatorics/montmort.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
127
2019-07-22T03:52:01.000Z
2022-03-11T07:20:21.000Z
library/Methods/Maths/combinatorics/montmort.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
39
2019-09-16T12:04:53.000Z
2022-03-29T15:43:35.000Z
library/Methods/Maths/combinatorics/montmort.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
29
2019-08-10T11:27:06.000Z
2022-03-11T07:02:43.000Z
/** * @brief Montmort-Number(モンモール数) * @docs docs/montmort.md */ template< typename T > vector< T > montmort(int N) { vector< T > dp(N + 1); for(int k = 2; k <= N; k++) { dp[k] = dp[k - 1] * k; if(k & 1) dp[k] -= 1; else dp[k] += 1; } return dp; }
18.066667
33
0.490775
sarafanshul
e8572eeb790963169619fe590f6c05beb3d79ffc
9,995
cpp
C++
src/InstantInterface/WebInterface.cpp
matthieu-ft/InstantInterface
b27212df6769be6e9a5d168a2b0ed49e0130ce42
[ "MIT" ]
null
null
null
src/InstantInterface/WebInterface.cpp
matthieu-ft/InstantInterface
b27212df6769be6e9a5d168a2b0ed49e0130ce42
[ "MIT" ]
null
null
null
src/InstantInterface/WebInterface.cpp
matthieu-ft/InstantInterface
b27212df6769be6e9a5d168a2b0ed49e0130ce42
[ "MIT" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // License Agreement // For InstantInterface Library // // The MIT License (MIT) // // Copyright (c) 2016 Matthieu Fraissinet-Tachet (www.matthieu-ft.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies // or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. // //M*/ #include "WebInterface.h" #include <json/json.h> #include <fstream> using namespace std; namespace InstantInterface { WebInterface::WebInterface(bool withThread) : m_count(0), threaded(withThread), structureCache(""), valuesCache(""), m_stopped(false) { // set up access channels to only log interesting things m_endpoint.clear_access_channels(websocketpp::log::alevel::all); m_endpoint.set_access_channels(websocketpp::log::alevel::access_core); m_endpoint.set_access_channels(websocketpp::log::alevel::app); m_endpoint.set_reuse_addr(true); // Initialize the Asio transport policy m_endpoint.init_asio(); // Bind the handlers we are using using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; m_endpoint.set_open_handler(bind(&WebInterface::on_open,this,_1)); m_endpoint.set_close_handler(bind(&WebInterface::on_close,this,_1)); m_endpoint.set_http_handler(bind(&WebInterface::on_http,this,_1)); m_endpoint.set_message_handler(bind(&WebInterface::on_message,this,_1,_2)); } bool WebInterface::poll() { try { m_endpoint.poll(); } catch (websocketpp::exception const & e) { std::cout << e.what() << std::endl; } return !m_stopped; } void WebInterface::stop() { //do not accept new connection m_endpoint.stop_listening(); //close properly all existing connections for(auto& it: m_connections) { m_endpoint.close(it,websocketpp::close::status::normal, "close button pressed"); } m_stopped = true; thread.join(); } void WebInterface::init(uint16_t port, std::string docroot) { std::stringstream ss; if(docroot == "#") { //in this case we look for the path in the file pathToWebInterface.txt std::ifstream ifstr ("pathToWebInterface.txt"); if(!std::getline(ifstr, docroot)) { std::cout<<"InstantInterface::WebInterface::init(), couldn't find the path to the web interface. " "Make sure that the file pathToWebInterface.txt exists in the same directory where the program is executed" " and make sure that there are no additional space or lines in the file." " Also, don't forget to add a directory separator at the end of the file"<<std::endl; return; } } ss << "Running telemetry server on port "<< port <<" using docroot=" << docroot; m_endpoint.get_alog().write(websocketpp::log::alevel::app,ss.str()); m_docroot = docroot; // listen on specified port m_endpoint.listen(port); // Start the server accept loop m_endpoint.start_accept(); } void WebInterface::run() { updateStructureCache(); updateParameterCache(); // Start the ASIO io_service run loop try { if(threaded) { thread = std::thread(&server::run,&m_endpoint); } else { m_endpoint.run(); } } catch (websocketpp::exception const & e) { std::cout << e.what() << std::endl; } } void WebInterface::on_message(websocketpp::connection_hdl hdl, server::message_ptr msg) { if (msg->get_opcode() == websocketpp::frame::opcode::text) { std::string content = msg->get_payload(); if(content == "send_interface") { send_interface(hdl); } else if (content == "update") { send_values_update(hdl); } else { //this must contain json, so we try to do the udpate if(threaded) { addCommand(content); } else { executeSingleCommand(content); } } } else { std::cout<<"we don't know what to do with this message, because this is no text"<<std::endl; } } void WebInterface::send_interface(websocketpp::connection_hdl hdl) { if (threaded) { scoped_lock lock(parametersMutex); m_endpoint.send(hdl,structureCache,websocketpp::frame::opcode::text); } else { m_endpoint.send(hdl,getStructureJsonString(),websocketpp::frame::opcode::text); } //after sending the interface we send the update of all the parameters, because the structure of the interface //is stored in json::value that is not synchronized with the actual values of the parameters send_values_update(hdl); } void WebInterface::send_values_update(websocketpp::connection_hdl hdl) { if(threaded) { scoped_lock lock(parametersMutex); m_endpoint.send(hdl,valuesCache,websocketpp::frame::opcode::text); } else { m_endpoint.send(hdl,getStateJsonString(),websocketpp::frame::opcode::text); } } void WebInterface::addCommand(const std::string &command) { scoped_lock lock (mainPrgMessagesMutex); mainPrgMessages.push(command); } void WebInterface::executeCommands() { std::queue<std::string> queueCopy; { scoped_lock lock (mainPrgMessagesMutex); queueCopy = std::move(mainPrgMessages); } std::string content; while(!queueCopy.empty()) { content = queueCopy.front(); queueCopy.pop(); executeSingleCommand(content); } } bool WebInterface::executeSingleCommand(const string &content) { Json::Reader reader; Json::Value messageJson; bool success = reader.parse(content.c_str(), messageJson); if(!success) { std::cout<<"Couldn't parse received message to json."<<std::endl; return false; } if(messageJson["type"].asString()=="update") { Json::Value updates = messageJson["content"]; for(Json::ValueIterator itr = updates.begin(); itr != updates.end(); itr++) { std::string paramId = (*itr)["id"].asString(); updateInterfaceElement(paramId,(*itr)["value"]); } return true; } return false; } void WebInterface::updateStructureCache() { scoped_lock lock (parametersMutex); structureCache = this->getStructureJsonString(); } void WebInterface::updateParameterCache() { scoped_lock lock (parametersMutex); valuesCache = this->getStateJsonString(); } void WebInterface::forceRefreshAll() { updateParameterCache(); for(auto& it: m_connections) { send_values_update(it); } } void WebInterface::forceRefreshStructureAll() { updateStructureCache(); for(auto& it: m_connections) { send_interface(it); } } void WebInterface::on_http(WebInterface::connection_hdl hdl) { // Upgrade our connection handle to a full connection_ptr server::connection_ptr con = m_endpoint.get_con_from_hdl(hdl); std::ifstream file; std::string filename = con->get_uri()->get_resource(); std::string response; m_endpoint.get_alog().write(websocketpp::log::alevel::app, "http request1: "+filename); if (filename == "/") { filename = m_docroot+"index.html"; } else { filename = m_docroot+filename.substr(1); } m_endpoint.get_alog().write(websocketpp::log::alevel::app, "http request2: "+filename); file.open(filename.c_str(), std::ios::in); if (!file) { // 404 error std::stringstream ss; ss << "<!doctype html><html><head>" << "<title>Error 404 (Resource not found)</title><body>" << "<h1>Error 404</h1>" << "<p>The requested URL " << filename << " was not found on this server.</p>" << "</body></head></html>"; con->set_body(ss.str()); con->set_status(websocketpp::http::status_code::not_found); return; } file.seekg(0, std::ios::end); response.reserve(file.tellg()); file.seekg(0, std::ios::beg); response.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); con->set_body(response); con->set_status(websocketpp::http::status_code::ok); } void WebInterface::on_open(WebInterface::connection_hdl hdl) { m_connections.insert(hdl); } void WebInterface::on_close(WebInterface::connection_hdl hdl) { m_connections.erase(hdl); } }
27.610497
130
0.634317
matthieu-ft
e8581417aec80175e89a355b031613e636ba7577
1,496
hpp
C++
src/ndnSIM/tests/unit-tests/tests-common.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
1
2021-09-07T04:12:15.000Z
2021-09-07T04:12:15.000Z
src/ndnSIM/tests/unit-tests/tests-common.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
null
null
null
src/ndnSIM/tests/unit-tests/tests-common.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
1
2020-07-15T06:21:03.000Z
2020-07-15T06:21:03.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /** * Copyright (c) 2011-2015 Regents of the University of California. * * This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and * contributors. * * ndnSIM is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * ndnSIM 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 * ndnSIM, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>. **/ #ifndef NDNSIM_TESTS_UNIT_TESTS_TESTS_COMMON_HPP #define NDNSIM_TESTS_UNIT_TESTS_TESTS_COMMON_HPP #include "ns3/core-module.h" #include "model/ndn-global-router.hpp" #include "helper/ndn-scenario-helper.hpp" #include "boost-test.hpp" namespace ns3 { namespace ndn { class CleanupFixture { public: ~CleanupFixture() { Simulator::Destroy(); Names::Clear(); GlobalRouter::clear(); } }; class ScenarioHelperWithCleanupFixture : public ScenarioHelper, public CleanupFixture { public: }; } // namespace ndn } // namespace ns3 #endif // NDNSIM_TESTS_UNIT_TESTS_TESTS_COMMON_HPP
28.769231
86
0.738636
NDNLink
e859ada3637cdae6ad9d53c476e3ceea2404e1f8
903
cpp
C++
codeforces/D - Riverside Curio/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/D - Riverside Curio/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/D - Riverside Curio/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Mar/26/2018 18:41 * solution_verdict: Accepted language: GNU C++14 * run_time: 140 ms memory_used: 5100 KB * problem: https://codeforces.com/contest/957/problem/D ****************************************************************************************/ #include<bits/stdc++.h> using namespace std; long long n,arr[100005],ans,tmp[100005]; int main() { cin>>n; for(int i=1;i<=n;i++)cin>>arr[i]; for(int i=1;i<=n;i++)tmp[i]=max(tmp[i-1],arr[i]+1); for(int i=n;i>=1;i--)tmp[i]=max(tmp[i],tmp[i+1]-1); for(int i=1;i<=n;i++)ans+=tmp[i]-arr[i]-1; cout<<ans<<endl; return 0; }
47.526316
111
0.369878
kzvd4729
e85bc666455c7d89246688864cd3f712c3447a25
1,586
cpp
C++
codeforces/538div2/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
codeforces/538div2/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
codeforces/538div2/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); int n, m, k; while (cin >> n >> m >> k) { vector<int> a(n); cin >> a; auto b = a; sort(b.begin(), b.end()); reverse(b.begin(), b.end()); map<int, int> cnt; lli sum = 0; for (int i = 0; i < m * k; ++i) { ++cnt[b[i]]; sum += b[i]; } vector<int> idx; int x = m; for (int i = 0; i < a.size(); ++i) { if (cnt[a[i]]) { --x; --cnt[a[i]]; } if (!x) { idx.push_back(i + 1); x = m; } } idx.pop_back(); cout << sum << endl; each (i, idx) cout << i << ' ' ; cout << endl; } return 0; }
26.433333
144
0.516393
Johniel
e863ad2e1c232badb3e1b5fbf9cf5747017be7ff
1,325
cc
C++
thirdparty/rnd/gcd.cc
wilseypa/warped-models
3b43934ab0de69d776df369d1fd010360b1ea0b2
[ "MIT" ]
2
2015-09-21T20:26:05.000Z
2017-11-12T01:05:45.000Z
thirdparty/rnd/gcd.cc
wilseypa/warped-models
3b43934ab0de69d776df369d1fd010360b1ea0b2
[ "MIT" ]
null
null
null
thirdparty/rnd/gcd.cc
wilseypa/warped-models
3b43934ab0de69d776df369d1fd010360b1ea0b2
[ "MIT" ]
null
null
null
/* Copyright (C) 1990 Free Software Foundation written by Doug Lea (dl@rocky.oswego.edu) This file is part of the GNU C++ Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef __GNUG__ #pragma implementation #endif #include "gcd.h" /* common functions on built-in types */ inline long abs(long arg) { return (arg < 0)? -arg : arg; } long gcd(long x, long y) // euclid's algorithm { long a = abs(x); long b = abs(y); long tmp; if (b > a) { tmp = a; a = b; b = tmp; } for(;;) { if (b == 0) return a; else if (b == 1) return b; else { tmp = b; b = a % b; a = tmp; } } }
22.844828
70
0.66717
wilseypa
e868aa9e796d41c5026061c65ac4e2e0fa7d4719
8,370
cpp
C++
stromx/cvml/test/SvmTest.cpp
uboot/stromx-opencv
c7de6353905fee8870f8bf700363e0868ab17b78
[ "Apache-2.0" ]
null
null
null
stromx/cvml/test/SvmTest.cpp
uboot/stromx-opencv
c7de6353905fee8870f8bf700363e0868ab17b78
[ "Apache-2.0" ]
null
null
null
stromx/cvml/test/SvmTest.cpp
uboot/stromx-opencv
c7de6353905fee8870f8bf700363e0868ab17b78
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015 Matthias Fuchs * * 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 "stromx/cvml/test/SvmTest.h" #include <cppunit/TestAssert.h> #include <stromx/cvsupport/Matrix.h> #include <stromx/runtime/File.h> #include <stromx/runtime/Id2DataMapper.h> #include <stromx/runtime/OperatorException.h> #include <stromx/runtime/OperatorTester.h> #include <stromx/runtime/ReadAccess.h> #include <stromx/runtime/Variant.h> #include "stromx/cvml/Svm.h" CPPUNIT_TEST_SUITE_REGISTRATION (stromx::cvml::SvmTest); namespace stromx { using namespace runtime; namespace cvml { void SvmTest::setUp ( void ) { m_operator = new runtime::OperatorTester(new Svm()); m_operator->initialize(); m_operator->activate(); } void SvmTest::testExecutePredict() { File modelFile("svm_model.xml"); m_operator->setParameter(Svm::STATISTICAL_MODEL, modelFile); cvsupport::Matrix* data = new cvsupport::Matrix(1, 3, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = 0.0; data->at<float>(0, 2) = -1.0; DataContainer input(data); m_operator->setInputData(Svm::DATA, input); DataContainer output = m_operator->getOutputData(Svm::PREDICTED_RESPONSE); ReadAccess access(output); const Float32 & response = access.get<Float32>(); CPPUNIT_ASSERT_DOUBLES_EQUAL(float(-1.0), static_cast<float>(response), 0.001); } void SvmTest::testExecutePredictInt32Data() { File modelFile("svm_model.xml"); m_operator->setParameter(Svm::STATISTICAL_MODEL, modelFile); cvsupport::Matrix* data = new cvsupport::Matrix(1, 3, runtime::Matrix::INT_32); data->at<int32_t>(0, 0) = 0.0; data->at<int32_t>(0, 1) = 0.0; data->at<int32_t>(0, 2) = -1.0; DataContainer input(data); m_operator->setInputData(Svm::DATA, input); CPPUNIT_ASSERT_THROW(m_operator->getOutputData(Svm::PREDICTED_RESPONSE), runtime::OperatorError); } void SvmTest::testExecutePredictWrongDimension() { File modelFile("svm_model.xml"); m_operator->setParameter(Svm::STATISTICAL_MODEL, modelFile); cvsupport::Matrix* data = new cvsupport::Matrix(1, 2, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = 0.0; DataContainer input(data); m_operator->setInputData(Svm::DATA, input); CPPUNIT_ASSERT_THROW(m_operator->getOutputData(Svm::PREDICTED_RESPONSE), runtime::OperatorError); } void SvmTest::testExecuteTrain() { m_operator->setParameter(Svm::TRAINING_IS_ACTIVE, Bool(true)); cvsupport::Matrix* data = 0; Float32* response = 0; data = new cvsupport::Matrix(1, 2, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = 1.1; response = new Float32(1.0); m_operator->setInputData(Svm::DATA, DataContainer(data)); m_operator->setInputData(Svm::TRAINING_RESPONSE, DataContainer(response)); DataContainer output = m_operator->getOutputData(Svm::PREDICTED_RESPONSE); ReadAccess access(output); const Float32 & predictedResponse = access.get<Float32>(); CPPUNIT_ASSERT_DOUBLES_EQUAL(float(1.0), static_cast<float>(predictedResponse), 0.001); } void SvmTest::testExecuteTrainAndPredict() { m_operator->setParameter(Svm::TRAINING_IS_ACTIVE, Bool(true)); cvsupport::Matrix* data = 0; Float32* response = 0; data = new cvsupport::Matrix(1, 2, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = 1.1; response = new Float32(1.0); m_operator->setInputData(Svm::DATA, DataContainer(data)); m_operator->setInputData(Svm::TRAINING_RESPONSE, DataContainer(response)); m_operator->getOutputData(Svm::PREDICTED_RESPONSE); m_operator->clearOutputData(Svm::PREDICTED_RESPONSE); data = new cvsupport::Matrix(1, 2, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = 0.9; response = new Float32(1.0); m_operator->setInputData(Svm::DATA, DataContainer(data)); m_operator->setInputData(Svm::TRAINING_RESPONSE, DataContainer(response)); m_operator->getOutputData(Svm::PREDICTED_RESPONSE); m_operator->clearOutputData(Svm::PREDICTED_RESPONSE); data = new cvsupport::Matrix(1, 2, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = -1.0; response = new Float32(-1.0); m_operator->setInputData(Svm::DATA, DataContainer(data)); m_operator->setInputData(Svm::TRAINING_RESPONSE, DataContainer(response)); m_operator->getOutputData(Svm::PREDICTED_RESPONSE); m_operator->clearOutputData(Svm::PREDICTED_RESPONSE); m_operator->setParameter(Svm::TRAINING_IS_ACTIVE, Bool(false)); data = new cvsupport::Matrix(1, 2, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = 1.0; m_operator->setInputData(Svm::DATA, DataContainer(data)); DataContainer output = m_operator->getOutputData(Svm::PREDICTED_RESPONSE); ReadAccess access(output); const Float32 & predictedResponse = access.get<Float32>(); CPPUNIT_ASSERT_DOUBLES_EQUAL(float(1.0), static_cast<float>(predictedResponse), 0.001); } void SvmTest::testExecuteTrainWrongDimension() { m_operator->setParameter(Svm::TRAINING_IS_ACTIVE, Bool(true)); cvsupport::Matrix* data = 0; Float32* response = 0; data = new cvsupport::Matrix(1, 2, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = 1.1; response = new Float32(1.0); m_operator->setInputData(Svm::DATA, DataContainer(data)); m_operator->setInputData(Svm::TRAINING_RESPONSE, DataContainer(response)); m_operator->getOutputData(Svm::PREDICTED_RESPONSE); m_operator->clearOutputData(Svm::PREDICTED_RESPONSE); data = new cvsupport::Matrix(1, 3, runtime::Matrix::FLOAT_32); data->at<float>(0, 0) = 0.0; data->at<float>(0, 1) = 0.9; data->at<float>(0, 2) = 0.9; response = new Float32(1.0); m_operator->setInputData(Svm::DATA, DataContainer(data)); m_operator->setInputData(Svm::TRAINING_RESPONSE, DataContainer(response)); CPPUNIT_ASSERT_THROW(m_operator->getOutputData(Svm::PREDICTED_RESPONSE), runtime::OperatorError); } void SvmTest::testGetStatisticalModel() { DataRef value = m_operator->getParameter(Svm::STATISTICAL_MODEL); CPPUNIT_ASSERT(value.isVariant(Variant::FILE)); } void SvmTest::tearDown ( void ) { delete m_operator; } } }
40.631068
109
0.583751
uboot
e869a68c1dfab6c471406d9ed2739ea46a018bd4
751
cpp
C++
llarp/link/encoder.cpp
defcon201/llarp
ff07fb118486a0cd646d004ea33d0786972e3061
[ "Zlib" ]
null
null
null
llarp/link/encoder.cpp
defcon201/llarp
ff07fb118486a0cd646d004ea33d0786972e3061
[ "Zlib" ]
null
null
null
llarp/link/encoder.cpp
defcon201/llarp
ff07fb118486a0cd646d004ea33d0786972e3061
[ "Zlib" ]
1
2020-12-16T16:32:40.000Z
2020-12-16T16:32:40.000Z
#include "encoder.hpp" namespace llarp { /// encode Link Introduce Message onto a buffer /// if router is nullptr then the LIM's r member is omitted. bool EncodeLIM(llarp_buffer_t* buff, llarp_rc* router) { if(!bencode_start_dict(buff)) return false; // message type if(!bencode_write_bytestring(buff, "a", 1)) return false; if(!bencode_write_bytestring(buff, "i", 1)) return false; // router contact if(router) { if(!bencode_write_bytestring(buff, "r", 1)) return false; if(!llarp_rc_bencode(router, buff)) return false; } // version if(!bencode_write_version_entry(buff)) return false; return bencode_end(buff); } } // namespace llarp
21.457143
62
0.636485
defcon201
e86c708436fe4f50479c49c8adda64e688fec8a1
26,264
cc
C++
soa/service/zmq_endpoint.cc
oktal/rtbkit
1b1b3b76ab211111c20b2957634619b3ba2813f4
[ "Apache-2.0" ]
1
2019-02-12T10:40:08.000Z
2019-02-12T10:40:08.000Z
soa/service/zmq_endpoint.cc
oktal/rtbkit
1b1b3b76ab211111c20b2957634619b3ba2813f4
[ "Apache-2.0" ]
null
null
null
soa/service/zmq_endpoint.cc
oktal/rtbkit
1b1b3b76ab211111c20b2957634619b3ba2813f4
[ "Apache-2.0" ]
null
null
null
/* zmq_endpoint.cc Jeremy Barnes, 9 November 2012 Copyright (c) 2012 Datacratic Inc. All rights reserved. */ #include "zmq_endpoint.h" #include "jml/utils/smart_ptr_utils.h" #include <sys/utsname.h> #include <thread> #include "jml/arch/timers.h" #include "jml/arch/info.h" using namespace std; namespace Datacratic { /******************************************************************************/ /* ZMQ LOGS */ /******************************************************************************/ Logging::Category ZmqLogs::print("ZMQ"); Logging::Category ZmqLogs::error("ZMQ Error", ZmqLogs::print); Logging::Category ZmqLogs::trace("ZMQ Trace", ZmqLogs::print); /*****************************************************************************/ /* ZMQ EVENT SOURCE */ /*****************************************************************************/ ZmqEventSource:: ZmqEventSource() : socket_(0), socketLock_(nullptr) { needsPoll = false; } ZmqEventSource:: ZmqEventSource(zmq::socket_t & socket, SocketLock * socketLock) : socket_(&socket), socketLock_(socketLock) { needsPoll = false; updateEvents(); } void ZmqEventSource:: init(zmq::socket_t & socket, SocketLock * socketLock) { socket_ = &socket; socketLock_ = socketLock; needsPoll = false; updateEvents(); } int ZmqEventSource:: selectFd() const { int res = -1; size_t resSize = sizeof(int); socket().getsockopt(ZMQ_FD, &res, &resSize); if (res == -1) THROW(ZmqLogs::error) << "no fd for zeromq socket" << endl; return res; } bool ZmqEventSource:: poll() const { if (currentEvents & ZMQ_POLLIN) return true; std::unique_lock<SocketLock> guard; if (socketLock_) guard = std::unique_lock<SocketLock>(*socketLock_); updateEvents(); return currentEvents & ZMQ_POLLIN; } void ZmqEventSource:: updateEvents() const { size_t events_size = sizeof(currentEvents); socket().getsockopt(ZMQ_EVENTS, &currentEvents, &events_size); } bool ZmqEventSource:: processOne() { using namespace std; if (debug_) cerr << "called processOne on " << this << ", poll = " << poll() << endl; if (!poll()) return false; std::vector<std::string> msg; // We process all events, as otherwise the select fd can't be guaranteed to wake us up for (;;) { { std::unique_lock<SocketLock> guard; if (socketLock_) guard = std::unique_lock<SocketLock>(*socketLock_); msg = recvAllNonBlocking(socket()); if (msg.empty()) { if (currentEvents & ZMQ_POLLIN) throw ML::Exception("empty message with currentEvents"); return false; // no more events } updateEvents(); } if (debug_) cerr << "got message of length " << msg.size() << endl; handleMessage(msg); } return currentEvents & ZMQ_POLLIN; } void ZmqEventSource:: handleMessage(const std::vector<std::string> & message) { if (asyncMessageHandler) { asyncMessageHandler(message); return; } auto reply = handleSyncMessage(message); if (!reply.empty()) { sendAll(socket(), reply); } } std::vector<std::string> ZmqEventSource:: handleSyncMessage(const std::vector<std::string> & message) { if (!syncMessageHandler) THROW(ZmqLogs::error) << "no message handler set" << std::endl; return syncMessageHandler(message); } /*****************************************************************************/ /* ZMQ SOCKET MONITOR */ /*****************************************************************************/ //static int numMonitors = 0; ZmqSocketMonitor:: ZmqSocketMonitor(zmq::context_t & context) : monitorEndpoint(new zmq::socket_t(context, ZMQ_PAIR)), monitoredSocket(0) { //cerr << "creating socket monitor at " << this << endl; //__sync_fetch_and_add(&numMonitors, 1); } void ZmqSocketMonitor:: shutdown() { if (!monitorEndpoint) return; //cerr << "shutting down socket monitor at " << this << endl; connectedUri.clear(); std::unique_lock<Lock> guard(lock); monitorEndpoint.reset(); //cerr << __sync_add_and_fetch(&numMonitors, -1) << " monitors still active" // << endl; } void ZmqSocketMonitor:: disconnect() { std::unique_lock<Lock> guard(lock); if (monitorEndpoint) monitorEndpoint->tryDisconnect(connectedUri.c_str()); } void ZmqSocketMonitor:: init(zmq::socket_t & socketToMonitor, int events) { static int serial = 0; // Initialize the monitor connection connectedUri = ML::format("inproc://monitor-%p-%d", this, __sync_fetch_and_add(&serial, 1)); monitoredSocket = &socketToMonitor; //using namespace std; //cerr << "connecting monitor to " << connectedUri << endl; int res = zmq_socket_monitor(socketToMonitor, connectedUri.c_str(), events); if (res == -1) throw zmq::error_t(); // Connect it in monitorEndpoint->connect(connectedUri.c_str()); // Make sure we receive events from it ZmqBinaryTypedEventSource<zmq_event_t>::init(*monitorEndpoint); messageHandler = [=] (const zmq_event_t & event) { this->handleEvent(event); }; } bool debugZmqMonitorEvents = false; int ZmqSocketMonitor:: handleEvent(const zmq_event_t & event) { if (debugZmqMonitorEvents) { cerr << "got socket event " << printZmqEvent(event.event) << " at " << this << " " << connectedUri << " for socket " << monitoredSocket << endl; } auto doEvent = [&] (const EventHandler & handler, const char * addr, int param) { if (handler) handler(addr, param, event); else if (defaultHandler) defaultHandler(addr, param, event); else return 0; return 1; }; switch (event.event) { // Bind case ZMQ_EVENT_LISTENING: return doEvent(bindHandler, event.data.listening.addr, event.data.listening.fd); case ZMQ_EVENT_BIND_FAILED: return doEvent(bindFailureHandler, event.data.bind_failed.addr, event.data.bind_failed.err); // Accept case ZMQ_EVENT_ACCEPTED: return doEvent(acceptHandler, event.data.accepted.addr, event.data.accepted.fd); case ZMQ_EVENT_ACCEPT_FAILED: return doEvent(acceptFailureHandler, event.data.accept_failed.addr, event.data.accept_failed.err); break; // Connect case ZMQ_EVENT_CONNECTED: return doEvent(connectHandler, event.data.connected.addr, event.data.connected.fd); case ZMQ_EVENT_CONNECT_DELAYED: return doEvent(connectFailureHandler, event.data.connect_delayed.addr, event.data.connect_delayed.err); case ZMQ_EVENT_CONNECT_RETRIED: return doEvent(connectRetryHandler, event.data.connect_retried.addr, event.data.connect_retried.interval); // Close and disconnection case ZMQ_EVENT_CLOSE_FAILED: return doEvent(closeFailureHandler, event.data.close_failed.addr, event.data.close_failed.err); case ZMQ_EVENT_CLOSED: return doEvent(closeHandler, event.data.closed.addr, event.data.closed.fd); case ZMQ_EVENT_DISCONNECTED: return doEvent(disconnectHandler, event.data.disconnected.addr, event.data.disconnected.fd); default: LOG(ZmqLogs::print) << "got unknown event type " << event.event << endl; return doEvent(defaultHandler, "", -1); } } /*****************************************************************************/ /* NAMED ZEROMQ ENDPOINT */ /*****************************************************************************/ ZmqNamedEndpoint:: ZmqNamedEndpoint(std::shared_ptr<zmq::context_t> context) : context_(context) { } void ZmqNamedEndpoint:: init(std::shared_ptr<ConfigurationService> config, int socketType, const std::string & endpointName) { NamedEndpoint::init(config, endpointName); this->socketType = socketType; this->socket_.reset(new zmq::socket_t(*context_, socketType)); setHwm(*socket_, 65536); addSource("ZmqNamedEndpoint::socket", std::make_shared<ZmqBinaryEventSource> (*socket_, [=] (std::vector<zmq::message_t> && message) { handleRawMessage(std::move(message)); })); } std::string ZmqNamedEndpoint:: bindTcp(PortRange const & portRange, std::string host) { std::unique_lock<Lock> guard(lock); if (!socket_) THROW(ZmqLogs::error) << "bind called before init" << std::endl; using namespace std; if (host == "") host = "*"; int port = bindAndReturnOpenTcpPort(*socket_, portRange, host); auto getUri = [&] (const std::string & host) { return "tcp://" + host + ":" + to_string(port); }; Json::Value config; auto addEntry = [&] (const std::string& addr, const std::string& hostScope) { std::string uri; if(hostScope != "*") { uri = "tcp://" + addr + ":" + to_string(port); } else { uri = "tcp://" + ML::fqdn_hostname(to_string(port)) + ":" + to_string(port); } Json::Value & entry = config[config.size()]; entry["zmqConnectUri"] = uri; Json::Value & transports = entry["transports"]; transports[0]["name"] = "tcp"; transports[0]["addr"] = addr; transports[0]["hostScope"] = hostScope; transports[0]["port"] = port; transports[1]["name"] = "zeromq"; transports[1]["socketType"] = socketType; transports[1]["uri"] = uri; }; if (host == "*") { auto interfaces = getInterfaces({AF_INET}); for (unsigned i = 0; i < interfaces.size(); ++i) { addEntry(interfaces[i].addr, interfaces[i].hostScope); } publishAddress("tcp", config); return getUri(host); } else { string host2 = addrToIp(host); // TODO: compute the host scope; don't just assume "*" addEntry(host2, "*"); publishAddress("tcp", config); return getUri(host2); } } /*****************************************************************************/ /* NAMED ZEROMQ PROXY */ /*****************************************************************************/ ZmqNamedProxy:: ZmqNamedProxy() : context_(new zmq::context_t(1)), local(true) { } ZmqNamedProxy:: ZmqNamedProxy(std::shared_ptr<zmq::context_t> context) : context_(context), local(true) { } void ZmqNamedProxy:: init(std::shared_ptr<ConfigurationService> config, int socketType, const std::string & identity) { this->connectionType = NO_CONNECTION; this->connectionState = NOT_CONNECTED; this->config = config; socket_.reset(new zmq::socket_t(*context_, socketType)); if (identity != "") setIdentity(*socket_, identity); setHwm(*socket_, 65536); serviceWatch.init(std::bind(&ZmqNamedProxy::onServiceNodeChange, this, std::placeholders::_1, std::placeholders::_2)); endpointWatch.init(std::bind(&ZmqNamedProxy::onEndpointNodeChange, this, std::placeholders::_1, std::placeholders::_2)); } bool ZmqNamedProxy:: connect(const std::string & endpointName, ConnectionStyle style) { if (!config) { THROW(ZmqLogs::error) << "attempt to connect to " << endpointName << " without calling init()" << endl; } if (connectionState == CONNECTED) THROW(ZmqLogs::error) << "already connected" << endl; this->connectedService = endpointName; if (connectionType == NO_CONNECTION) connectionType = CONNECT_DIRECT; LOG(ZmqLogs::print) << "connecting to " << endpointName << endl; vector<string> children = config->getChildren(endpointName, endpointWatch); auto setPending = [&] { std::lock_guard<ZmqEventSource::SocketLock> guard(socketLock_); if (connectionState == NOT_CONNECTED) connectionState = CONNECTION_PENDING; }; for (auto c: children) { ExcAssertNotEqual(connectionState, CONNECTED); string key = endpointName + "/" + c; Json::Value epConfig = config->getJson(key); for (auto & entry: epConfig) { if (!entry.isMember("zmqConnectUri")) return true; string uri = entry["zmqConnectUri"].asString(); auto hs = entry["transports"][0]["hostScope"]; if (!hs) continue; string hostScope = hs.asString(); if (hs != "*") { utsname name; if (uname(&name)) { THROW(ZmqLogs::error) << "uname error: " << strerror(errno) << std::endl; } if (hostScope != name.nodename) continue; // wrong host scope } { std::lock_guard<ZmqEventSource::SocketLock> guard(socketLock_); socket().connect(uri.c_str()); connectedUri = uri; connectionState = CONNECTED; } LOG(ZmqLogs::print) << "connected to " << uri << endl; onConnect(uri); return true; } setPending(); return false; } if (style == CS_MUST_SUCCEED && connectionState != CONNECTED) { THROW(ZmqLogs::error) << "couldn't connect to any services of class " << serviceClass << endl; } setPending(); return connectionState == CONNECTED; } bool ZmqNamedProxy:: connectToServiceClass(const std::string & serviceClass, const std::string & endpointName, bool local_, ConnectionStyle style) { local = local_; // TODO: exception safety... if we bail don't screw around the auction ExcAssertNotEqual(connectionType, CONNECT_DIRECT); ExcAssertNotEqual(serviceClass, ""); ExcAssertNotEqual(endpointName, ""); this->serviceClass = serviceClass; this->endpointName = endpointName; if (connectionType == NO_CONNECTION) connectionType = CONNECT_TO_CLASS; if (!config) { THROW(ZmqLogs::error) << "attempt to connect to " << endpointName << " without calling init()" << endl; } if (connectionState == CONNECTED) THROW(ZmqLogs::error) << "attempt to double connect connection" << endl; vector<string> children = config->getChildren("serviceClass/" + serviceClass, serviceWatch); for (auto c: children) { string key = "serviceClass/" + serviceClass + "/" + c; Json::Value value = config->getJson(key); std::string name = value["serviceName"].asString(); std::string path = value["servicePath"].asString(); std::string location = value["serviceLocation"].asString(); if (local && location != config->currentLocation) { LOG(ZmqLogs::trace) << path << " / " << name << " dropped while connecting to " << serviceClass << "/" << endpointName << "(" << location << " != " << config->currentLocation << ")" << std::endl; continue; } if (connect(path + "/" + endpointName, style == CS_ASYNCHRONOUS ? CS_ASYNCHRONOUS : CS_SYNCHRONOUS)) return true; } if (style == CS_MUST_SUCCEED && connectionState != CONNECTED) { THROW(ZmqLogs::error) << "couldn't connect to any services of class " << serviceClass << endl; } { std::lock_guard<ZmqEventSource::SocketLock> guard(socketLock_); if (connectionState == NOT_CONNECTED) connectionState = CONNECTION_PENDING; } return connectionState == CONNECTED; } void ZmqNamedProxy:: onServiceNodeChange(const std::string & path, ConfigurationService::ChangeType change) { if (connectionState != CONNECTION_PENDING) return; // no need to watch anymore connectToServiceClass(serviceClass, endpointName, local, CS_ASYNCHRONOUS); } void ZmqNamedProxy:: onEndpointNodeChange(const std::string & path, ConfigurationService::ChangeType change) { if (connectionState != CONNECTION_PENDING) return; // no need to watch anymore connect(connectedService, CS_ASYNCHRONOUS); } /******************************************************************************/ /* ZMQ MULTIPLE NAMED CLIENT BUS PROXY */ /******************************************************************************/ void ZmqMultipleNamedClientBusProxy:: connectAllServiceProviders(const std::string & serviceClass, const std::string & endpointName, bool local) { if (connected) { THROW(ZmqLogs::error) << "already connected to " << serviceClass << " / " << endpointName << std::endl; } this->serviceClass = serviceClass; this->endpointName = endpointName; serviceProvidersWatch.init([=] (const std::string & path, ConfigurationService::ChangeType change) { ++changesCount[change]; onServiceProvidersChanged("serviceClass/" + serviceClass, local); }); onServiceProvidersChanged("serviceClass/" + serviceClass, local); connected = true; } /** Zookeeper makes the onServiceProvidersChanged calls re-entrant which is annoying to deal with. Instead, when a re-entrant call is detected we defer the call until we're done with the original call. */ bool ZmqMultipleNamedClientBusProxy:: enterProvidersChanged(const std::string& path, bool local) { std::lock_guard<ML::Spinlock> guard(providersChangedLock); if (!inProvidersChanged) { inProvidersChanged = true; return true; } LOG(ZmqLogs::trace) << "defering providers changed for " << path << std::endl; deferedProvidersChanges.emplace_back(path, local); return false; } void ZmqMultipleNamedClientBusProxy:: exitProvidersChanged() { std::vector<DeferedProvidersChanges> defered; { std::lock_guard<ML::Spinlock> guard(providersChangedLock); defered = std::move(deferedProvidersChanges); inProvidersChanged = false; } for (const auto& item : defered) onServiceProvidersChanged(item.first, item.second); } void ZmqMultipleNamedClientBusProxy:: onServiceProvidersChanged(const std::string & path, bool local) { if (!enterProvidersChanged(path, local)) return; // The list of service providers has changed std::vector<std::string> children = config->getChildren(path, serviceProvidersWatch); for (auto c: children) { Json::Value value = config->getJson(path + "/" + c); std::string name = value["serviceName"].asString(); std::string path = value["servicePath"].asString(); std::string location = value["serviceLocation"].asString(); if (local && location != config->currentLocation) { LOG(ZmqLogs::trace) << path << " / " << name << " dropped (" << location << " != " << config->currentLocation << ")" << std::endl; continue; } watchServiceProvider(name, path); } // deleting the connection could trigger a callback which is a bad idea // while we're holding the connections lock. So instead we move all the // connections to be deleted to a temp map which we'll wipe once the // lock is released. ConnectionMap pendingDisconnects; { std::unique_lock<Lock> guard(connectionsLock); // Services that are no longer in zookeeper are considered to be // disconnected so remove them from our connection map. for (auto& conn : connections) { auto it = find(children.begin(), children.end(), conn.first); if (it != children.end()) continue; // Erasing from connections in this loop would invalidate our // iterator so defer until we're done with the connections map. removeSource(conn.second.get()); pendingDisconnects[conn.first] = std::move(conn.second); } for (const auto& conn : pendingDisconnects) connections.erase(conn.first); } // We're no longer holding the lock so any delayed. Time to really // disconnect and trigger the callbacks. pendingDisconnects.clear(); exitProvidersChanged(); } /** Encapsulates a lock-free state machine that manages the logic of the on config callback. The problem being solved is that the onConnect callback should not call the user's callback while we're holding the connection lock but should do it when the lock is released. The lock-free state machine guarantees that no callbacks are lost and that no callbacks will be triggered before a call to release is made. The overhead of this class amounts to at most 2 CAS when the callback is triggered; one if there's no contention. Note that this isn't an ideal solution to this problem because we really should get rid of the locks when manipulating these events. \todo could be generalized if we need this pattern elsewhere. */ struct ZmqMultipleNamedClientBusProxy::OnConnectCallback { OnConnectCallback(const ConnectionHandler& fn, std::string name) : fn(fn), name(name), state(DEFER) {} /** Should ONLY be called AFTER the lock is released. */ void release() { State old = state; ExcAssertNotEqual(old, CALL); // If the callback wasn't triggered while we were holding the lock // then trigger it the next time we see it. if (old == DEFER && ML::cmp_xchg(state, old, CALL)) return; ExcAssertEqual(old, DEFERRED); fn(name); } void operator() (std::string blah) { State old = state; ExcAssertNotEqual(old, DEFERRED); // If we're still in the locked section then trigger the callback // when release is called. if (old == DEFER && ML::cmp_xchg(state, old, DEFERRED)) return; // We're out of the locked section so just trigger the callback. ExcAssertEqual(old, CALL); fn(name); } private: ConnectionHandler fn; std::string name; enum State { DEFER, // We're holding the lock so defer an incoming callback. DEFERRED, // We were called while holding the lock. CALL // We were not called while holding the lock. } state; }; void ZmqMultipleNamedClientBusProxy:: watchServiceProvider(const std::string & name, const std::string & path) { // Protects the connections map... I think. std::unique_lock<Lock> guard(connectionsLock); auto & c = connections[name]; // already connected if (c) { LOG(ZmqLogs::trace) << path << " / " << name << " is already connected" << std::endl; return; } LOG(ZmqLogs::trace) << "connecting to " << path << " / " << name << std::endl; try { auto newClient = std::make_shared<ZmqNamedClientBusProxy>(zmqContext); newClient->init(config, identity); // The connect call below could trigger this callback while we're // holding the connectionsLock which is a big no-no. This fancy // wrapper ensures that it's only called after we call its release // function. if (connectHandler) newClient->connectHandler = OnConnectCallback(connectHandler, name); newClient->disconnectHandler = [=] (std::string s) { // TODO: chain in so that we know it's not around any more this->onDisconnect(s); }; newClient->connect(path + "/" + endpointName); newClient->messageHandler = [=] (const std::vector<std::string> & msg) { this->handleMessage(name, msg); }; c = std::move(newClient); // Add it to our message loop so that it can process messages addSource("ZmqMultipleNamedClientBusProxy child " + name, c); guard.unlock(); if (connectHandler) c->connectHandler.target<OnConnectCallback>()->release(); } catch (...) { // Avoid triggering the disconnect callbacks while holding the // connectionsLock by defering the delete of the connection until // we've manually released the lock. ConnectionMap::mapped_type conn(std::move(connections[name])); connections.erase(name); guard.unlock(); // conn is a unique_ptr so it gets destroyed here. throw; } } } // namespace Datacratic
29.410974
91
0.563585
oktal
e86fa29433ef1ba27d0011d69c29eb071d1e5777
19,559
cpp
C++
src/sgcmc.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
3
2018-06-06T05:43:36.000Z
2020-07-18T14:31:37.000Z
src/sgcmc.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
null
null
null
src/sgcmc.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
7
2018-01-16T03:21:20.000Z
2020-07-20T19:36:13.000Z
/*-------------------------------------------- Created by Sina on 06/05/13. Copyright (c) 2013 MIT. All rights reserved. --------------------------------------------*/ #include "elements.h" #include "sgcmc.h" #include "memory.h" #include "random.h" #include "neighbor_md.h" #include "ff_md.h" #include "xmath.h" #include "atoms_md.h" #include "MAPP.h" #include "dynamic_md.h" using namespace MAPP_NS; /*-------------------------------------------- constructor --------------------------------------------*/ SGCMC::SGCMC(AtomsMD*& __atoms,ForceFieldMD*&__ff,DynamicMD*& __dynamic,int __m,elem_type __gas_type,type0 __mu,type0 __T,int seed): GCMC(__atoms,__ff,__dynamic,__gas_type,__mu,__T,seed), m(__m) { s_x_buff=NULL; head_atm=NULL; cell_coord_buff=NULL; n_cells=0; /*-------------------------------------------------- find the relative neighbor list for cells here we figure out the number of neighboring cells and also allocate the memory for rel_neigh_lst and rel_neigh_lst_coord. values for rel_neigh_lst_coord is assigned here,but finding the values for rel_neigh_lst requires knowledge of the box and domain, it will be differed to create() --------------------------------------------------*/ int countr[__dim__]; for(int i=0;i<__dim__;i++) countr[i]=-m; int max_no_neighs=1; for(int i=0;i<__dim__;i++) max_no_neighs*=2*m+1; nneighs=0; rel_neigh_lst_coord=new int[max_no_neighs*__dim__]; int* rel_neigh_lst_coord_=rel_neigh_lst_coord; int sum; int rc_sq=m*m; for(int i=0;i<max_no_neighs;i++) { sum=0; for(int j=0;j<__dim__;j++) { sum+=countr[j]*countr[j]; if(countr[j]!=0) sum+=1-2*std::abs(countr[j]); } if(sum<rc_sq) { for(int j=0;j<__dim__;j++) rel_neigh_lst_coord_[j]=countr[j]; rel_neigh_lst_coord_+=__dim__; nneighs++; } countr[0]++; for(int j=0;j<__dim__-1;j++) if(countr[j]==m+1) { countr[j]=-m; countr[j+1]++; } } rel_neigh_lst_coord_=new int[nneighs*__dim__]; memcpy(rel_neigh_lst_coord_,rel_neigh_lst_coord,nneighs*__dim__*sizeof(int)); delete [] rel_neigh_lst_coord; rel_neigh_lst_coord=rel_neigh_lst_coord_; } /*-------------------------------------------- destructor --------------------------------------------*/ SGCMC::~SGCMC() { delete [] rel_neigh_lst_coord; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::init() { dof_empty=atoms->x_dof->is_empty(); GCMC::init(); MPI_Scan(&ngas_lcl,&ngas_before,1,MPI_INT,MPI_SUM,world); ngas_before-=ngas_lcl; box_setup(); vars=new type0[ff->gcmc_n_vars]; lcl_vars=new type0[ff->gcmc_n_vars]; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::fin() { delete [] vars; delete [] lcl_vars; box_dismantle(); GCMC::fin(); } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::box_setup() { GCMC::box_setup(); n_cells=1; for(int i=0;i<__dim__;i++) { cell_size[i]=cut_s[i]/static_cast<type0>(m); N_cells[i]=static_cast<int>((s_hi[i]-s_lo[i])/cell_size[i])+1; B_cells[i]=n_cells; n_cells*=N_cells[i]; } head_atm=new int[n_cells]; cell_coord_buff=new int[max_ntrial_atms*__dim__]; s_x_buff=new type0[__dim__*max_ntrial_atms]; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::box_dismantle() { delete [] head_atm; delete [] cell_coord_buff; delete [] s_x_buff; head_atm=NULL; cell_coord_buff=NULL; s_x_buff=NULL; n_cells=0; } /*-------------------------------------------- construct the bin list --------------------------------------------*/ void SGCMC::xchng(bool chng_box,int nattmpts) { curr_comm=&world; curr_root=0; dynamic->init_xchng(); if(chng_box) box_setup(); /*-------------------------------------------------- here we allocate the memory for cell_vec & next_vec --------------------------------------------------*/ if(ff->gcmc_tag_enabled) tag_vec_p=new Vec<int>(atoms,1); else tag_vec_p=NULL; cell_vec_p=new Vec<int>(atoms,1); next_vec_p=new Vec<int>(atoms,1); s_vec_p=new Vec<type0>(atoms,__dim__); memcpy(s_vec_p->begin(),atoms->x->begin(),sizeof(type0)*natms_lcl*__dim__); /*-------------------------------------------------- here we reset head_atm --------------------------------------------------*/ for(int i=0;i<n_cells;i++) head_atm[i]=-1; /*-------------------------------------------------- here we assign values for cell_vec, next_vec & headt_atm; it is supposed that we have fractional coordinates at this point --------------------------------------------------*/ int* next_vec=next_vec_p->begin(); int* cell_vec=cell_vec_p->begin(); type0* s=atoms->x->begin()+(natms_lcl-1)*__dim__; for(int i=natms_lcl-1;i>-1;i--,s-=__dim__) { find_cell_no(s,cell_vec[i]); next_vec[i]=head_atm[cell_vec[i]]; head_atm[cell_vec[i]]=i; } ff->neighbor->create_list(chng_box); ff->init_xchng(); for(int i=0;i<atoms->ndynamic_vecs;i++) atoms->dynamic_vecs[i]->resize(natms_lcl); ngas_lcl=0; elem_type* elem=atoms->elem->begin(); for(int i=0;i<natms_lcl;i++) if(elem[i]==gas_type) ngas_lcl++; MPI_Scan(&ngas_lcl,&ngas_before,1,MPI_INT,MPI_SUM,world); MPI_Allreduce(&ngas_lcl,&ngas,1,MPI_INT,MPI_SUM,world); ngas_before-=ngas_lcl; next_jatm_p=&SGCMC::next_jatm_reg; dof_diff=0; for(int i=0;i<nattmpts;i++) attmpt(); ff->fin_xchng(); memcpy(atoms->x->begin(),s_vec_p->begin(),sizeof(type0)*natms_lcl*__dim__); delete tag_vec_p; delete s_vec_p; delete next_vec_p; delete cell_vec_p; dynamic->fin_xchng(); } /*-------------------------------------------- this must be used only for local atoms --------------------------------------------*/ inline void SGCMC::find_cell_no(type0*& s,int& cell_no) { cell_no=0; for(int i=0;i<__dim__;i++) cell_no+=B_cells[i]*MIN(static_cast<int>((s[i]-s_lo[i])/cell_size[i]),N_cells[i]-1); } /*-------------------------------------------- --------------------------------------------*/ inline void SGCMC::find_cell_coord(type0*& s,int*& cell_coord) { for(int i=0;i<__dim__;i++) { if(s[i]<s_lo[i]) cell_coord[i]=-static_cast<int>((s_lo[i]-s[i])/cell_size[i])-1; else if(s_hi[i]<=s[i]) cell_coord[i]=MAX(static_cast<int>((s[i]-s_lo[i])/cell_size[i]),N_cells[i]-1); else cell_coord[i]=MIN(static_cast<int>((s[i]-s_lo[i])/cell_size[i]),N_cells[i]-1); } } /*-------------------------------------------- attempt an insertion --------------------------------------------*/ void SGCMC::attmpt() { if(random->uniform()<0.5) { xchng_mode=INS_MODE; im_root=true; int iproc=-1; for(int i=0;i<__dim__;i++) { s_buff[i]=random->uniform(); if(s_buff[i]<s_lo[i] || s_buff[i]>=s_hi[i]) im_root=false; } if(im_root) iproc=atoms->comm_rank; MPI_Allreduce(&iproc,&curr_root,1,MPI_INT,MPI_MAX,world); } else { if(ngas==0) return; xchng_mode=DEL_MODE; igas=static_cast<int>(ngas*random->uniform()); int iproc=-1; im_root=false; if(ngas_before<=igas && igas<ngas_before+ngas_lcl) { im_root=true; iproc=atoms->comm_rank; int n=igas-ngas_before; int icount=-1; elem_type* elem=atoms->elem->begin(); del_idx=0; for(;icount!=n;del_idx++) if(elem[del_idx]==gas_type) icount++; del_idx--; gas_id=atoms->id->begin()[del_idx]; memcpy(s_buff,s_vec_p->begin()+del_idx*__dim__,__dim__*sizeof(type0)); } MPI_Allreduce(&iproc,&curr_root,1,MPI_INT,MPI_MAX,world); MPI_Bcast(s_buff,__dim__,Vec<type0>::MPI_T,curr_root,world); MPI_Bcast(&gas_id,1,MPI_INT,curr_root,world); } prep_s_x_buff(); if(tag_vec_p) reset_tag(); ff->pre_xchng_energy_timer(this); delta_u=ff->xchng_energy_timer(this); MPI_Bcast(&delta_u,1,Vec<type0>::MPI_T,curr_root,world); type0 fac; root_succ=false; if(xchng_mode==INS_MODE) { fac=z_fac*vol/((static_cast<type0>(ngas)+1.0)*exp(beta*delta_u)); if(random->uniform()<fac) { root_succ=true; ins_succ(); ff->post_xchng_energy_timer(this); } } else { fac=static_cast<type0>(ngas)*exp(beta*delta_u)/(z_fac*vol); if(random->uniform()<fac) { root_succ=true; del_succ(); ff->post_xchng_energy_timer(this); } } } /*-------------------------------------------- things to do after a successful insertion --------------------------------------------*/ void SGCMC::ins_succ() { int new_id=get_new_id(); for(int i=0;i<__dim__;i++) vel_buff[i]=random->gaussian()*sigma; if(im_root) { atoms->add(); memcpy(atoms->x->begin()+(natms_lcl-1)*__dim__,s_x_buff,__dim__*sizeof(type0)); memcpy(atoms->x_d->begin()+(natms_lcl-1)*__dim__,vel_buff,__dim__*sizeof(type0)); atoms->elem->begin()[natms_lcl-1]=gas_type; atoms->id->begin()[natms_lcl-1]=new_id; if(tag_vec_p) tag_vec_p->begin()[natms_lcl-1]=-1; if(!dof_empty) { bool* dof=atoms->x_dof->begin()+(natms_lcl-1)*__dim__; for(int i=0;i<__dim__;i++) dof[i]=true; } memcpy(s_vec_p->begin()+(natms_lcl-1)*__dim__,s_buff,__dim__*sizeof(type0)); int cell_=0; for(int i=0;i<__dim__;i++) cell_+=B_cells[i]*cell_coord_buff[i]; cell_vec_p->begin()[natms_lcl-1]=cell_; int* nxt_p=head_atm+cell_; while(*nxt_p!=-1) nxt_p=next_vec_p->begin()+*nxt_p; *nxt_p=natms_lcl-1; next_vec_p->begin()[natms_lcl-1]=-1; ngas_lcl++; } else { if(atoms->comm_rank>curr_root) ngas_before++; } dof_diff+=__dim__; ngas++; atoms->natms++; } /*-------------------------------------------- things to do after a successful deletion --------------------------------------------*/ void SGCMC::del_succ() { add_del_id(&gas_id,1); if(im_root) { /*-------------------------------------------------- 0.0 find the link to del_idx --------------------------------------------------*/ int* p_2_idx=head_atm+cell_vec_p->begin()[del_idx]; while(*p_2_idx!=del_idx) p_2_idx=next_vec_p->begin()+*p_2_idx; /*-------------------------------------------------- 0.1 replace link to del_idx with link from del_idx --------------------------------------------------*/ *p_2_idx=next_vec_p->begin()[del_idx]; if(del_idx!=natms_lcl-1) { /*-------------------------------------------------- 1.0 find the first link to after del_idx --------------------------------------------------*/ int* p_2_first_aft_del=head_atm+cell_vec_p->begin()[natms_lcl-1]; while(*p_2_first_aft_del<del_idx) p_2_first_aft_del=next_vec_p->begin()+*p_2_first_aft_del; /*-------------------------------------------------- 1.1 find the link to natms_lcl-1 --------------------------------------------------*/ int* p_2_last=p_2_first_aft_del; while(*p_2_last!=natms_lcl-1) p_2_last=next_vec_p->begin()+*p_2_last; /*-------------------------------------------------- 1.2 remove the link to natms_lcl-1 and end it ther --------------------------------------------------*/ *p_2_last=-1; /*-------------------------------------------------- 1.3 insert the new link at del_idx, but for now it is at natms_lcl-1 after the move operation which happens next it will go del_idx --------------------------------------------------*/ next_vec_p->begin()[natms_lcl-1]=*p_2_first_aft_del; *p_2_first_aft_del=del_idx; } atoms->del(del_idx); ngas_lcl--; } else { if(igas<ngas_before) ngas_before--; } dof_diff-=__dim__; ngas--; atoms->natms--; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::prep_s_x_buff() { im_root=true; for(int i=0;i<__dim__;i++) if(s_buff[i]<s_lo[i] || s_buff[i]>=s_hi[i]) im_root=false; int n_per_dim[__dim__]; type0 s; int no; ntrial_atms=1; for(int i=0;i<__dim__;i++) { no=0; s=s_buff[i]; for(type0 s_=s;s_<s_hi_ph[i];s_++) if(s_lo_ph[i]<=s_ && s_<s_hi_ph[i]) s_trials[i][no++]=s_; for(type0 s_=s-1.0;s_lo_ph[i]<=s_;s_--) if(s_lo_ph[i]<=s_ && s_<s_hi_ph[i]) s_trials[i][no++]=s_; ntrial_atms*=no; n_per_dim[i]=no; } int count[__dim__]; type0* buff=s_x_buff; int* cell_coord=cell_coord_buff; //type0 (&H)[__dim__][__dim__]=atoms->H; for(int i=0;i<__dim__;i++) count[i]=0; for(int i=0;i<ntrial_atms;i++) { for(int j=0;j<__dim__;j++) buff[j]=s_trials[j][count[j]]; find_cell_coord(buff,cell_coord); //XMatrixVector::s2x<__dim__>(buff,H); Algebra::S2X<__dim__>(atoms->__h,buff); count[0]++; for(int j=0;j<__dim__-1;j++) if(count[j]==n_per_dim[j]) { count[j]=0; count[j+1]++; } cell_coord+=__dim__; buff+=__dim__; } } /*-------------------------------------------- this is used for insertion trial --------------------------------------------*/ void SGCMC::reset_iatm() { itrial_atm=-1; next_iatm(); } /*-------------------------------------------- this is used for insertion trial --------------------------------------------*/ void SGCMC::next_iatm() { itrial_atm++; if(itrial_atm==ntrial_atms) { /*-------------------------------------------------- if we have reached the end of the list --------------------------------------------------*/ iatm=-1; return; } /*-------------------------------------------------- give the atom a number that cannot be the same as the existing ones: iatm=natms_lcl+natms_ph+itrial_atm; natms_lcl+natms_ph <= iatm iatm < natms_lcl+natms_ph+ntrial_atms --------------------------------------------------*/ if(itrial_atm==0 && im_root && xchng_mode==DEL_MODE) iatm=del_idx; else iatm=natms_lcl+itrial_atm; /*-------------------------------------------------- assign the cell number and the already calculated cell coordinates --------------------------------------------------*/ for(int i=0;i<__dim__;i++) icell_coord[i]=cell_coord_buff[__dim__*itrial_atm+i]; /*-------------------------------------------------- assign the position of iatm --------------------------------------------------*/ ix=s_x_buff+itrial_atm*__dim__; } /*-------------------------------------------- this is used for insertion trial --------------------------------------------*/ void SGCMC::reset_jatm() { ineigh=0; jatm_next=-1; next_jatm_reg(); } /*-------------------------------------------- find the next lcl atom --------------------------------------------*/ inline void SGCMC::next_jatm_reg() { while(true) { while(jatm_next==-1 && ineigh<nneighs) { bool lcl=true; jcell=0; for(int i=0;i<__dim__ && lcl;i++) { jcell_coord[i]=icell_coord[i]+rel_neigh_lst_coord[ineigh*__dim__+i]; jcell+=B_cells[i]*jcell_coord[i]; if(jcell_coord[i]<0 || jcell_coord[i]>N_cells[i]-1) lcl=false; } if(lcl) jatm_next=head_atm[jcell]; ineigh++; } jatm=jatm_next; if(jatm==-1) { if(itrial_atm==0 && im_root) { iself=0; next_jatm_p=&SGCMC::next_jatm_self; return next_jatm_self(); } else return; } jatm_next=next_vec_p->begin()[jatm]; if(jatm==iatm) continue; jx=atoms->x->begin()+__dim__*jatm; jelem=atoms->elem->begin()[jatm]; rsq=Algebra::RSQ<__dim__>(ix,jx); if(rsq>=cut_sq[ielem][jelem]) continue; if(tag_vec_p) tag_vec_p->begin()[jatm]=icomm; return; } } /*-------------------------------------------- find the next interactin image atom --------------------------------------------*/ inline void SGCMC::next_jatm_self() { while(true) { iself++; if(iself==ntrial_atms) { next_jatm_p=&SGCMC::next_jatm_reg; jatm=-1; return; } jatm=natms_lcl+iself; jx=s_x_buff+iself*__dim__; jelem=gas_type; rsq=Algebra::RSQ<__dim__>(ix,jx); if(rsq>=cut_sq[ielem][jelem]) continue; return; } } /*-------------------------------------------- find the next interactin image atom --------------------------------------------*/ void SGCMC::next_jatm() { (this->*next_jatm_p)(); } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::next_icomm() { icomm=-1; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::reset_icomm() { icomm=0; } /*-------------------------------------------- --------------------------------------------*/ inline void SGCMC::refresh() { for(int i=0;i<n_cells;i++) head_atm[i]=-1; int* next_vec=next_vec_p->begin()+natms_lcl-1; int* cell_vec=cell_vec_p->begin()+natms_lcl-1; for(int i=natms_lcl-1;i>-1;i--,next_vec--,cell_vec--) { *next_vec=head_atm[*cell_vec]; head_atm[*cell_vec]=i; } } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::reset_tag() { int* tag=tag_vec_p->begin(); for(int i=0;i<natms_lcl;i++) tag[i]=-1; }
28.387518
132
0.448029
sinamoeini
e87069c3a6cb3b029eef4ede77dc8578c9729216
813
cpp
C++
Interviewbit/two-pointers/intersection-of-sorted-arrays.cpp
jatin69/Revision-cpp
52742ea76ee2440d92b116252399360fef46e0c7
[ "MIT" ]
4
2020-01-16T14:49:46.000Z
2021-08-23T12:45:19.000Z
Interviewbit/two-pointers/intersection-of-sorted-arrays.cpp
jatin69/coding-practice
52742ea76ee2440d92b116252399360fef46e0c7
[ "MIT" ]
2
2018-06-06T13:08:11.000Z
2018-10-02T19:07:32.000Z
Interviewbit/two-pointers/intersection-of-sorted-arrays.cpp
jatin69/coding-practice
52742ea76ee2440d92b116252399360fef46e0c7
[ "MIT" ]
5
2018-10-02T13:49:16.000Z
2021-08-11T07:29:50.000Z
/* * Author : Jatin Rohilla * Date : 8-5-2019 * * Editor : Dev c++ 5.11 * Compiler : g++ 5.1.0 * flags : -std=c++14 * * link - https://www.interviewbit.com/problems/intersection-of-sorted-arrays/ */ #include<bits/stdc++.h> using namespace std; vector<int> intersect(const vector<int> &A, const vector<int> &B) { vector<int> res; int i=0; int j=0; while(i<A.size() && j<B.size()){ if(A[i]==B[j]){ res.push_back(A[i]); i++; j++; } else if(A[i] < B[j]){ i++; } else{ j++; } } return res; } int main(){ vector<int> A = {1,2,3,3,4,5,6}; vector<int> B = {3,3,5}; vector<int> res = intersect(A, B); for(auto it : res){ cout << it << " "; } return 0; }
16.26
78
0.463715
jatin69
e871800708f2bfcd67139cb614c0a8abff434087
2,214
cpp
C++
source/procedural_objects/triangulate_geometry.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
12
2019-04-16T17:35:53.000Z
2020-04-12T14:37:27.000Z
source/procedural_objects/triangulate_geometry.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
47
2019-05-27T15:24:43.000Z
2020-04-27T17:54:54.000Z
source/procedural_objects/triangulate_geometry.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
null
null
null
#include "triangulate_geometry.h" #include "procedural_object_system.h" #include "geometry_component.h" #include "geometry_system.h" #include "hierarchical_component.h" #include "hierarchical_system.h" #include "procedural_component.h" #include "geometry_operations/ear_clipping.h" #include <memory> namespace pagoda { const std::string TriangulateGeometry::sInputGeometry("in"); const std::string TriangulateGeometry::sOutputGeometry("out"); const char* TriangulateGeometry::name = "TriangulateGeometry"; TriangulateGeometry::TriangulateGeometry(ProceduralObjectSystemPtr objectSystem) : ProceduralOperation(objectSystem) { START_PROFILE; CreateInputInterface(sInputGeometry); CreateOutputInterface(sOutputGeometry); } TriangulateGeometry::~TriangulateGeometry() {} void TriangulateGeometry::DoWork() { START_PROFILE; auto geometrySystem = m_proceduralObjectSystem->GetComponentSystem<GeometrySystem>(); auto hierarchicalSystem = m_proceduralObjectSystem->GetComponentSystem<HierarchicalSystem>(); EarClipping<Geometry> earClipping; while (HasInput(sInputGeometry)) { // Geometry ProceduralObjectPtr inObject = GetInputProceduralObject(sInputGeometry); ProceduralObjectPtr outObject = CreateOutputProceduralObject(sOutputGeometry); std::shared_ptr<GeometryComponent> inGeometryComponent = geometrySystem->GetComponentAs<GeometryComponent>(inObject); std::shared_ptr<GeometryComponent> outGeometryComponent = geometrySystem->CreateComponentAs<GeometryComponent>(outObject); GeometryPtr inGeometry = inGeometryComponent->GetGeometry(); auto outGeometry = std::make_shared<Geometry>(); earClipping.Execute(inGeometry, outGeometry); outGeometryComponent->SetGeometry(outGeometry); outGeometryComponent->SetScope(inGeometryComponent->GetScope()); // Hierarchy std::shared_ptr<HierarchicalComponent> inHierarchicalComponent = hierarchicalSystem->GetComponentAs<HierarchicalComponent>(inObject); std::shared_ptr<HierarchicalComponent> outHierarchicalComponent = hierarchicalSystem->GetComponentAs<HierarchicalComponent>(outObject); hierarchicalSystem->SetParent(outHierarchicalComponent, inHierarchicalComponent); } } } // namespace pagoda
32.558824
116
0.81617
diegoarjz
e873a9d0c68d138b93eb8fe0f84ce9aed2359aa6
1,135
cpp
C++
yard/skills/66-cpp/apr-demo/apr-md5-test.cpp
paser4se/bbxyard
d09bc6efb75618b2cef047bad9c8b835043446cb
[ "Apache-2.0" ]
1
2016-03-29T02:01:58.000Z
2016-03-29T02:01:58.000Z
yard/skills/66-cpp/apr-demo/apr-md5-test.cpp
paser4se/bbxyard
d09bc6efb75618b2cef047bad9c8b835043446cb
[ "Apache-2.0" ]
18
2019-02-13T09:15:25.000Z
2021-12-09T21:32:13.000Z
yard/skills/66-cpp/apr-demo/apr-md5-test.cpp
paser4se/bbxyard
d09bc6efb75618b2cef047bad9c8b835043446cb
[ "Apache-2.0" ]
2
2020-07-05T01:01:30.000Z
2020-07-08T22:33:06.000Z
/* * ===================================================================================== * * Filename: apr-md5-test.cpp * * Description: apr md5 test * * Version: 1.0 * Created: 2014/08/14 22时06分07秒 * Revision: none * Compiler: gcc/g++ * * Author: bbxyard (Brian), bbxyard@gmail.com * Copyright: copyright (c) 2014, LGPL, bbxyard, http://www.bbxyard.com * * ===================================================================================== */ #include <stdlib.h> #include "apr.h" #include "apr_md5.h" void apr_md5_test(const void* buff, int size) { apr_md5_ctx_t ctx; apr_md5_init(); apr_md5_update(); apr_md5_final(); } /* * === FUNCTION ====================================================================== * Name: main * Author: bbxyard * Created: 2014/08/14 22时09分50秒 * Description: * ===================================================================================== */ int main (int argc, char *argv[]) { return EXIT_SUCCESS; } /* ---------- end of function main ---------- */
24.148936
88
0.38326
paser4se
e879e044c1fb4a7718bef0bd74098249eb26ddd2
5,067
cpp
C++
QuantExt/qle/models/projectedcrossassetmodel.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
QuantExt/qle/models/projectedcrossassetmodel.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
QuantExt/qle/models/projectedcrossassetmodel.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2020 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <qle/models/projectedcrossassetmodel.hpp> namespace QuantExt { boost::shared_ptr<CrossAssetModel> getProjectedCrossAssetModel(const boost::shared_ptr<CrossAssetModel>& model, const std::vector<std::pair<CrossAssetModelTypes::AssetType, Size> >& selectedComponents, std::vector<Size>& projectedStateProcessIndices) { projectedStateProcessIndices.clear(); // vectors holding the selected parametrizations and associated indices in the correlation matrix std::vector<boost::shared_ptr<Parametrization> > parametrizations; std::vector<Size> correlationIndices; // loop over selected components and fill // - parametrizations // - correlation indices // - state process indices for (auto const& c : selectedComponents) { parametrizations.push_back(model->parametrizations().at(model->idx(c.first, c.second))); for (Size b = 0; b < model->brownians(c.first, c.second); ++b) correlationIndices.push_back(model->cIdx(c.first, c.second, b)); for (Size p = 0; p < model->stateVariables(c.first, c.second); ++p) projectedStateProcessIndices.push_back(model->pIdx(c.first, c.second, p)); } // build correlation matrix Matrix correlation(correlationIndices.size(), correlationIndices.size()); for (Size j = 0; j < correlationIndices.size(); ++j) { correlation(j, j) = 1.0; for (Size k = 0; k < j; ++k) { correlation(k, j) = correlation(j, k) = model->correlation()(correlationIndices.at(j), correlationIndices.at(k)); } } // build projected cam and return it return boost::make_shared<CrossAssetModel>(parametrizations, correlation, model->salvagingAlgorithm()); } std::vector<Size> getStateProcessProjection(const boost::shared_ptr<CrossAssetModel>& model, const boost::shared_ptr<CrossAssetModel>& projectedModel) { std::vector<Size> stateProcessProjection(projectedModel->stateProcess()->size(), Null<Size>()); for (Size i = 0; i < model->components(IR); ++i) { for (Size j = 0; j < projectedModel->components(IR); ++j) { if (projectedModel->ir(j)->currency() == model->ir(i)->currency()) { for (Size k = 0; k < projectedModel->stateVariables(IR, j); ++k) { stateProcessProjection[projectedModel->pIdx(IR, j, k)] = model->pIdx(IR, i, k); } } } } for (Size i = 0; i < model->components(FX); ++i) { for (Size j = 0; j < projectedModel->components(FX); ++j) { if (projectedModel->fx(j)->currency() == model->fx(i)->currency()) { for (Size k = 0; k < projectedModel->stateVariables(FX, j); ++k) { stateProcessProjection[projectedModel->pIdx(FX, j, k)] = model->pIdx(FX, i, k); } } } } for (Size i = 0; i < model->components(INF); ++i) { for (Size j = 0; j < projectedModel->components(INF); ++j) { if (projectedModel->inf(j)->name() == model->inf(i)->name()) { for (Size k = 0; k < projectedModel->stateVariables(INF, j); ++k) { stateProcessProjection[projectedModel->pIdx(INF, j, k)] = model->pIdx(INF, i, k); } } } } for (Size i = 0; i < model->components(CR); ++i) { for (Size j = 0; j < projectedModel->components(CR); ++j) { if (projectedModel->cr(j)->name() == model->cr(i)->name()) { for (Size k = 0; k < projectedModel->stateVariables(CR, j); ++k) { stateProcessProjection[projectedModel->pIdx(CR, j, k)] = model->pIdx(CR, i, k); } } } } for (Size i = 0; i < model->components(EQ); ++i) { for (Size j = 0; j < projectedModel->components(EQ); ++j) { if (projectedModel->eq(j)->name() == model->eq(i)->name()) { for (Size k = 0; k < projectedModel->stateVariables(EQ, j); ++k) { stateProcessProjection[projectedModel->pIdx(EQ, j, k)] = model->pIdx(EQ, i, k); } } } } return stateProcessProjection; } } // namespace QuantExt
41.195122
117
0.600947
mrslezak
e87b6f023edd43aad0befbe7aec559d135808a55
5,116
cpp
C++
NativeCode/Plugin_SpatializerReverb.cpp
PStewart95/Unity
f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331
[ "MIT" ]
58
2020-03-05T09:20:59.000Z
2022-03-31T10:06:20.000Z
NativeCode/Plugin_SpatializerReverb.cpp
PStewart95/Unity
f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331
[ "MIT" ]
5
2021-01-18T12:47:27.000Z
2022-03-08T08:41:06.000Z
NativeCode/Plugin_SpatializerReverb.cpp
PStewart95/Unity
f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331
[ "MIT" ]
13
2020-09-14T09:50:41.000Z
2022-02-08T15:53:33.000Z
// Simple Velvet-noise based reverb just to demonstrate how to send data from Spatializer to a common mix buffer that is routed into the mixer. #include "AudioPluginUtil.h" float reverbmixbuffer[65536] = { 0 }; namespace SpatializerReverb { const int MAXTAPS = 1024; enum { P_DELAYTIME, P_DIFFUSION, P_NUM }; struct InstanceChannel { struct Tap { int pos; float amp; }; struct Delay { enum { MASK = 0xFFFFF }; int writepos; inline void Write(float x) { writepos = (writepos + MASK) & MASK; data[writepos] = x; } inline float Read(int delay) const { return data[(writepos + delay) & MASK]; } float data[MASK + 1]; }; Tap taps[1024]; Delay delay; }; struct EffectData { float p[P_NUM]; Random random; InstanceChannel ch[2]; }; int InternalRegisterEffectDefinition(UnityAudioEffectDefinition& definition) { int numparams = P_NUM; definition.paramdefs = new UnityAudioParameterDefinition[numparams]; RegisterParameter(definition, "Delay Time", "", 0.0f, 5.0f, 2.0f, 1.0f, 1.0f, P_DELAYTIME, "Delay time in seconds"); RegisterParameter(definition, "Diffusion", "%", 0.0f, 1.0f, 0.5f, 100.0f, 1.0f, P_DIFFUSION, "Diffusion amount"); return numparams; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK CreateCallback(UnityAudioEffectState* state) { EffectData* effectdata = new EffectData; memset(effectdata, 0, sizeof(EffectData)); state->effectdata = effectdata; InitParametersFromDefinitions(InternalRegisterEffectDefinition, effectdata->p); return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ReleaseCallback(UnityAudioEffectState* state) { EffectData* data = state->GetEffectData<EffectData>(); delete data; return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK SetFloatParameterCallback(UnityAudioEffectState* state, int index, float value) { EffectData* data = state->GetEffectData<EffectData>(); if (index >= P_NUM) return UNITY_AUDIODSP_ERR_UNSUPPORTED; data->p[index] = value; return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK GetFloatParameterCallback(UnityAudioEffectState* state, int index, float* value, char *valuestr) { EffectData* data = state->GetEffectData<EffectData>(); if (index >= P_NUM) return UNITY_AUDIODSP_ERR_UNSUPPORTED; if (value != NULL) *value = data->p[index]; if (valuestr != NULL) valuestr[0] = 0; return UNITY_AUDIODSP_OK; } int UNITY_AUDIODSP_CALLBACK GetFloatBufferCallback(UnityAudioEffectState* state, const char* name, float* buffer, int numsamples) { return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ProcessCallback(UnityAudioEffectState* state, float* inbuffer, float* outbuffer, unsigned int length, int inchannels, int outchannels) { if (inchannels != 2 || outchannels != 2) { memcpy(outbuffer, inbuffer, length * outchannels * sizeof(float)); return UNITY_AUDIODSP_OK; } EffectData* data = state->GetEffectData<EffectData>(); const float delaytime = data->p[P_DELAYTIME] * state->samplerate + 1.0f; const int numtaps = (int)(data->p[P_DIFFUSION] * (MAXTAPS - 2) + 1); data->random.Seed(0); for (int c = 0; c < 2; c++) { InstanceChannel& ch = data->ch[c]; const InstanceChannel::Tap* tap_end = ch.taps + numtaps; float decay = powf(0.01f, 1.0f / (float)numtaps); float p = 0.0f, amp = (decay - 1.0f) / (powf(decay, numtaps + 1) - 1.0f); InstanceChannel::Tap* tap = ch.taps; while (tap != tap_end) { p += data->random.GetFloat(0.0f, 100.0f); tap->pos = p; tap->amp = amp; amp *= decay; ++tap; } float scale = delaytime / p; tap = ch.taps; while (tap != tap_end) { tap->pos *= scale; ++tap; } for (int n = 0; n < length; n++) { ch.delay.Write(inbuffer[n * 2 + c] + reverbmixbuffer[n * 2 + c]); float s = 0.0f; const InstanceChannel::Tap* tap = ch.taps; while (tap != tap_end) { s += ch.delay.Read(tap->pos) * tap->amp; ++tap; } outbuffer[n * 2 + c] = s; } } memset(reverbmixbuffer, 0, sizeof(reverbmixbuffer)); return UNITY_AUDIODSP_OK; } }
31.006061
184
0.561572
PStewart95
e87bffa2d3aa6a268a397a246e9eafc797be18e9
1,005
cpp
C++
src/ctypes/annotation_optional.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
4,816
2017-12-12T18:07:09.000Z
2019-04-17T02:01:04.000Z
src/ctypes/annotation_optional.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
514
2017-12-12T18:22:52.000Z
2019-04-16T16:07:11.000Z
src/ctypes/annotation_optional.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
579
2017-12-12T18:38:02.000Z
2019-04-11T13:32:53.000Z
/** * @file src/ctypes/annotation_optional.cpp * @brief Implementation of @c optional annotation. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include <cassert> #include "retdec/ctypes/annotation_optional.h" #include "retdec/ctypes/context.h" namespace retdec { namespace ctypes { /** * @brief Creates @c optional annotation. * * @par Preconditions * - @a context is not null */ std::shared_ptr<AnnotationOptional> AnnotationOptional::create( const std::shared_ptr<Context> &context, const std::string &name) { assert(context && "violated precondition - context cannot be null"); auto annot = context->getAnnotation(name); if (annot && annot->isOptional()) { return std::static_pointer_cast<AnnotationOptional>(annot); } std::shared_ptr<AnnotationOptional> newAnnot(new AnnotationOptional(name)); context->addAnnotation(newAnnot); return newAnnot; } bool AnnotationOptional::isOptional() const { return true; } } // namespace ctypes } // namespace retdec
22.333333
76
0.744279
mehrdad-shokri
e87d53d3851d9e31961506fc18709be8060bb742
16,313
hpp
C++
include/gb/cpu.inc.hpp
nfsu/gb
bfbed4c0effa541fac1ed48e79544f054b8c7376
[ "MIT" ]
null
null
null
include/gb/cpu.inc.hpp
nfsu/gb
bfbed4c0effa541fac1ed48e79544f054b8c7376
[ "MIT" ]
null
null
null
include/gb/cpu.inc.hpp
nfsu/gb
bfbed4c0effa541fac1ed48e79544f054b8c7376
[ "MIT" ]
null
null
null
namespace gb { //Debugging template<bool isCb, typename ...args> _inline_ void Emulator::operation(const args &...arg) { oic::System::log()->debug(oic::Log::concat(std::hex, arg...), "\t\t; $", oic::Log::concat(std::hex, pc - 1 - isCb)); } const char *crName[] = { "b", "c", "d", "e", "h", "l", "(hl)", "a" }; const char *addrRegName[] = { "bc", "de", "hl+", "hl-" }; const char *shortRegName[] = { "bc", "de", "hl", "sp" }; const char *shortRegNameAf[] = { "bc", "de", "hl", "af" }; const char *aluName[] = { "add", "adc", "sub", "sbc", "and", "xor", "or", "cp" }; const char *condName[] = { "nz", "z", "nc", "c", "" }; //Function for setting a cr template<u8 cr, typename T> _inline_ void Emulator::set(const T &t) { m; if constexpr (cr != 6) regs[registerMapping[cr]] = t; else m.set(hl, t); } template<u8 c, typename T> _inline_ void Emulator::setc(const T &t) { set<(c >> 3) & 7>(t); } //Function for getting a cr template<u8 cr, typename T> _inline_ T Emulator::get() { m; if constexpr (cr == 6) return m.get<T>(hl); else if constexpr ((cr & 0x8) != 0) { const T t = m.get<T>(pc); pc += sizeof(T); return t; } else return regs[registerMapping[cr]]; } template<u8 c, typename T> _inline_ T Emulator::getc() { return get<c & 7, T>(); } //Special instructions _inline_ usz Emulator::halt() { //TODO: HALT operation("halt"); return 1; } _inline_ usz Emulator::stop() { //TODO: Stop operation("stop"); return 1; } template<bool enable, usz flag> _inline_ void Emulator::setFlag() { if constexpr (enable) m.getMemory<u8>(flag >> 8) |= flag & 0xFF; else m.getMemory<u8>(flag >> 8) &= ~(flag & 0xFF); } template<usz flag> _inline_ bool Emulator::getFlag() { return m.getMemory<u8>(flag >> 8) & (flag & 0xFF); } template<usz flag> _inline_ bool Emulator::getFlagFromAddress() { return m.getRef<u8>(flag >> 8) & (flag & 0xFF); } //LD operations //LD cr, cr template<u8 c> _inline_ usz Emulator::ld() { operation("ld ", crName[(c >> 3) & 7], ",", crName[c & 7]); setc<c, u8>(getc<c, u8>()); return (c & 0x7) == 6 || ((c >> 3) & 7) == 6 ? 2 : 1; } //LD cr, (pc) template<u8 s> _inline_ u16 Emulator::addrFromReg() { if constexpr (s < 2) return lregs[s]; else if constexpr (s == 2) { ++hl; return hl - 1; } else { --hl; return hl + 1; } } template<u8 c> _inline_ usz Emulator::ldi() { //LD cr, #8 if constexpr ((c & 7) == 6) { u8 v = get<8, u8>(); operation("ld ", crName[(c >> 3) & 7], ",", u16(v)); setc<c>(v); } //LD (nn), A else if constexpr ((c & 0xF) == 2) { operation("ld (", addrRegName[c >> 4], "),a"); m[addrFromReg<u8(c >> 4)>()] = a; } //LD A, (nn) else { operation("ld a,(", addrRegName[c >> 4], ")"); a = m[addrFromReg<u8(c >> 4)>()]; } return c == 0x36 ? 3 : 2; } //LD A, (a16) / LD (a16), A template<u8 c> _inline_ usz Emulator::lds() { operation("ld ", shortRegName[c / 16], ",", m.get<u16>(pc)); shortReg<c>() = m.get<u16>(pc); pc += 2; return 3; } //All alu operations (ADD/ADC/SUB/SUBC/AND/XOR/OR/CP) template<u8 c> _inline_ usz Emulator::performAlu(u8 b) { static constexpr u8 code = c & 0x3F; if constexpr (code < 0x08) emu::addTo(f, a, b); else if constexpr (code < 0x10) emu::adcTo(f, a, b); else if constexpr (code < 0x18) emu::subFrom(f, a, b); else if constexpr (code < 0x20) emu::sbcFrom(f, a, b); else if constexpr (code < 0x28) emu::andInto(f, a, b); else if constexpr (code < 0x30) emu::eorInto(f, a, b); else if constexpr (code < 0x38) emu::orrInto(f, a, b); else emu::sub(f, a, b); return 1; } template<u8 c> _inline_ usz Emulator::aluOp() { //(HL) or (pc) if constexpr ((c & 7) == 6) { if constexpr (c < 0xC0) { operation(aluName[(c >> 3) & 7], " a,(hl)"); return performAlu<c>(m[hl]); } else { operation(aluName[(c >> 3) & 7], " a,", u16(m[pc])); usz v = performAlu<c>(m[pc]); ++pc; return v; } } //Reg ALU else { operation(aluName[(c >> 3) & 7], " a,", crName[c & 7]); return performAlu<c>(regs[c & 7]); } } //RST x instruction template<u8 addr> _inline_ usz Emulator::reset() { operation("rst ", u16(addr)); Stack::push(m, sp, pc); pc = addr; return 4; } template<u8 c> _inline_ usz Emulator::rst() { return reset<(c & 0x30) | (c & 0x8)>(); } //Condtional calls template<u8 c> _inline_ bool Emulator::cond() { static constexpr u8 condition = (c >> 3) & 3; if constexpr (condition == 0) return !f.zero(); else if constexpr (condition == 1) return f.zero(); else if constexpr (condition == 2) return !f.carry(); else return f.carry(); } //JR/JP calls template<u8 jp, u8 check> _inline_ usz Emulator::branch() { //Print operation if constexpr ((jp & 3) == 3) operation("ret", jp & 8 ? "i" : " ", check != 0 ? condName[(check >> 3) & 3] : ""); else if constexpr (inRegion<jp & 3, 1, 3>) operation((jp & 3) == 1 ? "jp " : "call ", check != 0 ? condName[(check >> 3) & 3] : "", check != 0 ? "," : "", jp & 4 ? "(hl)" : oic::Log::num<16>(m.get<u16>(pc)) ); else if constexpr ((jp & 3) == 0) operation("jr ", check != 0 ? condName[(check >> 3) & 3] : "", check != 0 ? "," : "", i32(m.get<i8>(pc)) ); //Jump if check failed if constexpr (check != 0) if (!cond<check>()) { //2-width instructions if constexpr (inRegion<jp & 3, 1, 3>) { pc += 2; return 3; } //1-width instructions else if constexpr ((jp & 3) == 0) { ++pc; return 2; } else return 2; } //RET if constexpr ((jp & 3) == 3) { Stack::pop(m, sp, pc); if constexpr ((jp & 8) != 0) //RETI setFlag<true, Emulator::IME>(); return check == 0 ? 4 : 5; } //JP/CALL else if constexpr (inRegion<jp & 3, 1, 3>) { //CALL if constexpr ((jp & 3) == 2) Stack::push(m, sp, pc + 2); if constexpr ((jp & 4) != 0) pc = m.get<u16>(hl); else pc = m.get<u16>(pc); return 2 + jp * 2; } //JR else { pc += u16(i16(m.get<i8>(pc))); ++pc; return 3; } } template<u8 c, u8 code> _inline_ usz Emulator::jmp() { if constexpr (c == 0x18) return branch<0, 0>(); //JR else if constexpr (c < 0x40) return branch<0, c>(); //JR conditional else if constexpr (c == 0xC3) return branch<1, 0>(); //JP else if constexpr (code == 2) return branch<1, c>(); //JP conditional else if constexpr (c == 0xCD) return branch<2, 0>(); //CALL else if constexpr (code == 4) return branch<2, c>(); //CALL conditional else if constexpr (c == 0xE9) return branch<5, 0>(); //JP (HL) else if constexpr (c == 0xC9) return branch<7, 0>(); //RET else if constexpr (c == 0xD9) return branch<15, 0>(); //RETI else return branch<3, c>(); //RET conditional } //INC/DEC x instructions template<u8 c> _inline_ usz Emulator::inc() { static constexpr u8 add = c & 1 ? u8_MAX : 1; static constexpr u8 r1 = (c >> 3) & 7; if constexpr ((c & 1) == 0) { operation("inc ", crName[r1]); f.clearSubtract(); } else { operation("dec ", crName[r1]); f.setSubtract(); } u8 v; if constexpr (r1 != 6) v = regs[registerMapping[r1]] += add; else v = m[hl] += add; f.carryHalf(v & 0x10); f.zero(v == 0); return r1 == 6 ? 3 : 1; } //Short register functions template<u8 c> _inline_ u16 &Emulator::shortReg() { if constexpr (((c >> 4) & 3) < 3) return lregs[c >> 4]; else return sp; } template<u8 c> _inline_ usz Emulator::incs() { static constexpr u16 add = c & 8 ? u16_MAX : 1; operation(c & 8 ? "dec " : "inc ", shortRegName[(c >> 4) & 3]); shortReg<c>() += add; return 2; } //Every case runs through this template<u8 c, u8 start, u8 end> static constexpr bool inRegion = c >= start && c < end; template<u8 c, u8 code, u8 hi> static constexpr bool isJump = (inRegion<c, 0x18, 0x40> && code == 0) || //JR (inRegion<c, 0xC0, 0xE0> && ( //JP/RET/CALL code == 0 || //RET conditional code == 2 || //JP conditional code == 4 || //CALL conditional c == 0xC3 || //JP hi == 9 || //RET/RETI c == 0xCD //CALL )) || c == 0xE9; //JP (HL) enum OpCode : u8 { NOP = 0x00, STOP = 0x10, HALT = 0x76, DI = 0xF3, EI = 0xFB }; template<u8 c> _inline_ usz Emulator::opCb() { static constexpr u8 p = (c >> 3) & 7; static constexpr u8 cr = c & 7; //Barrel shifts if constexpr (c < 0x40) { f.clearSubtract(); f.clearHalf(); u8 i = get<cr, u8>(), j = i; j; //RLC (rotate to the left) if constexpr (p == 0) { operation("rlc ", crName[cr]); a = i = u8(i << 1) | u8(i >> 7); } //RRC (rotate to the right) else if constexpr (p == 1) { operation("rrc ", crName[cr]); a = i = u8(i >> 1) | u8(i << 7); } //RL (<<1 shift in carry) else if constexpr (p == 2) { operation("rl ", crName[cr]); a = i = (i << 1) | u8(f.carry()); } //RR (>>1 shift in carry) else if constexpr (p == 3) { operation("rr ", crName[cr]); a = i = (i >> 1) | u8(0x80 * f.carry()); } //SLA (a = cr << 1) else if constexpr (p == 4) { operation("sla ", crName[cr]); a = i <<= 1; } //SRA (a = cr >> 1 (maintain sign)) else if constexpr (p == 5) { operation("sra ", crName[cr]); a = i = (i >> 1) | (i & 0x80); } //Swap two nibbles else if constexpr (p == 6) { operation("swap ", crName[cr]); a = i = u8(i << 4) | (i >> 4); } //SRL else { operation("srl ", crName[cr]); a = i >>= 1; } //Set carry if constexpr ((p & 1) == 1) //Shifted to the left f.carry(j & 1); else if constexpr (p < 6) //Shifted to the right f.carry(j & 0x80); else //N.A. f.clearCarry(); //Set zero f.zero(i == 0); } //Bit masks else if constexpr (c < 0x80) { operation<true>("bit ", std::to_string(p), ",", crName[cr]); f.setHalf(); f.clearSubtract(); f.zero(!(get<cr, u8>() & (1 << p))); } //Reset bit else if constexpr (c < 0xC0) { operation<true>("res ", std::to_string(p), ",", crName[cr]); set<cr, u8>(get<cr, u8>() & ~(1 << p)); } //Set bit else { operation<true>("set ", std::to_string(p), ",", crName[cr]); set<cr, u8>(get<cr, u8>() | (1 << p)); } return cr == 6 ? 4 : 2; } template<u8 i> _inline_ usz Emulator::op256() { static constexpr u8 code = i & 0x07, hi = i & 0xF; if constexpr (i == NOP) { operation("nop"); return 1; } else if constexpr (i == STOP) return stop(); else if constexpr (i == HALT) return halt(); //DI/EI; disable/enable interrupts else if constexpr (i == DI || i == EI) { operation(i == DI ? "di" : "ei"); setFlag<i == EI, Emulator::IME>(); return 1; } //LD (a16), SP instruction; TODO: else if constexpr (i == 0x8) { m.set(m.get<u16>(pc), sp); pc += 2; return 5; } //RET, JP, JR and CALL else if constexpr (isJump<i, code, hi>) return jmp<i, code>(); //RLCA, RLA, RRCA, RRA else if constexpr (i < 0x20 && code == 7) return opCb<i>(); else if constexpr (i < 0x40) { if constexpr (hi == 1) return lds<i>(); else if constexpr (hi == 0x9) { operation("add hl,", shortRegName[(i >> 4) & 3]); u16 hl_ = hl; hl += shortReg<i>(); f.clearSubtract(); f.carryHalf(hl & 0x10); f.carry(hl < hl_); return 2; } else if constexpr (code == 3) return incs<i>(); else if constexpr (code == 4 || code == 5) return inc<i>(); else if constexpr (code == 2 || code == 6) return ldi<i>(); //SCF, CCF else if constexpr (i == 0x37 || i == 0x3F) { operation(i == 0x37 ? "scf" : "ccf"); f.clearSubtract(); f.clearHalf(); if constexpr (i == 0x37) f.setCarry(); else f.carry(!f.carry()); return 1; } //CPL else if constexpr (i == 0x2F) { operation("cpl"); f.setSubtract(); f.setHalf(); a = ~a; return 1; } //DAA else if constexpr (i == 0x27) { operation("daa"); u8 k = 0, j = a; f.clearCarry(); if (f.carryHalf() || (!f.subtract() && (j & 0xF) > 0x9)) k |= 0x6; if (f.carry() || (!f.subtract() && j > 0x99)) { k |= 0x60; f.setCarry(); } a = j += u8(-i8(k)); f.clearHalf(); f.zero(j == 0); return 1; } //TODO: LD (a16), SP else throw std::exception(); } else if constexpr (i < 0x80) return ld<i>(); else if constexpr (i < 0xC0 || code == 0x6) return aluOp<i>(); else if constexpr (code == 0x7) return rst<i>(); //LD (a8/a16/C)/A, (a8/a16/C)/A else if constexpr (i >= 0xE0 && (hi == 0x0 || hi == 0x2 || hi == 0xA)) { u16 addr; //TODO: ??? if constexpr (hi == 0x0) { const u8 im = m[pc]; operation( "ldh ", i < 0xF0 ? oic::Log::num<16>((u16)im) : "a", ",", i >= 0xF0 ? oic::Log::num<16>((u16)im) : "a" ); addr = 0xFF00 | im; ++pc; } else if constexpr (hi == 0x2) { operation("ld ", i < 0xF0 ? "(c)," : "a,", i >= 0xF0 ? "(c)" : "a"); addr = 0xFF00 | c; } else { const u16 j = m.get<u16>(pc); operation( "ld ", i < 0xF0 ? oic::Log::num<16>(j) : "a", ",", i >= 0xF0 ? oic::Log::num<16>(j) : "a" ); addr = j; pc += 2; } if constexpr (i < 0xF0) //Store m[addr] = a; else //Load a = m[addr]; return 1; } //CB instructions (mask, reset, set, rlc/rrc/rl/rr/sla/sra/swap/srl) else if constexpr (i == 0xCB) return cbInstruction(); //PUSH/POP else if constexpr (hi == 1 || hi == 5) { static constexpr u8 reg = (i - 0xC0) >> 4; operation(hi == 1 ? "pop " : "push ", shortRegNameAf[reg]); //Push to or pop from stack if constexpr (hi == 1) Stack::pop(m, sp, lregs[reg]); else Stack::push(m, sp, lregs[reg]); return hi == 1 ? 3 : 4; } //LD HL, SP+a8 else if constexpr (i == 0xF8) { operation("ld hl, sp+", u16(m[pc])); hl = emu::add(f, sp, u16(m[pc])); ++pc; f.clearZero(); return 3; } //TODO: ADD SP, r8 //TODO: LD HL, SP+a8 //TODO: LD SP, HL else //Undefined operation throw std::exception(); } //Switch case of all opcodes //For our switch case of 256 entries #define case1(x,y) case x: return op##y<x>(); #define case2(x,y) case1(x,y) case1(x + 1,y) #define case4(x,y) case2(x,y) case2(x + 2,y) #define case8(x,y) case4(x,y) case4(x + 4,y) #define case16(x,y) case8(x,y) case8(x + 8,y) #define case32(x,y) case16(x,y) case16(x + 16,y) #define case64(x,y) case32(x,y) case32(x + 32,y) #define case128(x,y) case64(x,y) case64(x + 64,y) #define case256(y) case128(0,y) case128(128,y) _inline_ usz Emulator::cbInstruction() { u8 opCode = m[pc]; print(u16(opCode), '\t'); ++pc; switch (opCode) { case256(Cb) } return 0; } _inline_ usz Emulator::cpuStep() { u8 &mem = m.getMemory<u8>(Emulator::IS_IN_BIOS >> 8); constexpr u8 bit = Emulator::IS_IN_BIOS & 0xFF; if (mem & bit && pc >= MemoryMapper::biosLength) mem &= ~bit; u8 opCode = m[pc]; print(std::hex, pc, ' ', u16(opCode), '\t'); ++pc; switch (opCode) { case256(256) } return 0; } _inline usz Emulator::interruptHandler() { #ifndef NDEBUG print( u16(a), " ", u16(b), " ", u16(c), " ", u16(d), " ", u16(e), " ", u16(f.v), " ", sp, "\n" ); /*if((pc >= 0x2A0 && pc < 0x2795) || pc >= 0x27A3) system("pause");*/ #endif usz counter {}; if (getFlag<Emulator::IME>()) { u8 &u = m.getRef<u8>(io::IF); const u8 &enabled = m.getRef<u8>(io::IE); const u8 g = u & enabled; u &= ~g; //Mark as handled if (g) setFlag<false, Emulator::IME>(); if (g & 1) //V-Blank counter += reset<0x40>(); if (g & 2) //LCD STAT counter += reset<0x48>(); if (g & 4) //Timer counter += reset<0x50>(); if (g & 8) //Serial counter += reset<0x58>(); if (g & 16) //Joypad counter += reset<0x60>(); } return counter; } }
19.443385
118
0.518482
nfsu
e87e40bb54d3ff3333c68a07c392b39b4763d71b
4,492
cpp
C++
commandsFonts.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
7
2018-04-24T22:11:58.000Z
2021-09-10T22:12:35.000Z
commandsFonts.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
36
2018-02-24T18:34:18.000Z
2021-08-08T10:33:29.000Z
commandsFonts.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
2
2018-10-22T18:47:30.000Z
2020-09-16T06:10:52.000Z
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <string> #include <iostream> #include <vector> #include <string> #ifdef __amigaos4__ #include <proto/exec.h> #include <proto/exec.h> #include <proto/dos.h> #include <proto/diskfont.h> #include <proto/graphics.h> #include <proto/retroMode.h> #include "amosString.h" extern struct RastPort font_render_rp; #endif #ifdef __linux__ #include "os/linux/stuff.h" #endif #include <amosKittens.h> #include <stack.h> #include "debug.h" #include "commandsFonts.h" #include "kittyErrors.h" #include "engine.h" extern struct TextFont *open_font( char const *filename, int size ); extern struct TextFont *gfx_font ; using namespace std; class font { public: string amosString; string name; int size; }; vector<font> fonts; void set_font_buffer( char *buffer, char *name, int size, char *type ) { char *c; char *b; int n; memset(buffer,' ',37); // char 0 to 36 buffer[37]=0; n = 0; b = buffer; for (c=name;(*c) && (n<37);c++) { *b++=*c; n++; } n = 0; b = buffer+37-4; for (c=type;(*c) && (n<4);c++) { *b++=*c; n++; } b = buffer+37-6; while (size) { n = size % 10; size /=10; *b-- = n + '0'; } } void getfonts(char *buffer, int source_type ) { int32 afShortage, afSize; struct AvailFontsHeader *afh; struct AvailFonts *_fonts; font tfont; afSize = 400; do { afh = (struct AvailFontsHeader *) AllocVecTags(afSize, TAG_END); if (afh) { afShortage = AvailFonts( (char *) afh, afSize, AFF_MEMORY | AFF_DISK); if (afShortage) { FreeVec(afh); afSize += afShortage; } else { int n; _fonts = (AvailFonts *) ((char *) afh + sizeof(uint16_t)); for (n=0;n<afh -> afh_NumEntries;n++) { if ((_fonts -> af_Type | source_type ) && (_fonts -> af_Attr.ta_Style == FS_NORMAL)) { set_font_buffer(buffer, (char *) _fonts -> af_Attr.ta_Name, _fonts -> af_Attr.ta_YSize, (char *) "disc"); tfont.amosString =buffer; tfont.name = _fonts -> af_Attr.ta_Name; tfont.size = _fonts -> af_Attr.ta_YSize; fonts.push_back(tfont); } _fonts++; } FreeVec(afh); } } else { printf("AllocMem of AvailFonts buffer afh failed\n"); break; } } while (afShortage); } char *fontsGetRomFonts(struct nativeCommand *cmd, char *tokenBuffer) { char buffer[39]; fonts.erase( fonts.begin(), fonts.end() ); getfonts( buffer, AFF_MEMORY ); return tokenBuffer; } char *fontsGetDiscFonts(struct nativeCommand *cmd, char *tokenBuffer) { char buffer[39]; fonts.erase( fonts.begin(), fonts.end() ); getfonts( buffer, AFF_DISK ); return tokenBuffer; } char *fontsGetAllFonts(struct nativeCommand *cmd, char *tokenBuffer) { char buffer[39]; fonts.erase( fonts.begin(), fonts.end() ); getfonts( buffer, AFF_DISK | AFF_MEMORY ); return tokenBuffer; } char *_fontsSetFont( struct glueCommands *data, int nextToken ) { int args =__stack - data->stack +1 ; int ret = 0; printf("%s:%d\n",__FUNCTION__,__LINE__); switch (args) { case 1: ret = getStackNum(__stack ) ; if ((ret>=0)&&(ret<=(int) fonts.size())) { if (gfx_font) CloseFont(gfx_font); gfx_font = open_font( fonts[ret].name.c_str(),fonts[ret].size ); engine_lock(); if (engine_ready()) { SetFont( &font_render_rp, gfx_font ); } engine_unlock(); } break; default: setError(22,data->tokenBuffer); } popStack(__stack - data->stack ); return NULL; } char *fontsSetFont(struct nativeCommand *cmd, char *tokenBuffer) { stackCmdNormal( _fontsSetFont, tokenBuffer ); setStackNone(); return tokenBuffer; } char *_fontsFontsStr( struct glueCommands *data, int nextToken ) { int args =__stack - data->stack +1 ; unsigned int index; string font; printf("%s:%d\n",__FUNCTION__,__LINE__); switch (args) { case 1: index = (unsigned int) getStackNum(__stack); if ((index>0) && (index <= fonts.size())) { popStack(__stack - data->stack ); setStackStr( toAmosString( fonts[ index-1 ].amosString.c_str(), strlen(fonts[ index-1 ].amosString.c_str()) ) ); return NULL; } break; default: setError(22,data->tokenBuffer); } popStack(__stack - data->stack ); setStackStrDup(toAmosString("",0)); return NULL; } char *fontsFontsStr(struct nativeCommand *cmd, char *tokenBuffer) { stackCmdParm( _fontsFontsStr, tokenBuffer ); setStackNone(); return tokenBuffer; }
18.716667
111
0.645147
SamuraiCrow
e88370976cedbfad1e32e280b392f31c1c9f4233
22,540
cc
C++
ash/message_center/notifier_settings_view.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ash/message_center/notifier_settings_view.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ash/message_center/notifier_settings_view.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/message_center/notifier_settings_view.h" #include <stddef.h> #include <set> #include <string> #include <utility> #include "ash/message_center/message_center_controller.h" #include "ash/message_center/message_center_style.h" #include "ash/message_center/message_center_view.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/tray/tray_constants.h" #include "base/macros.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "skia/ext/image_operations.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/compositor/paint_recorder.h" #include "ui/events/event_utils.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image.h" #include "ui/gfx/skia_paint_util.h" #include "ui/message_center/message_center.h" #include "ui/message_center/public/cpp/message_center_constants.h" #include "ui/message_center/vector_icons.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/controls/button/toggle_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/link.h" #include "ui/views/controls/link_listener.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/scrollbar/overlay_scroll_bar.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/painter.h" #include "ui/views/widget/widget.h" namespace ash { using message_center::MessageCenter; using mojom::NotifierUiData; using message_center::NotifierId; namespace { const int kNotifierButtonWrapperHeight = 48; const int kHorizontalMargin = 12; const int kEntryIconSize = 20; const int kInternalHorizontalSpacing = 16; const int kSmallerInternalHorizontalSpacing = 12; const int kCheckboxSizeWithPadding = 28; // The width of the settings pane in pixels. const int kWidth = 360; // The minimum height of the settings pane in pixels. const int kMinimumHeight = 480; // Checkboxes have some built-in right padding blank space. const int kInnateCheckboxRightPadding = 2; // Spec defines the checkbox size; the innate padding throws this measurement // off so we need to compute a slightly different area for the checkbox to // inhabit. constexpr int kComputedCheckboxSize = kCheckboxSizeWithPadding - kInnateCheckboxRightPadding; // A function to create a focus border. std::unique_ptr<views::Painter> CreateFocusPainter() { return views::Painter::CreateSolidFocusPainter( message_center::kFocusBorderColor, gfx::Insets(1, 2, 3, 2)); } // TODO(tetsui): Give more general names and remove kEntryHeight, etc. constexpr gfx::Insets kTopLabelPadding(16, 18, 15, 18); const int kQuietModeViewSpacing = 18; constexpr gfx::Insets kHeaderViewPadding(4, 0); constexpr gfx::Insets kQuietModeViewPadding(0, 18, 0, 0); constexpr gfx::Insets kQuietModeLabelPadding(16, 0, 15, 0); constexpr gfx::Insets kQuietModeTogglePadding(0, 14); constexpr SkColor kTopLabelColor = gfx::kGoogleBlue500; constexpr SkColor kLabelColor = SkColorSetA(SK_ColorBLACK, 0xDE); constexpr SkColor kTopBorderColor = SkColorSetA(SK_ColorBLACK, 0x1F); constexpr SkColor kDisabledNotifierFilterColor = SkColorSetA(SK_ColorWHITE, 0xB8); const int kLabelFontSizeDelta = 1; // NotifierButtonWrapperView --------------------------------------------------- // A wrapper view of NotifierButton to guarantee the fixed height // |kNotifierButtonWrapperHeight|. The button is placed in the middle of // the wrapper view by giving padding to the top and the bottom. // The view is focusable and provides focus painter. When the button is disabled // (NotifierUiData.enforced), it also applies filter to make the color of the // button dim. class NotifierButtonWrapperView : public views::View { public: explicit NotifierButtonWrapperView(views::View* contents); ~NotifierButtonWrapperView() override; // views::View: void Layout() override; gfx::Size CalculatePreferredSize() const override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; void OnFocus() override; bool OnKeyPressed(const ui::KeyEvent& event) override; bool OnKeyReleased(const ui::KeyEvent& event) override; void OnPaint(gfx::Canvas* canvas) override; void OnBlur() override; private: // Initialize |disabled_filter_|. Should be called once. void CreateDisabledFilter(); std::unique_ptr<views::Painter> focus_painter_; // NotifierButton to wrap. views::View* contents_; // A view to add semi-transparent filter on top of |contents_|. // It is only visible when NotifierButton is disabled (e.g. the setting is // enforced by administrator.) The color of the NotifierButton would be dim // and users notice they can't change the setting. views::View* disabled_filter_ = nullptr; DISALLOW_COPY_AND_ASSIGN(NotifierButtonWrapperView); }; NotifierButtonWrapperView::NotifierButtonWrapperView(views::View* contents) : focus_painter_(CreateFocusPainter()), contents_(contents) { AddChildView(contents); } NotifierButtonWrapperView::~NotifierButtonWrapperView() = default; void NotifierButtonWrapperView::Layout() { int contents_width = width(); int contents_height = contents_->GetHeightForWidth(contents_width); int y = std::max((height() - contents_height) / 2, 0); contents_->SetBounds(0, y, contents_width, contents_height); // Since normally we don't show |disabled_filter_|, initialize it lazily. if (!contents_->enabled()) { if (!disabled_filter_) CreateDisabledFilter(); disabled_filter_->SetVisible(true); gfx::Rect filter_bounds = GetContentsBounds(); filter_bounds.set_width(filter_bounds.width() - kEntryIconSize); disabled_filter_->SetBoundsRect(filter_bounds); } else if (disabled_filter_) { disabled_filter_->SetVisible(false); } SetFocusBehavior(contents_->enabled() ? FocusBehavior::ALWAYS : FocusBehavior::NEVER); } gfx::Size NotifierButtonWrapperView::CalculatePreferredSize() const { return gfx::Size(kWidth, kNotifierButtonWrapperHeight); } void NotifierButtonWrapperView::GetAccessibleNodeData( ui::AXNodeData* node_data) { contents_->GetAccessibleNodeData(node_data); } void NotifierButtonWrapperView::OnFocus() { views::View::OnFocus(); ScrollRectToVisible(GetLocalBounds()); // We render differently when focused. SchedulePaint(); } bool NotifierButtonWrapperView::OnKeyPressed(const ui::KeyEvent& event) { return contents_->OnKeyPressed(event); } bool NotifierButtonWrapperView::OnKeyReleased(const ui::KeyEvent& event) { return contents_->OnKeyReleased(event); } void NotifierButtonWrapperView::OnPaint(gfx::Canvas* canvas) { View::OnPaint(canvas); views::Painter::PaintFocusPainter(this, canvas, focus_painter_.get()); } void NotifierButtonWrapperView::OnBlur() { View::OnBlur(); // We render differently when focused. SchedulePaint(); } void NotifierButtonWrapperView::CreateDisabledFilter() { DCHECK(!disabled_filter_); disabled_filter_ = new views::View; disabled_filter_->SetBackground( views::CreateSolidBackground(kDisabledNotifierFilterColor)); disabled_filter_->set_can_process_events_within_subtree(false); AddChildView(disabled_filter_); } // ScrollContentsView ---------------------------------------------------------- class ScrollContentsView : public views::View { public: ScrollContentsView() = default; private: void PaintChildren(const views::PaintInfo& paint_info) override { views::View::PaintChildren(paint_info); if (y() == 0) return; // Draw a shadow at the top of the viewport when scrolled. const ui::PaintContext& context = paint_info.context(); gfx::Rect shadowed_area(0, 0, width(), -y()); ui::PaintRecorder recorder(context, size()); gfx::Canvas* canvas = recorder.canvas(); gfx::ShadowValues shadow; shadow.emplace_back( gfx::Vector2d(0, message_center_style::kScrollShadowOffsetY), message_center_style::kScrollShadowBlur, message_center_style::kScrollShadowColor); cc::PaintFlags flags; flags.setLooper(gfx::CreateShadowDrawLooper(shadow)); flags.setAntiAlias(true); canvas->ClipRect(shadowed_area, SkClipOp::kDifference); canvas->DrawRect(shadowed_area, flags); } DISALLOW_COPY_AND_ASSIGN(ScrollContentsView); }; // EmptyNotifierView ----------------------------------------------------------- class EmptyNotifierView : public views::View { public: EmptyNotifierView() { auto layout = std::make_unique<views::BoxLayout>( views::BoxLayout::kVertical, gfx::Insets(), 0); layout->set_main_axis_alignment( views::BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); layout->set_cross_axis_alignment( views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); SetLayoutManager(std::move(layout)); views::ImageView* icon = new views::ImageView(); icon->SetImage(gfx::CreateVectorIcon( kNotificationCenterEmptyIcon, message_center_style::kEmptyIconSize, message_center_style::kEmptyViewColor)); icon->SetBorder( views::CreateEmptyBorder(message_center_style::kEmptyIconPadding)); AddChildView(icon); views::Label* label = new views::Label( l10n_util::GetStringUTF16(IDS_ASH_MESSAGE_CENTER_NO_NOTIFIERS)); label->SetEnabledColor(message_center_style::kEmptyViewColor); // "Roboto-Medium, 12sp" is specified in the mock. label->SetFontList( gfx::FontList().DeriveWithWeight(gfx::Font::Weight::MEDIUM)); AddChildView(label); } private: DISALLOW_COPY_AND_ASSIGN(EmptyNotifierView); }; } // namespace // NotifierSettingsView::NotifierButton --------------------------------------- // We do not use views::Checkbox class directly because it doesn't support // showing 'icon'. NotifierSettingsView::NotifierButton::NotifierButton( const mojom::NotifierUiData& notifier_ui_data, views::ButtonListener* listener) : views::Button(listener), notifier_id_(notifier_ui_data.notifier_id), icon_view_(new views::ImageView()), name_view_(new views::Label(notifier_ui_data.name)), checkbox_(new views::Checkbox(base::string16(), true /* force_md */)) { name_view_->SetAutoColorReadabilityEnabled(false); name_view_->SetEnabledColor(kLabelColor); // "Roboto-Regular, 13sp" is specified in the mock. name_view_->SetFontList( gfx::FontList().DeriveWithSizeDelta(kLabelFontSizeDelta)); checkbox_->SetChecked(notifier_ui_data.enabled); checkbox_->set_listener(this); checkbox_->SetFocusBehavior(FocusBehavior::NEVER); checkbox_->SetAccessibleName(notifier_ui_data.name); if (notifier_ui_data.enforced) { Button::SetEnabled(false); checkbox_->SetEnabled(false); } UpdateIconImage(notifier_ui_data.icon); } NotifierSettingsView::NotifierButton::~NotifierButton() = default; void NotifierSettingsView::NotifierButton::UpdateIconImage( const gfx::ImageSkia& icon) { if (icon.isNull()) { icon_view_->SetImage(gfx::CreateVectorIcon( message_center::kProductIcon, kEntryIconSize, gfx::kChromeIconGrey)); } else { icon_view_->SetImage(icon); icon_view_->SetImageSize(gfx::Size(kEntryIconSize, kEntryIconSize)); } GridChanged(); } void NotifierSettingsView::NotifierButton::SetChecked(bool checked) { checkbox_->SetChecked(checked); } bool NotifierSettingsView::NotifierButton::checked() const { return checkbox_->checked(); } void NotifierSettingsView::NotifierButton::ButtonPressed( views::Button* button, const ui::Event& event) { DCHECK_EQ(button, checkbox_); // The checkbox state has already changed at this point, but we'll update // the state on NotifierSettingsView::ButtonPressed() too, so here change // back to the previous state. checkbox_->SetChecked(!checkbox_->checked()); Button::NotifyClick(event); } void NotifierSettingsView::NotifierButton::GetAccessibleNodeData( ui::AXNodeData* node_data) { static_cast<views::View*>(checkbox_)->GetAccessibleNodeData(node_data); } void NotifierSettingsView::NotifierButton::GridChanged() { using views::ColumnSet; using views::GridLayout; GridLayout* layout = SetLayoutManager(std::make_unique<GridLayout>(this)); ColumnSet* cs = layout->AddColumnSet(0); // Add a column for the checkbox. cs->AddPaddingColumn(0, kInnateCheckboxRightPadding); cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::FIXED, kComputedCheckboxSize, 0); cs->AddPaddingColumn(0, kInternalHorizontalSpacing); // Add a column for the icon. cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::FIXED, kEntryIconSize, 0); cs->AddPaddingColumn(0, kSmallerInternalHorizontalSpacing); // Add a column for the name. cs->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); // Add a padding column which contains expandable blank space. cs->AddPaddingColumn(1, 0); layout->StartRow(0, 0); layout->AddView(checkbox_); layout->AddView(icon_view_); layout->AddView(name_view_); if (!enabled()) { views::ImageView* policy_enforced_icon = new views::ImageView(); policy_enforced_icon->SetImage(gfx::CreateVectorIcon( kSystemMenuBusinessIcon, kEntryIconSize, gfx::kChromeIconGrey)); cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::FIXED, kEntryIconSize, 0); layout->AddView(policy_enforced_icon); } Layout(); } // NotifierSettingsView ------------------------------------------------------- NotifierSettingsView::NotifierSettingsView() : title_arrow_(nullptr), quiet_mode_icon_(nullptr), quiet_mode_toggle_(nullptr), header_view_(nullptr), top_label_(nullptr), scroller_(nullptr), no_notifiers_view_(nullptr) { SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); SetBackground( views::CreateSolidBackground(message_center_style::kBackgroundColor)); SetPaintToLayer(); header_view_ = new views::View; header_view_->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kVertical, kHeaderViewPadding, 0)); header_view_->SetBorder( views::CreateSolidSidedBorder(1, 0, 0, 0, kTopBorderColor)); views::View* quiet_mode_view = new views::View; auto* quiet_mode_layout = quiet_mode_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kHorizontal, kQuietModeViewPadding, kQuietModeViewSpacing)); quiet_mode_icon_ = new views::ImageView(); quiet_mode_icon_->SetBorder(views::CreateEmptyBorder(kQuietModeLabelPadding)); quiet_mode_view->AddChildView(quiet_mode_icon_); views::Label* quiet_mode_label = new views::Label(l10n_util::GetStringUTF16( IDS_ASH_MESSAGE_CENTER_QUIET_MODE_BUTTON_TOOLTIP)); quiet_mode_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); // "Roboto-Regular, 13sp" is specified in the mock. quiet_mode_label->SetFontList( gfx::FontList().DeriveWithSizeDelta(kLabelFontSizeDelta)); quiet_mode_label->SetAutoColorReadabilityEnabled(false); quiet_mode_label->SetEnabledColor(kLabelColor); quiet_mode_label->SetBorder(views::CreateEmptyBorder(kQuietModeLabelPadding)); quiet_mode_view->AddChildView(quiet_mode_label); quiet_mode_layout->SetFlexForView(quiet_mode_label, 1); quiet_mode_toggle_ = new views::ToggleButton(this); quiet_mode_toggle_->SetAccessibleName(l10n_util::GetStringUTF16( IDS_ASH_MESSAGE_CENTER_QUIET_MODE_BUTTON_TOOLTIP)); quiet_mode_toggle_->SetBorder( views::CreateEmptyBorder(kQuietModeTogglePadding)); quiet_mode_toggle_->EnableCanvasFlippingForRTLUI(true); SetQuietModeState(MessageCenter::Get()->IsQuietMode()); quiet_mode_view->AddChildView(quiet_mode_toggle_); header_view_->AddChildView(quiet_mode_view); top_label_ = new views::Label(l10n_util::GetStringUTF16( IDS_ASH_MESSAGE_CENTER_SETTINGS_DIALOG_DESCRIPTION)); top_label_->SetBorder(views::CreateEmptyBorder(kTopLabelPadding)); // "Roboto-Medium, 13sp" is specified in the mock. top_label_->SetFontList(gfx::FontList().Derive( kLabelFontSizeDelta, gfx::Font::NORMAL, gfx::Font::Weight::MEDIUM)); top_label_->SetAutoColorReadabilityEnabled(false); top_label_->SetEnabledColor(kTopLabelColor); top_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); top_label_->SetMultiLine(true); header_view_->AddChildView(top_label_); AddChildView(header_view_); scroller_ = new views::ScrollView(); scroller_->SetBackgroundColor(message_center_style::kBackgroundColor); scroller_->SetVerticalScrollBar(new views::OverlayScrollBar(false)); scroller_->SetHorizontalScrollBar(new views::OverlayScrollBar(true)); scroller_->set_draw_overflow_indicator(false); AddChildView(scroller_); no_notifiers_view_ = new EmptyNotifierView(); AddChildView(no_notifiers_view_); SetNotifierList({}); Shell::Get()->message_center_controller()->SetNotifierSettingsListener(this); } NotifierSettingsView::~NotifierSettingsView() { Shell::Get()->message_center_controller()->SetNotifierSettingsListener( nullptr); } bool NotifierSettingsView::IsScrollable() { return scroller_->height() < scroller_->contents()->height(); } void NotifierSettingsView::SetQuietModeState(bool is_quiet_mode) { quiet_mode_toggle_->SetIsOn(is_quiet_mode, false /* animate */); if (is_quiet_mode) { quiet_mode_icon_->SetImage(gfx::CreateVectorIcon( kNotificationCenterDoNotDisturbOnIcon, kMenuIconSize, kMenuIconColor)); } else { quiet_mode_icon_->SetImage( gfx::CreateVectorIcon(kNotificationCenterDoNotDisturbOffIcon, kMenuIconSize, kMenuIconColorDisabled)); } } void NotifierSettingsView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kList; node_data->SetName(l10n_util::GetStringUTF16( IDS_ASH_MESSAGE_CENTER_SETTINGS_DIALOG_DESCRIPTION)); } void NotifierSettingsView::SetNotifierList( const std::vector<mojom::NotifierUiDataPtr>& ui_data) { buttons_.clear(); views::View* contents_view = new ScrollContentsView(); contents_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kVertical, gfx::Insets(0, kHorizontalMargin))); size_t notifier_count = ui_data.size(); for (size_t i = 0; i < notifier_count; ++i) { NotifierButton* button = new NotifierButton(*ui_data[i], this); NotifierButtonWrapperView* wrapper = new NotifierButtonWrapperView(button); wrapper->SetFocusBehavior(FocusBehavior::ALWAYS); contents_view->AddChildView(wrapper); buttons_.insert(button); } top_label_->SetVisible(notifier_count > 0); no_notifiers_view_->SetVisible(notifier_count == 0); scroller_->SetContents(contents_view); contents_view->SetBoundsRect(gfx::Rect(contents_view->GetPreferredSize())); InvalidateLayout(); } void NotifierSettingsView::UpdateNotifierIcon(const NotifierId& notifier_id, const gfx::ImageSkia& icon) { for (auto* button : buttons_) { if (button->notifier_id() == notifier_id) { button->UpdateIconImage(icon); return; } } } void NotifierSettingsView::Layout() { int header_height = header_view_->GetHeightForWidth(width()); header_view_->SetBounds(0, 0, width(), header_height); views::View* contents_view = scroller_->contents(); int content_width = width(); int content_height = contents_view->GetHeightForWidth(content_width); if (header_height + content_height > height()) { content_width -= scroller_->GetScrollBarLayoutWidth(); content_height = contents_view->GetHeightForWidth(content_width); } contents_view->SetBounds(0, 0, content_width, content_height); scroller_->SetBounds(0, header_height, width(), height() - header_height); no_notifiers_view_->SetBounds(0, header_height, width(), height() - header_height); } gfx::Size NotifierSettingsView::GetMinimumSize() const { gfx::Size size(kWidth, kMinimumHeight); int total_height = header_view_->GetPreferredSize().height() + scroller_->contents()->GetPreferredSize().height(); if (total_height > kMinimumHeight) size.Enlarge(scroller_->GetScrollBarLayoutWidth(), 0); return size; } gfx::Size NotifierSettingsView::CalculatePreferredSize() const { gfx::Size header_size = header_view_->GetPreferredSize(); gfx::Size content_size = scroller_->contents()->GetPreferredSize(); int no_notifiers_height = 0; if (no_notifiers_view_->visible()) no_notifiers_height = no_notifiers_view_->GetPreferredSize().height(); return gfx::Size( std::max(header_size.width(), content_size.width()), std::max(kMinimumHeight, header_size.height() + content_size.height() + no_notifiers_height)); } bool NotifierSettingsView::OnKeyPressed(const ui::KeyEvent& event) { if (event.key_code() == ui::VKEY_ESCAPE) { GetWidget()->Close(); return true; } return scroller_->OnKeyPressed(event); } bool NotifierSettingsView::OnMouseWheel(const ui::MouseWheelEvent& event) { return scroller_->OnMouseWheel(event); } void NotifierSettingsView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender == title_arrow_) { MessageCenterView* center_view = static_cast<MessageCenterView*>(parent()); center_view->SetSettingsVisible(!center_view->settings_visible()); return; } if (sender == quiet_mode_toggle_) { MessageCenter::Get()->SetQuietMode(quiet_mode_toggle_->is_on()); return; } auto iter = buttons_.find(static_cast<NotifierButton*>(sender)); if (iter == buttons_.end()) return; NotifierButton* button = *iter; button->SetChecked(!button->checked()); Shell::Get()->message_center_controller()->SetNotifierEnabled( button->notifier_id(), button->checked()); } } // namespace ash
36.296296
80
0.73811
zipated
e88e8c7a26dee04f4f1b5749a556d436496df34e
1,614
cpp
C++
sentutil/chat.cpp
surrealwaffle/thesurrealwaffle
6937d8e2604628a5c9141feef837d89e81f68165
[ "BSL-1.0" ]
3
2018-07-20T23:04:45.000Z
2021-07-09T04:16:42.000Z
sentutil/chat.cpp
surrealwaffle/thesurrealwaffle
6937d8e2604628a5c9141feef837d89e81f68165
[ "BSL-1.0" ]
null
null
null
sentutil/chat.cpp
surrealwaffle/thesurrealwaffle
6937d8e2604628a5c9141feef837d89e81f68165
[ "BSL-1.0" ]
1
2018-07-21T06:32:13.000Z
2018-07-21T06:32:13.000Z
// Copyright surrealwaffle 2018 - 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) #include <sentutil/chat.hpp> #include <cstdarg> // std::va_list #include <cstring> // std::strlen #include <cwchar> // std::vswprintf #include <iterator> // std::size #include <string> // std::wstring namespace { void send_chat_valist(int channel, const char* fmt, std::va_list args); void send_chat_wvalist(int channel, const wchar_t* fmt, std::va_list args); } // namespace (anonymous) namespace sentutil { namespace chat { void send_chat(utility::format_marker_type, int channel, const char* fmt, ...) { std::va_list args; va_start(args, fmt); send_chat_valist(channel, fmt, args); va_end(args); } void send_chat(utility::format_marker_type, const char* fmt, ...) { std::va_list args; va_start(args, fmt); send_chat_valist(0, fmt, args); va_end(args); } } } // namespace sentutil::chat namespace { void send_chat_valist(int channel, const char* fmt, va_list args) { std::wstring wfmt(fmt, fmt + std::strlen(fmt)); return send_chat_wvalist(channel, wfmt.c_str(), args); } void send_chat_wvalist(int channel, const wchar_t* fmt, va_list args) { wchar_t buf[0xFF]; buf[0xFE] = L'\0'; std::vswprintf(buf, std::size(buf) - 1, fmt, args); sentinel_Chat_SendChatToServer(channel, buf); } } // namespace (anonymous)
24.830769
76
0.639405
surrealwaffle
e895368d7b727dd0fcc78181bc264e55667dd1ed
907
cpp
C++
sicxe/sim/device.cpp
blaz-r/SIC-XE-simulator
c148657a120331eea26e137db219c0f60662a1e8
[ "MIT" ]
null
null
null
sicxe/sim/device.cpp
blaz-r/SIC-XE-simulator
c148657a120331eea26e137db219c0f60662a1e8
[ "MIT" ]
null
null
null
sicxe/sim/device.cpp
blaz-r/SIC-XE-simulator
c148657a120331eea26e137db219c0f60662a1e8
[ "MIT" ]
null
null
null
#include "device.h" #include <iostream> uint8_t InputDevice::read() { return inputStream.get(); } void OutputDevice::write(uint8_t value) { outputStream.write(reinterpret_cast<char*>(&value), 1); outputStream.flush(); } FileDevice::FileDevice(std::string file) { fileStream.open(file, std::fstream::in); if(!fileStream) { fileStream.open(file, std::fstream::out); } fileStream.close(); fileStream.open(file, std::fstream::out | std::fstream::in); } FileDevice::~FileDevice() { fileStream.close(); } uint8_t FileDevice::read() { if (fileStream.peek() == EOF) { return 0; } else { return fileStream.get(); } } void FileDevice::write(uint8_t value) { fileStream.write(reinterpret_cast<char*>(&value), 1); fileStream.flush(); } void FileDevice::reset() { fileStream.clear(); fileStream.seekg(0); }
16.490909
64
0.628445
blaz-r
e8999ac0e209fb7bb469a1ebd6d497d3929d8e97
6,515
cc
C++
homeworks/HierarchicalErrorEstimator/mastersolution/hierarchicalerrorestimator.cc
0xBachmann/NPDECODES
70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea
[ "MIT" ]
1
2022-02-22T10:59:19.000Z
2022-02-22T10:59:19.000Z
homeworks/HierarchicalErrorEstimator/mastersolution/hierarchicalerrorestimator.cc
0xBachmann/NPDECODES
70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea
[ "MIT" ]
null
null
null
homeworks/HierarchicalErrorEstimator/mastersolution/hierarchicalerrorestimator.cc
0xBachmann/NPDECODES
70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea
[ "MIT" ]
null
null
null
/** * @ file * @ brief NPDE homework on hierarchical error estimation * @ author Ralf Hiptmair * @ date July 2021 * @ copyright Developed at SAM, ETH Zurich */ #include "hierarchicalerrorestimator.h" namespace HEST { /* SAM_LISTING_BEGIN_3 */ Eigen::VectorXd trfLinToQuad( std::shared_ptr<const lf::uscalfe::FeSpaceLagrangeO1<double>> fes_lin_p, std::shared_ptr<const lf::uscalfe::FeSpaceLagrangeO2<double>> fes_quad_p, const Eigen::VectorXd &mu) { using gdof_idx_t = lf::assemble::gdof_idx_t; // Obtain local-to-global index mappings const lf::assemble::DofHandler &dh_lin{fes_lin_p->LocGlobMap()}; const lf::assemble::DofHandler &dh_quad{fes_quad_p->LocGlobMap()}; LF_ASSERT_MSG(dh_lin.Mesh() == dh_quad.Mesh(), "DofHandlers must be based on the same mesh"); LF_ASSERT_MSG(dh_lin.NumDofs() == mu.size(), "Vector length mismath"); // Underlying mesh std::shared_ptr<const lf::mesh::Mesh> mesh_p{dh_lin.Mesh()}; const lf::mesh::Mesh &mesh{*mesh_p}; LF_ASSERT_MSG( (dh_lin.NumDofs() == mesh.NumEntities(2)) && (dh_quad.NumDofs() == mesh.NumEntities(2) + mesh.NumEntities(1)), "#DOFs do not match #entities"); // The coefficients of a FE function in the quadratic Lagrangian FE space with // respect to the nodal basis are simply its values at the nodes and the // midpoints of the edges. Eigen::VectorXd nu(dh_quad.NumDofs()); // Visit nodes (codimension =2) and copy values for (const lf::mesh::Entity *node : mesh.Entities(2)) { nonstd::span<const gdof_idx_t> lf_dof_idx{dh_lin.GlobalDofIndices(*node)}; LF_ASSERT_MSG(lf_dof_idx.size() == 1, "Exactly one LFE basis functiona at a node"); LF_ASSERT_MSG(lf_dof_idx[0] < dh_lin.NumDofs(), "LFE dof number too large"); nonstd::span<const gdof_idx_t> qf_dof_idx{dh_quad.GlobalDofIndices(*node)}; LF_ASSERT_MSG(lf_dof_idx.size() == 1, "Exactly one QFE basis functiona at a node"); LF_ASSERT_MSG(qf_dof_idx[0] < dh_quad.NumDofs(), "QFE dof number too large"); nu[qf_dof_idx[0]] = mu[lf_dof_idx[0]]; } // Run through all edges for (const lf::mesh::Entity *edge : mesh.Entities(1)) { // Obtain global numbers of LFE DOFs associated with the endpoints of // the edge, that is, of those DOFs covering the edge. nonstd::span<const gdof_idx_t> lf_dof_idx{dh_lin.GlobalDofIndices(*edge)}; LF_ASSERT_MSG(lf_dof_idx.size() == 2, "Exactly two basis functions must cover an edge"); LF_ASSERT_MSG((lf_dof_idx[0] < dh_lin.NumDofs()) && (lf_dof_idx[1] < dh_lin.NumDofs()), "LFE dof numbers too large"); // Obtain global number of QFE basis function associated with the edge nonstd::span<const gdof_idx_t> qf_dof_idx{ dh_quad.InteriorGlobalDofIndices(*edge)}; LF_ASSERT_MSG(qf_dof_idx.size() == 1, "A single QFE basis function is associated to an edge!"); LF_ASSERT_MSG(qf_dof_idx[0] < dh_quad.NumDofs(), "QFE dof number too large"); // Value of p.w. linear continuous FE function at the midpoint of the edge const double mp_val = (mu[lf_dof_idx[0]] + mu[lf_dof_idx[1]]) / 2.0; // Store value as appropriate coefficient nu[qf_dof_idx[0]] = mp_val; } return nu; } /* SAM_LISTING_END_3 */ std::tuple<double, double, double> solveAndEstimate( std::shared_ptr<const lf::mesh::Mesh> mesh_p) { // Note: the mesh must cover the unit square for this test setting ! // Create finite element space for p.w. linear Lagrangian FE std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> lfe_space_p = std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p); std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO2<double>> quad_space_p = std::make_shared<lf::uscalfe::FeSpaceLagrangeO2<double>>(mesh_p); // Define homogeneous Dirichlet boundary value problem // Diffusion coefficient function std::function<double(Eigen::Vector2d)> alpha = [](Eigen::Vector2d x) -> double { return (1.0 /* + x.squaredNorm() */); }; // Manufactured exact solution auto u_exact = [](Eigen::Vector2d x) -> double { return (x[0] * (1.0 - x[0]) * x[1] * (1.0 - x[1])); }; auto grad_u = [](Eigen::Vector2d x) -> Eigen::Vector2d { return ((Eigen::Vector2d() << (1 - 2 * x[0]) * x[1] * (1 - x[1]), x[0] * (1 - x[0]) * (1 - 2 * x[1])) .finished()); }; // Right-hand side matching exact solution auto f = [](Eigen::Vector2d x) -> double { return 2 * (x[1] * (1 - x[1]) + x[0] * (1 - x[0])); }; // Lambdas have to be wrapped into a mesh function for error computation lf::mesh::utils::MeshFunctionGlobal mf_u{u_exact}; lf::mesh::utils::MeshFunctionGlobal mf_grad_u{grad_u}; lf::mesh::utils::MeshFunctionGlobal mf_alpha{alpha}; lf::mesh::utils::MeshFunctionGlobal mf_f{f}; // Compute basis expansion coefficient vector of finite-element solution const Eigen::VectorXd mu{solveBVPWithLinFE(mf_alpha, mf_f, lfe_space_p)}; // Compute error norms // create MeshFunctions representing solution / gradient of LFE solution const lf::fe::MeshFunctionFE mf_sol(lfe_space_p, mu); const lf::fe::MeshFunctionGradFE mf_grad_sol(lfe_space_p, mu); // compute errors with 3rd order quadrature rules, which is sufficient for // piecewise linear finite elements double L2err = // NOLINT std::sqrt(lf::fe::IntegrateMeshFunction( *mesh_p, lf::mesh::utils::squaredNorm(mf_sol - mf_u), 2)); double H1serr = std::sqrt(lf::fe::IntegrateMeshFunction( // NOLINT *mesh_p, lf::mesh::utils::squaredNorm(mf_grad_sol - mf_grad_u), 2)); std::cout << "Mesh (" << mesh_p->NumEntities(0) << " cells, " << mesh_p->NumEntities(1) << " edges, " << mesh_p->NumEntities(2) << " nodes): L2err = " << L2err << ", H1serr = " << H1serr << std::endl; // Evaluate a-posteriori error estimator const Eigen::VectorXd nu = compHierSurplusSolution(mf_alpha, mf_f, lfe_space_p, quad_space_p, mu); // Compute H1-seminorm of solution in hierarchical surplus space const lf::fe::MeshFunctionGradFE mf_grad_hps(quad_space_p, nu); double hier_surplus_norm = std::sqrt(lf::fe::IntegrateMeshFunction( // NOLINT *mesh_p, lf::mesh::utils::squaredNorm(mf_grad_hps), 4)); std::cout << "Estimated error = " << hier_surplus_norm << std::endl; return {L2err, H1serr, hier_surplus_norm}; } // end solveAndEstimate } // namespace HEST
46.205674
80
0.666616
0xBachmann
e89edf4bc15b80365ab3ef7cc4313005917998e8
996
cpp
C++
sdl/Hypergraph/src/UseOpenFst.cpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/Hypergraph/src/UseOpenFst.cpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2015-12-08T15:03:15.000Z
2016-01-26T14:31:06.000Z
sdl/Hypergraph/src/UseOpenFst.cpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
4
2015-11-21T14:25:38.000Z
2017-10-30T22:22:00.000Z
// Copyright 2014-2015 SDL plc // 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 <sdl/Hypergraph/UseOpenFst.hpp> #if HAVE_OPENFST #include <graehl/shared/warning_push.h> GCC6_DIAG_IGNORE(misleading-indentation) GCC_DIAG_IGNORE(uninitialized) GCC_DIAG_IGNORE(unused-local-typedefs) #include <lib/compat.cc> #include <lib/flags.cc> #include <lib/fst.cc> #include <lib/properties.cc> #include <lib/symbol-table.cc> #include <lib/util.cc> #include <graehl/shared/warning_pop.h> #endif
31.125
75
0.767068
sdl-research
e89fe7ec6cc06a497dbc6c11ed45b36c858ee463
598
cpp
C++
src/window_with_linux_gamepad.cpp
hissingshark/game-window
7d270d3ffc711ae4c66a014cd18ad5276cdbc0a4
[ "MIT" ]
4
2019-03-10T02:35:16.000Z
2021-02-20T17:57:17.000Z
src/window_with_linux_gamepad.cpp
hissingshark/game-window
7d270d3ffc711ae4c66a014cd18ad5276cdbc0a4
[ "MIT" ]
2
2020-06-28T09:28:37.000Z
2021-04-17T10:35:49.000Z
src/window_with_linux_gamepad.cpp
hissingshark/game-window
7d270d3ffc711ae4c66a014cd18ad5276cdbc0a4
[ "MIT" ]
7
2019-06-12T00:03:25.000Z
2021-07-29T13:06:32.000Z
#include "window_with_linux_gamepad.h" #include "joystick_manager_linux_gamepad.h" WindowWithLinuxJoystick::WindowWithLinuxJoystick(std::string const& title, int width, int height, GraphicsApi api) : GameWindow(title, width, height, api) { } WindowWithLinuxJoystick::~WindowWithLinuxJoystick() { LinuxGamepadJoystickManager::instance.removeWindow(this); } void WindowWithLinuxJoystick::addWindowToGamepadManager() { LinuxGamepadJoystickManager::instance.addWindow(this); } void WindowWithLinuxJoystick::updateGamepad() { LinuxGamepadJoystickManager::instance.update(this); }
33.222222
116
0.799331
hissingshark
e8a426d4b092a2a3bad7dd0e7f1f17ab34287675
3,363
hpp
C++
uActor/include/remote/remote_connection.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
1
2021-09-15T12:41:37.000Z
2021-09-15T12:41:37.000Z
uActor/include/remote/remote_connection.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
null
null
null
uActor/include/remote/remote_connection.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
null
null
null
#pragma once extern "C" { #include <arpa/inet.h> } #include <atomic> #include <cstdint> #include <cstring> #include <list> #include <map> #include <memory> #include <mutex> #include <queue> #include <set> #include <string> #include <unordered_map> #include <vector> #include "forwarder_api.hpp" #include "forwarding_strategy.hpp" #include "pubsub/publication_factory.hpp" #include "remote/sequence_info.hpp" #include "subscription_processors/subscription_processor.hpp" namespace uActor::Remote { class TCPForwarder; enum struct ConnectionRole : uint8_t { SERVER = 0, CLIENT = 1 }; class RemoteConnection { public: RemoteConnection(const RemoteConnection&) = delete; RemoteConnection& operator=(const RemoteConnection&) = delete; RemoteConnection(RemoteConnection&&) = default; RemoteConnection& operator=(RemoteConnection&&) = default; RemoteConnection(uint32_t local_id, int32_t socket_id, std::string remote_addr, uint16_t remote_port, ConnectionRole connection_role, ForwarderSubscriptionAPI* handle); ~RemoteConnection(); enum ProcessingState { empty, waiting_for_size, waiting_for_data, }; void handle_subscription_update_notification( const PubSub::Publication& update_message); void send_routing_info(); void process_data(uint32_t len, char* data); static std::map<std::string, std::string> local_location_labels; static std::list<std::vector<std::string>> clusters; private: uint32_t local_id; int sock = 0; // TCP Related // TODO(raphaelhetzel) potentially move this to a separate // wrapper once we have more types of forwarders std::string partner_ip; uint16_t partner_port; ConnectionRole connection_role; // Subscription related ForwarderSubscriptionAPI* handle; std::set<uint32_t> subscription_ids; uint32_t update_sub_id = 0; uint32_t local_sub_added_id = 0; uint32_t local_sub_removed_id = 0; uint32_t remote_subs_added_id = 0; uint32_t remote_subs_removed_id = 0; // Peer related std::string partner_node_id; std::map<std::string, std::string> partner_location_labels; uint32_t last_read_contact = 0; uint32_t last_write_contact = 0; std::vector<std::unique_ptr<SubscriptionProcessor>> egress_subscription_processors; // Connection statemachine ProcessingState state{empty}; int len = 0; std::vector<char> rx_buffer = std::vector<char>(512); // The size field may be split into multiple recvs char size_buffer[4]{0, 0, 0, 0}; uint32_t size_field_remaining_bytes{0}; uint32_t publicaton_remaining_bytes{0}; uint32_t publicaton_full_size{0}; PubSub::PublicationFactory publication_buffer = PubSub::PublicationFactory(); std::unique_ptr<ForwardingStrategy> forwarding_strategy; std::queue<std::shared_ptr<std::vector<char>>> write_buffer; size_t write_offset = 0; void process_remote_publication(PubSub::Publication&& p); void handle_local_subscription_removed(const PubSub::Publication& p); void handle_local_subscription_added(const PubSub::Publication& p); void handle_remote_subscriptions_removed(const PubSub::Publication& p); void handle_remote_subscriptions_added(const PubSub::Publication& p); void handle_remote_hello(PubSub::Publication&& p); friend uActor::Remote::TCPForwarder; }; } // namespace uActor::Remote
27.120968
79
0.749926
uActor
e8aab68527a7cd0ffa9fc714daad51ea18c92a75
134
hpp
C++
src/hardware/chips/stm32/stm32f103c4.hpp
xenris/nblib
72bf25b6d086bf6f6f3003d709f92a9975bfddaf
[ "MIT" ]
3
2016-03-31T04:41:32.000Z
2017-07-17T02:50:38.000Z
src/hardware/chips/stm32/stm32f103c4.hpp
xenris/nbavr
72bf25b6d086bf6f6f3003d709f92a9975bfddaf
[ "MIT" ]
18
2015-08-12T12:13:16.000Z
2017-05-10T12:55:55.000Z
src/hardware/chips/stm32/stm32f103c4.hpp
xenris/nblib
72bf25b6d086bf6f6f3003d709f92a9975bfddaf
[ "MIT" ]
null
null
null
#ifndef NBLIB_STM32F103C4_HPP #define NBLIB_STM32F103C4_HPP #include "stm32f103t4.hpp" #undef CHIP #define CHIP stm32f103c4 #endif
13.4
29
0.820896
xenris
e8aae74fc176487bb56981bc58fab4197dd93a2a
8,390
hpp
C++
ufora/core/Logging.hpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
ufora/core/Logging.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
ufora/core/Logging.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2015 Ufora Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ #pragma once #include <ostream> #include <stdio.h> #include <sstream> #include "cppml/CPPMLPrettyPrinter.hppml" enum LogLevel { LOG_LEVEL_DEBUG = 0, LOG_LEVEL_INFO, LOG_LEVEL_WARN, LOG_LEVEL_ERROR, LOG_LEVEL_CRITICAL, LOG_LEVEL_TEST }; #define LOG_LEVEL_SCOPED(scope) \ ([]() { \ static LogLevel** shouldLog = \ Ufora::Logging::getScopedLoggingLevelHandle(scope, __FILE__); \ return **shouldLog; \ }()) #define SHOULD_LOG_DEBUG_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_DEBUG) #define SHOULD_LOG_INFO_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_INFO) #define SHOULD_LOG_WARN_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_WARN) #define SHOULD_LOG_ERROR_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_ERROR) #define SHOULD_LOG_CRITICAL_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_CRITICAL) #define SHOULD_LOG_TEST_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_TEST) #define SHOULD_LOG_DEBUG() SHOULD_LOG_DEBUG_SCOPED("") #define SHOULD_LOG_INFO() SHOULD_LOG_INFO_SCOPED("") #define SHOULD_LOG_WARN() SHOULD_LOG_WARN_SCOPED("") #define SHOULD_LOG_ERROR() SHOULD_LOG_ERROR_SCOPED("") #define SHOULD_LOG_CRITICAL() SHOULD_LOG_CRITICAL_SCOPED("") #define SHOULD_LOG_TEST() SHOULD_LOG_TEST_SCOPED("") #define LOG_DEBUG if(!SHOULD_LOG_DEBUG()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_DEBUG, __FILE__, __LINE__)) #define LOG_INFO if(!SHOULD_LOG_INFO()) ; else ::Ufora::Logging::Logger(LOG_LEVEL_INFO, __FILE__, __LINE__) #define LOG_WARN if(!SHOULD_LOG_WARN()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_WARN, __FILE__, __LINE__)) #define LOG_ERROR if(!SHOULD_LOG_ERROR()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_ERROR, __FILE__, __LINE__)) #define LOG_CRITICAL if(!SHOULD_LOG_CRITICAL()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_CRITICAL, __FILE__, __LINE__)) #define LOG_TEST if(!SHOULD_LOG_TEST()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_TEST, __FILE__, __LINE__)) #define LOG_DEBUG_SCOPED(scope) if(!SHOULD_LOG_DEBUG_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_DEBUG, __FILE__, __LINE__)) #define LOG_INFO_SCOPED(scope) if(!SHOULD_LOG_INFO_SCOPED(scope)) ; else ::Ufora::Logging::Logger(LOG_LEVEL_INFO, __FILE__, __LINE__) #define LOG_WARN_SCOPED(scope) if(!SHOULD_LOG_WARN_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_WARN, __FILE__, __LINE__)) #define LOG_ERROR_SCOPED(scope) if(!SHOULD_LOG_ERROR_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_ERROR, __FILE__, __LINE__)) #define LOG_CRITICAL_SCOPED(scope) if(!SHOULD_LOG_CRITICAL_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_CRITICAL, __FILE__, __LINE__)) #define LOG_TEST_SCOPED(scope) if(!SHOULD_LOG_TEST_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_TEST, __FILE__, __LINE__)) #define LOGGER_DEBUG ::Ufora::Logging::Logger(LOG_LEVEL_DEBUG, __FILE__, __LINE__, SHOULD_LOG_DEBUG()) #define LOGGER_INFO ::Ufora::Logging::Logger(LOG_LEVEL_INFO, __FILE__, __LINE__, SHOULD_LOG_INFO()) #define LOGGER_WARN ::Ufora::Logging::Logger(LOG_LEVEL_WARN, __FILE__, __LINE__, SHOULD_LOG_WARN()) #define LOGGER_ERROR ::Ufora::Logging::Logger(LOG_LEVEL_ERROR, __FILE__, __LINE__, SHOULD_LOG_ERROR()) #define LOGGER_CRITICAL ::Ufora::Logging::Logger(LOG_LEVEL_CRITICAL, __FILE__, __LINE__, SHOULD_LOG_CRITICAL()) #define LOGGER_TEST ::Ufora::Logging::Logger(LOG_LEVEL_TEST, __FILE__, __LINE__, SHOULD_LOG_TEST()) #define LOGGER_DEBUG_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_DEBUG, __FILE__, __LINE__, SHOULD_LOG_DEBUG_SCOPED(scope)) #define LOGGER_INFO_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_INFO, __FILE__, __LINE__, SHOULD_LOG_INFO_SCOPED(scope)) #define LOGGER_WARN_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_WARN, __FILE__, __LINE__, SHOULD_LOG_WARN_SCOPED(scope)) #define LOGGER_ERROR_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_ERROR, __FILE__, __LINE__, SHOULD_LOG_ERROR_SCOPED(scope)) #define LOGGER_CRITICAL_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_CRITICAL, __FILE__, __LINE__, SHOULD_LOG_CRITICAL_SCOPED(scope)) #define LOGGER_TEST_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_TEST, __FILE__, __LINE__, SHOULD_LOG_TEST_SCOPED(scope)) #define LOGGER_DEBUG_T ::Ufora::Logging::Logger #define LOGGER_INFO_T ::Ufora::Logging::Logger #define LOGGER_WARN_T ::Ufora::Logging::Logger #define LOGGER_ERROR_T ::Ufora::Logging::Logger #define LOGGER_CRITICAL_T ::Ufora::Logging::Logger #define LOGGER_TEST_T ::Ufora::Logging::Logger namespace Ufora { namespace Logging { using LogWriter = std::function<void(LogLevel level, const char* filename, int lineNumber, const std::string& message)>; void setLogLevel(LogLevel logLevel); class Logger { public: static void setLogWriter(LogWriter writer); static void logToStream(std::ostream& stream, LogLevel level, const char* filename, int lineNumber, const std::string& message); Logger(LogLevel logLevel, const char * file, int line, bool shouldLog = true); Logger(const Logger& other); ~Logger(); Logger& operator<<(const bool& in) { mStringstream << in; return *this; } Logger& operator<<(const int8_t& in) { mStringstream << in; return *this; } Logger& operator<<(const int16_t& in) { mStringstream << in; return *this; } Logger& operator<<(const int32_t& in) { mStringstream << in; return *this; } Logger& operator<<(const int64_t& in) { mStringstream << in; return *this; } Logger& operator<<(const uint8_t& in) { mStringstream << in; return *this; } Logger& operator<<(const uint16_t& in) { mStringstream << in; return *this; } Logger& operator<<(const uint32_t& in) { mStringstream << in; return *this; } Logger& operator<<(const uint64_t& in) { mStringstream << in; return *this; } Logger& operator<<(const double& in) { mStringstream << in; return *this; } Logger& operator<<(const float& in) { mStringstream << in; return *this; } Logger& operator<<(const std::string& in) { mStringstream << in; return *this; } Logger& operator<<(const char* in) { mStringstream << in; return *this; } Logger& operator<<( std::ostream&(*streamer)(std::ostream& ) ); Logger& operator<<( std::ios_base&(*streamer)(std::ios_base& ) ); Logger& operator<<(const decltype(std::setw(0))& t) { mStringstream << t; return *this; } Logger& operator<<(const decltype(std::setprecision(0))& t) { mStringstream << t; return *this; } template<class T> Logger& operator<<(const T& t) { mStringstream << prettyPrintString(t); return *this; } static std::string logLevelToString(LogLevel level); private: static LogWriter logWriter; const char* mFileName; int mLineNumber; LogLevel mLogLevel; std::ostringstream mStringstream; bool mShouldLog; }; LogLevel** getScopedLoggingLevelHandle(const char* scope, const char* file); void setScopedLoggingLevel(std::string scopeRegex, std::string fileRegex, LogLevel logLevel); void resetScopedLoggingLevelToDefault(std::string scopeRegex, std::string fileRegex); } }
34.958333
147
0.682598
ufora
e8adbb3f0a9d4440e2df99ab9fc61d91f8c494a8
498
cpp
C++
Online Judges/URI/1789/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/1789/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/1789/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> using namespace std; int main() { int quant, lesmas, maior; while(cin >> quant) { maior = 0; for ( int i = 0; i < quant; i++) { cin >> lesmas; if(lesmas > maior) maior = lesmas; } if(maior > 0 && maior < 10) cout << 1 << endl; else if (maior >= 10 && maior < 20) cout << 2 << endl; else if(maior >= 20) cout << 3 << endl; } return 0; }
20.75
43
0.415663
AnneLivia
e8b2900874ba5e1051d5ec24b7bce0678f782276
2,633
cc
C++
src/base/threading/scoped_blocking_call.cc
goochen/naiveproxy
1d0682ee5bae6e648cd43c65f49b4eefd224f206
[ "BSD-3-Clause" ]
1
2020-06-02T02:28:34.000Z
2020-06-02T02:28:34.000Z
src/base/threading/scoped_blocking_call.cc
goochen/naiveproxy
1d0682ee5bae6e648cd43c65f49b4eefd224f206
[ "BSD-3-Clause" ]
null
null
null
src/base/threading/scoped_blocking_call.cc
goochen/naiveproxy
1d0682ee5bae6e648cd43c65f49b4eefd224f206
[ "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/threading/scoped_blocking_call.h" #include "base/lazy_instance.h" #include "base/threading/thread_local.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "base/trace_event/base_tracing.h" #include "build/build_config.h" namespace base { namespace { #if DCHECK_IS_ON() // Used to verify that the trace events used in the constructor do not result in // instantiating a ScopedBlockingCall themselves (which would cause an infinite // reentrancy loop). LazyInstance<ThreadLocalBoolean>::Leaky tls_construction_in_progress = LAZY_INSTANCE_INITIALIZER; #endif } // namespace ScopedBlockingCall::ScopedBlockingCall(const Location& from_here, BlockingType blocking_type) : UncheckedScopedBlockingCall( from_here, blocking_type, UncheckedScopedBlockingCall::BlockingCallType::kRegular) { #if DCHECK_IS_ON() DCHECK(!tls_construction_in_progress.Get().Get()); tls_construction_in_progress.Get().Set(true); #endif internal::AssertBlockingAllowed(); TRACE_EVENT_BEGIN2("base", "ScopedBlockingCall", "file_name", from_here.file_name(), "function_name", from_here.function_name()); #if DCHECK_IS_ON() tls_construction_in_progress.Get().Set(false); #endif } ScopedBlockingCall::~ScopedBlockingCall() { TRACE_EVENT_END0("base", "ScopedBlockingCall"); } namespace internal { ScopedBlockingCallWithBaseSyncPrimitives:: ScopedBlockingCallWithBaseSyncPrimitives(const Location& from_here, BlockingType blocking_type) : UncheckedScopedBlockingCall( from_here, blocking_type, UncheckedScopedBlockingCall::BlockingCallType::kBaseSyncPrimitives) { #if DCHECK_IS_ON() DCHECK(!tls_construction_in_progress.Get().Get()); tls_construction_in_progress.Get().Set(true); #endif internal::AssertBaseSyncPrimitivesAllowed(); TRACE_EVENT_BEGIN2("base", "ScopedBlockingCallWithBaseSyncPrimitives", "file_name", from_here.file_name(), "function_name", from_here.function_name()); #if DCHECK_IS_ON() tls_construction_in_progress.Get().Set(false); #endif } ScopedBlockingCallWithBaseSyncPrimitives:: ~ScopedBlockingCallWithBaseSyncPrimitives() { TRACE_EVENT_END0("base", "ScopedBlockingCallWithBaseSyncPrimitives"); } } // namespace internal } // namespace base
31.345238
80
0.726168
goochen
e8b958959daf1290263a0cee7a98315e0e567f90
5,497
cpp
C++
Final Project 2/Final Project 2/DoubleList_Shounak.cpp
ShounakNR/Programming-for-Finance-16-332-503
56048c67179d98ab519fcb4e9df4d8dfc323266a
[ "Apache-2.0" ]
null
null
null
Final Project 2/Final Project 2/DoubleList_Shounak.cpp
ShounakNR/Programming-for-Finance-16-332-503
56048c67179d98ab519fcb4e9df4d8dfc323266a
[ "Apache-2.0" ]
null
null
null
Final Project 2/Final Project 2/DoubleList_Shounak.cpp
ShounakNR/Programming-for-Finance-16-332-503
56048c67179d98ab519fcb4e9df4d8dfc323266a
[ "Apache-2.0" ]
null
null
null
// // DoubleList.cpp // Final Project // // Created by Shounak Rangwala on 11/24/19. // Copyright © 2019 Shounak Rangwala. All rights reserved. // #include <iostream> #include <string> #include "DoubleList.h" #include <fstream> #include <iomanip> DoubleList::DoubleList(){ listsize = 0; head= NULL; tail=NULL; } int DoubleList::size(){ return listsize; } void DoubleList::addToEnd(StockNode * N1){ if(listsize==0){ head = tail = N1; N1->setPrevPtr(NULL); } else{ StockNode* temp = tail; tail->setNextPtr(N1); tail = N1; tail->setPrevPtr(temp); tail->setNextPtr(NULL); } listsize++; } void DoubleList::printList(){ if(listsize==0){ cout<<"Bazinga! List is empty"<<endl; } else{ StockNode* current = head; do { cout<<current->getStockName()<<"\t"<<current->getQuantity()<<"\t"<<current->getTot()<<endl; current = current->getNextPtr(); }while (current!=NULL); } } void DoubleList::removeNode(StockNode* current){ if(listsize==0){ cout<<"get real nub"<<endl; } else{ if(current==head){ removeFromStart(current); } else if(current!=NULL && current!= tail){ (current->getPrevPtr())->setNextPtr(current->getNextPtr()) ; (current->getNextPtr())->setPrevPtr(current->getPrevPtr()); listsize--; delete current; } else if(current==tail){ removeFromEnd(current); } else if(current==NULL){ cout<<"Not found"<<endl; return; } } } void DoubleList::removeFromEnd(StockNode* current){ if(listsize==0){ return; } if(head==tail){ head = tail = 0; listsize--; } else{ tail = current->getPrevPtr(); tail->setNextPtr(NULL); listsize--; } } void DoubleList::removeFromStart(StockNode* current){ if(listsize==0){ return; } if(head==tail){ head = tail = 0; listsize--; } else{ head = current->getNextPtr(); head->setPrevPtr(NULL); listsize--; } } float DoubleList::calcTotal(){ float res=0; if (listsize==0) return 0; StockNode* current =head; do{ res += current->getTot(); current = current->getNextPtr(); }while(current!=NULL); return res; } StockNode* DoubleList ::getHead(){ return head; } StockNode* DoubleList:: getTail(){ return tail; } void DoubleList::copyToPortfolio(){ ofstream file; file.open("stockPortfolio.txt"); file << std::left << setw(20) << "Company Symbol" << std::left << setw(10) << "Number" << std::left << setw(20) << "Price-per-share" << std::left << setw(10) << "Total value" << "\n"; StockNode *ptr = head; while (ptr != NULL) { file << std::left << setw(20) << ptr->getStockName() << std::left << setw(10) << ptr->getQuantity() << std::left << setw(20) << ptr->getValue() << std::left << setw(20) << ptr->getTot() << "\n"; ptr = ptr->getNextPtr(); } file.close(); } void DoubleList::bubblesortList(){ StockNode *ptr = head; StockNode *iter = head; for (int i = 0; i < listsize ; i++) { for (int j = 0; j < listsize-i-1; j++) { if (ptr->getTot() < ptr->getNextPtr()->getTot()) { swap(ptr->getNextPtr(), ptr); // string temp_comSymbol = ptr->getStockName(); // double temp_price = ptr->getValue(); // int temp_shares = ptr->getQuantity(); // float totalNodeValue = ptr->getTot(); // // ptr->setStockName(ptr->getNextPtr()->getStockName()); // ptr->setValue(ptr->getNextPtr()->getValue()); // // ptr->NumberOfStocks = ptr->getNextPtr()->getQuantity(); // ptr->setTotal(ptr->getNextPtr()->getTot()); // // ptr->getNextPtr()->setStockName(temp_comSymbol); // ptr->getNextPtr()->setValue(temp_price); // ptr->getNextPtr()->NumberOfStocks=temp_shares; // ptr->getNextPtr()->setTotal(totalNodeValue); } ptr = ptr->getNextPtr(); } ptr = iter; } } void DoubleList:: swap (StockNode* a, StockNode* b){ StockNode* temp = new StockNode(); // int z = temp->getQuantity(); temp->setQuantity(b->getQuantity()); temp->setValue(b->getValue()); temp->setStockName(b->getStockName()); temp->setTotal(b->getTot()); b->setQuantity(a->getQuantity()-b->getQuantity()); b->setValue(a->getValue()); b->setStockName(a->getStockName()); b->setTotal(a->getTot()); a->setQuantity(temp->getQuantity()-a->getQuantity()); a->setValue(temp->getValue()); a->setStockName(temp->getStockName()); a->setTotal(temp->getTot()); } void DoubleList::selectionsortList(){ StockNode* temp = head; // Traverse the List while (temp) { StockNode* max = temp; StockNode* r = temp->next; // Traverse the unsorted sublist while (r) { if (max->getTot() < r->getTot()) max= r; r = r->next; } // Swap Data swap (max,temp); temp = temp->next; } }
25.100457
203
0.524468
ShounakNR
e8ba1a2fb6a73ff12564cd09de787c50e025df4f
3,625
cpp
C++
test/sandbox/test_digraph.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
test/sandbox/test_digraph.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
test/sandbox/test_digraph.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <algorithm> #include <memory> #include <vector> template<typename T_> using Vector = std::vector<T_>; template<typename T1_, typename T2_> using Pair = std::pair<T1_, T2_>; template<typename T_> using Pointer = std::shared_ptr<T_>; template<typename T_> class Layer { public: typedef T_ Value; Layer(const T_ & value): value_(value) {} const T_ & output(void) const { return this->value_; } void set_input(const T_ & value) { this->input_values_.push_back(value); } void propagate(void) { for(auto v: this->input_values_) { std::cout << this->value_ << " <- " << v << std::endl; } this->input_values_.clear(); } private: Vector<Value> input_values_; Value value_; }; template<typename T_> struct Vertex_ { typedef T_ Item; typedef Vertex_<Item> Vertex; Vertex_(Item key, Item value): key_(key), depends_(1, value){} Item key_; Vector<Item> depends_; }; template<typename T_> class Graph { public: typedef T_ Item; typedef Pair<Item, Item> Arc; typedef Vertex_<Item> Vertex; Graph(Vector<Arc> & arcs) : arcs_(arcs) { this->build_dependencies(); } Vector<Vertex> & vertices() { return this->vertices_; } static Vector<Arc> reversed_arcs(Vector<Arc> & arcs) { Vector<Arc> arcs_rev(arcs.rbegin(), arcs.rend()); for(auto & arc: arcs_rev) { std::swap(arc.first, arc.second); } return arcs_rev; } private: void build_dependencies() { if (this->arcs_.empty()) { return; } for(auto arc: this->arcs_) { auto key = arc.second; auto it = std::find_if(this->vertices_.begin(), this->vertices_.end(), [key](const Vertex & v) { return v.key_ == key; }); if (this->vertices_.end() == it) { auto value = arc.first; this->vertices_.push_back(Vertex(key, value)); } else { auto value = arc.first; it->depends_.push_back(value); } } } Vector<Arc> arcs_; Vector<Vertex> vertices_; }; TEST(SANDBOX, DIGRAPH) { /* * [0] -- [1] --+-- [2] -- [4] --+-- [5] * | | * +-- [3] ---------+ * */ Layer<char> layers[] = {'0', '1', '2', '3', '4', '5'}; Graph<Layer<char>*>::Arc arc_array[] = { std::make_pair(layers + 0, layers + 1), std::make_pair(layers + 1, layers + 2), std::make_pair(layers + 1, layers + 3), std::make_pair(layers + 2, layers + 4), std::make_pair(layers + 3, layers + 5), std::make_pair(layers + 4, layers + 5), }; Vector<typename Graph<Layer<char>*>::Arc> arcs; arcs.push_back(arc_array[0]); arcs.push_back(arc_array[1]); arcs.push_back(arc_array[2]); arcs.push_back(arc_array[3]); arcs.push_back(arc_array[4]); arcs.push_back(arc_array[5]); Graph<Layer<char>*> digraph(arcs); for(auto vertex: digraph.vertices()) { for(auto depend: vertex.depends_) { vertex.key_->set_input(depend->output()); } vertex.key_->propagate(); } arcs = Graph<Layer<char>*>::reversed_arcs(arcs); Graph<Layer<char>*> digraph_rev(arcs); for(auto vertex: digraph_rev.vertices()) { for(auto depend: vertex.depends_) { vertex.key_->set_input(depend->output()); } vertex.key_->propagate(); } }
26.459854
86
0.543448
wataro
e8c1780e18d20c5b439240af585541cf69438cb1
6,089
cpp
C++
STEPVis.cpp
steptools/STEPGraph
e35712e9572e836ca8a7c4db40e54c97c9f08079
[ "Apache-2.0" ]
10
2015-07-23T14:51:11.000Z
2021-06-11T17:37:27.000Z
STEPVis.cpp
steptools/STEPGraph
e35712e9572e836ca8a7c4db40e54c97c9f08079
[ "Apache-2.0" ]
null
null
null
STEPVis.cpp
steptools/STEPGraph
e35712e9572e836ca8a7c4db40e54c97c9f08079
[ "Apache-2.0" ]
4
2015-09-08T01:55:18.000Z
2017-12-24T15:14:36.000Z
#include <rose.h> #include <stp_schema.h> using namespace System; void markme(RoseObject * obj); void graphaddnode(Microsoft::Msagl::Drawing::Graph^ graph, String^ out, String^ in, String^ name=""); void graphatts(RoseObject* obj, Microsoft::Msagl::Drawing::Graph^ graph); void parsetonode(RoseObject*parent, RoseObject*child, String^ attstr, Microsoft::Msagl::Drawing::Graph^ graph); void graphdepth(RoseObject* obj, Microsoft::Msagl::Drawing::Graph^ graph, int depth = 0); int maxdepth = 0; int main(int argc, char ** argv) { if (argc < 3) { Console::WriteLine("Usage: STEPVis.exe [step file to map] [depth]"); return -1; } int depth; try { String ^ depthstr = gcnew String(argv[2]); depth = Convert::ToInt32(depthstr); } catch (Exception^) { Console::WriteLine("invalid depth parameter."); return -1; } maxdepth = depth; ROSE.quiet(ROSE_TRUE); FILE * f = fopen("rlog.txt","w"); if (nullptr == f) return -1; ROSE.error_reporter()->error_file(f); stplib_init(); System::Windows::Forms::Form^ form = gcnew System::Windows::Forms::Form(); Microsoft::Msagl::GraphViewerGdi::GViewer^ viewer = gcnew Microsoft::Msagl::GraphViewerGdi::GViewer(); Microsoft::Msagl::Drawing::Graph^ graph = gcnew Microsoft::Msagl::Drawing::Graph("graph"); RoseDesign * d = ROSE.findDesign(argv[1]); if (!d) { printf("Usage: %s [step file to map]", argv[0]); return -1; } RoseCursor curs; curs.traverse(d); RoseObject * obj; curs.domain(ROSE_DOMAIN(stp_draughting_model)); while(obj = curs.next()) { graphdepth(obj, graph); } viewer->Graph = graph; //associate the viewer with the form form->SuspendLayout(); viewer->Dock = System::Windows::Forms::DockStyle::Fill; form->Controls->Add(viewer); form->ResumeLayout(); //show the form form->ShowDialog(); return 0; } void graphdepth(RoseObject* obj, Microsoft::Msagl::Drawing::Graph^ graph, int depth) { if (obj==nullptr) return; if (maxdepth >=0 && depth > maxdepth) return; if (obj->isa(ROSE_DOMAIN(RoseUnion))) { obj = rose_get_nested_object(ROSE_CAST(RoseUnion, obj)); if (nullptr == obj) return; //Select with a non-object type } if (obj->isa(ROSE_DOMAIN(RoseAggregate))) { if (nullptr == obj->getObject((unsigned)0)) { graphatts(obj, graph);//not an aggregate of objects. return; } for (unsigned j = 0, jsz = obj->size(); j < jsz; j++) { graphdepth(obj->getObject(j), graph, depth + 1); } } if (obj->isa(ROSE_DOMAIN(RoseStructure))) { graphatts(obj, graph); for (unsigned i = 0, sz = obj->attributes()->size(); i < sz; i++) { graphdepth(obj->getObject(obj->attributes()->get(i)), graph, depth + 1); } } } void graphatts(RoseObject* obj,Microsoft::Msagl::Drawing::Graph^ graph) { printf("Getting atts of Obj %s\n", obj->domain()->name()); auto eid = obj->entity_id(); for (auto i = 0u, sz = obj->attributes()->size(); i < sz; i++) { auto sobj = obj->getObject(obj->attributes()->get(i)); if (nullptr == sobj) { printf("\t att %d: %s\n", i, obj->attributes()->get(i)->name()); graphaddnode(graph, gcnew String(obj->domain()->name()), gcnew String(obj->attributes()->get(i)->name()), gcnew String(obj->attributes()->get(i)->name())); continue; } printf("\t att %d: %s\n", i, sobj->domain()->name()); parsetonode(obj, sobj, gcnew String(obj->attributes()->get(i)->name()), graph); } } void parsetonode(RoseObject*parent, RoseObject*child,String ^ attstr, Microsoft::Msagl::Drawing::Graph^ graph) { if (!child || !parent) return; if (child->isa(ROSE_DOMAIN(RoseUnion))) { RoseObject * unnestchild = rose_get_nested_object(ROSE_CAST(RoseUnion, child)); graphaddnode(graph, gcnew String(parent->domain()->name()), gcnew String(child->domain()->name()), attstr); if (nullptr == unnestchild) return; else { parsetonode(child, unnestchild, gcnew String(""), graph); return; } } if (child->isa(ROSE_DOMAIN(RoseAggregate))) { graphaddnode(graph, gcnew String(parent->domain()->name()), gcnew String(child->domain()->name()), attstr); for (unsigned i = 0, sz = child->size(); i < sz; i++) { if (nullptr == child->getObject(i)) return; parsetonode(child,child->getObject(i),gcnew String(child->getAttribute()->name()),graph); } } if (child->isa(ROSE_DOMAIN(RoseStructure))) graphaddnode(graph, gcnew String(parent->domain()->name()), gcnew String(child->domain()->name()), attstr); } void graphaddnode(Microsoft::Msagl::Drawing::Graph^ graph, String^ out, String^ in,String^ name) { if (in == "name") in = out + "_name"; if (in == "description") in = out + "_description"; Microsoft::Msagl::Drawing::Node^ nout = graph->FindNode(out); Microsoft::Msagl::Drawing::Node^ nin = graph->FindNode(in); if (!nout) { nout = graph->AddNode(out); } if (!nin) { nin = graph->AddNode(in); } for each (auto edge in nout->Edges) { if (edge->TargetNode == nin && edge->SourceNode == nout) return; } Microsoft::Msagl::Drawing::Edge ^ edge = gcnew Microsoft::Msagl::Drawing::Edge(nout,nin,Microsoft::Msagl::Drawing::ConnectionToGraph::Connected); edge->LabelText = name; if (in == out + "_name") nin->LabelText = "name"; if (in == out + "_description") nin->LabelText = "description"; return; } void markme(RoseObject*obj) { if (nullptr == obj) return; if (rose_is_marked(obj)) return; //MARK HERE rose_mark_set(obj); auto foo = obj->attributes(); if (obj->isa(ROSE_DOMAIN(RoseStructure))) { for (auto i = 0u; i < foo->size(); i++) { markme(obj->getObject(foo->get(i))); } } if (obj->isa(ROSE_DOMAIN(RoseUnion))) { markme(rose_get_nested_object(ROSE_CAST(RoseUnion,obj))); } if (obj->isa(ROSE_DOMAIN(RoseAggregate))) { RoseAttribute *att = obj->getAttribute(); if (!att->isObject()) return; for (auto i = 0u, sz = obj->size(); i < sz;i++) { markme(obj->getObject(i)); } } }
31.066327
160
0.629824
steptools
e8c22bf8af4daf96ece0f21a30578992f4291cf8
253
cpp
C++
Wind_Vegetation_GOW4/Source/Wind_Vegetation_GOW4/Wind_Vegetation_GOW4.cpp
SungJJinKang/UE4_Interactive_Wind_and_Vegetation_in_God_of_War
cecf72dd6f0982d03b1b01c2fff15cdd07028f11
[ "MIT" ]
15
2022-02-16T00:20:21.000Z
2022-03-21T14:40:37.000Z
Wind_Vegetation_GOW4/Source/Wind_Vegetation_GOW4/Wind_Vegetation_GOW4.cpp
SungJJinKang/UE4_Interactive_Wind_and_Vegetation_in_God_of_War
cecf72dd6f0982d03b1b01c2fff15cdd07028f11
[ "MIT" ]
1
2022-03-06T20:41:06.000Z
2022-03-08T18:21:41.000Z
Wind_Vegetation_GOW4/Source/Wind_Vegetation_GOW4/Wind_Vegetation_GOW4.cpp
SungJJinKang/UE4_Interactive_Wind_and_Vegetation_in_God_of_War
cecf72dd6f0982d03b1b01c2fff15cdd07028f11
[ "MIT" ]
1
2022-03-25T02:09:14.000Z
2022-03-25T02:09:14.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "Wind_Vegetation_GOW4.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Wind_Vegetation_GOW4, "Wind_Vegetation_GOW4" );
36.142857
102
0.83004
SungJJinKang
e8c23c1a1ef9d468819e1ac045e7f0b522b2d841
28,136
hpp
C++
lib/dmitigr/pgfe/array_conversions.hpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
121
2018-05-23T19:51:00.000Z
2022-03-12T13:05:34.000Z
lib/dmitigr/pgfe/array_conversions.hpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
36
2019-11-11T03:25:10.000Z
2022-03-28T21:54:07.000Z
lib/dmitigr/pgfe/array_conversions.hpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
17
2018-05-24T04:01:28.000Z
2022-01-16T13:22:26.000Z
// -*- C++ -*- // Copyright (C) Dmitry Igrishin // For conditions of distribution and use, see files LICENSE.txt or pgfe.hpp #ifndef DMITIGR_PGFE_ARRAY_CONVERSIONS_HPP #define DMITIGR_PGFE_ARRAY_CONVERSIONS_HPP #include "dmitigr/pgfe/basic_conversions.hpp" #include "dmitigr/pgfe/conversions_api.hpp" #include "dmitigr/pgfe/data.hpp" #include "dmitigr/pgfe/exceptions.hpp" #include <dmitigr/misc/str.hpp> #include <algorithm> #include <cassert> #include <locale> #include <memory> #include <optional> #include <string> #include <utility> namespace dmitigr::pgfe { namespace detail { /// @returns The PostgreSQL array literal representation of the `container`. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator, typename ... Types> std::string to_array_literal(const Container<Optional<T>, Allocator<Optional<T>>>& container, char delimiter = ',', Types&& ... args); /// @returns The container representation of the PostgreSQL array `literal`. template<class Container, typename ... Types> Container to_container(const char* literal, char delimiter = ',', Types&& ... args); // ============================================================================= /** * The compile-time converter from a "container of values" type * to a "container of optionals" type. */ template<typename T> struct Cont_of_opts final { using Type = T; }; /** * @brief Forces treating `std::string` as a non-container type. * * Without this specialization, `std::string` treated as * `std::basic_string<Optional<char>, ...>`. * * @remarks This is a workaround for GCC since the partial specialization by * `std::basic_string<CharT, Traits, Allocator>` (see below) does not works. */ template<> struct Cont_of_opts<std::string> final { using Type = std::string; }; /** * @brief Forces treating `std::basic_string<>` as a non-container type. * * Without this specialization, `std::basic_string<CharT, ...>` treated as * `std::basic_string<Optional<CharT>, ...>`. * * @remarks This specialization doesn't works with GCC (tested with version 8), * and doesn't needs to MSVC. It's exists just in case, probably, for other * compilers. */ template<class CharT, class Traits, class Allocator> struct Cont_of_opts<std::basic_string<CharT, Traits, Allocator>> final { using Type = std::basic_string<CharT, Traits, Allocator>; }; /// The partial specialization of Cont_of_opts. template<typename T, template<class, class> class Container, template<class> class Allocator> struct Cont_of_opts<Container<T, Allocator<T>>> final { private: using Elem = typename Cont_of_opts<T>::Type; public: using Type = Container<std::optional<Elem>, Allocator<std::optional<Elem>>>; }; /// The convenient alias of Cont_of_opts. template<typename T> using Cont_of_opts_t = typename Cont_of_opts<T>::Type; // ===================================== /** * The compile-time converter from a "container of optionals" * to a "container of values". */ template<typename T> struct Cont_of_vals final { using Type = T; }; /// The partial specialization of Cont_of_vals. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> struct Cont_of_vals<Container<Optional<T>, Allocator<Optional<T>>>> final { private: using Elem = typename Cont_of_vals<T>::Type; public: using Type = Container<Elem, Allocator<Elem>>; }; /// The convenient alias of the structure template Cont_of_vals. template<typename T> using Cont_of_vals_t = typename Cont_of_vals<T>::Type; // ===================================== /** * @returns The container of values converted from the container of optionals. * * @throws An instance of type Improper_value_type_of_container if there are * element `e` presents in `container` for which `(bool(e) == false)`. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> Cont_of_vals_t<Container<Optional<T>, Allocator<Optional<T>>>> to_container_of_values(Container<Optional<T>, Allocator<Optional<T>>>&& container); /// @returns The container of optionals converted from the container of values. template<template<class> class Optional, typename T, template<class, class> class Container, template<class> class Allocator> Cont_of_opts_t<Container<T, Allocator<T>>> to_container_of_optionals(Container<T, Allocator<T>>&& container); // ============================================================================= /// Nullable array to/from `std::string` conversions. template<typename> struct Array_string_conversions_opts; /// Nullable array to/from Data conversions. template<typename> struct Array_data_conversions_opts; /// The partial specialization of Array_string_conversions_opts. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> struct Array_string_conversions_opts<Container<Optional<T>, Allocator<Optional<T>>>> final { using Type = Container<Optional<T>, Allocator<Optional<T>>>; template<typename ... Types> static Type to_type(const std::string& literal, Types&& ... args) { return to_container<Type>(literal.c_str(), ',', std::forward<Types>(args)...); } template<typename ... Types> static std::string to_string(const Type& value, Types&& ... args) { return to_array_literal(value, ',', std::forward<Types>(args)...); } }; /// The partial specialization of Array_data_conversions_opts. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> struct Array_data_conversions_opts<Container<Optional<T>, Allocator<Optional<T>>>> final { using Type = Container<Optional<T>, Allocator<Optional<T>>>; template<typename ... Types> static Type to_type(const Data* const data, Types&& ... args) { assert(data && data->format() == Data_format::text); return to_container<Type>(static_cast<const char*>(data->bytes()), ',', std::forward<Types>(args)...); } template<typename ... Types> static Type to_type(std::unique_ptr<Data>&& data, Types&& ... args) { return to_type(data.get(), std::forward<Types>(args)...); } template<typename ... Types> static std::unique_ptr<Data> to_data(const Type& value, Types&& ... args) { using StringConversions = Array_string_conversions_opts<Type>; return Data::make(StringConversions::to_string(value, std::forward<Types>(args)...), Data_format::text); } }; // ============================================================================= /// Non-nullable array to/from `std::string` conversions. template<typename> struct Array_string_conversions_vals; /// Non-nullable array to/from Data conversions. template<typename> struct Array_data_conversions_vals; /// The partial specialization of Array_string_conversions_vals. template<typename T, template<class, class> class Container, template<class> class Allocator> struct Array_string_conversions_vals<Container<T, Allocator<T>>> final { using Type = Container<T, Allocator<T>>; template<typename ... Types> static Type to_type(const std::string& literal, Types&& ... args) { return to_container_of_values(Array_string_conversions_opts<Cont>::to_type(literal, std::forward<Types>(args)...)); } template<typename ... Types> static std::string to_string(const Type& value, Types&& ... args) { return Array_string_conversions_opts<Cont>::to_string( to_container_of_optionals<std::optional>(value), std::forward<Types>(args)...); } private: using Cont = Cont_of_opts_t<Type>; }; /// The partial specialization of Array_data_conversions_vals. template<typename T, template<class, class> class Container, template<class> class Allocator> struct Array_data_conversions_vals<Container<T, Allocator<T>>> final { using Type = Container<T, Allocator<T>>; template<typename ... Types> static Type to_type(const Data* const data, Types&& ... args) { return to_container_of_values(Array_data_conversions_opts<Cont>::to_type(data, std::forward<Types>(args)...)); } template<typename ... Types> static Type to_type(std::unique_ptr<Data>&& data, Types&& ... args) { return to_container_of_values(Array_data_conversions_opts<Cont>::to_type(std::move(data), std::forward<Types>(args)...)); } template<typename ... Types> static std::unique_ptr<Data> to_data(Type&& value, Types&& ... args) { return Array_data_conversions_opts<Cont>::to_data( to_container_of_optionals<std::optional>(std::forward<Type>(value)), std::forward<Types>(args)...); } private: using Cont = Cont_of_opts_t<Type>; }; // ----------------------------------------------------------------------------- // Parser and filler // ------------------------------------------------------------------------------ /** * @brief Fills the container with values extracted from the PostgreSQL array * literal. * * This functor is for filling the deepest (sub-)container of STL-container (of * container ...) with a values extracted from the PostgreSQL array literals. * I.e., it's a filler of a STL-container of the highest dimensionality. * * @par Requires * See the requirements of the API. Also, `T` mustn't be container. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> class Filler_of_deepest_container final { private: template<typename U> struct Is_container final : std::false_type{}; template<typename U, template<class> class Opt, template<class, class> class Cont, template<class> class Alloc> struct Is_container<Cont<Opt<U>, Alloc<Opt<U>>>> final : std::true_type{}; public: using Value_type = T; using Optional_type = Optional<Value_type>; using Allocator_type = Allocator<Optional_type>; using Container_type = Container<Optional_type, Allocator_type>; static constexpr bool is_value_type_container = Is_container<Value_type>::value; explicit constexpr Filler_of_deepest_container(Container_type& c) : cont_(c) {} constexpr void operator()(const int /*dimension*/) {} template<typename ... Types> void operator()(std::string&& value, const bool is_null, const int /*dimension*/, Types&& ... args) { if constexpr (!is_value_type_container) { if (is_null) cont_.push_back(Optional_type()); else cont_.push_back(Conversions<Value_type>::to_type(std::move(value), std::forward<Types>(args)...)); } else { (void)value; // dummy usage (void)is_null; // dummy usage throw Client_exception{Client_errc::excessive_array_dimensionality}; } } private: Container_type& cont_; }; // ===================================== /// Special overloads. namespace arrays { /// Used by fill_container(). template<typename T, typename ... Types> const char* fill_container(T& /*result*/, const char* /*literal*/, const char /*delimiter*/, Types&& ... /*args*/) { throw Client_exception{Client_errc::insufficient_array_dimensionality}; } /// Used by to_array_literal() template<typename T> const char* quote_for_array_element(const T&) { return "\""; } /// Used by to_array_literal(). template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> const char* quote_for_array_element(const Container<Optional<T>, Allocator<Optional<T>>>&) { return ""; } /// Used by to_array_literal(). template<typename T, typename ... Types> std::string to_array_literal(const T& element, const char /*delimiter*/, Types&& ... args) { return Conversions<T>::to_string(element, std::forward<Types>(args)...); } /// Used by to_array_literal(). template<class CharT, class Traits, class Allocator, typename ... Types> std::string to_array_literal(const std::basic_string<CharT, Traits, Allocator>& element, const char /*delimiter*/, Types&& ... args) { using String = std::basic_string<CharT, Traits, Allocator>; std::string result{Conversions<String>::to_string(element, std::forward<Types>(args)...)}; // Escaping quotes. typename String::size_type i = result.find("\""); while (i != String::npos) { result.replace(i, 1, "\\\""); i = result.find("\"", i + 2); } return result; } /// Used by to_container_of_values(). template<typename T> T to_container_of_values(T&& element) { return std::move(element); } /** * @brief Used by to_container_of_optionals(). * * @remarks Workaround for GCC. */ template<template<class> class Optional> Optional<std::string> to_container_of_optionals(std::string&& element) { return Optional<std::string>{std::move(element)}; } /** * @overload * * @remarks It does'nt works with GCC (tested on version 8), and it does not * needs to MSVC. It's exists just in case, probably, for other compilers. */ template<template<class> class Optional, class CharT, class Traits, class Allocator> Optional<std::basic_string<CharT, Traits, Allocator>> to_container_of_optionals(std::basic_string<CharT, Traits, Allocator>&& element) { using String = std::basic_string<CharT, Traits, Allocator>; return Optional<String>{std::move(element)}; } /** * @overload * * @brief Used by to_container_of_optionals(). */ template<template<class> class Optional, typename T> Optional<T> to_container_of_optionals(T&& element) { return Optional<T>{std::move(element)}; } } // namespace arrays // ===================================== /** * @brief PostgreSQL array parsing routine. * * Calls `handler(dimension)` every time the opening curly bracket is reached. * Here, dimension - is a zero-based index of type `int` of the reached * dimension of the literal. * * Calls `handler(element, is_element_null, dimension, args)` each time when * the element is extracted. Here: * - element (std::string&&) -- is a text representation of the array element; * - is_element_null (bool) is a flag that equals to true if the extracted * element is SQL NULL; * - dimension -- is a zero-based index of type `int` of the element dimension; * - args -- extra arguments for passing to the conversion routine. * * @returns The pointer that points to a next character after the last closing * curly bracket found in the `literal`. * * @throws Client_exception. */ template<class F, typename ... Types> const char* parse_array_literal(const char* literal, const char delimiter, F& handler, Types&& ... args) { assert(literal); /* * Syntax of the array literals: * * '{ val1 delimiter val2 delimiter ... }' * * Examples of valid literals: * * {} * {{}} * {1,2} * {{1,2},{3,4}} * {{{1,2}},{{3,4}}} */ enum { in_beginning, in_dimension, in_quoted_element, in_unquoted_element } state = in_beginning; int dimension{}; char previous_char{}; char previous_nonspace_char{}; std::string element; const std::locale loc; while (const char c = *literal) { switch (state) { case in_beginning: { if (c == '{') { handler(dimension); dimension = 1; state = in_dimension; } else if (std::isspace(c, loc)) { // Skip space. } else throw Client_exception{Client_errc::malformed_array_literal}; goto preparing_to_the_next_iteration; } case in_dimension: { assert(dimension > 0); if (std::isspace(c, loc)) { // Skip space. } else if (c == delimiter) { if (previous_nonspace_char == delimiter || previous_nonspace_char == '{') throw Client_exception{Client_errc::malformed_array_literal}; } else if (c == '{') { handler(dimension); ++dimension; } else if (c == '}') { if (previous_nonspace_char == delimiter) throw Client_exception{Client_errc::malformed_array_literal}; --dimension; if (dimension == 0) { // Any character may follow after the closing curly bracket. It's ok. ++literal; // consuming the closing curly bracket return literal; } } else if (c == '"') { state = in_quoted_element; } else { state = in_unquoted_element; continue; } goto preparing_to_the_next_iteration; } case in_quoted_element: { if (c == '\\' && previous_char != '\\') { // Skip escape character '\\'. } else if (c == '"' && previous_char != '\\') goto element_extracted; else element += c; goto preparing_to_the_next_iteration; } case in_unquoted_element: { if (c == delimiter || c == '{' || c == '}') goto element_extracted; else element += c; goto preparing_to_the_next_iteration; } } // switch (state) element_extracted: { if (element.empty()) throw Client_exception{Client_errc::malformed_array_literal}; const bool is_element_null = ((state == in_unquoted_element && element.size() == 4) && ((element[0] == 'n' || element[0] == 'N') && (element[1] == 'u' || element[1] == 'U') && (element[2] == 'l' || element[2] == 'L') && (element[3] == 'l' || element[3] == 'L'))); handler(std::move(element), is_element_null, dimension, std::forward<Types>(args)...); element = std::string{}; // The element was moved and must be recreated! if (state == in_unquoted_element) { /* * Just after extracting unquoted element, the (*literal) is a * character that must be processed next. Thus, continue immediately. */ state = in_dimension; continue; } else { state = in_dimension; } } // extracted element processing preparing_to_the_next_iteration: if (!std::isspace(c, loc)) previous_nonspace_char = c; previous_char = c; ++literal; } // while if (dimension != 0) throw Client_exception{Client_errc::malformed_array_literal}; return literal; } /** * @brief Fills the container with elements extracted from the PostgreSQL array * literal. * * @returns The pointer that points to a next character after the last closing * curly bracket found in the `literal`. * * @throws Client_error. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator, typename ... Types> const char* fill_container(Container<Optional<T>, Allocator<Optional<T>>>& result, const char* literal, const char delimiter, Types&& ... args) { assert(result.empty()); assert(literal); /* * Note: On MSVS the "fatal error C1001: An internal error has occurred in the compiler." * is possible if the using directive below points to the incorrect symbol! */ using str::next_non_space_pointer; literal = next_non_space_pointer(literal); if (*literal != '{') throw Client_exception{Client_errc::malformed_array_literal}; const char* subliteral = next_non_space_pointer(literal + 1); if (*subliteral == '{') { // Multidimensional array literal detected. while (true) { using Subcontainer = T; result.push_back(Subcontainer()); Optional<Subcontainer>& element = result.back(); Subcontainer& subcontainer = *element; /* * The type of the result must have proper dimensionality to correspond * the dimensionality of array represented by the literal. * We are using overload of fill_container() defined in the nested * namespace "arrays" which throws exception if the dimensionality of the * result is insufficient. */ using namespace arrays; subliteral = fill_container(subcontainer, subliteral, delimiter, std::forward<Types>(args)...); // For better understanding, imagine the source literal as "{{{1,2}},{{3,4}}}". subliteral = next_non_space_pointer(subliteral); if (*subliteral == delimiter) { /* * The end of the subarray of the current dimension: subliteral is ",{{3,4}}}". * Parsing will be continued. The subliteral of next array must begins with '{'. */ subliteral = next_non_space_pointer(subliteral + 1); if (*subliteral != '{') throw Client_exception{Client_errc::malformed_array_literal}; } else if (*subliteral == '}') { // The end of the dimension: subliteral is "},{{3,4}}}" ++subliteral; return subliteral; } } } else { Filler_of_deepest_container<T, Optional, Container, Allocator> handler(result); return parse_array_literal(literal, delimiter, handler, std::forward<Types>(args)...); } } /// @returns PostgreSQL array literal converted from the given `container`. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator, typename ... Types> std::string to_array_literal(const Container<Optional<T>, Allocator<Optional<T>>>& container, const char delimiter, Types&& ... args) { auto i = cbegin(container); const auto e = cend(container); std::string result("{"); if (i != e) { while (true) { if (const Optional<T>& element = *i) { /* * End elements shall be quoted, subliterals shall not be quoted. * We are using overloads defined in nested namespace "arrays" for this. */ using namespace arrays; result.append(quote_for_array_element(*element)); result.append(to_array_literal(*element, delimiter, std::forward<Types>(args)...)); result.append(quote_for_array_element(*element)); } else result.append("NULL"); if (++i != e) result += delimiter; else break; } } result.append("}"); return result; } /// @returns A container converted from PostgreSQL array literal. template<class Container, typename ... Types> Container to_container(const char* const literal, const char delimiter, Types&& ... args) { Container result; fill_container(result, literal, delimiter, std::forward<Types>(args)...); return result; } /** * @returns A container of non-null values converted from PostgreSQL array literal. * * @throws Improper_value_type_of_container. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> auto to_container_of_values(Container<Optional<T>, Allocator<Optional<T>>>&& container) -> Cont_of_vals_t<Container<Optional<T>, Allocator<Optional<T>>>> { Cont_of_vals_t<Container<Optional<T>, Allocator<Optional<T>>>> result; result.resize(container.size()); std::transform(begin(container), end(container), begin(result), [](auto& elem) { using namespace arrays; if (elem) return to_container_of_values(std::move(*elem)); else throw Client_exception{Client_errc::improper_value_type_of_container}; }); return result; } /// @returns A container of nullable values converted from PostgreSQL array literal. template<template<class> class Optional, typename T, template<class, class> class Container, template<class> class Allocator> auto to_container_of_optionals(Container<T, Allocator<T>>&& container) -> Cont_of_opts_t<Container<T, Allocator<T>>> { Cont_of_opts_t<Container<T, Allocator<T>>> result; result.resize(container.size()); std::transform(begin(container), end(container), begin(result), [](auto& elem) { using namespace arrays; return to_container_of_optionals<Optional>(std::move(elem)); }); return result; } } // namespace detail /** * @ingroup conversions * * @brief The partial specialization of Conversions for nullable arrays (i.e. * containers with optional values). * * @par Requirements * @parblock * Requirements to the type T of elements of array: * - default-constructible, copy-constructible; * - convertible (there shall be a suitable specialization of Conversions). * * Requirements to the type Optional: * - default-constructible, copy-constructible; * - implemented operator bool() that returns true if the value is not null, or * false otherwise. (For default constructed Optional<T> it should return false); * - implemented operator*() that returns a reference to the value of type T. * @endparblock * * @tparam T The type of the elements of the Container (which may be a container * of optionals). * @tparam Optional The optional template class, such as `std::optional`. * @tparam Container The container template class, such as `std::vector`. * @tparam Allocator The allocator template class, such as `std::allocator`. * * The support of the following data formats is implemented: * - for input data - Data_format::text; * - for output data - Data_format::text. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> struct Conversions<Container<Optional<T>, Allocator<Optional<T>>>> final : public Basic_conversions<Container<Optional<T>, Allocator<Optional<T>>>, detail::Array_string_conversions_opts<Container<Optional<T>, Allocator<Optional<T>>>>, detail::Array_data_conversions_opts<Container<Optional<T>, Allocator<Optional<T>>>>> {}; /** * @ingroup conversions * * @brief The partial specialization of Conversions for non-nullable arrays. * * @par Requirements * @parblock * Requirements to the type T of elements of array: * - default-constructible, copy-constructible; * - convertible (there shall be a suitable specialization of Conversions). * @endparblock * * @tparam T The type of the elements of the Container (which may be a container). * @tparam Container The container template class, such as `std::vector`. * @tparam Allocator The allocator template class, such as `std::allocator`. * * @throws An instance of type Improper_value_type_of_container when converting * the PostgreSQL array representations with at least one `NULL` element. * * The support of the following data formats is implemented: * - for input data - Data_format::text; * - for output data - Data_format::text. */ template<typename T, template<class, class> class Container, template<class> class Allocator> struct Conversions<Container<T, Allocator<T>>> : public Basic_conversions<Container<T, Allocator<T>>, detail::Array_string_conversions_vals<Container<T, Allocator<T>>>, detail::Array_data_conversions_vals<Container<T, Allocator<T>>>> {}; /** * @brief The partial specialization of Conversions for non-nullable arrays. * * This is a workaround for GCC. When using multidimensional STL-containers GCC * (at least version 8.1) incorrectly choises the specialization of * `Conversions<Container<Optional<T>, Allocator<Optional<T>>>>` by deducing * `Optional` as an STL container, instead of choising * `Conversions<Container<T>, Allocator<T>>` and thus, the nested vector in * `std::vector<std::vector<int>>` treated as `Optional`. */ template<typename T, template<class, class> class Container, template<class, class> class Subcontainer, template<class> class ContainerAllocator, template<class> class SubcontainerAllocator> struct Conversions<Container<Subcontainer<T, SubcontainerAllocator<T>>, ContainerAllocator<Subcontainer<T, SubcontainerAllocator<T>>>>> : public Basic_conversions<Container<Subcontainer<T, SubcontainerAllocator<T>>, ContainerAllocator<Subcontainer<T, SubcontainerAllocator<T>>>>, detail::Array_string_conversions_vals<Container<Subcontainer<T, SubcontainerAllocator<T>>, ContainerAllocator<Subcontainer<T, SubcontainerAllocator<T>>>>>, detail::Array_data_conversions_vals<Container<Subcontainer<T, SubcontainerAllocator<T>>, ContainerAllocator<Subcontainer<T, SubcontainerAllocator<T>>>>>> {}; } // namespace dmitigr::pgfe #endif // DMITIGR_PGFE_ARRAY_CONVERSIONS_HPP
33.140165
125
0.681902
dmitigr
e8c64818f81bb22edcb898ba35b7f60f1e9530d5
843
cpp
C++
cap04/cap04-ex4_3-00-dinamic_array-replaceString.cpp
ggaaaff/think_like_a_programmer--test_code
fb081d24d70db6dd503608562625b84607c7a3ab
[ "MIT" ]
1
2020-12-08T10:54:39.000Z
2020-12-08T10:54:39.000Z
cap04/cap04-ex4_3-00-dinamic_array-replaceString.cpp
ggaaaff/think_like_a_programmer--test_code
fb081d24d70db6dd503608562625b84607c7a3ab
[ "MIT" ]
null
null
null
cap04/cap04-ex4_3-00-dinamic_array-replaceString.cpp
ggaaaff/think_like_a_programmer--test_code
fb081d24d70db6dd503608562625b84607c7a3ab
[ "MIT" ]
null
null
null
//2014.03.28 Gustaf - CTG. /* EXERCISE 4-3 : For our dynamically allocated strings, create a function replaceString that takes three parameters, each of type arrayString: source, target, and replaceText. The function replaces every occurrence of target in source with replaceText. For example, if source points to an array containing "abcdabee", target points to "ab", and replaceText points to "xyz", then when the function ends, source should point to an array containing "xyzcdxyzee". === PLAN === - Diagram of the example. - Traverse (go over) the SOURCE string and identify the initial and final positions in the TARGET string. */ #include <iostream> using namespace std; typedef char *arrayString; int main() { cout << "Variable-Length String Manipulation. REPLACE" << endl; cout << endl; return 0; }
18.326087
105
0.729537
ggaaaff
e8c737caea08dc08f30b761194ab66c7955ee9ac
2,843
cpp
C++
dev/Mobile/PerfMonitor/Views/ToolBoxView.cpp
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
dev/Mobile/PerfMonitor/Views/ToolBoxView.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
dev/Mobile/PerfMonitor/Views/ToolBoxView.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include "ToolBoxView.h" #include <MobileDeviceBridge.h> #include <QBoxLayout> #include <QPushButton> #include <QLabel> #include <QLineEdit> #include <QFileDialog> #include <QListWidget> ToolBoxView::ToolBoxView(QWidget* parent) : QWidget(parent) , m_Device(nullptr) { CreateUI(); } ToolBoxView::~ToolBoxView() { } void ToolBoxView::CreateUI() { QVBoxLayout* rootLayout = new QVBoxLayout; QHBoxLayout* toolLine = new QHBoxLayout; QHBoxLayout* inputLine = new QHBoxLayout; QPushButton* btnInstall = new QPushButton(tr("Install App"), this); connect(btnInstall, SIGNAL(clicked()), SLOT(showApkInstallDirectory())); QPushButton* btnPull = new QPushButton(tr("Pull"), this); connect(btnPull, SIGNAL(clicked()), SLOT(pullRemoteToLocal())); QPushButton* btnPush = new QPushButton(tr("Push"), this); connect(btnPush, SIGNAL(clicked()), SLOT(pushLocalToRemote())); toolLine->addWidget(btnInstall); toolLine->addWidget(btnPull); toolLine->addWidget(btnPush); QLabel* localLb = new QLabel(tr("Local Dir:"), this); QLabel* remoteLb = new QLabel(tr("Remote Dir:"), this); m_LocalDir = new QLineEdit(this); m_RemoteDir = new QLineEdit(this); inputLine->addWidget(localLb); inputLine->addWidget(m_LocalDir); inputLine->addWidget(remoteLb); inputLine->addWidget(m_RemoteDir); rootLayout->addLayout(toolLine); rootLayout->addLayout(inputLine); setLayout(rootLayout); } void ToolBoxView::SetCurrentDevice(k3d::mobi::IDevice * pDevice) { m_Device = pDevice; } void ToolBoxView::showApkInstallDirectory() { if (!m_Device) return; auto plat = m_Device->GetPlatform(); QFileDialog dialog(this); dialog.setWindowTitle(plat == k3d::mobi::EPlatform::Android ? tr("Select App (Android: apk) to Install") : tr("Select App (iOS: ipa) to Install") ); dialog.setDirectory("."); dialog.setNameFilter(plat == k3d::mobi::EPlatform::Android ? tr("Android App (*.apk)") : tr("iOS App (*.ipa)")); dialog.setFileMode(QFileDialog::ExistingFile); dialog.setViewMode(QFileDialog::Detail); QStringList fileNames; if (dialog.exec()) { fileNames = dialog.selectedFiles(); } if (fileNames.size() == 1) { QString appPath = fileNames[0]; m_Device->InstallApp(appPath.toUtf8().data()); // add recent installed app } } void ToolBoxView::pullRemoteToLocal() { QString localDir = m_LocalDir->text(); QString remoteDir = m_RemoteDir->text(); m_Device->Download(localDir.toUtf8().data(), remoteDir.toUtf8().data()); } void ToolBoxView::pushLocalToRemote() { QString localDir = m_LocalDir->text(); QString remoteDir = m_RemoteDir->text(); m_Device->Upload(localDir.toUtf8().data(), remoteDir.toUtf8().data()); }
28.148515
76
0.673584
PixPh
e8c8213bc7b85fa2a94f92f355d3ea213c0e593a
1,511
cpp
C++
Hacker_Rank_Challenges/C++/Sets-STL.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
1
2019-03-24T12:35:43.000Z
2019-03-24T12:35:43.000Z
Hacker_Rank_Challenges/C++/Sets-STL.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
Hacker_Rank_Challenges/C++/Sets-STL.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
/* you will be give Q queries.Each query is of one of the three types: 1 x:Add an element x to the set. 2 x:Delete an element x from the set. (If the number x is not present in the set then do nothing). 3 x:If the number x is present in the set then print "Yes"(without quotes) else print "No"(without quotes). Input Format The first line of the input contains Q where Q is the number of queries. The next Q lines contain 1 query each. Each query consists of two integers y and x where y is the type of the query and x is an integer. Constraints 1<=Q<=105 1<=y<=3 1<=x<=109 Output Format For queries of type 3 print "Yes"(without quotes) if the number x is present in the set and if not present then print "No"(without quotes). Each query of type 3 should be printed in a new line. */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <set> #include <algorithm> #include <sstream> #include<istream> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ string s; int n,a,b; cin>>n; set<int>SET; for(int i=0;i<n;i++) { cin>>a; cin>>b; if(a==1) SET.insert(b); if(a==2) SET.erase(b); if(a==3) { set<int>::iterator itr=SET.find(b); if(itr==SET.end()) cout<<"No"<<endl; else cout<<"Yes"<<endl; } } return 0; }
24.370968
209
0.604236
anishacharya
e8c98b346df12bf53ae3a3a51e720e1baedd0486
2,536
cpp
C++
webkit/WebCore/plugins/Plugin.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/plugins/Plugin.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/plugins/Plugin.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "Plugin.h" #include "AtomicString.h" #include "PluginData.h" #include "Frame.h" namespace WebCore { Plugin::Plugin(PluginData* pluginData, unsigned index) : m_pluginData(pluginData) , m_index(index) { } Plugin::~Plugin() { } String Plugin::name() const { return m_pluginData->plugins()[m_index]->name; } String Plugin::filename() const { return m_pluginData->plugins()[m_index]->file; } String Plugin::description() const { return m_pluginData->plugins()[m_index]->desc; } unsigned Plugin::length() const { return m_pluginData->plugins()[m_index]->mimes.size(); } PassRefPtr<MimeType> Plugin::item(unsigned index) { const Vector<PluginInfo*>& plugins = m_pluginData->plugins(); if (index >= plugins[m_index]->mimes.size()) return 0; MimeClassInfo* mime = plugins[m_index]->mimes[index]; const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); for (unsigned i = 0; i < mimes.size(); ++i) if (mimes[i] == mime) return MimeType::create(m_pluginData.get(), i).get(); return 0; } bool Plugin::canGetItemsForName(const AtomicString& propertyName) { const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); for (unsigned i = 0; i < mimes.size(); ++i) if (mimes[i]->type == propertyName) return true; return false; } PassRefPtr<MimeType> Plugin::namedItem(const AtomicString& propertyName) { const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); for (unsigned i = 0; i < mimes.size(); ++i) if (mimes[i]->type == propertyName) return MimeType::create(m_pluginData.get(), i).get(); return 0; } } // namespace WebCore
27.565217
82
0.682177
s1rcheese
e8cd32226646c8f0e83a040e7344d0c1989634cf
12,725
cpp
C++
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Graphics/Rendering/GraphicsRenderer2D.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Graphics/Rendering/GraphicsRenderer2D.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Graphics/Rendering/GraphicsRenderer2D.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
using namespace RSLib; //------------------------------------------------------------------------------------------------- // class rsGraphicsRenderer2D (the abstract baseclass): // construction/destruction: rsGraphicsRenderer2D::rsGraphicsRenderer2D() { } rsGraphicsRenderer2D::~rsGraphicsRenderer2D() { } // setup: void rsGraphicsRenderer2D::setColor(const rsColorRGBA& newColor) { state.color = newColor; } void rsGraphicsRenderer2D::setLineThickness(const double newThickness) { state.lineThickness = newThickness; } // drawing: void rsGraphicsRenderer2D::drawFilledEllipseInscribedPolygon(int numVertices, double cx, double cy, double rx, double ry, double a) { rsPolygon2D<double> polygon(numVertices, rsPoint2D<double>(cx, cy), rx, ry, a); drawFilledPolygon(polygon); } void rsGraphicsRenderer2D::drawLine(double x1, double y1, double x2, double y2) { double dx = x2 - x1; double dy = y2 - y1; double d = rsSqrt(dx*dx + dy*dy); double s = 0.5*state.lineThickness/d; dx = s * dy; dy = s * (x2-x1); // == s times the old dx (before reassigning it) rsPolygon2D<double> p; p.reserveVertexMemory(4); p.addVertex(rsPoint2D<double>(x1 - dx, y1 + dy)); p.addVertex(rsPoint2D<double>(x2 - dx, y2 + dy)); p.addVertex(rsPoint2D<double>(x2 + dx, y2 - dy)); p.addVertex(rsPoint2D<double>(x1 + dx, y1 - dy)); drawFilledPolygon(p); } void rsGraphicsRenderer2D::drawOutlinedRectangle(double x, double y, double w, double h) { double t = state.lineThickness; double t2 = 0.5*t; drawFilledRectangle(x-t2, y-t2, t, h+t2); // left edge drawFilledRectangle(x-t2, y-t2, w+t2, t); // top edge drawFilledRectangle(x+w-t2, y-t2, t, h+t2); // right edge drawFilledRectangle(x-t2, y+h-t2, w+t2, t); // bottom edge } void rsGraphicsRenderer2D::drawFilledRectangle(double x, double y, double w, double h) { rsPolygon2D<double> p; p.reserveVertexMemory(4); p.addVertex(rsPoint2D<double>(x, y )); p.addVertex(rsPoint2D<double>(x+w, y )); p.addVertex(rsPoint2D<double>(x+w, y+h)); p.addVertex(rsPoint2D<double>(x, y+h)); drawFilledPolygon(p); } void rsGraphicsRenderer2D::drawFilledEllipse(double cx, double cy, double rx, double ry) { int n = rsMax((int) ceil(rx), (int) ceil(ry)); // \todo use rsCeilInt if( rsIsOdd(n) ) n += 1; n = rsMax(n, 8); // at least 8 vertices drawFilledEllipseInscribedPolygon(n, cx, cy, rx, ry); // \todo maybe an ellipse can be drawn more efficiently using some functions from // agg_renderer_primitives.h - look into this, if this turns out to be true, override it // rsGraphicsRenderer2DImage } void rsGraphicsRenderer2D::drawOutlinedPixelRectangle(int x, int y, int w, int h) { drawFilledRectangle(x, y, 1.0, h); // left edge drawFilledRectangle(x, y, w, 1.0); // top edge drawFilledRectangle(x+w-1.0, y, 1.0, h); // right edge drawFilledRectangle(x, y+h-1.0, w, 1.0); // top edge } void rsGraphicsRenderer2D::drawFilledPixelRectangle(int x, int y, int w, int h) { drawFilledRectangle(x, y, w, h); } //------------------------------------------------------------------------------------------------- // class rsGraphicsRenderer2DImage: rsGraphicsRenderer2DImage::rsGraphicsRenderer2DImage(rsImageRegionRGBA &imageRegionToRenderOn) : imageRegion(imageRegionToRenderOn) { } rsGraphicsRenderer2DImage::~rsGraphicsRenderer2DImage() { } // drawing: void rsGraphicsRenderer2DImage::fillAll() { imageRegion.fillAll(state.color); } void rsGraphicsRenderer2DImage::drawFilledPolygon(const rsPolygon2D<double> &polygon) { rsAGG::drawFilledPolygon(polygon, imageRegion, state.color); } void rsGraphicsRenderer2DImage::drawOutlinedPolygon(const rsPolygon2D<double> &polygon) { rsAGG::drawOutlinedPolygon(polygon, imageRegion, state.color, state.lineThickness); } void rsGraphicsRenderer2DImage::drawText(const rsString &text, int x, int y, int width, int height) { const rsPixelFont *fontToUse = rsGlobalFontInstances::getPixelFontRoundedBoldA16D0(); // \todo shall become reference parameter or state-variable later int kerning = fontToUse->getDefaultKerning(); rsJustification justification; //justification.setJustifiedLeft(); //justification.setJustifiedRight(); //justification.setHorizontallyCentered(); //justification.setJustifiedTop(); //justification.setVerticallyCentered(); //justification.setJustifiedBottom(); //justification.setCentered(); // adjust x, y according to justification (factor out): int xText = x; int yText = y; int textWidth = fontToUse->getTextPixelWidth(text, kerning); int textHeight = fontToUse->getFontHeight(); if( justification.isHorizontallyCentered() ) xText += (width - textWidth) / 2; else if( justification.isJustifiedRight() ) xText += (width - textWidth); if( justification.isVerticallyCentered() ) yText += (height - textHeight) / 2; else if( justification.isJustifiedBottom() ) yText += (height - textHeight); // draw top-left justified text with the modified x, y (factor out): int xMin = x; int yMin = y; int xMax = x + width; int yMax = y + height; for(int i = 0; i < text.getLength(); i++) { rsUint8 c = text.getElement(i); const rsImageGray *glyphImage = fontToUse->getGlyphImage(c/*, state.color*/); if( glyphImage != NULL ) { // clip glyph when text extends beyond its box: int x = rsMax(xText, xMin); int y = rsMax(yText, yMin); int w = rsMin(glyphImage->getWidth(), xMax-x); int h = rsMin(glyphImage->getHeight(), yMax-y); // draw glyph: fillRectangleUsingAlphaMask(x, y, w, h, glyphImage, x-xText, y-yText); xText += fontToUse->getGlyphWidth(c) + kerning; } } // \todo maybe handle line-break characters by incrementing y // \todo factor out a function drawTopLeftJustifiedTextAt } void rsGraphicsRenderer2DImage::fillRectangleWithBilinearGradient(int x, int y, int w, int h, const rsColorRGBA &topLeftColor, const rsColorRGBA &topRightColor, const rsColorRGBA &bottomLeftColor, const rsColorRGBA &bottomRightColor) { rsColorRGBA cL, cR; double scaler = 1.0 / (h-1); rsUint8 weight; int iStart = rsMax(y, 0); int iEnd = rsMin(y+h-1, imageRegion.getHeight()-1); for(int i = iStart; i <= iEnd; i++) { weight = (rsUint8) (255.f * scaler * (i-y)); cL.setAsWeightedAverage(topLeftColor, bottomLeftColor, weight); cR.setAsWeightedAverage(topRightColor, bottomRightColor, weight); drawHorizontalGradientLine(y+i, x, x+w-1, cL, cR); } } void rsGraphicsRenderer2DImage::drawOutlinedPixelRectangle(int x, int y, int w, int h) { if( w <= 0 || h <= 0 ) return; int xMax = imageRegion.getWidth() - 1; int yMax = imageRegion.getHeight() - 1; if( rsIsInRange(y, 0, yMax) ) drawHorizontalPixelLine(y, x, x+w-1); // top line if( rsIsInRange(y+h-1, 0, yMax) ) drawHorizontalPixelLine(y+h-1, x, x+w-1); // bottom line if( rsIsInRange(x, 0, xMax) ) drawVerticalPixelLine(x, y, y+h-1); // left line if( rsIsInRange(x+w-1, 0, xMax) ) drawVerticalPixelLine(x+w-1, y, y+h-1); // right line } void rsGraphicsRenderer2DImage::drawFilledPixelRectangle(int x, int y, int w, int h) { clipToValidRange(x, y, w, h); for(int iy = y; iy < y+h; iy++) { for(int ix = x; ix < x+w; ix++) imageRegion.setPixelColor(ix, iy, state.color); } } void rsGraphicsRenderer2DImage::drawHorizontalPixelLine(int y, int x1, int x2) { rsSortAscending(x1, x2); for(int x = rsMax(0, x1); x <= rsMin(x2, imageRegion.getWidth()-1); x++) imageRegion.setPixelColor(x, y, state.color); } void rsGraphicsRenderer2DImage::drawVerticalPixelLine(int x, int y1, int y2) { rsSortAscending(y1, y2); for(int y = rsMax(0, y1); y <= rsMin(y2, imageRegion.getHeight()-1); y++) imageRegion.setPixelColor(x, y, state.color); } void rsGraphicsRenderer2DImage::drawBresenhamLine(int x1, int y1, int x2, int y2) { bool steep = abs(y2 - y1) > abs(x2 - x1); if( steep ) { rsSwap(x1, y1); rsSwap(x2, y2); } if( x1 > x2 ) { rsSwap(x1, x2); rsSwap(y1, y2); } int deltaX = x2 - x1; int deltaY = abs(y2 - y1); int error = deltaX / 2; int ystep; int y = y1; if( y1 < y2 ) ystep = 1; else ystep = -1; for(int x=x1; x<=x2; x++) { if( steep ) imageRegion.setPixelColor(y, x, state.color); else imageRegion.setPixelColor(x, y, state.color); error = error - deltaY; if( error < 0 ) { y = y + ystep; error = error + deltaX; } } } void rsGraphicsRenderer2DImage::drawVerticalGradientLine(int x, int yTop, int yBottom, const rsColorRGBA &topColor, const rsColorRGBA &bottomColor) { if( x < 0 || x > imageRegion.getWidth()-1 ) return; int h = yBottom - yTop; double scaler = 1.0 / h; rsColorRGBA c; rsUint8 weight; int iStart = rsMax(yTop, 0); int iEnd = rsMin(yBottom, imageRegion.getHeight()-1); for(int i = iStart; i <= iEnd; i++) { weight = (rsUint8) (255.f * scaler * (i-yTop)); c.setAsWeightedAverage(topColor, bottomColor, weight); imageRegion.setPixelColor(x, i, c); } } void rsGraphicsRenderer2DImage::drawHorizontalGradientLine(int y, int xLeft, int xRight, const rsColorRGBA &leftColor, const rsColorRGBA &rightColor) { if( y < 0 || y > imageRegion.getHeight()-1 ) return; int w = xRight - xLeft; double scaler = 1.0 / w; rsColorRGBA c; rsUint8 weight; int iStart = rsMax(xLeft, 0); int iEnd = rsMin(xRight, imageRegion.getWidth()-1); for(int i = iStart; i <= iEnd; i++) { weight = (rsUint8) (255.f * scaler * (i-xLeft)); c.setAsWeightedAverage(leftColor, rightColor, weight); imageRegion.setPixelColor(i, y, c); } } void rsGraphicsRenderer2DImage::fillRectangleUsingAlphaMask(int x, int y, int w, int h, const rsImageGray *mask, int xOffset, int yOffset) { // range checking (write a test and factor this out (maybe into // rsImage::restrictImageCopyRange or something)) if( x < 0 ) { w += x; x = 0; } if( y < 0 ) { h += y; y = 0; } if( x+w > imageRegion.getWidth() ) w = imageRegion.getWidth() - x; if( y+h > imageRegion.getHeight() ) h = imageRegion.getHeight() - y; if( w > imageRegion.getWidth()-xOffset ) w = imageRegion.getWidth() - xOffset; if( h > imageRegion.getHeight()-yOffset ) h = imageRegion.getHeight() - yOffset; // OK - range should be safe now for(int iy = 0; iy < h; iy++) { for(int ix = 0; ix < w; ix++) { rsUint8 alpha = mask->getPixelColor(ix+xOffset, iy+yOffset); rsColorRGBA oldColor = imageRegion.getPixelColor(x+ix, y+iy); rsColorRGBA newColor = state.color; rsColorRGBA blendColor; blendColor.setAsWeightedAverage(oldColor, newColor, alpha); imageRegion.setPixelColor(x+ix, y+iy, blendColor); // \todo take into account the alpha value of "newColor" - retain alpha of the "oldColor" but // mix-in the new color according to its own alpha value and the alpha value from the // alpha-mask // write rsColorRGBA.alphaBlendWith(newColor, alpha) and // image.blendPixelWith(x, y, color, alpha) // ....maybe it can be streamlined } } } void rsGraphicsRenderer2DImage::clipToValidRange(int &x, int &y, int &w, int &h) { x = rsClipToRange(x, 0, imageRegion.getWidth()-1); w = rsClipToRange(w, 0, imageRegion.getWidth()-x); y = rsClipToRange(y, 0, imageRegion.getHeight()-1); h = rsClipToRange(h, 0, imageRegion.getHeight()-y); } //------------------------------------------------------------------------------------------------- // class rsGraphicsRenderer2DOpenGL: rsGraphicsRenderer2DOpenGL::rsGraphicsRenderer2DOpenGL() { } rsGraphicsRenderer2DOpenGL::~rsGraphicsRenderer2DOpenGL() { } // setup: void rsGraphicsRenderer2DOpenGL::setColor(const rsColorRGBA& newColor) { rsGraphicsRenderer2D::setColor(newColor); // glSetColor ...or something } // drawing: /* void rsGraphicsRenderer2DOpenGL::drawLine(rsPoint2D<double> p1, rsPoint2D<double> p2) { // glDrawLine or something } */
30.442584
140
0.627741
RobinSchmidt
e8d05c7655dd1149727b26b9f7b175237253d9a1
5,861
cpp
C++
vaca/FileDialog.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
vaca/FileDialog.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
vaca/FileDialog.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
// Vaca - Visual Application Components Abstraction // Copyright (c) 2005-2010 David Capello // // This file is distributed under the terms of the MIT license, // please read LICENSE.txt for more information. #include "vaca/FileDialog.h" #include "vaca/Widget.h" #include "vaca/Application.h" #include "vaca/System.h" #include "vaca/String.h" // 32k is the limit for Win95/98/Me/NT4/2000/XP with ANSI version #define FILENAME_BUFSIZE (1024*32) using namespace vaca; // ====================================================================== // FileDialog FileDialog::FileDialog(const String& title, Widget* parent) : CommonDialog(parent) , m_title(title) , m_defaultExtension(L"") , m_showReadOnly(false) , m_showHelp(false) , m_defaultFilter(0) { m_fileName = new Char[FILENAME_BUFSIZE]; ZeroMemory(m_fileName, sizeof(Char[FILENAME_BUFSIZE])); } FileDialog::~FileDialog() { delete[] m_fileName; } /** Sets the title text. */ void FileDialog::setTitle(const String& str) { m_title = str; } /** Sets the default extension to add to the entered file name when an extension isn't specified by the user. By default it's an empty string. */ void FileDialog::setDefaultExtension(const String& str) { m_defaultExtension = str; } /** Sets the property that indicates if the dialog should show the read only check box. By default it's false: the button is hidden. */ void FileDialog::setShowReadOnly(bool state) { m_showReadOnly = state; } /** Sets the property that indicates if the dialog should show the help button. By default it's false: the button is hidden. */ void FileDialog::setShowHelp(bool state) { m_showHelp = state; } void FileDialog::addFilter(const String& extensions, const String& description, bool defaultFilter) { m_filters.push_back(std::make_pair(extensions, description)); if (defaultFilter) m_defaultFilter = m_filters.size(); } String FileDialog::getFileName() { return String(m_fileName); } void FileDialog::setFileName(const String& fileName) { copy_string_to(fileName, m_fileName, FILENAME_BUFSIZE); } LPTSTR FileDialog::getOriginalFileName() { return m_fileName; } bool FileDialog::doModal() { // make the m_filtersString m_filtersString.clear(); for (std::vector<std::pair<String, String> >::iterator it=m_filters.begin(); it!=m_filters.end(); ++it) { m_filtersString.append(it->first); m_filtersString.push_back('\0'); m_filtersString.append(it->second); m_filtersString.push_back('\0'); } m_filtersString.push_back('\0'); // fill the OPENFILENAME structure OPENFILENAME ofn; ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = getParentHandle(); ofn.hInstance = Application::getHandle(); ofn.lpstrFilter = m_filtersString.c_str(); ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = m_defaultFilter; ofn.lpstrFile = m_fileName; ofn.nMaxFile = FILENAME_BUFSIZE; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.lpstrTitle = m_title.c_str(); ofn.Flags = 0 // #define OFN_CREATEPROMPT 0x2000 // #define OFN_ENABLEHOOK 32 | OFN_ENABLESIZING // #define OFN_ENABLETEMPLATE 64 // #define OFN_ENABLETEMPLATEHANDLE 128 | OFN_EXPLORER // #define OFN_EXTENSIONDIFFERENT 0x400 | (m_showReadOnly ? 0: OFN_HIDEREADONLY) | OFN_LONGNAMES | OFN_NOCHANGEDIR // | OFN_NODEREFERENCELINKS // | OFN_NOLONGNAMES // | OFN_NONETWORKBUTTON // | OFN_NOREADONLYRETURN // | OFN_NOTESTFILECREATE // | OFN_NOVALIDATE // #define OFN_READONLY 1 // #define OFN_SHAREAWARE 0x4000 | (m_showHelp ? OFN_SHOWHELP: 0) ; // | OFN_SHAREFALLTHROUGH // | OFN_SHARENOWARN // | OFN_SHAREWARN // | OFN_NODEREFERENCELINKS // #if (_WIN32_WINNT >= 0x0500) // | OFN_DONTADDTORECENT // #endif ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = m_defaultExtension.c_str(); ofn.lCustData = 0; ofn.lpfnHook = NULL; ofn.lpTemplateName = NULL; #if (_WIN32_WINNT >= 0x0500) ofn.pvReserved = NULL; ofn.dwReserved = 0; ofn.FlagsEx = 0; #endif return showDialog(&ofn); } // ====================================================================== // OpenFileDialog OpenFileDialog::OpenFileDialog(const String& title, Widget* parent) : FileDialog(title, parent) , m_multiselect(false) { } OpenFileDialog::~OpenFileDialog() { } /** By default it's false. */ void OpenFileDialog::setMultiselect(bool state) { m_multiselect = state; } std::vector<String> OpenFileDialog::getFileNames() { std::vector<String> result; if (m_multiselect) { LPTSTR ptr, start; String path; for (ptr=start=getOriginalFileName(); ; ++ptr) { if (*ptr == '\0') { if (path.empty()) path = start; else result.push_back(path + L"\\" + start); if (*(++ptr) == '\0') break; start = ptr; } } } // empty results? one file-name selected if (result.empty()) result.push_back(getFileName()); return result; } bool OpenFileDialog::showDialog(LPOPENFILENAME lpofn) { lpofn->Flags |= 0 | (m_multiselect ? OFN_ALLOWMULTISELECT: 0) | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST ; return GetOpenFileName(lpofn) != FALSE; } // ====================================================================== // SaveFileDialog SaveFileDialog::SaveFileDialog(const String& title, Widget* parent) : FileDialog(title, parent) { } SaveFileDialog::~SaveFileDialog() { } bool SaveFileDialog::showDialog(LPOPENFILENAME lpofn) { lpofn->Flags |= 0 | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT ; return GetSaveFileName(lpofn) != FALSE; }
23.257937
100
0.651254
picrap
e8d08ef24eb9f7d4ac4cb5a186b0765686e35d40
6,595
cpp
C++
GD_HW/hw5/Game.cpp
HKhademian/UniGameDev
0abfe552ce863338a04e4efc38d3e87c31a99013
[ "Unlicense" ]
null
null
null
GD_HW/hw5/Game.cpp
HKhademian/UniGameDev
0abfe552ce863338a04e4efc38d3e87c31a99013
[ "Unlicense" ]
null
null
null
GD_HW/hw5/Game.cpp
HKhademian/UniGameDev
0abfe552ce863338a04e4efc38d3e87c31a99013
[ "Unlicense" ]
null
null
null
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <cstdlib> #include <cstdio> #include <chrono> #include <thread> #include "Scene.h" using namespace glm; namespace Game { Scene *scene; GLFWwindow *window; glm::vec2 press_mouse_position; glm::vec2 current_mouse_position; bool is_mouse_press; float angle_of_selected_bone; glm::vec3 axis_of_selected_bone; static void error_callback(int error, const char *description) { fprintf(stderr, "Error: %s\n", description); } static void key_callback(GLFWwindow *curWindow, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); else if (key >= GLFW_KEY_1 && key <= GLFW_KEY_9 && action == GLFW_PRESS) { scene->SelectBone(key - GLFW_KEY_1); } else if (key == GLFW_KEY_F && action == GLFW_PRESS) { scene->SwitchMode(); } else if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) { scene->PlayPause(); } else if (key >= GLFW_KEY_F1 && key <= GLFW_KEY_F19 && action == GLFW_PRESS) { scene->SetKeyFrame(key - GLFW_KEY_F1); } } static void mouse_callback(GLFWwindow *curWindow, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { double x, y; glfwGetCursorPos(window, &x, &y); press_mouse_position = glm::vec2(x, y); is_mouse_press = true; auto selectedBone = scene->GetSelectedBone(); if (selectedBone != nullptr) { glm::quat quat = glm::quat_cast(selectedBone->getLocalTransformation()); angle_of_selected_bone = glm::angle(quat); axis_of_selected_bone = glm::axis(quat); } } else is_mouse_press = false; } static void cursor_position_callback(GLFWwindow *curWindow, double xpos, double ypos) { current_mouse_position = glm::vec2(xpos, ypos); } glm::vec2 viewport2camera(glm::vec2 point) { int width, height; glfwGetFramebufferSize(window, &width, &height); float ratio = (float) width / (float) height; return glm::vec2(point.x * 150 * ratio / (float) width - 75 * ratio, -point.y * 150 / (float) height + 75); } void initScene() { scene = new Scene(); scene->AddBone("", "Bone 1", 25, 0); scene->AddBone("Bone 1", "Bone 2", 10, 0); scene->AddBone("Bone 2", "Bone 3", 20, 0); scene->AddBone("Bone 3", "Bone 4", 10, 0); scene->AddBone("Bone 4", "Bone 5", 20, 0); scene->AddBone("Bone 4", "Bone 5L", 10, glm::radians(45.0f)); // scene->AddBone("Bone 4", "Bone 5R", 10, -glm::radians(45.0f)); scene->AddBone("Bone 5", "Bone 6", 10, 0); scene->AddBone("Bone 6", "Bone 7", 10, 0); // scene->AddBone("Bone 7", "Bone HL", 10, glm::radians(45.0f)); // scene->AddBone("Bone 7", "Bone HR", 10, glm::radians(-45.0f)); scene->AddBone("Bone 7", "Bone H", 15, 0); scene->Init(); const int DefSegments = 100; std::vector<Vertex> skin; int bone_count = scene->GetBoneCount(); float x = 0; for (int i = 0; i < bone_count; i++) { int previous_bone_index = max(0, i - 1); int next_bone_index = min(bone_count - 1, i + 1); //Bone *previous_bone = scene->GetBone(previous_bone_index); Bone *bone = scene->GetBone(i); //Bone *next_bone = scene->GetBone(next_bone_index); // I add Variable segment count // it depends on bone length int Segments = (int) round((float) bone->getLength() / 10 * DefSegments); float step = (float) bone->getLength() / Segments; for (int j = 0; j < Segments; j++) { x += step; for (auto y : {5.f, -5.f}) { float part = (float) j / Segments; if (j < Segments / 2) skin.push_back(Vertex{ x, y, previous_bone_index, i, 0.5f - part, 0.5f + part, 0, 0 }); else skin.push_back(Vertex{ x, y, i, next_bone_index, (float) (1.0f - ((float) j - Segments / 2.0f) / Segments), (float) (((float) j - Segments / 2.0f) / Segments), 0, 0 }); } } } scene->SetSkin(skin); } void init() { glClearColor(0, 0, 0, 1); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); initScene(); } void processInput() { if (scene->mode == Scene::MODE_INVERSE) { scene->inverse_target = viewport2camera(press_mouse_position); } else if (scene->mode == Scene::MODE_NORMAL && is_mouse_press) { auto diff = (current_mouse_position - press_mouse_position); auto angle = glm::atan(-diff.y, diff.x); scene->RotateSelectedBone(angle + axis_of_selected_bone.z * angle_of_selected_bone); } glfwPollEvents(); } void Update(float deltaTime) { int width, height; glfwGetFramebufferSize(window, &width, &height); float ratio = float(width) / float(height); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-ratio * 75.f, ratio * 75.f, -75, 75.f); scene->Update(deltaTime); } void Render() { glClear(GL_COLOR_BUFFER_BIT); // Draw Origin for rotation auto pos = viewport2camera(press_mouse_position); glColor3f(1, 0, 0); glBegin(GL_LINES); glVertex2f(pos.x - 5, pos.y + 0); glVertex2f(pos.x + 5, pos.y + 0); glVertex2f(pos.x + 0, pos.y - 5); glVertex2f(pos.x + 0, pos.y + 5); glEnd(); scene->Render(); glfwSwapBuffers(window); } } using namespace Game; int main() { glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_SAMPLES, 8); window = glfwCreateWindow(640, 480, "Skeletal Animation", nullptr, nullptr); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mouse_callback); glfwSetCursorPosCallback(window, cursor_position_callback); glfwMakeContextCurrent(window); glewInit(); init(); glfwSwapInterval(0); double prevTime = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double current_time = glfwGetTime(); double delta = current_time - prevTime; if (delta >= 0.1) { processInput(); Update(float(delta)); Render(); prevTime = current_time; } else { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); return 0; }
27.365145
110
0.636694
HKhademian
e8d1613538e38d128d0daab9ba655f80d012d907
13,633
cpp
C++
ext/pronto-v1.1/src/nvm_manager.cpp
rvs314/Montage
d4c49e66addefe947c03ff2bd0c463ebd2c34436
[ "MIT" ]
9
2020-10-04T22:03:31.000Z
2021-10-08T01:52:57.000Z
ext/pronto-v1.1/src/nvm_manager.cpp
rvs314/Montage
d4c49e66addefe947c03ff2bd0c463ebd2c34436
[ "MIT" ]
18
2020-10-20T02:39:12.000Z
2021-08-30T00:23:32.000Z
ext/pronto-v1.1/src/nvm_manager.cpp
rvs314/Montage
d4c49e66addefe947c03ff2bd0c463ebd2c34436
[ "MIT" ]
9
2020-10-04T22:06:11.000Z
2021-02-19T17:23:17.000Z
#include <pthread.h> #include <list> #include <queue> #include "nv_factory.hpp" #include "nv_object.hpp" #include "nvm_manager.hpp" #include "nv_catalog.hpp" #include "recovery_context.hpp" #include "snapshot.hpp" using namespace std; NVManager::NVManager() { PRINT("Initializing manager object\n"); pthread_mutex_init(&_lock, NULL); pthread_mutex_init(&_ckptLock, NULL); pthread_cond_init(&_ckptCondition, NULL); /* * Reading catalog from NVM -- this will populate ex_objects * The catalog contains the superset of objects in any snapshot */ list< pair<std::string, CatalogEntry *> > ex_objects; catalog = new NVCatalog(CATALOG_FILE_NAME, ex_objects); PRINT("Finished creating/opening persistent catalog.\n"); if (ex_objects.size() == 0) return; // Prepare for recovery RecoveryContext::getInstance().setManager(this); struct timespec t1, t2; clock_gettime(CLOCK_REALTIME, &t1); // Load the latest snapshot (if any) Snapshot *snapshot = new Snapshot(PMEM_PATH); if (snapshot->lastSnapshotID() > 0) { snapshot->load(snapshot->lastSnapshotID(), this); } delete snapshot; // Prepare environment for recovery (populate objects from ex_objects) for (auto it = ex_objects.begin(); it != ex_objects.end(); ++it) { recoverObject(it->first.c_str(), it->second); } ex_objects.clear(); const size_t obj_count = objects.size(); /* * Handling unclean shutdowns * We provide support for transaction aborts here. The effect of an aborted * transaction on other objects/transactions is implemented here. */ uint64_t cflags = catalog->getFlags(); if ((cflags & CatalogFlagCleanShutdown) == 0) { PRINT("Manager: detected unclean shutdown, fixing redo-logs ...\n"); int aborted_transactions = emulateRecoveryAndFixRedoLogs(); PRINT("Manager: finished fixing redo-logs, total aborted transactions = %d\n", aborted_transactions); } /* * Creating recovery threads (one per persistent object) * We assume number of persistent objects are not much larger than * the number of CPU cores. * If that is not the case, we should partition persistent objects to * groups with no inter-class dependencies and recover partitions * one at a time. */ PRINT("Manager: recovering persistent objects ...\n"); size_t counter = 0; pthread_t *threads = (pthread_t *)malloc(sizeof(pthread_t) * obj_count); for (auto it = objects.begin(); it != objects.end(); ++it) { assert(counter < obj_count); pthread_create(&threads[counter++], NULL, recoveryWorker, it->second); } // Wait for recovery threads to return for (size_t i = 0; i < obj_count; i++) { pthread_join(threads[i], NULL); } // Cleanup environment clock_gettime(CLOCK_REALTIME, &t2); PRINT("Manager: finished recovering persistent objects!\n"); free(threads); PRINT("Manager: updating catalog flags.\n"); cflags = catalog->getFlags(); cflags = (cflags & (~CatalogFlagCleanShutdown)); // unclean shutdown catalog->setFlags(cflags); uint64_t recoveryTime = (t2.tv_sec - t1.tv_sec) * 1E9; recoveryTime += (t2.tv_nsec - t1.tv_nsec); fprintf(stdout, "Recovery Time (ms)\t%.2f\n", (double)recoveryTime / 1E6); } NVManager::~NVManager() { PRINT("Manager: updating catalog flags before terminating.\n"); uint64_t cflags = catalog->getFlags(); cflags = cflags | CatalogFlagCleanShutdown; catalog->setFlags(cflags); delete catalog; pthread_mutex_destroy(&_lock); pthread_mutex_destroy(&_ckptLock); pthread_cond_destroy(&_ckptCondition); PRINT("Destroyed manager object\n"); #ifdef DEBUG GlobalAlloc::getInstance()->report(); #endif } PersistentObject *NVManager::findRecovered(uuid_t uuid) { char uuid_str[64]; uuid_unparse(uuid, uuid_str); auto it = objects.find(uuid_str); if (it == objects.end()) return NULL; PersistentObject *object = it->second; assert(!object->assigned); object->assigned = true; return object; } void NVManager::createNew(uint64_t type_id, PersistentObject *object) { CatalogEntry *entry = catalog->add(object->getUUID(), type_id); if (object->const_args != NULL) { catalog->addConstructorArgs(entry, object->const_args, object->const_args_size); } char uuid_str[64]; uuid_unparse(object->getUUID(), uuid_str); objects.insert(pair<string, PersistentObject *>(uuid_str, object)); object->assigned = true; } void NVManager::destroy(PersistentObject *object) { assert(object->assigned); object->assigned = false; } void NVManager::recoverObject(const char *uuid_str, CatalogEntry *object) { if (objects.find(uuid_str) != objects.end()) { // Recover from snapshot PRINT("Recovering object from snapshot, uuid = %s\n", uuid_str); PersistentObject *pobj = objects.find(uuid_str)->second; assert(pobj != NULL); PersistentFactory::vTableUpdate(object->type, pobj); PRINT("Updated vTable to %p for persistent object, uuid = %s\n", (void*)(((uintptr_t*)pobj)[0]), uuid_str); pobj->recovering = true; pobj->log = Savitar_log_open(pobj->uuid); pobj->alloc = GlobalAlloc::getInstance()->findAllocator(pobj->uuid); pobj->assigned = false; } else { PRINT("Adding object to recovery queue, uuid = %s\n", uuid_str); PersistentObject *pobj = PersistentFactory::create(this, object->type, object); assert(pobj != NULL); pobj->recovering = true; pobj->last_played_commit_id = 0; objects.insert(pair<string, PersistentObject *>(uuid_str, pobj)); } } void *NVManager::recoveryWorker(void *arg) { PersistentObject *object = (PersistentObject *)arg; object->Recover(); object->recovering = false; return NULL; } PersistentObject *NVManager::findObject(string uuid_str) { auto it = objects.find(uuid_str); if (it == objects.end()) { PRINT("Unable to find object with uuid = %s\n", uuid_str.c_str()); PRINT("Total objects present: %zu\n", objects.size()); return NULL; } return it->second; } const char *NVManager::getArgumentPointer(CatalogEntry *entry) { return (const char *)catalog->catalog + entry->args_offset; } typedef struct AbortChainNode { PersistentObject *object; uint64_t log_offset; uint64_t commit_id; struct AbortChainNode *next; } AbortChainNode; typedef struct { pthread_t thread; NVManager *instance; PersistentObject *object; uint64_t max_committed_tx; list<AbortChainNode *> *abort_chains; } AbortChainBuilderArg; void *NVManager::buildAbortChains(void *arg) { NVManager *me = ((AbortChainBuilderArg *)arg)->instance; PersistentObject *object = ((AbortChainBuilderArg *)arg)->object; SavitarLog *log = object->log; priority_queue<uint64_t, vector<uint64_t>, greater<uint64_t> > min_heap; uint64_t max_committed_tx = 0; uint64_t offset = log->head; const char *data = (const char *)object->log; while (offset < log->tail) { assert(offset % CACHE_LINE_WIDTH == 0); uint64_t commit_id = *((uint64_t *)&data[offset]); offset += sizeof(uint64_t); uint64_t magic = *((uint64_t *)&data[offset]); offset += sizeof (uint64_t); uint64_t method_tag = *((uint64_t *)&data[offset]); offset += sizeof(uint64_t); if (magic != REDO_LOG_MAGIC) { // Corrupted log entry offset += CACHE_LINE_WIDTH - 3 * sizeof(uint64_t); continue; } if (commit_id != 0) { min_heap.push(commit_id); while (min_heap.top() == max_committed_tx + 1) { max_committed_tx++; min_heap.pop(); } } if ((method_tag & NESTED_TX_TAG) == 0) { assert(method_tag != 0); offset += object->Play(method_tag, (uint64_t *)&data[offset], true); // dry run offset += CACHE_LINE_WIDTH - offset % CACHE_LINE_WIDTH; continue; } /* * Nested transaction * [1] commit_id == 0: no need to follow the chain * [2] commit_id != 0: follow the chain and check if aborted */ if (commit_id == 0) { offset += CACHE_LINE_WIDTH - 3 * sizeof(uint64_t); continue; } typedef struct uuid_ptr { uuid_t uuid; } uuid_ptr; // Creating abort chain AbortChainNode *head = (AbortChainNode *)malloc(sizeof(AbortChainNode)); head->object = object; head->commit_id = commit_id; head->log_offset = offset - 3 * sizeof(uint64_t); head->next = NULL; char uuid_str[37]; uuid_unparse(((uuid_ptr *)&data[offset])->uuid, uuid_str); auto parent_it = me->objects.find(uuid_str); assert(parent_it != me->objects.end()); PersistentObject *parent = parent_it->second; uint64_t parent_offset = method_tag & (~NESTED_TX_TAG); /* * Note: we always know the log entry for parent transactions are persistent * before the child transactions, so it is safe to assume parent logs are * not corrupted (i.e., partially persisted). */ while (parent != NULL) { SavitarLog *parent_log = parent->log; uint64_t *parent_ptr = (uint64_t *)((char *)parent_log + parent_offset); uint64_t parent_commit_id = parent_ptr[0]; uint64_t parent_magic = parent_ptr[1]; if (parent_magic != REDO_LOG_MAGIC) { PRINT("Invalid magic: (uuid, commit id, offset) = (%s, %zu, %zu)\n", parent->uuid_str, parent_commit_id, parent_offset); } assert(parent_magic == REDO_LOG_MAGIC); uint64_t parent_method_tag = parent_ptr[2]; // Adding parent to the chain AbortChainNode *node = (AbortChainNode *)malloc(sizeof(AbortChainNode)); node->next = head; node->object = parent; node->log_offset = parent_offset; node->commit_id = parent_commit_id; head = node; if ((parent_method_tag & NESTED_TX_TAG) == 0) { // outer-most transaction if (parent_commit_id == 0) { // aborted transaction ((AbortChainBuilderArg *)arg)->abort_chains->push_back(head); } else { // Chain clean-up while (head != NULL) { AbortChainNode *t = head; head = head->next; free(t); } } parent = NULL; } else { uuid_unparse(((uuid_ptr *)((char *)parent_ptr + 24))->uuid, uuid_str); auto parent_it = me->objects.find(uuid_str); assert(parent_it != me->objects.end()); parent = parent_it->second; parent_offset = parent_method_tag & (~NESTED_TX_TAG); } } offset += CACHE_LINE_WIDTH - 3 * sizeof(uint64_t); } ((AbortChainBuilderArg *)arg)->max_committed_tx = max_committed_tx; return NULL; } int NVManager::emulateRecoveryAndFixRedoLogs() { size_t counter = 0; const size_t obj_count = objects.size(); AbortChainBuilderArg *builders = (AbortChainBuilderArg *)malloc(obj_count * sizeof(AbortChainBuilderArg)); PRINT("Manager: building abort chains for %zu objects.\n", obj_count); for (auto it = objects.begin(); it != objects.end(); ++it) { assert(counter < obj_count); builders[counter].instance = this; builders[counter].object = it->second; builders[counter].abort_chains = new list<AbortChainNode *>(); pthread_create(&builders[counter].thread, NULL, buildAbortChains, &builders[counter]); counter++; } // Wait for recovery threads to return for (size_t i = 0; i < obj_count; i++) { pthread_join(builders[i].thread, NULL); AbortChainNode *chain = NULL; PRINT("Manager: processing abort chain for %s (max commit = %zu)\n", builders[i].object->uuid_str, builders[i].max_committed_tx); if (!builders[i].abort_chains->empty()) { PRINT("Aborted nested transactions are not yet supported!"); } assert(builders[i].abort_chains->empty()); /* while (!builders[i].abort_chains->empty()) { PRINT("\t> Found abort chain:"); chain = builders[i].abort_chains->front(); while (chain != NULL) { // Process the abort node PRINT("\t\t> %s : (%zu, %zu)\n", chain->object->uuid_str, chain->log_offset, chain->commit_id); // TODO process chain // Cleanup AbortChainNode *t = chain; chain = chain->next; free(t); } builders[i].abort_chains->pop_front(); } */ } PRINT("Manager: finished building abort chains.\n"); // TODO free(builders); return 0; } void NVManager::registerThread(pthread_t thread, ThreadConfig *cfg) { program_threads[thread] = cfg; } void NVManager::unregisterThread(pthread_t thread) { program_threads.erase(thread); }
35.688482
86
0.611017
rvs314
e8d473761c3328e29927eddb682114201b63f940
302
cpp
C++
SimpleLearn/99.Learn/Test2.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
SimpleLearn/99.Learn/Test2.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
SimpleLearn/99.Learn/Test2.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<string> using namespace std; int Test2(void) { const int n = 9 ; for(int i=1 ; i!= n+1 ; ++i) { for(int j=1 ; j!= i+1 ; ++j) { cout << i << "*" << j << "=" << i*j << "\t"; if(! (j%10) && j) { cout << endl ; } } cout << endl ; } return 0 ; }
12.583333
47
0.427152
codeworkscn
e8d76f278c8b413083732ba9463daecbb233465e
2,991
cpp
C++
test/TestReadIterator.cpp
RPG-18/QMiniZip
aba71ec55e05e4a67e9ece81ca1aa16f825e438e
[ "MIT" ]
null
null
null
test/TestReadIterator.cpp
RPG-18/QMiniZip
aba71ec55e05e4a67e9ece81ca1aa16f825e438e
[ "MIT" ]
null
null
null
test/TestReadIterator.cpp
RPG-18/QMiniZip
aba71ec55e05e4a67e9ece81ca1aa16f825e438e
[ "MIT" ]
2
2018-05-23T14:46:30.000Z
2018-06-23T02:04:32.000Z
#include <gtest/gtest.h> #include <config.h> #include <QtCore/QDir> #include <QtCore/QDebug> #include <QtCore/QVector> #include <QtCore/QStringList> #include "ZipFile.h" #include "ZipReadIterator.h" using namespace QMiniZip; TEST(ZipReadIterator, next) { QDir dir(TEST_SOURCE_DIR); ASSERT_TRUE(dir.cd("data")); const auto archive = dir.absoluteFilePath("dataset1.zip"); ZipFile zipFile(archive); ASSERT_TRUE(zipFile.open(ZipFile::UNZIP)); ZipReadIterator zIiterator(zipFile); ASSERT_TRUE(zIiterator.toBegin()); int cnt = 1; while(zIiterator.next()) { ++cnt; } ASSERT_EQ(4, cnt); } TEST(ZipReadIterator, fileInfo) { QDir dir(TEST_SOURCE_DIR); ASSERT_TRUE(dir.cd("data")); const auto archive = dir.absoluteFilePath("dataset1.zip"); ZipFile zipFile(archive); ASSERT_TRUE(zipFile.open(ZipFile::UNZIP)); ZipReadIterator zIiterator(zipFile); ASSERT_TRUE(zIiterator.toBegin()); int cnt = 0; QStringList files; QVector<size_t> unSizes; do { const auto info = zIiterator.fileInfo(); files<<info.name(); unSizes.push_back(info.uncompressedSize()); ++cnt; }while(zIiterator.next()); ASSERT_EQ(4, cnt); const QStringList expectedFiles = {"folder1/zen2.txt", "folder1/zen1.txt", "folder3/zen4.txt", "folder2/zen3.txt"}; ASSERT_EQ(expectedFiles, files); const QVector<size_t> expectedUnSizes = {5099, 916, 1970, 1792}; ASSERT_EQ(expectedUnSizes, unSizes); } TEST(ZipReadIterator, read) { QDir dir(TEST_SOURCE_DIR); ASSERT_TRUE(dir.cd("data")); const auto archive = dir.absoluteFilePath("dataset1.zip"); ZipFile zipFile(archive); ASSERT_TRUE(zipFile.open(ZipFile::UNZIP)); ZipReadIterator zIiterator(zipFile); ASSERT_TRUE(zIiterator.toBegin()); ASSERT_TRUE(zIiterator.openCurrentFile()); QByteArray data; QByteArray buff(1024, 0); while(qint64 cnt = zIiterator.read(buff.data(), buff.size())) { if(cnt<0) { break; } data.append(buff.data(), cnt); } ASSERT_EQ(5099, data.size()); } TEST(ZipReadIterator, readAll) { QDir dir(TEST_SOURCE_DIR); ASSERT_TRUE(dir.cd("data")); const auto archive = dir.absoluteFilePath("dataset1.zip"); ZipFile zipFile(archive); ASSERT_TRUE(zipFile.open(ZipFile::UNZIP)); ZipReadIterator zIiterator(zipFile); ASSERT_TRUE(zIiterator.toBegin()); QVector<QByteArray> dataSet; do { ASSERT_TRUE(zIiterator.openCurrentFile()); dataSet.push_back(zIiterator.readAll()); ASSERT_TRUE(dataSet.back().size()>0); }while(zIiterator.next()); const QVector<int> expectedUnSizes = {5099, 916, 1970, 1792}; ASSERT_EQ(expectedUnSizes.size(), dataSet.size()); for(int i = 0; i < expectedUnSizes.size(); ++i) { ASSERT_EQ(expectedUnSizes[i], dataSet[i].size()); } }
22.320896
65
0.646272
RPG-18
e8d851c4449252672d946d6bec0cf8cefaa24526
1,306
cpp
C++
kernel/arch/x86_64/avx.cpp
heatd/Onyx
404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d
[ "MIT" ]
44
2017-02-16T20:48:09.000Z
2022-03-14T17:58:57.000Z
kernel/arch/x86_64/avx.cpp
heatd/Onyx
404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d
[ "MIT" ]
72
2017-02-16T20:22:10.000Z
2022-03-31T21:17:06.000Z
kernel/arch/x86_64/avx.cpp
heatd/Onyx
404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d
[ "MIT" ]
10
2017-04-07T19:20:14.000Z
2021-12-16T03:31:14.000Z
/* * Copyright (c) 2017 - 2021 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information * * SPDX-License-Identifier: MIT */ #include <stdint.h> #include <cpuid.h> #include <stdio.h> #include <onyx/x86/avx.h> #include <onyx/fpu.h> #include <onyx/cpu.h> #include <onyx/x86/control_regs.h> static inline void xsetbv(unsigned long r, unsigned long xcr0) { __asm__ __volatile__("xsetbv" :: "c"(r), "a"(xcr0 & 0xffffffff), "d"(xcr0 >> 32)); } static inline unsigned long xgetbv(unsigned long r) { unsigned long ret = 0; __asm__ __volatile__("xgetbv" : "=A"(ret) : "c"(r)); return ret; } extern size_t fpu_area_size; extern size_t fpu_area_alignment; void avx_init(void) { if(x86_has_cap(X86_FEATURE_XSAVE)) { x86_write_cr4(x86_read_cr4() | CR4_OSXSAVE); } if(x86_has_cap(X86_FEATURE_AVX) && x86_has_cap(X86_FEATURE_XSAVE)) { /* If it's supported, set the proper xcr0 bits */ int64_t xcr0 = 0; xcr0 |= AVX_XCR0_AVX | AVX_XCR0_FPU | AVX_XCR0_SSE; xsetbv(0, xcr0); uint32_t eax, ebx, ecx, edx; ecx = 0; if(!__get_cpuid_count(CPUID_XSTATE, 0, &eax, &ebx, &ecx, &edx)) return; fpu_area_size = ebx; fpu_area_alignment = AVX_SAVE_ALIGNMENT; avx_supported = true; } }
21.409836
83
0.696784
heatd
e8dcef6aadbf15c7a345a97f6cb187c6164a23fd
779
cpp
C++
source/src/Tensors.cpp
TatianaOvsiannikova/ostap
a005a78b4e2860ac8f4b618e94b4b563b2eddcf1
[ "BSD-3-Clause" ]
14
2017-03-24T12:38:08.000Z
2022-02-21T05:00:57.000Z
source/src/Tensors.cpp
TatianaOvsiannikova/ostap
a005a78b4e2860ac8f4b618e94b4b563b2eddcf1
[ "BSD-3-Clause" ]
10
2019-03-08T18:48:42.000Z
2022-03-22T11:59:48.000Z
source/src/Tensors.cpp
TatianaOvsiannikova/ostap
a005a78b4e2860ac8f4b618e94b4b563b2eddcf1
[ "BSD-3-Clause" ]
11
2017-03-23T15:29:58.000Z
2022-02-21T05:03:57.000Z
// ============================================================================ // Include files // ============================================================================ // LoKi // ============================================================================ #include "Ostap/Tensors.h" // ============================================================================ /** @file * Implementation file for classes from namespace Ostap::Math::Tensors * @author Vanya BELYAEV Ivan.Belyaev@itep.ru * @date 2008-07-26 */ // ============================================================================ // ============================================================================ // The END // ============================================================================
41
79
0.192555
TatianaOvsiannikova
e8e050b4cda28176096b6e8f3f9bdaff02d15143
8,011
cpp
C++
tools/ctmconv.cpp
SaeedTaghavi/OpenCTM
d6c1138eb39632244e6b5d133a100f431c5c5082
[ "Zlib" ]
80
2015-04-08T08:48:06.000Z
2022-03-23T10:36:55.000Z
tools/ctmconv.cpp
rasata/OpenCTM
243a343bd23bbeef8731f06ed91e3996604e1af4
[ "Zlib" ]
7
2015-09-25T21:11:59.000Z
2021-11-09T00:22:18.000Z
tools/ctmconv.cpp
rasata/OpenCTM
243a343bd23bbeef8731f06ed91e3996604e1af4
[ "Zlib" ]
36
2015-05-21T16:34:42.000Z
2021-12-29T06:41:52.000Z
//----------------------------------------------------------------------------- // Product: OpenCTM tools // File: ctmconv.cpp // Description: 3D file format conversion tool. The program can be used to // convert various 3D file formats to and from the OpenCTM file // format, and also for conversion between other formats. //----------------------------------------------------------------------------- // Copyright (c) 2009-2010 Marcus Geelnard // // 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 acknowledgment 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 <stdexcept> #include <vector> #include <iostream> #include <list> #include <string> #include <cctype> #include "systimer.h" #include "convoptions.h" #include "mesh.h" #include "meshio.h" using namespace std; //----------------------------------------------------------------------------- // PreProcessMesh() //----------------------------------------------------------------------------- static void PreProcessMesh(Mesh &aMesh, Options &aOptions) { // Nothing to do? if((aOptions.mScale == 1.0f) && (aOptions.mUpAxis == uaZ) && (!aOptions.mFlipTriangles) && (!aOptions.mCalcNormals)) return; // Create 3x3 transformation matrices for the vertices and the normals Vector3 vX, vY, vZ; Vector3 nX, nY, nZ; switch(aOptions.mUpAxis) { case uaX: nX = Vector3(0.0f, 0.0f, 1.0f); nY = Vector3(0.0f, 1.0f, 0.0f); nZ = Vector3(-1.0f, 0.0f, 0.0f); break; case uaY: nX = Vector3(1.0f, 0.0f, 0.0f); nY = Vector3(0.0f, 0.0f, 1.0f); nZ = Vector3(0.0f, -1.0f, 0.0f); break; case uaZ: nX = Vector3(1.0f, 0.0f, 0.0f); nY = Vector3(0.0f, 1.0f, 0.0f); nZ = Vector3(0.0f, 0.0f, 1.0f); break; case uaNX: nX = Vector3(0.0f, 0.0f, -1.0f); nY = Vector3(0.0f, 1.0f, 0.0f); nZ = Vector3(1.0f, 0.0f, 0.0f); break; case uaNY: nX = Vector3(1.0f, 0.0f, 0.0f); nY = Vector3(0.0f, 0.0f, -1.0f); nZ = Vector3(0.0f, 1.0f, 0.0f); break; case uaNZ: nX = Vector3(-1.0f, 0.0f, 0.0f); nY = Vector3(0.0f, 1.0f, 0.0f); nZ = Vector3(0.0f, 0.0f, -1.0f); break; } vX = nX * aOptions.mScale; vY = nY * aOptions.mScale; vZ = nZ * aOptions.mScale; cout << "Processing... " << flush; SysTimer timer; timer.Push(); // Update all vertex coordinates for(CTMuint i = 0; i < aMesh.mVertices.size(); ++ i) aMesh.mVertices[i] = vX * aMesh.mVertices[i].x + vY * aMesh.mVertices[i].y + vZ * aMesh.mVertices[i].z; // Update all normals if(aMesh.HasNormals() && !aOptions.mNoNormals) { for(CTMuint i = 0; i < aMesh.mNormals.size(); ++ i) aMesh.mNormals[i] = nX * aMesh.mNormals[i].x + nY * aMesh.mNormals[i].y + nZ * aMesh.mNormals[i].z; } // Flip trianlges? if(aOptions.mFlipTriangles) { CTMuint triCount = aMesh.mIndices.size() / 3; for(CTMuint i = 0; i < triCount; ++ i) { CTMuint tmp = aMesh.mIndices[i * 3]; aMesh.mIndices[i * 3] = aMesh.mIndices[i * 3 + 1]; aMesh.mIndices[i * 3 + 1] = tmp; } } // Calculate normals? if((!aOptions.mNoNormals) && aOptions.mCalcNormals && (!aMesh.HasNormals())) aMesh.CalculateNormals(); double dt = timer.PopDelta(); cout << 1000.0 * dt << " ms" << endl; } //----------------------------------------------------------------------------- // main() //----------------------------------------------------------------------------- int main(int argc, char ** argv) { // Get file names and options Options opt; string inFile; string outFile; try { if(argc < 3) throw runtime_error("Too few arguments."); inFile = string(argv[1]); outFile = string(argv[2]); opt.GetFromArgs(argc, argv, 3); } catch(exception &e) { cout << "Error: " << e.what() << endl << endl; cout << "Usage: " << argv[0] << " infile outfile [options]" << endl << endl; cout << "Options:" << endl; cout << endl << " Data manipulation (all formats)" << endl; cout << " --scale arg Scale the mesh by a scalar factor." << endl; cout << " --upaxis arg Set up axis (X, Y, Z, -X, -Y, -Z). If != Z, the mesh will" << endl; cout << " be flipped." << endl; cout << " --flip Flip triangle orientation." << endl; cout << " --calc-normals If the source file does not contain any normals, calculate" << endl; cout << " them." << endl; cout << " --no-normals Do not export normals." << endl; cout << " --no-texcoords Do not export texture coordinates." << endl; cout << " --no-colors Do not export vertex colors." << endl; cout << endl << " OpenCTM output" << endl; cout << " --method arg Select compression method (RAW, MG1, MG2)" << endl; cout << " --level arg Set the compression level (0 - 9)" << endl; cout << endl << " OpenCTM MG2 method" << endl; cout << " --vprec arg Set vertex precision" << endl; cout << " --vprecrel arg Set vertex precision, relative method" << endl; cout << " --nprec arg Set normal precision" << endl; cout << " --tprec arg Set texture map precision" << endl; cout << " --cprec arg Set color precision" << endl; cout << " --aprec arg Set attributes precision" << endl; cout << endl << " Miscellaneous" << endl; cout << " --comment arg Set the file comment (default is to use the comment" << endl; cout << " from the input file, if any)." << endl; cout << " --texfile arg Set the texture file name reference for the texture" << endl; cout << " (default is to use the texture file name reference" << endl; cout << " from the input file, if any)." << endl; // Show supported formats cout << endl << "Supported file formats:" << endl << endl; list<string> formatList; SupportedFormats(formatList); for(list<string>::iterator i = formatList.begin(); i != formatList.end(); ++ i) cout << " " << (*i) << endl; cout << endl; return 0; } try { // Define mesh Mesh mesh; // Create a timer instance SysTimer timer; double dt; // Load input file cout << "Loading " << inFile << "... " << flush; timer.Push(); ImportMesh(inFile.c_str(), &mesh); dt = timer.PopDelta(); cout << 1000.0 * dt << " ms" << endl; // Manipulate the mesh PreProcessMesh(mesh, opt); // Override comment? if(opt.mComment.size() > 0) mesh.mComment = opt.mComment; // Override texture file name? if(opt.mTexFileName.size() > 0) mesh.mTexFileName = opt.mTexFileName; // Save output file cout << "Saving " << outFile << "... " << flush; timer.Push(); ExportMesh(outFile.c_str(), &mesh, opt); dt = timer.PopDelta(); cout << 1000.0 * dt << " ms" << endl; } catch(exception &e) { cout << "Error: " << e.what() << endl; return 1; } return 0; }
33.801688
99
0.536887
SaeedTaghavi
e8e0b1207f2100452fb7a6b11af67b52b01d04d0
480
hpp
C++
llarp/exit/policy.hpp
killvxk/loki-network
3715c28616fac132f622a80d5d0e8e794166315a
[ "Zlib" ]
1
2019-05-01T11:06:52.000Z
2019-05-01T11:06:52.000Z
llarp/exit/policy.hpp
majestrate/m
8b83651c8d0dddb03ca016bf0645e23514e9e41d
[ "Zlib" ]
null
null
null
llarp/exit/policy.hpp
majestrate/m
8b83651c8d0dddb03ca016bf0645e23514e9e41d
[ "Zlib" ]
1
2019-04-21T17:53:56.000Z
2019-04-21T17:53:56.000Z
#ifndef LLARP_EXIT_POLICY_HPP #define LLARP_EXIT_POLICY_HPP #include <util/bencode.hpp> namespace llarp { namespace exit { struct Policy final : public llarp::IBEncodeMessage { ~Policy(); uint64_t proto; uint64_t port; uint64_t drop; bool DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* val) override; bool BEncode(llarp_buffer_t* buf) const override; }; } // namespace exit } // namespace llarp #endif
17.142857
71
0.664583
killvxk
e8e1fb670c240b9729731cfaa920aaa970c460eb
227
cpp
C++
Engine/Source/Runtime/Engine/Private/MatineeAnimInterface.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Engine/Private/MatineeAnimInterface.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Engine/Private/MatineeAnimInterface.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Matinee/MatineeAnimInterface.h" UMatineeAnimInterface::UMatineeAnimInterface(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { }
25.222222
89
0.814978
windystrife
e8e38af016bc84b4fc3e2d4aa970e8b440599a8e
339
cc
C++
project/src/package_factory.cc
WileyBui/Package-Delivery-System
dd7bb15366623ddeb86a305cc8dfa50ed94f0cad
[ "MIT" ]
null
null
null
project/src/package_factory.cc
WileyBui/Package-Delivery-System
dd7bb15366623ddeb86a305cc8dfa50ed94f0cad
[ "MIT" ]
null
null
null
project/src/package_factory.cc
WileyBui/Package-Delivery-System
dd7bb15366623ddeb86a305cc8dfa50ed94f0cad
[ "MIT" ]
null
null
null
#include "entity_base.h" #include "json_helper.h" #include "package_factory.h" #include "package.h" namespace csci3081 { IEntity* PackageFactory::CreateEntity(const picojson::object& val){ if (JsonHelper::GetString(val, "type") == "package") { return new Package(val); } return NULL; } } // end of namespace csci2081
22.6
67
0.690265
WileyBui
e8e907277d26798fc44242b4d2f30dde38835985
12,350
cpp
C++
UnitTest/Basic.cpp
akfreed/CppSocketsXPlatform
06be7da54e4ac29ac87c6e68626bbc3226217f4e
[ "Apache-2.0" ]
null
null
null
UnitTest/Basic.cpp
akfreed/CppSocketsXPlatform
06be7da54e4ac29ac87c6e68626bbc3226217f4e
[ "Apache-2.0" ]
null
null
null
UnitTest/Basic.cpp
akfreed/CppSocketsXPlatform
06be7da54e4ac29ac87c6e68626bbc3226217f4e
[ "Apache-2.0" ]
null
null
null
// ================================================================== // Copyright 2018 Alexander K. Freed // // 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. // ================================================================== // Contains the basic tests. #include "TcpListener.h" #include "TcpSocket.h" #include "UdpSocket.h" #include <cstring> #include <string> #include <vector> #include <array> #include "TestReport.h" #include "UnitTestMain.h" //============================================================================ // tests template <typename SOCKET> TestReport SendRecvChar(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvChar", "Sends and receives a char."); char sentData = 'f'; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(sentData)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } char c; if (!receiver.Read(c)) { report.ResultNotes = "Read failed."; return report; } if (c != sentData) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvBool(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvBool", "Sends and receives true and false."); if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(false)) { report.ResultNotes = "Write failed."; return report; } if (!sender.Write(true)) { report.ResultNotes = "Write failed."; return report; } if (!sender.Write(true)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } bool b; if (!receiver.Read(b)) { report.ResultNotes = "Read failed."; return report; } if (b != false) { report.ResultNotes = "Read received wrong data."; return report; } if (!receiver.Read(b)) { report.ResultNotes = "Read failed."; return report; } if (b != true) { report.ResultNotes = "Read received wrong data."; return report; } // this test is not necessary char c; if (!receiver.Read(c)) { report.ResultNotes = "Read failed."; return report; } if (c != 1) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvInt(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvInt", "Sends and receives an int32."); int sentData = -20; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(sentData)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } int i; if (!receiver.Read(i)) { report.ResultNotes = "Read failed."; return report; } if (i != sentData) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvDouble(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvDouble", "Sends and receives a double."); double sentData = 5.1234567890; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(sentData)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } double d; if (!receiver.Read(d)) { report.ResultNotes = "Read failed."; return report; } if (d != sentData) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvBuf(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvBuf", "Sends and receives a char buffer."); char sentData[6] = { 1, 2, 3, 4, 5, 6 }; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(sentData, 5)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } char buf[6] = { 0, 0, 0, 0, 0 }; std::array<char, 6> expected = { 1, 2, 3, 4, 5, 0 }; if (!receiver.Read(buf, 5)) { report.ResultNotes = "Read failed."; return report; } if (!bufferMatches(buf, expected, 5)) { report.ResultNotes = "Read received wrong data."; return report; } if (!sender.Write(sentData + 3, 3)) { report.ResultNotes = "Write failed."; return report; } if (!sender.Write(sentData, 3)) { report.ResultNotes = "Write failed."; return report; } expected = { 4, 5, 3, 4, 5, 0 }; if (!receiver.Read(buf, 2)) { report.ResultNotes = "Read failed."; return report; } expected = { 6, 1, 2, 3, 5, 0 }; if (!receiver.Read(buf, 4)) { report.ResultNotes = "Read failed."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvCharString(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvCharString", "Sends and receives a char string."); char s[101] = "Hello, World!"; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.WriteString(s)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } char msg[101]; memset(msg, 0xFF, 101); if (!receiver.ReadString(msg, 101)) { report.ResultNotes = "Read failed."; return report; } if (strcmp(s, msg) != 0) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //============================================================================ // Test Basic Main TestReport TestBasic() { TestReport report("RunBasic", "Runs basic read/write tests."); TestReport result; TcpSocket senderTcp, receiverTcp; result = SelfConnect("11111", senderTcp, receiverTcp); report.SubTests.push_back(result); bool assumptions = result.Passed; result = SendRecvChar(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvBool(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvInt(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvDouble(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvBuf(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvCharString(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); UdpSocket senderUdp, receiverUdp; result = SelfConnect(11111, senderUdp, receiverUdp); report.SubTests.push_back(result); assumptions = result.Passed; result = SendRecvBuf(assumptions, senderUdp, receiverUdp); report.SubTests.push_back(result); // set top-level report report.Passed = true; for (auto& subtest : report.SubTests) { if (!subtest.Passed) { report.Passed = false; break; } } return report; }
23.434535
85
0.570202
akfreed
e8ecdaba33e0129890adb674a80dc6aedd1a59a4
564
hpp
C++
src/breakout/ball_object.hpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/breakout/ball_object.hpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/breakout/ball_object.hpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
#if !defined(BALL_OBJECT_H) #define BALL_OBJECT_H #include "./game_object.hpp" namespace breakout { class BallObject : public GameObject { public: // ball state float Radius; bool Stuck; BallObject(); BallObject(glm::vec2 pos, float radius, glm::vec2 velocity, Texture2D sprite); ~BallObject(); glm::vec2 Move(float dt, unsigned int windowWidth); void Reset(glm::vec2 pos, glm::vec2 velocity); private: /* data */ }; } // namespace breakout #endif // BALL_OBJECT_H
19.448276
86
0.613475
clsrfish
e8ef2e7dfc0e4b9073b3f91f0947ba70037b8eff
7,739
cc
C++
src/metrics_filter_interpreter.cc
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
src/metrics_filter_interpreter.cc
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
src/metrics_filter_interpreter.cc
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2013 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gestures/include/metrics_filter_interpreter.h" #include <cmath> #include "gestures/include/filter_interpreter.h" #include "gestures/include/finger_metrics.h" #include "gestures/include/gestures.h" #include "gestures/include/logging.h" #include "gestures/include/prop_registry.h" #include "gestures/include/tracer.h" #include "gestures/include/util.h" namespace gestures { MetricsFilterInterpreter::MetricsFilterInterpreter( PropRegistry* prop_reg, Interpreter* next, Tracer* tracer, GestureInterpreterDeviceClass devclass) : FilterInterpreter(NULL, next, tracer, false), mstate_mm_(kMaxFingers * MState::MaxHistorySize()), history_mm_(kMaxFingers), devclass_(devclass), mouse_movement_session_index_(0), mouse_movement_current_session_length(0), mouse_movement_current_session_start(0), mouse_movement_current_session_last(0), mouse_movement_current_session_distance(0), noisy_ground_distance_threshold_(prop_reg, "Metrics Noisy Ground Distance", 10.0), noisy_ground_time_threshold_(prop_reg, "Metrics Noisy Ground Time", 0.1), mouse_moving_time_threshold_(prop_reg, "Metrics Mouse Moving Time", 0.05), mouse_control_warmup_sessions_(prop_reg, "Metrics Mouse Warmup Session", 100) { InitName(); } void MetricsFilterInterpreter::SyncInterpretImpl(HardwareState* hwstate, stime_t* timeout) { if (devclass_ == GESTURES_DEVCLASS_TOUCHPAD) { // Right now, we only want to update finger states for built-in touchpads // because all the generated metrics gestures would be put under each // platform's hat on the Chrome UMA dashboard. If we send metrics gestures // (e.g. noisy ground instances) for external peripherals (e.g. multi-touch // mice), they would be mistaken as from the platform's touchpad and thus // results in over-counting. // // TODO(sheckylin): Don't send metric gestures for external touchpads // either. // TODO(sheckylin): Track finger related metrics for external peripherals // as well after gaining access to the UMA log. UpdateFingerState(*hwstate); } else if (devclass_ == GESTURES_DEVCLASS_MOUSE || devclass_ == GESTURES_DEVCLASS_MULTITOUCH_MOUSE) { UpdateMouseMovementState(*hwstate); } next_->SyncInterpret(hwstate, timeout); } template <class StateType, class DataType> void MetricsFilterInterpreter::AddNewStateToBuffer( MemoryManagedList<StateType>* history, const DataType& data, const HardwareState& hwstate) { // The history buffer is already full, pop one if (history->size() == StateType::MaxHistorySize()) history->DeleteFront(); // Push the new finger state to the back of buffer StateType* current = history->PushNewEltBack(); if (!current) { Err("MetricsFilterInterpreter buffer out of space"); return; } current->Init(data, hwstate); } void MetricsFilterInterpreter::UpdateMouseMovementState( const HardwareState& hwstate) { // Skip finger-only hardware states for multi-touch mice. if (hwstate.rel_x == 0 && hwstate.rel_y == 0) return; // If the last movement is too long ago, we consider the history // an independent session. Report statistic for it and start a new // one. if (mouse_movement_current_session_length >= 1 && (hwstate.timestamp - mouse_movement_current_session_last > mouse_moving_time_threshold_.val_)) { // We skip the first a few sessions right after the user starts using the // mouse because they tend to be more noisy. if (mouse_movement_session_index_ >= mouse_control_warmup_sessions_.val_) ReportMouseStatistics(); mouse_movement_current_session_length = 0; mouse_movement_current_session_distance = 0; ++mouse_movement_session_index_; } // We skip the movement of the first event because there is no way to tell // the start time of it. if (!mouse_movement_current_session_length) { mouse_movement_current_session_start = hwstate.timestamp; } else { mouse_movement_current_session_distance += sqrtf(hwstate.rel_x * hwstate.rel_x + hwstate.rel_y * hwstate.rel_y); } mouse_movement_current_session_last = hwstate.timestamp; ++mouse_movement_current_session_length; } void MetricsFilterInterpreter::ReportMouseStatistics() { // At least 2 samples are needed to compute delta t. if (mouse_movement_current_session_length == 1) return; // Compute the average speed. stime_t session_time = mouse_movement_current_session_last - mouse_movement_current_session_start; double avg_speed = mouse_movement_current_session_distance / session_time; // Send the metrics gesture. ProduceGesture(Gesture(kGestureMetrics, mouse_movement_current_session_start, mouse_movement_current_session_last, kGestureMetricsTypeMouseMovement, avg_speed, session_time)); } void MetricsFilterInterpreter::UpdateFingerState( const HardwareState& hwstate) { FingerHistoryMap removed; RemoveMissingIdsFromMap(&histories_, hwstate, &removed); for (FingerHistoryMap::const_iterator it = removed.begin(); it != removed.end(); ++it) { it->second->DeleteAll(); history_mm_.Free(it->second); } FingerState *fs = hwstate.fingers; for (short i = 0; i < hwstate.finger_cnt; i++) { FingerHistory* hp; // Update the map if the contact is new if (!MapContainsKey(histories_, fs[i].tracking_id)) { hp = history_mm_.Allocate(); if (!hp) { Err("FingerHistory out of space"); continue; } hp->Init(&mstate_mm_); histories_[fs[i].tracking_id] = hp; } else { hp = histories_[fs[i].tracking_id]; } // Check if the finger history contains interesting patterns AddNewStateToBuffer(hp, fs[i], hwstate); DetectNoisyGround(hp); } } bool MetricsFilterInterpreter::DetectNoisyGround( const FingerHistory* history) { MState* current = history->Tail(); size_t n_samples = history->size(); // Noise pattern takes 3 samples if (n_samples < 3) return false; MState* past_1 = current->prev_; MState* past_2 = past_1->prev_; // Noise pattern needs to happen in a short period of time if(current->timestamp - past_2->timestamp > noisy_ground_time_threshold_.val_) { return false; } // vec[when][x,y] float vec[2][2]; vec[0][0] = current->data.position_x - past_1->data.position_x; vec[0][1] = current->data.position_y - past_1->data.position_y; vec[1][0] = past_1->data.position_x - past_2->data.position_x; vec[1][1] = past_1->data.position_y - past_2->data.position_y; const float thr = noisy_ground_distance_threshold_.val_; // We dictate the noise pattern as two consecutive big moves in // opposite directions in either X or Y for (size_t i = 0; i < arraysize(vec[0]); i++) if ((vec[0][i] < -thr && vec[1][i] > thr) || (vec[0][i] > thr && vec[1][i] < -thr)) { ProduceGesture(Gesture(kGestureMetrics, past_2->timestamp, current->timestamp, kGestureMetricsTypeNoisyGround, vec[0][i], vec[1][i])); return true; } return false; } } // namespace gestures
37.206731
79
0.68032
mxzeng
e8f0448702ac73515827890272e5aa25ccd4980b
12,860
cpp
C++
core/cc/scratch_allocator_test.cpp
cdotstout/gapid
a729b0ca72b2a9fffa208577578725345695ed72
[ "Apache-2.0" ]
1
2021-02-26T16:08:00.000Z
2021-02-26T16:08:00.000Z
core/cc/scratch_allocator_test.cpp
cdotstout/gapid
a729b0ca72b2a9fffa208577578725345695ed72
[ "Apache-2.0" ]
25
2017-04-25T20:39:25.000Z
2018-06-14T17:10:48.000Z
core/cc/scratch_allocator_test.cpp
cdotstout/gapid
a729b0ca72b2a9fffa208577578725345695ed72
[ "Apache-2.0" ]
1
2017-06-27T02:17:50.000Z
2017-06-27T02:17:50.000Z
/* * Copyright (C) 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "scratch_allocator.h" #include <functional> #include <memory> #include <tuple> #include <unordered_map> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> namespace core { namespace test { namespace { enum Type { TypeA, TypeB, TypeC }; struct I { virtual Type getType() = 0; }; struct A : public I { Type getType() override { return TypeA; } }; struct B : public I { Type getType() override { return TypeB; } }; struct C : public I { Type getType() override { return TypeC; } }; } // anonymous namespace // A testing class to test the ScratchAllocator. It provides the buffer // creating and releasing functions which are suppposed to be used to test // scratch allocators. class ScratchAllocatorTestBase : public ::testing::Test { public: ScratchAllocatorTestBase() : mCreatedBuffers() , mLastCreatedBufferBase(nullptr) , mLastCreatedBufferEnd(nullptr) {} // A mock buffer creating function. Returns a tuple of two: 1) a pointer to // a buffer aligned to the given alignment value, 2) the size of the buffer // starting from the return buffer pointer. std::tuple<uint8_t*, size_t> createBuffer(size_t request_size, size_t min_heap_buffer_size, size_t alignment) { size_t size = request_size > min_heap_buffer_size ? request_size : min_heap_buffer_size; auto buffer = std::unique_ptr<std::vector<uint8_t>>( new std::vector<uint8_t>(size, 0)); // Adjust the created buffer to fit the alignment. buffer->reserve(size + alignment); uintptr_t p = reinterpret_cast<uintptr_t>(buffer->data()); if (uintptr_t o = p % alignment) { p += alignment - o; buffer->insert(buffer->end(), alignment - o, 0); } mLastCreatedBufferBase = reinterpret_cast<uint8_t*>(p); mLastCreatedBufferEnd = &*buffer->end(); mCreatedBuffers[mLastCreatedBufferBase] = std::move(buffer); EXPECT_EQ(0, p % alignment) << "createBuffer: The buffer pointer to be " "is not aligned to the alignment value:" << alignment; return std::make_tuple(mLastCreatedBufferBase, size); } // A mock buffer releasing function. void freeBuffer(uint8_t* buffer) { EXPECT_EQ(1, mCreatedBuffers.count(buffer)); mCreatedBuffers.erase(buffer); } // Bookkeeping of created functions. std::unordered_map<uint8_t*, std::unique_ptr<std::vector<uint8_t>>> mCreatedBuffers; // The base address of the last created buffer. uint8_t* mLastCreatedBufferBase; // The end address of the last created buffer. uint8_t* mLastCreatedBufferEnd; }; // Templated tests. template <typename Allocator> class ScratchAllocatorTest : public ScratchAllocatorTestBase {}; namespace { // A derived class template from the test target: ScratchAllocator. It exposes // the internal members and functions for tests. template <size_t stack_capacity> class ScratchAllocatorForTest : public ScratchAllocator<stack_capacity> { public: using BufferHeader = typename ScratchAllocator<stack_capacity>::BufferHeader; // Constructs a scratch allocator with a custom alignment for the // internally created buffers for tests. The underlying buffer creating and // releasing functions are provided by the given test instance. ScratchAllocatorForTest(size_t heap_buffer_size, ScratchAllocatorTestBase* test, size_t buffer_alignment = alignof(BufferHeader)) : ScratchAllocator<stack_capacity>( [test, heap_buffer_size, buffer_alignment](size_t size) { return test->createBuffer(size, heap_buffer_size, buffer_alignment); }, [test](uint8_t* buffer) { return test->freeBuffer(buffer); }) { this->mUsableStackBufferSize = this->mStackBufferHeader->end - this->mStackBufferHeader->head; } // Delegates the internal allocation buffer initialization function so that // we can test it. static BufferHeader* initializeAllocationBuffer(uint8_t* buffer, size_t size) { return ScratchAllocator<stack_capacity>::initializeAllocationBuffer( buffer, size); } // Delegates the internal try-to-allocate function so that we can test it. static uint8_t* tryAllocateOnBuffer(size_t size, size_t alignment, BufferHeader* buffer) { return ScratchAllocator<stack_capacity>::tryAllocateOnBuffer( size, alignment, buffer); } // Returns the first buffer (aka. stack buffer) header. BufferHeader* getStackBufferHeader() { return this->mStackBufferHeader; }; // The usable memory in bytes of the stack buffer. size_t mUsableStackBufferSize; }; } // anonymous namespace TYPED_TEST_CASE_P(ScratchAllocatorTest); TYPED_TEST_P(ScratchAllocatorTest, AlignmentOnStackBuffer) { // Tests whether the allocator handles the alignment on its stack buffer // correctly. Note that when the stack buffer size is too small, this test // may be allocating on the heap buffers instead of stack buffer. size_t alignments[] = {1, 2, 4, 8, 16, 8, 4, 2, 1}; size_t sizes[] = {1, 2, 4, 8, 16}; TypeParam allocator(1, this); for (size_t a : alignments) { for (size_t s : sizes) { uintptr_t ptr = reinterpret_cast<uintptr_t>(allocator.template allocate(s, a)); EXPECT_EQ(0, ptr % a) << "allocation size: " << s << ", " << "alignment: " << a; } } } TYPED_TEST_P(ScratchAllocatorTest, AlignmentOnHeapBuffer) { // Tests whether the allocator handles the alignment on its heap buffers // correctly. size_t alloc_alignments[] = {1, 2, 4, 8, 16, 8, 4, 2, 1}; size_t alloc_sizes[] = {1, 2, 4, 8, 16}; size_t buf_alignments[] = {1, 3, 5, 7, 17}; for (size_t buf_a : buf_alignments) { TypeParam allocator(1, this, buf_a); // Fill up the stack buffer so that we always test on the heap buffer. allocator.allocate(allocator.mUsableStackBufferSize, 1); for (size_t a : alloc_alignments) { for (size_t s : alloc_sizes) { uintptr_t ptr = reinterpret_cast<uintptr_t>( allocator.template allocate(s, a)); EXPECT_EQ(0, ptr % a) << "allocation size: " << s << ", " << "alignment: " << a; } } } } TYPED_TEST_P(ScratchAllocatorTest, CreateInternalBuffers) { // Tests on an allocator whose minimal heap buffer size is only 1 byte, so // that once the stack buffer is full, any allocation request with size // greater than 1 results into new a buffer. TypeParam allocator(1, this); // Fill up the the first buffer which should be a stack buffer. void* ptr = allocator.template allocate(allocator.mUsableStackBufferSize, 1); EXPECT_EQ(0, this->mCreatedBuffers.size()); // From now on, allocate() should trigger the creation of new internal // buffers. for (size_t i = 0; i < 10; i++) { void* ptr = allocator.template allocate(100, 1); EXPECT_NE(0, this->mCreatedBuffers.size()); // ptr should be in the range of the created buffer. EXPECT_TRUE(ptr > this->mLastCreatedBufferBase); EXPECT_TRUE(ptr < this->mLastCreatedBufferEnd); } } TYPED_TEST_P(ScratchAllocatorTest, FreeInternalBuffers) { // Tests that the allocator is able to release its internal buffers when it // goes out of scope. size_t buf_alignments[] = {1, 2, 4, 8, 16, 3, 5, 7, 11, 13, 17}; for (size_t buf_a : buf_alignments) { TypeParam allocator(1, this, buf_a); allocator.template allocate(allocator.mUsableStackBufferSize + 1, 1); allocator.template allocate(allocator.mUsableStackBufferSize + 1, 1); allocator.template allocate(allocator.mUsableStackBufferSize + 1, 1); EXPECT_EQ(3, this->mCreatedBuffers.size()); } // All the buffers should be erased by now. EXPECT_EQ(0, this->mCreatedBuffers.size()); } TYPED_TEST_P(ScratchAllocatorTest, Reset) { // Tests that function reset() does reset the stack buffer and releases // all the heap buffers. TypeParam allocator(1024, this, 17 /* bad internal buffer alignment */); void* first = allocator.template allocate(1, 1); EXPECT_EQ(0, this->mCreatedBuffers.size()); // The stack buffer should has been reset, a same allocation request should // return a same pointer. allocator.template reset(); EXPECT_EQ(first, allocator.template allocate(1, 1)); // No heap buffer should has been created by now. EXPECT_EQ(0, this->mCreatedBuffers.size()); allocator.template allocate(allocator.mUsableStackBufferSize + 1, 1); EXPECT_EQ(1, this->mCreatedBuffers.size()); allocator.template reset(); EXPECT_EQ(0, this->mCreatedBuffers.size()); } TYPED_TEST_P(ScratchAllocatorTest, Create) { TypeParam allocator(1024, this); // Test the stack buffer first. auto* base = allocator.template create<char>(1); allocator.template reset(); auto* a = allocator.template create<char>(1); EXPECT_EQ(base, a); // Resets then tests on the new created buffers. allocator.reset(); allocator.allocate(allocator.mUsableStackBufferSize, 1); int* b = allocator.template create<int>(1); int* c = allocator.template create<int>(2); int* d = allocator.template create<int>(3); EXPECT_EQ(b + 1, c); EXPECT_EQ(d, c + 2); EXPECT_TRUE(reinterpret_cast<uint8_t*>(b) > this->mLastCreatedBufferBase); EXPECT_TRUE(reinterpret_cast<uint8_t*>(d) < this->mLastCreatedBufferEnd); } // Tests function make. TYPED_TEST_P(ScratchAllocatorTest, Make) { TypeParam allocator(0x1000, this); size_t* made_ptrs[100]; for (size_t i = 0; i < 100; i++) { made_ptrs[i] = allocator.template make<size_t>(i); } for (size_t i = 0; i < 100; i++) { EXPECT_EQ(i, *made_ptrs[i]); } } // Tests function vector. TYPED_TEST_P(ScratchAllocatorTest, Vector) { TypeParam allocator(0x1000, this); auto v = allocator.template vector<I*>(3); for (auto e : v) { FAIL() << "Empty vector should not interate."; } v.append(allocator.template create<A>()); v.append(allocator.template create<B>()); v.append(allocator.template create<C>()); EXPECT_EQ(TypeA, v[0]->getType()); EXPECT_EQ(TypeB, v[1]->getType()); EXPECT_EQ(TypeC, v[2]->getType()); Type expected[3] = {TypeA, TypeB, TypeC}; int i = 0; for (auto c : v) { EXPECT_EQ(expected[i++], c->getType()); } } // Tests function map. TYPED_TEST_P(ScratchAllocatorTest, Map) { TypeParam allocator(0x1000, this); auto m = allocator.template map<int, I*>(3); for (auto e : m) { FAIL() << "Empty map should not interate."; } m.set(2, allocator.template create<A>()); m.set(4, allocator.template create<B>()); m.set(8, allocator.template create<C>()); int keys[3] = {2, 4, 8}; Type types[3] = {TypeA, TypeB, TypeC}; int i = 0; for (auto e : m) { EXPECT_EQ(keys[i], e.key); EXPECT_EQ(types[i], e.value->getType()); i++; } } REGISTER_TYPED_TEST_CASE_P(ScratchAllocatorTest, Reset, AlignmentOnStackBuffer, AlignmentOnHeapBuffer, CreateInternalBuffers, FreeInternalBuffers, Create, Make, Vector, Map); template <size_t stack_capacity> using SA = ScratchAllocatorForTest<stack_capacity>; // Implementations of stack scratch allocator to test. using AllocatorImplementations = ::testing::Types<SA<1>, SA<5>, SA<1024>>; INSTANTIATE_TYPED_TEST_CASE_P(ScratchAllocatorTest, ScratchAllocatorTest, AllocatorImplementations); } // namespace test } // namespace core
37.935103
80
0.646345
cdotstout
e8f1e771a41dd05d5ac23c8f7ba8886f641d2b04
344
hpp
C++
src/searches/benchmarks.hpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
src/searches/benchmarks.hpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
src/searches/benchmarks.hpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
#ifndef REMAINDERTREE_SRC_SEARCHES_BENCHMARKS_H_ #define REMAINDERTREE_SRC_SEARCHES_BENCHMARKS_H_ //std::function< std::vector<bool> (long N)> remember this is what is being passed in! #include <vector> std::vector<bool> constant_slow(long); std::vector<bool> random_zz(long, long, long); #endif //REMAINDERTREE_SRC_SEARCHES_BENCHMARKS_H_
26.461538
86
0.802326
adienes
e8f5f70763191c62774bcfa9b7cf1762cfdefa57
3,473
cpp
C++
src/commandline.cpp
flopp/gol-sat
40a92d6c9e32bcdaf2d83b8f317f8be955e378fb
[ "MIT" ]
1
2020-01-10T23:08:00.000Z
2020-01-10T23:08:00.000Z
src/commandline.cpp
flopp/gol-sat
40a92d6c9e32bcdaf2d83b8f317f8be955e378fb
[ "MIT" ]
1
2020-01-12T10:27:36.000Z
2020-01-12T10:27:36.000Z
src/commandline.cpp
flopp/gol-sat
40a92d6c9e32bcdaf2d83b8f317f8be955e378fb
[ "MIT" ]
null
null
null
/******************************************************************************* * gol-sat * * Copyright (c) 2015 Florian Pigorsch * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ #include "commandline.h" #include <boost/program_options.hpp> #include <iostream> #include <stdexcept> namespace po = boost::program_options; void usage(char* program, const po::options_description& desc) { std::cout << "Usage: " << program << " [OPTIONS]... PATTERN_FILE\n" << desc << std::endl; } bool parseCommandLine(int argc, char** argv, Options& options) { po::options_description desc("Allowed options"); desc.add_options()("help", "Display this help message")( "forward,f", "Perform forward computation (default is backwards)")( "grow,g", "Allow for field size growth")( "evolutions,e", po::value<int>(), "Set number of computed evolution steps (default is 1)"); po::options_description hidden("Hidden options"); hidden.add_options()("pattern", po::value<std::string>()); po::positional_options_description p; p.add("pattern", -1); po::options_description cmdline_options; cmdline_options.add(desc).add(hidden); try { po::variables_map vm; po::store(po::command_line_parser(argc, argv) .options(cmdline_options) .positional(p) .run(), vm); po::notify(vm); if (vm.count("help")) { usage(argv[0], desc); return false; } if (vm.count("evolutions")) { options.evolutions = vm["evolutions"].as<int>(); } if (vm.count("forward")) { options.backwards = false; } if (vm.count("grow")) { options.grow = true; } if (vm.count("pattern")) { options.pattern = vm["pattern"].as<std::string>(); } if (options.pattern.empty()) { throw std::runtime_error("No PATTERN_FILE given"); } if (options.evolutions < 1) { throw std::runtime_error( "Specified number of evolutions must be >= 1"); } return true; } catch (std::exception& e) { std::cout << "-- Error: " << e.what() << "\n\n"; usage(argv[0], desc); return false; } }
36.177083
80
0.59142
flopp
e8f637ad13bb661a9253fcf598c2c0e248e03ae3
2,193
hpp
C++
include/codegen/include/Oculus/Platform/MessageWithMatchmakingEnqueueResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Oculus/Platform/MessageWithMatchmakingEnqueueResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Oculus/Platform/MessageWithMatchmakingEnqueueResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:07 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: Oculus.Platform.Message`1 #include "Oculus/Platform/Message_1.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Oculus::Platform::Models namespace Oculus::Platform::Models { // Forward declaring type: MatchmakingEnqueueResult class MatchmakingEnqueueResult; } // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! } // Completed forward declares // Type namespace: Oculus.Platform namespace Oculus::Platform { // Autogenerated type: Oculus.Platform.MessageWithMatchmakingEnqueueResult class MessageWithMatchmakingEnqueueResult : public Oculus::Platform::Message_1<Oculus::Platform::Models::MatchmakingEnqueueResult*> { public: // protected Oculus.Platform.Models.MatchmakingEnqueueResult GetDataFromMessage(System.IntPtr c_message) // Offset: 0xE8E7E0 Oculus::Platform::Models::MatchmakingEnqueueResult* GetDataFromMessage(System::IntPtr c_message); // public System.Void .ctor(System.IntPtr c_message) // Offset: 0xE88740 // Implemented from: Oculus.Platform.Message`1 // Base method: System.Void Message`1::.ctor(System.IntPtr c_message) // Base method: System.Void Message::.ctor(System.IntPtr c_message) static MessageWithMatchmakingEnqueueResult* New_ctor(System::IntPtr c_message); // public override Oculus.Platform.Models.MatchmakingEnqueueResult GetMatchmakingEnqueueResult() // Offset: 0xE8E79C // Implemented from: Oculus.Platform.Message // Base method: Oculus.Platform.Models.MatchmakingEnqueueResult Message::GetMatchmakingEnqueueResult() Oculus::Platform::Models::MatchmakingEnqueueResult* GetMatchmakingEnqueueResult(); }; // Oculus.Platform.MessageWithMatchmakingEnqueueResult } DEFINE_IL2CPP_ARG_TYPE(Oculus::Platform::MessageWithMatchmakingEnqueueResult*, "Oculus.Platform", "MessageWithMatchmakingEnqueueResult"); #pragma pack(pop)
48.733333
137
0.760146
Futuremappermydud
e8fc5928349f4b930c3d40219bd4f5a2ea1a92c5
4,699
cpp
C++
src/soundproducer-track-manager.cpp
adct-the-experimenter/Binaural-Audio-Editor
213e37f6cfe0530f0091b82a700085159ee7babe
[ "BSD-3-Clause" ]
42
2019-05-20T12:54:14.000Z
2022-03-18T01:01:56.000Z
src/soundproducer-track-manager.cpp
adct-the-experimenter/Binaural-Audio-Editor
213e37f6cfe0530f0091b82a700085159ee7babe
[ "BSD-3-Clause" ]
21
2019-05-13T18:40:32.000Z
2021-05-03T20:17:44.000Z
src/soundproducer-track-manager.cpp
adct-the-experimenter/Binaural-Audio-Editor
213e37f6cfe0530f0091b82a700085159ee7babe
[ "BSD-3-Clause" ]
5
2020-05-08T06:02:07.000Z
2021-04-17T12:15:41.000Z
#include "soundproducer-track-manager.h" SoundProducerTrackManager::SoundProducerTrackManager(const wxString& title,ALCdevice* thisAudioDevice,ALCcontext* thisAudioContext) : Track(title) { //initialize audio player audioPlayer = new OpenALSoftPlayer(); audioPlayer->SetReferenceToAudioContext(thisAudioContext); audioPlayer->SetReferenceToAudioDevice(thisAudioDevice); soundProducerTracks_vec = nullptr; SoundProducerTrackManager::SetSoundPlayingBool(false); } SoundProducerTrackManager::~SoundProducerTrackManager() { if(audioPlayer != nullptr) { delete audioPlayer; } } void SoundProducerTrackManager::SetReferenceToAudioDevice(ALCdevice* thisAudioDevice){audioDevicePtr = thisAudioDevice;} void SoundProducerTrackManager::SetReferenceToAudioContext(ALCcontext* thisAudioContext){alContextPtr = thisAudioContext;} void SoundProducerTrackManager::SetReferenceToSoundProducerTrackVector(std::vector <SoundProducerTrack*> *thisTrackVec) { soundProducerTracks_vec = thisTrackVec; } void SoundProducerTrackManager::AddSourceOfLastTrackToSoundProducerTrackManager() { if(soundProducerTracks_vec != nullptr) { ALuint* thisSource = soundProducerTracks_vec->at(soundProducerTracks_vec->size() - 1)->GetReferenceToTrackSource(); soundproducertracks_sources_vector.push_back(thisSource); } } void SoundProducerTrackManager::RemoveSourceOfLastTrackFromSoundProducerTrackManager() { soundproducertracks_sources_vector.pop_back(); } //Functions inherited from Track void SoundProducerTrackManager::SetReferenceToCurrentTimeVariable(double* thisTimeVariable){Track::SetReferenceToCurrentTimeVariable(thisTimeVariable);} double SoundProducerTrackManager::GetCurrentTime(){return Track::GetCurrentTime();} //function to call in timer loop, variable to manipulate gets changed here void SoundProducerTrackManager::FunctionToCallInPlayState() { SoundProducerTrackManager::SetSoundPlayingBool(true); //buffer audio for all track sources for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInPlayState(); } //play all sources in sync if(soundProducerTracks_vec->at(0)->GetReferenceToStereoAudioTrack()->GetAudioTrackState() == StereoAudioTrack::State::PLAYER_NULL) { audioPlayer->PlayMultipleSources(&soundproducertracks_sources_vector); } else if(soundProducerTracks_vec->at(0)->GetReferenceToStereoAudioTrack()->GetAudioTrackState() == StereoAudioTrack::State::PLAYER_PLAYING) { audioPlayer->PlayMultipleUpdatedPlayerBuffers(&soundproducertracks_sources_vector); } } void SoundProducerTrackManager::FunctionToCallInPauseState() { SoundProducerTrackManager::SetSoundPlayingBool(false); for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInPauseState(); } } void SoundProducerTrackManager::FunctionToCallInRewindState() { SoundProducerTrackManager::SetSoundPlayingBool(false); for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInRewindState(); } } void SoundProducerTrackManager::FunctionToCallInFastForwardState() { SoundProducerTrackManager::SetSoundPlayingBool(false); for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInFastForwardState(); } } void SoundProducerTrackManager::FunctionToCallInNullState() { SoundProducerTrackManager::SetSoundPlayingBool(false); for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInNullState(); } } void SoundProducerTrackManager::SetSoundPlayingBool(bool status){soundPlaying = status;} bool SoundProducerTrackManager::IsSoundBeingPlayed(){return soundPlaying;} void SoundProducerTrackManager::PlayThisTrackFromSoundProducerTrackVector(int& index) { //buffer audio for track source //soundProducerTracks_vec->at(index)->FunctionToCallInPlayState(); double current_time = 0; soundProducerTracks_vec->at(index)->BufferAndPlayAudio(current_time); } void SoundProducerTrackManager::PauseThisTrackFromSoundProducerTrackVector(int& index) { audioPlayer->PauseSource(soundproducertracks_sources_vector[index]); } void SoundProducerTrackManager::StopThisTrackFromSoundProducerTrackVector(int& index) { soundProducerTracks_vec->at(index)->StopAudio(); } void SoundProducerTrackManager::BrowseAudioForThisSoundProducer(SoundProducer* lastProducer) { //get sound producer name of last sound producer created soundProducerTracks_vec->back()->SelectSoundProducerByName(lastProducer->GetNameString()); soundProducerTracks_vec->back()->GetReferenceToStereoAudioTrack()->BrowseForInputAudioFile(); }
31.75
152
0.816557
adct-the-experimenter
e8fe95714a081e8571f376df9faa294761282073
710
cpp
C++
common_helper_functions.cpp
pintotomas/tp3
dd319ec583a73b931a0751b3b4f15e7e6b04b245
[ "MIT" ]
null
null
null
common_helper_functions.cpp
pintotomas/tp3
dd319ec583a73b931a0751b3b4f15e7e6b04b245
[ "MIT" ]
null
null
null
common_helper_functions.cpp
pintotomas/tp3
dd319ec583a73b931a0751b3b4f15e7e6b04b245
[ "MIT" ]
null
null
null
#include "helper_functions.h" #include <iostream> const bool contains_unique_numbers(const std::string &str) { bool numbers[DIGITS] = { 0 }; for (unsigned int i = 0; i < str.length(); i++) { int n = (int) str[i] - ASCII_DIGITS_START; if (numbers[n] == true) return false; numbers[n] = true; } return true; } const bool is_digits(const std::string &str) { return std::all_of(str.begin(), str.end(), ::isdigit); } const bool str_to_uint16(const char *str) { char *end; errno = 0; intmax_t val = strtoimax(str, &end, 10); if (errno == ERANGE || val < 0 || val > UINT16_MAX || end == str || *end != '\0') return false; return true; }
23.666667
60
0.585915
pintotomas
3303637c5e2acc2df4f0a2d0e8178adf6ae95540
264
cc
C++
codes/cpp/cpp-concurrency/ch03/test_stack_s.cc
zhoujiagen/learning-system-programming
2a18e9f8558433708837ba4bd0fae5d7c11bf110
[ "MIT" ]
null
null
null
codes/cpp/cpp-concurrency/ch03/test_stack_s.cc
zhoujiagen/learning-system-programming
2a18e9f8558433708837ba4bd0fae5d7c11bf110
[ "MIT" ]
null
null
null
codes/cpp/cpp-concurrency/ch03/test_stack_s.cc
zhoujiagen/learning-system-programming
2a18e9f8558433708837ba4bd0fae5d7c11bf110
[ "MIT" ]
null
null
null
#include "stack_s.h" #include <iostream> stack_s<int> stack; // TODO // void work_push() // { // } // void work_pop() // { // } int main(int argc, char const *argv[]) { stack.push(0); stack.push(1); std::cout << stack.pop() << std::endl; return 0; }
11
40
0.568182
zhoujiagen
33062b0624f425e8eef0c18b7ff4dfb3b67ef0eb
8,298
cxx
C++
third-party/libstudxml/xml/serializer.cxx
haquocviet/xlnt
8f39375f4c29e7f7590efaeb6ce8c56490560c1f
[ "Unlicense" ]
8
2019-02-28T14:49:56.000Z
2022-03-29T06:32:09.000Z
third-party/libstudxml/xml/serializer.cxx
haquocviet/xlnt
8f39375f4c29e7f7590efaeb6ce8c56490560c1f
[ "Unlicense" ]
2
2021-04-09T15:36:05.000Z
2021-11-17T22:38:10.000Z
third-party/libstudxml/xml/serializer.cxx
haquocviet/xlnt
8f39375f4c29e7f7590efaeb6ce8c56490560c1f
[ "Unlicense" ]
3
2019-12-31T14:04:17.000Z
2022-03-18T11:44:49.000Z
// file : xml/serializer.cxx // copyright : Copyright (c) 2013-2017 Code Synthesis Tools CC // license : MIT; see accompanying LICENSE file #include <new> // std::bad_alloc #include <cstring> // std::strlen #include <xml/serializer> using namespace std; namespace xml { // serialization // void serialization:: init () { if (!name_.empty ()) { what_ += name_; what_ += ": "; } what_ += "error: "; what_ += description_; } // serializer // extern "C" genxStatus genx_write (void* p, constUtf8 us) { // It would have been easier to throw the exception directly, // however, the Genx code is most likely not exception safe. // ostream* os (static_cast<ostream*> (p)); const char* s (reinterpret_cast<const char*> (us)); os->write (s, static_cast<streamsize> (strlen (s))); return os->good () ? GENX_SUCCESS : GENX_IO_ERROR; } extern "C" genxStatus genx_write_bound (void* p, constUtf8 start, constUtf8 end) { ostream* os (static_cast<ostream*> (p)); const char* s (reinterpret_cast<const char*> (start)); streamsize n (static_cast<streamsize> (end - start)); os->write (s, n); return os->good () ? GENX_SUCCESS : GENX_IO_ERROR; } extern "C" genxStatus genx_flush (void* p) { ostream* os (static_cast<ostream*> (p)); os->flush (); return os->good () ? GENX_SUCCESS : GENX_IO_ERROR; } serializer:: ~serializer () { if (s_ != 0) genxDispose (s_); } serializer:: serializer (ostream& os, const string& oname, unsigned short ind) : os_ (os), os_state_ (os.exceptions ()), oname_ (oname), depth_ (0) { // Temporarily disable exceptions on the stream. // os_.exceptions (ostream::goodbit); // Allocate the serializer. Make sure nothing else can throw after // this call since otherwise we will leak it. // s_ = genxNew (0, 0, 0); if (s_ == 0) throw bad_alloc (); genxSetUserData (s_, &os_); if (ind != 0) genxSetPrettyPrint (s_, ind); sender_.send = &genx_write; sender_.sendBounded = &genx_write_bound; sender_.flush = &genx_flush; if (genxStatus e = genxStartDocSender (s_, &sender_)) { string m (genxGetErrorMessage (s_, e)); genxDispose (s_); throw serialization (oname, m); } } void serializer:: handle_error (genxStatus e) const { switch (e) { case GENX_ALLOC_FAILED: throw bad_alloc (); case GENX_IO_ERROR: // Restoring the original exception state should trigger the // exception. If it doesn't (e.g., because the user didn't // configure the stream to throw), then fall back to the // serialiation exception. // os_.exceptions (os_state_); // Fall through. default: throw serialization (oname_, genxGetErrorMessage (s_, e)); } } void serializer:: start_element (const string& ns, const string& name) { if (genxStatus e = genxStartElementLiteral ( s_, reinterpret_cast<constUtf8> (ns.empty () ? 0 : ns.c_str ()), reinterpret_cast<constUtf8> (name.c_str ()))) handle_error (e); depth_++; } void serializer:: end_element () { if (genxStatus e = genxEndElement (s_)) handle_error (e); // Call EndDocument() if we are past the root element. // if (--depth_ == 0) { if (genxStatus e = genxEndDocument (s_)) handle_error (e); // Also restore the original exception state on the stream. // os_.exceptions (os_state_); } } void serializer:: end_element (const string& ns, const string& name) { constUtf8 cns, cn; genxStatus e; if ((e = genxGetCurrentElement (s_, &cns, &cn)) || reinterpret_cast<const char*> (cn) != name || (cns == 0 ? !ns.empty () : reinterpret_cast<const char*> (cns) != ns)) { handle_error (e != GENX_SUCCESS ? e : GENX_SEQUENCE_ERROR); } end_element (); } void serializer:: element (const string& ns, const string& n, const string& v) { start_element (ns, n); element (v); } void serializer:: start_attribute (const string& ns, const string& name) { if (genxStatus e = genxStartAttributeLiteral ( s_, reinterpret_cast<constUtf8> (ns.empty () ? 0 : ns.c_str ()), reinterpret_cast<constUtf8> (name.c_str ()))) handle_error (e); } void serializer:: end_attribute () { if (genxStatus e = genxEndAttribute (s_)) handle_error (e); } void serializer:: end_attribute (const string& ns, const string& name) { constUtf8 cns, cn; genxStatus e; if ((e = genxGetCurrentAttribute (s_, &cns, &cn)) || reinterpret_cast<const char*> (cn) != name || (cns == 0 ? !ns.empty () : reinterpret_cast<const char*> (cns) != ns)) { handle_error (e != GENX_SUCCESS ? e : GENX_SEQUENCE_ERROR); } end_attribute (); } void serializer:: attribute (const string& ns, const string& name, const string& value) { if (genxStatus e = genxAddAttributeLiteral ( s_, reinterpret_cast<constUtf8> (ns.empty () ? 0 : ns.c_str ()), reinterpret_cast<constUtf8> (name.c_str ()), reinterpret_cast<constUtf8> (value.c_str ()))) handle_error (e); } void serializer:: characters (const string& value) { if (genxStatus e = genxAddCountedText ( s_, reinterpret_cast<constUtf8> (value.c_str ()), value.size ())) handle_error (e); } void serializer:: namespace_decl (const string& ns, const string& p) { if (genxStatus e = ns.empty () && p.empty () ? genxUnsetDefaultNamespace (s_) : genxAddNamespaceLiteral ( s_, reinterpret_cast<constUtf8> (ns.c_str ()), reinterpret_cast<constUtf8> (p.c_str ()))) handle_error (e); } void serializer:: xml_decl (const string& ver, const string& enc, const string& stl) { if (genxStatus e = genxXmlDeclaration ( s_, reinterpret_cast<constUtf8> (ver.c_str ()), (enc.empty () ? 0 : reinterpret_cast<constUtf8> (enc.c_str ())), (stl.empty () ? 0 : reinterpret_cast<constUtf8> (stl.c_str ())))) handle_error (e); } void serializer:: doctype_decl (const string& re, const string& pi, const string& si, const string& is) { if (genxStatus e = genxDoctypeDeclaration ( s_, reinterpret_cast<constUtf8> (re.c_str ()), (pi.empty () ? 0 : reinterpret_cast<constUtf8> (pi.c_str ())), (si.empty () ? 0 : reinterpret_cast<constUtf8> (si.c_str ())), (is.empty () ? 0 : reinterpret_cast<constUtf8> (is.c_str ())))) handle_error (e); } bool serializer:: lookup_namespace_prefix (const string& ns, string& p) const { // Currently Genx will create a namespace mapping if one doesn't // already exist. // genxStatus e; genxNamespace gns ( genxDeclareNamespace ( s_, reinterpret_cast<constUtf8> (ns.c_str ()), 0, &e)); if (e != GENX_SUCCESS) handle_error (e); p = reinterpret_cast<const char*> (genxGetNamespacePrefix (gns)); return true; } qname serializer:: current_element () const { constUtf8 ns, n; if (genxStatus e = genxGetCurrentElement (s_, &ns, &n)) handle_error (e); return qname (ns != 0 ? reinterpret_cast<const char*> (ns) : "", reinterpret_cast<const char*> (n)); } qname serializer:: current_attribute () const { constUtf8 ns, n; if (genxStatus e = genxGetCurrentAttribute (s_, &ns, &n)) handle_error (e); return qname (ns != 0 ? reinterpret_cast<const char*> (ns) : "", reinterpret_cast<const char*> (n)); } void serializer:: suspend_indentation () { if (genxStatus e = genxSuspendPrettyPrint (s_)) handle_error (e); } void serializer:: resume_indentation () { if (genxStatus e = genxResumePrettyPrint (s_)) handle_error (e); } size_t serializer:: indentation_suspended () const { return static_cast<size_t> (genxPrettyPrintSuspended (s_)); } }
25.453988
78
0.600265
haquocviet
3306cd5d1317baed6256f45ba3c47e4b0136ae61
2,700
hpp
C++
SOLVER/src/core/element/material/elastic/Elastic.hpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
8
2020-06-05T01:13:20.000Z
2022-02-24T05:11:50.000Z
SOLVER/src/core/element/material/elastic/Elastic.hpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
24
2020-10-21T19:03:38.000Z
2021-11-17T21:32:02.000Z
SOLVER/src/core/element/material/elastic/Elastic.hpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
5
2020-06-21T11:54:22.000Z
2021-06-23T01:02:39.000Z
// // Elastic.hpp // AxiSEM3D // // Created by Kuangdai Leng on 2/26/19. // Copyright © 2019 Kuangdai Leng. All rights reserved. // // elastic material #ifndef Elastic_hpp #define Elastic_hpp #include "Attenuation.hpp" class Elastic { public: // constructor Elastic(bool is1D, std::unique_ptr<Attenuation> &attenuation): m1D(is1D), mAttenuation(attenuation.release()) { // nothing } // copy constructor Elastic(const Elastic &other): m1D(other.m1D), mAttenuation((other.mAttenuation == nullptr) ? nullptr : other.mAttenuation->clone()) { // nothing } // destructor virtual ~Elastic() = default; // clone for copy constructor virtual std::unique_ptr<Elastic> clone() const = 0; // 1D operation bool is1D() const { return m1D; } // check compatibility virtual void checkCompatibility(int nr, bool elemInFourier) const { if (mAttenuation) { mAttenuation->checkCompatibility(nr, elemInFourier, m1D); } } // reset to zero void resetToZero() const { if (mAttenuation) { mAttenuation->resetToZero(); } } ///////////////////////// strain to stress ///////////////////////// // RTZ coordinates virtual bool inRTZ() const = 0; // strain => stress in Fourier space virtual void strainToStress_FR(const eigen::vec_ar6_CMatPP_RM &strain, eigen::vec_ar6_CMatPP_RM &stress, int nu_1) const = 0; // strain => stress in cardinal space virtual void strainToStress_CD(const eigen::RMatXN6 &strain, eigen::RMatXN6 &stress, int nr) const = 0; ///////////////////////// attenuation ///////////////////////// protected: // attenuation in Fourier space void applyAttenuation(const eigen::vec_ar6_CMatPP_RM &strain, eigen::vec_ar6_CMatPP_RM &stress, int nu_1) const { if (mAttenuation) { mAttenuation->apply(strain, stress, nu_1); } } // attenuation in cardinal space void applyAttenuation(const eigen::RMatXN6 &strain, eigen::RMatXN6 &stress, int nr) const { if (mAttenuation) { mAttenuation->apply(strain, stress, nr); } } ////////////////////////// data ////////////////////////// protected: // 1D/3D flag const bool m1D; private: // attenuation const std::unique_ptr<Attenuation> mAttenuation; }; #endif /* Elastic_hpp */
26.213592
77
0.537778
nicklinyi
3309cc0da29dc3c26c30407a3edf49d8790ac209
4,472
cpp
C++
BCC55/Examples/StdLib/memfunc.cpp
C14427818/CollegeYr1
2b551d70ae3cc14a354c49657d476515466ca66f
[ "MIT" ]
null
null
null
BCC55/Examples/StdLib/memfunc.cpp
C14427818/CollegeYr1
2b551d70ae3cc14a354c49657d476515466ca66f
[ "MIT" ]
null
null
null
BCC55/Examples/StdLib/memfunc.cpp
C14427818/CollegeYr1
2b551d70ae3cc14a354c49657d476515466ca66f
[ "MIT" ]
null
null
null
#include "stlexam.h" #pragma hdrstop /************************************************************************** * * memfunc.cpp - Example program for mem_fun and other member function * pointer wrappers. See Class Reference Section. * *************************************************************************** * * (c) Copyright 1994, 1998 Rogue Wave Software, Inc. * ALL RIGHTS RESERVED * * The software and information contained herein are proprietary to, and * comprise valuable trade secrets of, Rogue Wave Software, Inc., which * intends to preserve as trade secrets such software and information. * This software is furnished pursuant to a written license agreement and * may be used, copied, transmitted, and stored only in accordance with * the terms of such license and with the inclusion of the above copyright * notice. This software and information or any other copies thereof may * not be provided or otherwise made available to any other person. * * Notwithstanding any other lease or license that may pertain to, or * accompany the delivery of, this computer software and information, the * rights of the Government regarding its use, reproduction and disclosure * are as set forth in Section 52.227-19 of the FARS Computer * Software-Restricted Rights clause. * * Use, duplication, or disclosure by the Government is subject to * restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in * Technical Data and Computer Software clause at DFARS 252.227-7013. * Contractor/Manufacturer is Rogue Wave Software, Inc., * P.O. Box 2328, Corvallis, Oregon 97339. * * This computer software and information is distributed with "restricted * rights." Use, duplication or disclosure is subject to restrictions as * set forth in NASA FAR SUP 18-52.227-79 (April 1985) "Commercial * Computer Software-Restricted Rights (April 1985)." If the Clause at * 18-52.227-74 "Rights in Data General" is specified in the contract, * then the "Alternate III" clause applies. * **************************************************************************/ #include <vector> #include <functional> #include <algorithm> #ifdef _RW_STD_IOSTREAM #include <iostream> #else #include <iostream.h> #endif #ifndef _RWSTD_NO_NAMESPACE using namespace std; #endif // // Very large city class // class MegaPolis { public: MegaPolis(char* s = 0 , float n = 0):cityName(s),population(n) {;} // The following function cannot return void due to limitations in // some current C++ implementations. virtual size_t byPopulation() { cout<<cityName<<"(MegaPolis)"<<"\t\t\t"<<population<<endl; return 0; } float population; protected: char* cityName; }; // // City and surrounding area class // class MetroPolis : public MegaPolis { public: MetroPolis(char* s = 0 , float n = 0):MegaPolis(s,n){;} virtual size_t byPopulation() { cout<<cityName<<"(MetroPolis)"<<"\t\t\t"<<population<<endl; return 0; } }; // // Functor compares the size of two MeagPolis classes // struct GreaterPopulation { bool operator()(MegaPolis* m1, MegaPolis* m2) { return m1->population<m2->population; } } greater_pop; int main() { // // Create a vector of very lareg cities // vector<MegaPolis*, allocator<MegaPolis*> > cityList; cityList.push_back(new MegaPolis ("Calcutta",35)); cityList.push_back(new MegaPolis ("Tokyo",20)); cityList.push_back(new MegaPolis ("Delhi",10)); cityList.push_back(new MegaPolis ("Bombay",15)); cityList.push_back(new MetroPolis ("Cairo",5)); cityList.push_back(new MetroPolis ("New York",2.5)); cityList.push_back(new MetroPolis ("Los Angeles",3)); cityList.push_back(new MetroPolis ("Jakarta",1.5)); // // Now use mem_fun to pass byPopulation member function // of MegaPolis to the for_each function. // cout<<"City "<<" Population (in millions) "<<endl; cout<<"----- "<<" -----------------------"<<endl; for_each(cityList.begin(),cityList.end(),mem_fun(&MegaPolis::byPopulation)); cout<<"..............After sorting..........................."<<endl; stable_sort(cityList.begin(),cityList.end(),greater_pop); for_each(cityList.begin(),cityList.end(),mem_fun(&MegaPolis::byPopulation)); return 0; }
32.642336
79
0.635733
C14427818
331012ad1f9182cfb56eee2c8fb656a32fc7dc7a
1,642
cpp
C++
src/platform/testing/alchemy/audio.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
11
2015-03-02T07:43:00.000Z
2021-12-04T04:53:02.000Z
src/platform/testing/alchemy/audio.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
1
2015-03-28T17:17:13.000Z
2016-10-10T05:49:07.000Z
src/platform/testing/alchemy/audio.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
3
2016-11-04T01:14:31.000Z
2020-05-07T23:42:27.000Z
/**************************** Copyright © 2006-2011 Luke Salisbury 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 acknowledgment 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 "../luxengine.h" #include "../functions.h" #include "../gamepack.h" AudioSystem::AudioSystem ( ) { lux::core->SystemMessage(SYSTEM_MESSAGE_LOG) << "Audio System" << std::endl; } AudioSystem::~AudioSystem ( ) { } bool AudioSystem::Init() { return true; } bool AudioSystem::LoadAudio(std::string name) { return false; } bool AudioSystem::PlayEffect ( std::string requestSound ) { return false; } bool AudioSystem::PlayDialog ( int requestSound ) { return false; } bool AudioSystem::PlayMusic ( std::string requestMusic, int loop, int fadeLength ) { return false; } int AudioSystem::SetMusicVolume(int volume) { return 0; } int AudioSystem::SetEffectsVolume(int volume) { return 0; } void AudioSystem::Pause() { }
26.063492
243
0.732643
mokoi
33109be627e39e30e59be26f77467aa853c51efe
16,952
cpp
C++
MarlinClient/TestsetClient/TestWS.cpp
zYg-sys/Marlin
eeabb4d324c5f8d253a50c106208bb833cb824e8
[ "MIT" ]
23
2016-09-16T11:25:54.000Z
2022-03-03T07:18:57.000Z
MarlinClient/TestsetClient/TestWS.cpp
zYg-sys/Marlin
eeabb4d324c5f8d253a50c106208bb833cb824e8
[ "MIT" ]
26
2016-10-21T11:07:54.000Z
2022-03-05T18:27:03.000Z
MarlinClient/TestsetClient/TestWS.cpp
zYg-sys/Marlin
eeabb4d324c5f8d253a50c106208bb833cb824e8
[ "MIT" ]
7
2018-09-11T12:17:46.000Z
2021-07-08T09:10:04.000Z
///////////////////////////////////////////////////////////////////////////////// // // SourceFile: TestWS.cpp // // Marlin Server: Internet server/client // // Copyright (c) 2015-2018 ir. W.E. Huisman // All rights reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "stdafx.h" #include "SOAPMessage.h" #include "XMLMessage.h" #include "TestClient.h" #include "HTTPClient.h" #include "WebServiceClient.h" #include "GetLastErrorAsString.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif int DoSend(HTTPClient& p_client,SOAPMessage* p_msg,char* p_what,bool p_fault = false) { bool result = false; // 1: CHECK SYNCHROON VERZONDEN. NORMAAL BERICHT if(p_client.Send(p_msg)) { if(p_msg->GetFaultCode().IsEmpty()) { xprintf("Received: %s\n%s",p_msg->GetSoapAction().GetString(),p_msg->GetSoapMessage().GetString()); CString action = p_msg->GetSoapAction(); CString test = p_msg->GetParameter("Three"); int number = p_msg->GetParameterInteger("Four"); CString testing = p_msg->GetParameter("Testing"); xprintf("Answer: %s : %s\n","Three",test.GetString()); xprintf("Answer: %s : %d\n","Four",number); // See if the answer is satisfying if(test == "DEF" || number == 123 && action == "TestMessageResponse" || testing == "OK") { result = true; } // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Send: SOAP Message %-27s : %s\n",p_what,result ? "OK" : "ERROR"); } else { if(p_fault) { if(p_msg->GetFaultCode() == "FX1" && p_msg->GetFaultActor() == "Server" && p_msg->GetFaultString() == "Testing SOAP Fault" && p_msg->GetFaultDetail() == "See if the SOAP Fault does work!") { result = true; } // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Send: SOAP Message %-27s : %s\n",p_what,result ? "OK" : "ERROR"); } else { // But we where NOT expecting a FAULT! printf("Answer with error: %s\n",(LPCTSTR)p_msg->GetFault()); printf("SOAP Fault code: %s\n",(LPCTSTR)p_msg->GetFaultCode()); printf("SOAP Fault actor: %s\n",(LPCTSTR)p_msg->GetFaultActor()); printf("SOAP Fault string: %s\n",(LPCTSTR)p_msg->GetFaultString()); printf("SOAP FAULT detail: %s\n",(LPCTSTR)p_msg->GetFaultDetail()); } } } else { // Possibly a SOAP fault as answer if(!p_msg->GetFaultCode().IsEmpty()) { printf("SOAP Fault: %s\n",p_msg->GetFault().GetString()); } else { // Raw HTTP error BYTE* response = NULL; unsigned length = 0; p_client.GetResponse(response, length); printf("Message not sent!\n"); printf("Service answer: %s\n", (char*)response); printf("HTTP Client error: %s\n", p_client.GetStatusText().GetString()); } } // ready with the message delete p_msg; return result ? 0 : 1; } int DoSendPrice(HTTPClient& p_client, SOAPMessage* p_msg,double p_price) { bool result = false; // 1: CHECK SYNCHROON VERZONDEN. NORMAAL BERICHT if (p_client.Send(p_msg)) { if(p_msg->GetFaultCode().IsEmpty()) { double priceInclusive = p_msg->GetParameterDouble("PriceInclusive"); if(priceInclusive - (p_price * 1.21) < 0.005) // Dutch VAT percentage { result = true; } } else { printf("Answer with error: %s\n", (LPCTSTR)p_msg->GetFault()); printf("SOAP Fault code: %s\n", (LPCTSTR)p_msg->GetFaultCode()); printf("SOAP Fault actor: %s\n", (LPCTSTR)p_msg->GetFaultActor()); printf("SOAP Fault string: %s\n", (LPCTSTR)p_msg->GetFaultString()); printf("SOAP FAULT detail: %s\n", (LPCTSTR)p_msg->GetFaultDetail()); } } else { // Possibly a SOAP fault as answer if(!p_msg->GetFaultCode().IsEmpty()) { printf("SOAP Fault: %s\n", p_msg->GetFault().GetString()); } else { // Raw HTTP error BYTE* response = NULL; unsigned length = 0; p_client.GetResponse(response, length); printf("Message not sent!\n"); printf("Service answer: %s\n", (char*)response); printf("HTTP Client error: %s\n", p_client.GetStatusText().GetString()); } } // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Send: SOAP datatype double calculation : %s\n", result ? "OK" : "ERROR"); // ready with the message delete p_msg; return (result == true) ? 0 : 1; } SOAPMessage* CreateSoapMessage(CString p_namespace ,CString p_command ,CString p_url ,SoapVersion p_version = SoapVersion::SOAP_12 ,XMLEncryption p_encrypt = XMLEncryption::XENC_Plain) { // Build message SOAPMessage* msg = new SOAPMessage(p_namespace,p_command,p_version,p_url); msg->SetParameter("One","ABC"); msg->SetParameter("Two","1-2-3"); // "17" will stop the server XMLElement* param = msg->SetParameter("Units",""); XMLElement* enh1 = msg->AddElement(param,"Unit",XDT_String,""); XMLElement* enh2 = msg->AddElement(param,"Unit",XDT_String,""); msg->SetElement(enh1,"Unitnumber",12345); msg->SetElement(enh2,"Unitnumber",67890); msg->SetAttribute(enh1,"Independent",true); msg->SetAttribute(enh2,"Independent",false); if(p_encrypt != XMLEncryption::XENC_Plain) { msg->SetSecurityLevel(p_encrypt); msg->SetSecurityPassword("ForEverSweet16"); if(p_encrypt == XMLEncryption::XENC_Body) { // msg->SetSigningMethod(CALG_RSA_SIGN); } } return msg; } SOAPMessage* CreateSoapPriceMessage(CString p_namespace ,CString p_command ,CString p_url ,double p_price) { SOAPMessage* msg = new SOAPMessage(p_namespace,p_command,SoapVersion::SOAP_12,p_url); msg->SetParameter("Price", p_price); return msg; } int TestReliableMessaging(HTTPClient* p_client,CString p_namespace,CString p_action,CString p_url,bool p_tokenProfile) { int errors = 0; int totalDone = 0; WebServiceClient client(p_namespace,p_url,"",true); client.SetHTTPClient(p_client); client.SetLogAnalysis(p_client->GetLogging()); // testing soap compression // client.SetSoapCompress(true); // Testing with WS-Security Token profile if(p_tokenProfile) { client.SetUser("marlin"); client.SetPassword("M@rl!nS3cr3t"); client.SetTokenProfile(true); } SOAPMessage* message = nullptr; try { // Client must be opened for RM protocol client.Open(); for(int ind = 0; ind < NUM_RM_TESTS; ++ind) { // Make a copy of the message message = CreateSoapMessage(p_namespace,p_action,p_url); // Forced that it is not set to reliable. It doesn't have to, becouse the client.Send() will do that // message->SetReliability(true); xprintf("Sending RM message: %s\n",message->GetSoapMessage().GetString()); if(client.Send(message)) { xprintf("Received: %s\n%s",message->GetSoapAction().GetString(),message->GetSoapMessage().GetString()); CString action = message->GetSoapAction(); CString test = message->GetParameter("Three"); int number = message->GetParameterInteger("Four"); xprintf("Answer: %s : %s\n","Three",test.GetString()); xprintf("Answer: %s : %d\n","Four ",number); bool result = false; if(test == "DEF" || number == 123 && action == "TestMessageResponse") { ++totalDone; result = true; } else { printf("Answer with fault: %s\n",message->GetFault().GetString()); result = false; } // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Send: SOAP WS-ReliableMessaging : %s\n",result ? "OK" : "ERROR"); errors += result ? 0 : 1; } else { ++errors; printf("Message **NOT** correctly sent!\n"); printf("Error code WebServiceClient: %s\n",client.GetErrorText().GetString()); printf("Return message error:\n%s\n",message->GetFault().GetString()); } // Ready with the message if(message) { delete message; message = nullptr; } } // Must be closed to complete RM protocol client.Close(); } catch(StdException& error) { ++errors; printf("ERROR received : %s\n",error.GetErrorMessage().GetString()); printf("ERROR from WS Client: %s\n",client.GetErrorText().GetString()); } if(message) { delete message; message = nullptr; } return (totalDone == NUM_RM_TESTS) ? 0 : 1; } int DoSendByQueue(HTTPClient& p_client,CString p_namespace,CString p_action,CString p_url) { int times = 20; CString name("TestNumber"); for(int x = 1; x <= times; ++x) { SOAPMessage* message = CreateSoapMessage(p_namespace,p_action,p_url); message->SetParameter(name,x); p_client.AddToQueue(message); } // --- "---------------------------------------------- - ------ printf("Send: [%d] messages added to the sending queue : OK\n",times); return 0; } int DoSendAsyncQueue(HTTPClient& p_client,CString p_namespace,CString p_url) { int times = 10; CString resetMess("MarlinReset"); CString textMess ("MarlinText"); SOAPMessage* reset1 = new SOAPMessage(p_namespace,resetMess,SoapVersion::SOAP_12,p_url); SOAPMessage* reset2 = new SOAPMessage(p_namespace,resetMess,SoapVersion::SOAP_12,p_url); reset1->SetParameter("DoReset",true); reset2->SetParameter("DoReset",true); p_client.AddToQueue(reset1); for(int ind = 0;ind < times; ++ind) { SOAPMessage* msg = new SOAPMessage(p_namespace,textMess,SoapVersion::SOAP_12,p_url); msg->SetParameter("Text","This is a testing message to see if async SOAP messages are delivered."); p_client.AddToQueue(msg); } p_client.AddToQueue(reset2); // --- "---------------------------------------------- - ------ printf("Send: Asynchronous messages added to the queue : OK\n"); return 0; } inline CString CreateURL(CString p_extra) { CString url; url.Format("http://%s:%d/MarlinTest/%s",MARLIN_HOST,TESTING_HTTP_PORT,p_extra.GetString()); return url; } int TestWebservices(HTTPClient& client) { int errors = 0; extern CString logfileName; SOAPMessage* msg = nullptr; // Testing cookie function errors += TestCookies(client); // Standard values for messages CString namesp("http://interface.marlin.org/services"); CString command("TestMessage"); CString url(CreateURL("Insecure")); // Test 1 xprintf("TESTING STANDARD SOAP MESSAGE TO /MarlinTest/Insecure/\n"); xprintf("====================================================\n"); msg = CreateSoapMessage(namesp,command,url); errors += DoSend(client,msg,(char*)"insecure"); // Test 2 xprintf("TESTING BODY SIGNING SOAP TO /MarlinTest/BodySigning/\n"); xprintf("===================================================\n"); url = CreateURL("BodySigning"); msg = CreateSoapMessage(namesp,command,url,SoapVersion::SOAP_12, XMLEncryption::XENC_Signing); errors += DoSend(client,msg,(char*)"body signing"); // Test 3 xprintf("TESTING BODY ENCRYPTION SOAP TO /MarlinTest/BodyEncrypt/\n"); xprintf("======================================================\n"); url = CreateURL("BodyEncrypt"); msg = CreateSoapMessage(namesp,command,url, SoapVersion::SOAP_12, XMLEncryption::XENC_Body); errors += DoSend(client,msg,(char*)"body encrypting"); // Test 4 xprintf("TESTING WHOLE MESSAGE ENCRYPTION TO /MarlinTest/MessageEncrypt/\n"); xprintf("=============================================================\n"); url = CreateURL("MessageEncrypt"); msg = CreateSoapMessage(namesp,command,url, SoapVersion::SOAP_12, XMLEncryption::XENC_Message); errors += DoSend(client,msg,(char*)"message encrypting"); // Test 5 xprintf("TESTING RELIABLE MESSAGING TO /MarlinTest/Reliable/\n"); xprintf("=================================================\n"); url = CreateURL("Reliable"); errors += TestReliableMessaging(&client,namesp,command,url,false); // Test 6 xprintf("TESTING RELIABLE MESSAGING TO /MarlinTest/ReliableBA/ with WS-Security token profile\n"); xprintf("=================================================\n"); url = CreateURL("ReliableBA"); errors += TestReliableMessaging(&client,namesp,command,url,true); // Test 7 xprintf("TESTING THE TOKEN FUNCTION TO /MarlinTest/TestToken/\n"); xprintf("====================================================\n"); url = CreateURL("TestToken"); msg = CreateSoapMessage(namesp,command,url); client.SetSingleSignOn(true); CString user("CERT6\\Beheerder"); CString password("altijd"); client.SetUser(user); client.SetPassword(password); errors += DoSend(client,msg,(char*)"token testing"); client.SetSingleSignOn(false); // Test 8 xprintf("TESTING THE SUB-SITES FUNCTION TO /MarlinTest/TestToken/One/\n"); xprintf("TESTING THE SUB-SITES FUNCTION TO /MarlinTest/TestToken/Two/\n"); xprintf("============================================================\n"); CString url1 = CreateURL("TestToken/One"); CString url2 = CreateURL("TestToken/Two"); msg = CreateSoapMessage(namesp,command,url1); client.SetSingleSignOn(true); client.SetUser(user); client.SetPassword(password); errors += DoSend(client,msg,(char*)"single sign on"); msg = CreateSoapMessage(namesp,command,url2); errors += DoSend(client,msg,(char*)"single sign on"); client.SetSingleSignOn(false); // Test 9 xprintf("TESTING SOAP FAULT TO /MarlinTest/Insecure/\n"); xprintf("=================================================\n"); url = CreateURL("Insecure"); msg = CreateSoapMessage(namesp,command,url); msg->SetParameter("TestFault",true); errors += DoSend(client,msg,(char*)"soap fault",true); // Test 10 xprintf("TESTING UNICODE SENDING TO /MarlinTest/Insecure/\n"); xprintf("================================================\n"); url = CreateURL("Insecure"); msg = CreateSoapMessage(namesp,command,url); msg->SetSendUnicode(true); errors += DoSend(client,msg,(char*)"sending unicode"); // Test 11 xprintf("TESTING FILTERING CAPABILITIES TO /MarlinTest/Filter/\n"); xprintf("=====================================================\n"); url = CreateURL("Filter"); msg = CreateSoapPriceMessage(namesp,command,url,456.78); errors += DoSendPrice(client,msg,456.78); // Test 12 xprintf("TESTING HIGH SPEED QUEUE TO /MarlinTest/Insecure/\n"); xprintf("=================================================\n"); url = CreateURL("Insecure"); errors += DoSendByQueue(client,namesp,command,url); // Test 13 xprintf("TESTING ASYNCHRONEOUS SOAP MESSAGES TO /MarlinTest/Asynchrone/\n"); xprintf("==============================================================\n"); url = CreateURL("Asynchrone"); errors += DoSendAsyncQueue(client,namesp,url); // Waiting for the queue to drain printf("\nWait for last test to complete.\n"); while(client.GetQueueSize()) { Sleep(200); } printf("\n**READY**\n\nType a word and ENTER\n"); // Wait for key to occur // so the messages can be send and debugged :-) WaitForKey(); printf("Stopping the client\n"); client.StopClient(); printf("The client is %s\n",client.GetIsRunning() ? "still running!\n" : "stopped.\n"); // Any error found CString boodschap; int error = client.GetError(&boodschap); if(error) { CString systeemText = GetLastErrorAsString(error); printf("ERROR! Code: %d = %s\nErrortext: %s\n",error,systeemText.GetString(),boodschap.GetString()); } return errors; }
33.044834
114
0.611137
zYg-sys
3310fc883d5290508e50010a44d7806fa2bfeaae
8,092
cpp
C++
rwa2_group_2/src/rwa2_node_mack.cpp
siddharthtelang/ARIAC_Robotics
158bb49edfce650a5c442b48b5df3955e378ea06
[ "MIT" ]
null
null
null
rwa2_group_2/src/rwa2_node_mack.cpp
siddharthtelang/ARIAC_Robotics
158bb49edfce650a5c442b48b5df3955e378ea06
[ "MIT" ]
null
null
null
rwa2_group_2/src/rwa2_node_mack.cpp
siddharthtelang/ARIAC_Robotics
158bb49edfce650a5c442b48b5df3955e378ea06
[ "MIT" ]
2
2022-02-19T01:34:06.000Z
2022-03-06T21:56:50.000Z
// Copyright 2016 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <vector> #include <ros/ros.h> #include <nist_gear/LogicalCameraImage.h> #include <nist_gear/Order.h> #include <nist_gear/Proximity.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/Range.h> #include <std_msgs/Float32.h> #include <std_msgs/String.h> #include <std_srvs/Trigger.h> #include <tf2_ros/transform_listener.h> #include <geometry_msgs/TransformStamped.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> //--needed for tf2::Matrix3x3 /** * @brief Start the competition * Create a service client to /ariac/start_competition */ void start_competition(ros::NodeHandle &node) { // Create a Service client for the correct service, i.e. '/ariac/start_competition'. ros::ServiceClient start_client = node.serviceClient<std_srvs::Trigger>("/ariac/start_competition"); // If it's not already ready, wait for it to be ready. // Calling the Service using the client before the server is ready would fail. if (!start_client.exists()) { ROS_INFO("Waiting for the competition to be ready..."); start_client.waitForExistence(); ROS_INFO("Competition is now ready."); } ROS_INFO("Requesting competition start..."); std_srvs::Trigger srv; // Combination of the "request" and the "response". start_client.call(srv); // Call the start Service. if (!srv.response.success) { // If not successful, print out why. ROS_ERROR_STREAM("Failed to start the competition: " << srv.response.message); } else { ROS_INFO("Competition started!"); } } /** * @brief A simple competition class. * * This class can hold state and provide methods that handle incoming data. * */ class MyCompetitionClass { public: explicit MyCompetitionClass(ros::NodeHandle &node) : current_score_(0) { } /** * @brief Called when a new Message is received on the Topic /ariac/current_score * * This function sets the value of the attribute current_score_ * @param msg Message used to set the state of the competition. */ void current_score_callback(const std_msgs::Float32::ConstPtr &msg) { if (msg->data != current_score_) { ROS_INFO_STREAM("Score: " << msg->data); } current_score_ = msg->data; } /** * @brief Called when a new Message is received on /ariac/competition_state * * This function sets the state of the competition to 'done'. * @param msg Message used to set the state of the competition. */ void competition_state_callback(const std_msgs::String::ConstPtr &msg) { if (msg->data == "done" && competition_state_ != "done") { ROS_INFO("Competition ended."); } competition_state_ = msg->data; } /** * @brief Called when a new Message is received on the Topic /ariac/orders * * This function adds the Message to received_orders_ * * @param msg Message containing information on the order. */ void order_callback(const nist_gear::Order::ConstPtr &msg) { ROS_INFO_STREAM("Received order:\n" << *msg); received_orders_.push_back(*msg); } /** * @brief Called when a new Message is received on the Topic /ariac/logical_camera_x * * This function reports the number of objects detected by a logical camera. * * @param msg Message containing information on objects detected by the camera. */ // void logical_camera_callback(const nist_gear::LogicalCameraImage::ConstPtr & image_msg, int cam_idx){ // ROS_INFO_STREAM(cam_idx); // } void logical_camera_callback( const nist_gear::LogicalCameraImage::Ptr &msg) { ROS_INFO_STREAM("Logical camera: '" << msg->models.size()); // msg->models. for (int i = 0; i < msg->models.size(); i++) { ROS_INFO_STREAM("Model = " << msg->models[i].type << "\nPose = " << msg->models[i].pose << "\n"); } } /** * @brief Called when a new Message is received on the Topic /ariac/break_beam_x_change * * This function reports when an object crossed the beam. * * @param msg Message of Boolean type returning true if an object crossed the beam. */ void break_beam_callback(const nist_gear::Proximity::ConstPtr &msg) { if (msg->object_detected) // If there is an object in proximity. ROS_WARN("Break beam triggered."); } void proximity_sensor_callback(const sensor_msgs::Range::ConstPtr &msg) { if ((msg->max_range - msg->range) > 0.01) { // If there is an object in proximity. ROS_INFO_THROTTLE(1, "Proximity sensor sees something."); } } void laser_profiler_callback(const sensor_msgs::LaserScan::ConstPtr &msg) { size_t number_of_valid_ranges = std::count_if( msg->ranges.begin(), msg->ranges.end(), [](const float f) { return std::isfinite(f); }); if (number_of_valid_ranges > 0) { ROS_INFO_THROTTLE(5, "Laser profiler sees something."); } } private: std::string competition_state_; double current_score_; std::vector<nist_gear::Order> received_orders_; // const nist_gear::LogicalCameraImage camera_msg_; // std::vector<nist_gear::Model_<std::allocator<void>>, std::allocator<nist_gear::Model_<std::allocator<void>>>> = camera_msg_; // const nist_gear::LogicalCameraImage::Ptr camera_msg_; }; int main(int argc, char **argv) { // Last argument is the default name of the node. ros::init(argc, argv, "ariac_example_node"); ros::NodeHandle node; // Instance of custom class from above. MyCompetitionClass comp_class(node); // Subscribe to the '/ariac/current_score' Topic. ros::Subscriber current_score_subscriber = node.subscribe( "/ariac/current_score", 10, &MyCompetitionClass::current_score_callback, &comp_class); // Subscribe to the '/ariac/competition_state' Topic. ros::Subscriber competition_state_subscriber = node.subscribe( "/ariac/competition_state", 10, &MyCompetitionClass::competition_state_callback, &comp_class); // Subscribe to the '/ariac/orders' Topic. ros::Subscriber orders_subscriber = node.subscribe( "/ariac/orders", 10, &MyCompetitionClass::order_callback, &comp_class); // Subscribe to the '/ariac/range_finder_0' Topic. //ros::Subscriber proximity_sensor_subscriber = node.subscribe( // "/ariac/range_finder_0", // 10, // &MyCompetitionClass::proximity_sensor_callback, // &comp_class); // Subscribe to the '/ariac/breakbeam_0_change' Topic. ros::Subscriber break_beam_subscriber = node.subscribe( "/ariac/breakbeam_0_change", 10, &MyCompetitionClass::break_beam_callback, &comp_class); // Subscribe to the '/ariac/logical_camera_12' Topic. ros::Subscriber logical_camera_subscriber = node.subscribe( "/ariac/logical_camera_12", 10, &MyCompetitionClass::logical_camera_callback, &comp_class); // int a = 12; // ros::Subscriber logical_camera_subscriber = node.subscribe<nist_gear::LogicalCameraImage> ("/ariac/logical_camera_12", 10,boost::bind(&MyCompetitionClass::logical_camera_callback, &comp_class, _1, 12)); // Subscribe to the '/ariac/laser_profiler_0' Topic. // ros::Subscriber laser_profiler_subscriber = node.subscribe( // "/ariac/laser_profiler_0", 10, &MyCompetitionClass::laser_profiler_callback, &comp_class); ROS_INFO("Setup complete."); start_competition(node); ros::spin(); // This executes callbacks on new data until ctrl-c. // while(1) { // MyCompetitionClass.sort() // MyCompetitionClass.PrintData() // } return 0; }
32.111111
207
0.700445
siddharthtelang
33129146cb1044846470f9ed6329c2a1e51be0a9
3,522
cpp
C++
PrettyEngine/src/engine/Networking/Client.cpp
cristi191096/Pretty_Engine
53a5d305b3de5786223e3ad6775199dbc7b5e90c
[ "Apache-2.0" ]
null
null
null
PrettyEngine/src/engine/Networking/Client.cpp
cristi191096/Pretty_Engine
53a5d305b3de5786223e3ad6775199dbc7b5e90c
[ "Apache-2.0" ]
null
null
null
PrettyEngine/src/engine/Networking/Client.cpp
cristi191096/Pretty_Engine
53a5d305b3de5786223e3ad6775199dbc7b5e90c
[ "Apache-2.0" ]
1
2021-04-16T09:10:46.000Z
2021-04-16T09:10:46.000Z
#include "pepch.h" #include "Client.h" namespace PrettyEngine { Client::Client(bool isHost) : m_IsHost(isHost) { if (isHost) { m_Address.host = ENET_HOST_ANY; m_Address.port = 1234; m_Host = enet_host_create(&m_Address, 32, 2, 0, 0); if (m_Host == NULL) PE_ERROR("Host could not be initialised!"); } else { m_Host = enet_host_create(NULL, 1, 2, 0, 0); if (m_Host == NULL) PE_ERROR("Host could not be initialised!"); enet_address_set_host(&m_Address, "localhost"); m_Address.port = 1234; m_Peer = enet_host_connect(m_Host, &m_Address, 2, 0); if (m_Peer == NULL) PE_ERROR("No available peers for initializing an ENet connection!"); } } Client::~Client() { } void Client::SendData(void* data, size_t size) { if (!m_IsHost) { m_PlayerConnected = true; m_Data = enet_packet_create(data, size, ENET_PACKET_FLAG_RELIABLE); enet_peer_send(m_Peer, 0, m_Data); } else { m_Data = enet_packet_create(data, size, ENET_PACKET_FLAG_RELIABLE); enet_host_broadcast(m_Host, 0, m_Data); } while (enet_host_service(m_Host, &m_Event, 0) > 0) { if (m_IsHost) { //String data = "someClient"; int packetType = 0; switch (m_Event.type) { case ENET_EVENT_TYPE_CONNECT: m_PlayerConnected = true; m_ConnectedClients++; id = enet_packet_create(&m_ConnectedClients, sizeof(int), ENET_PACKET_FLAG_RELIABLE); enet_peer_send(m_Event.peer, 0, id); break; case ENET_EVENT_TYPE_RECEIVE: if (m_Event.packet && m_Event.packet->data) memcpy(&packetType, m_Event.packet->data, sizeof(int)); if (packetType == PacketType::LEVELINFO) { LevelInfo* tempInfo = new LevelInfo; memcpy(tempInfo, m_Event.packet->data, sizeof(LevelInfo)); if (!tempInfo->isFromHost) { memcpy(&m_LevelData, m_Event.packet->data, sizeof(LevelInfo)); } } if (packetType == PacketType::TRANSFORM) { TransformData* tempTransform = new TransformData; memcpy(tempTransform, m_Event.packet->data, sizeof(TransformData)); if (!tempTransform->isFromHost) { memcpy(&m_TransformData, m_Event.packet->data, sizeof(TransformData)); } } break; default: break; } } else { int packetType = 0; //m_PlayerConnected = true; //enet_peer_send(m_Peer, 0, m_Data); switch (m_Event.type) { case ENET_EVENT_TYPE_CONNECT: break; case ENET_EVENT_TYPE_RECEIVE: if (m_Event.packet && m_Event.packet->dataLength == sizeof(int)) { memcpy(&m_ClientID, m_Event.packet->data, sizeof(int)); } if (m_Event.packet && m_Event.packet->data) memcpy(&packetType, m_Event.packet->data, sizeof(int)); if (packetType == PacketType::LEVELINFO) { LevelInfo* tempInfo = new LevelInfo; memcpy(tempInfo, m_Event.packet->data, sizeof(LevelInfo)); if (tempInfo->isFromHost && tempInfo->clientID != m_ClientID) { memcpy(&m_LevelData, m_Event.packet->data, sizeof(LevelInfo)); } } if (packetType == PacketType::TRANSFORM) { TransformData* tempTransform = new TransformData; memcpy(tempTransform, m_Event.packet->data, sizeof(TransformData)); if (tempTransform->isFromHost && tempTransform->clientID != m_ClientID) memcpy(&m_TransformData, m_Event.packet->data, sizeof(TransformData)); } break; default: break; } } } } }
23.797297
90
0.638842
cristi191096
33135cc07e32c6a3d5c92fe5b3273e2978f26d72
2,387
cpp
C++
src/piper-token-to-cst.cpp
PiperLang/piper
7b2dc57793fca7f3bb153e399e36b0ad0ec33ca1
[ "MIT" ]
null
null
null
src/piper-token-to-cst.cpp
PiperLang/piper
7b2dc57793fca7f3bb153e399e36b0ad0ec33ca1
[ "MIT" ]
null
null
null
src/piper-token-to-cst.cpp
PiperLang/piper
7b2dc57793fca7f3bb153e399e36b0ad0ec33ca1
[ "MIT" ]
null
null
null
#include <array> #include <cassert> #include <cerrno> #include <cstring> #include <vector> #include <iostream> #include <scanner.hpp> #include <tokentype.hpp> #define INIT_BUFFER_SIZE 1024 int main(int argc, char *argv[]) { std::freopen(nullptr, "rb", stdin); if (std::ferror(stdin)) { throw std::runtime_error(std::strerror(errno)); } std::size_t len; std::array<char, INIT_BUFFER_SIZE> buf; std::vector<char> input; while ((len = std::fread(buf.data(), sizeof(buf[0]), buf.size(), stdin)) > 0) { if (std::ferror(stdin) && !std::feof(stdin)) { throw std::runtime_error(std::strerror(errno)); } input.insert(input.end(), buf.data(), buf.data() + len); } int idx = 0; assert(input.at(idx++) == 'P'); assert(input.at(idx++) == 'P'); assert(input.at(idx++) == 'R'); assert(input.at(idx++) == 'A'); assert(input.at(idx++) == 'L'); assert(input.at(idx++) == 'C'); assert(input.at(idx++) == 'F'); assert(input.at(idx++) == 'T'); assert(input.at(idx++) == 'T'); assert(input.at(idx++) == 0); int string_count = (int)input.at(idx++); std::cout << "String Count: " << string_count << std::endl; for (int i = 0; i < string_count; i++) { int single_string_length = (int)input.at(idx++); std::cout << " Single string (" << single_string_length << "): "; for (int p = 0; p < single_string_length; p++) { std::cout << input.at(idx++); } std::cout << std::endl; } while (true) { bool is_at_end = false; uint8_t token_type = input.at(idx++); uint8_t token_line = input.at(idx++); uint8_t token_column = input.at(idx++); std::cout << "(" << std::hex << (int)token_type << "): " << piper::Scanner::getTokenName(static_cast<piper::TokenType>(token_type)) << std::endl; switch (token_type) { case piper::TokenType::TOKEN_EOF: is_at_end = true; break; case piper::TokenType::FORMAT_STRING: case piper::TokenType::IDENTIFIER: case piper::TokenType::NUMBER: case piper::TokenType::STRING: idx++; break; } if (is_at_end) break; } // use input vector here }
27.125
86
0.528697
PiperLang
33151018fbd0bfd906ad5aacba9d5df3dcf8857c
2,077
cpp
C++
source/CompilerState.cpp
Time0o/CPPBind
88dafba49d366fd96f9d7367dd7c20ead5fac20d
[ "MIT" ]
3
2021-04-16T21:14:51.000Z
2022-03-07T18:42:35.000Z
source/CompilerState.cpp
Time0o/CPPBind
88dafba49d366fd96f9d7367dd7c20ead5fac20d
[ "MIT" ]
2
2020-12-21T14:47:25.000Z
2021-09-23T19:10:31.000Z
source/CompilerState.cpp
Time0o/CPPBind
88dafba49d366fd96f9d7367dd7c20ead5fac20d
[ "MIT" ]
null
null
null
#include <cassert> #include <string> #include "boost/filesystem.hpp" #include "clang/Basic/SourceLocation.h" #include "CompilerState.hpp" namespace fs = boost::filesystem; namespace cppbind { void CompilerStateRegistry::updateFileEntry(std::string const &File) { fs::path Path(File); FilesByStem_.emplace(Path.stem().string(), fs::canonical(Path).string()); } void CompilerStateRegistry::updateCompilerInstance(clang::CompilerInstance const &CI) { CI_ = CI; } void CompilerStateRegistry::updateFile(std::string const &File) { fs::path Path(File); auto Stem(Path.stem().string()); Stem = Stem.substr(0, Stem.rfind("_tmp")); TmpFile_ = File; auto It(FilesByStem_.find(Stem)); assert(It != FilesByStem_.end()); File_ = It->second; TI_->clearRecords(); TI_->clearEnums(); } std::string CompilerStateRegistry::currentFile(InputFile IF, bool Relative) const { std::optional<std::string> File; switch (IF) { case ORIG_INPUT_FILE: File = File_; break; case TMP_INPUT_FILE: File = TmpFile_; break; default: break; } assert(File); fs::path Path(*File); if (Relative) Path = Path.filename(); return Path.string(); } bool CompilerStateRegistry::inCurrentFile(InputFile IF, clang::SourceLocation const &Loc) const { auto &SM(ASTContext().getSourceManager()); auto Filename(SM.getFilename(Loc)); if (Filename.empty()) return false; fs::path Path(Filename.str()); auto Canonical(fs::canonical(Path).string()); if (IF == ORIG_INPUT_FILE || IF == COMPLETE_INPUT_FILE) { if (Canonical == currentFile(ORIG_INPUT_FILE)) return true; } if (IF == TMP_INPUT_FILE || IF == COMPLETE_INPUT_FILE) { if (Canonical == currentFile(TMP_INPUT_FILE)) return true; } return false; } clang::CompilerInstance const & CompilerStateRegistry::operator*() const { assert(CI_); return CI_->get(); } clang::CompilerInstance const * CompilerStateRegistry::operator->() const { assert(CI_); return &CI_->get(); } } // namespace cppbind
18.219298
80
0.675975
Time0o