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
5c28e1034573a00ce52b97665327d13d08dae8f1
126
cpp
C++
chapter_4/ex_4.12.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
chapter_4/ex_4.12.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
chapter_4/ex_4.12.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
/** * i != (j < k) * i != (true/false) * i != (0/1) * It means checking if i is 1 or 0 which is resulted from j < k */
15.75
64
0.484127
YasserKa
5c2cb34533524ee582232ac99c94f7525ef3a6d7
7,536
cpp
C++
winnie1/new_delete_example/new_delete.cpp
r-lyeh/malloc-survey
6da5aca6aa2720d64bff709c111a5d8a5fa7a1be
[ "Zlib" ]
16
2015-06-26T20:58:23.000Z
2017-11-05T09:46:45.000Z
winnie1/new_delete_example/new_delete.cpp
r-lyeh/test-allocators
6da5aca6aa2720d64bff709c111a5d8a5fa7a1be
[ "Zlib" ]
1
2015-07-22T22:48:56.000Z
2015-07-22T22:48:56.000Z
winnie1/new_delete_example/new_delete.cpp
r-lyeh/test-allocators
6da5aca6aa2720d64bff709c111a5d8a5fa7a1be
[ "Zlib" ]
2
2015-09-26T17:40:20.000Z
2016-06-23T17:15:23.000Z
#include "winnie_alloc.h" #include "new_delete.h" #if defined(NDEBUG) && OP_NEW_DEBUG #undef NDEBUG #pragma message ("warning: NDEBUG and OP_NEW_DEBUG do not match. forcing #undef NDEBUG") #endif #include "assert.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <new> #include "string.h" #if OP_NEW_USE_WINNIE_ALLOC #define OP_NEW_DEBUG_BREAK __asm int 3 //#define OP_NEW_DEBUG_BREAK DebugBreak() namespace { #if OP_NEW_DEBUG //begin of allocated block linked list //should be initialized at compile-time, before any new/delete operations. DebugHeader fake_header = { &fake_header, &fake_header }; #endif #if OP_NEW_MULTITHREADING CRITICAL_SECTION OperatorNewCriticalSection; bool OperatorNewCriticalSectionInitialized = false; struct LockOpNew { LockOpNew() { if (OperatorNewCriticalSectionInitialized) //allow one thread entering before initialization EnterCriticalSection(&OperatorNewCriticalSection); } ~LockOpNew() { if (OperatorNewCriticalSectionInitialized) //allow one thread entering before initialization LeaveCriticalSection(&OperatorNewCriticalSection); } }; #endif //OP_NEW_MULTITHREADING const unsigned guard_begin = 0x12345678; const unsigned guard_end = 0x87654321; const unsigned guard_after_delete = 0xDeadBeaf; unsigned op_new_alloc_num = 0; DWORD thread_id = 0; void *OpNewAlloc(size_t size) { size_t real_size = size; #if OP_NEW_DEBUG #if (!OP_NEW_MULTITHREADING) //assert, that only one thread owns new/delete DWORD cur_thread_id = GetCurrentThreadId(); if (thread_id) { if (thread_id != cur_thread_id) OP_NEW_ASSERT( !"Allocation from different threads detected in single thread mode." "You should enable OP_NEW_MULTITHREADING from new_detete_config.h"); } else { thread_id = cur_thread_id; } #endif //!OP_NEW_MULTITHREADING real_size+= sizeof(guard_begin) + sizeof(guard_end) + sizeof(DebugHeader); unsigned block_num; #endif //OP_NEW_DEBUG void *p; { #if OP_NEW_MULTITHREADING LockOpNew lock; #if OP_NEW_DEBUG DWORD cur_thread_id = GetCurrentThreadId(); if (thread_id) { if (thread_id != cur_thread_id && !OperatorNewCriticalSectionInitialized) OP_NEW_ASSERT( !"Allocation from different threads detected, but OperatorNewCriticalSectionInit was not called." "You should call OperatorNewCriticalSectionInit before any allocations from any second thread."); } else { thread_id = cur_thread_id; } #endif //OP_NEW_DEBUG #endif //OP_NEW_MULTITHREADING p= Winnie::Alloc(real_size); #if OP_NEW_DEBUG block_num = ++op_new_alloc_num; { DebugHeader *ph = (DebugHeader *)p; ph->prev = &fake_header; ph->next = fake_header.next; fake_header.next->prev = ph; fake_header.next= ph; } #endif } //end of multithread protection #if OP_NEW_DEBUG if (block_num == op_new_break_alloc) { OP_NEW_DEBUG_BREAK; } DebugHeader *ph = (DebugHeader *)p; ph->block_num = block_num; ph->size = size; unsigned *p_guard_begin = (unsigned *)(ph+1); *p_guard_begin = guard_begin; void *p_user_memory= (p_guard_begin + 1); unsigned *p_guard_end = (unsigned *)((char*)p_user_memory + size); *p_guard_end = guard_end; memset(p_user_memory, 0xCC, size); p = p_user_memory; #endif return p; } void OpNewFree(void *p_user_memory) { void *p = p_user_memory; #if OP_NEW_DEBUG OpNewAssertIsValid(p_user_memory); DebugHeader *ph = OpNewGetHeader(p_user_memory); unsigned *p_guard_begin = (unsigned *)p_user_memory - 1; *p_guard_begin = guard_after_delete; p= ph; #endif { #if OP_NEW_MULTITHREADING LockOpNew lock; #endif #if OP_NEW_DEBUG ph->prev->next = ph->next; ph->next->prev = ph->prev; memset(ph, 0xDD, ph->size + sizeof(DebugHeader)+2*sizeof(unsigned)); #endif Winnie::Free(p); } //end of multithread protection } } //namespace unsigned op_new_break_alloc = 0; void OperatorNewCriticalSectionInit() { #if OP_NEW_MULTITHREADING if (!OperatorNewCriticalSectionInitialized) { InitializeCriticalSection(&OperatorNewCriticalSection); OperatorNewCriticalSectionInitialized = true; } #endif } #if OP_NEW_DEBUG void OpNewAssertIsValid(void *p_user_memory) { OP_NEW_ASSERT(p_user_memory); unsigned *p_guard_begin = (unsigned *)p_user_memory - 1; DebugHeader *ph = (DebugHeader *)p_guard_begin-1; size_t size =ph->size; unsigned *p_guard_end = (unsigned *)((char *)p_user_memory + size); if (*p_guard_begin == guard_after_delete) { OP_NEW_ASSERT(!"possibly this block was already deleted"); } if (*p_guard_begin != guard_begin) { if (*(p_guard_begin-1) == guard_begin) //MSVC place size of array in first 4 bytes { OP_NEW_ASSERT( !"likely, applying delete to memory, allocated by new TYPE[], where TYPE has non-trivial destructor (use delete[])"); } OP_NEW_ASSERT(!"deletion of invalid block or non-block, heap-buffer underrun, or other error"); } if (*p_guard_end != guard_end) { OP_NEW_ASSERT(!"possibly heap-buffer overrun"); } } void *OpNewBegin() { return OpNewGetHeadersBlock(fake_header.next); } void *OpNewEnd() { return OpNewGetHeadersBlock(&fake_header); } void *OpNewNextBlock(void *p_user_memory) { return OpNewGetHeadersBlock(OpNewGetHeader(p_user_memory)->next); } void *OpNewGetBlockPointer(void *p) { if (!p) return NULL; for ( void *pum = OpNewBegin(), *p_end = OpNewEnd(); pum != p_end; pum = OpNewNextBlock(pum)) { DebugHeader *ph = OpNewGetHeader(pum); if ( p >= pum && p < ((char*)pum + ph->size)) return pum; } return NULL; } void OpNewValidateHeap() { for ( void *pum = OpNewBegin(), *p_end = OpNewEnd(); pum != p_end; pum = OpNewNextBlock(pum)) { OpNewAssertIsValid(pum); } } void *OpNewGetHeadersBlock(DebugHeader *p_header) { void *p_user_memory = (unsigned*)(p_header+1)+1; return p_user_memory; } DebugHeader *OpNewGetHeader(void *p_user_memory) { OpNewAssertIsValid(p_user_memory); return (DebugHeader*)((unsigned*)p_user_memory-1)-1; } #endif //OP_NEW_DEBUG void *operator new(size_t size) { void *p = OpNewAlloc(size); #if OP_NEW_DEBUG OpNewGetHeader(p)->is_array = false; #endif return p; } void *operator new[](size_t size) { void *p = OpNewAlloc(size); #if OP_NEW_DEBUG OpNewGetHeader(p)->is_array = true; #endif return p; } void operator delete(void *p) throw() { if (p) { #if OP_NEW_DEBUG int is_array= OpNewGetHeader(p)->is_array; #endif OpNewFree(p); #if OP_NEW_DEBUG OP_NEW_ASSERT(!is_array && "what allocated with new[], should be released by delete[], not delete"); #endif } } void operator delete[](void *p)throw() { if (p) { #if OP_NEW_DEBUG int is_array= OpNewGetHeader(p)->is_array; #endif OpNewFree(p); #if OP_NEW_DEBUG OP_NEW_ASSERT(is_array && "what allocated with new, should be released by delete, not delete[]"); #endif } } void *operator new(size_t size, const std::nothrow_t&) throw() { try { void *p = OpNewAlloc(size); #if OP_NEW_DEBUG OpNewGetHeader(p)->is_array = false; #endif return p; } catch (...) { return NULL; } } void *operator new[](size_t size, const std::nothrow_t&) throw() { try { void *p = OpNewAlloc(size); #if OP_NEW_DEBUG OpNewGetHeader(p)->is_array = true; #endif return p; } catch (...) { return NULL; } } #endif //OP_NEW_USE_WINNIE_ALLOC
20.096
126
0.697452
r-lyeh
5c3215dc46c4abbfc288ff7b72f4d89b5f9fd65d
1,718
cpp
C++
08.cpp
0xmanjoos/cpp_collection
306164ed398410674a814839f510d7b6c85a222d
[ "MIT" ]
1
2021-01-24T01:48:57.000Z
2021-01-24T01:48:57.000Z
08.cpp
0xmanjoos/cpp_collection
306164ed398410674a814839f510d7b6c85a222d
[ "MIT" ]
null
null
null
08.cpp
0xmanjoos/cpp_collection
306164ed398410674a814839f510d7b6c85a222d
[ "MIT" ]
null
null
null
#include <iostream> // linked lists hee hee ha fucking kill me // SOURCE: https://www.geeksforgeeks.org/linked-list-set-1-introduction/ // modified a bit class Node { public: // int data and pointer to class node? int data; Node* next; // pointer to the next node // example: second->data=2; second->next = third; }; // function for printing out the linked list void printl(Node* n) { // Node* n == the pointer to the next node within the list.. probably... while (n != NULL) { std::cout<< n->data << std::endl; // print the value of data n = n -> next; // update the value of n? } } int main() { // init maybe? idk these fuckers dont explain Node* head = NULL; Node* second = NULL; Node* third = NULL; // allocate 3 new nodes in the heap head = new Node(); second = new Node(); third = new Node(); /* Three blocks have been allocated dynamically. We have pointers to these three blocks as head, second and third head second third | | | | | | +---+-----+ +----+----+ +----+----+ | # | # | | # | # | | # | # | +---+-----+ +----+----+ +----+----+ represents any random value. Data is random because we haven’t assigned anything yet */ head -> data = 1; // assign data in first node head -> next = second; // Link first node with // the second node second -> data = 2; // int data, the value of data in this node :) second -> next = third; // link the next node, which is third third -> data = 3; third -> next = NULL; printl(head); return 0; }
27.709677
95
0.531432
0xmanjoos
5c36e5b32504023f0f525737ac7a754118636085
5,414
cc
C++
src/nixtag.cc
JiriVanek/nix-mx
1e8fec06d4aae67116d5e3b212784f6606dbaeaf
[ "BSD-3-Clause" ]
null
null
null
src/nixtag.cc
JiriVanek/nix-mx
1e8fec06d4aae67116d5e3b212784f6606dbaeaf
[ "BSD-3-Clause" ]
null
null
null
src/nixtag.cc
JiriVanek/nix-mx
1e8fec06d4aae67116d5e3b212784f6606dbaeaf
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2016, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include "nixtag.h" #include "mex.h" #include <nix.hpp> #include "arguments.h" #include "filters.h" #include "handle.h" #include "mkarray.h" #include "struct.h" namespace nixtag { mxArray *describe(const nix::Tag &tag) { struct_builder sb({ 1 }, { "id", "type", "name", "definition", "position", "extent", "units" }); sb.set(tag.id()); sb.set(tag.type()); sb.set(tag.name()); sb.set(tag.definition()); sb.set(tag.position()); sb.set(tag.extent()); sb.set(tag.units()); return sb.array(); } void addReference(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); currObj.addReference(input.str(2)); } void addReferences(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::DataArray> curr = input.entity_vec<nix::DataArray>(2); currObj.references(curr); } void addSource(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); currObj.addSource(input.str(2)); } void addSources(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::Source> curr = input.entity_vec<nix::Source>(2); currObj.sources(curr); } void createFeature(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::Feature newFeat = currObj.createFeature(input.str(2), input.ltype(3)); output.set(0, handle(newFeat)); } void openReferenceIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); output.set(0, currObj.getReference(idx)); } void openFeatureIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); output.set(0, currObj.getFeature(idx)); } void openSourceIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); output.set(0, currObj.getSource(idx)); } void compare(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::Tag other = input.entity<nix::Tag>(2); output.set(0, currObj.compare(other)); } void sourcesFiltered(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::Source> res = filterFullEntity<nix::Source>(input, [currObj](const nix::util::Filter<nix::Source>::type &filter) { return currObj.sources(filter); }); output.set(0, res); } void referencesFiltered(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::DataArray> res = filterFullEntity<nix::DataArray>(input, [currObj](const nix::util::Filter<nix::DataArray>::type &filter) { return currObj.references(filter); }); output.set(0, res); } void featuresFiltered(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::Feature> res = filterEntity<nix::Feature>(input, [currObj](const nix::util::Filter<nix::Feature>::type &filter) { return currObj.features(filter); }); output.set(0, res); } void retrieveData(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::string name_id = input.str(2); mxArray *data = make_mx_array_from_ds(currObj.retrieveData(name_id)); output.set(0, data); } void retrieveDataIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); mxArray *data = make_mx_array_from_ds(currObj.retrieveData(idx)); output.set(0, data); } void retrieveFeatureData(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::string name_id = input.str(2); mxArray *data = make_mx_array_from_ds(currObj.retrieveFeatureData(name_id)); output.set(0, data); } void retrieveFeatureDataIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); mxArray *data = make_mx_array_from_ds(currObj.retrieveFeatureData(idx)); output.set(0, data); } } // namespace nixtag
36.093333
111
0.593831
JiriVanek
5c388318a3c9af8911eed5f695c3eb46da682f06
459
hpp
C++
Paper/Group.hpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
20
2016-12-13T22:34:35.000Z
2021-09-20T12:44:56.000Z
Paper/Group.hpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
null
null
null
Paper/Group.hpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
null
null
null
#ifndef PAPER_GROUP_HPP #define PAPER_GROUP_HPP #include <Paper/Item.hpp> #include <Paper/Constants.hpp> namespace paper { class Document; class STICK_API Group : public Item { friend class Item; public: static constexpr EntityType itemType = EntityType::Group; Group(); void setClipped(bool _b); bool isClipped() const; Group clone() const; }; } #endif //PAPER_GROUP_HPP
14.806452
65
0.627451
mokafolio
5c39d404f1e2252e54a71db14346b6dbd5fa7b4d
3,560
cpp
C++
flextyper/test/tst_stat.cpp
wassermanlab/OpenFlexTyper_restore
f599011a8f856bd81e73e5472d50980b4695055c
[ "MIT" ]
1
2020-02-20T20:01:38.000Z
2020-02-20T20:01:38.000Z
flextyper/test/tst_stat.cpp
wassermanlab/OpenFlexTyper_restore
f599011a8f856bd81e73e5472d50980b4695055c
[ "MIT" ]
null
null
null
flextyper/test/tst_stat.cpp
wassermanlab/OpenFlexTyper_restore
f599011a8f856bd81e73e5472d50980b4695055c
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////// /// /// Copyright (c) 2019, Wasserman lab /// /// FILE tst_stats.cpp /// /// DESCRIPTION This file contains tests for the stats class /// /// Initial version @ Godfrain Jacques Kounkou /// //////////////////////////////////////////////////////////////////////// #include <gtest/gtest.h> #include "stats.cpp" #include <experimental/filesystem> using namespace std; using namespace ft; namespace fs = experimental::filesystem; namespace ft { class TestStats : public ::testing::Test { protected: virtual void SetUp() { ofstream output_expected("output_expected.log"); if (output_expected.is_open()) { output_expected << "ATTATCTATCTACTACTTCTATCTACTCTA : 3\n"; output_expected << "CTAGCATCGATCGATCGATCGATCGACTGC : 5\n"; output_expected << "CTTTTTTTTATCTACTTACTATCTTTTTTT : 1\n"; output_expected << "GGGGCTGACTACGTAGCTACGATCGATCGT : 4\n"; } output_expected.close(); } virtual void TeadDown() { // std::remove("output_expected.log"); } public: bool compareFiles(const string& file1, const string& file2) { ifstream f1(file1), f2(file2); string content1, content2; string line; if (f1.is_open()) { while (getline(f1, line)) content1 += line; } f1.close(); line.clear(); if (f2.is_open()) { while (getline(f2, line)) content2 += line; } f2.close(); return content1 == content2; } public: Stats _stats; }; #define TEST_DESCRIPTION(desc) RecordProperty("description", desc) //====================================================================== TEST_F(TestStats, printKmerCountToFile) { TEST_DESCRIPTION("This test will chech that the function creates an ouput file"); map<string, uint> counter {{ "ATTATCTATCTACTACTTCTATCTACTCTA", 3}, { "GGGGCTGACTACGTAGCTACGATCGATCGT", 4}, { "CTTTTTTTTATCTACTTACTATCTTTTTTT", 1}, { "CTAGCATCGATCGATCGATCGATCGACTGC", 5}}; fs::path output ("output.log"); _stats.printKmerCountToFile(output, counter); EXPECT_NO_FATAL_FAILURE(); EXPECT_NO_THROW(); EXPECT_TRUE(fs::exists(output)); } //====================================================================== TEST_F(TestStats, printKmerCountToFileEmpty) { TEST_DESCRIPTION("This test will chech that the function creates an ouput file"); map<string, uint> counter {}; fs::path output ("output.log"); _stats.printKmerCountToFile(output, counter); EXPECT_NO_FATAL_FAILURE(); EXPECT_NO_THROW(); EXPECT_FALSE(fs::exists(output)); } //====================================================================== TEST_F(TestStats, printKmerCountToFileCompareContent) { TEST_DESCRIPTION("This test will chech that the function creates an ouput file"); map<string, uint> counter {{ "ATTATCTATCTACTACTTCTATCTACTCTA", 3}, { "GGGGCTGACTACGTAGCTACGATCGATCGT", 4}, { "CTTTTTTTTATCTACTTACTATCTTTTTTT", 1}, { "CTAGCATCGATCGATCGATCGATCGACTGC", 5}}; fs::path output ("output.log"); fs::path expectedOutpt ("output_expected.log"); _stats.printKmerCountToFile(output, counter); EXPECT_NO_FATAL_FAILURE(); EXPECT_NO_THROW(); EXPECT_TRUE(compareFiles(output, expectedOutpt)); } }
28.48
85
0.562079
wassermanlab
5c39de7473c67da99a4e3e6af7b76cfc4f6b483d
1,328
cpp
C++
dependencies/PyMesh/tools/Wires/Parameters/VertexCustomOffsetParameter.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
5
2018-06-04T19:52:02.000Z
2022-01-22T09:04:00.000Z
dependencies/PyMesh/tools/Wires/Parameters/VertexCustomOffsetParameter.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
null
null
null
dependencies/PyMesh/tools/Wires/Parameters/VertexCustomOffsetParameter.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
null
null
null
/* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */ #include "VertexCustomOffsetParameter.h" using namespace PyMesh; VertexCustomOffsetParameter::VertexCustomOffsetParameter( WireNetwork::Ptr wire_network, const MatrixFr& offset) : PatternParameter(wire_network), m_derivative(offset) { } void VertexCustomOffsetParameter::apply( VectorF& results, const Variables& vars) { const size_t dim = m_wire_network->get_dim(); const size_t num_vertices = m_wire_network->get_num_vertices(); const size_t roi_size = m_roi.size(); assert(results.size() == dim * num_vertices); if (m_formula != "") evaluate_formula(vars); for (size_t i=0; i<roi_size; i++) { size_t v_idx = m_roi[i]; assert(v_idx < num_vertices); results.segment(v_idx*dim, dim) += m_derivative.row(v_idx) * m_value; } } MatrixFr VertexCustomOffsetParameter::compute_derivative() const { const size_t num_vertices = m_wire_network->get_num_vertices(); const size_t dim = m_wire_network->get_dim(); const size_t roi_size = m_roi.size(); MatrixFr derivative = MatrixFr::Zero(num_vertices, dim); for (size_t i=0; i<roi_size; i++) { size_t v_idx = m_roi[i]; derivative.row(v_idx) += m_derivative.row(v_idx); } return derivative; }
34.051282
77
0.692771
aprieels
5c3bc9320dc133c5b9595487d4f56053eb4b36f8
2,478
hpp
C++
src/bonefish/dealer/wamp_dealer_registration.hpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
58
2015-08-24T18:43:56.000Z
2022-01-09T00:55:06.000Z
src/bonefish/dealer/wamp_dealer_registration.hpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
47
2015-08-25T11:04:51.000Z
2018-02-28T22:38:12.000Z
src/bonefish/dealer/wamp_dealer_registration.hpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
32
2015-08-25T15:14:45.000Z
2020-03-23T09:35:31.000Z
/** * Copyright (C) 2015 Topology LP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP #define BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP #include <bonefish/identifiers/wamp_registration_id.hpp> #include <bonefish/session/wamp_session.hpp> #include <unordered_set> namespace bonefish { class wamp_dealer_registration { public: wamp_dealer_registration(); wamp_dealer_registration(const std::shared_ptr<wamp_session>& session, const wamp_registration_id& registration_id); ~wamp_dealer_registration(); void set_session(const std::shared_ptr<wamp_session>& session); void set_registration_id(const wamp_registration_id& registration_id); const wamp_registration_id& get_registration_id() const; const std::shared_ptr<wamp_session>& get_session() const; private: std::shared_ptr<wamp_session> m_session; wamp_registration_id m_registration_id; }; inline wamp_dealer_registration::wamp_dealer_registration() : m_session() , m_registration_id() { } inline wamp_dealer_registration::wamp_dealer_registration(const std::shared_ptr<wamp_session>& session, const wamp_registration_id& registration_id) : m_session(session) , m_registration_id(registration_id) { } inline wamp_dealer_registration::~wamp_dealer_registration() { } inline void wamp_dealer_registration::set_session(const std::shared_ptr<wamp_session>& session) { m_session = session; } inline void wamp_dealer_registration::set_registration_id(const wamp_registration_id& registration_id) { m_registration_id = registration_id; } inline const std::shared_ptr<wamp_session>& wamp_dealer_registration::get_session() const { return m_session; } inline const wamp_registration_id& wamp_dealer_registration::get_registration_id() const { return m_registration_id; } } // namespace bonefish #endif // BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP
28.813953
103
0.778854
aiwc
5c3d62f0e2a30326c8f0458fe39c3355f406e1a8
983
cc
C++
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
zoranzhao/NoSDSE
0e3148572e7cdf3a2d012c95c81863864da236d6
[ "MIT" ]
3
2019-01-26T20:35:47.000Z
2019-07-18T22:09:22.000Z
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
zoranzhao/NoSSim
7b0e9edde0fe19f83d7aaa946fd580a6d9dab978
[ "BSD-3-Clause" ]
null
null
null
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
zoranzhao/NoSSim
7b0e9edde0fe19f83d7aaa946fd580a6d9dab978
[ "BSD-3-Clause" ]
3
2017-09-08T22:13:28.000Z
2019-06-29T21:42:53.000Z
#include <iostream> #include <sstream> #include "OmnetIf_pkt.h" OmnetIf_pkt::OmnetIf_pkt() { fileBuffer_arraysize = 0; this->fileBuffer = NULL; } OmnetIf_pkt::~OmnetIf_pkt() { delete [] fileBuffer; } void OmnetIf_pkt::setFileBufferArraySize(unsigned int size) { char *fileBuffer_var2 = (size==0) ? NULL : new char[size]; unsigned int sz = fileBuffer_arraysize < size ? fileBuffer_arraysize : size; for (unsigned int i=0; i<sz; i++) fileBuffer_var2[i] = this->fileBuffer[i]; for (unsigned int i=sz; i<size; i++) fileBuffer_var2[i] = 0; fileBuffer_arraysize = size; delete [] this->fileBuffer; this->fileBuffer = fileBuffer_var2; } unsigned int OmnetIf_pkt::getFileBufferArraySize() const { return fileBuffer_arraysize; } char OmnetIf_pkt::getFileBuffer(unsigned int k) const { return fileBuffer[k]; } void OmnetIf_pkt::setFileBuffer(unsigned int k, char fileBuffer) { this->fileBuffer[k] = fileBuffer; }
20.061224
80
0.690743
zoranzhao
5c3da2baceaccc641b25645c84ef2f97b3d802c2
2,002
cc
C++
RecoTracker/TkNavigation/test/TkMSParameterizationTest.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2020-01-27T15:21:37.000Z
2020-05-11T11:13:18.000Z
RecoTracker/TkNavigation/test/TkMSParameterizationTest.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
8
2020-03-20T23:18:36.000Z
2020-05-27T11:00:06.000Z
RecoTracker/TkNavigation/test/TkMSParameterizationTest.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
3
2019-03-09T13:06:43.000Z
2020-07-03T00:47:30.000Z
#include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "RecoTracker/TkNavigation/interface/TkMSParameterization.h" #include "RecoTracker/Record/interface/TkMSParameterizationRecord.h" class TkMSParameterizationTest final : public edm::EDAnalyzer { public: explicit TkMSParameterizationTest(const edm::ParameterSet&) {} private: void analyze(const edm::Event&, const edm::EventSetup&) override; }; void TkMSParameterizationTest::analyze(const edm::Event&, const edm::EventSetup& iSetup) { using namespace tkMSParameterization; edm::ESHandle<TkMSParameterization> paramH; iSetup.get<TkMSParameterizationRecord>().get(paramH); auto const& msParam = *paramH; // test MSParam { std::cout << "\n\nProduced MSParam" << std::endl; unsigned short f, t; for (auto const& e : msParam()) { std::tie(f, t) = unpackLID(e.first); std::cout << "from/to " << f << "->" << t << std::endl; for (auto const& d : e.second()) { std::cout << d().size() << ' '; } std::cout << std::endl; } int lst[] = {0, 1, 29}; for (auto st : lst) for (int il = 1; il < 5; ++il) { int ll = st + il; if (st == 0 && il == 5) ll = 29; std::cout << "from/to " << st << "->" << ll << std::endl; auto const& d = *msParam.fromTo(st, ll); int lb = 0; for (auto const& ld : d()) { lb++; if (ld().empty()) continue; std::cout << lb << ": "; for (auto const& e : ld()) std::cout << e << ' '; std::cout << std::endl; } } } }; //define this as a plug-in DEFINE_FWK_MODULE(TkMSParameterizationTest);
30.333333
90
0.606394
NTrevisani
5c3f75e171fb117831597306fe89412e84c90c9f
2,204
cpp
C++
iotivity-1.0.1/resource/csdk/security/unittest/svcresourcetest.cpp
gerald-yang/ubuntu-iotivity-demo
17e799e209442bbefb2df846e329c802ee5255f7
[ "Apache-2.0" ]
1,433
2015-04-30T09:26:53.000Z
2022-03-26T12:44:12.000Z
AllJoyn/Samples/OICAdapter/iotivity-1.0.0/resource/csdk/security/unittest/svcresourcetest.cpp
buocnhay/samples-1
ddd614bb5ae595f03811e3dfa15a5d107005d0fc
[ "MIT" ]
530
2015-05-02T09:12:48.000Z
2018-01-03T17:52:01.000Z
AllJoyn/Samples/OICAdapter/iotivity-1.0.0/resource/csdk/security/unittest/svcresourcetest.cpp
buocnhay/samples-1
ddd614bb5ae595f03811e3dfa15a5d107005d0fc
[ "MIT" ]
1,878
2015-04-30T04:18:57.000Z
2022-03-15T16:51:17.000Z
//****************************************************************** // // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include "gtest/gtest.h" #include <pwd.h> #include <grp.h> #include <linux/limits.h> #include <sys/stat.h> #include "ocstack.h" #include "oic_malloc.h" #include "cJSON.h" #include "cainterface.h" #include "secureresourcemanager.h" #include "securevirtualresourcetypes.h" #include "srmresourcestrings.h" #include "svcresource.h" #include "srmtestcommon.h" using namespace std; #ifdef __cplusplus extern "C" { #endif extern char * BinToSvcJSON(const OicSecSvc_t * svc); extern OicSecSvc_t * JSONToSvcBin(const char * jsonStr); extern void DeleteSVCList(OicSecSvc_t* svc); #ifdef __cplusplus } #endif static const char* JSON_FILE_NAME = "oic_unittest.json"; #define NUM_SVC_IN_JSON_DB (2) // JSON Marshalling Tests TEST(SVCResourceTest, JSONMarshallingTests) { char *jsonStr1 = ReadFile(JSON_FILE_NAME); if (jsonStr1) { OicSecSvc_t * svc = JSONToSvcBin(jsonStr1); EXPECT_TRUE(NULL != svc); int cnt = 0; OicSecSvc_t * tempSvc = svc; while(tempSvc) { EXPECT_EQ(tempSvc->svct, ACCESS_MGMT_SERVICE); cnt++; tempSvc = tempSvc->next; } EXPECT_EQ(cnt, NUM_SVC_IN_JSON_DB); char * jsonStr2 = BinToSvcJSON(svc); EXPECT_TRUE(NULL != jsonStr2); OICFree(jsonStr1); OICFree(jsonStr2); DeleteSVCList(svc); } }
26.878049
75
0.627495
gerald-yang
5c4291a9eb3539d3bbeb778695a5e4c600527e93
4,642
cpp
C++
core/src/plugin/PluginDiscovery.cpp
tristanseifert/lichtenstein_client
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
[ "BSD-3-Clause" ]
null
null
null
core/src/plugin/PluginDiscovery.cpp
tristanseifert/lichtenstein_client
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
[ "BSD-3-Clause" ]
null
null
null
core/src/plugin/PluginDiscovery.cpp
tristanseifert/lichtenstein_client
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
[ "BSD-3-Clause" ]
null
null
null
#include "PluginDiscovery.h" #include "LichtensteinPluginHandler.h" #include "HardwareInfoStruct.h" #include "../util/StringUtils.h" #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> // includes for i2c #ifdef __linux__ #include <linux/i2c.h> #include <linux/i2c-dev.h> #endif #include <glog/logging.h> /** * Initializes the plugin discovery system. */ PluginDiscovery::PluginDiscovery(LichtensteinPluginHandler *_handler) : handler(_handler) { this->config = this->handler->getConfig(); } /** * Cleans up any allocated resources. */ PluginDiscovery::~PluginDiscovery() { } /** * Attempts to discover hardware. All EEPROMs in the specified range are read, * and their info structs parsed. * * If the first I2C read times out, it's assumed no chips are at that address; * any subsequent timeouts are considered errors. */ int PluginDiscovery::discover(void) { int err = 0, numAddresses = 0; // get a vector of all addresses std::string addrStr = this->config->Get("discovery", "eeprom_addresses", "0x50,0x51,0x52,0x53"); std::vector<int> addr; numAddresses = StringUtils::parseCsvList(addrStr, addr, 16); LOG(INFO) << "Checking " << numAddresses << " addresses"; // read each memory for(auto it = addr.begin(); it != addr.end(); it++) { int addr = *it; VLOG(1) << "Reading EEPROM at 0x" << std::hex << addr; err = this->discoverAtAddress(addr); // handle errors if(err < 0) { LOG(ERROR) << "Failed reading EEPROM at 0x" << std::hex << addr << std::dec << ": " << err << std::endl; // errors other than a nonexistent device are fatal if(err != kDiscoveryErrNoSuchDevice) { return err; } } } // return error status return err; } /** * Reads the memory at the given I2C location, and attempts to match plugins to * the input and output channels defined by the plugin. */ int PluginDiscovery::discoverAtAddress(int addr) { int err; void *romData = nullptr; size_t romDataLen = 0; // read the ROM err = this->readConfigRom(addr, &romData, &romDataLen); if(err < 0) { LOG(ERROR) << "Couldn't read ROM: " << err; return err; } // TODO: implement return 0; } /** * Reads the config ROM into memory, then provides the caller the address and * length of the data. * * @note Release the buffer with free() when done. */ int PluginDiscovery::readConfigRom(int addr, void **data, size_t *len) { int err = 0, fd = -1; void *readBuf = nullptr; // validate arguments CHECK(data != nullptr) << "data out pointer may not be null"; CHECK(len != nullptr) << "length out pointer may not be null"; CHECK(addr > 0) << "I2C address may not be negative"; CHECK(addr < 0x80) << "I2C address may not be more than 0x7F"; // get bus number from config int busNr = this->config->GetInteger("discovery", "eeprom_bus", 0); CHECK(busNr >= 0) << "Address is negative, wtf (got " << busNr << ", check discovery.eeprom_bus)"; // create bus name const size_t busPathSz = 32 + 1; char busPath[busPathSz]; memset(&busPath, 0, busPathSz); snprintf(busPath, (busPathSz - 1), "/dev/i2c-%d", busNr); // open i2c device fd = open(busPath, O_RDWR); if(fd < 0) { PLOG(ERROR) << "Couldn't open I2C bus at " << busPath; return kDiscoveryErrIo; } // send slave address #ifdef __linux__ err = ioctl(fd, I2C_SLAVE, addr); if(err < 0) { PLOG(ERROR) << "Couldn't set I2C slave address"; close(fd); return kDiscoveryErrIoctl; } #endif // allocate buffer and clear it (fixed size for now); then set its location static const size_t readBufLen = 256; readBuf = malloc(readBufLen); memset(readBuf, 0, readBufLen); *data = readBuf; #ifdef __linux__ // write buffer for read command static const char readCmdBuf[1] = { 0x00 }; // build i2c txn: random read starting at 0x00, 256 bytes. static const size_t txMsgsCount = 2; struct i2c_msg txnMsgs[txMsgsCount] = { { .addr = static_cast<__u16>(addr), .flags = I2C_M_RD, .len = sizeof(readCmdBuf), .buf = (__u8 *) (&readCmdBuf) }, { .addr = static_cast<__u16>(addr), .flags = I2C_M_RD, .len = readBufLen, .buf = static_cast<__u8 *>(readBuf), } }; struct i2c_rdwr_ioctl_data txn = { .msgs = txnMsgs, .nmsgs = txMsgsCount }; err = ioctl(fd, I2C_RDWR, &txn); if(err < 0) { PLOG(ERROR) << "Couldn't read from EEPROM (assuming no such device)"; close(fd); return kDiscoveryErrNoSuchDevice; } #endif // success, write the output buffer location *len = readBufLen; return 0; }
23.21
100
0.646273
tristanseifert
5c469e86a1ad9a6493481c2c4b692795a8225067
12,826
cpp
C++
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
Erick194/gzdoom
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
[ "RSA-MD" ]
2
2020-04-19T13:37:34.000Z
2021-06-09T04:26:25.000Z
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
Erick194/gzdoom
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
[ "RSA-MD" ]
null
null
null
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
Erick194/gzdoom
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
[ "RSA-MD" ]
null
null
null
/* ** Provides an ALSA implementation of a MIDI output device. ** **--------------------------------------------------------------------------- ** Copyright 2008-2010 Randy Heit ** Copyright 2020 Petr Mrazek ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** */ #if defined __linux__ && defined HAVE_SYSTEM_MIDI #include <thread> #include <mutex> #include <condition_variable> #include "mididevice.h" #include "zmusic/m_swap.h" #include "zmusic/mus2midi.h" #include "music_alsa_state.h" #include <alsa/asoundlib.h> namespace { enum class EventType { Null, Delay, Action }; struct EventState { int ticks = 0; snd_seq_event_t data; int size_of = 0; void Clear() { ticks = 0; snd_seq_ev_clear(&data); size_of = 0; } }; class AlsaMIDIDevice : public MIDIDevice { public: AlsaMIDIDevice(int dev_id, int (*printfunc_)(const char *, ...)); ~AlsaMIDIDevice(); int Open() override; void Close() override; bool IsOpen() const override; int GetTechnology() const override; int SetTempo(int tempo) override; int SetTimeDiv(int timediv) override; int StreamOut(MidiHeader *data) override; int StreamOutSync(MidiHeader *data) override; int Resume() override; void Stop() override; bool FakeVolume() override { // Not sure if we even can control the volume this way with Alsa, so make it fake. return true; }; bool Pause(bool paused) override; void InitPlayback() override; bool Update() override; void PrecacheInstruments(const uint16_t *instruments, int count) override {} bool CanHandleSysex() const override { // Assume we can, let Alsa sort it out. We do not truly have full control. return true; } void SendStopEvents(); void SetExit(bool exit); bool WaitForExit(std::chrono::microseconds usec, snd_seq_queue_status_t * status); EventType PullEvent(EventState & state); void PumpEvents(); protected: AlsaSequencer &sequencer; int (*printfunc)(const char*, ...); MidiHeader *Events = nullptr; bool Started = false; uint32_t Position = 0; const static int IntendedPortId = 0; bool Connected = false; int PortId = -1; int QueueId = -1; int DestinationClientId; int DestinationPortId; int Technology; int Tempo = 480000; int TimeDiv = 480; std::thread PlayerThread; bool Exit = false; std::mutex ExitLock; std::condition_variable ExitCond; }; } AlsaMIDIDevice::AlsaMIDIDevice(int dev_id, int (*printfunc_)(const char*, ...) = nullptr) : sequencer(AlsaSequencer::Get()), printfunc(printfunc_) { auto & internalDevices = sequencer.GetInternalDevices(); auto & device = internalDevices.at(dev_id); DestinationClientId = device.ClientID; DestinationPortId = device.PortNumber; Technology = device.GetDeviceClass(); } AlsaMIDIDevice::~AlsaMIDIDevice() { Close(); } int AlsaMIDIDevice::Open() { if (!sequencer.IsOpen()) { return 1; } if(PortId < 0) { snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca(&pinfo); snd_seq_port_info_set_port(pinfo, IntendedPortId); snd_seq_port_info_set_port_specified(pinfo, 1); snd_seq_port_info_set_name(pinfo, "GZDoom Music"); snd_seq_port_info_set_capability(pinfo, 0); snd_seq_port_info_set_type(pinfo, SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION); int err = 0; err = snd_seq_create_port(sequencer.handle, pinfo); PortId = IntendedPortId; } if (QueueId < 0) { QueueId = snd_seq_alloc_named_queue(sequencer.handle, "GZDoom Queue"); } if (!Connected) { Connected = (snd_seq_connect_to(sequencer.handle, PortId, DestinationClientId, DestinationPortId) == 0); } return 0; } void AlsaMIDIDevice::Close() { if(Connected) { snd_seq_disconnect_to(sequencer.handle, PortId, DestinationClientId, DestinationPortId); Connected = false; } if(QueueId >= 0) { snd_seq_free_queue(sequencer.handle, QueueId); QueueId = -1; } if(PortId >= 0) { snd_seq_delete_port(sequencer.handle, PortId); PortId = -1; } } bool AlsaMIDIDevice::IsOpen() const { return Connected; } int AlsaMIDIDevice::GetTechnology() const { return Technology; } int AlsaMIDIDevice::SetTempo(int tempo) { Tempo = tempo; return 0; } int AlsaMIDIDevice::SetTimeDiv(int timediv) { TimeDiv = timediv; return 0; } EventType AlsaMIDIDevice::PullEvent(EventState & state) { state.Clear(); if(!Events) { Callback(CallbackData); if(!Events) { return EventType::Null; } } if (Position >= Events->dwBytesRecorded) { Events = Events->lpNext; Position = 0; if (Callback != NULL) { Callback(CallbackData); } if(!Events) { return EventType::Null; } } uint32_t *event = (uint32_t *)(Events->lpData + Position); state.ticks = event[0]; // Advance to next event. if (event[2] < 0x80000000) { // Short message state.size_of = 12; } else { // Long message state.size_of = 12 + ((MEVENT_EVENTPARM(event[2]) + 3) & ~3); } if (MEVENT_EVENTTYPE(event[2]) == MEVENT_TEMPO) { int tempo = MEVENT_EVENTPARM(event[2]); if(Tempo != tempo) { Tempo = tempo; snd_seq_change_queue_tempo(sequencer.handle, QueueId, Tempo, &state.data); return EventType::Action; } } else if (MEVENT_EVENTTYPE(event[2]) == MEVENT_LONGMSG) { // SysEx messages... uint8_t * data = (uint8_t *)&event[3]; int len = MEVENT_EVENTPARM(event[2]); if (len > 1 && (data[0] == 0xF0 || data[0] == 0xF7)) { snd_seq_ev_set_sysex(&state.data, len, (void *)data); return EventType::Action; } } else if (MEVENT_EVENTTYPE(event[2]) == 0) { // Short MIDI event int command = event[2] & 0xF0; int channel = event[2] & 0x0F; int parm1 = (event[2] >> 8) & 0x7f; int parm2 = (event[2] >> 16) & 0x7f; switch (command) { case MIDI_NOTEOFF: snd_seq_ev_set_noteoff(&state.data, channel, parm1, parm2); return EventType::Action; case MIDI_NOTEON: snd_seq_ev_set_noteon(&state.data, channel, parm1, parm2); return EventType::Action; case MIDI_POLYPRESS: // FIXME: Seems to be missing in the Alsa sequencer implementation break; case MIDI_CTRLCHANGE: snd_seq_ev_set_controller(&state.data, channel, parm1, parm2); return EventType::Action; case MIDI_PRGMCHANGE: snd_seq_ev_set_pgmchange(&state.data, channel, parm1); return EventType::Action; case MIDI_CHANPRESS: snd_seq_ev_set_chanpress(&state.data, channel, parm1); return EventType::Action; case MIDI_PITCHBEND: { long bend = ((long)parm1 + (long)(parm2 << 7)) - 0x2000; snd_seq_ev_set_pitchbend(&state.data, channel, bend); return EventType::Action; } default: break; } } // We didn't really recognize the event, treat it as a delay return EventType::Delay; } void AlsaMIDIDevice::SetExit(bool exit) { std::unique_lock<std::mutex> lock(ExitLock); if(exit != Exit) { Exit = exit; ExitCond.notify_all(); } } bool AlsaMIDIDevice::WaitForExit(std::chrono::microseconds usec, snd_seq_queue_status_t * status) { std::unique_lock<std::mutex> lock(ExitLock); if(Exit) { return true; } ExitCond.wait_for(lock, usec); if(Exit) { return true; } snd_seq_get_queue_status(sequencer.handle, QueueId, status); return false; } /* * Pumps events from the input to the output in a worker thread. * It tries to keep the amount of events (time-wise) in the ALSA sequencer queue to be between 40 and 80ms by sleeping where necessary. * This means Alsa can play them safely without running out of things to do, and we have good control over the events themselves (volume, pause, etc.). */ void AlsaMIDIDevice::PumpEvents() { const std::chrono::microseconds pump_step(40000); // TODO: fill in error handling throughout this. snd_seq_queue_tempo_t *tempo; snd_seq_queue_tempo_alloca(&tempo); snd_seq_queue_tempo_set_tempo(tempo, Tempo); snd_seq_queue_tempo_set_ppq(tempo, TimeDiv); snd_seq_set_queue_tempo(sequencer.handle, QueueId, tempo); snd_seq_start_queue(sequencer.handle, QueueId, NULL); snd_seq_drain_output(sequencer.handle); int buffer_ticks = 0; EventState event; snd_seq_queue_status_t *status; snd_seq_queue_status_malloc(&status); while (true) { auto type = PullEvent(event); // if we reach the end of events, await our doom at a steady rate while looking for more events if(type == EventType::Null) { if(WaitForExit(pump_step, status)) { break; } continue; } // chomp delays as they come... if(type == EventType::Delay) { buffer_ticks += event.ticks; Position += event.size_of; continue; } // Figure out if we should sleep (the event is too far in the future for us to care), and for how long int next_event_tick = buffer_ticks + event.ticks; int queue_tick = snd_seq_queue_status_get_tick_time(status); int tick_delta = next_event_tick - queue_tick; auto usecs = std::chrono::microseconds(tick_delta * Tempo / TimeDiv); auto schedule_time = std::max(std::chrono::microseconds(0), usecs - pump_step); if(schedule_time >= pump_step) { if(WaitForExit(schedule_time, status)) { break; } continue; } if (tick_delta < 0) { if(printfunc) { printfunc("Alsa sequencer underrun: %d ticks!\n", tick_delta); } } // We found an event worthy of sending to the sequencer snd_seq_ev_set_source(&event.data, PortId); snd_seq_ev_set_subs(&event.data); snd_seq_ev_schedule_tick(&event.data, QueueId, false, buffer_ticks + event.ticks); int result = snd_seq_event_output(sequencer.handle, &event.data); if(result < 0) { if(printfunc) { printfunc("Alsa sequencer did not accept event: error %d!\n", result); } if(WaitForExit(pump_step, status)) { break; } continue; } buffer_ticks += event.ticks; Position += event.size_of; snd_seq_drain_output(sequencer.handle); } snd_seq_queue_status_free(status); snd_seq_drop_output(sequencer.handle); // FIXME: the event source should give use these, but it doesn't. { for (int channel = 0; channel < 16; ++channel) { snd_seq_event_t ev; snd_seq_ev_clear(&ev); snd_seq_ev_set_source(&ev, PortId); snd_seq_ev_set_subs(&ev); snd_seq_ev_schedule_tick(&ev, QueueId, true, 0); snd_seq_ev_set_controller(&ev, channel, MIDI_CTL_ALL_NOTES_OFF, 0); snd_seq_event_output(sequencer.handle, &ev); snd_seq_ev_set_controller(&ev, channel, MIDI_CTL_RESET_CONTROLLERS, 0); snd_seq_event_output(sequencer.handle, &ev); } snd_seq_drain_output(sequencer.handle); snd_seq_sync_output_queue(sequencer.handle); } snd_seq_sync_output_queue(sequencer.handle); snd_seq_stop_queue(sequencer.handle, QueueId, NULL); snd_seq_drain_output(sequencer.handle); } int AlsaMIDIDevice::Resume() { if(!Connected) { return 1; } SetExit(false); PlayerThread = std::thread(&AlsaMIDIDevice::PumpEvents, this); return 0; } void AlsaMIDIDevice::InitPlayback() { SetExit(false); } void AlsaMIDIDevice::Stop() { SetExit(true); PlayerThread.join(); } bool AlsaMIDIDevice::Pause(bool paused) { // TODO: implement return false; } int AlsaMIDIDevice::StreamOut(MidiHeader *header) { header->lpNext = NULL; if (Events == NULL) { Events = header; Position = 0; } else { MidiHeader **p; for (p = &Events; *p != NULL; p = &(*p)->lpNext) { } *p = header; } return 0; } int AlsaMIDIDevice::StreamOutSync(MidiHeader *header) { return StreamOut(header); } bool AlsaMIDIDevice::Update() { return true; } MIDIDevice *CreateAlsaMIDIDevice(int mididevice) { return new AlsaMIDIDevice(mididevice, musicCallbacks.Alsa_MessageFunc); } #endif
25.198428
151
0.710432
Erick194
5c4bd0115b98a0e53944cadf2f743dde628c407f
443
cpp
C++
heap/kSortedArray.cpp
sumana2001/problems450
90b804b7063bb3f11f90b7506576ed14d27e1776
[ "MIT" ]
null
null
null
heap/kSortedArray.cpp
sumana2001/problems450
90b804b7063bb3f11f90b7506576ed14d27e1776
[ "MIT" ]
null
null
null
heap/kSortedArray.cpp
sumana2001/problems450
90b804b7063bb3f11f90b7506576ed14d27e1776
[ "MIT" ]
1
2021-08-19T12:20:06.000Z
2021-08-19T12:20:06.000Z
#include<bits/stdc++.h> using namespace std; int main(){ int arr[]={6, 5, 3, 2, 8, 10, 9}; int n=sizeof(arr)/sizeof(arr[0]); int k=3; priority_queue<int,vector<int>,greater<int> > pq; for(int i=0;i<n;i++){ pq.push(arr[i]); if(pq.size()==k+1){ cout<<pq.top()<<" "; pq.pop(); } } while(!pq.empty()){ cout<<pq.top()<<" "; pq.pop(); } return 0; }
21.095238
53
0.446953
sumana2001
5c4e7d0561f155e336d64344bb8746b7ae1bbc17
3,927
cpp
C++
Source/ISnd2/LoadOgg.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
2
2022-02-11T11:59:44.000Z
2022-02-16T20:33:25.000Z
Source/ISnd2/LoadOgg.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
Source/ISnd2/LoadOgg.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
#include "all.h" #include "loader.h" extern"C"{ #include "vorbis\vorbisfile.h" } #ifdef _DEBUG #pragma comment(lib, "ogg_d.lib") #pragma comment(lib, "vorbis_d.lib") #else #pragma comment(lib, "ogg.lib") #pragma comment(lib, "vorbis.lib") #endif //---------------------------- const int BITDEPTH = 16; //bitdepth of data //---------------------------- static class C_ogg_loader: public C_sound_loader{ static size_t read_func(void *ptr, size_t size, size_t nmemb, void *datasource){ PC_dta_stream dta = (PC_dta_stream)datasource; return dta->Read(ptr, size*nmemb); } static int seek_func(void *datasource, __int64 offset, int whence){ PC_dta_stream dta = (PC_dta_stream)datasource; return dta->Seek((int)offset, whence); } static int close_func(void *datasource){ PC_dta_stream dta = (PC_dta_stream)datasource; dta->Release(); return 0; //return dtaClose((int)datasource) ? 0 : -1; } static long tell_func(void *datasource){ PC_dta_stream dta = (PC_dta_stream)datasource; return dta->Seek(0, DTA_SEEK_CUR); } public: C_ogg_loader() { RegisterSoundLoader(this); } //---------------------------- virtual dword Open(PC_dta_stream dta, const char *file_name, void *header, dword hdr_size, S_wave_format *wf){ //if header is not RIFF, don't bother if(hdr_size<4) return 0; if((*(dword*)header) != 0x5367674f) return 0; OggVorbis_File *vf = new OggVorbis_File; //try to open the file ov_callbacks ovc = { read_func, seek_func, close_func, tell_func }; int vret = ov_open_callbacks(dta, vf, (char*)header, hdr_size, ovc); if(vret != 0){ delete vf; return 0; } //init format vorbis_info *vi = ov_info(vf, -1); assert(vi); wf->num_channels = vi->channels; wf->bytes_per_sample = BITDEPTH/8 * wf->num_channels; wf->samples_per_sec = vi->rate; wf->size = (int)ov_pcm_total(vf, -1) * wf->bytes_per_sample; return (dword)vf; } //---------------------------- virtual void Close(dword handle){ OggVorbis_File *vf = (OggVorbis_File*)handle; assert(vf); ov_clear(vf); delete vf; } //---------------------------- virtual int Read(dword handle, void *mem, dword size){ OggVorbis_File *vf = (OggVorbis_File*)handle; dword read = 0; //must read in multiple chunks (design of VorbisFile?) while(read < size){ int current_section; dword to_read = size - read; int rd1 = ov_read(vf, ((char*)mem) + read, to_read, 0, //little/big endian BITDEPTH/8, //byte-depth BITDEPTH==8 ? 0 : 1, //unsigned=0, signed=1 &current_section); assert(rd1); if(rd1<0) return -1; read += rd1; } assert(read==size); return read; } //---------------------------- virtual int Seek(dword handle, dword pos){ OggVorbis_File *vf = (OggVorbis_File*)handle; //convert position back to samples dword sample = pos / (vf->vi->channels * 2); ov_pcm_seek(vf, sample); /* assert(pos==0); if(pos!=0) return -1; if(ov_pcm_tell(vf)!=0){ //re-open int h = (int)vf->datasource; vf->datasource = NULL; int ok; ok = ov_clear(vf); assert(!ok); dtaSeek(h, 0, DTA_SEEK_SET); ov_callbacks ovc = { read_func, seek_func, close_func, tell_func }; ok = ov_open_callbacks((void*)h, vf, NULL, 0, ovc); assert(!ok); } */ return pos; } } ogg_loader; //----------------------------
26.355705
113
0.531449
mice777
5c56baa2acd3c5c05d37e50e16780bdc49fe6f47
6,068
cpp
C++
QtWebApp/httpserver/staticfilecontroller.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
QtWebApp/httpserver/staticfilecontroller.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
QtWebApp/httpserver/staticfilecontroller.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
/** @file @author Stefan Frings */ #include "staticfilecontroller.h" #include <QFileInfo> #include <QDir> #include <QDateTime> using namespace stefanfrings; StaticFileController::StaticFileController( const QSettings* settings, QObject* parent ) : HttpRequestHandler( parent ), m_encoding( settings->value( "encoding", "UTF-8" ).toString() ), m_docroot( settings->value( "path", "." ).toString() ), m_maxAge( settings->value( "maxAge", "60000" ).toInt() ), m_cacheTimeout( settings->value( "cacheTime", "60000" ).toInt() ), m_maxCachedFileSize( settings->value( "maxCachedFileSize", "65536" ).toInt() ) { if ( !( m_docroot.startsWith( ":/" ) || m_docroot.startsWith( "qrc://" ) ) ) { // Convert relative path to absolute, based on the directory of the config file. #ifdef Q_OS_WIN32 if ( QDir::isRelativePath( docroot ) && settings->format() != QSettings::NativeFormat ) #else if ( QDir::isRelativePath( m_docroot ) ) #endif { QFileInfo configFile( settings->fileName() ); m_docroot=QFileInfo( configFile.absolutePath(), m_docroot ).absoluteFilePath(); } } m_cache.setMaxCost( settings->value( "cacheSize", "1000000" ).toInt() ); #ifdef SUPERVERBOSE qDebug( "StaticFileController: docroot=%s, encoding=%s, maxAge=%i", qPrintable( m_docroot ), qPrintable( m_encoding ), m_maxAge ); long int cacheMaxCost=(long int)m_cache.maxCost(); qDebug( "StaticFileController: cache timeout=%i, size=%li", m_cacheTimeout, cacheMaxCost ); #endif } void StaticFileController::service( HttpRequest& request, HttpResponse& response ) { QByteArray path = request.getPath(); // Check if we have the file in cache qint64 now = QDateTime::currentMSecsSinceEpoch(); m_mutex.lock(); CacheEntry* entry = m_cache.object( path ); if ( entry && ( m_cacheTimeout == 0 || entry->created>now - m_cacheTimeout ) ) { QByteArray document = entry->document; //copy the cached document, because other threads may destroy the cached entry immediately after mutex unlock. QByteArray filename = entry->filename; m_mutex.unlock(); #ifdef SUPERVERBOSE qDebug( "StaticFileController: Cache hit for %s", path.data() ); #endif setContentType( filename, response ); response.setHeader( "Cache-Control", "max-age=" + QByteArray::number( m_maxAge / 1000 ) ); response.write( document, true ); return; } m_mutex.unlock(); // The file is not in cache. #ifdef SUPERVERBOSE qDebug( "StaticFileController: Cache miss for %s", path.data() ); #endif // Forbid access to files outside the docroot directory if ( path.contains( "/.." ) ) { qWarning( "StaticFileController: detected forbidden characters in path %s", path.data() ); response.setStatus( 403, "forbidden" ); response.write( "403 forbidden", true ); return; } // If the filename is a directory, append index.html. if ( QFileInfo( m_docroot + path ).isDir() ) { path += "/index.html"; } // Try to open the file QFile file( m_docroot + path ); #ifdef SUPERVERBOSE qDebug( "StaticFileController: Open file %s", qPrintable( file.fileName() ) ); #endif if ( file.open( QIODevice::ReadOnly ) ) { setContentType( path, response ); response.setHeader( "Cache-Control", "max-age=" + QByteArray::number( m_maxAge / 1000 ) ); response.setHeader( "Content-Length", QByteArray::number( file.size() ) ); if ( file.size() <= m_maxCachedFileSize ) { // Return the file content and store it also in the cache entry = new CacheEntry(); while ( !file.atEnd() && !file.error() ) { QByteArray buffer = file.read( 65536 ); response.write( buffer, false ); entry->document.append( buffer, false ); } entry->created = now; entry->filename = path; m_mutex.lock(); m_cache.insert( request.getPath(), entry, entry->document.size() ); m_mutex.unlock(); } else { // Return the file content, do not store in cache while ( !file.atEnd() && !file.error() ) { response.write( file.read( 65536 ) ); } } file.close(); return; } if ( file.exists() ) { qWarning( "StaticFileController: Cannot open existing file %s for reading", qPrintable( file.fileName() ) ); response.setStatus( 403, "forbidden" ); response.write( "403 forbidden", true ); return; } response.setStatus( 404, "not found" ); response.write( "404 not found", true ); } void StaticFileController::setContentType( const QString& fileName, HttpResponse& response ) const { // Todo: add all of your content types const QMap<QString, QString> contentTypeMap = { { ".png", "image/png" }, { ".jpg", "image/jpeg" }, { ".gif", "image/gif" }, { ".pdf", "application/pdf" }, { ".txt", "text/plain; charset=" + m_encoding }, { ".html", "text/html; charset=" + m_encoding }, { ".htm", "text/html; charset=" + m_encoding }, { ".css", "text/css" }, { ".js", "text/javascript" }, { ".svg", "image/svg+xml" }, { ".woff", "font/woff" }, { ".woff2", "font/woff2" }, { ".ttf", "application/x-font-ttf" }, { ".eot", "application/vnd.ms-fontobject" }, { ".otf", "application/font-otf" }, { ".json", "application/json" }, { ".xml", "text/xml" }, }; for ( auto contentType = contentTypeMap.cbegin(); contentType != contentTypeMap.cend(); ++contentType ) { if ( fileName.endsWith( contentType.key() ) ) { response.setHeader( "Content-Type", qPrintable( contentType.value() ) ); return; } } qWarning( "StaticFileController: unknown MIME type for filename '%s'", qPrintable( fileName ) ); }
38.897436
157
0.599044
cbcalves
5c56c79b9d72ec05c7afc418b555be8c4cd08aee
579
hpp
C++
src/common/idtypes/brushid.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
3
2020-03-05T06:36:51.000Z
2020-06-20T03:25:02.000Z
src/common/idtypes/brushid.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
13
2020-03-11T17:43:42.000Z
2020-12-11T03:36:05.000Z
src/common/idtypes/brushid.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
1
2020-09-28T06:53:46.000Z
2020-09-28T06:53:46.000Z
/** * Addle source code * @file * @copyright Copyright 2020 Eleanor Hawk * @copyright Modification and distribution permitted under the terms of the * MIT License. See "LICENSE" for full details. */ #ifndef BRUSHID_HPP #define BRUSHID_HPP #include "addleid.hpp" #include "brushengineid.hpp" namespace Addle { class ADDLE_COMMON_EXPORT BrushId final : public AddleId { ID_TYPE_BOILERPLATE(BrushId) }; } // namespace Addle Q_DECLARE_METATYPE(Addle::BrushId) Q_DECLARE_TYPEINFO(Addle::BrushId, Q_PRIMITIVE_TYPE); ID_TYPE_BOILERPLATE2(BrushId); #endif // BRUSHID_HPP
20.678571
76
0.768566
squeevee
5c5ac118797daf1cc64df7b8b0f9c2c3a17b9590
9,723
hpp
C++
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
#ifndef LIBNDGPP_NET_BASIC_IPV4_ADDRESS_HPP #define LIBNDGPP_NET_BASIC_IPV4_ADDRESS_HPP #include <cstdint> #include <array> #include <ostream> #include <stdexcept> #include <string> #include <type_traits> #include <libndgpp/error.hpp> #include <libndgpp/net/ipv4_array.hpp> namespace ndgpp { namespace net { template <uint32_t Min, uint32_t Max> struct basic_ipv4_address_validator { constexpr bool operator () (uint32_t value) { if (value < Min || value > Max) { throw ndgpp_error(std::out_of_range, "supplied address out of range"); } return true; } }; template <> struct basic_ipv4_address_validator<0, 0xffffffff> { constexpr bool operator () (uint32_t value) noexcept { return true; } }; /** IPv4 address value type * * @tparam Min The minimum address value in network byte order * @tparam Max The maximum address value in network byte order * * @par Move Semantics * Move operations behave just like copy operations */ template <uint32_t Min = 0, uint32_t Max = 0xffffffff> class basic_ipv4_address final { public: using value_type = ndgpp::net::ipv4_array; /// The minimum address value in network byte order static constexpr uint32_t min = Min; /// The maximum address value in network byte order static constexpr uint32_t max = Max; using constrained_bool_type = std::conditional_t<Min == 0x0 && Max == 0xffffffff, std::false_type, std::true_type>; static constexpr bool constrained = constrained_bool_type::value; /// Constructs an address assigned to Min constexpr basic_ipv4_address() noexcept; template <uint32_t MinO, uint32_t MaxO> constexpr basic_ipv4_address(const basic_ipv4_address<MinO, MaxO> & other) noexcept(MinO >= Min && MaxO <= Max); /// Constructs an address assigned to the value provided constexpr basic_ipv4_address(const value_type value) noexcept(!constrained); /** Constructs an address from an unsigned 32 bit integer * * The parameter's value is mapped to the address octet like * so: * * address[0] = (value >> 24) & 0xff000000; * address[1] = (value >> 16) & 0x00ff0000; * address[2] = (value >> 8) & 0x0000ff00; * address[3] = value & 0x000000ff; * * @param An unsigned 32 bit integer */ explicit constexpr basic_ipv4_address(const uint32_t value) noexcept(!constrained); /** Constructs an address from a string * * @param value A string representing an IP address in dotted * quad notation. The string can be optionally * terminated by a colon. */ explicit basic_ipv4_address(const std::string & value); basic_ipv4_address & operator = (const basic_ipv4_address & value) noexcept; /// Assignes the address based on the value_type value basic_ipv4_address & operator = (const value_type value) noexcept(!constrained); /// Assignes the address based on the passed in unsigned 32 bit value basic_ipv4_address & operator = (const uint32_t value) noexcept (!constrained); /// Assignes the address based on the passed in dotted quad string value basic_ipv4_address & operator = (const std::string & value); void swap(basic_ipv4_address & other) noexcept; constexpr uint8_t operator[] (const std::size_t index) const noexcept; constexpr ndgpp::net::ipv4_array value() const noexcept; /** Returns the address as an unsigned 32 bit integer * * The address is mapped to the value like so: * * addr[0] << 24 | addr[1] << 16 | addr[2] << 8 | addr[3] */ constexpr uint32_t to_uint32() const noexcept; /// Returns the address as a dotted quad string std::string to_string() const; private: ndgpp::net::ipv4_array value_ = {ndgpp::net::make_ipv4_array(Min)}; }; template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address() noexcept = default; template <uint32_t Min, uint32_t Max> template <uint32_t MinO, uint32_t MaxO> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const basic_ipv4_address<MinO, MaxO> & addr) noexcept(MinO >= Min && MaxO <= Max): value_ {addr.value()} { if (!(MinO >= Min && MaxO <= Max)) { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } } template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const ndgpp::net::ipv4_array value) noexcept(!basic_ipv4_address::constrained): value_ {value} { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const uint32_t value) noexcept(!basic_ipv4_address::constrained): value_ {ndgpp::net::make_ipv4_array(value)} { basic_ipv4_address_validator<Min, Max> {} (value); } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max>::basic_ipv4_address(const std::string & value): value_ {ndgpp::net::make_ipv4_array(value)} { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const basic_ipv4_address &) noexcept = default; template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const ndgpp::net::ipv4_array rhs) noexcept(!basic_ipv4_address::constrained) { this->value_ = rhs; basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); return *this; } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const uint32_t rhs) noexcept(!basic_ipv4_address::constrained) { this->value_ = ndgpp::net::make_ipv4_array(rhs); basic_ipv4_address_validator<Min, Max> {} (rhs); return *this; } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const std::string & rhs) { this->value_ = ndgpp::net::make_ipv4_array(rhs); basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); return *this; } template <uint32_t Min, uint32_t Max> void basic_ipv4_address<Min, Max>::swap(basic_ipv4_address & other) noexcept { std::swap(this->value_, other.value_); } template <uint32_t Min, uint32_t Max> inline constexpr uint8_t basic_ipv4_address<Min, Max>::operator [] (const std::size_t index) const noexcept { return this->value_[index]; } template <uint32_t Min, uint32_t Max> inline constexpr ndgpp::net::ipv4_array basic_ipv4_address<Min, Max>::value() const noexcept { return this->value_; } template <uint32_t Min, uint32_t Max> inline constexpr uint32_t basic_ipv4_address<Min, Max>::to_uint32() const noexcept { return ndgpp::net::to_uint32(this->value_); } template <uint32_t Min, uint32_t Max> inline std::string basic_ipv4_address<Min, Max>::to_string() const { return ndgpp::net::to_string(this->value_); } template <uint32_t Min, uint32_t Max> void swap(basic_ipv4_address<Min, Max> & lhs, basic_ipv4_address<Min, Max> & rhs) { lhs.swap(rhs); } template <uint32_t Min, uint32_t Max> inline std::ostream & operator <<(std::ostream & stream, const basic_ipv4_address<Min, Max> address) { stream << static_cast<uint16_t>(address[0]); for (std::size_t i = 1; i < std::tuple_size<typename ndgpp::net::basic_ipv4_address<Min, Max>::value_type>::value; ++i) { stream.put('.'); stream << static_cast<uint16_t>(address[i]); } return stream; } template <uint32_t Min, uint32_t Max> inline bool operator ==(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return lhs.value() == rhs.value(); } template <uint32_t Min, uint32_t Max> inline bool operator !=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(lhs == rhs); } template <uint32_t Min, uint32_t Max> inline bool operator <(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return lhs.value() < rhs.value(); } template <uint32_t Min, uint32_t Max> inline bool operator >=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(lhs < rhs); } template <uint32_t Min, uint32_t Max> inline bool operator >(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return rhs < lhs; } template <uint32_t Min, uint32_t Max> inline bool operator <=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(rhs < lhs); } }} #endif
33.297945
145
0.62851
goodfella
5c5d4896cdef7918d1b9b1b525726cbddbafd513
597
hxx
C++
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
#pragma once #include "RuleSet.hh" #include "VolumeRegistry.hh" #include "VolumeSet.hh" #include <memory> class Profile { public: const RuleSet& getRuleSet() const { return getRuleSet_impl(); } RuleSet& getRuleSet() { return getRuleSet_impl(); } const VolumeRegistry& getVolumeRegistry() const { return getVolumeRegistry_impl(); } VolumeRegistry& getVolumeRegistry() { return getVolumeRegistry_impl(); } virtual bool createVolumes(VolumeSet &volumes) const = 0; protected: virtual RuleSet& getRuleSet_impl() const = 0; virtual VolumeRegistry& getVolumeRegistry_impl() const = 0; };
22.961538
85
0.755444
Angew
5c5e6063275e112ec3c117a6c97cc9442bf36d9b
996
cpp
C++
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
// // Created by 赖於领 on 2021/9/1. // #include <vector> #include <iostream> using namespace std; //最佳观光组合 class Solution { public: int maxScoreSightseeingPair(vector<int> &values) { // if (values.size() == 2) { // return values[0] + values[1] - 1; // } //values[i]+values[j]+i-j = int n = values.size(); vector<int> r(n, 0); vector<int> sums(n, 0); r[0] = values[0]; sums[0] = INT_MIN; for (int i = 1; i < n; i++) { r[i] = max(r[i - 1], values[i - 1]) - 1; sums[i] = max(sums[i - 1], r[i] + values[i]); cout << "i is " << i << " " << r[i] << " " << sums[i] << endl; } return sums[n - 1]; } }; //int main() { // // Solution *solution = new Solution(); //// vector<int> a = {8, 1, 5, 2, 6}; // vector<int> a = {1, 2}; //// vector<int> a = {1, 3, 5}; // cout << solution->maxScoreSightseeingPair(a) << endl; // // return 0; //}
21.191489
78
0.447791
laiyuling424
5c5f2368e1c6d05bba92409dbfefcac47bc0d744
1,343
cpp
C++
src/src/collision_sphere.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
2
2015-11-05T20:08:00.000Z
2016-07-07T04:17:07.000Z
src/src/collision_sphere.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
3
2016-10-29T02:20:49.000Z
2017-04-01T11:09:53.000Z
src/src/collision_sphere.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
null
null
null
#include "collision/spherecollider.hpp" #include "collision/aabbcollider.hpp" #include <cstddef> using namespace Collision; SphereCollider::SphereCollider(const glm::vec3& center, const float radius){ this->center = glm::vec3(center); this->radius = radius; } bool SphereCollider::visitCollide(Collider* node){ return node->visitCollide(this); } bool SphereCollider::visitCollide(AABBCollider* aabb){ glm::vec3 q; glm::vec3 center = getTransformedCenter(); glm::vec3 min = aabb->getTransformedMin(); glm::vec3 max = aabb->getTransformedMax(); for (int i = 0; i < 3; i++) { float v = center[i]; if (v < min[i]) v = min[i]; // v = max(v, b.min[i]) if (v > max[i]) v = max[i]; // v = min(v, b.max[i]) q[i] = v; } glm::vec3 v = q - center; return glm::dot(v,v) <= this->radius * this->radius; } bool SphereCollider::visitCollide(SphereCollider* sphere){ glm::vec3 d = this->getTransformedCenter() - sphere->getTransformedCenter(); float dist2 = glm::dot(d, d); float radiusSum = this->radius + sphere->getRadius(); return dist2 <= radiusSum * radiusSum; } void SphereCollider::notifyCollider(Collider* collider){ } glm::vec3 SphereCollider::getTransformedCenter(){ return glm::vec3(moveable.getCulumativeMatrix() * glm::vec4(center, 1.0f)); } Geometry::Moveable& SphereCollider::getMoveable(){ return moveable; }
28.574468
77
0.694713
crr0004
5c60f0151b28f916dc90688f5b7d0b866658f1ec
676
cpp
C++
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
6
2020-06-20T23:56:42.000Z
2021-12-18T08:13:54.000Z
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
153
2020-06-09T14:49:29.000Z
2022-01-31T16:39:39.000Z
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
10
2020-08-02T00:55:38.000Z
2022-01-24T23:06:51.000Z
#include <cinttypes> #include <cstdint> #include "utility/log.hpp" #include "utility/time/time.hpp" int main() { sjsu::LogInfo("Delay Application Starting..."); sjsu::LogInfo("This demo prints a statement every second using Delay(1s)."); sjsu::LogInfo( "Notice that the uptime does not increase by 1 second but by a little " "more then that."); sjsu::LogInfo( "This is due to the fact that we delay for a whole second, but it takes " "time to print each statement."); int counter = 0; while (true) { sjsu::LogInfo( "[%d] Uptime = %" PRId64 "ns", counter++, sjsu::Uptime().count()); sjsu::Delay(1s); } return 0; }
23.310345
79
0.633136
SarahS16
5c63ad45055fc5b87ccc0f9aa9c7696d28857b5d
4,991
cc
C++
Source/BladeBase/source/graphics/RenderProperty.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeBase/source/graphics/RenderProperty.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeBase/source/graphics/RenderProperty.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2011/12/21 filename: RenderProperty.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <interface/public/graphics/RenderProperty.h> #include <interface/public/graphics/ITexture.h> namespace Blade { template class FixedArray<HRENDERPROPERTY,RPT_COUNT>; /************************************************************************/ /* */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// IRenderProperty* IRenderProperty::createProperty(RENDER_PROPERTY eProp) { switch(eProp) { case RPT_COLOR: return BLADE_NEW ColorProperty(); case RPT_COLORWIRTE: return BLADE_NEW ColorWriteProperty(); case RPT_FOG: return BLADE_NEW FogProperty(); case RPT_ALPHABLEND: return BLADE_NEW AlphaBlendProperty(); case RPT_DEPTH: return BLADE_NEW DepthProperty(); case RPT_STENCIL: return BLADE_NEW StencilProperty(); case RPT_SCISSOR: return BLADE_NEW ScissorProperty(); default: break; } assert(false); return NULL; } ////////////////////////////////////////////////////////////////////////// IRenderProperty* IRenderProperty::cloneProperty(IRenderProperty* prop) { if(prop == NULL) return NULL; switch(prop->getType()) { case RPT_COLOR: return BLADE_NEW ColorProperty( *static_cast<ColorProperty*>(prop) ); case RPT_COLORWIRTE: return BLADE_NEW ColorWriteProperty( *static_cast<ColorWriteProperty*>(prop) ); case RPT_FOG: return BLADE_NEW FogProperty( *static_cast<FogProperty*>(prop) ); case RPT_ALPHABLEND: return BLADE_NEW AlphaBlendProperty( *static_cast<AlphaBlendProperty*>(prop) ); case RPT_DEPTH: return BLADE_NEW DepthProperty( *static_cast<DepthProperty*>(prop) ); case RPT_STENCIL: return BLADE_NEW StencilProperty( *static_cast<StencilProperty*>(prop) ); case RPT_SCISSOR: return BLADE_NEW ScissorProperty( *static_cast<ScissorProperty*>(prop) ); default: break; } assert(false); return NULL; } /************************************************************************/ /* */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::addProperty(const HRENDERPROPERTY& hProp) { if( hProp == NULL || this->hasProperty(hProp->getType())) return false; RENDER_PROPERTY eRP = hProp->getType(); if( eRP < RPT_COUNT ) { HRENDERPROPERTY& hTarget = mPropertyList[eRP]; assert(hTarget == NULL ); hTarget = hProp; mPropertyMask.raiseBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::setProperty(const HRENDERPROPERTY& hProp) { if( hProp == NULL ) return false; RENDER_PROPERTY eRP = hProp->getType(); if( eRP < RPT_COUNT ) { mPropertyList[eRP] = hProp; mPropertyMask.raiseBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::removeProperty(RENDER_PROPERTY eRP) { if( eRP < RPT_COUNT ) { HRENDERPROPERTY& hProp = mPropertyList[eRP]; hProp.clear(); mPropertyMask.clearBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// void RenderPropertySet::mergeProperties(const RenderPropertySet& mergeSource) { for(int i = RPT_BEGIN; i < RPT_COUNT; ++i) { RENDER_PROPERTY eProp = (RENDER_PROPERTY)i; if( mergeSource.hasProperty(eProp) ) this->setProperty(mergeSource.getProperty(eProp)); } //mCullMode = mergeSource.mCullMode; //FIXME: } ////////////////////////////////////////////////////////////////////////// const HRENDERPROPTYSET& RenderPropertySet::getDefaultRenderProperty() { static HRENDERPROPTYSET DEFAULT_PROPERTY; if( DEFAULT_PROPERTY == NULL ) { DEFAULT_PROPERTY.lock(); DEFAULT_PROPERTY.bind( BLADE_NEW RenderPropertySet() ); Lock::memoryBarrier(); DEFAULT_PROPERTY.unlock(); } return DEFAULT_PROPERTY; } /************************************************************************/ /* */ /************************************************************************/ const Sampler Sampler::DEFAULT; const Sampler Sampler::DEFAULT_RTT(TAM_CLAMP, TAM_CLAMP, TAM_CLAMP, TFM_LINEAR, TFM_LINEAR, TFM_LINEAR, 0.0f, 0.0f); const Sampler Sampler::DEFAULT_RTT_DEPTH(TAM_CLAMP, TAM_CLAMP, TAM_CLAMP, TFM_POINT, TFM_POINT, TFM_POINT, 0.0f, 0.0f); }//namespace Blade
31
120
0.530154
OscarGame
5c65d2b705eadf9e53f5d161593f3221b758eaa0
2,763
cpp
C++
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
1
2017-12-20T14:27:01.000Z
2017-12-20T14:27:01.000Z
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
null
null
null
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
null
null
null
// Copyright 2006 Peralex Electronics (Pty) Ltd // // 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. // LIBRARY INCLUDE FILES #include <cstring> #include "handlers/ChunkHandlerSFNC.h" #include "handlers/PxgfHandlerException.h" #include "SwapEndian.h" namespace pxgf { using namespace std; cChunkHandlerSFNC::cChunkHandlerSFNC() : m_pCallbackSFNCHandler(nullptr) { } void cChunkHandlerSFNC::registerCallbackHandler(cCallbackSFNC *pHandler) { m_pCallbackSFNCHandler = pHandler; } bool cChunkHandlerSFNC::processChunk(const vector<char> &vchData, bool bBigEndian) { // check that there is enough data for an even number of floats if(((vchData.size()) & 0x3) != 0) return false; if(m_pCallbackSFNCHandler == nullptr) { return true; } int64_t lTimestamp_ns = *(int64_t *)vchData.data(); int iLength = (vchData.size() - 8) / sizeof(float); //vector<float> vfIqData (iLength); m_vfIqData.resize(iLength); memcpy(&m_vfIqData[0], &vchData[8], iLength * sizeof(float)); if(cPXGWriterBase::getIsLocalBigEndian() != bBigEndian) { SWAP_INT64(lTimestamp_ns); for(vector<float>::iterator it = m_vfIqData.begin(); it != m_vfIqData.end(); it++) SWAP_FLOAT(*it); } m_pCallbackSFNCHandler->callbackSFNC(lTimestamp_ns, m_vfIqData); return true; } void cChunkHandlerSFNC::writeChunkSFNC(cPXGWriterBase &stream, int64_t lTimestamp_ns, const vector<float> &vfIqData) const { stream.writeChunkHeader(*this, 8 + vfIqData.size() * sizeof(float)); stream.writeInt64(lTimestamp_ns); stream.writeFloatArray(vfIqData); } void cChunkHandlerSFNC::repack(const cPackingSIQP &oInputPacking, const cPackingSIQP &oOutputPacking, const vector<float> &vfInputIQData, vector<float> &vfOutputData) { if(oInputPacking.equals(oOutputPacking)) { vfOutputData = vfInputIQData; return; } // check that there are an even number of elements if((vfInputIQData.size() & 0x1) != 0) throw cPxgfHandlerException("The length of vfInputIQData must be even."); // swap IQ data vfOutputData.resize(vfInputIQData.size()); for(unsigned uSample = 0; uSample < vfInputIQData.size(); uSample += 2) { vfOutputData[uSample] = vfInputIQData[uSample + 1]; vfOutputData[uSample + 1] = vfInputIQData[uSample]; } } }
32.892857
167
0.734347
Peralex
5c67c4dc7eed0fa630f41634250e101387f5b1a3
2,710
cpp
C++
src/baekjoon_solutions/q2178/main_q2178.cpp
OptimistLabyrinth/competitive_programming
92ef372053813fbeca8f7b1f0cde90555e2ea1d8
[ "Apache-2.0" ]
null
null
null
src/baekjoon_solutions/q2178/main_q2178.cpp
OptimistLabyrinth/competitive_programming
92ef372053813fbeca8f7b1f0cde90555e2ea1d8
[ "Apache-2.0" ]
null
null
null
src/baekjoon_solutions/q2178/main_q2178.cpp
OptimistLabyrinth/competitive_programming
92ef372053813fbeca8f7b1f0cde90555e2ea1d8
[ "Apache-2.0" ]
null
null
null
#include <deque> #include <iostream> #include <sstream> #include <vector> using namespace std; int horizontal_length; int vertical_length; vector<vector<bool>> maze; vector<vector<bool>> is_visited; deque<pair<int, int>> neighboring_paths; int number_of_needed_pop_front; int current_new_path_count; int row_step[4] = {-1, 0, 1, 0}; int col_step[4] = {0, -1, 0, 1}; int path_length; void add_new_path_if_possible(const pair<int, int>& current); int main() { std::string line; std::string token; std::getline(std::cin, line); { std::stringstream ss(line); std::getline(ss, token, ' '); vertical_length = stoi(token); std::getline(ss, token); horizontal_length = stoi(token); } maze.resize(vertical_length, vector<bool>(horizontal_length, false)); is_visited.resize(vertical_length, vector<bool>(horizontal_length, false)); for (int c = 0; c < vertical_length; ++c) { std::getline(std::cin, line); for (int r = 0; r < horizontal_length; ++r) { if (line[r] == '1') { maze[c][r] = true; } else if (line[r] == '0') { maze[c][r] = false; } } } neighboring_paths.emplace_back(0, 0); is_visited[0][0] = true; number_of_needed_pop_front = 1; pair<int, int> current(0, 0); bool found_path = false; while (not neighboring_paths.empty()) { current_new_path_count = 0; for (int i = 0; i < number_of_needed_pop_front; ++i) { current = neighboring_paths.front(); neighboring_paths.pop_front(); if (current.first == horizontal_length - 1 and current.second == vertical_length - 1) { found_path = true; break; } add_new_path_if_possible(current); } if (found_path) { break; } number_of_needed_pop_front = current_new_path_count; ++path_length; } cout << path_length + 1<< "\n"; return 0; } void add_new_path_if_possible(const pair<int, int>& current) { int current_row = 0; int current_col = 0; for (int i = 0; i < 4; ++i) { current_row = current.first + row_step[i]; current_col = current.second + col_step[i]; if (0 <= current_row and current_row < horizontal_length and 0 <= current_col and current_col < vertical_length and maze[current_col][current_row] and not is_visited[current_col][current_row]) { neighboring_paths.emplace_back(current_row, current_col); is_visited[current_col][current_row] = true; ++current_new_path_count; } } }
31.511628
99
0.597786
OptimistLabyrinth
5c683a17d743c3a35d9e5f54c3197d497153624c
3,505
cpp
C++
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// // get_environment_from_os.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // Defines a pair of functions to get the environment strings from the operating // system. These functions copy the environment strings into a CRT-allocated // buffer and return a pointer to that buffer. The caller is responsible for // freeing the returned buffer (via _crt_free). // #include <corecrt_internal.h> #include <corecrt_internal_traits.h> #include <stdlib.h> namespace { struct environment_strings_traits { typedef wchar_t* type; static bool close(_In_ type p) throw() { FreeEnvironmentStringsW(p); return true; } static type get_invalid_value() throw() { return nullptr; } }; typedef __crt_unique_handle_t<environment_strings_traits> environment_strings_handle; } static wchar_t const* __cdecl find_end_of_double_null_terminated_sequence(wchar_t const* const first) throw() { wchar_t const* last = first; for (; *last != '\0'; last += wcslen(last) + 1) { } return last + 1; // Return the pointer one-past-the-end of the double null terminator } extern "C" wchar_t* __cdecl __dcrt_get_wide_environment_from_os() throw() { environment_strings_handle const environment(GetEnvironmentStringsW()); if (!environment) return nullptr; // Find the wchar_t const* const first = environment.get(); wchar_t const* const last = find_end_of_double_null_terminated_sequence(first); size_t const required_count = last - first; __crt_unique_heap_ptr<wchar_t> buffer(_malloc_crt_t(wchar_t, required_count)); if (!buffer) return nullptr; // Note that the multiplication here cannot overflow: memcpy(buffer.get(), environment.get(), required_count * sizeof(wchar_t)); return buffer.detach(); } extern "C" char* __cdecl __dcrt_get_narrow_environment_from_os() throw() { // Note that we call GetEnvironmentStringsW and convert to multibyte. The // GetEnvironmentStringsA function returns the environment in the OEM code // page, but we need the strings in ANSI. environment_strings_handle const environment(GetEnvironmentStringsW()); if (!environment.is_valid()) return nullptr; wchar_t const* const first = environment.get(); wchar_t const* const last = find_end_of_double_null_terminated_sequence(first); size_t const required_wide_count = last - first; #pragma warning(suppress:__WARNING_W2A_BEST_FIT) // 38021 Prefast recommends WC_NO_BEST_FIT_CHARS. size_t const required_narrow_count = static_cast<size_t>(__acrt_WideCharToMultiByte( CP_ACP, 0, environment.get(), static_cast<int>(required_wide_count), nullptr, 0, nullptr, nullptr)); if (required_narrow_count == 0) return nullptr; __crt_unique_heap_ptr<char> buffer(_malloc_crt_t(char, required_narrow_count)); if (!buffer) return nullptr; #pragma warning(suppress:__WARNING_W2A_BEST_FIT) // 38021 Prefast recommends WC_NO_BEST_FIT_CHARS. int const conversion_result = __acrt_WideCharToMultiByte( CP_ACP, 0, environment.get(), static_cast<int>(required_wide_count), buffer.get(), static_cast<int>(required_narrow_count), nullptr, nullptr); if (conversion_result == 0) return nullptr; return buffer.detach(); }
28.729508
109
0.694722
825126369
5c6fc2ea2c3eef41dd62d1afbe34ac4cbeea7a44
29,192
cpp
C++
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
81
2018-07-31T17:13:47.000Z
2022-03-03T09:24:22.000Z
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
2
2018-10-15T04:39:43.000Z
2019-12-05T03:46:50.000Z
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
9
2018-10-11T06:32:12.000Z
2020-10-01T03:46:37.000Z
//================================================================================================================================= // Joe Schutte //================================================================================================================================= #include "BuildCommon/CDisneySceneBuildProcessor.h" #include "BuildCommon/ImportMaterial.h" #include "BuildCommon/ModelBuildPipeline.h" #include "BuildCommon/BakeModel.h" #include "BuildCommon/BuildModel.h" #include "BuildCore/BuildContext.h" #include "SceneLib/SceneResource.h" #include "SceneLib/SubSceneResource.h" #include "Assets/AssetFileUtils.h" #include "UtilityLib/JsonUtilities.h" #include "UtilityLib/MurmurHash.h" #include "IoLib/Directory.h" #include "MathLib/FloatFuncs.h" #include "SystemLib/Logging.h" #include "SystemLib/MemoryAllocation.h" #include "SystemLib/CheckedCast.h" #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include <rapidjson/stringbuffer.h> namespace Selas { #define CurveModelNameSuffix_ "_generatedcurves" struct ElementDesc { FilePathString file; int32 lightSetIndex; }; struct LightSetDesc { CArray<FilePathString> lightFiles; }; //============================================================================================================================= struct SceneFileData { CArray<FilePathString> cameraFiles; FilePathString iblFile; CArray<LightSetDesc*> lightsets; CArray<ElementDesc> elements; }; //============================================================================================================================= struct CurveSegment { uint64 startIndex; uint64 controlPointCount; }; //============================================================================================================================= struct CurveData { float widthTip; float widthRoot; float degrees; bool faceCamera; CArray<float3> controlPoints; CArray<CurveSegment> segments; Hash32 name; }; //============================================================================================================================= static FixedString256 ContentRoot(BuildProcessorContext* context) { FixedString256 root; root.Copy(context->source.name.Ascii()); char* addr = StringUtil::FindLastChar(root.Ascii(), '~'); if(addr == nullptr) { root.Clear(); } else { *(addr + 1) = '\0'; } return root; } //============================================================================================================================= static Error ParseArchiveFile(BuildProcessorContext* context, const FixedString256& root, const FilePathString& sourceId, SubsceneResourceData* subscene) { FilePathString filepath; AssetFileUtils::ContentFilePath(sourceId.Ascii(), filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint modelCount = 0; for(const auto& objFileKV : document.GetObject()) { modelCount += objFileKV.value.GetObject().MemberCount(); } subscene->modelInstances.Reserve(subscene->modelInstances.Count() + modelCount); for(const auto& objFileKV : document.GetObject()) { cpointer objFile = objFileKV.name.GetString(); FilePathString instanceObjFile; FixedStringSprintf(instanceObjFile, "%s%s", root.Ascii(), objFile); AssetFileUtils::IndependentPathSeperators(instanceObjFile); uint meshIndex = subscene->modelNames.Add(instanceObjFile); const auto& element = objFileKV.value; for(const auto& instanceKV : element.GetObject()) { cpointer instanceName = instanceKV.name.GetString(); Instance modelInstance; modelInstance.index = meshIndex; if(Json::ReadMatrix4x4(instanceKV.value, modelInstance.localToWorld) == false) { return Error_("Failed to parse transform from instance '%s' in primfile '%s'", instanceName, filepath.Ascii()); } subscene->modelInstances.Add(modelInstance); } } return Success_; } //============================================================================================================================= static Error ParseControlPointsFile(BuildProcessorContext* context, cpointer path, CurveData* importedCurve) { FilePathString filepath; AssetFileUtils::ContentFilePath(path, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint totalControlPoints = 0; // -- Do a prepass to count the total number of control points uint segmentCount = document.Size(); for(const auto& curveElement : document.GetArray()) { uint controlPointCount = curveElement.Size(); totalControlPoints += controlPointCount; } importedCurve->controlPoints.Resize(totalControlPoints); importedCurve->segments.Resize(segmentCount); uint segmentIndex = 0; uint cpIndex = 0; for(const auto& curveElement : document.GetArray()) { uint controlPointCount = curveElement.Size(); importedCurve->segments[segmentIndex].startIndex = cpIndex; importedCurve->segments[segmentIndex].controlPointCount = controlPointCount; ++segmentIndex; for(const auto& controlPointElement : curveElement.GetArray()) { float3& controlPoint = importedCurve->controlPoints[cpIndex]; ++cpIndex; controlPoint.x = controlPointElement[0].GetFloat(); controlPoint.y = controlPointElement[1].GetFloat(); controlPoint.z = controlPointElement[2].GetFloat(); } } return Success_; } //============================================================================================================================= static void BuildCurveModel(CurveData* importedCurve, cpointer curveName, BuiltModel& curveModel) { uint controlPointCount = importedCurve->controlPoints.Count(); uint curveCount = importedCurve->segments.Count(); MakeInvalid(&curveModel.aaBox); uint curveIndex = 0; uint64 indexOffset = 0; curveModel.curveModelNameHash = MurmurHash3_x86_32(curveName, StringUtil::Length(curveName)); curveModel.curves.Resize(curveCount); curveModel.curveIndices.Reserve(controlPointCount + curveCount * 3); curveModel.curveVertices.Reserve(controlPointCount + curveCount * 2); float widthRoot = importedCurve->widthRoot; float widthTip = importedCurve->widthTip; for(uint segIndex = 0, segCount = importedCurve->segments.Count(); segIndex < segCount; ++segIndex) { const CurveSegment& segment = importedCurve->segments[segIndex]; CurveMetaData& curve = curveModel.curves[curveIndex++]; curve.indexOffset = CheckedCast<uint32>(curveModel.curveIndices.Count()); curve.indexCount = CheckedCast<uint32>(segment.controlPointCount - 1); for(uint cpScan = 0; cpScan < segment.controlPointCount - 1; ++cpScan) { curveModel.curveIndices.Add(CheckedCast<uint32>(indexOffset)); ++indexOffset; } indexOffset += 3; curveModel.curveVertices.Add(float4(importedCurve->controlPoints[segment.startIndex], widthRoot)); for(uint cpScan = 0; cpScan < segment.controlPointCount; ++cpScan) { float w = Lerp(widthRoot, widthTip, (float)cpScan / (float)(segment.controlPointCount - 1)); float3 cpPosition = importedCurve->controlPoints[segment.startIndex + cpScan]; IncludePosition(&curveModel.aaBox, cpPosition); curveModel.curveVertices.Add(float4(cpPosition, w)); } curveModel.curveVertices.Add(float4(importedCurve->controlPoints[segment.startIndex + segment.controlPointCount - 1], widthTip)); } } //============================================================================================================================= static Error ParseCurveElement(BuildProcessorContext* context, cpointer curveName, const FixedString256& root, const rapidjson::Value& element, SubsceneResourceData* subscene) { FilePathString curveFile; if(Json::ReadFixedString(element, "jsonFile", curveFile) == false) { return Error_("`jsonFile ` parameter missing from instanced primitives section"); } AssetFileUtils::IndependentPathSeperators(curveFile); CurveData curve; Json::ReadFloat(element, "widthTip", curve.widthTip, 1.0f); Json::ReadFloat(element, "widthRoot", curve.widthRoot, 1.0f); Json::ReadFloat(element, "degrees", curve.degrees, 1.0f); Json::ReadBool(element, "faceCamera", curve.faceCamera, false); FilePathString controlPointsFile; FixedStringSprintf(controlPointsFile, "%s%s", root.Ascii(), curveFile.Ascii()); FilePathString curveModelName; FixedStringSprintf(curveModelName, "%s%s%s", root.Ascii(), curveFile.Ascii(), CurveModelNameSuffix_); ReturnError_(ParseControlPointsFile(context, controlPointsFile.Ascii(), &curve)); BuiltModel curveModel; BuildCurveModel(&curve, curveName, curveModel); ReturnError_(BakeModel(context, curveModelName.Ascii(), curveModel)); Instance curveInstance; curveInstance.index = subscene->modelNames.Add(curveModelName); curveInstance.localToWorld = Matrix4x4::Identity(); subscene->modelInstances.Add(curveInstance); return Success_; } //============================================================================================================================= static Error ParseInstancePrimitivesSection(BuildProcessorContext* context, const FixedString256& root, const rapidjson::Value& section, SubsceneResourceData* subscene) { uint controlPointCount = 0; uint curveCount = 0; for(const auto& keyvalue : section.GetObject()) { const auto& element = keyvalue.value; FixedString32 type; if(Json::ReadFixedString(element, "type", type) == false) { return Error_("'type' parameter missing from instanced primitives section."); } if(StringUtil::Equals(type.Ascii(), "archive")) { FilePathString primFile; if(Json::ReadFixedString(element, "jsonFile", primFile) == false) { return Error_("`jsonFile ` parameter missing from instanced primitives section"); } AssetFileUtils::IndependentPathSeperators(primFile); FilePathString sourceId; FixedStringSprintf(sourceId, "%s%s", root.Ascii(), primFile.Ascii()); ReturnError_(ParseArchiveFile(context, root, sourceId, subscene)); } else if(StringUtil::Equals(type.Ascii(), "curve")) { ReturnError_(ParseCurveElement(context, keyvalue.name.GetString(), root, element, subscene)); } } return Success_; } //============================================================================================================================= static Error ParseLightsFile(BuildProcessorContext* context, cpointer lightfile, CArray<SceneLight>& lights) { if(StringUtil::Length(lightfile) == 0) { return Success_; } FilePathString filepath; AssetFileUtils::ContentFilePath(lightfile, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint lightCount = document.MemberCount(); lights.Reserve(lights.Count() + lightCount); for(const auto& lightElementKV : document.GetObject()) { FixedString64 type; Json::ReadFixedString(lightElementKV.value, "type", type); if(StringUtil::Equals(type.Ascii(), "quad") == false) { continue; } float4 color; float exposure; Json::ReadFloat4(lightElementKV.value, "color", color, float4::Zero_); Json::ReadFloat(lightElementKV.value, "exposure", exposure, 0.0f); float width, height; Json::ReadFloat(lightElementKV.value, "width", width, 0.0f); Json::ReadFloat(lightElementKV.value, "height", height, 0.0f); float3 rgb = color.XYZ(); float3 radiance = Math::Powf(2.0f, exposure) * Pow(rgb, 2.2f); if(Dot(radiance, float3::One_) <= 0.0f) { continue; } SceneLight& light = lights.Add(); float4x4 matrix; Json::ReadMatrix4x4(lightElementKV.value, "translationMatrix", matrix); light.position = MatrixMultiplyPoint(float3::Zero_, matrix); light.direction = MatrixMultiplyVector(-float3::ZAxis_, matrix); light.x = MatrixMultiplyVector(width * float3::XAxis_, matrix); light.z = MatrixMultiplyVector(height * float3::YAxis_, matrix); light.radiance = radiance; light.type = QuadLight; } return Success_; } //============================================================================================================================= static Error ParseLightSets(BuildProcessorContext* context, const SceneFileData& sceneFile, SceneResourceData* scene) { scene->lightSetRanges.Resize((sceneFile.lightsets.Count())); for(uint setScan = 0, setCount = sceneFile.lightsets.Count(); setScan < setCount; ++setScan) { scene->lightSetRanges[setScan].start = (uint32)scene->lights.Count(); for(uint fileScan = 0, fileCount = sceneFile.lightsets[setScan]->lightFiles.Count(); fileScan < fileCount; ++fileScan) { cpointer filename = sceneFile.lightsets[setScan]->lightFiles[fileScan].Ascii(); ReturnError_(ParseLightsFile(context, filename, scene->lights)); } scene->lightSetRanges[setScan].count = (uint32)(scene->lights.Count() - scene->lightSetRanges[setScan].start); } return Success_; } //============================================================================================================================= static Error ImportDisneyMaterials(BuildProcessorContext* context, cpointer materialPath, cpointer prefix, SubsceneResourceData* subscene) { FilePathString filepath; AssetFileUtils::ContentFilePath(materialPath, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); CArray<FixedString64> materialNames; CArray<ImportedMaterialData> importedMaterials; ReturnError_(ImportDisneyMaterials(filepath.Ascii(), materialNames, importedMaterials)); subscene->sceneMaterialNames.Reserve(importedMaterials.Count()); subscene->sceneMaterials.Reserve(importedMaterials.Count()); for(uint scan = 0, count = importedMaterials.Count(); scan < count; ++scan) { if(importedMaterials[scan].baseColorTexture.Length() > 0) { FilePathString temp; temp.Copy(importedMaterials[scan].baseColorTexture.Ascii()); FixedStringSprintf(importedMaterials[scan].baseColorTexture, "%s%s", prefix, temp.Ascii()); } Hash32 materialNameHash = MurmurHash3_x86_32(materialNames[scan].Ascii(), (int32)materialNames[scan].Length()); subscene->sceneMaterialNames.Add(materialNameHash); MaterialResourceData& material = subscene->sceneMaterials.Add(); BuildMaterial(importedMaterials[scan], material); } return Success_; } //============================================================================================================================= static Error ParseSceneFile(BuildProcessorContext* context, SceneFileData& output) { FilePathString filepath; AssetFileUtils::ContentFilePath(context->source.name.Ascii(), filepath); context->AddFileDependency(filepath.Ascii()); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); if(document.HasMember("elements") == false) { return Error_("'elements' member not found in Disney scene '%s'", filepath.Ascii()); } for(const auto& elementJson : document["elements"].GetArray()) { ElementDesc& element = output.elements.Add(); Json::ReadFixedString(elementJson, "element", element.file); Json::ReadInt32(elementJson, "lightset", element.lightSetIndex, 0); } if(document.HasMember("cameras")) { for(const auto& cameraElement : document["cameras"].GetArray()) { FilePathString& cameraFile = output.cameraFiles.Add(); cameraFile.Copy(cameraElement.GetString()); } } Json::ReadFixedString(document, "ibl", output.iblFile); if(document.HasMember("lightsets")) { for(const auto& lightsetElement : document["lightsets"].GetArray()) { LightSetDesc* desc = New_(LightSetDesc); for(const auto& lightfiles : lightsetElement.GetArray()) { FilePathString& lightFile = desc->lightFiles.Add(); lightFile.Copy(lightfiles.GetString()); } output.lightsets.Add(desc); } } return Success_; } //============================================================================================================================= static Error AllocateSubscene(BuildProcessorContext* context, CArray<SubsceneResourceData*>& scenes, cpointer name, int32 lightSetIndex, const FilePathString& materialFile, const FixedString256& root, SubsceneResourceData*& scene) { scene = New_(SubsceneResourceData); scene->name.Copy(name); scene->lightSetIndex = lightSetIndex; ReturnError_(ImportDisneyMaterials(context, materialFile.Ascii(), root.Ascii(), scene)); scenes.Add(scene); return Success_; } //============================================================================================================================= static Error ParseElementFile(BuildProcessorContext* context, const FixedString256& root, const FilePathString& path, int32 lightSetIndex, SceneResourceData* rootScene, CArray<SubsceneResourceData*>& scenes) { FilePathString elementFilePath; AssetFileUtils::ContentFilePath(path.Ascii(), elementFilePath); ReturnError_(context->AddFileDependency(elementFilePath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(elementFilePath.Ascii(), document)); // -- Prepare the materials json file path FilePathString materialFile; FixedStringSprintf(materialFile, "%s%s", root.Ascii(), document["matFile"].GetString()); FilePathString geomSceneName; FixedStringSprintf(geomSceneName, "%s_geometry", path.Ascii()); SubsceneResourceData* elementGeometryScene; ReturnError_(AllocateSubscene(context, scenes, geomSceneName.Ascii(), lightSetIndex, materialFile, root, elementGeometryScene)); uint geometrySceneIndex = rootScene->subsceneNames.Add(geomSceneName); Instance geometrySceneInstance; geometrySceneInstance.index = geometrySceneIndex; rootScene->subsceneInstances.Add(geometrySceneInstance); // -- Add the main geometry file FilePathString geomObjFile; FixedStringSprintf(geomObjFile, "%s%s", root.Ascii(), document["geomObjFile"].GetString()); AssetFileUtils::IndependentPathSeperators(geomObjFile); uint rootModelIndex = elementGeometryScene->modelNames.Add(geomObjFile); // -- create a child scene to contain the instanced primitives uint primitivesSceneIndex = InvalidIndex64; if(document.HasMember("instancedPrimitiveJsonFiles")) { SubsceneResourceData* primitivesScene; ReturnError_(AllocateSubscene(context, scenes, path.Ascii(), lightSetIndex, materialFile, root, primitivesScene)); primitivesSceneIndex = rootScene->subsceneNames.Add(primitivesScene->name); // -- read the instanced primitives section. ReturnError_(ParseInstancePrimitivesSection(context, root, document["instancedPrimitiveJsonFiles"], primitivesScene)); } { // -- Each element file will have a transform for the 'root level' object file... Instance rootInstance; Json::ReadMatrix4x4(document["transformMatrix"], rootInstance.localToWorld); rootInstance.index = rootModelIndex; elementGeometryScene->modelInstances.Add(rootInstance); if(primitivesSceneIndex != InvalidIndex64) { rootInstance.index = primitivesSceneIndex; rootScene->subsceneInstances.Add(rootInstance); } } // -- add instanced copies if(document.HasMember("instancedCopies")) { for(const auto& instancedCopyKV : document["instancedCopies"].GetObject()) { Instance copyInstance; if(Json::ReadMatrix4x4(instancedCopyKV.value["transformMatrix"], copyInstance.localToWorld) == false) { return Error_("Failed to read `transformMatrix` from instancedCopy '%s'", instancedCopyKV.name.GetString()); } uint modelIndex = rootModelIndex; if(instancedCopyKV.value.HasMember("geomObjFile")) { FilePathString altGeomObjFile; FixedStringSprintf(altGeomObjFile, "%s%s", root.Ascii(), instancedCopyKV.value["geomObjFile"].GetString()); AssetFileUtils::IndependentPathSeperators(altGeomObjFile); modelIndex = elementGeometryScene->modelNames.Add(altGeomObjFile); } copyInstance.index = modelIndex; elementGeometryScene->modelInstances.Add(copyInstance); uint sceneIndex = primitivesSceneIndex; if(instancedCopyKV.value.HasMember("instancedPrimitiveJsonFiles") && instancedCopyKV.value["instancedPrimitiveJsonFiles"].MemberCount() > 0) { SubsceneResourceData* altScene; ReturnError_(AllocateSubscene(context, scenes, instancedCopyKV.name.GetString(), lightSetIndex, materialFile, root, altScene)); sceneIndex = rootScene->subsceneNames.Add(altScene->name); // -- read the instanced primitives section. ReturnError_(ParseInstancePrimitivesSection(context, root, instancedCopyKV.value["instancedPrimitiveJsonFiles"], altScene)); } if(sceneIndex != InvalidIndex64) { copyInstance.index = sceneIndex; rootScene->subsceneInstances.Add(copyInstance); } } } return Success_; } //============================================================================================================================= static Error ParseCameraFile(BuildProcessorContext* context, cpointer path, CameraSettings& settings) { FilePathString fullPath; AssetFileUtils::ContentFilePath(path, fullPath); ReturnError_(context->AddFileDependency(fullPath.Ascii())); cpointer lastSep = StringUtil::FindLastChar(path, PlatformIndependentPathSep_) + 1; settings.name.Copy(lastSep); StringUtil::RemoveExtension(settings.name.Ascii()); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(fullPath.Ascii(), document)); Json::ReadFloat3(document, "eye", settings.position, float3(1.0f, 0.0f, 0.0f)); Json::ReadFloat(document, "fov", settings.fovDegrees, 70.0f); Json::ReadFloat3(document, "look", settings.lookAt, float3::Zero_); Json::ReadFloat3(document, "up", settings.up, float3::YAxis_); settings.znear = 0.1f; settings.zfar = 50000.0f; return Success_; } //============================================================================================================================= Error CDisneySceneBuildProcessor::Setup() { AssetFileUtils::EnsureAssetDirectory<SceneResource>(); AssetFileUtils::EnsureAssetDirectory<SubsceneResource>(); AssetFileUtils::EnsureAssetDirectory<ModelResource>(); return Success_; } //============================================================================================================================= cpointer CDisneySceneBuildProcessor::Type() { return "disneyscene"; } //============================================================================================================================= uint64 CDisneySceneBuildProcessor::Version() { return SceneResource::kDataVersion + SubsceneResource::kDataVersion + ModelResource::kDataVersion; } //============================================================================================================================= Error CDisneySceneBuildProcessor::Process(BuildProcessorContext* context) { FixedString256 contentRoot = ContentRoot(context); SceneFileData sceneFile; ReturnError_(ParseSceneFile(context, sceneFile)); CArray<SubsceneResourceData*> allScenes; SceneResourceData* rootScene = New_(SceneResourceData); rootScene->name.Copy(context->source.name.Ascii()); rootScene->backgroundIntensity = float4::One_; rootScene->iblName.Copy(sceneFile.iblFile.Ascii()); for(uint scan = 0, count = sceneFile.cameraFiles.Count(); scan < count; ++scan) { CameraSettings& settings = rootScene->cameras.Add(); ReturnError_(ParseCameraFile(context, sceneFile.cameraFiles[scan].Ascii(), settings)); } ReturnError_(ParseLightSets(context, sceneFile, rootScene)); for(uint scan = 0, count = sceneFile.elements.Count(); scan < count; ++scan) { const FilePathString& elementName = sceneFile.elements[scan].file; int32 lightSetIndex = sceneFile.elements[scan].lightSetIndex; ReturnError_(ParseElementFile(context, contentRoot, elementName, lightSetIndex, rootScene, allScenes)); } for(uint scan = 0, count = allScenes.Count(); scan < count; ++scan) { SubsceneResourceData* scene = allScenes[scan]; for(uint scan = 0, count = scene->modelNames.Count(); scan < count; ++scan) { if(!StringUtil::EndsWithIgnoreCase(scene->modelNames[scan].Ascii(), CurveModelNameSuffix_)) { context->AddProcessDependency("model", scene->modelNames[scan].Ascii()); } } ReturnError_(context->CreateOutput(SubsceneResource::kDataType, SubsceneResource::kDataVersion, scene->name.Ascii(), *scene)); Delete_(scene); } allScenes.Shutdown(); if(StringUtil::Length(sceneFile.iblFile.Ascii()) > 0) { context->AddProcessDependency("DualIbl", sceneFile.iblFile.Ascii()); } ReturnError_(context->CreateOutput(SceneResource::kDataType, SceneResource::kDataVersion, rootScene->name.Ascii(), *rootScene)); Delete_(rootScene); for(uint scan = 0, count = sceneFile.lightsets.Count(); scan < count; ++scan) { Delete_(sceneFile.lightsets[scan]); } return Success_; } }
43.700599
141
0.571047
schuttejoe
5c7557362a73f40f51615910d3586efe130137ba
1,477
cpp
C++
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
// question link: https://www.geeksforgeeks.org/common-elements-in-all-rows-of-a-given-matrix/ #include <bits/stdc++.h> using namespace std; vector<int> findCommon(vector<vector<int>> &nums) { vector<int> common; unordered_map<int, int> map; // marking all row 0 elements as present for (int j = 0; j < nums[0].size(); j++) { map[nums[0][j]] = 1; } for (int i = 1; i < nums.size(); i++) { for (int j = 0; j < nums[0].size(); j++) { // we initialize first row with 1, here i=0 // then when i =1 we check in map if the count of that element is 1 // increment it by 1, now the count is 2 in map of that element // now in second row i=2 if the element is present then we compare the count of that element in map which is also now 2 with i. if (map[nums[i][j]] == i) { map[nums[i][j]] = i + 1; if ((i == nums.size() - 1) && map[nums[i][j]] == nums.size()) { common.push_back(nums[i][j]); } } } } return common; } int main() { vector<vector<int>> nums = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; vector<int> result = findCommon(nums); for (int j = 0; j < result.size(); j++) { cout << result[j] << " "; } cout << endl; return 0; }
25.912281
139
0.477319
vikkastiwari
5c7610d0031114fd6ae16fbd1d44b0c1e1400667
622
cpp
C++
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
// Name: Tommy Le // This program calculates the tax and tip on a restaurant bill. #include <iostream> int main() { double mealcost,tax,tip,totalbill; std::cout << "Welcome to the Restaurant Bill Calculator!\n"; //Input Meal Cost std::cout << "What is the total meal cost? "; std::cin >> mealcost; //Calculating Tax tax= mealcost * 0.0775; std::cout << "Tax: $" << tax << "\n"; //Calculating Tip tip= mealcost * 0.20; std::cout << "Tip: $" << tip << "\n"; //Calculating Total Bill totalbill=tip+tax+mealcost; std::cout << "Total Bill: $" << totalbill; return 0; }
22.214286
64
0.599678
CSUF-CPSC120-2019F23-24
f07c4142ce407a400c9a397ea735499fd273c066
215
hpp
C++
src/modules/osg/generated_code/TriangleList.pypp.hpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osg/generated_code/TriangleList.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osg/generated_code/TriangleList.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #ifndef TriangleList_hpp__pyplusplus_wrapper #define TriangleList_hpp__pyplusplus_wrapper void register_TriangleList_class(); #endif//TriangleList_hpp__pyplusplus_wrapper
23.888889
44
0.855814
JaneliaSciComp
f07f84cdd2ba1c1e88458535c89ae66d4374b2e5
12,766
cpp
C++
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
15
2019-12-15T21:57:27.000Z
2022-02-22T05:28:24.000Z
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
null
null
null
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
3
2020-07-28T17:19:39.000Z
2021-10-01T09:01:51.000Z
//////////////////////////////////////////////////////////////////////////////// // flash.cpp //////////////////////////////////////////////////////////////////////////////// extern "C" { #include "gd32vf103.h" } #include "GD32VF103/spi.h" #include "GD32VF103/gpio.h" #include "GD32VF103/time.h" #include "Longan/lcd.h" using ::RV::GD32VF103::Spi ; using ::RV::GD32VF103::Gpio ; using ::RV::GD32VF103::TickTimer ; using ::RV::Longan::Lcd ; using ::RV::Longan::LcdArea ; Gpio &button(Gpio::gpioA8()) ; Lcd &lcd(Lcd::lcd()) ; //////////////////////////////////////////////////////////////////////////////// class Flash { private: enum class Cmd { WriteEnable = 0x06, VolatileSrWriteEnable = 0x50, WriteDisable = 0x04, ReleasePowerDownId = 0xAB, // Dummy Dummy Dummy (ID7-ID0) ManufacturerDeviceId = 0x90, // Dummy Dummy 00h (MF7-MF0) (ID7-ID0) JedecId = 0x9F, // (MF7-MF0) (ID15-ID8) (ID7-ID0) UniqueId = 0x4B, // Dummy Dummy Dummy Dummy (UID63-0) ReadData = 0x03, // A23-A16 A15-A8 A7-A0 (D7-D0) FastRead = 0x0B, // A23-A16 A15-A8 A7-A0 Dummy (D7-D0) PageProgram = 0x02, // A23-A16 A15-A8 A7-A0 D7-D0 D7-D0 SectorErase = 0x20, // ( 4KB) A23-A16 A15-A8 A7-A0 BlockErase32 = 0x52, // (32KB) A23-A16 A15-A8 A7-A0 BlockErase64 = 0xD8, // (64KB) A23-A16 A15-A8 A7-A0 ChipErase = 0xC7, // 60h ReadStatusRegister1 = 0x05, // (S7-S0) WriteStatusRegister1 = 0x01, // (S7-S0) ReadStatusRegister2 = 0x35, // (S15-S8) WriteStatusRegister2 = 0x31, // (S15-S8) ReadStatusRegister3 = 0x15, // (S23-S16) WriteStatusRegister3 = 0x11, // (S23-S16) ReadSfdpRegister = 0x5A, // 00h 00h A7–A0 Dummy (D7-D0) EraseSecurityRegister = 0x44, // A23-A16 A15-A8 A7-A0 ProgramSecurityRegister = 0x42, // A23-A16 A15-A8 A7-A0 D7-D0 D7-D0 ReadSecurityRegister = 0x48, // A23-A16 A15-A8 A7-A0 Dummy (D7-D0) GlobalBlockLock = 0x7E, GlobalBlockUnlock = 0x98, ReadBlockLock = 0x3D, // A23-A16 A15-A8 A7-A0 (L7-L0) IndividualBlockLock = 0x36, // A23-A16 A15-A8 A7-A0 IndividualBlockUnlock = 0x39, // A23-A16 A15-A8 A7-A0 EraseProgramSuspend = 0x75, EraseProgramResume = 0x7A, PowerDown = 0xB9, EnableReset = 0x66, ResetDevice = 0x99, } ; public: Flash() : _spi(Spi::spi1()), _cs(Gpio::gpioB8()) { } void setup() { _spi.setup(Spi::Psc::_2) ; // SPI1: 54MHz/2 _cs.setup(Gpio::Mode::OUT_PP) ; _cs.high() ; } void getManufacturerDeviceId(uint8_t &mfid, uint8_t &did) { uint8_t dout[] = { 0x00, 0x00, 0x00 } ; uint8_t din[2] ; xch(Cmd::ManufacturerDeviceId, dout, sizeof(dout), din, sizeof(din)) ; mfid = din[0] ; did = din[1] ; } void getJedecId(uint8_t &mfid, uint8_t &memoryType, uint8_t &capacity) { uint8_t din[3] ; xch(Cmd::JedecId, nullptr, 0, din, sizeof(din)) ; mfid = din[0] ; memoryType = din[1] ; capacity = din[2] ; } void getUniqueId(uint64_t &uid) { uint8_t dout[] = { 0x00, 0x00, 0x00, 0x00 } ; uint8_t din[8] ; xch(Cmd::UniqueId, dout, sizeof(dout), din, sizeof(din)) ; uid = din[0] ; uid <<= 8 ; uid |= din[1] ; uid <<= 8 ; uid |= din[2] ; uid <<= 8 ; uid |= din[3] ; uid <<= 8 ; uid |= din[4] ; uid <<= 8 ; uid |= din[5] ; uid <<= 8 ; uid |= din[6] ; uid <<= 8 ; uid |= din[7] ; } void read(uint32_t addr, uint8_t *data, size_t size) { uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadData, dout, sizeof(dout), data, size) ; } void write(uint32_t addr, uint8_t *data, size_t size) { if ((size == 0) || (size > 256)) return ; xch(Cmd::WriteEnable, nullptr, 0, nullptr, 0) ; uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; uint8_t cc = (uint8_t)Cmd::PageProgram ; _cs.low() ; _spi.xch(&cc, 1, 1) ; _spi.xch(dout, sizeof(dout), 1) ; _spi.xch(data, size, 1) ; _cs.high() ; } void erase(uint32_t addr) { xch(Cmd::WriteEnable, nullptr, 0, nullptr, 0) ; uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::SectorErase, dout, sizeof(dout), nullptr, 0) ; } void waitBusy() { uint8_t dout = (uint8_t) Cmd::ReadStatusRegister1 ; _cs.low() ; _spi.xch(&dout, sizeof(dout), 1) ; uint8_t status ; while (true) { _spi.xch(&status, sizeof(status), 2) ; if (!(status & 0x01)) break ; } _cs.high() ; } void getStatus1(uint8_t &status) { xch(Cmd::ReadStatusRegister1, nullptr, 0, &status, sizeof(status)) ; } void getStatus2(uint8_t &status) { xch(Cmd::ReadStatusRegister2, nullptr, 0, &status, sizeof(status)) ; } void getStatus3(uint8_t &status) { xch(Cmd::ReadStatusRegister3, nullptr, 0, &status, sizeof(status)) ; } bool getSize(uint32_t &size) { #pragma pack(push, 1) struct SfdpHeader { uint32_t _magic ; uint8_t _minor ; uint8_t _major ; uint8_t _count ; // n = _count+1 uint8_t _unused ; } ; struct SfdpParameterHeader { uint8_t _id ; uint8_t _minor ; uint8_t _major ; uint8_t _size ; // in 32 bit uint32_t _offset ; // clear MSByte / only lower 24 Bits used } ; struct SfdpParameter0 { uint32_t _1 ; uint32_t _flashMemoryDensity ; uint32_t _3 ; uint32_t _4 ; uint32_t _5 ; uint32_t _6 ; uint32_t _7 ; uint32_t _8 ; uint32_t _9 ; } ; #pragma pack(pop) SfdpHeader sfdpHdr ; SfdpParameterHeader sfdpParamHdr ; SfdpParameter0 sfdpParam0 ; uint8_t dout[] = { 0x00, 0x00, 0x00, 0x00 } ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpHdr , sizeof(sfdpHdr)) ; if (sfdpHdr._magic != 'PDFS') return false ; uint32_t offset ; uint8_t *o = (uint8_t*)&offset ; offset = sizeof(SfdpHeader) ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpParamHdr , sizeof(sfdpParamHdr)) ; sfdpParamHdr._offset &= 0xffffff ; if (sfdpParamHdr._id != 0) return false ; if (sfdpParamHdr._size < 9) return false ; offset = sfdpParamHdr._offset ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpParam0 , sizeof(sfdpParam0)) ; size = sfdpParam0._flashMemoryDensity ; return true ; } private: void xch(Cmd cmd, uint8_t *txData, size_t txSize, uint8_t *rxData, size_t rxSize) { uint8_t cc = (uint8_t)cmd ; _cs.low() ; _spi.xch(&cc, 1, 1) ; if (txSize) _spi.xch(txData, txSize, 1) ; if (rxSize) _spi.xch(rxData, rxSize, 2) ; _cs.high() ; } private: Spi &_spi ; Gpio &_cs ; } ; //////////////////////////////////////////////////////////////////////////////// uint8_t buttonPressed() { struct State { State() : _value{0x00}, _tick{TickTimer::now()} {} uint8_t _value ; uint64_t _tick ; } ; static State last ; static State current ; uint64_t now = TickTimer::now() ; if ((now - current._tick) < TickTimer::usToTick(2500)) return 0 ; current._tick = now ; current._value = (current._value << 1) | button.get() ; if ((current._value == last._value) || ((current._value != 0x00) && (current._value != 0xff))) return 0 ; uint32_t ms = TickTimer::tickToMs(current._tick - last._tick) ; last = current ; if (current._value) return 0 ; return (ms < 600) ? 1 : 2 ; } //////////////////////////////////////////////////////////////////////////////// int main() { Flash flash ; button.setup(Gpio::Mode::IN_FL) ; lcd.setup() ; flash.setup() ; lcd.clear() ; lcd.txtPos(0) ; lcd.put("Flash ") ; lcd.txtPos(4) ; lcd.put("press button to continue") ; LcdArea lcdWrk(lcd, 0, 160, 16, 48) ; while (true) { { uint8_t mfid ; uint8_t did ; flash.getManufacturerDeviceId(mfid, did) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Manufacturer ID: ") ; lcdWrk.put(mfid, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Device ID: ") ; lcdWrk.put(did, 2, '0', true) ; } while (!buttonPressed()) ; { uint8_t mfid ; uint8_t memoryType ; uint8_t capacity ; flash.getJedecId(mfid, memoryType, capacity) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Manufacturer ID: ") ; lcdWrk.put(mfid, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Memory Type: ") ; lcdWrk.put(memoryType, 2, '0', true) ; lcdWrk.txtPos(2) ; lcdWrk.put("Capacity: ") ; lcdWrk.put(capacity, 2, '0', true) ; } while (!buttonPressed()) ; { uint64_t uid ; flash.getUniqueId(uid) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Unique ID: ") ; lcdWrk.txtPos(1) ; lcdWrk.put((uint32_t)(uid>>32), 8, '0', true) ; lcdWrk.put((uint32_t)(uid>> 0), 8, '0', true) ; } while (!buttonPressed()) ; { uint32_t size ; uint64_t size64 ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Size: ") ; if (flash.getSize(size)) { if (size & 0x80000000) size64 = 1LL << size ; else size64 = size + 1 ; size64 >>= 3 ; // bit to byte if (size64 > (1LL << 30)) { size64 >>= 30 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("GByte") ; } else if (size64 > (1LL << 20)) { size64 >>= 20 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("MByte") ; } else if (size64 > (1LL << 20)) { size64 >>= 10 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("kByte") ; } else { lcdWrk.put((uint32_t)size64) ; lcdWrk.put("Byte") ; } } else lcdWrk.put('?') ; } while (!buttonPressed()) ; { uint8_t status1 ; uint8_t status2 ; uint8_t status3 ; flash.getStatus1(status1) ; flash.getStatus2(status2) ; flash.getStatus3(status3) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Status1: ") ; lcdWrk.put(status1, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Status2: ") ; lcdWrk.put(status2, 2, '0', true) ; lcdWrk.txtPos(2) ; lcdWrk.put("Status3: ") ; lcdWrk.put(status3, 2, '0', true) ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } } while (!buttonPressed()) ; { const char *txt = "Hallo Welt?!" ; flash.write(0x1000, (uint8_t*)txt, 11) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Write") ; lcdWrk.txtPos(1) ; lcdWrk.put("...") ; flash.waitBusy() ; lcdWrk.put(" done") ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } lcdWrk.clearEOL() ; } while (!buttonPressed()) ; { flash.erase(0x1000) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Erase") ; lcdWrk.txtPos(1) ; lcdWrk.put("...") ; flash.waitBusy() ; lcdWrk.put(" done") ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } lcdWrk.clearEOL() ; } while (!buttonPressed()) ; } } //////////////////////////////////////////////////////////////////////////////// // EOF ////////////////////////////////////////////////////////////////////////////////
24.933594
100
0.513943
MuellerA
f07fddd0d7e9745b75518d3d5266c40ab673b3d0
13,076
cpp
C++
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
#include <iostream> #include <stdexcept> #include "../globals.hpp" #include "opcodes.hpp" using namespace std; opcodes::opcodes() { std::map<unsigned short, int> optable; } opcodes::~opcodes() { } /** * Gets function from the hashtable at a given index - If the function has not yet * been added to the lookup table it is inserted here with the key of the opcode * that has called it * * @param o opcode */ func_p opcodes::get(unsigned short o) { // Check if instruction already exists in opcode lookup table // If not then decode instruction based on HPP header and add to lookup int instruction = lookup(o); if ( instruction == -1 ) { instruction = decode( o ); if ( instruction != -1 ) { cerr << "Inserting new opcode: " << std::hex << o << " with key: " << std::hex << instruction << endl; optable.insert( std::pair<unsigned short, int>(o, instruction) ); } else { throw std::runtime_error("Invalid opcode: " + to_string(o)); } } // Run instruction from opcode lookup table, passes along current opcode operation return oplist[instruction]; } /** * Checks if an instruction already exists in the optable * If not it will be decoded and added for faster lookup next time * * @param o Opcode * * @return Returns the index location of function to call */ int opcodes::lookup(unsigned short o) { // Find in optable auto search = optable.find(o); if ( search != optable.end() ) return search->second; else return -1; } /** * Decodes a given opcode and returns an index * * @param o Opcode * * @return Returns the index location lookup key of the function to call */ int opcodes::decode(unsigned short o) { cerr << "Parsing new opcode: " << std::hex << o << endl; switch( o & 0xF000) { case 0x0000: switch( o & 0x0F00 ) { case 0x0000: switch( o & 0x000F ) { case 0x0000: return 1; break; case 0x000E: return 2; break; } break; default: return 0; } break; case 0x1000: return 3; break; case 0x2000: return 4; break; case 0x3000: return 5; break; case 0x4000: return 6; break; case 0x5000: return 7; break; case 0x6000: return 8; break; case 0x7000: return 9; break; case 0x8000: switch( o & 0x000F ) { case 0x0000: return 10; break; case 0x0001: return 11; break; case 0x0002: return 12; break; case 0x0003: return 13; break; case 0x0004: return 14; break; case 0x0005: return 15; break; case 0x0006: return 16; break; case 0x0007: return 17; break; case 0x000E: return 18; break; } break; case 0x9000: return 19; break; case 0xA000: return 20; break; case 0xB000: return 21; break; case 0xC000: return 22; break; case 0xD000: return 23; break; case 0xE000: switch( o & 0x00FF ) { case 0x009E: return 24; break; case 0x00A1: return 25; break; } break; case 0xF000: switch ( o & 0x00FF ) { case 0x0007: return 26; break; case 0x000A: return 27; break; case 0x0015: return 28; break; case 0x0018: return 29; break; case 0x001E: return 30; break; case 0x0029: return 31; break; case 0x0033: return 32; break; case 0x0055: return 33; break; case 0x0065: return 34; break; } break; } cerr << "Unknown opcode encountered: " << o << endl; return -1; } /** * @brief Calls RCA 1802 program at address NNN. * Not necessary for most ROMs */ void opcodes::op0NNN(cpu* proc) { } /** * @brief Clears the screen */ void opcodes::op00E0(cpu* proc) { proc->clearScreen = true; } /** * Returns from a subroutine */ void opcodes::op00EE(cpu* proc) { proc->setPC(proc->popStack()); } /** * Jumps to address NNN */ void opcodes::op1NNN(cpu* proc) { proc->setPC( proc->getOP() & 0x0FFF ); } /** * Calls subroutine at NNN */ void opcodes::op2NNN(cpu* proc) { proc->pushStack( proc->getPC() ); proc->setPC( proc->getOP() & 0x0FFF ); } /** * Skips the next instruction if VX equals NN */ void opcodes::op3XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); if ( proc->getV( x ) == n ) { proc->stepPC(1); } } /** * Skips the next instruction if VX doesn't equal NN */ void opcodes::op4XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); if ( proc->getV( x ) != n ) { proc->stepPC(1); } } /** * Skips the next instruction if VX equals VY */ void opcodes::op5XY0(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; if ( proc->getV(x) == proc->getV(y) ) { proc->stepPC(1); } } /** * Sets VX to NN */ void opcodes::op6XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); proc->setV(x, n); } /** * Adds NN to VX */ void opcodes::op7XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); proc->setV(x, proc->getV(x) + n); } /** * Sets VX to the value of VY */ void opcodes::op8XY0(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV( x, proc->getV( y ) ); } /** * Sets VX to VX or VY */ void opcodes::op8XY1(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) | proc->getV(y)); } /** * Sets VX to VX and VY */ void opcodes::op8XY2(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) & proc->getV(y)); } /** * Sets VX to VX xor VY */ void opcodes::op8XY3(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) ^ proc->getV(y)); } /** * Adds VY to VX. VF is set to 1 when there's a carry, * and to 0 when there isn't */ void opcodes::op8XY4(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short sum = proc->getV(x) + proc->getV(y); if (sum > 0xFF) { proc->setV(0xF, 1); sum -= 0x100; } proc->setV(x, sum); } /** * VY is subtracted from VX. VF is set to 0 when there's a * borrow, and 1 when there isn't */ void opcodes::op8XY5(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short diff = proc->getV(x) - proc->getV(y); proc->setV(0xF, 1); if (diff < 0) { proc->setV(0xF, 0); diff += 0x100; } proc->setV(x, diff); } /** * Shifts VX right by one. VF is set to the value * of the least significant bit of VX before the shift */ void opcodes::op8XY6(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; // Get least significant bit proc->setV(0xF, proc->getV(x) & 0x1); proc->setV(x, proc->getV(x) >> 1); } /** * Sets VX to VY minus VX. VF is set to 0 when there's a borrow, * and 1 when there isn't */ void opcodes::op8XY7(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short diff = proc->getV(y) - proc->getV(x); proc->setV(0xF, 1); if (diff < 0) { proc->setV(0xF, 0); diff += 0x100; } proc->setV(x, diff); } /** * Shifts VX left by one.VF is set to the value of the * most significant bit of VX before the shift */ void opcodes::op8XYE(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setV(0xF, proc->getV(x) >> 7); proc->setV(x, proc->getV(x) << 1); } /** * Skips the next instruction if VX doesn't equal VY */ void opcodes::op9XY0(cpu* proc) { unsigned short x = ( proc->getOP() & 0x0F00 ) >> 8; unsigned short y = ( proc->getOP() & 0x00F0 ) >> 4; if ( proc->getV(x) != proc->getV(y) ) { proc->stepPC(1); } } /** * Sets I to the address NNN */ void opcodes::opANNN(cpu* proc) { proc->setI( proc->getOP() & 0x0FFF ); } /** * Jumps to the address NNN plus V0 */ void opcodes::opBNNN(cpu* proc) { proc->setPC( (proc->getOP() & 0x0FFF) + proc->getV(0) ); } /** * Sets VX to the result of a bitwise and * operation on a random number and NN */ void opcodes::opCXNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short v_nn = proc->getOP() & 0x00FF; // TODO: generate random byte in the following format int r = ((rand() % (0xF + 1 - 0x0)) + 0x0); proc->setV(x, r & v_nn); } /** * Sprites stored in memory at location in index register (I), * 8bits wide. Wraps around the screen. If when * drawn, clears a pixel, register VF is set to 1 otherwise it is * zero. All drawing is XOR drawing (i.e. it toggles the screen pixels). * Sprites are drawn starting at position VX, VY. N is the number of 8bit * rows that need to be drawn. If N is greater than 1, * second line continues at position VX, VY+1, and so on */ void opcodes::opDXYN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; unsigned short nRows = (proc->getOP() & 0x000F); proc->setV(0xF, 0); // Normalized coordinates unsigned short xPos = proc->getV(x) % c8_display::INTERNAL_WIDTH; unsigned short yPos = proc->getV(y) % c8_display::INTERNAL_HEIGHT; // Iterate over display for (int row = 0; row < nRows; ++row) { unsigned short sprite = proc->mem->get(proc->getI() + row); for (int col = 0; col < 8; ++col) { if ((sprite & (0x80 >> col)) != 0) { unsigned short index = ((yPos + row) * c8_display::INTERNAL_WIDTH) + (xPos + col); index %= (c8_display::INTERNAL_WIDTH * c8_display::INTERNAL_HEIGHT); unsigned char gfxVal = proc->gfx->getPixel(index); if (gfxVal == 0xF) { proc->setV(0xF, 1); } gfxVal ^= 0xF; proc->gfx->setPixel(index, gfxVal); } } } proc->drawFlag = true; } /** * Skips the next instruction if the key stored in VX is pressed */ void opcodes::opEX9E(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short key = proc->getV(x); if (proc->keyPressed(key)) { proc->stepPC(1); } } /** * Skips the next instruction if the key stored in VX isn't pressed */ void opcodes::opEXA1(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short key = proc->getV(x); if (!proc->keyPressed(key)) { proc->stepPC(1); } } /** * Sets VX to the value of the delay timer */ void opcodes::opFX07(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setV(x, proc->delayTimer); } /** * A key press is awaited, and then stored in VX */ void opcodes::opFX0A(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; bool keyPressed = false; while (!keyPressed) { for (int i = 0; i < 0xF; i++) { if (proc->keyPressed(i)) { proc->setV(x, i); keyPressed = true; break; } } } } /** * Sets the delay timer to VX */ void opcodes::opFX15(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->delayTimer = proc->getV(x); } /** * Sets the sound timer to VX */ void opcodes::opFX18(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->soundTimer = proc->getV(x); } /** * Adds VX to I */ void opcodes::opFX1E(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setI(proc->getI() + proc->getV(x)); } /** * Sets I to the location of the sprite for the shortacter in VX. * shortacters 0-F (in hexadecimal) are represented by a 4x5 font */ void opcodes::opFX29(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setI(proc->getV(x) * 5); } /** * Stores the Binary-coded decimal representation of VX, * with the most significant of three digits at the address in I, * the middle digit at I plus 1, and the least significant digit at * I plus 2. (In other words, take the decimal representation of VX, * place the hundreds digit in memory at location in I, * the tens digit at location I+1, * and the ones digit at location I+2) */ void opcodes::opFX33(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short vx = proc->getV(x); for (int i = 2; i >= 0; i--) { proc->mem->set(proc->getI() + i, vx % 10); vx /= 10; } } /** * Stores V0 to VX in memory starting at address I */ void opcodes::opFX55(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; for (int i = 0; i <= x; ++i) { proc->mem->set( proc->getI() + i, proc->getV(i) ); } } /** * Fills V0 to VX with values from memory starting at address I */ void opcodes::opFX65(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; for (int i = 0; i <= x; ++i) { proc->setV( i, proc->mem->get(proc->getI() + i) ); } }
19.229412
106
0.601101
bryan-pakulski
f0844ff5707784bddf9aff38dcd89c3fded92da1
941
cpp
C++
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
1
2022-02-15T12:53:00.000Z
2022-02-15T12:53:00.000Z
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int postfixEvaluation(string s) { stack<double> st; for (int i = 0; i < s.length(); i++) { if (s[i] >= '0' && s[i] <= '9') { st.push(s[i] - '0'); } else { double op2 = st.top(); st.pop(); double op1 = st.top(); st.pop(); switch (s[i]) { case '+': st.push(op1 + op2); case '-': st.push(op1 - op2); case '*': st.push(op1 * op2); case '/': st.push(op1 / op2); break; case '^': st.push(pow(op1, op2)); break; default: break; } } } return st.top(); } int main() { cout << postfixEvaluation("46+2/5*7+") << endl; return 0; }
19.604167
51
0.336876
gaurav147-star
f084a7ccdba1a870071401028679bfbe7618d1f6
2,386
cpp
C++
phoenix/.test/test-listicons.cpp
vgmtool/vgm2pre
f4f917df35d531512292541234a5c1722b8af96f
[ "MIT" ]
21
2015-04-13T03:07:12.000Z
2021-11-20T00:27:00.000Z
phoenix/.test/test-listicons.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2015-10-06T14:59:48.000Z
2022-01-27T08:57:57.000Z
phoenix/.test/test-listicons.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2021-11-19T08:36:57.000Z
2022-03-04T16:03:16.000Z
#include "phoenix.hpp" using namespace nall; using namespace phoenix; struct TestWindow : Window { TestWindow() { setGeometry({64, 64, 480, 640}); setTitle("Test Window"); onClose = [&] { setVisible(false); }; } } *testWindow = nullptr; struct Application : Window { VerticalLayout layout; ListView listView; ListView test; ComboBox comboView; Button button; Label label; Menu file; Menu submenu; Item quit; Application() { setTitle("Main Window"); setGeometry({128, 128, 640, 480}); file.setText("File"); submenu.setText("Submenu"); submenu.setImage(image("folder.png")); quit.setText("Quit"); quit.setImage(image("image.png")); //submenu.setImage(); //quit.setImage(); setMenuVisible(); append(file); file.append(submenu); file.append(quit); listView.setHeaderText("Column 1", "Column 2", "Column 3"); listView.setHeaderVisible(); listView.setCheckable(); listView.append("A", "B", "C"); listView.append("D", "E", "F"); listView.append("G", "H", "I"); test.setHeaderText("Column 1", "Column 2"); test.setHeaderVisible(); test.append("A", "B"); test.append("C", "D"); test.append("E", "F"); listView.setImage(0, 0, image("image.png")); listView.setImage(1, 0, image("folder.png")); listView.setImage(2, 2, image("folder.png")); //listView.setImage(0, 0); //listView.setImage(1, 0); //button.setText("Hello"); button.setImage(image("image.png")); //button.setImage(); label.setText("Label"); append(layout); layout.setMargin(5); layout.append(listView, {~0, ~0}, 5); layout.append(test, {~0, ~0}, 5); layout.append(comboView, {~0, 0}, 5); layout.append(button, {~0, 0}, 5); layout.append(label, {~0, 0}); comboView.append("item1", "item2*", "item3", "item4", "item5", "item6", "item7", "item8"); button.onActivate = [&] { testWindow->setVisible(); //DialogWindow::folderSelect(*this, "c:/users/byuu/appdata/roaming/emulation"); //, "All files (*)"); //listView.remove(1); //comboView.modify(1, "item2"); //comboView.remove(2); }; setVisible(); onClose = &OS::quit; } } *application = nullptr; int main() { OS::setName("higan"); testWindow = new TestWindow; application = new Application; OS::main(); return 0; }
23.86
108
0.604359
vgmtool
f08869385b8bd0b0f20dd057ebc8fdbf6b9426c8
298
cpp
C++
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
1
2020-05-25T15:32:23.000Z
2020-05-25T15:32:23.000Z
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
null
null
null
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int main(){ int k; ll sum = 0; cin >> k; for(int i=1; i<=k; i++){ for(int j=1; j<=k; j++){ int a = __gcd(i, j); for(int l=1; l<=k; l++){ sum+= __gcd(a, l); } } } cout << sum << endl; return 0; }
12.416667
27
0.47651
igortakeo
f08c2d61feb5de0e5929ee721e6e49d47a942450
53
cpp
C++
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
#include "Capstan/Allocators/DoubleStackAllocator.h"
26.5
52
0.849057
teemid
f0944e557457ef143775a29eda3792bb6760d37e
23,656
cpp
C++
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
1
2021-01-27T12:23:43.000Z
2021-01-27T12:23:43.000Z
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
null
null
null
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
null
null
null
#include "Canopen.hpp" #include "ANSIEscapeCodes.hpp" #include "CanFestivalLocker.hpp" #include "Logging.hpp" #include "PeripheralDrivers/CanIO.hpp" #include "PeripheralDrivers/TerminalIO.hpp" #include <algorithm> namespace remote_control_device { Canopen *Canopen::_instance = nullptr; Message Canopen::RTD_StateBootupMessage = { Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Bootup, 0, 0, 0, 0, 0, 0, 0}}; Message Canopen::RTD_StateReadyMessage = { Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Ready, 0, 0, 0, 0, 0, 0, 0}}; Message Canopen::RTD_StateEmcyMessage = {Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Emergency, 0, 0, 0, 0, 0, 0, 0}}; Canopen::Canopen(CanIO &canio, Logging &log, bool bypass) : _canIO(canio), _log(log), _monitoredDevices{{MonitoredDevice(BusDevices::DriveMotorController), MonitoredDevice(BusDevices::BrakeActuator), MonitoredDevice(BusDevices::BrakePressureSensor), MonitoredDevice(BusDevices::SteeringActuator), MonitoredDevice(BusDevices::SteeringAngleSensor)}}, _stateControlledDevices{ {StateControlledDevice(BusDevices::DriveMotorController, CanDeviceState::Operational), StateControlledDevice(BusDevices::BrakeActuator, CanDeviceState::Operational), StateControlledDevice(BusDevices::SteeringActuator, CanDeviceState::Operational), StateControlledDevice(BusDevices::BrakePressureSensor, CanDeviceState::Operational)}}, _couplings{{Coupling(BusDevices::BrakeActuator, BrakeActuatorCoupling_IndexOD, BrakeActuatorCoupling_SubIndexOD, BrakeActuatorCoupling_EngagedValue, BrakeActuatorCoupling_DisEngagedValue), Coupling(BusDevices::SteeringActuator, SteeringActuatorCoupling_IndexOD, SteerinActuatorCoupling_SubIndexOD, SteerinActuatorCoupling_EngagedValue, SteerinActuatorCoupling_DisEngagedValue)}} { specialAssert(_instance == nullptr); _instance = this; if (bypass) { return; } { CFLocker locker; setNodeId(locker.getOD(), static_cast<UNS8>(BusDevices::RemoteControlDevice)); // fix for REPEAT_NMT_MAX_NODE_ID_TIMES not having enough repeats by default thus not // initializing the NMT table correctly which makes post_SlaveStateChange miss bootup // events for nodes with higher ids for (auto &e : locker.getOD()->NMTable) { e = Unknown_state; } // set zero values to not have canfestival send pure zeros 0 // which could cause damage setBrakeForce(0.0); setSteeringAngle(0.0); setWheelDriveTorque(0.0); setSelfState(StateId::Start); RTD_State = RTD_State_Bootup; setTPDO(TPDOIndex::SelfState, true); setActuatorPDOs(false); // setup callbacks locker.getOD()->heartbeatError = &cbHeartbeatError; locker.getOD()->post_SlaveStateChange = &cbSlaveStateChange; // avoids global reset sent out // preOperational callback is pre-programmed with // masterSendNMTstateChange (d, 0, NMT_Reset_Node) // by overwriting the callback we stop this from being sent locker.getOD()->preOperational = [](CO_Data *d) -> void {}; setState(locker.getOD(), Initialisation); setState(locker.getOD(), Operational); // RX timeout requires a timer table that can't be generated and is initialized with NULL // every time adding our own // also the stack has a bug in timeout registration (since fixed) // where it reads from the wrong memory address and uses garbage for the timeout value std::fill(_rpdoTimers.begin(), _rpdoTimers.end(), TIMER_NONE); locker.getOD()->RxPDO_EventTimers = _rpdoTimers.data(); // hack in rpdo timeout callback as it can't be registered anyhere locker.getOD()->RxPDO_EventTimers_Handler = [](CO_Data *d, UNS32 timerId) -> void { // remove reference to previously used timer // if not done, the next reception of this rpdo will clear the timer spot previously // used again even though it could be attributed to something completely different d->RxPDO_EventTimers[timerId] = TIMER_NONE; // NOLINT testHook_signalRTDTimeout(); _instance->signalRTDTimeout(); }; // when a rpdo is received, the OD entry where RTD_State resides is updated, every entry // can have a callback so we use this cb to reset the timeout flag set by the rpdo timeout RegisterSetODentryCallBack(locker.getOD(), RTD_State_ODIndex, RTD_State_ODSubIndex, [](CO_Data *d, const indextable *, UNS8 bSubindex) -> UNS32 { testHook_signalRTDRecovery(); _instance->signalRTDRecovery(); return OD_SUCCESSFUL; }); // rpdo timeout is a poorly supported feature in canopen // canfestival is also not capable to start the rpdo timeout unless at least // one message was received, so dispatch one fake message to get the timer going _canIO.addRXMessage(RTD_StateBootupMessage); } } Canopen::~Canopen() { _instance = nullptr; CFLocker locker; locker.getOD()->RxPDO_EventTimers = nullptr; } bool Canopen::isDeviceOnline(const BusDevices device) const { for (auto &dev : _monitoredDevices) { if (dev.device == device) { return !dev.disconnected; } } return false; } void Canopen::drawUIDevicesPart(TerminalIO &term) { term.write(ANSIEscapeCodes::ColorSection_WhiteText_GrayBackground); term.write("\r\nMonitored Devices:\r\n"); term.write(ANSIEscapeCodes::ColorSection_End); auto printMonitoredDevice = [&](const MonitoredDevice &dev) -> void { if (dev.disconnected) { term.write(ANSIEscapeCodes::ColorSection_WhiteText_RedBackground); } term.write(getBusDeviceName(dev.device)); if (dev.disconnected) { term.write(": Offline"); term.write(ANSIEscapeCodes::ColorSection_End); } else { term.write(": Online"); } term.write("\r\n"); }; for (auto &dev : _monitoredDevices) { printMonitoredDevice(dev); } MonitoredDevice rtd(BusDevices::RealTimeDevice); rtd.disconnected = _rtdTimeout; printMonitoredDevice(rtd); term.write(ANSIEscapeCodes::ColorSection_WhiteText_GrayBackground); term.write("\r\nState Controlled Devices:\r\n"); term.write(ANSIEscapeCodes::ColorSection_End); for (auto &scd : _stateControlledDevices) { if (scd.targetState != scd.currentState) { term.write(ANSIEscapeCodes::ColorSection_BlackText_YellowBackground); } term.write(getBusDeviceName(scd.device)); term.write(": "); term.write(getCanDeviceStateName(scd.currentState)); term.write(" (Target: "); term.write(getCanDeviceStateName(scd.targetState)); term.write(")"); if (scd.targetState != scd.currentState) { term.write(ANSIEscapeCodes::ColorSection_End); } term.write("\r\n"); } } void Canopen::kickstartPDOTranmission() { // setState(operational) calls sendPDOEvent which // causes the stack to register event timers for continous sending for all // enabled PDOs. As only self state is enabled by default // All other pdos get left behind and will not start transmitting // on their own until sendPDOEvent is called again. // Also: The stack has an oversight within pdo transmission in where there is no easy way // to force it to transmit a pdo with the same data continously. Every time a pdo tries to get // sent it is compared against the last one and if it is the same the function aborts. In this // case the event timers are not re-registered and the pdo is functionally broken You could do // something like this here below after every pdo transmission /*lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::SelfState)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::BrakeForce)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::SteeringAngle)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::MotorTorque)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::TargetValues)].last_message.cob_id = 0;*/ // bus this is tedious as there is no callback to hook into after a pdo has fired. // So to avoid all this b.s. pdo.c was modified in line 539 to not compare at all. CFLocker lock; sendPDOevent(lock.getOD()); } void Canopen::setSelfState(const StateId state) { { CFLocker locker; SelfState = static_cast<UNS8>(state); } } void Canopen::setBrakeForce(float force) { { CFLocker locker; BrakeTargetForce = mapValue<float, INTEGER16>(0.0f, 1.0f, BrakeForceRaw_Min, BrakeForceRaw_Max, force); } } void Canopen::setWheelDriveTorque(float torque) { { CFLocker locker; WheelTargetTorque = mapValue<float, INTEGER16>(-1.0f, 1.0f, WheelDriveTorqueRaw_Min, WheelDriveTorqueRaw_Max, torque); } } void Canopen::setSteeringAngle(float angle) { // inverted due to hardware gearing angle *= -1.0f; { CFLocker locker; SteeringTargetAngle = mapValue<float, INTEGER32>(-1.0f, 1.0f, SteeringAngleRaw_Min, SteeringAngleRaw_Max, angle); } } void Canopen::setCouplingStates(bool brake, bool steering) { { CFLocker locker; _setCouplingState(_couplings[CouplingIndex_Brake], steering); _setCouplingState(_couplings[CouplingIndex_Steering], brake); } } void Canopen::setTPDO(const TPDOIndex index, bool enable) { { CFLocker locker; if (enable) { PDOEnable(locker.getOD(), static_cast<UNS8>(index)); } else { PDODisable(locker.getOD(), static_cast<UNS8>(index)); } } } void Canopen::setActuatorPDOs(bool enable) { setTPDO(TPDOIndex::BrakeForce, enable); setTPDO(TPDOIndex::SteeringAngle, enable); setTPDO(TPDOIndex::MotorTorque, enable); setTPDO(TPDOIndex::TargetValues, enable); if (enable) { kickstartPDOTranmission(); } } void Canopen::update(BusDevicesState &target) { { CFLocker locker; target.rtdEmergency = RTD_State == RTD_State_Emergency; target.rtdBootedUp = RTD_State != RTD_State_Bootup; } target.timeout = false; for (auto &e : _monitoredDevices) { target.timeout = target.timeout || e.disconnected; } target.timeout = target.timeout || _rtdTimeout; } void Canopen::cbSlaveStateChange(CO_Data *d, UNS8 heartbeatID, e_nodeState state) { const auto dev = static_cast<BusDevices>(heartbeatID); // state controlled devices int8_t index{0}; if ((index = _instance->findInStateControlledList(dev)) != -1) { { CFLocker lock; // interpret node state to check if device is in correct state CanDeviceState convertedState = CanDeviceState::Unknown; switch (state) { case e_nodeState::Operational: convertedState = CanDeviceState::Operational; break; case e_nodeState::Pre_operational: convertedState = CanDeviceState::Preoperational; break; case e_nodeState::Initialisation: /* fall through */ case e_nodeState::Disconnected: /* fall through */ case e_nodeState::Connecting: /* fall through */ // case Preparing: has same value as connecting /* fall through */ case e_nodeState::Stopped: /* fall through */ case e_nodeState::Unknown_state: /* fall through */ default: break; } _instance->_stateControlledDevices[index].currentState = convertedState; _instance->_log.logInfo(Logging::Origin::BusDevices, "%s changed state to %s", getBusDeviceName(dev), getCanDeviceStateName(convertedState)); if (convertedState != _instance->_stateControlledDevices[index].targetState) { _instance->setDeviceState( dev, _instance->_stateControlledDevices[index].targetState); } } } // reset disconnected state for (MonitoredDevice &e : _instance->_monitoredDevices) { if (e.device == dev && e.disconnected) { _instance->_log.logInfo(Logging::Origin::BusDevices, "%s is online", getBusDeviceName(dev)); e.disconnected = false; return; } } } void Canopen::cbHeartbeatError(CO_Data *d, UNS8 heartbeatID) { // Called when a node registered in the heartbeat consumer od index // didn't send a heartbeat within the timeout range // after timeout the node's state is changed to disconnected internally // when the timed out node recovers, slave state change callback is called const auto dev = static_cast<BusDevices>(heartbeatID); _instance->_log.logInfo(Logging::Origin::BusDevices, "%s timed out", getBusDeviceName(dev)); // Reset internal current state when device is state monitored // so UI doesn't show wrong information int8_t index = 0; if ((index = _instance->findInStateControlledList(dev)) != -1) { _instance->_stateControlledDevices[index].currentState = CanDeviceState::Unknown; } for (MonitoredDevice &e : _instance->_monitoredDevices) { if (e.device == dev) { e.disconnected = true; return; } } _instance->_log.logWarning(Logging::Origin::BusDevices, "Received heartbeat error callback for nodeId %d but it isn't registered as a " "monitored device", heartbeatID); } void Canopen::cbSDO(CO_Data *d, UNS8 nodeId) { // search for coupling with nodeid Coupling *coupling = nullptr; for (Coupling &e : _instance->_couplings) { if (e.device == static_cast<BusDevices>(nodeId)) { coupling = &e; break; } } if (coupling == nullptr) { _instance->_log.logDebug(Logging::Origin::BusDevices, "Unexpected SDO received from nodeId %d", nodeId); return; } bool restart = false; uint32_t abortCode = 0; if (getWriteResultNetworkDict(d, nodeId, &abortCode) != SDO_FINISHED) { // transfer failed // abortCode is 0 for timeout which isn't correct // but flow errors in the stack cause this to be 0 if (abortCode == 0) { // timeout, try again restart = true; } else { // serious error, most likely ill configured node // not attempting new transmission as these errors are more likely // to come from an active node which answers quickly (like we do) // causing risk of flooding _instance->_log.logWarning(Logging::Origin::BusDevices, "SDO to nodeId %d failed (%s)", nodeId, abortCodeToString(abortCode)); restart = false; } } else { // sucess but check if target changed mid request processing if (coupling->stateForThisRequest != coupling->targetState) { _instance->_log.logDebug(Logging::Origin::BusDevices, "SDO finished successfully but state changed mid transmission"); restart = true; } else { _instance->_log.logDebug(Logging::Origin::BusDevices, "SDO finished successfully"); } } // closing isn't necessary when the transfer is finished but this isn't always the case closeSDOtransfer(d, nodeId, SDO_CLIENT); if (restart) { // logDebug(Logging::Origin::BusDevices, "Repeating transmission"); _instance->_setCouplingState(*coupling, coupling->targetState); } } const char *Canopen::abortCodeToString(uint32_t abortCode) { switch (abortCode) { /* case OD_SUCCESSFUL: return "OD_SUCCESSFUL"; case OD_READ_NOT_ALLOWED: return "OD_READ_NOT_ALLOWED"; case OD_WRITE_NOT_ALLOWED: return "OD_WRITE_NOT_ALLOWED"; case OD_NO_SUCH_OBJECT: return "OD_NO_SUCH_OBJECT"; case OD_NOT_MAPPABLE: return "OD_NOT_MAPPABLE"; case OD_ACCES_FAILED: return "OD_ACCES_FAILED"; case OD_LENGTH_DATA_INVALID: return "OD_LENGTH_DATA_INVALID"; case OD_NO_SUCH_SUBINDEX: return "OD_NO_SUCH_SUBINDEX"; case OD_VALUE_RANGE_EXCEEDED: return "OD_VALUE_RANGE_EXCEEDED"; case OD_VALUE_TOO_LOW: return "OD_VALUE_TOO_LOW"; case OD_VALUE_TOO_HIGH: return "OD_VALUE_TOO_HIGH"; case SDOABT_TOGGLE_NOT_ALTERNED: return "SDOABT_TOGGLE_NOT_ALTERNED"; case SDOABT_TIMED_OUT: return "SDOABT_TIMED_OUT"; case SDOABT_CS_NOT_VALID: return "SDOABT_CS_NOT_VALID"; case SDOABT_INVALID_BLOCK_SIZE: return "SDOABT_INVALID_BLOCK_SIZE"; case SDOABT_OUT_OF_MEMORY: return "SDOABT_OUT_OF_MEMORY"; case SDOABT_GENERAL_ERROR: return "SDOABT_GENERAL_ERROR"; case SDOABT_LOCAL_CTRL_ERROR: return "SDOABT_LOCAL_CTRL_ERROR";*/ default: return "Error Unknown"; } } int8_t Canopen::findInStateControlledList(const BusDevices device) { for (uint8_t i = 0; i < _stateControlledDevices.size(); ++i) { if (_stateControlledDevices[i].device == device) { return i; } } return -1; } void Canopen::setDeviceState(const BusDevices device, CanDeviceState state) { // check if allowed to change state int8_t index = findInStateControlledList(device); if (index == -1) { _instance->_log.logWarning(Logging::Origin::BusDevices, "Denied request to change state of unlisted device with nodeId %d", static_cast<uint8_t>(device)); return; } uint8_t nmtCommand = 0; switch (state) { case CanDeviceState::Operational: nmtCommand = NMT_Start_Node; break; case CanDeviceState::Preoperational: nmtCommand = NMT_Enter_PreOperational; break; case CanDeviceState::Unknown: /* fall through */ default: return; } _instance->_log.logInfo(Logging::Origin::BusDevices, "Requesting %s to change status to %s", getBusDeviceName(device), getCanDeviceStateName(state)); _stateControlledDevices[index].targetState = state; { CFLocker locker; masterSendNMTstateChange(locker.getOD(), static_cast<uint8_t>(_stateControlledDevices[index].device), nmtCommand); // masterSendNMTstateChange is just blindly transmitting the state change request // when a node doesn't switch it isn't noticed as proceedNODE_GUARD which processes incoming // heartbeats compares the old state with the unchanged newly received one and finds no // difference // invalidating the local state of a node will force the change state callback to be fired // which allows confirming the state change or retrying locker.getOD()->NMTable[static_cast<UNS8>(_stateControlledDevices[index].device)] = Disconnected; } } const char *Canopen::getBusDeviceName(const BusDevices dev) { switch (dev) { case BusDevices::DriveMotorController: return "Drive Motor Controller (10h)"; case BusDevices::BrakeActuator: return "Brake Actuator (20h)"; case BusDevices::SteeringActuator: return "Steering Actuator (30h)"; case BusDevices::RemoteControlDevice: return "Remote Control Device (1h)"; case BusDevices::RealTimeDevice: return "Real Time Device (2h)"; case BusDevices::WheelSpeedSensor: return "Wheel Speed Sensor (11h)"; case BusDevices::BrakePressureSensor: return "Brake Pressure Sensor (21h)"; case BusDevices::SteeringAngleSensor: return "Steering Angle Sensor (31h)"; default: return "Unamed device"; } } Canopen::Coupling::Coupling(BusDevices device, uint16_t odIndex, uint8_t odSubIndex, uint32_t engagedValue, uint32_t disengagedValue) : device(device), odIndex(odIndex), odSubIndex(odSubIndex), engagedValue(engagedValue), disengagedValue(disengagedValue) { } void Canopen::_setCouplingState(Coupling &coupling, bool state) { coupling.targetState = state; // check if sdo is still in porgress { CFLocker locker; UNS32 abortCode = 0; if (getWriteResultNetworkDict(locker.getOD(), static_cast<UNS8>(coupling.device), &abortCode) == SDO_ABORTED_INTERNAL) { // nothing in progress, start write request coupling.stateForThisRequest = coupling.targetState; uint32_t couplingState = coupling.stateForThisRequest ? coupling.engagedValue : coupling.disengagedValue; writeNetworkDictCallBack(locker.getOD(), static_cast<UNS8>(coupling.device), coupling.odIndex, coupling.odSubIndex, 4, uint32, &couplingState, &Canopen::cbSDO, false); } else { _instance->_log.logInfo(Logging::Origin::BusDevices, "SDO transfer already in progress, repeating after this one finished"); } } } std::array<Canopen::BusDevices, Canopen::MonitoredDeviceCount> Canopen::getMonitoredDevices() const { std::array<Canopen::BusDevices, Canopen::MonitoredDeviceCount> list; for (uint8_t i = 0; i < _monitoredDevices.size(); ++i) { list[i] = _monitoredDevices[i].device; } return list; } std::array<Canopen::BusDevices, Canopen::StateControlledDeviceCount> Canopen::getStateControlledDevices() const { std::array<Canopen::BusDevices, Canopen::StateControlledDeviceCount> list; for (uint8_t i = 0; i < _stateControlledDevices.size(); ++i) { list[i] = _stateControlledDevices[i].device; } return list; } } // namespace remote_control_device
36.337942
113
0.625592
sprenger120
f096246210bf176cfe8d59ed7623c939fe2b7924
13,759
cpp
C++
my-cs/extern/loki-0.1.7/test/Checker/main.cpp
zaqwes8811/cs-courses
aa9cf5ad109c9cfcacaadc11bf2defb2188ddce2
[ "Apache-2.0" ]
24
2016-08-09T23:32:08.000Z
2022-02-08T02:24:34.000Z
my-cs/extern/loki-0.1.7/test/Checker/main.cpp
zaqwes8811/cs-courses
aa9cf5ad109c9cfcacaadc11bf2defb2188ddce2
[ "Apache-2.0" ]
15
2015-03-07T12:46:41.000Z
2015-04-11T09:08:36.000Z
extern/loki-0.1.7/test/Checker/main.cpp
zaqwes8811/micro-apps
7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a
[ "MIT" ]
30
2015-04-22T16:10:43.000Z
2021-12-24T06:37:04.000Z
//////////////////////////////////////////////////////////////////////////////// // // Test program for The Loki Library // Copyright (c) 2008 Richard Sposato // The copyright on this file is protected under the terms of the MIT license. // // Permission to use, copy, modify, distribute and sell this software for any // purpose is hereby granted without fee, provided that the above copyright // notice appear in all copies and that both that copyright notice and this // permission notice appear in supporting documentation. // // The author makes no representations about the suitability of this software // for any purpose. It is provided "as is" without express or implied warranty. // //////////////////////////////////////////////////////////////////////////////// // $Id$ /// @file main.cpp This provides examples on how to use Loki's Checker facility. // ---------------------------------------------------------------------------- #include "../../include/loki/Checker.h" #include <stdexcept> #include <iostream> #include <vector> #if !defined( nullptr ) #define nullptr NULL #endif #if !defined( NULL ) #define NULL 0 #endif using namespace std; // ---------------------------------------------------------------------------- /* This class has 2 invariants. The this pointer may never equal NULL, and the value may not equal zero. */ class Thingy { public: static void ChangeThat( void ); static unsigned int GetThat( void ); explicit Thingy( unsigned int value ); Thingy( const Thingy & that ); Thingy & operator = ( const Thingy & that ); ~Thingy( void ); void Swap( Thingy & that ); bool operator == ( const Thingy & that ) const; void DoSomethingEvil( void ); unsigned int GetValue( void ) const; unsigned int DoSomething( bool doThrow ) const; void DoSomethingElse( void ) const; void AddCount( unsigned int count ); unsigned int GetCount( unsigned int index ) const; void ClearCounts( void ); private: /// This is a static validator. static bool StaticIsValid( void ); /// This is a per-instance validator. bool IsValid( void ) const; /// This can be used to validate pre-conditions and post-conditions. bool IsValidEmpty( void ) const; /// This can be used to validate pre-conditions and post-conditions. bool IsValidFull( void ) const; // These lines show how to declare checkers for non-static functions in a host class. typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForNoThrow > CheckForNoThrow; typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForNoChangeOrThrow > CheckForNoChangeOrThrow; typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForNoChange > CheckForNoChange; typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForEquality > CheckForEquality; typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForNothing > CheckInvariants; // These lines show how to declare checkers for static functions of a host class. typedef ::Loki::StaticChecker< ::Loki::CheckStaticForNoThrow > CheckStaticForNoThrow; typedef ::Loki::StaticChecker< ::Loki::CheckStaticForNothing > CheckStaticInvariants; typedef ::std::vector< unsigned int > IntBlock; static unsigned int s_value; unsigned int m_value; IntBlock m_counts; }; unsigned int Thingy::s_value = 10; // ---------------------------------------------------------------------------- // This example shows how static functions can use a no-throw checkers. void Thingy::ChangeThat( void ) { CheckStaticForNoThrow checker( &Thingy::StaticIsValid ); (void)checker; s_value--; } // ---------------------------------------------------------------------------- // This example shows how static functions can use an invariant checker. unsigned int Thingy::GetThat( void ) { CheckStaticInvariants checker( &Thingy::StaticIsValid ); (void)checker; return s_value; } // ---------------------------------------------------------------------------- // This example shows how ctors can use an invariant checker. Thingy::Thingy( unsigned int value ) : m_value( value ), m_counts() { CheckInvariants checker( this, &Thingy::IsValid ); (void)checker; } // ---------------------------------------------------------------------------- Thingy::Thingy( const Thingy & that ) : m_value( that.m_value ), m_counts( that.m_counts ) { CheckInvariants checker( this, &Thingy::IsValid ); (void)checker; } // ---------------------------------------------------------------------------- Thingy & Thingy::operator = ( const Thingy & that ) { CheckInvariants checker( this, &Thingy::IsValid ); (void)checker; if ( &that != this ) { Thingy temp( that ); temp.Swap( *this ); } return *this; } // ---------------------------------------------------------------------------- // A destructor really doesn't need a checker, but does need to confirm // the object is valid at the start of the destructor. Thingy::~Thingy( void ) { assert( IsValid() ); } // ---------------------------------------------------------------------------- // A swap function gets 2 checkers - one for this, and another for that. void Thingy::Swap( Thingy & that ) { CheckInvariants checker1( this, &Thingy::IsValid ); (void)checker1; CheckInvariants checker2( &that, &Thingy::IsValid ); (void)checker2; const IntBlock counts( m_counts ); m_counts = that.m_counts; that.m_counts = counts; const unsigned int value = m_value; m_value = that.m_value; that.m_value = value; } // ---------------------------------------------------------------------------- bool Thingy::operator == ( const Thingy & that ) const { return ( m_value == that.m_value ); } // ---------------------------------------------------------------------------- void Thingy::DoSomethingEvil( void ) { m_value = 0; } // ---------------------------------------------------------------------------- // This example shows how to use the no-throw checker. unsigned int Thingy::GetValue( void ) const { CheckForNoThrow checker( this, &Thingy::IsValid ); (void)checker; return m_value; } // ---------------------------------------------------------------------------- // This example shows how to use the equality checker. unsigned int Thingy::DoSomething( bool doThrow ) const { CheckForEquality checker( this, &Thingy::IsValid ); (void)checker; if ( doThrow ) throw ::std::logic_error( "Test Exception." ); return m_value; } // ---------------------------------------------------------------------------- // This example shows how to use the no-change checker. void Thingy::DoSomethingElse( void ) const { CheckForNoChange checker( this, &Thingy::IsValid ); (void)checker; } // ---------------------------------------------------------------------------- void Thingy::AddCount( unsigned int count ) { // This function's checker cares about class invariants and post-conditions, // but does not need to check pre-conditions, so it passes in a nullptr for // the pre-condition validator. Ths post-condition validator just makes sure // the container has at least 1 element. CheckInvariants checker( this, &Thingy::IsValid, nullptr, &Thingy::IsValidFull ); m_counts.push_back( count ); } // ---------------------------------------------------------------------------- unsigned int Thingy::GetCount( unsigned int index ) const { // This function's checker cares about class invariants and both the pre- and // post-conditions, so it passes in pointers for all 3 validators. The pre- // and post-conditions are both about making sure the container is not empty. CheckForNoChangeOrThrow checker( this, &Thingy::IsValid, &Thingy::IsValidFull, &Thingy::IsValidFull ); if ( m_counts.size() <= index ) return 0; const unsigned int count = m_counts[ index ]; return count; } // ---------------------------------------------------------------------------- void Thingy::ClearCounts( void ) { // This function's checker cares about class invariants and post-conditions, // but does not need to check pre-conditions, so it passes in a nullptr for // the pre-condition validator. Ths post-condition validator just makes sure // the container has no elements. CheckForNoThrow checker( this, &Thingy::IsValid, nullptr, &Thingy::IsValidEmpty ); m_counts.clear(); } // ---------------------------------------------------------------------------- // This is a static validator. bool Thingy::StaticIsValid( void ) { assert( s_value != 0 ); return true; } // ---------------------------------------------------------------------------- // This is a per-instance validator. bool Thingy::IsValid( void ) const { assert( nullptr != this ); assert( m_value != 0 ); return true; } // ---------------------------------------------------------------------------- bool Thingy::IsValidEmpty( void ) const { assert( nullptr != this ); assert( m_counts.size() == 0 ); return true; } // ---------------------------------------------------------------------------- bool Thingy::IsValidFull( void ) const { assert( nullptr != this ); assert( m_counts.size() != 0 ); return true; } // ---------------------------------------------------------------------------- // This is a validator function called by checkers inside standalone functions. bool AllIsValid( void ) { assert( Thingy::GetThat() != 0 ); return true; } // ---------------------------------------------------------------------------- // These lines show how to declare checkers for standalone functions. typedef ::Loki::StaticChecker< ::Loki::CheckStaticForNoThrow > CheckStaticForNoThrow; typedef ::Loki::StaticChecker< ::Loki::CheckStaticForNothing > CheckStaticInvariants; // ---------------------------------------------------------------------------- void DoSomething( void ) { // This example shows how to use a checker in a stand-alone function. CheckStaticForNoThrow checker( &AllIsValid ); (void)checker; Thingy::ChangeThat(); } // ---------------------------------------------------------------------------- void ThrowTest( void ) { Thingy thingy( 10 ); throw ::std::logic_error( "Will Thingy assert during an exception?" ); } // ---------------------------------------------------------------------------- int main( unsigned int argc, const char * const argv[] ) { try { cout << "Just before call to ThrowTest." << endl; ThrowTest(); cout << "Just after call to ThrowTest." << endl; } catch ( const ::std::logic_error & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } unsigned int count = 0; try { cout << "Running basic tests with Thingy." << endl; // First do some tests on class member functions. Thingy t1( 1 ); t1.DoSomething( false ); Thingy t2( 2 ); t2.DoSomething( true ); cout << "Done with basic tests with Thingy." << endl; } catch ( const ::std::logic_error & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } try { Thingy t1( 1 ); cout << "Now running tests with Thingy counts." << endl; // These lines will exercise the functions with pre- and post-conditions. t1.AddCount( 11 ); t1.AddCount( 13 ); t1.AddCount( 17 ); t1.AddCount( 19 ); count = t1.GetCount( 3 ); assert( count == 19 ); count = t1.GetCount( 0 ); assert( count == 11 ); t1.ClearCounts(); cout << "Done with tests with Thingy counts." << endl; } catch ( const ::std::logic_error & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } try { cout << "Now run tests on static member functions" << endl; // Next do some tests with static member functions. Thingy::ChangeThat(); const unsigned int value = Thingy::GetThat(); assert( value != 0 ); cout << "Done with tests on static member functions" << endl; } catch ( const ::std::logic_error & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } try { cout << "Now run test on a standalone function." << endl; // Then do a test with a standalone function. DoSomething(); cout << "Done with test on a standalone function." << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } cout << "All done!" << endl; return 0; } // ----------------------------------------------------------------------------
29.088795
106
0.529181
zaqwes8811
f09853d57b96f656cd589da1c25a2f02cc1897ea
1,524
hpp
C++
include/codegen/include/RootMotion/FinalIK/EditorIK.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/RootMotion/FinalIK/EditorIK.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/RootMotion/FinalIK/EditorIK.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:09:17 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: RootMotion::FinalIK namespace RootMotion::FinalIK { // Forward declaring type: IK class IK; } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Autogenerated type: RootMotion.FinalIK.EditorIK class EditorIK : public UnityEngine::MonoBehaviour { public: // private RootMotion.FinalIK.IK ik // Offset: 0x18 RootMotion::FinalIK::IK* ik; // private System.Void Start() // Offset: 0x1395670 void Start(); // private System.Void Update() // Offset: 0x1395718 void Update(); // public System.Void .ctor() // Offset: 0x13957E8 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static EditorIK* New_ctor(); }; // RootMotion.FinalIK.EditorIK } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::EditorIK*, "RootMotion.FinalIK", "EditorIK"); #pragma pack(pop)
33.866667
89
0.672572
Futuremappermydud
f098e60a5ec2af63aaac74f9d576e9cfb39f56f5
11,089
cc
C++
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
null
null
null
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
null
null
null
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
3
2016-10-25T01:56:17.000Z
2019-06-24T04:45:06.000Z
// Copyright (c) 2015-2015 The restful Authors. All rights reserved. // Created on: 2015/11/24 Author: jiaoyongqing #include<malloc.h> #include<stdlib.h> #include<memory.h> #include <string> #include <sstream> #include <map> #include <list> #include <vector> #include "tools/tools.h" #include "tea/tea.h" #include "net/typedef.h" #include "base/logic/logic_comm.h" #include "db/db_comm.h" #include "logic/logic_unit.h" namespace tools { std::string GetTimeKey(int64 time) { struct tm timeTm; int64 s = time; localtime_r(&s, &timeTm); char s_char[32]; memset(s_char, '\0', sizeof(s_char)); snprintf(s_char, sizeof(s_char), "%4d-%02d-%02d %02d", timeTm.tm_year+1900, timeTm.tm_mon+1, timeTm.tm_mday, timeTm.tm_hour); std::string str_time = s_char; return str_time; } std::string GetProvinceString(int province) { switch (province) { case 1 : return "jsdx:"; case 2: return "shdx:"; case 3: return "zjdx:"; } return ""; } int64 StrToTime(const char *Data) { struct tm* tmp_time = (struct tm*)malloc(sizeof( struct tm )); strptime(Data, "%Y-%m-%d %H", tmp_time); tmp_time->tm_min = 0; tmp_time->tm_sec = 0; time_t t = mktime(tmp_time); free(tmp_time); return t; } int64 TodayStartTime() { return time(NULL) - (time(NULL) + 28800) % 86400; } int64 CurrentTime() { return time(NULL); } // 集合的形式为:a,b,c,d, std::string MergeSet(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "") return set_two; if (set_two == "") return set_one; std::string ret(set_two); if (ret[ret.length() - 1] != separator) { ret = ret + std::string(1, separator); } std::list<std::string> set_one_list; SeparatorStr(set_one, ',', &set_one_list); std::list<std::string>::iterator it = set_one_list.begin(); for (; it != set_one_list.end(); ++it) { if (set_two.find((*it).c_str()) == std::string::npos) { ret += *it; ret += std::string(","); } } return ret; } void ListGroup(const ContainerStr &l, \ int group_size, \ char separator, \ ContainerStr *const out) { ContainerStr::const_iterator it = l.begin(); int i = 0; std::string value(""); for (; it != l.end(); ++it) { value += *it; value += std::string(1, separator); ++i; if (i == group_size) { out->push_back(value); value = ""; i = 0; } } if (value != "") { out->push_back(value); } } bool IfSetOneIsInSetTwo(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "") return true; if (set_two == "") return false; std::list<std::string> set_one_list; SeparatorStr(set_one, ',', &set_one_list); std::list<std::string>::iterator it = set_one_list.begin(); for (; it != set_one_list.end(); ++it) { if (set_two.find((*it).c_str()) == std::string::npos) { return false; } } return true; } std::string DeleteSet(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "" || set_two == "") return set_two; std::string ret(""); std::list<std::string> set_two_list; SeparatorStr(set_two, ',', &set_two_list); std::list<std::string>::iterator it = set_two_list.begin(); for (; it != set_two_list.end(); ++it) { if (set_one.find((*it).c_str()) == std::string::npos) { ret += *it; ret += std::string(","); } } return ret; } std::string::size_type FindNth(const std::string &str, \ std::string::size_type start, \ int len, \ char ch, \ int num) { if (num == 0) return -1; std::string::size_type end = str.find(ch, start); int count = 0; int cur_len = end + 1 - start; while (true) { if (end == std::string::npos) break; if (cur_len > len) break; ++count; if (cur_len == len) break; if (count == num )break; start = end + 1; end = str.find(ch, start); cur_len = end + 1 - start; } if (count < num) { return -1; } return end; } void NumToChar(void *d, size_t l, std::string &token) { std::stringstream os; char *p = reinterpret_cast<char *>(d); int temp; for (int i = 0; i < l; ++i) { temp = p[i]; os << temp << ","; } token = os.str(); } size_t CharToNum(void **d, std::string &token) { ContainerStr out; tools::SeparatorStr<ContainerStr>(token, ',', &out, true); *d = reinterpret_cast<void *>(malloc(out.size())); char *p = reinterpret_cast<char*>(*d); for (int i = 0; i < out.size(); ++i) { p[i] = atoi(out[i].c_str()); } return out.size(); } std::string TeaEncode(const std::string src) { LOG_DEBUG2("encode before: %s", src.c_str()); int src_len = src.length(); int len = ((src.length() - 1) / 8 + 1) * 8; char *in = reinterpret_cast<char*>(malloc(len)); memset(in, 0, len); strcpy(in, src.c_str()); struct tea_data td; td.d = reinterpret_cast<void *>(in); td.l = len; StrEn(&td); std::string des; NumToChar(td.d, td.l, des); free(in); LOG_DEBUG2("encode after:%s", des.c_str()); return des; } std::string TeaDecode(const std::string src) { struct tea_data td; std::string temp_src(src); td.l = CharToNum(&td.d, temp_src); StrDe(&td); std::string temp(""); for (int i = 0; i < td.l; ++i) { temp.append(1, (reinterpret_cast<char*>(td.d))[i]); } temp.append(1, '\0'); LOG_DEBUG2("decode after:%s", temp.c_str()); free(td.d); return temp; } std::string GetToken(int64 user_id, std::string &token) { std::stringstream os; std::string cur_token; std::string temp; os.str(""); os << user_id; os << ","; os << time(NULL); cur_token = os.str(); LOG_DEBUG2("\n\norigin token: %s\n\n", cur_token.c_str()); int len = ((cur_token.length() - 1) / 8 + 1) * 8; char *in = reinterpret_cast<char*>(malloc(len)); memset(in, 0, len); strcpy(in, cur_token.c_str()); in[cur_token.length()] = 0; struct tea_data td; td.d = reinterpret_cast<void *>(in); td.l = len; StrEn(&td); NumToChar(td.d, td.l, token); free(in); return token; } bool CheckToken(int64 user_id, std::string &token) { struct tea_data td; td.l = CharToNum(&td.d, token); StrDe(&td); std::string origin_token(""); for (int i = 0; i < td.l; ++i) { origin_token.append(1, (reinterpret_cast<char*>(td.d))[i]); } origin_token.append(1, '\0'); std::string::size_type separator_pos = origin_token.find(',', 0); std::string origin_id = origin_token.substr(0, separator_pos); std::stringstream os; os.str(""); os << origin_token.substr(separator_pos + 1, origin_token.length()); int64 origin_time; os >> origin_time; os.str(""); os << user_id; std::string current_id = os.str(); LOG_DEBUG2("\n\norigin token: %s,%d\n\n", origin_id.c_str(), origin_time); int64 current_time = time(NULL); const int TOKEN_SURVIVE_TIME = 86400; if (origin_id == current_id && (current_time - origin_time <= 86400)) { return true; } return false; } void MapAdd(std::map<std::string, int64> *map, \ const std::string &key, int64 value) { std::map<std::string, int64>::iterator it; it = map->find(key); if (it == map->end()) { (*map)[key] = value; } else { (*map)[key] += value; } } std::string TimeFormat(int64 time, const char* format) { struct tm timeTm; localtime_r(&time, &timeTm); char s_char[32]; memset(s_char, '\0', sizeof(s_char)); snprintf(s_char, sizeof(s_char), format, timeTm.tm_year+1900, timeTm.tm_mon+1, timeTm.tm_mday, timeTm.tm_hour); std::string str_time = s_char; return str_time; } std::vector<std::string> Split(std::string str, std::string pattern) { std::string::size_type pos; std::vector<std::string> result; str += pattern; int size = str.size(); for (int i = 0; i < size; i++) { pos = str.find(pattern, i); if (pos < size) { std::string s = str.substr(i , pos - i); result.push_back(s); i = pos + pattern.size() - 1; } } return result; } void replace_all(std::string *str, \ const std::string &old_value, \ const std::string &new_value) { while (true) { std::string::size_type pos(0); if ((pos = str->find(old_value)) != std::string::npos) str->replace(pos, old_value.length(), new_value); else break; } } void replace_all_distinct(std::string *str, \ const std::string &old_value, \ const std::string &new_value) { for (std::string::size_type pos(0); \ pos != std::string::npos; pos += new_value.length()) { if ((pos = str->find(old_value, pos)) != std::string::npos) str->replace(pos, old_value.length(), new_value); else break; } } void ReplaceBlank(std::string *str) { // 去除空格 replace_all_distinct(str, " ", ""); // 去除\t replace_all_distinct(str, "\t", ""); // 去除\n replace_all_distinct(str, "\n", ""); } bool check_userid_if_in_sql(NetBase* value,const int socket) { bool r = false; bool flag = false; int64 user_id = 0; int error_code = 0; r = value->GetBigInteger(L"user_id", static_cast<int64*>(&user_id)); if (false == r) error_code = STRUCT_ERROR; if (user_id > 0) { db::DbSql sql; flag = sql.CheckUseridIfInSql(user_id); error_code = sql.get_error_info(); LOG_DEBUG2("\n\DbSql::check_id_token-------error_code: %d\n\n",error_code); if (error_code != 0) { send_error(error_code, socket); return false; } if (flag == false) { error_code = USER_ID_ISNOT_IN_SQL; LOG_DEBUG2("\n\DbSql::check_id_token-------error_code1: %d\n\n",error_code); send_error(error_code, socket); return false; LOG_DEBUG2("\n\DbSql::check_id_token-------error_code2: %d\n\n",error_code); } } return true; } bool check_id_token(NetBase* value,const int socket) { bool r = false; bool flag = false; int error_code = 0; std::string token = ""; int64 user_id = 0; r = value->GetString(L"token", &token); if (false == r) error_code = STRUCT_ERROR; r = value->GetBigInteger(L"user_id", static_cast<int64*>(&user_id)); if (false == r) error_code = STRUCT_ERROR; /*LOG_DEBUG2("\n\DbSql::check_id_token-------user_id: %d\n\n",user_id);*/ if (CheckToken(user_id, token)) { return true; } else { error_code = USER_ACCESS_NOT_ENOUGH; send_error(error_code, socket); return false; } return false; } bool CheckUserIdAndToken(NetBase* value,const int socket) { if (!tools::check_userid_if_in_sql(value, socket)) { return false; } if (!tools::check_id_token(value, socket)) { return false; } return true; } } // namespace tools
24.533186
93
0.584994
smartdata-x
f09924a80a0e716a64c7699e1ed64931e559b292
228
hpp
C++
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
#pragma once #include "Rimfrost\EventSystem\Event.hpp" namespace Rimfrost { class EventObserver { public: EventObserver() = default; virtual ~EventObserver() = default; virtual void onEvent(const Event& e) = 0; }; }
15.2
43
0.710526
Cgunnar
f09a60960c8157f4cce0993e7a96946606567a9c
129
cpp
C++
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:943d9f005beb984bd9d29ed487bf6adf30882f9fa79903c6092cbd91ecee3e90 size 6381
32.25
75
0.883721
realtehcman
f09f35100976469d13d4837b3b002ae69f7a61da
1,060
cpp
C++
cpp/0_check/modernes_cpp_source/source/lambdaAndAuto.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
cpp/0_check/modernes_cpp_source/source/lambdaAndAuto.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
cpp/0_check/modernes_cpp_source/source/lambdaAndAuto.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
// lambdaAndAuto.cpp #include <functional> #include <iostream> double divMe(double a, double b){ return double(a/b); } using namespace std::placeholders; int main(){ std::cout << std::endl; // invoking the function object directly std::cout << "1/2.0= " << [](int a, int b){ return divMe(a, b); }(1, 2.0) << std::endl; // placeholders for both arguments auto myDivBindPlaceholder= [](int a, int b){ return divMe(a, b); }; std::cout << "1/2.0= " << myDivBindPlaceholder(1, 2.0) << std::endl; // placeholders for both arguments, swap the arguments auto myDivBindPlaceholderSwap= [](int a, int b){ return divMe(b, a); }; std::cout << "1/2.0= " << myDivBindPlaceholderSwap(2.0, 1) << std::endl; // placeholder for the first argument auto myDivBind1St= [](int a){ return divMe(a, 2.0); }; std::cout<< "1/2.0= " << myDivBind1St(1) << std::endl; // placeholder for the second argument auto myDivBind2Nd= [](int b){ return divMe(1, b); }; std::cout << "1/2.0= " << myDivBind2Nd(2.0) << std::endl; std::cout << std::endl; }
28.648649
89
0.626415
shadialameddin
f09f8aea9ce08a9f95211f0e97a1b16ed177fd9e
12,063
cc
C++
whisperstreamlib/mts/mts_types.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/mts/mts_types.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/mts/mts_types.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
#include <whisperstreamlib/mts/mts_types.h> #define CHECK_MARKER(bit_array, type, bit_size, expected_value) {\ type marker = bit_array.Read<type>(bit_size);\ if ( marker != expected_value ) {\ LOG_ERROR << "Invalid marker: " << (int)marker\ << ", expected: " << (int)expected_value;\ }\ } #define CHECK_MARKER_BIT(bit_array) CHECK_MARKER(bit_array, uint8, 1, 0x01); #define CHECK_ZERO_BIT(bit_array) CHECK_MARKER(bit_array, uint8, 1, 0x00); namespace streaming { namespace mts { const char* TSScramblingName(TSScrambling scrambling) { switch ( scrambling ) { CONSIDER(NOT_SCRAMBLED); CONSIDER(SCRAMBLED_RESERVED); CONSIDER(SCRAMBLED_EVEN_KEY); CONSIDER(SCRAMBLED_ODD_KEY); } LOG_FATAL << "Illegal TSScrambling: " << (int)scrambling; return "Unknown"; } DecodeStatus TSPacket::Decode(io::MemoryStream* in) { if ( in->Size() < kTSPacketSize ) { return DECODE_NO_DATA; } if ( io::NumStreamer::PeekByte(in) != kTSSyncByte ) { LOG_ERROR << "Cannot decode TSPacket, sync byte: " << strutil::ToHex(kTSSyncByte) << " not found in stream: " << in->DumpContentInline(16); return DECODE_ERROR; } in->Skip(1); // skip the sync byte io::BitArray h; h.PutMS(*in, 3); transport_error_indicator_ = h.Read<bool>(1); payload_unit_start_indicator_ = h.Read<bool>(1); transport_priority_ = h.Read<bool>(1); pid_ = h.Read<uint16>(13); scrambling_ = (TSScrambling)h.Read<uint8>(2); bool has_adaptation = h.Read<bool>(1); bool has_payload = h.Read<bool>(1); continuity_counter_ = h.Read<uint8>(4); if ( has_adaptation ) { adaptation_field_ = new AdaptationField(); DecodeStatus status = adaptation_field_->Decode(in); if ( status != DECODE_SUCCESS ) { LOG_ERROR << "Cannot decode TSPacket, failed to decode AdaptationField" ", result: " << DecodeStatusName(status); return status; } } if ( has_payload ) { payload_ = new io::MemoryStream(); // the header, before adaptation field, has 4 bytes. payload_->AppendStream(in, kTSPacketSize - 4 - (has_adaptation ? adaptation_field_->Size() : 0)); } return DECODE_SUCCESS; } string TSPacket::ToString() const { ostringstream oss; oss << "TSPacket{" "transport_error_indicator_: " << strutil::BoolToString(transport_error_indicator_) << ", payload_unit_start_indicator_: " << strutil::BoolToString(payload_unit_start_indicator_) << ", transport_priority_: " << strutil::BoolToString(transport_priority_) << ", pid_: " << pid_ << ", scrambling_: " << TSScramblingName(scrambling_) << ", continuity_counter_: " << (uint32)continuity_counter_; if ( adaptation_field_ == NULL ) { oss << ", adaptation_field_: NULL"; } else { oss << ", adaptation_field: " << adaptation_field_->ToString(); } if ( payload_ == NULL ) { oss << ", payload_: NULL"; } else { oss << ", payload_: " << payload_->Size() << " bytes"; } oss << "}"; return oss.str(); } //////////////////////////////////////////////////////////////////////// DecodeStatus ProgramAssociationTable::Decode(io::MemoryStream* in) { if ( in->Size() < 8 ) { return DECODE_NO_DATA; } io::BitArray data; data.PutMS(*in, 8); table_id_ = data.Read<uint8>(8); CHECK_MARKER_BIT(data); // 1 bit: section_syntax_indicator, must be 1 CHECK_ZERO_BIT(data); data.Skip(2); // 2 reserved bits uint16 section_length = data.Read<uint16>(12); ts_id_ = data.Read<uint16>(16); data.Skip(2); // 2 reserved bits version_number_ = data.Read<uint8>(5); currently_applicable_ = data.Read<bool>(1); section_number_ = data.Read<uint8>(8); last_section_number_ = data.Read<uint8>(8); // section_length is the length of the remaining section data // (starting with ts_id_ and including the last CRC). // So we've already decoded 5 bytes from this length. if ( section_length < 9 ) { LOG_ERROR << "Cannot decode ProgramAssociationTable, invalid section_length" ": " << section_length << " is too small"; return DECODE_ERROR; } if ( in->Size() < section_length - 5 ) { return DECODE_NO_DATA; } if ( (section_length - 5) % 4 ) { LOG_ERROR << "Cannot decode ProgramAssociationTable, invalid section_length" ": " << section_length << ", after the header there are: " << section_length - 5 << " bytes, which is not a multiple of 4"; return DECODE_ERROR; } for ( uint32 i = 5; i < section_length - 4; i += 4 ) { uint16 program_number = io::NumStreamer::ReadUInt16(in, common::BIGENDIAN); io::BitArray a; a.PutMS(*in, 16); a.Skip(3); uint16 pid = a.Read<uint16>(13); if ( program_number == 0 ) { network_pid_[program_number] = pid; } else { program_map_pid_[program_number] = pid; } } crc_ = io::NumStreamer::ReadUInt32(in, common::BIGENDIAN); return DECODE_SUCCESS; } string ProgramAssociationTable::ToString() const { ostringstream oss; oss << "ProgramAssociationTable{table_id_: " << (uint32)table_id_ << ", ts_id_: " << ts_id_ << ", version_number_: " << version_number_ << ", currently_applicable_: " << strutil::BoolToString(currently_applicable_) << ", section_number_: " << section_number_ << ", last_section_number_: " << last_section_number_ << ", network_pid_: " << strutil::ToString(network_pid_) << ", program_map_pid_: " << strutil::ToString(program_map_pid_) << ", crc_: " << crc_ << "}"; return oss.str(); } //////////////////////////////////////////////////////////////////////// DecodeStatus PESPacket::Header::Decode(io::MemoryStream* in) { if ( in->Size() < 2 ) { return DECODE_NO_DATA; } io::BitArray h; h.PutMS(*in, 1); uint8 mark = h.Read<uint8>(2); scrambling_ = (TSScrambling)h.Read<uint8>(2); is_priority_ = h.Read<bool>(1); is_data_aligned_ = h.Read<bool>(1); is_copyright_ = h.Read<bool>(1); is_original_ = h.Read<bool>(1); bool has_PTS = h.Read<bool>(1); bool has_DTS = h.Read<bool>(1); bool has_ESCR = h.Read<bool>(1); bool has_ES_rate = h.Read<bool>(1); bool has_DSM_trick_mode = h.Read<bool>(1); bool has_additional_copy_info = h.Read<bool>(1); bool has_CRC = h.Read<bool>(1); bool has_extension = h.Read<bool>(1); uint8 size = io::NumStreamer::ReadByte(in); uint32 start_size = in->Size(); if ( mark != 0b01 ) { LOG_ERROR << "Invalid marker before PES: " << strutil::ToBinary(mark); return DECODE_ERROR; } if ( has_PTS && !has_DTS ) { io::BitArray data; data.PutMS(*in, 5); pts_ = 0; // Note: 33 bit encoded! CHECK_MARKER(data, uint8, 4, 0b0010); pts_ = pts_ << 3 | data.Read<uint8>(3); CHECK_MARKER_BIT(data); pts_ = pts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); pts_ = pts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); } else if ( has_PTS && has_DTS ) { io::BitArray data; data.PutMS(*in, 10); pts_ = 0; // Note: 33 bit encoded! dts_ = 0; // Note: 33 bit encoded! CHECK_MARKER(data, uint8, 4, 0b0011); pts_ = pts_ << 3 | data.Read<uint8>(3); CHECK_MARKER_BIT(data); pts_ = pts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); pts_ = pts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); CHECK_MARKER(data, uint8, 4, 0b0001); dts_ = dts_ << 3 | data.Read<uint8>(3); CHECK_MARKER_BIT(data); dts_ = dts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); dts_ = dts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); } else if ( !has_PTS && has_DTS ) { LOG_ERROR << "Found Decoding Timestamp without Presentation Timestamp"; return DECODE_ERROR; } if ( has_ESCR ) { io::BitArray data; data.PutMS(*in, 6); escr_base_ = 0; data.Skip(2); // reserved escr_base_ = escr_base_ << 3 | data.Read<uint8>(3); CHECK_MARKER_BIT(data); escr_base_ = escr_base_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); escr_base_ = escr_base_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); escr_extension_ = data.Read<uint16>(9); CHECK_MARKER_BIT(data); } if ( has_ES_rate ) { io::BitArray data; data.PutMS(*in, 3); CHECK_MARKER_BIT(data); es_rate_ = data.Read<uint32>(22); CHECK_MARKER_BIT(data); } if ( has_DSM_trick_mode ) { // trick mode is encoded on 8 bits. // TODO(cosmin): decode DSM trick mode trick_mode_ = io::NumStreamer::ReadByte(in); } if ( has_additional_copy_info ) { // additional copy info is encoded on 8 bits. Ignore it for now. // TODO(cosmin): decode additional copy info additional_copy_info_ = io::NumStreamer::ReadByte(in); } if ( has_CRC ) { previous_pes_packet_crc_ = io::NumStreamer::ReadUInt16(in, common::BIGENDIAN); } if ( has_extension ) { // TODO(cosmin): decode extension } // skip the rest of the header (extension + stuffing bytes) uint32 decoded_size = start_size - in->Size(); in->Skip(size - decoded_size); return DECODE_SUCCESS; } string PESPacket::Header::ToString() const { ostringstream oss; oss << "{scrambling_: " << TSScramblingName(scrambling_) << ", is_priority_: " << strutil::BoolToString(is_priority_) << ", is_data_aligned_: " << strutil::BoolToString(is_data_aligned_) << ", is_copyright_: " << strutil::BoolToString(is_copyright_) << ", is_original_: " << strutil::BoolToString(is_original_) << ", pts_: " << pts_ << ", dts_: " << dts_ << ", escr_base_: " << escr_base_ << ", escr_extension_: " << escr_extension_ << ", es_rate_: " << es_rate_ << ", trick_mode_: " << strutil::ToHex(trick_mode_) << ", add_info: " << strutil::ToHex(additional_copy_info_) << ", prev_crc: " << previous_pes_packet_crc_ << "}"; return oss.str(); } DecodeStatus PESPacket::Decode(io::MemoryStream* in) { if ( in->Size() < 6 ) { return DECODE_NO_DATA; } in->MarkerSet(); uint32 mark = io::NumStreamer::ReadUInt24(in, common::BIGENDIAN); if ( mark != kPESMarker ) { in->MarkerRestore(); LOG_ERROR << "PES Marker not found." " Expected: " << strutil::ToHex(kPESMarker, 3) << ", found: " << strutil::ToHex(mark, 3) << ", in stream: " << in->DumpContentInline(16); return DECODE_ERROR; } uint8 stream_id = io::NumStreamer::ReadByte(in); uint16 size = io::NumStreamer::ReadUInt16(in, common::BIGENDIAN); if ( in->Size() < size ) { in->MarkerRestore(); return DECODE_NO_DATA; } if ( stream_id == kPESStreamIdPadding ) { in->Skip(size); in->MarkerClear(); return DECODE_SUCCESS; } if ( stream_id == kPESStreamIdProgramMap || stream_id == kPESStreamIdProgramDirectory || stream_id == kPESStreamIdECM || stream_id == kPESStreamIdEMM || stream_id == kPESStreamIdPrivate2 ) { // decode body (no header) data_.AppendStream(in, size); in->MarkerClear(); return DECODE_SUCCESS; } if ( (stream_id >= kPESStreamIdAudioStart && stream_id <= kPESStreamIdAudioEnd) || (stream_id >= kPESStreamIdVideoStart && stream_id <= kPESStreamIdVideoEnd) ) { // decode header const uint32 start_size = in->Size(); DecodeStatus status = header_.Decode(in); if ( status != DECODE_SUCCESS ) { in->MarkerRestore(); return status; } const uint32 header_encoding_size = start_size - in->Size(); CHECK_GE(size, header_encoding_size); // decode body data_.AppendStream(in, size - header_encoding_size); in->MarkerClear(); return DECODE_SUCCESS; } LOG_ERROR << "Unknown stream ID: " << strutil::StringPrintf("%02x", stream_id); in->Skip(size); in->MarkerClear(); return DECODE_SUCCESS; } string PESPacket::ToString() const { ostringstream oss; oss << "PESPacket{stream_id_: " << PESStreamIdName(stream_id_) << ", header_: " << header_.ToString() << ", data_: #" << data_.Size() << " bytes}"; return oss.str(); } } }
34.269886
96
0.631186
cpopescu
f0a3986dff053570d226301f52321899ed5ba9bd
8,948
cpp
C++
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
19
2015-05-14T09:57:38.000Z
2022-01-10T23:32:28.000Z
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
3
2015-08-04T09:07:26.000Z
2018-01-18T07:14:35.000Z
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
1
2015-08-04T09:05:22.000Z
2015-08-04T09:05:22.000Z
#include "DocumentRoot.h" //static const double pi = std::acos(-1.0); // お手軽に π を得る。 //============================================================== // Constructor / Destructor //============================================================== //-------------------------------------------------------------- // //-------------------------------------------------------------- DocumentRoot::DocumentRoot() { cout << "[DocumentRoot]DocumentRoot()" << endl; _target = this; name("DocumentRoot"); useHandCursor(true); } //-------------------------------------------------------------- // //-------------------------------------------------------------- DocumentRoot::~DocumentRoot() { cout << "[DocumentRoot]~DocumentRoot()" << endl; } //============================================================== // Setup / Update / Draw //============================================================== //-------------------------------------------------------------- // //-------------------------------------------------------------- void DocumentRoot::_setup() { cout << "[DocumentRoot]_setup()" << endl; //-------------------------------------- //ステージに追加された時にキーボードイベントを監視する addEventListener(flEvent::ADDED_TO_STAGE, this, &DocumentRoot::_eventHandler); addEventListener(flMouseEvent::MOUSE_DOWN, this, &DocumentRoot::_mouseEventHandler); addEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); flGraphics* g; g = graphics(); g->clear(); g->beginFill(0x888888, 0.1); g->drawRect(0, 0, ofGetWidth(), ofGetHeight()); g->endFill(); //----------------------------------- //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し counter = 0; ofSetCircleResolution(50); ofBackground(255,255,255); bSmooth = false; // ofSetWindowTitle("graphics example"); ofSetFrameRate(60); // if vertical sync is off, we can go a bit fast... this caps the framerate at 60fps. //----------------------------------- } //-------------------------------------------------------------- void DocumentRoot::_update() { //-------------------------------------- if(!isMouseDown()){ _forceX *= 0.95; _forceY *= 0.95; float temp; temp = x(); temp += _forceX; x(temp); temp = y(); temp += _forceY; y(temp); } else { _preX = x(); _preY = y(); } //-------------------------------------- //-------------------------------------- flGraphics* g; g = graphics(); g->clear(); //背景色 g->beginFill(0x888888, 0.1); g->drawRect(0, 0, ofGetWidth(), ofGetHeight()); g->endFill(); //透明のヒットエリア g->beginFill(0x0000cc, 0); g->drawRect(-x(), -y(), ofGetWidth(), ofGetHeight()); g->endFill(); //-------------------------------------- //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し counter = counter + 0.033f; //----------------------------------- } //-------------------------------------------------------------- void DocumentRoot::_draw() { //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し //--------------------------- circles //let's draw a circle: ofSetColor(255,130,0); float radius = 50 + 10 * sin(counter); ofFill(); // draw "filled shapes" ofDrawCircle(100,400,radius); // now just an outline ofNoFill(); ofSetHexColor(0xCCCCCC); ofDrawCircle(100,400,80); // use the bitMap type // note, this can be slow on some graphics cards // because it is using glDrawPixels which varies in // speed from system to system. try using ofTrueTypeFont // if this bitMap type slows you down. ofSetHexColor(0x000000); ofDrawBitmapString("circle", 75,500); //--------------------------- rectangles ofFill(); for (int i = 0; i < 200; i++){ ofSetColor((int)ofRandom(0,255),(int)ofRandom(0,255),(int)ofRandom(0,255)); ofDrawRectangle(ofRandom(250,350),ofRandom(350,450),ofRandom(10,20),ofRandom(10,20)); } ofSetHexColor(0x000000); ofDrawBitmapString("rectangles", 275,500); //--------------------------- transparency ofSetHexColor(0x00FF33); ofDrawRectangle(400,350,100,100); // alpha is usually turned off - for speed puposes. let's turn it on! ofEnableAlphaBlending(); ofSetColor(255,0,0,127); // red, 50% transparent ofDrawRectangle(450,430,100,33); ofSetColor(255,0,0,(int)(counter * 10.0f) % 255); // red, variable transparent ofDrawRectangle(450,370,100,33); ofDisableAlphaBlending(); ofSetHexColor(0x000000); ofDrawBitmapString("transparency", 410,500); //--------------------------- lines // a bunch of red lines, make them smooth if the flag is set ofSetHexColor(0xFF0000); for (int i = 0; i < 20; i++){ ofDrawLine(600,300 + (i*5),800, 250 + (i*10)); } ofSetHexColor(0x000000); ofDrawBitmapString("lines\npress 's' to toggle smoothness", 600,500); //----------------------------------- } //============================================================== // Public Method //============================================================== //============================================================== // Protected / Private Method //============================================================== //============================================================== // Private Event Handler //============================================================== //-------------------------------------------------------------- void DocumentRoot::_eventHandler(flEvent& event) { cout << "[DocumentRoot]_eventHandler(" + event.type() + ")"; if(event.type() == flEvent::ADDED_TO_STAGE) { removeEventListener(flEvent::ADDED_TO_STAGE, this, &DocumentRoot::_eventHandler); stage()->addEventListener(flKeyboardEvent::KEY_PRESS, this, &DocumentRoot::_keyboardEventHandler); stage()->addEventListener(flKeyboardEvent::KEY_RELEASE, this, &DocumentRoot::_keyboardEventHandler); } } //-------------------------------------------------------------- void DocumentRoot::_keyboardEventHandler(flEvent& event) { // cout << "[DocumentRoot]_keyboardEventHandler(" + event.type() + ")"; flKeyboardEvent* keyboardEvent = dynamic_cast<flKeyboardEvent*>(&event); int key = keyboardEvent->keyCode(); if(event.type() == flKeyboardEvent::KEY_PRESS) { //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し if (key == 's') { bSmooth = !bSmooth; if (bSmooth){ ofEnableAntiAliasing(); }else{ ofDisableAntiAliasing(); } } //----------------------------------- } if(event.type() == flKeyboardEvent::KEY_RELEASE) { } } //-------------------------------------------------------------- void DocumentRoot::_moveEventHandler(flEvent& event) { //cout << "[DocumentRoot]_moveEventHandler(" << event.type() << ")" << endl; // cout << "mouse is moving" << endl; } //-------------------------------------------------------------- void DocumentRoot::_mouseEventHandler(flEvent& event) { // cout << "[DocumentRoot]_mouseEventHandler(" << event.type() << ")" << endl; // cout << "[PrentBox]this = " << this << endl; // cout << "[ParetBox]currentTarget = " << event.currentTarget() << endl; // cout << "[ParetBox]target = " << event.target() << endl; if(event.type() == flMouseEvent::MOUSE_OVER) { if(event.target() == this) { } } if(event.type() == flMouseEvent::MOUSE_OUT) { if(event.target() == this) { } } if(event.type() == flMouseEvent::MOUSE_DOWN) { if(event.target() == this) { startDrag(); stage()->addEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); stage()->addEventListener(flMouseEvent::MOUSE_MOVE, this, &DocumentRoot::_moveEventHandler); } } if(event.type() == flMouseEvent::MOUSE_UP) { if(event.currentTarget() == stage()) { stopDrag(); stage()->removeEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); stage()->removeEventListener(flMouseEvent::MOUSE_MOVE, this, &DocumentRoot::_moveEventHandler); _forceX = (x() - _preX) * 0.5; _forceY = (y() - _preY) * 0.5; } } }
34.022814
109
0.456638
selflash
f0a6282ef467cbb597f6376aa9e36c7f9759eb46
3,508
cpp
C++
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
1
2018-07-11T03:47:41.000Z
2018-07-11T03:47:41.000Z
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
null
null
null
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
null
null
null
#include "SQLite.h" #include <sqlite3/sqlite3.h> #include <stdio.h> #include <vector> namespace beebox { CSQLite::CSQLite() { m_db = NULL; } CSQLite::~CSQLite() { close(); } bool CSQLite::open(string filePath) { if (m_db) { close(); } return sqlite3_open_v2(filePath.c_str(), &m_db, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK ? true : false; } void CSQLite::close() { sqlite3_close(m_db); } bool CSQLite::create(string filePath) { return sqlite3_open_v2(filePath.c_str(), &m_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) == SQLITE_OK ? true : false; } bool CSQLite::select(string sql, string& recordInJson) { sqlite3_stmt* res = NULL; const char* unused = NULL; recordInJson.clear(); int rc = sqlite3_prepare_v2(m_db, sql.c_str(), sql.size(), &res, &unused); if (rc != SQLITE_OK) { return false; } int columnCount = sqlite3_column_count(res); vector<string> fieldNameList; for (int i=0; i<columnCount; ++i) { const char* name = sqlite3_column_name(res, i); string _name = "\"" ; _name += name; _name += "\":"; fieldNameList.push_back(_name); } recordInJson += "["; rc = sqlite3_step(res); while(rc == SQLITE_ROW) { for(int i=0; i<columnCount; i++) { if (i == 0) { recordInJson += "{"; } string val = getValue(res, i); recordInJson += fieldNameList[i]; recordInJson += val.empty() ? "null" : val; if (i < columnCount - 1) { recordInJson += ","; } else { recordInJson += "}"; } } rc = sqlite3_step(res); if (rc == SQLITE_ROW) { recordInJson += ","; } } recordInJson += "]"; sqlite3_finalize(res); if (recordInJson.size() < 3) { recordInJson.clear(); } return true; } bool CSQLite::execute(string sql) { printf("########## sql: %s\n", sql.c_str()); char* errMsg = NULL; int rc = sqlite3_exec(m_db, sql.c_str(), 0, 0, &errMsg); if (rc != SQLITE_OK) { printf("SQL error:%s\n", errMsg); return false; } else { printf("SQL Execute OK!\n"); } return true; } string CSQLite::getError() { return sqlite3_errmsg(m_db); } string CSQLite::getValue(sqlite3_stmt* res, int columnIndex) { const unsigned char* pStr = NULL; int type = sqlite3_column_type(res, columnIndex); string out; char buffer[256] = {0}; switch(type) { case SQLITE_INTEGER: sprintf(buffer, "%d", sqlite3_column_int(res, columnIndex)); out = buffer; break; case SQLITE_FLOAT: sprintf(buffer, "%f", sqlite3_column_double(res, columnIndex)); out = buffer; break; case SQLITE3_TEXT: pStr = sqlite3_column_text(res, columnIndex); if (pStr) { out = "\""; out += (char*)pStr; out += "\""; } break; case SQLITE_BLOB: //sqlite3_column_bytes(res, 0); //(void*) sqlite3_column_blob(res, 0); out = "blob"; break; case SQLITE_NULL: out = ""; break; default: out = ""; break; }; return out; } } // namespace beebox
19.381215
80
0.517104
nianfh
f0a6567ff64ee8caa5ac52d811f47b9e0bea8794
1,246
cpp
C++
Dynamic Programming/Coin Change/SolutionbyPooja.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
261
2019-09-30T19:47:29.000Z
2022-03-29T18:20:07.000Z
Dynamic Programming/Coin Change/SolutionbyPooja.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
647
2019-10-01T16:51:29.000Z
2021-12-16T20:39:44.000Z
Dynamic Programming/Coin Change/SolutionbyPooja.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
383
2019-09-30T19:32:07.000Z
2022-03-24T16:18:26.000Z
/* Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, How many ways can we make the change? The order of coins doesn’t matter. input: N = 4 S = [ 1, 2, 3 ] Output = 4 There are four solutions: [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ], [ 1, 3 ]. */ #include <iostream> using namespace std; int coin_change(int* arr, int N, int n) { int t[n + 1][N + 1]; for (int i = 0; i < N + 1; i++) t[0][i] = 0; for (int i = 0; i < n + 1; i++) t[i][0] = 1; for (int i = 1; i < n + 1; i++) { for (int j = 1; j < N + 1; j++) { if (arr[i - 1] <= j) t[i][j] = t[i - 1][j] + t[i][j - arr[i - 1]]; else t[i][j] = t[i - 1][j]; } } return t[n][N]; } int main() { int size, N; cout << "Array Size "; cin >> size; int* arr = new int[size]; cout << "\nEnter coins "; for (int i = 0; i < size; i++) cin >> *(arr + i); cout << "Enter sum "; cin >> N; cout << "\nNo. of ways : " << coin_change(arr, N, size); }
21.859649
161
0.399679
Mdanish777
f0ad631f8a4cc60d71b0bedeeead556dbc107356
542
cpp
C++
8 Hashing/03.hard/10.indexpairs.cpp
markpairdha/DataStructures
cf002e5a982543bd91e4a06ab22e76c40095786e
[ "MIT" ]
null
null
null
8 Hashing/03.hard/10.indexpairs.cpp
markpairdha/DataStructures
cf002e5a982543bd91e4a06ab22e76c40095786e
[ "MIT" ]
null
null
null
8 Hashing/03.hard/10.indexpairs.cpp
markpairdha/DataStructures
cf002e5a982543bd91e4a06ab22e76c40095786e
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> #include<unordered_map> using namespace std; int countindexpairs(int arr[],int n) { unordered_map<int,int> mp; for(int i=0;i<n;i++) mp[arr[i]]++; int ans=0; unordered_map<int,int> ::iterator it; for(it = mp.begin();it != mp.end();it++) { int freq = it->second; ans += (freq*(freq-1))/2; } return ans; } int main() { int arr[] = {1,1,1,1,1,2,2,2,2}; int size = sizeof(arr)/sizeof(arr[0]); cout << countindexpairs(arr,size) << endl; return 0; }
20.074074
44
0.577491
markpairdha
f0ae115e5186c11bf9fd48e719659cc0cace4643
8,946
cpp
C++
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#include <iostream> #include <sstream> #include <vector> #include <OGRE/Ogre.h> #include <OIS/OIS.h> #include "Gui3D.h" #include "Gui3DPanel.h" #include "MyEnvironmentDemoPanelColors.h" typedef struct PanelAndDirection { Gui3D::Panel* panel; Ogre::Vector3 cameraDirection; int yaw; } PanelAndDirection; class EnvironmentDemo : public Ogre::FrameListener, public OIS::KeyListener, public OIS::MouseListener { public: // Gui3D main object Gui3D::Gui3D* mGui3D; // Keep track of some captions to modify their contents on callback Gui3D::Caption* captionButton; Gui3D::Caption* captionChecked; Gui3D::Caption* captionCombobox; Ogre::SceneNode* tvNode; Ogre::Vector3 originalTvNodePos; Ogre::Entity* entSinbad; Ogre::AnimationState* a, *a2; Gui3D::Panel* mPanel; MyEnvironmentDemoPanelColors mMyEnvironmentDemoPanelColors; EnvironmentDemo() { originalTvNodePos = Ogre::Vector3(0, 1, 10); _makeOgre(); _makeOIS(); _makeScene(); mGui3D = new Gui3D::Gui3D(&mMyEnvironmentDemoPanelColors); mGui3D->createScreen(mViewport, "environmentDemo", "mainScreen"); mPanel = _createPanel(Ogre::Vector3(0, 5.3, -2.5), 180); mCamera->setPosition(0, 6.f, -8); mCamera->setDirection(Ogre::Vector3(0, 0, 1)); } Gui3D::Panel* _createPanel(Ogre::Vector3 pos, int yaw) { Gui3D::Panel* panel = new Gui3D::Panel( mGui3D, mSceneMgr, Ogre::Vector2(400, 400), 15, "environmentDemo", "kikoo"); panel->mNode->setPosition(pos); panel->mNode->yaw(Ogre::Degree(yaw)); panel->makeCaption(10, 10, 380, 30, "Move the TV please...", Gorilla::TextAlign_Centre); panel->makeCaption(10, 100, 90, 100, "Left", Gorilla::TextAlign_Centre, Gorilla::VerticalAlign_Middle); panel->makeCaption(310, 100, 90, 100, "Right", Gorilla::TextAlign_Centre, Gorilla::VerticalAlign_Middle); Gui3D::ScrollBar* s = panel->makeScrollBar(100, 100, 200, 100, 0, 15); s->setValueChangedCallback(this, &EnvironmentDemo::decalValueChanged); s->setStep(0.1); s->setDisplayedPrecision(0, false); s->setCallCallbackOnSelectingValue(true); s->setDisplayValue(false); return panel; } bool decalValueChanged(Gui3D::PanelElement* e) { Ogre::Vector3 pos = originalTvNodePos; pos.x -= ((Gui3D::ScrollBar*)e)->getValue(); tvNode->setPosition(pos); return true; } ~EnvironmentDemo() { delete mGui3D; std::ostringstream s; s << "\n** Average FPS (with FSAA to 1) is " << mWindow->getAverageFPS() << "\n\n"; Ogre::LogManager::getSingleton().logMessage(s.str()); delete mRoot; } bool frameStarted(const Ogre::FrameEvent& evt) { if (mWindow->isClosed()) return false; Ogre::Vector3 trans(0,0,0); if (mKeyboard->isKeyDown(OIS::KC_W)) trans.z = -1; else if (mKeyboard->isKeyDown(OIS::KC_S)) trans.z = 1; if (mKeyboard->isKeyDown(OIS::KC_A)) trans.x = -1; else if (mKeyboard->isKeyDown(OIS::KC_D)) trans.x = 1; if (trans.isZeroLength() == false) { Ogre::Vector3 pos = mCamera->getPosition(); pos += mCamera->getOrientation() * (trans * 10.0f) * evt.timeSinceLastFrame; pos.y = 6.0f; mCamera->setPosition(pos); } a->addTime(evt.timeSinceLastFrame); a2->addTime(evt.timeSinceLastFrame); mPanel->injectMouseMoved(mCamera->getCameraToViewportRay(0.5f, 0.5f)); mPanel->injectTime(evt.timeSinceLastFrame); mMouse->capture(); // Quit on ESCAPE Keyboard mKeyboard->capture(); if (mKeyboard->isKeyDown(OIS::KC_ESCAPE)) return false; return true; } bool keyPressed(const OIS::KeyEvent &e) { mPanel->injectKeyPressed(e); return true; } bool keyReleased(const OIS::KeyEvent &e) { mPanel->injectKeyReleased(e); return true; } bool mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { mPanel->injectMousePressed(evt, id); return true; } bool mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { mPanel->injectMouseReleased(evt, id); return true; } bool mouseMoved(const OIS::MouseEvent &arg) { Ogre::Real pitch = Ogre::Real(arg.state.Y.rel) * -0.005f; Ogre::Real yaw = Ogre::Real(arg.state.X.rel) * -0.005f; mCamera->pitch(Ogre::Radian(pitch)); mCamera->yaw(Ogre::Radian(yaw)); return true; } void _makeOgre() { mRoot = new Ogre::Root("", ""); mRoot->addFrameListener(this); #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX mRoot->loadPlugin(OGRE_RENDERER); #else #if 1 #ifdef _DEBUG mRoot->loadPlugin("RenderSystem_Direct3D9_d"); #else mRoot->loadPlugin("RenderSystem_Direct3D9"); #endif #else #ifdef _DEBUG mRoot->loadPlugin("RenderSystem_GL_d.dll"); #else mRoot->loadPlugin("RenderSystem_GL.dll"); #endif #endif #endif mRoot->setRenderSystem(mRoot->getAvailableRenderers()[0]); Ogre::ResourceGroupManager* rgm = Ogre::ResourceGroupManager::getSingletonPtr(); rgm->addResourceLocation(".", "FileSystem"); rgm->addResourceLocation("sinbad.zip", "Zip"); mRoot->initialise(false); Ogre::NameValuePairList misc; misc["FSAA"] = "1"; mWindow = mRoot->createRenderWindow("Gorilla", 800, 600, false, &misc); mSceneMgr = mRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE); mCamera = mSceneMgr->createCamera("Camera"); mViewport = mWindow->addViewport(mCamera); mViewport->setBackgroundColour(Ogre::ColourValue(0./255, 80./255, 160./255, .5f)); rgm->initialiseAllResourceGroups(); tvNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); tvNode->setPosition(originalTvNodePos); tvNode->setScale(2, 2, 2); Ogre::Entity* entTV = mSceneMgr->createEntity("TV.mesh"); tvNode->attachObject(entTV); Ogre::SceneNode* sinbadNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); sinbadNode->setPosition(0, 2, -2.2); sinbadNode->setScale(0.4, 0.4, 0.4); sinbadNode->yaw(Ogre::Degree(180)); entSinbad = mSceneMgr->createEntity("sinbad.mesh"); sinbadNode->attachObject(entSinbad); entSinbad->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE); a = entSinbad->getAnimationState("IdleBase"); a->setEnabled(true); a->setLoop(true); a2 = entSinbad->getAnimationState("IdleTop"); a2->setEnabled(true); a2->setLoop(true); //mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); //mCameraNode->attachObject(mCamera); mCamera->setNearClipDistance(0.05f); mCamera->setFarClipDistance(1000); } void _makeOIS() { // Initialise OIS OIS::ParamList pl; size_t windowHnd = 0; std::ostringstream windowHndStr; mWindow->getCustomAttribute("WINDOW", &windowHnd); windowHndStr << windowHnd; pl.insert(std::make_pair(Ogre::String("WINDOW"), windowHndStr.str())); mInputManager = OIS::InputManager::createInputSystem(pl); mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true)); mKeyboard->setEventCallback(this); mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true)); mMouse->setEventCallback(this); mMouse->getMouseState().width = mViewport->getActualWidth(); mMouse->getMouseState().height = mViewport->getActualHeight(); } void _makeScene() { Ogre::Plane plane(Ogre::Vector3::UNIT_Y, 0); Ogre::MeshManager::getSingleton().createPlane("ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, 1500, 1500, 20, 20, true, 1, 150, 150, Ogre::Vector3::UNIT_Z); Ogre::Entity* entGround = mSceneMgr->createEntity("GroundEntity", "ground"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(entGround); entGround->setMaterialName("Gui3DExample/Ground"); entGround->setCastShadows(false); } Ogre::Root* mRoot; Ogre::RenderWindow* mWindow; Ogre::Viewport* mViewport; Ogre::SceneManager* mSceneMgr; Ogre::Camera* mCamera; OIS::InputManager* mInputManager; OIS::Keyboard* mKeyboard; OIS::Mouse* mMouse; }; int main() { EnvironmentDemo* demo = new EnvironmentDemo(); demo->mRoot->startRendering(); delete demo; return 0; }
30.848276
120
0.625755
shanefarris
f0ae79a162cee6343a9cc5bdc989da19c7e0c60c
1,923
cpp
C++
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
46
2021-01-12T23:03:52.000Z
2021-10-01T17:29:01.000Z
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <cmath> #include <algorithm> #include <cannon/log/registry.hpp> #include <cannon/math/primes.hpp> #include <cannon/math/digits.hpp> using namespace cannon::log; using namespace cannon::math; /*! * The number 3797 has an interesting property. Being prime itself, it is * possible to continuously remove digits from left o right, and remain prime at * each stage: 3797, 797, 97, and 7. Similarly, we can work from right to left: * 3797, 379, 37, and 3. * * Find the sum of the only eleven primes that are both truncatable from left to * right and right to left. * * Note: 2, 3, 5, and 7 are not considered to be truncatable primes. */ bool is_right_truncatable(unsigned int x) { if (!is_prime(x)) return false; while (x != 0) { if (!is_prime(x)) return false; x /= 10; } return true; } bool is_left_truncatable(unsigned int x) { while (x != 0) { if (!is_prime(x)) return false; unsigned int first_digit_pow = std::floor(std::log10(x)); unsigned int first_digit = x / std::pow(10, first_digit_pow); x -= first_digit * std::pow(10, first_digit_pow); } return true; } bool is_truncatable(unsigned int x) { return is_left_truncatable(x) && is_right_truncatable(x); } unsigned int compute_truncatable_primes_sum() { unsigned int sum = 0; unsigned int num_truncatable = 0; unsigned int upper = 1000; auto primes = get_primes_up_to(upper); // Skipping 2-7 unsigned int i = 4; while (num_truncatable < 11) { for (; i < primes.size(); ++i) { if (is_truncatable(primes[i])) { log_info("Found truncatable prime:", primes[i]); sum += primes[i]; ++num_truncatable; } } upper *= 2; primes = get_primes_up_to(upper); } return sum; } int main(int argc, char** argv) { std::cout << compute_truncatable_primes_sum() << std::endl; }
22.360465
80
0.656786
cannontwo
f0af743f6522a91956e542645b9de037882c3874
1,901
cpp
C++
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
#include <chrono> #include <glm/geometric.hpp> #include "camera.h" #include "orthographic_camera.h" #include "pinhole_camera.h" #include "scene.h" #include "buffer.h" #include "raytracer.h" #include "path_tracer.h" #include "bvh.h" int main() { unsigned int width = 256; unsigned int height = 256; PinholeCamera camera(-2.5f, 2.5f, -2.5f, 2.5f, 5.0f, glm::ivec2(width, height), glm::vec3(0.0f, 0.0f, 6.0f), // position glm::vec3(0.0f, -1.0f, 0.0f), // up glm::vec3(0.0f, 0.0f, -1.0f)); // look at Scene scene; scene.load(); //Primitives number std::cout << "\nNumber of primitives: " << scene.primitives_.size(); // acceleration structure construction time auto start1 = std::chrono::high_resolution_clock::now(); scene.acc_ = std::make_unique<BVH_SAH>(scene.primitives_); auto duration1 = std::chrono:: duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start1); std::cout << "\nBVH construction time: " << duration1.count() << "s" << std::endl; Buffer rendering_buffer(width, height); glm::vec3 background_color(1.0f, 1.0f, 1.0f); // Set up the renderer. PathTracer rt(camera, scene, background_color, rendering_buffer); auto start2 = std::chrono::high_resolution_clock::now(); rt.integrate(); // Renders the final image. auto duration2 = std::chrono:: duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start2); std::cout << "\nElapsed time: " << duration2.count() << "s" << std::endl; // Save the rendered image to a .ppm file. rendering_buffer.save("teste.ppm"); return 0; }
30.174603
89
0.571804
vieiraa
f0af752401c2358f7c738dff258fa6e5bb7e7176
2,477
hpp
C++
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:27:57.000Z
2022-01-25T23:26:54.000Z
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:12:42.000Z
2015-06-23T12:41:00.000Z
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef LINEAR_BIT_BLOCK_ITERATOR_HPP_ #define LINEAR_BIT_BLOCK_ITERATOR_HPP_ #include "clotho/utility/bit_block_iterator_def.hpp" namespace clotho { namespace utility { namespace tag { struct linear_iterator_tag {}; } // namespace tag } // namespace utility } // namespace clotho namespace clotho { namespace utility { template < class Block > class bit_block_iterator < Block, clotho::utility::tag::linear_iterator_tag, typename std::enable_if< std::is_integral< Block >::value >::type > { public: typedef bit_block_iterator< Block, clotho::utility::tag::linear_iterator_tag, void > self_type; typedef Block block_type; bit_block_iterator( block_type b = (block_type)0) : m_val(b) , m_index(0) { if( (m_val & (block_type)1) == 0) next(); } bit_block_iterator( const self_type & rhs ) : m_val( rhs.m_val ) , m_index( rhs.m_index ) { } bit_block_iterator & operator++() { if( m_val ) next(); return *this; } bit_block_iterator operator++(int) { bit_block_iterator res(*this); this->operator++(); return res; } inline bool done() const { return (m_val == 0); } unsigned int operator*() const { return m_index; } bool operator==( const self_type & rhs ) const { return (this->m_val == rhs.m_val); } bool operator!=(const self_type & rhs ) const { return (this->m_val != rhs.m_val); } virtual ~bit_block_iterator() {} protected: inline void next() { do { m_val >>= 1; ++m_index; } while( (m_val != 0) && (m_val & (block_type)1) == 0 ); } block_type m_val; unsigned int m_index; }; } // namespace utility { } // namespace clotho { #endif // LINEAR_BIT_BLOCK_ITERATOR_HPP_
25.802083
146
0.634639
putnampp
f0b0a5d96d62348b136ca0edc7e881fd7b6cea60
7,451
cpp
C++
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
1
2019-01-19T01:05:07.000Z
2019-01-19T01:05:07.000Z
#define max(a, b) a > b ? a : b #define min(a, b) a < b ? a : b class bign { public: int len, s[MAX_L]; bign(); bign(const char *); bign(int); bool sign; string toStr() const; friend istream &operator>>(istream &, bign &); friend ostream &operator<<(ostream &, bign &); bign operator=(const char *); bign operator=(int); bign operator=(const string); bool operator>(const bign &) const; bool operator>=(const bign &) const; bool operator<(const bign &) const; bool operator<=(const bign &) const; bool operator==(const bign &) const; bool operator!=(const bign &) const; bign operator+(const bign &) const; bign operator++(); bign operator++(int); bign operator+=(const bign &); bign operator-(const bign &) const; bign operator--(); bign operator--(int); bign operator-=(const bign &); bign operator*(const bign &)const; bign operator*(const int num) const; bign operator*=(const bign &); bign operator/(const bign &) const; bign operator/=(const bign &); bign operator%(const bign &) const; bign bign::operator%=(const bign &); bign factorial() const; bign Sqrt() const; bign pow(const bign &) const; void clean(); ~bign(); }; bign::bign() { memset(s, 0, sizeof(s)); len = 1; sign = 1; } bign::bign(const char *num) { *this = num; } bign::bign(int num) { *this = num; } string bign::toStr() const { string res; res = ""; for (int i = 0; i < len; i++) res = (char)(s[i] + '0') + res; if (res == "") res = "0"; if (!sign && res != "0") res = "-" + res; return res; } istream &operator>>(istream &in, bign &num) { string str; in >> str; num = str; return in; } ostream &operator<<(ostream &out, bign &num) { out << num.toStr(); return out; } bign bign::operator=(const char *num) { memset(s, 0, sizeof(s)); char a[MAX_L] = ""; if (num[0] != '-') strcpy(a, num); else for (int i = 1; i < strlen(num); i++) a[i - 1] = num[i]; sign = !(num[0] == '-'); len = strlen(a); for (int i = 0; i < strlen(a); i++) s[i] = a[len - i - 1] - 48; return *this; } bign bign::operator=(int num) { char temp[MAX_L]; sprintf(temp, "%d", num); *this = temp; return *this; } bign bign::operator=(const string num) { const char *tmp; tmp = num.c_str(); *this = tmp; return *this; } bool bign::operator<(const bign &num) const { if (sign ^ num.sign) return num.sign; if (len != num.len) return len < num.len; for (int i = len - 1; i >= 0; i--) if (s[i] != num.s[i]) return sign ? (s[i] < num.s[i]) : (!(s[i] < num.s[i])); return !sign; } bool bign::operator>(const bign &num) const { return num < *this; } bool bign::operator<=(const bign &num) const { return !(*this > num); } bool bign::operator>=(const bign &num) const { return !(*this < num); } bool bign::operator!=(const bign &num) const { return *this > num || *this < num; } bool bign::operator==(const bign &num) const { return !(num != *this); } bign bign::operator+(const bign &num) const { if (sign ^ num.sign) { bign tmp = sign ? num : *this; tmp.sign = 1; return sign ? *this - tmp : num - tmp; } bign result; result.len = 0; int temp = 0; for (int i = 0; temp || i < (max(len, num.len)); i++) { int t = s[i] + num.s[i] + temp; result.s[result.len++] = t % 10; temp = t / 10; } result.sign = sign; return result; } bign bign::operator++() { *this = *this + 1; return *this; } bign bign::operator++(int) { bign old = *this; ++(*this); return old; } bign bign::operator+=(const bign &num) { *this = *this + num; return *this; } bign bign::operator-(const bign &num) const { bign b = num, a = *this; if (!num.sign && !sign) { b.sign = 1; a.sign = 1; return b - a; } if (!b.sign) { b.sign = 1; return a + b; } if (!a.sign) { a.sign = 1; b = bign(0) - (a + b); return b; } if (a < b) { bign c = (b - a); c.sign = false; return c; } bign result; result.len = 0; for (int i = 0, g = 0; i < a.len; i++) { int x = a.s[i] - g; if (i < b.len) x -= b.s[i]; if (x >= 0) g = 0; else { g = 1; x += 10; } result.s[result.len++] = x; } result.clean(); return result; } bign bign::operator*(const bign &num) const { bign result; result.len = len + num.len; for (int i = 0; i < len; i++) for (int j = 0; j < num.len; j++) result.s[i + j] += s[i] * num.s[j]; for (int i = 0; i < result.len; i++) { result.s[i + 1] += result.s[i] / 10; result.s[i] %= 10; } result.clean(); result.sign = !(sign ^ num.sign); return result; } bign bign::operator*(const int num) const { bign x = num; bign z = *this; return x * z; } bign bign::operator*=(const bign &num) { *this = *this * num; return *this; } bign bign::operator/(const bign &num) const { bign ans; ans.len = len - num.len + 1; if (ans.len < 0) { ans.len = 1; return ans; } bign divisor = *this, divid = num; divisor.sign = divid.sign = 1; int k = ans.len - 1; int j = len - 1; while (k >= 0) { while (divisor.s[j] == 0) j--; if (k > j) k = j; char z[MAX_L]; memset(z, 0, sizeof(z)); for (int i = j; i >= k; i--) z[j - i] = divisor.s[i] + '0'; bign dividend = z; if (dividend < divid) { k--; continue; } int key = 0; while (divid * key <= dividend) key++; key--; ans.s[k] = key; bign temp = divid * key; for (int i = 0; i < k; i++) temp = temp * 10; divisor = divisor - temp; k--; } ans.clean(); ans.sign = !(sign ^ num.sign); return ans; } bign bign::operator/=(const bign &num) { *this = *this / num; return *this; } bign bign::operator%(const bign &num) const { bign a = *this, b = num; a.sign = b.sign = 1; bign result, temp = a / b * b; result = a - temp; result.sign = sign; return result; } bign bign::operator%=(const bign &num) { *this = *this % num; return *this; } bign bign::pow(const bign &num) const { bign result = 1; for (bign i = 0; i < num; i++) result = result * (*this); return result; } bign bign::factorial() const { bign result = 1; for (bign i = 1; i <= *this; i++) result *= i; return result; } void bign::clean() { if (len == 0) len++; while (len > 1 && s[len - 1] == '\0') len--; } bign bign::Sqrt() const { if (*this < 0) return -1; if (*this <= 1) return *this; bign l = 0, r = *this, mid; while (r - l > 1) { mid = (l + r) / 2; if (mid * mid > *this) r = mid; else l = mid; } return l; } bign::~bign() { //Nothing to do. }
18.911168
67
0.476715
W-YXN
f0b193b1898fab2aabee86a2b7a9cf98b7551b35
14,729
cpp
C++
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
1
2019-11-22T12:03:44.000Z
2019-11-22T12:03:44.000Z
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
null
null
null
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
null
null
null
#include "smoothmethod.h" SmoothMethod::SmoothMethod() { } SmoothMethod::~SmoothMethod() { } QImage SmoothMethod::averageFiltering(QImage *originImage) { bool ok; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("均值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok); if (ok) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote() << "[Debug]" << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ":" << "图像平滑, 方式, 均值滤波" << "滤波器大小" << filterRadius; int kernel[filterRadius][filterRadius]; for (int i = 0; i < filterRadius; i++) for (int j = 0; j < filterRadius; j++) kernel[i][j] = 1; int len = filterRadius / 2; int originWidth = originImage->width(); int originHeight = originImage->height(); QImage targetImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); // 添加边框 for (int i = 0; i < targetImage.width(); i++) for (int j = 0; j < targetImage.height(); j++) if (i >= len && i < targetImage.width() - len && j >= len && j < targetImage.height() - len) { // 不在边框中 QColor originImageColor = QColor(originImage->pixel(i - len, j - len)); targetImage.setPixelColor(i, j, originImageColor); } else // 在边框中 targetImage.setPixel(i, j, Qt::white); // 将边框中颜色设置为白色 for (int i = len; i < targetImage.width() - len; i++) for (int j = len; j < targetImage.height() - len; j++) { int r = 0; int g = 0; int b = 0; for (int p = -len; p <= len; p++) for (int q = -len; q <= len; q++) { r = targetImage.pixelColor(i + p, j + q).red() * kernel[len + p][len + q] + r; g = targetImage.pixelColor(i + p, j + q).green() * kernel[len + p][len + q] + g; b = targetImage.pixelColor(i + p, j + q).blue() * kernel[len + p][len + q] + b; } r /= (filterRadius * filterRadius); g /= (filterRadius * filterRadius); b /= (filterRadius * filterRadius); if (((i - len) >= 0) && ((i - len) < originWidth) && ((j - len) >= 0) && ((j - len) < originHeight)) originImage->setPixel(i - len, j - len, qRgb(r, g, b)); } } return (*originImage); } // averageFiltering QImage SmoothMethod::medianFiltering(QImage *originImage) { // originImage 格式为 Format_RGB32 bool ok; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("中值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok); if (ok) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote() << "[Debug]" << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ":" << "图像平滑, 方式, 中值滤波" << "滤波器大小" << filterRadius; int len = filterRadius / 2; int threshold = filterRadius * filterRadius / 2 + 1; int originWidth = originImage->width(); int originHeight = originImage->height(); QImage middleImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); QImage targetImage = QImage(originWidth, originHeight, QImage::Format_RGB32); // 初始化 middleImage for (int i = 0; i < middleImage.width(); i++) { for (int j = 0; j < middleImage.height(); j++) { if ((i >= len) && (i < (middleImage.width() - len)) && (j >= len) && (j < (middleImage.height() - len))) { // 像素点不在边框中 middleImage.setPixelColor(i, j, QColor(originImage->pixel(i - len, j - len))); } else { // 像素点在边框中 middleImage.setPixelColor(i, j, Qt::white); } } } // 使用直方图记录窗口中出现的像素的出现次数 int redHist[256] = {0}; int greenHist[256] = {0}; int blueHist[256] = {0}; int grayHist[256] = {0}; for (int i = len; i < middleImage.width() - len; i++) { for (int j = len; j < middleImage.height() - len; j++) { // 设置窗口 if (j == len) { // 每到新的一列, 初始化直方图 memset(redHist, 0, sizeof(redHist)); memset(greenHist, 0, sizeof(greenHist)); memset(blueHist, 0, sizeof(blueHist)); memset(grayHist, 0, sizeof(grayHist)); for (int p = -len; p <= len; p++) { for (int q = -len; q <= len; q++) { int red = qRed(middleImage.pixel(i + p, j + q)); int green = qGreen(middleImage.pixel(i + p, j + q)); int blue = qBlue(middleImage.pixel(i + p, j + q)); int gray = qGray(middleImage.pixel(i + p, j + q)); redHist[red]++; greenHist[green]++; blueHist[blue]++; grayHist[gray]++; } } } else { // 列数增加, 窗口按列向下移动, 为窗口新添加一行像素值, 并删去一行像素值 int oldWindowStartCol = j - len - 1; int newWindowEndCol = j + len; for (int p = -len; p <= len; p++) { // 要减去的列的像素值, 从窗口上到窗口下, 即 [j-len,j+len] int red = qRed(middleImage.pixel(i + p, oldWindowStartCol)); int green = qGreen(middleImage.pixel(i + p, oldWindowStartCol)); int blue = qBlue(middleImage.pixel(i + p, oldWindowStartCol)); int gray = qGray(middleImage.pixel(i + p, oldWindowStartCol)); redHist[red]--; greenHist[green]--; blueHist[blue]--; grayHist[gray]--; red = qRed(middleImage.pixel(i + p, newWindowEndCol)); green = qGreen(middleImage.pixel(i + p, newWindowEndCol)); blue = qBlue(middleImage.pixel(i + p, newWindowEndCol)); gray = qGray(middleImage.pixel(i + p, newWindowEndCol)); redHist[red]++; greenHist[green]++; blueHist[blue]++; grayHist[gray]++; } } // 获取窗口内像素中值 int r = getMedianValue(redHist, threshold); int g = getMedianValue(greenHist, threshold); int b = getMedianValue(blueHist, threshold); targetImage.setPixel(i - len, j - len, qRgb(r, g, b)); } } return targetImage; } } // medianFiltering // 获取窗口中像素的中值 int SmoothMethod::getMedianValue(const int *histogram, int threshold) { int sum = 0; for (int i = 0; i < 256; i++) { sum += histogram[i]; if (sum >= threshold) return i; } return 255; } // getMedianValue QImage SmoothMethod::KNNF(QImage originImage) { bool ok1; bool ok2; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("K近邻均值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok1); int K = QInputDialog::getInt(nullptr, QObject::tr("K近邻均值平滑"), "输入K值", 1, 1, 30, 1, &ok2); if (ok1 & ok2) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote().nospace() << "[Debug] " << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ": " << "图像平滑, 方式, K近邻均值滤波, " << "滤波器大小, " << filterRadius << ", " << "K值, " << K; // int kernel[filterRadius][filterRadius]; // for (int i = 0; i < filterRadius; i++) // for (int j = 0; j < filterRadius; j++) // kernel[i][j] = 1; int len = filterRadius / 2; int originWidth = originImage.width(); int originHeight = originImage.height(); QImage middleImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); QImage targetImage = QImage(originWidth, originHeight, QImage::Format_RGB32); // 添加边框 for (int i = 0; i < middleImage.width(); i++) for (int j = 0; j < middleImage.height(); j++) if (i >= len && i < middleImage.width() - len && j >= len && j < middleImage.height() - len) { // 不在边框中 middleImage.setPixelColor(i, j, QColor(originImage.pixel(i - len, j - len))); } else { // 在边框中 middleImage.setPixel(i, j, Qt::white); // 将边框中颜色设置为白色 } int redHist[256] = {0}; int greenHist[256] = {0}; int blueHist[256] = {0}; for (int i = len; i < middleImage.width() - len; i++) for (int j = len; j < middleImage.height() - len; j++) { // 设置窗口 if (j == len) { // 每到新的一列, 初始化直方图 memset(redHist, 0, sizeof(redHist)); memset(greenHist, 0, sizeof(greenHist)); memset(blueHist, 0, sizeof(blueHist)); for (int p = -len; p <= len; p++) { for (int q = -len; q <= len; q++) { int red = qRed(middleImage.pixel(i + p, j + q)); int green = qGreen(middleImage.pixel(i + p, j + q)); int blue = qBlue(middleImage.pixel(i + p, j + q)); redHist[red]++; greenHist[green]++; blueHist[blue]++; } } } else { // 列数增加, 窗口按列向下移动, 为窗口新添加一行像素值, 并删去一行像素值 int oldWindowStartCol = j - len - 1; int newWindowEndCol = j + len; for (int p = -len; p <= len; p++) { // 要减去的列的像素值, 从窗口上到窗口下, 即 [j-len,j+len] int red = qRed(middleImage.pixel(i + p, oldWindowStartCol)); int green = qGreen(middleImage.pixel(i + p, oldWindowStartCol)); int blue = qBlue(middleImage.pixel(i + p, oldWindowStartCol)); redHist[red]--; greenHist[green]--; blueHist[blue]--; red = qRed(middleImage.pixel(i + p, newWindowEndCol)); green = qGreen(middleImage.pixel(i + p, newWindowEndCol)); blue = qBlue(middleImage.pixel(i + p, newWindowEndCol)); redHist[red]++; greenHist[green]++; blueHist[blue]++; } } int r = getKValue(redHist, qRed(middleImage.pixel(i, j)), K); int g = getKValue(greenHist, qGreen(middleImage.pixel(i, j)), K); int b = getKValue(blueHist, qBlue(middleImage.pixel(i, j)), K); // int r = getAverage(rKNNValue); // int g = getAverage(gKNNValue); // int b = getAverage(bKNNValue); targetImage.setPixel(i - len, j - len, qRgb(r, g, b)); } return targetImage; } return originImage; } // KNNF int SmoothMethod::getKValue(const int *histogram, int key, int K) { // 计算距离 key 的 K 近邻的方法也是桶排序 // 记录各点到 key 距离的数组长度不超过 255-key // bucket[255-key][0] => 像素值大于 key 的点其像素值与 key 的差值 // bucket[255-key][1] => 像素值小于 key 的点其像素值与 key 的差值 int bucket[255][2]; for (int i = 0; i <= 255; i++) { bucket[i][0] = 0; bucket[i][1] = 0; } for (int i = 0; i <= 255; i++) { if (histogram[i] > 0) { if (i - key >= 0) { bucket[i - key][0] = histogram[i]; } else { bucket[key - i][1] = histogram[i]; } } } int max = K + 1; int KNNValue[max] = {0}; K = K - 1; // 所有的 K 近邻点中 key 本身是第一个 KNNValue[0] = key; bucket[0][0]--; if (K <= 0) return key; // j 是 KNNValue 索引 for (int i = 0, j = 1; i <= 255; i++) { if (bucket[i][0] > 0) { // TODO 可优化 // 大于 key 的像素值 qDebug() << ">"; if (bucket[i][0] >= K) { for (int k = 0; k < K; j++, k++) { KNNValue[j] = i + key; } K = 0; } else { for (int k = 0; k < bucket[i][0]; j++, k++) { // 将所有像素值为 i 的点全部加入 KNNValue[j] = i + key; // 还原原始像素值 } K -= bucket[i][0]; } } if (K <= 0) break; if (bucket[i][1] > 0) { // 小于 key 的像素值 qDebug() << "<"; if (bucket[i][1] >= K) { for (int k = 0; k < K; j++, k++) { KNNValue[j] = key - i; } K = 0; } else { for (int k = 0; k < bucket[i][1]; j++, k++) { // 将所有像素值为 i 的点全部加入 KNNValue[j] = key - i; // 还原原始像素值 } K -= bucket[i][1]; } } if (K <= 0) break; } for (int i = 0; i < max - 1; i++) qDebug() << KNNValue[i]; // return KNNValue; int res = getAverage(KNNValue, max - 1); return res; } // getKValue int SmoothMethod::getAverage(const int *arr, int len) { int average = 0; for (int i = 0; i < len; i++) average += arr[i]; int res = average / len; return res; } // getAverage
34.494145
129
0.42345
TianSHH
f0b19e8ef7819f07395c7199e2a6c9f000b5a0ec
2,548
cpp
C++
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
5
2022-03-01T13:56:47.000Z
2022-03-09T02:57:15.000Z
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
null
null
null
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
1
2022-03-06T07:59:51.000Z
2022-03-06T07:59:51.000Z
#include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/visualization/cloud_viewer.h> #include <opencv2/opencv.hpp> #include "semanticConf.hpp" #include "genData.hpp" int main(int argc,char** argv){ if(argc<4){ std::cout<<"Usage: ./kitti_gen cloud_folder label_folder output_file"<<std::endl; exit(0); } std::string cloud_path=argv[1]; std::string label_path=argv[2]; bool label_valid[20]={0,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1}; bool use_min[20]={1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1}; int label_map[20]={-1,0,-1,-1,-1,-1,-1,-1,-1,1,2,3,4,5,6,7,8,9,10,11}; std::shared_ptr<semConf> semconf(new semConf("../conf/sem_config.yaml")); genData gener(cloud_path,label_path, semconf); CloudLPtr cloud(new CloudL); int totaldata = gener.totaldata; int num=0; pcl::visualization::CloudViewer viewer("cloud"); std::ofstream fout(argv[3],ios::binary); while (gener.getData(cloud)){ std::cout<<num<<"/"<<totaldata<<std::endl; CloudLPtr cloud_out(new CloudL); std::vector<float> dis_list; cloud_out->resize((label_map[19]+1)*360); dis_list.resize(cloud_out->size(),0.f); for(auto p:cloud->points){ if(label_valid[p.label]){ int angle=std::floor((std::atan2(p.y,p.x)+M_PI)*180./M_PI); if(angle<0||angle>359){ continue; } float dis=std::sqrt(p.x*p.x+p.y*p.y); if(dis>50){ continue; } auto& q=cloud_out->at(360*label_map[p.label]+angle); if(q.label>0){ float dis_temp=std::sqrt(q.x*q.x+q.y*q.y); if(use_min[p.label]){ if(dis<dis_temp){ q=p; dis_list[360*label_map[p.label]+angle]=dis; } }else{ if(dis>dis_temp){ q=p; dis_list[360*label_map[p.label]+angle]=dis; } } }else{ q=p; dis_list[360*label_map[p.label]+angle]=dis; } } } for(auto dis:dis_list){ fout.write((char*)(&dis),sizeof(dis)); } auto ccloud=semconf->getColorCloud(cloud_out); viewer.showCloud(ccloud); ++num; } fout.close(); return 0; }
36.4
89
0.494505
lilin-hitcrt
f0b9afdee429081c137cbabb2df8b2a312396ec3
1,221
cpp
C++
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa12096 The SetStack Computer // Rujia Liu #include<iostream> #include<string> #include<set> #include<map> #include<stack> #include<vector> #include<algorithm> using namespace std; #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) typedef set<int> Set; map<Set,int> IDcache; // 把集合映射成ID vector<Set> Setcache; // 根据ID取集合 // 查找给定集合x的ID。如果找不到,分配一个新ID int ID (Set x) { if (IDcache.count(x)) return IDcache[x]; Setcache.push_back(x); // 添加新集合 return IDcache[x] = Setcache.size() - 1; } int main () { int T; cin >> T; while(T--) { stack<int> s; // 题目中的栈 int n; cin >> n; for(int i = 0; i < n; i++) { string op; cin >> op; if (op[0] == 'P') s.push(ID(Set())); else if (op[0] == 'D') s.push(s.top()); else { Set x1 = Setcache[s.top()]; s.pop(); Set x2 = Setcache[s.top()]; s.pop(); Set x; if (op[0] == 'U') set_union (ALL(x1), ALL(x2), INS(x)); if (op[0] == 'I') set_intersection (ALL(x1), ALL(x2), INS(x)); if (op[0] == 'A') { x = x2; x.insert(ID(x1)); } s.push(ID(x)); } cout << Setcache[s.top()].size() << endl; } cout << "***" << endl; } return 0; }
23.037736
70
0.527437
Anyrainel
f0bfeb13d9f891159be59bd3a9018602f94a5beb
5,432
cc
C++
base/test/scoped_feature_list.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/test/scoped_feature_list.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/test/scoped_feature_list.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 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/test/scoped_feature_list.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" namespace base { namespace test { namespace { std::vector<StringPiece> GetFeatureVector( const std::initializer_list<Feature>& features) { std::vector<StringPiece> output; for (const Feature& feature : features) { output.push_back(feature.name); } return output; } // Extracts a feature name from a feature state string. For example, given // the input "*MyLovelyFeature<SomeFieldTrial", returns "MyLovelyFeature". StringPiece GetFeatureName(StringPiece feature) { StringPiece feature_name = feature; // Remove default info. if (feature_name.starts_with("*")) feature_name = feature_name.substr(1); // Remove field_trial info. std::size_t index = feature_name.find("<"); if (index != std::string::npos) feature_name = feature_name.substr(0, index); return feature_name; } struct Features { std::vector<StringPiece> enabled_feature_list; std::vector<StringPiece> disabled_feature_list; }; // Merges previously-specified feature overrides with those passed into one of // the Init() methods. |features| should be a list of features previously // overridden to be in the |override_state|. |merged_features| should contain // the enabled and disabled features passed into the Init() method, plus any // overrides merged as a result of previous calls to this function. void OverrideFeatures(const std::string& features, FeatureList::OverrideState override_state, Features* merged_features) { std::vector<StringPiece> features_list = SplitStringPiece(features, ",", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY); for (StringPiece feature : features_list) { StringPiece feature_name = GetFeatureName(feature); if (ContainsValue(merged_features->enabled_feature_list, feature_name) || ContainsValue(merged_features->disabled_feature_list, feature_name)) continue; if (override_state == FeatureList::OverrideState::OVERRIDE_ENABLE_FEATURE) { merged_features->enabled_feature_list.push_back(feature); } else { DCHECK_EQ(override_state, FeatureList::OverrideState::OVERRIDE_DISABLE_FEATURE); merged_features->disabled_feature_list.push_back(feature); } } } } // namespace ScopedFeatureList::ScopedFeatureList() {} ScopedFeatureList::~ScopedFeatureList() { if (original_feature_list_) { FeatureList::ClearInstanceForTesting(); FeatureList::RestoreInstanceForTesting(std::move(original_feature_list_)); } } void ScopedFeatureList::Init() { std::unique_ptr<FeatureList> feature_list(new FeatureList); feature_list->InitializeFromCommandLine(std::string(), std::string()); InitWithFeatureList(std::move(feature_list)); } void ScopedFeatureList::InitWithFeatureList( std::unique_ptr<FeatureList> feature_list) { DCHECK(!original_feature_list_); original_feature_list_ = FeatureList::ClearInstanceForTesting(); FeatureList::SetInstance(std::move(feature_list)); } void ScopedFeatureList::InitFromCommandLine( const std::string& enable_features, const std::string& disable_features) { std::unique_ptr<FeatureList> feature_list(new FeatureList); feature_list->InitializeFromCommandLine(enable_features, disable_features); InitWithFeatureList(std::move(feature_list)); } void ScopedFeatureList::InitWithFeatures( const std::initializer_list<Feature>& enabled_features, const std::initializer_list<Feature>& disabled_features) { Features merged_features; merged_features.enabled_feature_list = GetFeatureVector(enabled_features); merged_features.disabled_feature_list = GetFeatureVector(disabled_features); FeatureList* feature_list = FeatureList::GetInstance(); // |current_enabled_features| and |current_disabled_features| must declare out // of if scope to avoid them out of scope before JoinString calls because // |merged_features| may contains StringPiece which holding pointer points to // |current_enabled_features| and |current_disabled_features|. std::string current_enabled_features; std::string current_disabled_features; if (feature_list) { FeatureList::GetInstance()->GetFeatureOverrides(&current_enabled_features, &current_disabled_features); OverrideFeatures(current_enabled_features, FeatureList::OverrideState::OVERRIDE_ENABLE_FEATURE, &merged_features); OverrideFeatures(current_disabled_features, FeatureList::OverrideState::OVERRIDE_DISABLE_FEATURE, &merged_features); } std::string enabled = JoinString(merged_features.enabled_feature_list, ","); std::string disabled = JoinString(merged_features.disabled_feature_list, ","); InitFromCommandLine(enabled, disabled); } void ScopedFeatureList::InitAndEnableFeature(const Feature& feature) { InitWithFeatures({feature}, {}); } void ScopedFeatureList::InitAndDisableFeature(const Feature& feature) { InitWithFeatures({}, {feature}); } } // namespace test } // namespace base
35.272727
80
0.745398
metux
f0c266afdbbcaeb1c0628f623cfc342ab307f85c
5,958
hh
C++
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
#ifndef MOONEY_RIVLIN_HH #define MOONEY_RIVLIN_HH #include "linalg/invariants.hh" #include "utilities/functionTools.hh" namespace Kaskade { template <int dim, class VolumetricPenalty = void, Invariant i = Invariant::Principal, class Direction = void> class MooneyRivlin; /** * \param lambda first Lame constant * \param mu second Lame constant */ template <class VolumetricPenalty, int dim, Invariant i = Invariant::Principal, class Direction = void> MooneyRivlin<dim,VolumetricPenalty,i,Direction> createMooneyRivlinFromLameConstants(double lambda, double mu) { static_assert(!std::is_same<VolumetricPenalty,void>::value,"not implemented"); VolumetricPenalty g; // std::cout << "g': " << g.d1(1) << ", g'': " << g.d2(1) << std::endl; //double c = (lambda + 2*mu)/(g.d2(1)-g.d1(1)); //double b = -0.5*mu - 0.5*c*g.d1(1); //double a = mu + 0.5*c*g.d1(1); double rho = g.d1(1)/(-g.d2(1)+g.d1(1)); double d = (lambda+2.0*mu)/(g.d2(1)-g.d1(1)); double c = (0.5*rho-0.25)*mu+0.25*rho*lambda; if(c > 0.25*mu) c = (rho-0.75)*mu+0.5*rho*lambda; double b = -mu + rho*(lambda+2.*mu)-2.*c; double a = b + mu; double alpha = 0.5*a - b; double beta = 0.5*b; // std::cout << "alpha: " << alpha << ", beta: " << beta << ", c: " << c << ", d: " << d << std::endl; if(a<0 || b<0 || c<0) { std::cout << "computed parameters: " << a << ", " << b << ", " << c << ", " << d << std::endl; std::cout << "alpha=" << alpha << ", beta=" << beta << std::endl; std::cout << "material law is not polyconvex" << std::endl; exit(1); } return MooneyRivlin<dim,VolumetricPenalty,i,Direction>(alpha,beta,c,d); } /** * \param E Young's modulus * \param nu Poisson ratio */ template <class VolumetricPenalty, int dim, Invariant i = Invariant::Principal, class Direction = void> MooneyRivlin<dim,VolumetricPenalty,i,Direction> createMooneyRivlinFromMaterialConstants(double E, double nu) { static_assert(!std::is_same<VolumetricPenalty,void>::value,"not implemented"); double lambda = E*nu/((1+nu)*(1-2*nu)); double mu = E/(2*(1+nu)); return createMooneyRivlinFromLameConstants<VolumetricPenalty,dim,i,Direction>(lambda,mu); } template <int dim, class VolumetricPenalty, Invariant i, class Direction> class MooneyRivlin : public StrainBase<double,dim>, public Sum<Scaled<ShiftedInvariant<typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, Scaled<ShiftedInvariant<typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, MatrixToScalarFunction<VolumetricPenalty,Determinant<dim> > > { typedef typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv1; typedef ShiftedInvariant<Inv1> SInv1; typedef typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv2; typedef ShiftedInvariant<Inv2> SInv2; typedef Determinant<dim> Det; typedef MatrixToScalarFunction<VolumetricPenalty,Det>Penalty; typedef Sum<Scaled<SInv1>,Scaled<SInv2>,Penalty> Base; using StrainBase<double,dim>::F; using StrainBase<double,dim>::S; public: typedef double Scalar; MooneyRivlin(double lambda, double mu) : MooneyRivlin(createMooneyRivlinFromLameConstants<VolumetricPenalty,dim>(lambda,mu)) {} // template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1, double c2, double c3) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S),dim)), Scaled<SInv2>(c1,SInv2(Inv2(S),dim)), Penalty(Det(F),VolumetricPenalty(c2,c3))) { assert(c0>0 && c1>0 && c2>0); } template <class Dir, class enable = typename std::enable_if< std::is_same<Direction,Dir>::value && !std::is_same<void,Direction>::value,void>::type> MooneyRivlin(double c0, double c1, double c2, double c3, Dir d) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S,d),dim)), Scaled<SInv2>(c1,SInv2(Inv2(S,d),dim)), Penalty(Det(F),VolumetricPenalty(c2,c3))) { assert(c0>0 && c1>0 && c2>0); } MooneyRivlin(MooneyRivlin const&) = default; MooneyRivlin& operator=(MooneyRivlin const&) = default; }; template <int dim, Invariant i,class Direction> class MooneyRivlin<dim,void,i,Direction> : public StrainBase<double,dim>, public Sum<Scaled<ShiftedInvariant<typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, Scaled<ShiftedInvariant<typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> > > { typedef typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv1; typedef typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv2; typedef ShiftedInvariant<Inv1> SInv1; typedef ShiftedInvariant<Inv2> SInv2; typedef Sum<Scaled<SInv1>,Scaled<SInv2> > Base; using StrainBase<double,dim>::S; public: typedef double Scalar; template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S),dim)),Scaled<SInv2>(c1,SInv2(Inv2(S),dim))) { assert(c0>0 && c1>0); } template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && !std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1, Direction const& d) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S,d),dim)),Scaled<SInv2>(c1,SInv2(Inv2(S,d),dim))) { assert(c0>0 && c1>0); } MooneyRivlin(MooneyRivlin const&) = default; MooneyRivlin& operator=(MooneyRivlin const&) = default; }; } #endif
46.546875
158
0.678583
chenzongxiong
f0c422605b8c43b5b392f5f57e418a229c356f8d
970
hpp
C++
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
#ifndef SOKOBAN_AGENT_DEFINES #define SOKOBAN_AGENT_DEFINES #include <vector> #include <string> #include <iostream> enum MoveDirection{ Left = 0, Right = 1, Up = 2, Down = 3, Unspecified = -1, }; using Map = std::vector<std::string>; using Position = std::pair<int, int>; using Decimal = float; std::string getKey(const Map map); std::string getKey(const Position manPos, const std::vector<Position> boxPos); std::pair< Position, std::vector<Position> > getPositions(const Map map); Map move(const Map& map, const MoveDirection direction, const Map& level); void write_solution(const std::string filename, const Map& map, const std::vector<MoveDirection>& policy); std::vector< std::pair<Map, std::vector<MoveDirection>> > read_solutions(std::string filename); Map readMap(std::istream &stream); std::vector< std::pair<Map, std::vector<MoveDirection>> > clean_solutions(std::vector< std::pair<Map, std::vector<MoveDirection>> > solutions); #endif
34.642857
143
0.727835
Yao-Chung
f0c83d8b974fd845985527c413970c06730c5cc1
1,561
hpp
C++
apps/src/videostitch-live-gui/src/configurations/rigconfigurationwidget.hpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
apps/src/videostitch-live-gui/src/configurations/rigconfigurationwidget.hpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
apps/src/videostitch-live-gui/src/configurations/rigconfigurationwidget.hpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #ifndef RIGCONFIGURATIONWIDGET_HPP #define RIGCONFIGURATIONWIDGET_HPP #include <QWidget> #include "ui_rigconfigurationwidget.h" #include "libvideostitch/stereoRigDef.hpp" class RigConfigurationWidget : public QFrame, public Ui::RigConfigurationWidgetClass { Q_OBJECT public: explicit RigConfigurationWidget(QWidget* const parent = nullptr); ~RigConfigurationWidget(); void loadConfiguration(const QStringList inputNames, const VideoStitch::Core::StereoRigDefinition::Orientation orientation, const VideoStitch::Core::StereoRigDefinition::Geometry geometry, const double diameter, const double ipd, const QVector<int> leftInputs, const QVector<int> rightInputs); signals: void notifyRigConfigured(const VideoStitch::Core::StereoRigDefinition::Orientation orientation, const VideoStitch::Core::StereoRigDefinition::Geometry geometry, const double diameter, const double ipd, const QVector<int> leftInputs, const QVector<int> rightInputs); public slots: void onButtonAcceptClicked(); void onButtonCircularChecked(); void onButtonPolygonalChecked(); void onOrientationChanged(const QString& orientation); private: void addInputsToList(const QVector<int> left, const QVector<int> right); QVector<int> getLeftInputs() const; QVector<int> getRightInputs() const; QStringList inputNames; }; #endif // RIGCONFIGURATIONWIDGET_HPP
39.025
114
0.73991
tlalexander
f0c9ea61afd241f3c72bd16e62d22587e4d0f3d9
53,605
hh
C++
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
2
2020-01-28T07:59:26.000Z
2020-09-17T06:32:14.000Z
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
null
null
null
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
null
null
null
#include <basic/options/option_macros.hh> #include <basic/options/keys/corrections.OptionKeys.gen.hh> #include <riflib/scaffold/nineA_util.hh> #include <vector> #ifdef GLOBAL_VARIABLES_ARE_BAD #ifndef INCLUDED_rif_dock_test_hh_1 #define INCLUDED_rif_dock_test_hh_1 OPT_1GRP_KEY( StringVector , rif_dock, scaffolds ) OPT_1GRP_KEY( StringVector, rif_dock, scaffold_res ) OPT_1GRP_KEY( StringVector, rif_dock, scaffold_res_fixed ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_res_use_best_guess ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_to_ala ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_to_ala_selonly ) OPT_1GRP_KEY( Boolean , rif_dock, replace_orig_scaffold_res ) OPT_1GRP_KEY( Boolean , rif_dock, replace_all_with_ala_1bre ) OPT_1GRP_KEY( Boolean , rif_dock, random_perturb_scaffold ) OPT_1GRP_KEY( StringVector, rif_dock, target_bounding_xmaps ) OPT_1GRP_KEY( String , rif_dock, target_pdb ) OPT_1GRP_KEY( String , rif_dock, target_res ) OPT_1GRP_KEY( String , rif_dock, target_rif ) OPT_1GRP_KEY( Real , rif_dock, target_rf_resl ) OPT_1GRP_KEY( Integer , rif_dock, target_rf_oversample ) OPT_1GRP_KEY( String , rif_dock, target_rf_cache ) OPT_1GRP_KEY( String , rif_dock, target_donors ) OPT_1GRP_KEY( String , rif_dock, target_acceptors ) OPT_1GRP_KEY( Boolean , rif_dock, only_load_highest_resl ) OPT_1GRP_KEY( Boolean , rif_dock, use_rosetta_grid_energies ) OPT_1GRP_KEY( Boolean , rif_dock, soft_rosetta_grid_energies ) OPT_1GRP_KEY( StringVector, rif_dock, data_cache_dir ) OPT_1GRP_KEY( Real , rif_dock, beam_size_M ) OPT_1GRP_KEY( Real , rif_dock, max_beam_multiplier ) OPT_1GRP_KEY( Boolean , rif_dock, multiply_beam_by_seeding_positions ) OPT_1GRP_KEY( Boolean , rif_dock, multiply_beam_by_scaffolds ) OPT_1GRP_KEY( Real , rif_dock, search_diameter ) OPT_1GRP_KEY( Real , rif_dock, hsearch_scale_factor ) OPT_1GRP_KEY( Real , rif_dock, max_rf_bounding_ratio ) OPT_1GRP_KEY( Boolean , rif_dock, make_bounding_plot_data ) OPT_1GRP_KEY( Boolean , rif_dock, align_output_to_scaffold ) OPT_1GRP_KEY( Boolean , rif_dock, output_scaffold_only ) OPT_1GRP_KEY( Boolean , rif_dock, output_full_scaffold_only ) OPT_1GRP_KEY( Boolean , rif_dock, output_full_scaffold ) OPT_1GRP_KEY( Integer , rif_dock, n_pdb_out ) OPT_1GRP_KEY( Real , rif_dock, rf_resl ) OPT_1GRP_KEY( Integer , rif_dock, rf_oversample ) OPT_1GRP_KEY( Boolean , rif_dock, downscale_atr_by_hierarchy ) OPT_1GRP_KEY( Real , rif_dock, favorable_1body_multiplier ) OPT_1GRP_KEY( Real , rif_dock, favorable_1body_multiplier_cutoff ) OPT_1GRP_KEY( Real , rif_dock, favorable_2body_multiplier ) OPT_1GRP_KEY( Integer , rif_dock, rotrf_oversample ) OPT_1GRP_KEY( Real , rif_dock, rotrf_resl ) OPT_1GRP_KEY( Real , rif_dock, rotrf_spread ) OPT_1GRP_KEY( Real , rif_dock, rotrf_scale_atr ) OPT_1GRP_KEY( String , rif_dock, rotrf_cache_dir ) OPT_1GRP_KEY( Boolean , rif_dock, hack_pack ) OPT_1GRP_KEY( Boolean , rif_dock, hack_pack_during_hsearch ) OPT_1GRP_KEY( Real , rif_dock, hack_pack_frac ) OPT_1GRP_KEY( Real , rif_dock, pack_iter_mult ) OPT_1GRP_KEY( Integer , rif_dock, pack_n_iters ) OPT_1GRP_KEY( Real , rif_dock, hbond_weight ) OPT_1GRP_KEY( Real , rif_dock, upweight_multi_hbond ) OPT_1GRP_KEY( Real , rif_dock, min_hb_quality_for_satisfaction ) OPT_1GRP_KEY( Real , rif_dock, long_hbond_fudge_distance ) OPT_1GRP_KEY( Real , rif_dock, global_score_cut ) OPT_1GRP_KEY( Real , rif_dock, redundancy_filter_mag ) OPT_1GRP_KEY( Boolean , rif_dock, filter_seeding_positions_separately ) OPT_1GRP_KEY( Boolean , rif_dock, filter_scaffolds_separately ) OPT_1GRP_KEY( Real , rif_dock, force_output_if_close_to_input ) OPT_1GRP_KEY( Integer , rif_dock, force_output_if_close_to_input_num ) OPT_1GRP_KEY( Real , rif_dock, upweight_iface ) OPT_1GRP_KEY( Boolean , rif_dock, use_scaffold_bounding_grids ) OPT_1GRP_KEY( Boolean , rif_dock, restrict_to_native_scaffold_res ) OPT_1GRP_KEY( Real , rif_dock, bonus_to_native_scaffold_res ) OPT_1GRP_KEY( Boolean , rif_dock, add_native_scaffold_rots_when_packing ) OPT_1GRP_KEY( Boolean , rif_dock, dump_all_rif_rots ) OPT_1GRP_KEY( Boolean , rif_dock, dump_all_rif_rots_into_output ) OPT_1GRP_KEY( Boolean , rif_dock, rif_rots_as_chains ) OPT_1GRP_KEY( String , rif_dock, dump_rifgen_near_pdb ) OPT_1GRP_KEY( Real , rif_dock, dump_rifgen_near_pdb_dist ) OPT_1GRP_KEY( Real , rif_dock, dump_rifgen_near_pdb_frac ) OPT_1GRP_KEY( Boolean , rif_dock, dump_rifgen_text ) OPT_1GRP_KEY( String , rif_dock, score_this_pdb ) OPT_1GRP_KEY( String , rif_dock, dump_pdb_at_bin_center ) OPT_1GRP_KEY( String , rif_dock, dokfile ) OPT_1GRP_KEY( String , rif_dock, outdir ) OPT_1GRP_KEY( String , rif_dock, output_tag ) OPT_1GRP_KEY( Boolean , rif_dock, dont_use_scaffold_loops ) OPT_1GRP_KEY( Boolean , rif_dock, dump_resfile ) OPT_1GRP_KEY( Boolean , rif_dock, pdb_info_pikaa ) OPT_1GRP_KEY( Boolean , rif_dock, cache_scaffold_data ) OPT_1GRP_KEY( Real , rif_dock, tether_to_input_position ) OPT_1GRP_KEY( Boolean , rif_dock, lowres_sterics_cbonly ) OPT_1GRP_KEY( Integer , rif_dock, require_satisfaction ) OPT_1GRP_KEY( Integer , rif_dock, num_hotspots ) OPT_1GRP_KEY( Integer , rif_dock, require_n_rifres ) OPT_1GRP_KEY( Boolean , rif_dock, use_dl_mix_bb ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_fraction ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_then_min_below_thresh ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_at_least ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_at_most ) OPT_1GRP_KEY( Real , rif_dock, rosetta_min_fraction ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_min_at_least ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_fix_target ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_targetbb ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_scaffoldbb ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_allbb ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_cut ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_hard_min ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_total ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_ddg_only ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_rifres_rifres_weight ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_rifres_scaffold_weight ) OPT_1GRP_KEY( String , rif_dock, rosetta_soft_score ) OPT_1GRP_KEY( String , rif_dock, rosetta_hard_score ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_filter_before ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_filter_n_per_scaffold ) OPT_1GRP_KEY( Real , rif_dock, rosetta_filter_redundancy_mag ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_filter_even_if_no_score ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_debug_dump_scores ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_select_random ) OPT_1GRP_KEY( Boolean , rif_dock, extra_rotamers ) OPT_1GRP_KEY( Boolean , rif_dock, extra_rif_rotamers ) OPT_1GRP_KEY( Integer , rif_dock, always_available_rotamers_level ) OPT_1GRP_KEY( Boolean , rif_dock, packing_use_rif_rotamers ) OPT_1GRP_KEY( Integer , rif_dock, nfold_symmetry ) OPT_1GRP_KEY( RealVector , rif_dock, symmetry_axis ) OPT_1GRP_KEY( Real , rif_dock, user_rotamer_bonus_constant ) OPT_1GRP_KEY( Real , rif_dock, user_rotamer_bonus_per_chi ) OPT_1GRP_KEY( Real , rif_dock, resl0 ) OPT_1GRP_KEY( Integer , rif_dock, dump_x_frames_per_resl ) OPT_1GRP_KEY( Boolean , rif_dock, dump_only_best_frames ) OPT_1GRP_KEY( Integer , rif_dock, dump_only_best_stride ) OPT_1GRP_KEY( String , rif_dock, dump_prefix ) OPT_1GRP_KEY( String , rif_dock, scaff_search_mode ) OPT_1GRP_KEY( String , rif_dock, nineA_cluster_path ) OPT_1GRP_KEY( String , rif_dock, nineA_baseline_range ) OPT_1GRP_KEY( Integer , rif_dock, low_cut_site ) OPT_1GRP_KEY( Integer , rif_dock, high_cut_site ) OPT_1GRP_KEY( Integer , rif_dock, max_insertion ) OPT_1GRP_KEY( Integer , rif_dock, max_deletion ) OPT_1GRP_KEY( Real , rif_dock, fragment_cluster_tolerance ) OPT_1GRP_KEY( Real , rif_dock, fragment_max_rmsd ) OPT_1GRP_KEY( Integer , rif_dock, max_fragments ) OPT_1GRP_KEY( StringVector, rif_dock, morph_rules_files ) OPT_1GRP_KEY( String , rif_dock, morph_silent_file ) OPT_1GRP_KEY( String , rif_dock, morph_silent_archetype ) OPT_1GRP_KEY( Real , rif_dock, morph_silent_max_structures ) OPT_1GRP_KEY( Boolean , rif_dock, morph_silent_random_selection ) OPT_1GRP_KEY( Real , rif_dock, morph_silent_cluster_use_frac ) OPT_1GRP_KEY( Boolean , rif_dock, include_parent ) OPT_1GRP_KEY( Boolean , rif_dock, use_parent_body_energies ) OPT_1GRP_KEY( Integer , rif_dock, dive_resl ) OPT_1GRP_KEY( Integer , rif_dock, pop_resl ) OPT_1GRP_KEY( String , rif_dock, match_this_pdb ) OPT_1GRP_KEY( Real , rif_dock, match_this_rmsd ) OPT_1GRP_KEY( String , rif_dock, rot_spec_fname ) // constrain file OPT_1GRP_KEY( StringVector, rif_dock, cst_files ) OPT_1GRP_KEY( StringVector, rif_dock, seed_with_these_pdbs ) OPT_1GRP_KEY( Boolean , rif_dock, seed_include_input ) OPT_1GRP_KEY( StringVector, rif_dock, seeding_pos ) OPT_1GRP_KEY( Boolean , rif_dock, seeding_by_patchdock ) OPT_1GRP_KEY( String , rif_dock, xform_pos ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_each_seeding_at_least ) OPT_1GRP_KEY( Real , rif_dock, cluster_score_cut ) OPT_1GRP_KEY( Real , rif_dock, keep_top_clusters_frac ) OPT_1GRP_KEY( Real , rif_dock, unsat_orbital_penalty ) OPT_1GRP_KEY( Real , rif_dock, neighbor_distance_cutoff ) OPT_1GRP_KEY( Integer , rif_dock, unsat_neighbor_cutoff ) OPT_1GRP_KEY( Boolean , rif_dock, unsat_debug ) OPT_1GRP_KEY( Boolean , rif_dock, test_hackpack ) OPT_1GRP_KEY( String , rif_dock, unsat_helper ) OPT_1GRP_KEY( Real , rif_dock, unsat_score_offset ) OPT_1GRP_KEY( Integer , rif_dock, unsat_require_burial ) OPT_1GRP_KEY( Boolean , rif_dock, report_common_unsats ) OPT_1GRP_KEY( Boolean , rif_dock, dump_presatisfied_donors_acceptors ) OPT_1GRP_KEY( IntegerVector, rif_dock, requirements ) void register_options() { using namespace basic::options; using namespace basic::options::OptionKeys; NEW_OPT( rif_dock::scaffolds, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res_fixed, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res_use_best_guess, "" , false ); NEW_OPT( rif_dock::scaffold_to_ala, "" , false ); NEW_OPT( rif_dock::scaffold_to_ala_selonly, "" , true ); NEW_OPT( rif_dock::replace_orig_scaffold_res, "", true ); NEW_OPT( rif_dock::replace_all_with_ala_1bre, "" , false ); NEW_OPT( rif_dock::random_perturb_scaffold, "" , false ); NEW_OPT( rif_dock::target_bounding_xmaps, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::target_pdb, "" , "" ); NEW_OPT( rif_dock::target_res, "" , "" ); NEW_OPT( rif_dock::target_rif, "" , "" ); NEW_OPT( rif_dock::target_rf_resl, "" , 0.25 ); NEW_OPT( rif_dock::target_rf_oversample, "" , 2 ); NEW_OPT( rif_dock::downscale_atr_by_hierarchy, "" , true ); NEW_OPT( rif_dock::favorable_1body_multiplier, "Anything with a one-body energy less than favorable_1body_cutoff gets multiplied by this", 1 ); NEW_OPT( rif_dock::favorable_1body_multiplier_cutoff, "Anything with a one-body energy less than this gets multiplied by favorable_1body_multiplier", 0 ); NEW_OPT( rif_dock::favorable_2body_multiplier, "Anything with a two-body energy less than 0 gets multiplied by this", 1 ); NEW_OPT( rif_dock::target_rf_cache, "" , "NO_CACHE_SPECIFIED_ON_COMMAND_LINE" ); NEW_OPT( rif_dock::target_donors, "", "" ); NEW_OPT( rif_dock::target_acceptors, "", "" ); NEW_OPT( rif_dock::only_load_highest_resl, "Only read in the highest resolution rif", false ); NEW_OPT( rif_dock::use_rosetta_grid_energies, "Use Frank's grid energies for scoring", false ); NEW_OPT( rif_dock::soft_rosetta_grid_energies, "Use soft option for grid energies", false ); NEW_OPT( rif_dock::data_cache_dir, "" , utility::vector1<std::string>(1,"./") ); NEW_OPT( rif_dock::beam_size_M, "" , 10.000000 ); NEW_OPT( rif_dock::max_beam_multiplier, "Maximum beam multiplier", 1 ); NEW_OPT( rif_dock::multiply_beam_by_seeding_positions, "Multiply beam size by number of seeding positions", false); NEW_OPT( rif_dock::multiply_beam_by_scaffolds, "Multiply beam size by number of scaffolds", true); NEW_OPT( rif_dock::max_rf_bounding_ratio, "" , 4 ); NEW_OPT( rif_dock::make_bounding_plot_data, "" , false ); NEW_OPT( rif_dock::align_output_to_scaffold, "" , false ); NEW_OPT( rif_dock::output_scaffold_only, "" , false ); NEW_OPT( rif_dock::output_full_scaffold_only, "" , false ); NEW_OPT( rif_dock::output_full_scaffold, "", false ); NEW_OPT( rif_dock::n_pdb_out, "" , 10 ); NEW_OPT( rif_dock::rf_resl, "" , 0.25 ); NEW_OPT( rif_dock::rf_oversample, "" , 2 ); NEW_OPT( rif_dock::rotrf_oversample, "" , 2 ); NEW_OPT( rif_dock::rotrf_resl, "" , 0.3 ); NEW_OPT( rif_dock::rotrf_spread, "" , 0.0 ); NEW_OPT( rif_dock::rotrf_scale_atr, "" , 1.0 ); NEW_OPT( rif_dock::rotrf_cache_dir, "" , "./" ); NEW_OPT( rif_dock::hack_pack, "" , true ); NEW_OPT( rif_dock::hack_pack_during_hsearch, "hackpack during hsearch", false ); NEW_OPT( rif_dock::hack_pack_frac, "" , 0.2 ); NEW_OPT( rif_dock::pack_iter_mult, "" , 2.0 ); NEW_OPT( rif_dock::pack_n_iters, "" , 1 ); NEW_OPT( rif_dock::hbond_weight, "" , 2.0 ); NEW_OPT( rif_dock::upweight_multi_hbond, "" , 0.0 ); NEW_OPT( rif_dock::min_hb_quality_for_satisfaction, "Minimum fraction of total hbond energy required for satisfaction. Scale -1 to 0", -0.6 ); NEW_OPT( rif_dock::long_hbond_fudge_distance, "Any hbond longer than 2A gets moved closer to 2A by this amount for scoring", 0.0 ); NEW_OPT( rif_dock::global_score_cut, "" , 0.0 ); NEW_OPT( rif_dock::redundancy_filter_mag, "" , 1.0 ); NEW_OPT( rif_dock::filter_seeding_positions_separately, "Redundancy filter each seeding position separately", true ); NEW_OPT( rif_dock::filter_scaffolds_separately, "Redundancy filter each scaffold separately", true ); NEW_OPT( rif_dock::force_output_if_close_to_input, "" , 1.0 ); NEW_OPT( rif_dock::force_output_if_close_to_input_num, "" , 0 ); NEW_OPT( rif_dock::upweight_iface, "", 1.2 ); NEW_OPT( rif_dock::use_scaffold_bounding_grids, "", false ); NEW_OPT( rif_dock::search_diameter, "", 150.0 ); NEW_OPT( rif_dock::hsearch_scale_factor, "global scaling of rotation/translation search grid", 1.0 ); NEW_OPT( rif_dock::restrict_to_native_scaffold_res, "aka structure prediction CHEAT", false ); NEW_OPT( rif_dock::bonus_to_native_scaffold_res, "aka favor native CHEAT", -0.3 ); NEW_OPT( rif_dock::add_native_scaffold_rots_when_packing, "CHEAT", false ); NEW_OPT( rif_dock::dump_all_rif_rots, "", false ); NEW_OPT( rif_dock::dump_all_rif_rots_into_output, "dump all rif rots into output", false); NEW_OPT( rif_dock::rif_rots_as_chains, "dump rif rots as chains instead of models, loses resnum if true", false ); NEW_OPT( rif_dock::dump_rifgen_near_pdb, "dump rifgen rotamers with same AA type near this single residue", ""); NEW_OPT( rif_dock::dump_rifgen_near_pdb_dist, "", 1 ); NEW_OPT( rif_dock::dump_rifgen_near_pdb_frac, "", 1 ); NEW_OPT( rif_dock::dump_rifgen_text, "Dump the rifgen tables within dump_rifgen_near_pdb_dist", false ); NEW_OPT( rif_dock::score_this_pdb, "Score every residue of this pdb using the rif scoring machinery", "" ); NEW_OPT( rif_dock::dump_pdb_at_bin_center, "Dump each residue of this pdb at the rotamer's bin center", "" ); NEW_OPT( rif_dock::dokfile, "", "default.dok" ); NEW_OPT( rif_dock::outdir, "", "./" ); NEW_OPT( rif_dock::output_tag, "", "" ); NEW_OPT( rif_dock::dont_use_scaffold_loops, "", false ); NEW_OPT( rif_dock::dump_resfile, "", false ); NEW_OPT( rif_dock::pdb_info_pikaa, "", false ); NEW_OPT( rif_dock::cache_scaffold_data, "", false ); NEW_OPT( rif_dock::tether_to_input_position, "", -1.0 ); NEW_OPT( rif_dock::lowres_sterics_cbonly, "", true ); NEW_OPT( rif_dock::require_satisfaction, "", 0 ); NEW_OPT( rif_dock::num_hotspots, "Number of hotspots found in Rifdock hotspots. If in doubt, set this to 1000", 0 ); NEW_OPT( rif_dock::require_n_rifres, "This doesn't work during HackPack", 0 ); NEW_OPT( rif_dock::use_dl_mix_bb, "use phi to decide where d is allow", false ); NEW_OPT( rif_dock::rosetta_score_fraction , "", 0.00 ); NEW_OPT( rif_dock::rosetta_score_then_min_below_thresh, "", -9e9 ); NEW_OPT( rif_dock::rosetta_score_at_least, "", -1 ); NEW_OPT( rif_dock::rosetta_score_at_most, "", 999999999 ); NEW_OPT( rif_dock::rosetta_min_fraction , "", 0.1 ); NEW_OPT( rif_dock::rosetta_min_at_least, "", -1 ); NEW_OPT( rif_dock::rosetta_min_targetbb , "", false ); NEW_OPT( rif_dock::rosetta_min_scaffoldbb , "", false ); NEW_OPT( rif_dock::rosetta_min_allbb , "", false ); NEW_OPT( rif_dock::rosetta_min_fix_target, "", false ); NEW_OPT( rif_dock::rosetta_score_cut , "", -10.0 ); NEW_OPT( rif_dock::rosetta_hard_min , "", false ); NEW_OPT( rif_dock::rosetta_score_total , "", false ); NEW_OPT( rif_dock::rosetta_score_ddg_only , "", false ); NEW_OPT( rif_dock::rosetta_score_rifres_rifres_weight, "", 0.75 ); NEW_OPT( rif_dock::rosetta_score_rifres_scaffold_weight, "", 0.5 ); NEW_OPT( rif_dock::rosetta_soft_score, "", "beta_soft" ); NEW_OPT( rif_dock::rosetta_hard_score, "", "beta" ); NEW_OPT( rif_dock::rosetta_filter_before, "redundancy filter results before rosetta score", false ); NEW_OPT( rif_dock::rosetta_filter_n_per_scaffold, "use with rosetta_filter_before, num to save per scaffold", 300); NEW_OPT( rif_dock::rosetta_filter_redundancy_mag, "use with rosetta_filter_before, redundancy mag on the clustering", 0.5); NEW_OPT( rif_dock::rosetta_filter_even_if_no_score, "Do the filtering for rosetta score and min even if you don't actually score/min", false ); NEW_OPT( rif_dock::rosetta_debug_dump_scores, "dump lists of scores around the rosetta score and min", false); NEW_OPT( rif_dock::rosetta_score_select_random, "Select random positions to score rather than best", false); NEW_OPT( rif_dock::extra_rotamers, "", true ); NEW_OPT( rif_dock::extra_rif_rotamers, "", true ); NEW_OPT( rif_dock::always_available_rotamers_level, "", 0 ); NEW_OPT( rif_dock::packing_use_rif_rotamers, "", true ); NEW_OPT( rif_dock::nfold_symmetry, "", 1 ); NEW_OPT( rif_dock::symmetry_axis, "", utility::vector1<double>() ); NEW_OPT( rif_dock::user_rotamer_bonus_constant, "", 0 ); NEW_OPT( rif_dock::user_rotamer_bonus_per_chi, "", 0 ); NEW_OPT( rif_dock::resl0, "", 16 ); NEW_OPT( rif_dock::dump_x_frames_per_resl, "Use this to make a movie", 0 ); NEW_OPT( rif_dock::dump_only_best_frames, "Only dump the best frames for the movie", false ); NEW_OPT( rif_dock::dump_only_best_stride, "When doing dump_only_best_frames, dump every Xth element of the best", 1 ); NEW_OPT( rif_dock::dump_prefix, "Convince Brian to make this autocreate the folder", "hsearch" ); NEW_OPT( rif_dock::scaff_search_mode, "Which scaffold mode and HSearch do you want? Options: default, morph_dive_pop, nineA_baseline", "default"); NEW_OPT( rif_dock::nineA_cluster_path, "Path to cluster database for nineA_baseline.", "" ); NEW_OPT( rif_dock::nineA_baseline_range, "format cdindex:low-high (python range style)", ""); NEW_OPT( rif_dock::low_cut_site, "The low cut point for fragment insertion, this res and the previous get minimized.", 0 ); NEW_OPT( rif_dock::high_cut_site, "The high cut point for fragment insertion, this res and the next get minimized.", 0 ); NEW_OPT( rif_dock::max_insertion, "Maximum number of residues to lengthen protein by.", 0 ); NEW_OPT( rif_dock::max_deletion, "Maximum number of residues to shorten protein by.", 0 ); NEW_OPT( rif_dock::fragment_cluster_tolerance, "RMSD cluster tolerance for fragments.", 0.5 ); NEW_OPT( rif_dock::fragment_max_rmsd , "Max RMSD to starting fragment.", 10000 ); NEW_OPT( rif_dock::max_fragments, "Maximum number of fragments to find.", 10000000 ); NEW_OPT( rif_dock::morph_rules_files, "List of files for each scaffold to specify morph regions", utility::vector1<std::string>() ); NEW_OPT( rif_dock::morph_silent_file, "Silent file containing pre-morphed structures. Overrides other options", "" ); NEW_OPT( rif_dock::morph_silent_archetype, "PDB to calculate transform difference between input position and silent file", "" ); NEW_OPT( rif_dock::morph_silent_max_structures, "Cluster silent file into this many cluster centers", 1000000000 ); NEW_OPT( rif_dock::morph_silent_random_selection, "Use random picks instead of clustering to limit silent file", false ); NEW_OPT( rif_dock::morph_silent_cluster_use_frac, "Cluster and take the top clusters that make up this frac of total", 1 ); NEW_OPT( rif_dock::include_parent, "Include parent fragment in diversified scaffolds.", false ); NEW_OPT( rif_dock::use_parent_body_energies, "Don't recalculate 1-/2-body energies for fragment insertions", false ); NEW_OPT( rif_dock::dive_resl , "Dive to this depth before diversifying", 5 ); NEW_OPT( rif_dock::pop_resl , "Return to this depth after diversifying", 4 ); NEW_OPT( rif_dock::match_this_pdb, "Like tether to input position but applied at diversification time.", "" ); NEW_OPT( rif_dock::match_this_rmsd, "RMSD for match_this_pdb", 7 ); NEW_OPT( rif_dock::rot_spec_fname,"rot_spec_fname","NOT SPECIFIED"); // constrain file names NEW_OPT( rif_dock::cst_files, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::seed_with_these_pdbs, "Use these pdbs as seeding positions, use this with tether_to_input_position", utility::vector1<std::string>() ); NEW_OPT( rif_dock::seed_include_input, "Include the input scaffold as a seeding position in seed_with_these_pdbs", true ); NEW_OPT( rif_dock::seeding_pos, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::seeding_by_patchdock, "The format of seeding file can be either Rosetta Xform or raw patchdock outputs", true ); NEW_OPT( rif_dock::xform_pos, "" , "" ); NEW_OPT( rif_dock::rosetta_score_each_seeding_at_least, "", -1 ); NEW_OPT( rif_dock::cluster_score_cut, "", 0); NEW_OPT( rif_dock::keep_top_clusters_frac, "", 0.5); NEW_OPT( rif_dock::unsat_orbital_penalty, "temp", 0 ); NEW_OPT( rif_dock::neighbor_distance_cutoff, "temp", 6.0 ); NEW_OPT( rif_dock::unsat_neighbor_cutoff, "temp", 6 ); NEW_OPT( rif_dock::unsat_debug, "Dump debug info from unsat calculations", false ); NEW_OPT( rif_dock::test_hackpack, "Test the packing objective in the original position too", false ); NEW_OPT( rif_dock::unsat_helper, "Helper file for use with unsats", "" ); NEW_OPT( rif_dock::unsat_score_offset, "This gets added to the score of all designs", 0.0 ); NEW_OPT( rif_dock::unsat_require_burial, "Require at least this many polar atoms be buried", 0 ); NEW_OPT( rif_dock::report_common_unsats, "Show probability of burying every unsat", false ); NEW_OPT( rif_dock::dump_presatisfied_donors_acceptors, "Dump the presatisifed donors and acceptors", false ); NEW_OPT( rif_dock::requirements, "which rif residue should be in the final output", utility::vector1< int >()); } #endif #endif #ifndef INCLUDED_rif_dock_test_hh_3 #define INCLUDED_rif_dock_test_hh_3 struct RifDockOpt { std::vector<std::string> scaffold_fnames; std::vector<std::string> scaffold_res_fnames; std::vector<std::string> data_cache_path; std::vector<std::string> rif_files; bool VERBOSE ; double resl0 ; int64_t DIM ; int64_t DIMPOW2 ; int64_t beam_size ; float max_beam_multiplier ; bool multiply_beam_by_seeding_positions ; bool multiply_beam_by_scaffolds ; bool replace_all_with_ala_1bre ; bool lowres_sterics_cbonly ; float tether_to_input_position_cut ; bool tether_to_input_position ; float global_score_cut ; std::string target_pdb ; std::string outdir ; std::string output_tag ; std::string dokfile_fname ; bool dump_all_rif_rots ; bool dump_all_rif_rots_into_output ; bool rif_rots_as_chains ; std::string dump_rifgen_near_pdb ; float dump_rifgen_near_pdb_dist ; float dump_rifgen_near_pdb_frac ; bool dump_rifgen_text ; std::string score_this_pdb ; std::string dump_pdb_at_bin_center ; bool add_native_scaffold_rots_when_packing; bool restrict_to_native_scaffold_res ; float bonus_to_native_scaffold_res ; float hack_pack_frac ; float hsearch_scale_factor ; float search_diameter ; bool use_scaffold_bounding_grids ; bool scaffold_res_use_best_guess ; bool scaff2ala ; bool scaff2alaselonly ; bool replace_orig_scaffold_res ; int require_satisfaction ; int num_hotspots ; int require_n_rifres ; bool use_dl_mix_bb ; float target_rf_resl ; bool align_to_scaffold ; bool output_scaffold_only ; bool output_full_scaffold_only ; bool output_full_scaffold ; bool pdb_info_pikaa ; bool dump_resfile ; std::string target_res_fname ; int target_rf_oversample ; float max_rf_bounding_ratio ; std::string target_rf_cache ; std::string target_donors ; std::string target_acceptors ; bool only_load_highest_resl ; bool use_rosetta_grid_energies ; bool soft_rosetta_grid_energies ; bool downscale_atr_by_hierarchy ; float favorable_1body_multiplier ; float favorable_1body_multiplier_cutoff ; float favorable_2body_multiplier ; bool random_perturb_scaffold ; bool dont_use_scaffold_loops ; bool cache_scaffold_data ; float rf_resl ; bool hack_pack ; bool hack_pack_during_hsearch ; int rf_oversample ; int rotrf_oversample ; float rotrf_resl ; float rotrf_spread ; std::string rotrf_cache_dir ; float rotrf_scale_atr ; float pack_iter_mult ; int pack_n_iters ; float hbond_weight ; float upweight_iface ; float upweight_multi_hbond ; float min_hb_quality_for_satisfaction ; float long_hbond_fudge_distance ; float redundancy_filter_mag ; bool filter_seeding_positions_separately ; bool filter_scaffolds_separately ; int force_output_if_close_to_input_num ; float force_output_if_close_to_input ; int n_pdb_out ; bool extra_rotamers ; bool extra_rif_rotamers ; int always_available_rotamers_level ; int packing_use_rif_rotamers ; float rosetta_score_fraction ; float rosetta_score_then_min_below_thresh ; float rosetta_score_at_least ; float rosetta_score_at_most ; float rosetta_min_fraction ; int rosetta_min_at_least ; bool rosetta_min_fix_target ; bool rosetta_min_targetbb ; bool rosetta_min_scaffoldbb ; bool rosetta_min_allbb ; float rosetta_score_cut ; float rosetta_hard_min ; bool rosetta_score_total ; bool rosetta_score_ddg_only ; float rosetta_score_rifres_rifres_weight ; float rosetta_score_rifres_scaffold_weight ; bool rosetta_beta ; std::string rosetta_soft_score ; std::string rosetta_hard_score ; bool rosetta_filter_before ; int rosetta_filter_n_per_scaffold ; float rosetta_filter_redundancy_mag ; bool rosetta_filter_even_if_no_score ; bool rosetta_debug_dump_scores ; bool rosetta_score_select_random ; int nfold_symmetry ; std::vector<float> symmetry_axis ; float user_rotamer_bonus_constant ; float user_rotamer_bonus_per_chi ; int dump_x_frames_per_resl ; bool dump_only_best_frames ; int dump_only_best_stride ; std::string dump_prefix ; std::string scaff_search_mode ; std::string nineA_cluster_path ; std::string nineA_baseline_range ; int low_cut_site ; int high_cut_site ; int max_insertion ; int max_deletion ; float fragment_cluster_tolerance ; float fragment_max_rmsd ; int max_fragments ; std::vector<std::string> morph_rules_fnames ; std::string morph_silent_file ; std::string morph_silent_archetype ; int morph_silent_max_structures ; bool morph_silent_random_selection ; float morph_silent_cluster_use_frac ; bool include_parent ; bool use_parent_body_energies ; int dive_resl ; int pop_resl ; std::string match_this_pdb ; float match_this_rmsd ; std::string rot_spec_fname ; // constrain file names std::vector<std::string> cst_fnames ; std::vector<std::string> seed_with_these_pdbs ; bool seed_include_input ; std::vector<std::string> seeding_fnames ; std::string xform_fname ; float rosetta_score_each_seeding_at_least ; float cluster_score_cut ; float keep_top_clusters_frac ; bool seeding_by_patchdock ; float unsat_orbital_penalty ; float neighbor_distance_cutoff ; int unsat_neighbor_cutoff ; bool unsat_debug ; bool test_hackpack ; std::string unsat_helper ; float unsat_score_offset ; int unsat_require_burial ; bool report_common_unsats ; bool dump_presatisfied_donors_acceptors ; std::vector<int> requirements; void init_from_cli(); }; #endif #ifdef GLOBAL_VARIABLES_ARE_BAD #ifndef INCLUDED_rif_dock_test_hh_4 #define INCLUDED_rif_dock_test_hh_4 void RifDockOpt::init_from_cli() { using basic::options::option; using namespace basic::options::OptionKeys; runtime_assert( option[rif_dock::target_rif].user() ); VERBOSE = false; resl0 = option[rif_dock::resl0 ](); DIM = 6; DIMPOW2 = 1<<DIM; beam_size = int64_t( option[rif_dock::beam_size_M]() * 1000000.0 / DIMPOW2 ) * DIMPOW2; max_beam_multiplier = option[rif_dock::max_beam_multiplier ](); multiply_beam_by_seeding_positions = option[rif_dock::multiply_beam_by_seeding_positions ](); multiply_beam_by_scaffolds = option[rif_dock::multiply_beam_by_scaffolds ](); replace_all_with_ala_1bre = option[rif_dock::replace_all_with_ala_1bre ](); target_pdb = option[rif_dock::target_pdb ](); lowres_sterics_cbonly = option[rif_dock::lowres_sterics_cbonly ](); tether_to_input_position_cut = option[rif_dock::tether_to_input_position ](); tether_to_input_position = tether_to_input_position_cut > 0.0; global_score_cut = option[rif_dock::global_score_cut ](); outdir = option[rif_dock::outdir ](); output_tag = option[rif_dock::output_tag ](); dokfile_fname = outdir + "/" + option[rif_dock::dokfile ](); dump_all_rif_rots = option[rif_dock::dump_all_rif_rots ](); dump_all_rif_rots_into_output = option[rif_dock::dump_all_rif_rots_into_output ](); rif_rots_as_chains = option[rif_dock::rif_rots_as_chains ](); dump_rifgen_near_pdb = option[rif_dock::dump_rifgen_near_pdb ](); dump_rifgen_near_pdb_dist = option[rif_dock::dump_rifgen_near_pdb_dist ](); dump_rifgen_near_pdb_frac = option[rif_dock::dump_rifgen_near_pdb_frac ](); dump_rifgen_text = option[rif_dock::dump_rifgen_text ](); score_this_pdb = option[rif_dock::score_this_pdb ](); dump_pdb_at_bin_center = option[rif_dock::dump_pdb_at_bin_center ](); add_native_scaffold_rots_when_packing = option[rif_dock::add_native_scaffold_rots_when_packing ](); restrict_to_native_scaffold_res = option[rif_dock::restrict_to_native_scaffold_res ](); bonus_to_native_scaffold_res = option[rif_dock::bonus_to_native_scaffold_res ](); hack_pack_frac = option[rif_dock::hack_pack_frac ](); hsearch_scale_factor = option[rif_dock::hsearch_scale_factor ](); search_diameter = option[rif_dock::search_diameter ](); use_scaffold_bounding_grids = option[rif_dock::use_scaffold_bounding_grids ](); scaffold_res_use_best_guess = option[rif_dock::scaffold_res_use_best_guess ](); scaff2ala = option[rif_dock::scaffold_to_ala ](); scaff2alaselonly = option[rif_dock::scaffold_to_ala_selonly ](); replace_orig_scaffold_res = option[rif_dock::replace_orig_scaffold_res ](); require_satisfaction = option[rif_dock::require_satisfaction ](); num_hotspots = option[rif_dock::num_hotspots ](); require_n_rifres = option[rif_dock::require_n_rifres ](); use_dl_mix_bb = option[rif_dock::use_dl_mix_bb ](); target_rf_resl = option[rif_dock::target_rf_resl ](); align_to_scaffold = option[rif_dock::align_output_to_scaffold ](); output_scaffold_only = option[rif_dock::output_scaffold_only ](); output_full_scaffold_only = option[rif_dock::output_full_scaffold_only ](); output_full_scaffold = option[rif_dock::output_full_scaffold ](); pdb_info_pikaa = option[rif_dock::pdb_info_pikaa ](); dump_resfile = option[rif_dock::dump_resfile ](); target_res_fname = option[rif_dock::target_res ](); target_rf_oversample = option[rif_dock::target_rf_oversample ](); max_rf_bounding_ratio = option[rif_dock::max_rf_bounding_ratio ](); target_rf_cache = option[rif_dock::target_rf_cache ](); target_donors = option[rif_dock::target_donors ](); target_acceptors = option[rif_dock::target_acceptors ](); only_load_highest_resl = option[rif_dock::only_load_highest_resl ](); use_rosetta_grid_energies = option[rif_dock::use_rosetta_grid_energies ](); soft_rosetta_grid_energies = option[rif_dock::soft_rosetta_grid_energies ](); downscale_atr_by_hierarchy = option[rif_dock::downscale_atr_by_hierarchy ](); favorable_1body_multiplier = option[rif_dock::favorable_1body_multiplier ](); favorable_1body_multiplier_cutoff = option[rif_dock::favorable_1body_multiplier_cutoff ](); favorable_2body_multiplier = option[rif_dock::favorable_2body_multiplier ](); random_perturb_scaffold = option[rif_dock::random_perturb_scaffold ](); dont_use_scaffold_loops = option[rif_dock::dont_use_scaffold_loops ](); cache_scaffold_data = option[rif_dock::cache_scaffold_data ](); rf_resl = option[rif_dock::rf_resl ](); hack_pack = option[rif_dock::hack_pack ](); hack_pack_during_hsearch = option[rif_dock::hack_pack_during_hsearch ](); rf_oversample = option[rif_dock::rf_oversample ](); redundancy_filter_mag = option[rif_dock::redundancy_filter_mag ](); filter_seeding_positions_separately = option[rif_dock::filter_seeding_positions_separately ](); filter_scaffolds_separately = option[rif_dock::filter_scaffolds_separately ](); rotrf_oversample = option[rif_dock::rotrf_oversample ](); rotrf_resl = option[rif_dock::rotrf_resl ](); rotrf_spread = option[rif_dock::rotrf_spread ](); rotrf_cache_dir = option[rif_dock::rotrf_cache_dir ](); rotrf_scale_atr = option[rif_dock::rotrf_scale_atr ](); pack_iter_mult = option[rif_dock::pack_iter_mult ](); pack_n_iters = option[rif_dock::pack_n_iters ](); hbond_weight = option[rif_dock::hbond_weight ](); upweight_iface = option[rif_dock::upweight_iface ](); upweight_multi_hbond = option[rif_dock::upweight_multi_hbond ](); min_hb_quality_for_satisfaction = option[rif_dock::min_hb_quality_for_satisfaction ](); long_hbond_fudge_distance = option[rif_dock::long_hbond_fudge_distance ](); redundancy_filter_mag = option[rif_dock::redundancy_filter_mag ](); force_output_if_close_to_input_num = option[rif_dock::force_output_if_close_to_input_num ](); force_output_if_close_to_input = option[rif_dock::force_output_if_close_to_input ](); n_pdb_out = option[rif_dock::n_pdb_out ](); extra_rotamers = option[rif_dock::extra_rotamers ](); extra_rif_rotamers = option[rif_dock::extra_rif_rotamers ](); always_available_rotamers_level = option[rif_dock::always_available_rotamers_level ](); packing_use_rif_rotamers = option[rif_dock::packing_use_rif_rotamers ](); rosetta_score_fraction = option[rif_dock::rosetta_score_fraction ](); rosetta_score_then_min_below_thresh = option[rif_dock::rosetta_score_then_min_below_thresh ](); rosetta_score_at_least = option[rif_dock::rosetta_score_at_least ](); rosetta_score_at_most = option[rif_dock::rosetta_score_at_most ](); rosetta_min_fraction = option[rif_dock::rosetta_min_fraction ](); rosetta_min_at_least = option[rif_dock::rosetta_min_at_least ](); rosetta_min_fix_target = option[rif_dock::rosetta_min_fix_target ](); rosetta_min_targetbb = option[rif_dock::rosetta_min_targetbb ](); rosetta_min_scaffoldbb = option[rif_dock::rosetta_min_scaffoldbb ](); rosetta_min_allbb = option[rif_dock::rosetta_min_allbb ](); rosetta_score_cut = option[rif_dock::rosetta_score_cut ](); rosetta_hard_min = option[rif_dock::rosetta_hard_min ](); rosetta_score_total = option[rif_dock::rosetta_score_total ](); rosetta_score_ddg_only = option[rif_dock::rosetta_score_ddg_only ](); rosetta_score_rifres_rifres_weight = option[rif_dock::rosetta_score_rifres_rifres_weight ](); rosetta_score_rifres_scaffold_weight = option[rif_dock::rosetta_score_rifres_scaffold_weight ](); rosetta_soft_score = option[rif_dock::rosetta_soft_score ](); rosetta_hard_score = option[rif_dock::rosetta_hard_score ](); rosetta_beta = option[corrections::beta ](); rosetta_filter_before = option[rif_dock::rosetta_filter_before ](); rosetta_filter_n_per_scaffold = option[rif_dock::rosetta_filter_n_per_scaffold ](); rosetta_filter_redundancy_mag = option[rif_dock::rosetta_filter_redundancy_mag ](); rosetta_filter_even_if_no_score = option[rif_dock::rosetta_filter_even_if_no_score ](); user_rotamer_bonus_constant = option[rif_dock::user_rotamer_bonus_constant ](); user_rotamer_bonus_per_chi = option[rif_dock::user_rotamer_bonus_per_chi ](); rosetta_debug_dump_scores = option[rif_dock::rosetta_debug_dump_scores ](); rosetta_score_select_random = option[rif_dock::rosetta_score_select_random ](); dump_x_frames_per_resl = option[rif_dock::dump_x_frames_per_resl ](); dump_only_best_frames = option[rif_dock::dump_only_best_frames ](); dump_only_best_stride = option[rif_dock::dump_only_best_stride ](); dump_prefix = option[rif_dock::dump_prefix ](); scaff_search_mode = option[rif_dock::scaff_search_mode ](); nineA_cluster_path = option[rif_dock::nineA_cluster_path ](); nineA_baseline_range = option[rif_dock::nineA_baseline_range ](); low_cut_site = option[rif_dock::low_cut_site ](); high_cut_site = option[rif_dock::high_cut_site ](); max_insertion = option[rif_dock::max_insertion ](); max_deletion = option[rif_dock::max_deletion ](); fragment_cluster_tolerance = option[rif_dock::fragment_cluster_tolerance ](); fragment_max_rmsd = option[rif_dock::fragment_max_rmsd ](); max_fragments = option[rif_dock::max_fragments ](); morph_silent_file = option[rif_dock::morph_silent_file ](); morph_silent_archetype = option[rif_dock::morph_silent_archetype ](); morph_silent_max_structures = option[rif_dock::morph_silent_max_structures ](); morph_silent_random_selection = option[rif_dock::morph_silent_random_selection ](); morph_silent_cluster_use_frac = option[rif_dock::morph_silent_cluster_use_frac ](); include_parent = option[rif_dock::include_parent ](); use_parent_body_energies = option[rif_dock::use_parent_body_energies ](); dive_resl = option[rif_dock::dive_resl ](); pop_resl = option[rif_dock::pop_resl ](); match_this_pdb = option[rif_dock::match_this_pdb ](); match_this_rmsd = option[rif_dock::match_this_rmsd ](); rot_spec_fname = option[rif_dock::rot_spec_fname ](); seed_include_input = option[rif_dock::seed_include_input ](); seeding_by_patchdock = option[rif_dock::seeding_by_patchdock ](); xform_fname = option[rif_dock::xform_pos ](); rosetta_score_each_seeding_at_least = option[rif_dock::rosetta_score_each_seeding_at_least ](); cluster_score_cut = option[rif_dock::cluster_score_cut ](); keep_top_clusters_frac = option[rif_dock::keep_top_clusters_frac ](); unsat_orbital_penalty = option[rif_dock::unsat_orbital_penalty ](); neighbor_distance_cutoff = option[rif_dock::neighbor_distance_cutoff ](); unsat_neighbor_cutoff = option[rif_dock::unsat_neighbor_cutoff ](); unsat_debug = option[rif_dock::unsat_debug ](); test_hackpack = option[rif_dock::test_hackpack ](); unsat_helper = option[rif_dock::unsat_helper ](); unsat_score_offset = option[rif_dock::unsat_score_offset ](); unsat_require_burial = option[rif_dock::unsat_require_burial ](); report_common_unsats = option[rif_dock::report_common_unsats ](); dump_presatisfied_donors_acceptors = option[rif_dock::dump_presatisfied_donors_acceptors ](); for( std::string s : option[rif_dock::scaffolds ]() ) scaffold_fnames.push_back(s); for( std::string s : option[rif_dock::scaffold_res ]() ) scaffold_res_fnames.push_back(s); for( std::string s : option[rif_dock::data_cache_dir]() ) data_cache_path.push_back(s); for( std::string fn : option[rif_dock::target_bounding_xmaps]() ) rif_files.push_back(fn); rif_files.push_back( option[rif_dock::target_rif]() ); if( scaff2ala && scaff2alaselonly && option[rif_dock::scaffold_to_ala_selonly].user() ){ std::cout << "WARNING: -scaffold_to_ala overrides -scaffold_to_ala_selonly!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; } if( rosetta_score_total && rosetta_score_ddg_only ){ std::cout << "WARNING: rosetta_score_total overrives rosetta_score_ddg_only" << std::endl; rosetta_score_ddg_only = false; } runtime_assert_msg( min_hb_quality_for_satisfaction < 0 && min_hb_quality_for_satisfaction > -1, "-min_hb_quality_for_satisfaction must be between -1 and 0"); nfold_symmetry = option[rif_dock::nfold_symmetry](); symmetry_axis.clear(); if( option[rif_dock::symmetry_axis]().size() == 3 ){ symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[1] ); symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[2] ); symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[3] ); } else if( option[rif_dock::symmetry_axis]().size() == 0 ){ symmetry_axis.push_back(0); symmetry_axis.push_back(0); symmetry_axis.push_back(1); } else { std::cout << "bad rif_dock::symmetry_axis option" << std::endl; std::exit(-1); } // Brian if (option[rif_dock::use_scaffold_bounding_grids]()) { std::cout << "ERROR: use_scaffold_bounding_grids no longer supported. Email bcov@uw.edu" << std::endl; std::exit(-1); } if (option[rif_dock::nfold_symmetry]() > 1) { std::cout << "ERROR: nfold_symmetry not currently supported. Email bcov@uw.edu" << std::endl; std::exit(-1); } if ( scaff_search_mode == "nineA_baseline" ) { if ( scaffold_fnames.size() > 0 ) { std::cout << "ERROR: can't use -scaffolds with nineA_baseline." << std::endl; std::exit(-1); } std::vector<uint64_t> cdindex_then_clusts = devel::scheme::parse_nineA_baseline_range( nineA_baseline_range ); uint64_t num_scaffolds = cdindex_then_clusts.size() - 1; runtime_assert( num_scaffolds > 0 ); scaffold_fnames.resize(num_scaffolds); } for( std::string s : option[rif_dock::morph_rules_files ]() ) morph_rules_fnames.push_back(s); // constrain file names for( std::string s : option[rif_dock::cst_files ]() ) cst_fnames.push_back(s); for( std::string s : option[rif_dock::seed_with_these_pdbs ]() ) seed_with_these_pdbs.push_back(s); for( std::string s : option[rif_dock::seeding_pos ]() ) seeding_fnames.push_back(s); for( int req : option[rif_dock::requirements]() ) requirements.push_back(req); } #endif #endif
58.648796
158
0.612406
willsheffler
f0cb289aca4dd19d69e868efc9e4137c98d0b056
1,771
cpp
C++
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
380
2018-02-23T02:58:35.000Z
2022-03-21T06:34:33.000Z
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
36
2018-04-11T03:49:42.000Z
2021-01-21T01:25:47.000Z
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
94
2018-02-25T05:23:51.000Z
2022-02-11T02:00:47.000Z
#include <cstdio> #include <cstdlib> #include <image.h> #include <misc.h> #include <pnmfile.h> #include "mex.h" #include "segment-image.h" void mexFunction(int nlhs,mxArray* plhs[],int nrhs,const mxArray* prhs[]) { // check arguments if (nrhs != 5) { mexPrintf("Usage: [seg] = segmentGraphMex_edge(maxID, numEdge, edges, threshold, minSize);\n"); return; } // convert edges memory from matlab to c++ int maxID = (int)mxGetScalar(prhs[0]); int numEdge = (int)mxGetScalar(prhs[1]); double* edgeMat = (double*)mxGetData(prhs[2]); double c = mxGetScalar(prhs[3]); int min_size = (int)mxGetScalar(prhs[4]); printf("maxID: %d, numEdge: %d, c: %f, min_size: %d\n", maxID, numEdge, c, min_size); edge *edges = new edge[numEdge]; for( int i = 0; i<numEdge; i++) { edges[i].a = edgeMat[i*3+0]; edges[i].b = edgeMat[i*3+1]; edges[i].w = edgeMat[i*3+2]; } printf("a: %d, b: %d, w: %f\n", edges[0].a, edges[0].b, edges[0].w); printf("Loading finished!\n"); universe *u = segment_graph( maxID, numEdge, edges, c); printf("get out of segment_graph\n"); // post process for (int i = 0; i < numEdge; i++) { int a = u->find(edges[i].a); int b = u->find(edges[i].b); if ((a != b) && ((u->size(a) < min_size) || (u->size(b) < min_size))) u->join(a, b); } printf("finish post process\n"); // pass result to matlab plhs[0] = mxCreateNumericMatrix((mwSize)maxID, 1, mxDOUBLE_CLASS, mxREAL); double* output = (double *)mxGetData(plhs[0]); for (int i = 0; i<maxID; i++) { output[i] = (double)(u->find(i+1)); } printf("packed up output\n"); delete[] edges; printf("delete edges\n"); //delete u; printf("memory released\n"); }
29.516667
98
0.585545
imamik
f0cd16803c3887c2e9fc46e5b45ea987f4b0c6b2
8,806
cpp
C++
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
3
2018-03-24T12:28:05.000Z
2021-07-29T02:00:16.000Z
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
null
null
null
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
1
2018-05-13T12:59:01.000Z
2018-05-13T12:59:01.000Z
/*///////////////////////////////////////////////////////////////////////////// /// @summary Implements the entry point of the application. This handles the /// setup of our third party libraries and the creation of our main window and /// rendering context, along with implementing the game loop. /// @author Russell Klenk (contact@russellklenk.com) ///////////////////////////////////////////////////////////////////////////80*/ /*//////////////// // Includes // ////////////////*/ #include <stdio.h> #include <stdlib.h> #include "math.hpp" #include "input.hpp" #include "display.hpp" #include "entity.hpp" #include "player.hpp" #include "ll_sprite.hpp" #include "ll_shader.hpp" /*///////////////// // Constants // /////////////////*/ #define GW_WINDOW_WIDTH 800 #define GW_WINDOW_HEIGHT 600 #define GW_WINDOW_TITLE "Geometry Wars" #define GW_MIN_TIMESTEP 0.000001 #define GW_MAX_TIMESTEP 0.25 #define GW_SIM_TIMESTEP 1.0 / 120.0 /*/////////////// // Globals // ///////////////*/ static EntityManager *gEntityManager = NULL; static DisplayManager *gDisplayManager = NULL; static InputManager *gInputManager = NULL; /*/////////////////////// // Local Functions // ///////////////////////*/ /// @summary Callback to handle a GLFW error. Prints the error information to stderr. /// @param error_code The internal GLFW error code. /// @param error_desc A textual description of the error. static void glfw_error(int error_code, char const *error_desc) { fprintf(stderr, "ERROR: (GLFW code 0x%08X): %s\n", error_code, error_desc); } #if GL_DEBUG_ENABLE /// @summary Callback to handle output from the GL_ARB_debug_output extension, /// which is of course not supported on OSX as of 10.9. /// @param source /// @param type /// @param id /// @param severity /// @param length /// @param message /// @param context static void gl_arb_debug( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, char const *message, void *context) { UNUSED_ARG(source); UNUSED_ARG(type); UNUSED_ARG(id); UNUSED_ARG(severity); UNUSED_ARG(length); UNUSED_ARG(context); fprintf(stdout, "ARB_debug: %s\n", message); } #endif /// @summary Executes all of the logic associated with game user input. This /// is also where we would run user interface logic. Runs once per application tick. /// @param currentTime The current absolute time, in seconds. This represents /// the time at which the current tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. static void input(double currentTime, double elapsedTime) { gInputManager->Update(currentTime, elapsedTime); gEntityManager->Input(currentTime, elapsedTime, gInputManager); } /// @summary Executes a single game simulation tick to move all game entities. /// Runs zero or more times per application tick at a fixed timestep. /// @param currentTime The current absolute simulation time, in seconds. This /// represents the time at which the current simulation tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. static void simulate(double currentTime, double elapsedTime) { gEntityManager->Update(currentTime, elapsedTime); } /// @summary Submits a single frame to the GPU for rendering. Runs once per /// application tick at a variable timestep. /// @param currentTime The current absolute time, in seconds. This represents /// the time at which the current tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. /// @param t A value in [0, 1] indicating how far into the current simulation /// step we are at the time the frame is generated. /// @param width The width of the default framebuffer, in pixels. /// @param height The height of the default framebuffer, in pixels. static void render(double currentTime, double elapsedTime, double t, int width, int height) { UNUSED_ARG(currentTime); UNUSED_ARG(elapsedTime); UNUSED_ARG(t); DisplayManager *dm = gDisplayManager; SpriteBatch *batch = dm->GetBatch(); SpriteFont *font = dm->GetFont(); float rgba[]= {1.0f, 0.0f, 0.0f, 1.0f}; dm->SetViewport(width, height); dm->Clear(0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0); dm->BeginFrame(); batch->SetBlendModeAlpha(); font->Draw("Hello, world!", 0, 0, 1, rgba, 5.0f, 5.0f, batch); gEntityManager->Draw(currentTime, elapsedTime, dm); dm->EndFrame(); } /*/////////////////////// // Public Functions // ///////////////////////*/ int main(int argc, char **argv) { GLFWwindow *window = NULL; UNUSED_ARG(argc); UNUSED_ARG(argv); // initialize GLFW, our platform abstraction library. glfwSetErrorCallback(glfw_error); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_VISIBLE, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #if GL_DEBUG_ENABLE glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif // create the main application window and OpenGL context. window = glfwCreateWindow(GW_WINDOW_WIDTH, GW_WINDOW_HEIGHT, GW_WINDOW_TITLE, NULL, NULL); if (window == NULL) { fprintf(stderr, "ERROR: Cannot create primary GLFW window.\n"); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); // now that we have an OpenGL context, load extensions provided by the platform. // note that glewExperimental is defined by the GLEW library and is required on // OSX or the glGenVertexArrays() call will cause a fault. glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { fprintf(stderr, "ERROR: Cannot initialize GLEW for the primary context.\n"); glfwTerminate(); exit(EXIT_FAILURE); } // clear any OpenGL error status and configure debug output. glGetError(); #if GL_DEBUG_ENABLE if (GLEW_ARB_debug_output) { glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageCallbackARB(gl_arb_debug, NULL); } #endif // initialize global managers: gDisplayManager = new DisplayManager(); gDisplayManager->Init(window); gInputManager = new InputManager(); gInputManager->Init(window); Player *player = new Player(0); player->Init(gDisplayManager); gEntityManager = new EntityManager(); gEntityManager->AddEntity(player); // game loop setup and run: const double Step = GW_SIM_TIMESTEP; double previousTime = glfwGetTime(); double currentTime = previousTime; double elapsedTime = 0.0; double accumulator = 0.0; double simTime = 0.0; double t = 0.0; int width = 0; int height = 0; while (!glfwWindowShouldClose(window)) { // retrieve the current framebuffer size, which // may be different from the current window size. glfwGetFramebufferSize(window, &width, &height); // update the main game clock. previousTime = currentTime; currentTime = glfwGetTime(); elapsedTime = currentTime - previousTime; if (elapsedTime > GW_MAX_TIMESTEP) { elapsedTime = GW_MAX_TIMESTEP; } if (elapsedTime < GW_MIN_TIMESTEP) { elapsedTime = GW_MIN_TIMESTEP; } accumulator += elapsedTime; // process user input at the start of the frame. input(currentTime, elapsedTime); // execute the simulation zero or more times per-frame. // the simulation runs at a fixed timestep. while (accumulator >= Step) { // @todo: swap game state buffers here. // pass the current game state to simulate. simulate(simTime, Step); accumulator -= Step; simTime += Step; } // interpolate display state. t = accumulator / Step; // state = currentState * t + previousState * (1.0 - t); render(currentTime, elapsedTime, t, width, height); // now present the current frame and process OS events. glfwSwapBuffers(window); glfwPollEvents(); } // teardown global managers. delete gEntityManager; delete gDisplayManager; delete gInputManager; // perform any top-level cleanup. glfwTerminate(); exit(EXIT_SUCCESS); }
33.356061
94
0.650693
russellklenk
f0da524a8ee5f41b5b255973c45add652ae74843
473
cc
C++
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
2
2015-02-14T04:24:07.000Z
2015-02-28T11:23:48.000Z
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
null
null
null
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
null
null
null
#include "core/logging_event.h" #include <errno.h> #include "util/environment.h" namespace logbox { LoggingEvent::LoggingEvent( LogSeverity severity, const char* file, int line, const char* function) : severity_(severity), file_fullname_(file), file_basename_(Environment::GetBasename(file)), line_no_(line), function_(function), preserved_errno_(errno), timestamp_(Environment::Now()) { } } // namespace logbox
20.565217
53
0.676533
pragkent
f0da74da343d1e48921fbefea6fe4b456427bae7
1,197
cpp
C++
Code/System/Core/Time/Time.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
[ "MIT" ]
419
2022-01-27T19:37:43.000Z
2022-03-31T06:14:22.000Z
Code/System/Core/Time/Time.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-01-28T20:35:33.000Z
2022-03-13T17:42:52.000Z
Code/System/Core/Time/Time.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
20
2022-01-27T20:41:02.000Z
2022-03-26T16:16:57.000Z
#include "Time.h" #include <chrono> //------------------------------------------------------------------------- namespace KRG { KRG::Nanoseconds EngineClock::CurrentTime = 0; //------------------------------------------------------------------------- Nanoseconds::operator Microseconds() const { auto const duration = std::chrono::duration<uint64, std::chrono::steady_clock::period>( m_value ); uint64 const numMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>( duration ).count(); return float( numMicroseconds ); } //------------------------------------------------------------------------- Nanoseconds PlatformClock::GetTime() { auto const time = std::chrono::high_resolution_clock::now(); uint64 const numNanosecondsSinceEpoch = time.time_since_epoch().count(); return Nanoseconds( numNanosecondsSinceEpoch ); } //------------------------------------------------------------------------- void EngineClock::Update( Milliseconds deltaTime ) { KRG_ASSERT( deltaTime >= 0 ); CurrentTime += deltaTime.ToNanoseconds(); } }
34.2
114
0.472013
JuanluMorales
f0db14785a36f33ca7d2e246eff7183b9b3bb82d
215
cpp
C++
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "types.h" #include "AppThread.h" /* * --INFO-- * Address: 80424E18 * Size: 00003C */ AppThread::AppThread(u32 stackSize, int msgCount, int priority) : JKRThread(stackSize, msgCount, priority) { }
15.357143
63
0.674419
projectPiki
f0ddf37d5a08322fefec7ff12c8b80b255fc02f5
370
cpp
C++
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int countPrimeSetBits(int L, int R) { const unordered_set<int> PRIMES = {2,3,5,7,11,13,17,19}; int answer = 0; for(int num = L; num <= R; ++num){ int setBitsCnt = __builtin_popcount(num); answer += (PRIMES.find(setBitsCnt) != PRIMES.end()); } return answer; } };
30.833333
65
0.524324
Tudor67
f0e175d7937cf22938a778b3d6a68b2e534d5321
44,217
hpp
C++
src/libraries/surfMesh/MeshedSurface/MeshedSurface.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/surfMesh/MeshedSurface/MeshedSurface.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/surfMesh/MeshedSurface/MeshedSurface.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2015 OpenFOAM Foundation Copyright (C) 2015 Applied CCM ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::MeshedSurface Description A surface geometry mesh with zone information, not to be confused with the similarly named surfaceMesh, which actually refers to the cell faces of a volume mesh. A MeshedSurface can have zero or more surface zones (roughly equivalent to faceZones for a polyMesh). If surface zones are defined, they must be contiguous and cover all of the faces. The MeshedSurface is intended for surfaces from a variety of sources. - A set of points and faces without any surface zone information. - A set of points and faces with randomly ordered zone information. This could arise, for example, from reading external file formats such as STL, etc. \*---------------------------------------------------------------------------*/ #ifndef MeshedSurface_H #define MeshedSurface_H #include "PrimitivePatch_.hpp" #include "PatchTools.hpp" #include "pointField.hpp" #include "face.hpp" #include "triFace.hpp" #include "surfZoneList.hpp" #include "surfaceFormatsCore.hpp" #include "runTimeSelectionTables.hpp" #include "memberFunctionSelectionTables.hpp" #include "HashSet.hpp" #include "boundBox.hpp" #include "Ostream.hpp" #include "UnsortedMeshedSurface.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { // Forward declaration of friend functions and operators class Time; class surfMesh; class polyBoundaryMesh; template<class Face> class MeshedSurface; template<class Face> class MeshedSurfaceProxy; template<class Face> class UnsortedMeshedSurface; /*---------------------------------------------------------------------------*\ Class MeshedSurface Declaration \*---------------------------------------------------------------------------*/ template<class Face> class MeshedSurface : public PrimitivePatch<Face, ::CML::List, pointField, point>, public fileFormats::surfaceFormatsCore { // friends - despite different face representationsx template<class Face2> friend class MeshedSurface; template<class Face2> friend class UnsortedMeshedSurface; friend class surfMesh; private: // Private typedefs for convenience typedef PrimitivePatch < Face, ::CML::List, pointField, point > ParentType; typedef UnsortedMeshedSurface<Face> FriendType; typedef MeshedSurfaceProxy<Face> ProxyType; // Private Member Data //- Zone information // (face ordering nFaces/startFace only used during reading/writing) List<surfZone> zones_; protected: // Protected Member functions //- Transfer points/zones and transcribe face -> triFace void transcribe(MeshedSurface<face>&); //- basic sanity check on zones void checkZones(); //- Non-const access to global points pointField& storedPoints() { return const_cast<pointField&>(ParentType::points()); } //- Non-const access to the faces List<Face>& storedFaces() { return static_cast<List<Face> &>(*this); } //- Non-const access to the zones surfZoneList& storedZones() { return zones_; } //- sort faces by zones and store sorted faces void sortFacesAndStore ( const Xfer<List<Face> >& unsortedFaces, const Xfer<List<label> >& zoneIds, const bool sorted ); //- Set new zones from faceMap virtual void remapFaces(const labelUList& faceMap); public: // Public typedefs //- Face type used typedef Face FaceType; //- Runtime type information ClassName("MeshedSurface"); // Static //- Face storage only handles triangulated faces inline static bool isTri(); //- Can we read this file format? static bool canRead(const fileName&, const bool verbose=false); //- Can we read this file format? static bool canReadType(const word& ext, const bool verbose=false); //- Can we write this file format? static bool canWriteType(const word& ext, const bool verbose=false); static wordHashSet readTypes(); static wordHashSet writeTypes(); // Constructors //- Construct null MeshedSurface(); //- Construct by transferring components (points, faces, zones). MeshedSurface ( const Xfer<pointField>&, const Xfer<List<Face> >&, const Xfer<surfZoneList>& ); //- Construct by transferring components (points, faces). // Use zone information if available MeshedSurface ( const Xfer<pointField>&, const Xfer<List<Face> >&, const labelUList& zoneSizes = labelUList(), const UList<word>& zoneNames = UList<word>() ); //- Construct as copy MeshedSurface(const MeshedSurface&); //- Construct from a UnsortedMeshedSurface MeshedSurface(const UnsortedMeshedSurface<Face>&); //- Construct from a boundary mesh with local points/faces MeshedSurface ( const polyBoundaryMesh&, const bool globalPoints=false ); //- Construct from a surfMesh MeshedSurface(const surfMesh&); //- Construct by transferring the contents from a UnsortedMeshedSurface MeshedSurface(const Xfer<UnsortedMeshedSurface<Face> >&); //- Construct by transferring the contents from a MeshedSurface MeshedSurface(const Xfer<MeshedSurface<Face> >&); //- Construct from file name (uses extension to determine type) MeshedSurface(const fileName&); //- Construct from file name (uses extension to determine type) MeshedSurface(const fileName&, const word& ext); //- Construct from database MeshedSurface(const Time&, const word& surfName=""); // Declare run-time constructor selection table declareRunTimeSelectionTable ( autoPtr, MeshedSurface, fileExtension, ( const fileName& name ), (name) ); // Selectors //- Select constructed from filename (explicit extension) static autoPtr<MeshedSurface> New ( const fileName&, const word& ext ); //- Select constructed from filename (implicit extension) static autoPtr<MeshedSurface> New(const fileName&); //- Destructor virtual ~MeshedSurface(); // Member Function Selectors declareMemberFunctionSelectionTable ( void, UnsortedMeshedSurface, write, fileExtension, ( const fileName& name, const MeshedSurface<Face>& surf ), (name, surf) ); //- Write to file static void write(const fileName&, const MeshedSurface<Face>&); // Member Functions // Access //- The surface size is the number of faces label size() const { return ParentType::size(); } //- Return const access to the faces inline const List<Face>& faces() const { return static_cast<const List<Face> &>(*this); } //- Const access to the surface zones. // If zones are defined, they must be contiguous and cover the // entire surface const List<surfZone>& surfZones() const { return zones_; } //- Add surface zones virtual void addZones ( const UList<surfZone>&, const bool cullEmpty=false ); //- Add surface zones virtual void addZones ( const labelUList& sizes, const UList<word>& names, const bool cullEmpty=false ); //- Add surface zones virtual void addZones ( const labelUList& sizes, const bool cullEmpty=false ); //- Remove surface zones virtual void removeZones(); // Edit //- Clear all storage virtual void clear(); //- Move points virtual void movePoints(const pointField&); //- Scale points. A non-positive factor is ignored virtual void scalePoints(const scalar); //- Reset primitive data (points, faces and zones) // Note, optimized to avoid overwriting data (with Xfer::null) virtual void reset ( const Xfer<pointField >& points, const Xfer<List<Face> >& faces, const Xfer<surfZoneList>& zones ); //- Reset primitive data (points, faces and zones) // Note, optimized to avoid overwriting data (with Xfer::null) virtual void reset ( const Xfer<List<point> >& points, const Xfer<List<Face> >& faces, const Xfer<surfZoneList >& zones ); //- Remove invalid faces virtual void cleanup(const bool verbose); virtual bool stitchFaces ( const scalar tol=SMALL, const bool verbose=false ); virtual bool checkFaces ( const bool verbose=false ); //- Triangulate in-place, returning the number of triangles added virtual label triangulate(); //- Triangulate in-place, returning the number of triangles added // and setting a map of original face Ids. // The faceMap is zero-sized when no triangulation was done. virtual label triangulate(List<label>& faceMap); //- Return new surface. // Returns return pointMap, faceMap from subsetMeshMap MeshedSurface subsetMesh ( const labelHashSet& include, labelList& pointMap, labelList& faceMap ) const; //- Return new surface. MeshedSurface subsetMesh ( const labelHashSet& include ) const; //- Transfer the contents of the argument and annul the argument void transfer(MeshedSurface<Face>&); //- Transfer the contents of the argument and annul the argument void transfer(UnsortedMeshedSurface<Face>&); //- Transfer contents to the Xfer container Xfer<MeshedSurface<Face> > xfer(); // Read //- Read from file. Chooses reader based on explicit extension bool read(const fileName&, const word& ext); //- Read from file. Chooses reader based on detected extension virtual bool read(const fileName&); // Write void writeStats(Ostream& os) const; //- Generic write routine. Chooses writer based on extension. virtual void write(const fileName& name) const { write(name, *this); } //- Write to database void write(const Time&, const word& surfName="") const; // Member operators void operator=(const MeshedSurface<Face>&); //- Conversion operator to MeshedSurfaceProxy operator MeshedSurfaceProxy<Face>() const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // //- Specialization for holding triangulated information template<> inline bool MeshedSurface<triFace>::isTri() { return true; } //- Specialization for holding triangulated information template<> inline label MeshedSurface<triFace>::triangulate() { return 0; } //- Specialization for holding triangulated information template<> inline label MeshedSurface<triFace>::triangulate(List<label>& faceMap) { if (notNull(faceMap)) { faceMap.clear(); } return 0; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML #include "UnsortedMeshedSurface.hpp" #include "MeshedSurfaceProxy.hpp" #include "mergePoints.hpp" #include "Time.hpp" #include "ListOps.hpp" #include "polyBoundaryMesh.hpp" #include "polyMesh.hpp" #include "surfMesh.hpp" #include "primitivePatch.hpp" #include "addToRunTimeSelectionTable.hpp" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // template<class Face> inline bool CML::MeshedSurface<Face>::isTri() { return false; } template<class Face> CML::wordHashSet CML::MeshedSurface<Face>::readTypes() { return wordHashSet(*fileExtensionConstructorTablePtr_); } template<class Face> CML::wordHashSet CML::MeshedSurface<Face>::writeTypes() { return wordHashSet(*writefileExtensionMemberFunctionTablePtr_); } // * * * * * * * * * * * * * Static Member Functions * * * * * * * * * * * * // template<class Face> bool CML::MeshedSurface<Face>::canReadType ( const word& ext, const bool verbose ) { return fileFormats::surfaceFormatsCore::checkSupport ( readTypes() | FriendType::readTypes(), ext, verbose, "reading" ); } template<class Face> bool CML::MeshedSurface<Face>::canWriteType ( const word& ext, const bool verbose ) { return fileFormats::surfaceFormatsCore::checkSupport ( writeTypes() | ProxyType::writeTypes(), ext, verbose, "writing" ); } template<class Face> bool CML::MeshedSurface<Face>::canRead ( const fileName& name, const bool verbose ) { word ext = name.ext(); if (ext == "gz") { ext = name.lessExt().ext(); } return canReadType(ext, verbose); } template<class Face> void CML::MeshedSurface<Face>::write ( const fileName& name, const MeshedSurface<Face>& surf ) { if (debug) { Info<< "MeshedSurface::write" "(const fileName&, const MeshedSurface&) : " "writing to " << name << endl; } const word ext = name.ext(); typename writefileExtensionMemberFunctionTable::iterator mfIter = writefileExtensionMemberFunctionTablePtr_->find(ext); if (mfIter == writefileExtensionMemberFunctionTablePtr_->end()) { // no direct writer, delegate to proxy if possible wordHashSet supported = ProxyType::writeTypes(); if (supported.found(ext)) { MeshedSurfaceProxy<Face>(surf).write(name); } else { FatalErrorInFunction << "Unknown file extension " << ext << nl << nl << "Valid types are :" << endl << (supported | writeTypes()) << exit(FatalError); } } else { mfIter()(name, surf); } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class Face> CML::MeshedSurface<Face>::MeshedSurface() : ParentType(List<Face>(), pointField()) {} template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Xfer<pointField>& pointLst, const Xfer<List<Face> >& faceLst, const Xfer<surfZoneList>& zoneLst ) : ParentType(List<Face>(), pointField()), zones_() { reset(pointLst, faceLst, zoneLst); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Xfer<pointField>& pointLst, const Xfer<List<Face> >& faceLst, const labelUList& zoneSizes, const UList<word>& zoneNames ) : ParentType(List<Face>(), pointField()) { reset(pointLst, faceLst, Xfer<surfZoneList>()); if (zoneSizes.size()) { if (zoneNames.size()) { addZones(zoneSizes, zoneNames); } else { addZones(zoneSizes); } } } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const MeshedSurface<Face>& surf ) : ParentType(surf.faces(), surf.points()), zones_(surf.surfZones()) {} template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const UnsortedMeshedSurface<Face>& surf ) : ParentType(List<Face>(), surf.points()) { labelList faceMap; this->storedZones().transfer(surf.sortedZones(faceMap)); const List<Face>& origFaces = surf.faces(); List<Face> newFaces(origFaces.size()); // this is somewhat like ListOps reorder and/or IndirectList forAll(newFaces, faceI) { newFaces[faceI] = origFaces[faceMap[faceI]]; } this->storedFaces().transfer(newFaces); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface(const surfMesh& mesh) : ParentType(List<Face>(), pointField()) { // same face type as surfMesh MeshedSurface<face> surf ( xferCopy(mesh.points()), xferCopy(mesh.faces()), xferCopy(mesh.surfZones()) ); this->transcribe(surf); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const polyBoundaryMesh& bMesh, const bool useGlobalPoints ) : ParentType(List<Face>(), pointField()) { const polyMesh& mesh = bMesh.mesh(); const polyPatchList& bPatches = bMesh; // Get a single patch for all boundaries primitivePatch allBoundary ( SubList<face> ( mesh.faces(), mesh.nFaces() - mesh.nInternalFaces(), mesh.nInternalFaces() ), mesh.points() ); // use global/local points: const pointField& bPoints = ( useGlobalPoints ? mesh.points() : allBoundary.localPoints() ); // global/local face addressing: const List<Face>& bFaces = ( useGlobalPoints ? allBoundary : allBoundary.localFaces() ); // create zone list surfZoneList newZones(bPatches.size()); label startFaceI = 0; label nZone = 0; forAll(bPatches, patchI) { const polyPatch& p = bPatches[patchI]; if (p.size()) { newZones[nZone] = surfZone ( p.name(), p.size(), startFaceI, nZone ); nZone++; startFaceI += p.size(); } } newZones.setSize(nZone); // same face type as the polyBoundaryMesh MeshedSurface<face> surf ( xferCopy(bPoints), xferCopy(bFaces), xferMove(newZones) ); this->transcribe(surf); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const fileName& name, const word& ext ) : ParentType(List<Face>(), pointField()) { read(name, ext); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface(const fileName& name) : ParentType(List<Face>(), pointField()) { read(name); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Time& t, const word& surfName ) : ParentType(List<Face>(), pointField()) { surfMesh mesh ( IOobject ( "dummyName", t.timeName(), t, IOobject::MUST_READ_IF_MODIFIED, IOobject::NO_WRITE, false ), surfName ); // same face type as surfMesh MeshedSurface<face> surf ( xferMove(mesh.storedPoints()), xferMove(mesh.storedFaces()), xferMove(mesh.storedZones()) ); this->transcribe(surf); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Xfer<UnsortedMeshedSurface<Face> >& surf ) : ParentType(List<Face>(), pointField()) { transfer(surf()); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Xfer<MeshedSurface<Face> >& surf ) : ParentType(List<Face>(), pointField()) { transfer(surf()); } // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // template<class Face> CML::MeshedSurface<Face>::~MeshedSurface() {} // * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::remapFaces ( const labelUList& faceMap ) { // recalculate the zone start/size if (notNull(faceMap) && faceMap.size()) { surfZoneList& zones = storedZones(); if (zones.size() == 1) { // optimized for single zone case zones[0].size() = faceMap.size(); } else if (zones.size()) { label newFaceI = 0; label origEndI = 0; forAll(zones, zoneI) { surfZone& zone = zones[zoneI]; // adjust zone start zone.start() = newFaceI; origEndI += zone.size(); for (label faceI = newFaceI; faceI < faceMap.size(); ++faceI) { if (faceMap[faceI] < origEndI) { ++newFaceI; } else { break; } } // adjust zone size zone.size() = newFaceI - zone.start(); } } } } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::clear() { ParentType::clearOut(); storedPoints().clear(); storedFaces().clear(); storedZones().clear(); } template<class Face> void CML::MeshedSurface<Face>::movePoints(const pointField& newPoints) { // Adapt for new point position ParentType::movePoints(newPoints); // Copy new points storedPoints() = newPoints; } template<class Face> void CML::MeshedSurface<Face>::scalePoints(const scalar scaleFactor) { // avoid bad scaling if (scaleFactor > 0 && scaleFactor != 1.0) { pointField newPoints(scaleFactor*this->points()); // Adapt for new point position ParentType::movePoints(newPoints); storedPoints() = newPoints; } } template<class Face> void CML::MeshedSurface<Face>::reset ( const Xfer<pointField>& pointLst, const Xfer<List<Face> >& faceLst, const Xfer<surfZoneList>& zoneLst ) { ParentType::clearOut(); // Take over new primitive data. // Optimized to avoid overwriting data at all if (notNull(pointLst)) { storedPoints().transfer(pointLst()); } if (notNull(faceLst)) { storedFaces().transfer(faceLst()); } if (notNull(zoneLst)) { storedZones().transfer(zoneLst()); } } template<class Face> void CML::MeshedSurface<Face>::reset ( const Xfer<List<point> >& pointLst, const Xfer<List<Face> >& faceLst, const Xfer<surfZoneList>& zoneLst ) { ParentType::clearOut(); // Take over new primitive data. // Optimized to avoid overwriting data at all if (notNull(pointLst)) { storedPoints().transfer(pointLst()); } if (notNull(faceLst)) { storedFaces().transfer(faceLst()); } if (notNull(zoneLst)) { storedZones().transfer(zoneLst()); } } // Remove badly degenerate faces, double faces. template<class Face> void CML::MeshedSurface<Face>::cleanup(const bool verbose) { // merge points (already done for STL, TRI) stitchFaces(SMALL, verbose); checkFaces(verbose); this->checkTopology(verbose); } template<class Face> bool CML::MeshedSurface<Face>::stitchFaces ( const scalar tol, const bool verbose ) { pointField& pointLst = this->storedPoints(); // Merge points labelList pointMap(pointLst.size()); pointField newPoints(pointLst.size()); bool hasMerged = mergePoints(pointLst, tol, verbose, pointMap, newPoints); if (!hasMerged) { return false; } if (verbose) { Info<< "MeshedSurface::stitchFaces : Renumbering all faces" << endl; } // Set the coordinates to the merged ones pointLst.transfer(newPoints); List<Face>& faceLst = this->storedFaces(); List<label> faceMap(faceLst.size()); // Reset the point labels to the unique points array label newFaceI = 0; forAll(faceLst, faceI) { Face& f = faceLst[faceI]; forAll(f, fp) { f[fp] = pointMap[f[fp]]; } // for extra safety: collapse face as well if (f.collapse() >= 3) { if (newFaceI != faceI) { faceLst[newFaceI] = f; } faceMap[newFaceI] = faceI; newFaceI++; } else if (verbose) { Pout<< "MeshedSurface::stitchFaces : " << "Removing collapsed face " << faceI << endl << " vertices :" << f << endl; } } pointMap.clear(); if (newFaceI != faceLst.size()) { if (verbose) { Pout<< "MeshedSurface::stitchFaces : " << "Removed " << faceLst.size() - newFaceI << " faces" << endl; } faceLst.setSize(newFaceI); faceMap.setSize(newFaceI); remapFaces(faceMap); } faceMap.clear(); // Merging points might have changed geometric factors ParentType::clearOut(); return true; } // Remove badly degenerate faces and double faces. template<class Face> bool CML::MeshedSurface<Face>::checkFaces ( const bool verbose ) { bool changed = false; List<Face>& faceLst = this->storedFaces(); List<label> faceMap(faceLst.size()); label newFaceI = 0; // Detect badly labelled faces and mark degenerate faces const label maxPointI = this->points().size() - 1; forAll(faceLst, faceI) { Face& f = faceLst[faceI]; // avoid degenerate faces if (f.collapse() >= 3) { forAll(f, fp) { if (f[fp] < 0 || f[fp] > maxPointI) { FatalErrorInFunction << "face " << f << " uses point indices outside point range 0.." << maxPointI << exit(FatalError); } } faceMap[faceI] = faceI; newFaceI++; } else { // mark as bad face faceMap[faceI] = -1; changed = true; if (verbose) { WarningInFunction << "face[" << faceI << "] = " << f << " does not have three unique vertices" << endl; } } } // Detect doubled faces // do not touch the faces const labelListList& fFaces = this->faceFaces(); newFaceI = 0; forAll(faceLst, faceI) { // skip already collapsed faces: if (faceMap[faceI] < 0) { continue; } const Face& f = faceLst[faceI]; // duplicate face check bool okay = true; const labelList& neighbours = fFaces[faceI]; // Check if faceNeighbours use same points as this face. // Note: discards normal information - sides of baffle are merged. forAll(neighbours, neighI) { const label neiFaceI = neighbours[neighI]; if (neiFaceI <= faceI || faceMap[neiFaceI] < 0) { // lower numbered faces already checked // skip neighbours that are themselves collapsed continue; } const Face& nei = faceLst[neiFaceI]; if (f == nei) { okay = false; if (verbose) { WarningInFunction << "faces share the same vertices:" << nl << " face[" << faceI << "] : " << f << nl << " face[" << neiFaceI << "] : " << nei << endl; // printFace(Warning, " ", f, points()); // printFace(Warning, " ", nei, points()); } break; } } if (okay) { faceMap[faceI] = faceI; newFaceI++; } else { faceMap[faceI] = -1; } } // Phase 1: pack // Done to keep numbering constant in phase 1 if (changed || newFaceI < faceLst.size()) { changed = true; if (verbose) { WarningInFunction << "Removed " << faceLst.size() - newFaceI << " illegal faces." << endl; } // compress the face list newFaceI = 0; forAll(faceLst, faceI) { if (faceMap[faceI] >= 0) { if (newFaceI != faceI) { faceLst[newFaceI] = faceLst[faceI]; } faceMap[newFaceI] = faceI; newFaceI++; } } faceLst.setSize(newFaceI); remapFaces(faceMap); } faceMap.clear(); // Topology can change because of renumbering ParentType::clearOut(); return changed; } template<class Face> CML::label CML::MeshedSurface<Face>::triangulate() { return triangulate ( const_cast<List<label>&>(List<label>::null()) ); } template<class Face> CML::label CML::MeshedSurface<Face>::triangulate ( List<label>& faceMapOut ) { label nTri = 0; label maxTri = 0; // the maximum number of triangles for any single face List<Face>& faceLst = this->storedFaces(); // determine how many triangles will be needed forAll(faceLst, faceI) { const label n = faceLst[faceI].nTriangles(); if (maxTri < n) { maxTri = n; } nTri += n; } // nothing to do if (nTri <= faceLst.size()) { if (notNull(faceMapOut)) { faceMapOut.clear(); } return 0; } List<Face> newFaces(nTri); List<label> faceMap; // reuse storage from optional faceMap if (notNull(faceMapOut)) { faceMap.transfer(faceMapOut); } faceMap.setSize(nTri); // remember the number of *additional* faces nTri -= faceLst.size(); if (this->points().empty()) { // triangulate without points // simple face triangulation around f[0] label newFaceI = 0; forAll(faceLst, faceI) { const Face& f = faceLst[faceI]; for (label fp = 1; fp < f.size() - 1; ++fp) { label fp1 = f.fcIndex(fp); newFaces[newFaceI] = triFace(f[0], f[fp], f[fp1]); faceMap[newFaceI] = faceI; newFaceI++; } } } else { // triangulate with points List<face> tmpTri(maxTri); label newFaceI = 0; forAll(faceLst, faceI) { // 'face' not '<Face>' const face& f = faceLst[faceI]; label nTmp = 0; f.triangles(this->points(), nTmp, tmpTri); for (label triI = 0; triI < nTmp; triI++) { newFaces[newFaceI] = Face ( static_cast<labelUList&>(tmpTri[triI]) ); faceMap[newFaceI] = faceI; newFaceI++; } } } faceLst.transfer(newFaces); remapFaces(faceMap); // optionally return the faceMap if (notNull(faceMapOut)) { faceMapOut.transfer(faceMap); } faceMap.clear(); // Topology can change because of renumbering ParentType::clearOut(); return nTri; } template<class Face> CML::MeshedSurface<Face> CML::MeshedSurface<Face>::subsetMesh ( const labelHashSet& include, labelList& pointMap, labelList& faceMap ) const { const pointField& locPoints = this->localPoints(); const List<Face>& locFaces = this->localFaces(); // Fill pointMap, faceMap PatchTools::subsetMap(*this, include, pointMap, faceMap); // Create compact coordinate list and forward mapping array pointField newPoints(pointMap.size()); labelList oldToNew(locPoints.size()); forAll(pointMap, pointI) { newPoints[pointI] = locPoints[pointMap[pointI]]; oldToNew[pointMap[pointI]] = pointI; } // create/copy a new zones list, each zone with zero size surfZoneList newZones(this->surfZones()); forAll(newZones, zoneI) { newZones[zoneI].size() = 0; } // Renumber face node labels List<Face> newFaces(faceMap.size()); forAll(faceMap, faceI) { const label origFaceI = faceMap[faceI]; newFaces[faceI] = Face(locFaces[origFaceI]); // Renumber labels for face Face& f = newFaces[faceI]; forAll(f, fp) { f[fp] = oldToNew[f[fp]]; } } oldToNew.clear(); // recalculate the zones start/size label newFaceI = 0; label origEndI = 0; // adjust zone sizes forAll(newZones, zoneI) { surfZone& zone = newZones[zoneI]; // adjust zone start zone.start() = newFaceI; origEndI += zone.size(); for (label faceI = newFaceI; faceI < faceMap.size(); ++faceI) { if (faceMap[faceI] < origEndI) { ++newFaceI; } else { break; } } // adjust zone size zone.size() = newFaceI - zone.start(); } // construct a sub-surface return MeshedSurface ( xferMove(newPoints), xferMove(newFaces), xferMove(newZones) ); } template<class Face> CML::MeshedSurface<Face> CML::MeshedSurface<Face>::subsetMesh ( const labelHashSet& include ) const { labelList pointMap, faceMap; return subsetMesh(include, pointMap, faceMap); } template<class Face> void CML::MeshedSurface<Face>::transfer ( MeshedSurface<Face>& surf ) { reset ( xferMove(surf.storedPoints()), xferMove(surf.storedFaces()), xferMove(surf.storedZones()) ); } template<class Face> void CML::MeshedSurface<Face>::transfer ( UnsortedMeshedSurface<Face>& surf ) { clear(); labelList faceMap; surfZoneList zoneLst = surf.sortedZones(faceMap); if (zoneLst.size() <= 1) { reset ( xferMove(surf.storedPoints()), xferMove(surf.storedFaces()), Xfer<surfZoneList>() ); } else { List<Face>& oldFaces = surf.storedFaces(); List<Face> newFaces(faceMap.size()); forAll(faceMap, faceI) { newFaces[faceI].transfer(oldFaces[faceMap[faceI]]); } reset ( xferMove(surf.storedPoints()), xferMove(newFaces), xferMove(zoneLst) ); } faceMap.clear(); surf.clear(); } template<class Face> CML::Xfer<CML::MeshedSurface<Face> > CML::MeshedSurface<Face>::xfer() { return xferMove(*this); } // Read from file, determine format from extension template<class Face> bool CML::MeshedSurface<Face>::read(const fileName& name) { word ext = name.ext(); if (ext == "gz") { fileName unzipName = name.lessExt(); return read(unzipName, unzipName.ext()); } else { return read(name, ext); } } // Read from file in given format template<class Face> bool CML::MeshedSurface<Face>::read ( const fileName& name, const word& ext ) { clear(); // read via selector mechanism transfer(New(name, ext)()); return true; } template<class Face> void CML::MeshedSurface<Face>::write ( const Time& t, const word& surfName ) const { MeshedSurfaceProxy<Face>(*this).write(t, surfName); } // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::operator=(const MeshedSurface& surf) { clear(); this->storedPoints() = surf.points(); this->storedFaces() = surf.faces(); this->storedZones() = surf.surfZones(); } template<class Face> CML::MeshedSurface<Face>::operator CML::MeshedSurfaceProxy<Face>() const { return MeshedSurfaceProxy<Face> ( this->points(), this->faces(), this->surfZones() ); } // * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::checkZones() { // extra safety, ensure we have at some zones // and they cover all the faces - fix start silently surfZoneList& zones = this->storedZones(); if (zones.size()) { label count = 0; forAll(zones, zoneI) { zones[zoneI].start() = count; count += zones[zoneI].size(); } if (count < this->size()) { WarningInFunction << "more faces " << this->size() << " than zones " << count << " ... extending final zone" << endl; zones.last().size() += count - this->size(); } else if (count > this->size()) { FatalErrorInFunction << "more zones " << count << " than faces " << this->size() << exit(FatalError); } } } template<class Face> void CML::MeshedSurface<Face>::sortFacesAndStore ( const Xfer<List<Face> >& unsortedFaces, const Xfer<List<label> >& zoneIds, const bool sorted ) { List<Face> oldFaces(unsortedFaces); List<label> zones(zoneIds); if (sorted) { // already sorted - simply transfer faces this->storedFaces().transfer(oldFaces); } else { // unsorted - determine the sorted order: // avoid SortableList since we discard the main list anyhow List<label> faceMap; sortedOrder(zones, faceMap); zones.clear(); // sorted faces List<Face> newFaces(faceMap.size()); forAll(faceMap, faceI) { // use transfer to recover memory where possible newFaces[faceI].transfer(oldFaces[faceMap[faceI]]); } this->storedFaces().transfer(newFaces); } zones.clear(); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::addZones ( const UList<surfZone>& srfZones, const bool cullEmpty ) { label nZone = 0; surfZoneList& zones = this->storedZones(); zones.setSize(zones.size()); forAll(zones, zoneI) { if (srfZones[zoneI].size() || !cullEmpty) { zones[nZone] = surfZone(srfZones[zoneI], nZone); nZone++; } } zones.setSize(nZone); } template<class Face> void CML::MeshedSurface<Face>::addZones ( const labelUList& sizes, const UList<word>& names, const bool cullEmpty ) { label start = 0; label nZone = 0; surfZoneList& zones = this->storedZones(); zones.setSize(sizes.size()); forAll(zones, zoneI) { if (sizes[zoneI] || !cullEmpty) { zones[nZone] = surfZone ( names[zoneI], sizes[zoneI], start, nZone ); start += sizes[zoneI]; nZone++; } } zones.setSize(nZone); } template<class Face> void CML::MeshedSurface<Face>::addZones ( const labelUList& sizes, const bool cullEmpty ) { label start = 0; label nZone = 0; surfZoneList& zones = this->storedZones(); zones.setSize(sizes.size()); forAll(zones, zoneI) { if (sizes[zoneI] || !cullEmpty) { zones[nZone] = surfZone ( word("zone") + ::CML::name(nZone), sizes[zoneI], start, nZone ); start += sizes[zoneI]; nZone++; } } zones.setSize(nZone); } template<class Face> void CML::MeshedSurface<Face>::removeZones() { this->storedZones().clear(); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::writeStats(Ostream& os) const { os << "points : " << this->points().size() << nl; if (MeshedSurface<Face>::isTri()) { os << "triangles : " << this->size() << nl; } else { label nTri = 0; label nQuad = 0; forAll(*this, i) { const label n = this->operator[](i).size(); if (n == 3) { nTri++; } else if (n == 4) { nQuad++; } } os << "faces : " << this->size() << " (tri:" << nTri << " quad:" << nQuad << " poly:" << (this->size() - nTri - nQuad ) << ")" << nl; } os << "boundingBox : " << boundBox(this->points()) << endl; } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Face> CML::autoPtr< CML::MeshedSurface<Face> > CML::MeshedSurface<Face>::New(const fileName& name, const word& ext) { if (debug) { Info<< "MeshedSurface::New(const fileName&, const word&) : " "constructing MeshedSurface" << endl; } typename fileExtensionConstructorTable::iterator cstrIter = fileExtensionConstructorTablePtr_->find(ext); if (cstrIter == fileExtensionConstructorTablePtr_->end()) { // no direct reader, delegate if possible wordHashSet supported = FriendType::readTypes(); if (supported.found(ext)) { // create indirectly autoPtr< MeshedSurface<Face> > surf(new MeshedSurface<Face>); surf().transfer(FriendType::New(name, ext)()); return surf; } // nothing left to try, issue error supported += readTypes(); FatalErrorInFunction << "Unknown file extension " << ext << nl << nl << "Valid types are :" << nl << supported << exit(FatalError); } return autoPtr< MeshedSurface<Face> >(cstrIter()(name)); } template<class Face> CML::autoPtr< CML::MeshedSurface<Face> > CML::MeshedSurface<Face>::New(const fileName& name) { word ext = name.ext(); if (ext == "gz") { ext = name.lessExt().ext(); } return New(name, ext); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
23.358162
79
0.542099
MrAwesomeRocks
f0e3176656a2486c5b034523bacc31885375ef30
1,525
cpp
C++
networkit/cpp/auxiliary/ParallelTimings.cpp
ArminWiebigke/networkit
713320a5961f6324d62df2ea7a32675fa053dfac
[ "MIT" ]
null
null
null
networkit/cpp/auxiliary/ParallelTimings.cpp
ArminWiebigke/networkit
713320a5961f6324d62df2ea7a32675fa053dfac
[ "MIT" ]
null
null
null
networkit/cpp/auxiliary/ParallelTimings.cpp
ArminWiebigke/networkit
713320a5961f6324d62df2ea7a32675fa053dfac
[ "MIT" ]
null
null
null
/* * ParallelTimings.cpp * * Created on: 2019-11-05 * Author: Armin Wiebigke */ #include <map> #include "ParallelTimings.h" namespace NetworKit { void ParallelTimings::addTime(Aux::Timer &timer, const std::string &name) const { timer.stop(); double elapsed = timer.elapsedNanoseconds(); auto tid = omp_get_thread_num(); timings[tid][name] += elapsed; timer.start(); } ParallelTimings::ParallelTimings() : timings(omp_get_max_threads()) { } void ParallelTimings::addTimings(const std::unordered_map<std::string, double> &ts, const std::string &prefix) const { auto tid = omp_get_thread_num(); for (auto &t : ts) { timings[tid][prefix + t.first] += t.second; } } std::unordered_map<std::string, double> ParallelTimings::getTimings() const { std::unordered_map<std::string, double> timingsSum; for (const auto& threadTimings : timings) { for (const auto& it : threadTimings) { timingsSum[it.first] += it.second; } } return timingsSum; } bool ParallelTimings::timingsEmpty() const { for (const auto& threadTimings : timings) { if (!threadTimings.empty()) return false; } return true; } std::string ParallelTimings::timingsAsString() const { std::map<std::string, double> timingsSum; for (const auto& threadTimings : timings) { for (const auto& it : threadTimings) { timingsSum[it.first] += it.second; } } std::stringstream str; for (const auto& t : timingsSum) { str << t.first + ": " << t.second / 1e6 << "ms" << "\n"; } return str.str(); } } // namespace NetworKit
23.106061
118
0.683934
ArminWiebigke
f0e719c6ea86f83338f9e8745890360cae78d634
6,370
cpp
C++
texture.cpp
CaptainDreamcast/prism
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
7
2018-04-08T15:01:59.000Z
2022-02-27T12:13:19.000Z
texture.cpp
CaptainDreamcast/prism
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
1
2017-04-23T15:27:37.000Z
2017-04-24T05:38:18.000Z
texture.cpp
CaptainDreamcast/libtari
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
1
2020-04-24T04:21:00.000Z
2020-04-24T04:21:00.000Z
#include "prism/texture.h" #include<algorithm> #ifdef DREAMCAST #include <png/png.h> #else #include <png.h> #endif #include "prism/file.h" #include "prism/log.h" #include "prism/system.h" #include "prism/math.h" using namespace std; #define FONT_CHARACTER_AMOUNT 91 static int isFontDataLoaded; static TextureData gFont; static FontCharacterData gFontCharacterData[FONT_CHARACTER_AMOUNT]; void unloadFont() { if (!isFontDataLoaded) return; unloadTexture(gFont); memset(gFontCharacterData, 0, sizeof gFontCharacterData); isFontDataLoaded = 0; } static void loadFontHeader(const char* tFileDir) { FileHandler file; file = fileOpen(tFileDir, O_RDONLY); if (file == FILEHND_INVALID) { logError("Cannot open font header."); logErrorString(tFileDir); recoverFromError(); } fileSeek(file, 0, 0); int i; for (i = 0; i < FONT_CHARACTER_AMOUNT; i++) { fileRead(file, &gFontCharacterData[i], sizeof gFontCharacterData[i]); } fileClose(file); } static void loadFontTexture(const char* tFileDir) { gFont = loadTexturePKG(tFileDir); } void setFont(const char* tFileDirHeader, const char* tFileDirTexture) { if (isFontDataLoaded) { unloadFont(); } if (!isFile(tFileDirHeader)) { return; } loadFontHeader(tFileDirHeader); loadFontTexture(tFileDirTexture); isFontDataLoaded = 1; } void loadConsecutiveTextures(TextureData * tDst, const char * tBaseFileDir, int tAmount) { int i; for (i = 0; i < tAmount; i++) { char path[1024]; getPathWithNumberAffixedFromAssetPath(path, tBaseFileDir, i); tDst[i] = loadTexture(path); } } TextureData getFontTexture() { return gFont; } FontCharacterData getFontCharacterData(char tChar) { int i; if (tChar < ' ' || tChar > 'z') i = 0; else i = tChar - ' '; return gFontCharacterData[i]; } TextureSize makeTextureSize(int x, int y) { TextureSize ret; ret.x = x; ret.y = y; return ret; } TextureData createWhiteTexture() { int length = 16 * 16 * 4; uint8_t* data = (uint8_t*)allocMemory(length); memset(data, 0xFF, length); TextureData ret = loadTextureFromARGB32Buffer(makeBuffer(data, length), 16, 16); freeMemory(data); return ret; } TextureData createWhiteCircleTexture() { int length = 16 * 16 * 4; uint8_t* data = (uint8_t*)allocMemory(length); memset(data, 0xFF, length); const std::vector<int> LINE_EMPTY_AMOUNT = {5, 3, 2, 1, 1}; for (size_t y = 0; y < LINE_EMPTY_AMOUNT.size(); y++) { const auto width = LINE_EMPTY_AMOUNT[y]; for (int x = 0; x < width; x++) { data[(y * 16 + x) * 4 + 3] = 0; data[(y * 16 + (15 - x)) * 4 + 3] = 0; data[((15 - y) * 16 + x) * 4 + 3] = 0; data[((15 - y) * 16 + (15 - x)) * 4 + 3] = 0; } } TextureData ret = loadTextureFromARGB32Buffer(makeBuffer(data, length), 16, 16); freeMemory(data); return ret; } Buffer turnARGB32BufferIntoARGB16Buffer(const Buffer& tSrc) { int dstSize = tSrc.mLength / 2; char* dst = (char*)allocMemory(dstSize); char* src = (char*)tSrc.mData; int n = dstSize / 2; int i; for(i = 0; i < n; i++) { int srcPos = 4*i; int dstPos = 2*i; uint8_t a = ((uint8_t)src[srcPos + 3]) >> 4; uint8_t r = ((uint8_t)src[srcPos + 2]) >> 4; uint8_t g = ((uint8_t)src[srcPos + 1]) >> 4; uint8_t b = ((uint8_t)src[srcPos + 0]) >> 4; dst[dstPos + 0] = (g << 4) | b; dst[dstPos + 1] = (a << 4) | r; } return makeBufferOwned(dst, dstSize); } /* Linear/iterative twiddling algorithm from Marcus' tatest */ #define TWIDTAB(x) ( (x&1)|((x&2)<<1)|((x&4)<<2)|((x&8)<<3)|((x&16)<<4)| \ ((x&32)<<5)|((x&64)<<6)|((x&128)<<7)|((x&256)<<8)|((x&512)<<9) ) #define TWIDOUT(x, y) ( TWIDTAB((y)) | (TWIDTAB((x)) << 1) ) #define MIN(a, b) ( (a)<(b)? (a):(b) ) /* This twiddling code is copied from pvr_texture.c, and the original algorithm was written by Vincent Penne. */ Buffer twiddleTextureBuffer8(const Buffer& tBuffer, int tWidth, int tHeight) { int w = tWidth; int h = tHeight; int mini = min(w, h); int mask = mini - 1; uint8_t * pixels = (uint8_t *)tBuffer.mData; uint8_t * vtex = (uint8_t*)allocMemory(tBuffer.mLength); int x, y, yout; for(y = 0; y < h; y++) { yout = y; for(x = 0; x < w; x++) { vtex[TWIDOUT(x & mask, yout & mask) + (x / mini + yout / mini)*mini * mini] = pixels[y * w + x]; } } return makeBufferOwned(vtex, tBuffer.mLength); } Buffer twiddleTextureBuffer16(const Buffer& tBuffer, int tWidth, int tHeight) { int w = tWidth; int h = tHeight; int mini = min(w, h); int mask = mini - 1; uint16_t * pixels = (uint16_t *)tBuffer.mData; uint16_t * vtex = (uint16_t*)allocMemory(tBuffer.mLength); int x, y, yout; for (y = 0; y < h; y++) { yout = y; for (x = 0; x < w; x++) { vtex[TWIDOUT(x & mask, yout & mask) + (x / mini + yout / mini)*mini * mini] = pixels[y * w + x]; } } return makeBufferOwned(vtex, tBuffer.mLength); } #ifdef DREAMCAST #pragma GCC diagnostic ignored "-Wclobbered" #endif #ifdef _WIN32 #pragma warning(push) #pragma warning(disable: 4611) #endif void saveRGB32ToPNG(const Buffer& b, int tWidth, int tHeight, const char* tFileDir) { char fullPath[1024]; getFullPath(fullPath, tFileDir); FILE *fp = fopen(fullPath, "wb"); if (!fp) { logErrorFormat("Unable to open file %s", tFileDir); return; } auto png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { logError("Unable to create png struct."); return; } auto info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { logError("Unable to create png info struct."); return; } if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_init_io(png_ptr, fp); if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_set_IHDR(png_ptr, info_ptr, tWidth, tHeight, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } for (int y = tHeight - 1; y >= 0; y--) { png_bytep bytes = ((png_bytep)b.mData) + tWidth * 3 * y; png_write_rows(png_ptr, &bytes, 1); } if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_write_end(png_ptr, NULL); fclose(fp); } #ifdef _WIN32 #pragma warning(pop) #endif
22.75
88
0.649137
CaptainDreamcast
f0e933ed100092fe5cf143ddcb9558b9fc32c21d
267
hpp
C++
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
1
2018-03-24T00:33:03.000Z
2018-03-24T00:33:03.000Z
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_BUILTIN_REFERENCEERROR_HPP #define PYTHONIC_INCLUDE_BUILTIN_REFERENCEERROR_HPP #include "pythonic/include/types/exceptions.hpp" PYTHONIC_NS_BEGIN namespace __builtin__ { PYTHONIC_EXCEPTION_DECL(ReferenceError) } PYTHONIC_NS_END #endif
16.6875
51
0.868914
SylvainCorlay
f0ea469a07225cc24c6b92a7cb30c43024a6108f
5,692
cpp
C++
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: ncbi_safe_static.cpp 177027 2009-11-24 19:19:28Z grichenk $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksey Grichenko * * File Description: * Static variables safety - create on demand, destroy on termination * * CSafeStaticGuard:: -- guarantee for CSafePtr<> and CSafeRef<> * destruction and cleanup * */ #include <ncbi_pch.hpp> #include <corelib/ncbi_safe_static.hpp> #include <corelib/ncbistd.hpp> #include <corelib/ncbithr.hpp> #include <corelib/ncbimtx.hpp> #include <corelib/error_codes.hpp> #include <memory> #include <assert.h> #define NCBI_USE_ERRCODE_X Corelib_Static BEGIN_NCBI_SCOPE CSafeStaticLifeSpan::CSafeStaticLifeSpan(ELifeSpan span, int adjust) : m_LifeSpan(int(span) + adjust) { if (span == eLifeSpan_Min) { m_LifeSpan = int(span); // ignore adjustments adjust = 0; } if (adjust >= 5000 || adjust <= -5000) { ERR_POST_X(1, Warning << "CSafeStaticLifeSpan level adjustment out of range: " << adjust); } _ASSERT(adjust > -5000 && adjust < 5000); } CSafeStaticLifeSpan& CSafeStaticLifeSpan::GetDefault(void) { static CSafeStaticLifeSpan s_DefaultSpan(eLifeSpan_Min); return s_DefaultSpan; } ///////////////////////////////////////////////////////////////////////////// // // CSafeStaticPtr_Base:: // // Protective mutex and the owner thread ID to avoid // multiple initializations and deadlocks DEFINE_STATIC_MUTEX(s_Mutex); static CThreadSystemID s_MutexOwner; // true if s_MutexOwner has been set (while the mutex is locked) static bool s_MutexLocked; bool CSafeStaticPtr_Base::Init_Lock(bool* mutex_locked) { // Check if already locked by the same thread to avoid deadlock // in case of nested calls to Get() by T constructor // Lock only if unlocked or locked by another thread // to prevent initialization by another thread CThreadSystemID id = CThreadSystemID::GetCurrent(); if (!s_MutexLocked || s_MutexOwner != id) { s_Mutex.Lock(); s_MutexLocked = true; *mutex_locked = true; s_MutexOwner = id; } return m_Ptr == 0; } void CSafeStaticPtr_Base::Init_Unlock(bool mutex_locked) { // Unlock the mutex only if it was locked by the same call to Get() if ( mutex_locked ) { s_MutexLocked = false; s_Mutex.Unlock(); } } int CSafeStaticPtr_Base::x_GetCreationOrder(void) { static CAtomicCounter s_CreationOrder; return s_CreationOrder.Add(1); } CSafeStaticPtr_Base::~CSafeStaticPtr_Base(void) { bool mutex_locked = false; if ( x_IsStdStatic() && !Init_Lock(&mutex_locked) ) { x_Cleanup(); } Init_Unlock(mutex_locked); } ///////////////////////////////////////////////////////////////////////////// // // CSafeStaticGuard:: // // Cleanup stack to keep all on-demand variables CSafeStaticGuard::TStack* CSafeStaticGuard::sm_Stack; // CSafeStaticGuard reference counter int CSafeStaticGuard::sm_RefCount; CSafeStaticGuard::CSafeStaticGuard(void) { // Initialize the guard only once if (sm_RefCount == 0) { CSafeStaticGuard::sm_Stack = new CSafeStaticGuard::TStack; } sm_RefCount++; } static CSafeStaticGuard* sh_CleanupGuard; CSafeStaticGuard::~CSafeStaticGuard(void) { CMutexGuard guard(s_Mutex); // Protect CSafeStaticGuard destruction if ( sh_CleanupGuard ) { CSafeStaticGuard* tmp = sh_CleanupGuard; sh_CleanupGuard = 0; delete tmp; } // If this is not the last reference, then do not destroy stack if (--sm_RefCount > 0) { return; } assert(sm_RefCount == 0); // Call Cleanup() for all variables registered NON_CONST_ITERATE(TStack, it, *sm_Stack) { (*it)->x_Cleanup(); } delete sm_Stack; sm_Stack = 0; } // Global guard - to prevent premature destruction by e.g. GNU compiler // (it destroys all local static variables before any global one) static CSafeStaticGuard sg_CleanupGuard; // Initialization of the guard CSafeStaticGuard* CSafeStaticGuard::x_Get(void) { // Local static variable - to initialize the guard // as soon as the function is called (global static // variable may be still uninitialized at this moment) static CSafeStaticGuard sl_CleanupGuard; if ( !sh_CleanupGuard ) sh_CleanupGuard = new CSafeStaticGuard; return &sl_CleanupGuard; } END_NCBI_SCOPE
27.765854
78
0.655657
OpenHero
f0ed6acb33e0b41499306ec4590b306a0280924d
5,808
cpp
C++
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
// This file is part of the Yttrium toolkit. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include <yttrium/geometry/matrix.h> #include <yttrium/geometry/euler.h> #include <yttrium/geometry/size.h> #include <cmath> #include <numbers> namespace Yt { Matrix4::Matrix4(const Euler& e) noexcept { const auto yaw = e._yaw / 180 * std::numbers::pi_v<float>; const auto pitch = e._pitch / 180 * std::numbers::pi_v<float>; const auto roll = e._roll / 180 * std::numbers::pi_v<float>; const auto cy = std::cos(yaw); const auto sy = std::sin(yaw); const auto cp = std::cos(pitch); const auto sp = std::sin(pitch); const auto cr = std::cos(roll); const auto sr = std::sin(roll); x = { sy * sp * sr + cy * cr, cy * sp * sr - sy * cr, -cp * sr, 0 }; y = { sy * cp, cy * cp, sp, 0 }; z = { cy * sr - sy * sp * cr, -cy * sp * cr - sy * sr, cp * cr, 0 }; t = { 0, 0, 0, 1 }; } Matrix4 Matrix4::camera(const Vector3& position, const Euler& orientation) noexcept { const Matrix4 r{ orientation }; return { r.x.x, r.x.y, r.x.z, -dot_product(position, { r.x.x, r.x.y, r.x.z }), r.y.x, r.y.y, r.y.z, -dot_product(position, { r.y.x, r.y.y, r.y.z }), r.z.x, r.z.y, r.z.z, -dot_product(position, { r.z.x, r.z.y, r.z.z }), 0, 0, 0, 1 }; } Matrix4 Matrix4::perspective(const SizeF& size, float vertical_fov, float near_plane, float far_plane) noexcept { const auto aspect = size._width / size._height; const auto f = 1 / std::tan(vertical_fov / 360 * std::numbers::pi_v<float>); const auto xx = f / aspect; const auto yy = f; const auto zz = (near_plane + far_plane) / (near_plane - far_plane); const auto tz = 2 * near_plane * far_plane / (near_plane - far_plane); const auto zw = -1.f; return { xx, 0, 0, 0, 0, yy, 0, 0, 0, 0, zz, tz, 0, 0, zw, 0 }; } Matrix4 Matrix4::projection_2d(const SizeF& size, float near_plane, float far_plane) noexcept { const auto xx = 2 / size._width; const auto yy = -2 / size._height; const auto zz = -2 / (far_plane - near_plane); const auto tx = -1.f; const auto ty = 1.f; const auto tz = (far_plane + near_plane) / (far_plane - near_plane); return { xx, 0, 0, tx, 0, yy, 0, ty, 0, 0, zz, tz, 0, 0, 0, 1 }; } Matrix4 Matrix4::rotation(float degrees, const Vector3& axis) noexcept { const auto v = normalize(axis); const auto radians = degrees / 180 * std::numbers::pi_v<float>; const auto c = std::cos(radians); const auto s = std::sin(radians); return { v.x * v.x * (1 - c) + c, v.y * v.x * (1 - c) - s * v.z, v.z * v.x * (1 - c) + s * v.y, 0, v.x * v.y * (1 - c) + s * v.z, v.y * v.y * (1 - c) + c, v.z * v.y * (1 - c) - s * v.x, 0, v.x * v.z * (1 - c) - s * v.y, v.y * v.z * (1 - c) + s * v.x, v.z * v.z * (1 - c) + c, 0, 0, 0, 0, 1 }; } float det(const Matrix4& m) noexcept { const auto xy = m.x.z * m.y.w - m.x.w * m.y.z; const auto xz = m.x.z * m.z.w - m.x.w * m.z.z; const auto xt = m.x.z * m.t.w - m.x.w * m.t.z; const auto yz = m.y.z * m.z.w - m.y.w * m.z.z; const auto yt = m.y.z * m.t.w - m.y.w * m.t.z; const auto zt = m.z.z * m.t.w - m.z.w * m.t.z; const auto yzt = m.y.y * zt - m.z.y * yt + m.t.y * yz; const auto xzt = m.x.y * zt - m.z.y * xt + m.t.y * xz; const auto xyt = m.x.y * yt - m.y.y * xt + m.t.y * xy; const auto xyz = m.x.y * yz - m.y.y * xz + m.z.y * xy; return m.x.x * yzt - m.y.x * xzt + m.z.x * xyt - m.t.x * xyz; } Matrix4 inverse(const Matrix4& m) noexcept { // Z and W rows. auto det01 = m.x.z * m.y.w - m.x.w * m.y.z; auto det02 = m.x.z * m.z.w - m.x.w * m.z.z; auto det03 = m.x.z * m.t.w - m.x.w * m.t.z; auto det12 = m.y.z * m.z.w - m.y.w * m.z.z; auto det13 = m.y.z * m.t.w - m.y.w * m.t.z; auto det23 = m.z.z * m.t.w - m.z.w * m.t.z; // Y, Z and W rows. const auto det123 = m.y.y * det23 - m.z.y * det13 + m.t.y * det12; const auto det023 = m.x.y * det23 - m.z.y * det03 + m.t.y * det02; const auto det013 = m.x.y * det13 - m.y.y * det03 + m.t.y * det01; const auto det012 = m.x.y * det12 - m.y.y * det02 + m.z.y * det01; const auto d = 1 / (m.x.x * det123 - m.y.x * det023 + m.z.x * det013 - m.t.x * det012); const auto xx = d * det123; const auto xy = d * -det023; const auto xz = d * det013; const auto xw = d * -det012; const auto yx = d * -(m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto yy = d * (m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto yz = d * -(m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto yw = d * (m.x.x * det12 - m.y.x * det02 + m.z.x * det01); // Y and W rows. det01 = m.x.y * m.y.w - m.y.y * m.x.w; det02 = m.x.y * m.z.w - m.z.y * m.x.w; det03 = m.x.y * m.t.w - m.t.y * m.x.w; det12 = m.y.y * m.z.w - m.z.y * m.y.w; det13 = m.y.y * m.t.w - m.t.y * m.y.w; det23 = m.z.y * m.t.w - m.t.y * m.z.w; const auto zx = d * (m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto zy = d * -(m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto zz = d * (m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto zw = d * -(m.x.x * det12 - m.y.x * det02 + m.z.x * det01); // Y and Z rows. det01 = m.y.z * m.x.y - m.x.z * m.y.y; det02 = m.z.z * m.x.y - m.x.z * m.z.y; det03 = m.t.z * m.x.y - m.x.z * m.t.y; det12 = m.z.z * m.y.y - m.y.z * m.z.y; det13 = m.t.z * m.y.y - m.y.z * m.t.y; det23 = m.t.z * m.z.y - m.z.z * m.t.y; const auto tx = d * -(m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto ty = d * (m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto tz = d * -(m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto tw = d * (m.x.x * det12 - m.y.x * det02 + m.z.x * det01); return { xx, yx, zx, tx, xy, yy, zy, ty, xz, yz, zz, tz, xw, yw, zw, tw }; } }
34.366864
112
0.532369
blagodarin
f0ef45f838db55c49ad28fb6f393909025c8e1d6
7,054
hpp
C++
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2012-2017 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_TRAVERSAL_HPP #define DTK_DETAILS_TREE_TRAVERSAL_HPP #include <DTK_DBC.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_DetailsNode.hpp> #include <DTK_DetailsPredicate.hpp> #include <DTK_DetailsPriorityQueue.hpp> #include <DTK_DetailsStack.hpp> namespace DataTransferKit { template <typename DeviceType> class BVH; namespace Details { template <typename DeviceType> struct TreeTraversal { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION static int query( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert ) { using Tag = typename Predicate::Tag; return queryDispatch( bvh, pred, insert, Tag{} ); } /** * Return true if the node is a leaf. */ KOKKOS_INLINE_FUNCTION static bool isLeaf( BVH<DeviceType> bvh, Node const *node ) { // COMMENT: could also check that pointer is in the range [leaf_nodes, // leaf_nodes+n] (void)bvh; return ( node->children.first == nullptr ) && ( node->children.second == nullptr ); } /** * Return the index of the leaf node. */ KOKKOS_INLINE_FUNCTION static int getIndex( BVH<DeviceType> bvh, Node const *leaf ) { return bvh._indices[leaf - bvh._leaf_nodes.data()]; } /** * Return the root node of the BVH. */ KOKKOS_INLINE_FUNCTION static Node const *getRoot( BVH<DeviceType> bvh ) { if ( bvh.empty() ) return nullptr; return ( bvh.size() > 1 ? bvh._internal_nodes : bvh._leaf_nodes ) .data(); } }; // There are two (related) families of search: one using a spatial predicate and // one using nearest neighbours query (see boost::geometry::queries // documentation). template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_FUNCTION int spatial_query( BVH<DeviceType> const bvh, Predicate const &predicate, Insert const &insert ) { if ( bvh.empty() ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); if ( predicate( leaf ) ) { int const leaf_index = TreeTraversal<DeviceType>::getIndex( bvh, leaf ); insert( leaf_index ); return 1; } else return 0; } Stack<Node const *> stack; Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); stack.push( root ); int count = 0; while ( !stack.empty() ) { Node const *node = stack.top(); stack.pop(); if ( TreeTraversal<DeviceType>::isLeaf( bvh, node ) ) { insert( TreeTraversal<DeviceType>::getIndex( bvh, node ) ); count++; } else { for ( Node const *child : {node->children.first, node->children.second} ) { if ( predicate( child ) ) { stack.push( child ); } } } } return count; } // query k nearest neighbours template <typename DeviceType, typename Insert> KOKKOS_FUNCTION int nearestQuery( BVH<DeviceType> const bvh, Point const &query_point, int k, Insert const &insert ) { if ( bvh.empty() || k < 1 ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); int const leaf_index = TreeTraversal<DeviceType>::getIndex( bvh, leaf ); double const leaf_distance = distance( query_point, leaf->bounding_box ); insert( leaf_index, leaf_distance ); return 1; } using PairNodePtrDistance = Kokkos::pair<Node const *, double>; struct CompareDistance { KOKKOS_INLINE_FUNCTION bool operator()( PairNodePtrDistance const &lhs, PairNodePtrDistance const &rhs ) { // reverse order (larger distance means lower priority) return lhs.second > rhs.second; } }; PriorityQueue<PairNodePtrDistance, CompareDistance> queue; // priority does not matter for the root since the node will be // processed directly and removed from the priority queue we don't even // bother computing the distance to it. Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); queue.push( root, 0. ); int count = 0; while ( !queue.empty() && count < k ) { // get the node that is on top of the priority list (i.e. is the // closest to the query point) Node const *node = queue.top().first; double const node_distance = queue.top().second; // NOTE: it would be nice to be able to do something like // tie( node, node_distance = queue.top(); queue.pop(); if ( TreeTraversal<DeviceType>::isLeaf( bvh, node ) ) { insert( TreeTraversal<DeviceType>::getIndex( bvh, node ), node_distance ); count++; } else { // insert children of the node in the priority list for ( Node const *child : {node->children.first, node->children.second} ) { double child_distance = distance( query_point, child->bounding_box ); queue.push( child, child_distance ); } } } return count; } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert, SpatialPredicateTag ) { return spatial_query( bvh, pred, insert ); } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert, NearestPredicateTag ) { return nearestQuery( bvh, pred._query_point, pred._k, insert ); } } // end namespace Details } // end namespace DataTransferKit #endif
31.632287
80
0.561242
flyingcat007
f0f058c70d3c3c2b34e72acbf78be9b844e025bb
788
cpp
C++
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
92
2019-01-23T23:02:31.000Z
2022-03-23T19:59:40.000Z
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto San Andreas) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CColDisk.h" // Converted from thiscall void CColDisk::Set(float startRadius,CVector const&start,CVector const&end,float endRadius,uchar material,uchar pieceType,uchar lighting) 0x40FD50 void CColDisk::Set(float startRadius, CVector const& start, CVector const& end, float endRadius, unsigned char material, unsigned char pieceType, unsigned char lighting) { plugin::CallMethod<0x40FD50, CColDisk *, float, CVector const&, CVector const&, float, unsigned char, unsigned char, unsigned char>(this, startRadius, start, end, endRadius, material, pieceType, lighting); }
65.666667
209
0.769036
MayconFelipeA
f0f3e273807c03960248ad61cc8e678f24cf06dc
78
hpp
C++
include/Pulsejet/Pulsejet.hpp
logicomacorp/pulsejet
ec73d19ccb71ff05b2122e258fe4b7b16e55fb53
[ "MIT" ]
30
2021-06-07T20:25:48.000Z
2022-03-30T00:52:38.000Z
include/Pulsejet/Pulsejet.hpp
going-digital/pulsejet
8452a0311645867d64c038cef7fdf751b26717ee
[ "MIT" ]
null
null
null
include/Pulsejet/Pulsejet.hpp
going-digital/pulsejet
8452a0311645867d64c038cef7fdf751b26717ee
[ "MIT" ]
1
2021-09-21T11:17:45.000Z
2021-09-21T11:17:45.000Z
#pragma once #include "Decode.hpp" #include "Encode.hpp" #include "Meta.hpp"
13
21
0.717949
logicomacorp
f0f4d31ae7f6da1fc55dcc061022c290329f8c54
724
cpp
C++
Array of objects.cpp
paurav11/Cpp
e8cc137d1530000898c9a92a98663a8a8b254068
[ "MIT" ]
1
2021-05-18T06:52:59.000Z
2021-05-18T06:52:59.000Z
Array of objects.cpp
paurav11/Cpp
e8cc137d1530000898c9a92a98663a8a8b254068
[ "MIT" ]
null
null
null
Array of objects.cpp
paurav11/Cpp
e8cc137d1530000898c9a92a98663a8a8b254068
[ "MIT" ]
null
null
null
#include <iostream> #include <conio.h> #include <stdlib.h> using namespace std; class student { char name[100]; int id,age; public: void getdata() { cout<<"\nEnter name: "; cin>>name; cout<<"Enter id: "; cin>>id; cout<<"Enter age: "; cin>>age; } void display() { cout<<"\nName: "<<name<<endl; cout<<"ID: "<<id<<endl; cout<<"Age: "<<age<<endl; } }; int main() { int i,n; cout<<"Enter no. of students: "; cin>>n; student s[n]; for(i=0;i<n;i++) { s[i].getdata(); } cout<<"\nStudent Details\n"; for(i=0;i<n;i++) { s[i].display(); } _getch(); return 0; }
15.73913
37
0.45442
paurav11
e7c8407173d6b4e707e9f2fdde5bfd73ab685257
14,476
cpp
C++
src/audio/CSoundMixer.cpp
rherriman/Avara
eaa68133ac273796b60162673b8f240619cb35ed
[ "MIT" ]
null
null
null
src/audio/CSoundMixer.cpp
rherriman/Avara
eaa68133ac273796b60162673b8f240619cb35ed
[ "MIT" ]
null
null
null
src/audio/CSoundMixer.cpp
rherriman/Avara
eaa68133ac273796b60162673b8f240619cb35ed
[ "MIT" ]
null
null
null
/* Copyright ©1994-1996, Juri Munkki All rights reserved. File: CSoundMixer.c Created: Friday, December 23, 1994, 08:25 Modified: Tuesday, August 20, 1996, 00:20 */ #include "CSoundMixer.h" #include "CBasicSound.h" #include "CSoundHub.h" #include "Memory.h" #include "System.h" #define DONT_USE_MINIMUM_VOLUME void AudioCallback(void *userData, uint8_t *stream, int size) { CSoundMixer *theMaster = (CSoundMixer *)userData; theMaster->DoubleBack(stream, size); } void CSoundMixer::StartTiming() { baseTime = SDL_GetTicks(); } int CSoundMixer::ReadTime() { return SDL_GetTicks() - baseTime; } void CSoundMixer::SetSoundEnvironment(Fixed speedOfSound, Fixed distanceToOne, int timeUnit) { if (speedOfSound) { soundSpeed = speedOfSound; distanceToSamples = (unsigned int)samplingRate / (unsigned int)soundSpeed; } if (timeUnit) { timeConversion = 65536L / timeUnit; } else { timeConversion = 65536; // Assume time unit is milliseconds. } if (distanceToOne) { distanceToLevelOne = distanceToOne; distanceToOne >>= 4; distanceAdjust = FMul(distanceToOne, distanceToOne); } if (stereo) maxAdjustedVolume = MAXADJUSTEDVOLUME; else maxAdjustedVolume = MAXADJUSTEDVOLUME / 2; } /* ** Since what you hear depends very much on what kind of environment ** is used to listen to the audio, two different stereo environments ** are provided. ** ** Strong stereo (strongStereo = true) is provided for users who have ** speakers. Since both ears can hear the sound from speakers, the ** stereo separation can be very clear as follows: ** ** Strong stereo: Sound position: LEFT MIDDLE RIGHT ** (Speakers) Left channel 1.0 0.5 0.0 ** Right channel 0.0 0.5 1.0 ** ** Users with headphones can only hear the left channel with the ** left ear and the right channel with the right ear. It seems the ** human hearing system doesn't like hearing sounds from just one ** ear (it gives me a headache), so even when the signal is coming ** from the left side, the channel will still play it at one third ** of the volume on the left and vice versa. ** ** Weak stereo: Sound position: LEFT MIDDLE RIGHT ** (Headphones) Left channel 1.0 0.66 0.33 ** Right channel 0.33 0.66 1.0 */ void CSoundMixer::SetStereoSeparation(Boolean strongFlag) { strongStereo = strongFlag; } void CSoundMixer::UpdateRightVector(Fixed *right) { // Lock with metaphor newRightMeta = false; newRight[0] = right[0]; newRight[1] = right[1]; newRight[2] = right[2]; // Announce that it is ok to access these. newRightMeta = true; } void CSoundMixer::ISoundMixer(Fixed sampRate, short maxChannelCount, short maxMixCount, Boolean stereoEnable, Boolean sample16Enable, Boolean interpolateEnable) { OSErr iErr; int globTemp; short i, j; Vector rightVect = {FIX(1), 0, 0, 0}; sample16flag = true; // TODO: bump this to 48khz? samplingRate = sampRate ? sampRate : rate22khz; if (samplingRate == rate22khz) { standardRate = FIX(1); } else { standardRate = FDivNZ(rate22050hz, samplingRate >> 1) >> 1; } soundBufferBits = BASESOUNDBUFFERBITS; if (samplingRate > rate22khz) { soundBufferBits++; } soundBufferSize = 1 << soundBufferBits; mixBuffers[0] = (WordSample *)NewPtr(2 * soundBufferSize * sizeof(WordSample)); mixBuffers[1] = mixBuffers[0] + soundBufferSize; frameTime = FMulDivNZ(soundBufferSize, FIX(500), samplingRate >> 1); SetSoundEnvironment(FIX(343), FIX(1), 1); UpdateRightVector(rightVect); motion.loc[0] = motion.loc[1] = motion.loc[2] = 0; motion.speed[0] = motion.speed[1] = motion.speed[2] = 0; motionLink = NULL; altLink = NULL; useAltLink = false; maxChannels = maxChannelCount; maxMix = maxMixCount; if (maxMix > maxChannels) maxMix = maxChannels; stereo = stereoEnable; strongStereo = false; hushFlag = false; infoTable = (MixerInfo *)NewPtr(sizeof(MixerInfo) * maxChannels); sortSpace[0] = (MixerInfo **)NewPtr(sizeof(MixerInfo *) * (maxChannels + 1) * 2); sortSpace[1] = sortSpace[0] + maxChannels + 1; for (i = 0; i < maxChannels; i++) { infoTable[i].intro = NULL; infoTable[i].introBackup = NULL; infoTable[i].active = NULL; infoTable[i].release = NULL; infoTable[i].volume = 0; infoTable[i].isFree = true; for (j = 0; j < 2; j++) sortSpace[j][i + 1] = &infoTable[i]; } if (sample16flag) { scaleLookup = NULL; #ifndef DONT_USE_MINIMUM_VOLUME if (soundCapabilities & gestalt16BitSoundIO) minimumVolume = 0; else minimumVolume = MINIMUM8BITVOLUME; #endif } else { PrepareScaleLookup(); #ifndef DONT_USE_MINIMUM_VOLUME minimumVolume = MINIMUM8BITVOLUME; #endif } volumeLookup = (SampleConvert *)NewPtr(sizeof(SampleConvert) * VOLUMERANGE); PrepareVolumeLookup(); sortSpace[0][0] = &dummyChannel; sortSpace[1][0] = &dummyChannel; dummyChannel.volume = 32767; volumeMax = VOLUMERANGE; StartTiming(); size_t bufferRAM = sizeof(WordSample) * 2 * soundBufferSize; doubleBuffers[0] = (WordSample *)malloc(bufferRAM); doubleBuffers[1] = (WordSample *)malloc(bufferRAM); SilenceBuffers(); frameCounter = -2; SDL_AudioSpec want, have; SDL_memset(&want, 0, sizeof(want)); want.freq = samplingRate / 65536; want.format = AUDIO_S16; want.channels = 2; want.samples = soundBufferSize; want.callback = AudioCallback; want.userdata = this; outputDevice = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0); SDL_Log("Sound device (id=%d): format=%d channels=%d samples=%d size=%d\n", outputDevice, want.format, want.channels, want.samples, want.size); SDL_PauseAudioDevice(outputDevice, 0); } void CSoundMixer::PrepareScaleLookup() { int i; int value; Sample *output; int scaleLookupSize; scaleLookupSize = sizeof(Sample) << (VOLUMEBITS + BITSPERSAMPLE - 1); scaleLookup = NewPtr(scaleLookupSize); output = (Sample *)scaleLookup; scaleLookupSize >>= 1; scaleLookupZero = scaleLookup + scaleLookupSize; for (i = -scaleLookupSize; i < scaleLookupSize; i++) { value = (i + (i >> 1)) >> (BITSPERSAMPLE + VOLUMEBITS - 10); value = (value + 257) >> 1; if (value > 255) value = 255; else if (value < 0) value = 0; *output++ = value; } } void CSoundMixer::PrepareVolumeLookup(uint8_t mixerVolume /* 0-100 */) { WordSample *dest; short vol, samp; dest = &volumeLookup[0][0]; if (sample16flag) { for (vol = 1; vol <= VOLUMERANGE; vol++) { for (samp = -SAMPLERANGE / 2; samp < SAMPLERANGE / 2; samp++) { *dest++ = (samp * vol * mixerVolume / 100) << (16 - BITSPERSAMPLE - VOLUMEBITS); } } } else { for (vol = 1; vol <= VOLUMERANGE; vol++) { for (samp = -SAMPLERANGE / 2; samp < SAMPLERANGE / 2; samp++) { *dest++ = (samp * vol * mixerVolume / 100); } } } } void CSoundMixer::SetVolume(uint8_t volume) { PrepareVolumeLookup(std::min(volume, uint8_t(100))); } void CSoundMixer::SilenceBuffers() { for (int j = 0; j < 2; j++) { size_t numChannels = 2; memset(doubleBuffers[j], 0, numChannels * soundBufferSize); } } void CSoundMixer::Dispose() { OSErr iErr; short i; MixerInfo *mix; SDL_PauseAudioDevice(outputDevice, 1); SDL_CloseAudioDevice(outputDevice); if (motionLink) { altLink = NULL; useAltLink = true; motionHub->ReleaseLink(motionLink); motionLink = NULL; } mix = infoTable; for (i = 0; i < maxChannels; i++) { if (mix->active) mix->active->Release(); else if (mix->release) mix->release->Release(); else if (mix->intro) mix->intro->Release(); mix++; } if (mixBuffers[0]) { DisposePtr((Ptr)mixBuffers[0]); mixBuffers[0] = NULL; } #define OBLITERATE(pointer) \ if (pointer) { \ DisposePtr((Ptr)pointer); \ pointer = NULL; \ } OBLITERATE(doubleBuffers[0]) OBLITERATE(doubleBuffers[1]) OBLITERATE(infoTable) OBLITERATE(volumeLookup) OBLITERATE(scaleLookup) OBLITERATE(sortSpace[0]) } void CSoundMixer::HouseKeep() { short i; MixerInfo *mix; mix = infoTable; for (i = 0; i < maxChannels; i++) { if (mix->release) { mix->release->Release(); mix->release = NULL; mix->isFree = true; } mix++; } } void CSoundMixer::AddSound(CBasicSound *theSound) { short i; MixerInfo *mix; mix = infoTable; for (i = 0; i < maxChannels; i++) { if (mix->isFree) { theSound->itsMixer = this; mix->isFree = false; mix->intro = theSound; mix->introBackup = theSound; return; } mix++; } // Couldn't find a free slot, so release the sound immediately. theSound->Release(); } void CSoundMixer::UpdateMotion() { SoundLink *aLink; frameStartTime = ReadTime(); frameEndTime = frameStartTime + frameTime; if (newRightMeta) { rightVector[0] = newRight[0]; rightVector[1] = newRight[1]; rightVector[2] = newRight[2]; newRightMeta = false; } if (useAltLink) aLink = altLink; else aLink = motionLink; if (aLink && (aLink->meta == metaNewData)) { Fixed *s, *d; Fixed t; s = aLink->nSpeed; d = aLink->speed; *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); s = aLink->nLoc; d = aLink->loc; *d++ = *s++; *d++ = *s++; *d++ = *s++; s = aLink->speed; d = aLink->loc; t = aLink->t; *d++ -= *s++ * t; *d++ -= *s++ * t; *d++ -= *s++ * t; aLink->meta = metaNoData; s = aLink->loc; d = motion.loc; *d++ = *s++; *d++ = *s++; *d++ = *s++; s = aLink->speed; d = motion.speed; *d++ = *s++; *d++ = *s++; *d++ = *s++; } } #define DEBUGSOUNDno #ifdef DEBUGSOUND short gDebugMixCount; #endif void CSoundMixer::DoubleBack(uint8_t *stream, int size) { short i; MixerInfo *mix; MixerInfo **sort, **inSort; int volumeTotal; short whichStereo; // SDL_Log("CSoundMixer::DoubleBack wants %d bytes, soundBufferSize=%d\n", size, soundBufferSize); SDL_memset(stream, 0, size); UpdateMotion(); frameCounter++; mixTo[0] = mixBuffers[0]; mixTo[1] = mixBuffers[1]; // Will never actually be touched by monophonic sounds. memset(mixTo[0], 0, soundBufferSize * sizeof(WordSample)); memset(mixTo[1], 0, soundBufferSize * sizeof(WordSample)); /* ** Activate new channels. */ mix = infoTable; i = maxChannels; do { if (mix->intro && mix->intro == mix->introBackup) { mix->active = mix->intro; mix->intro = NULL; mix->introBackup = NULL; mix->active->FirstFrame(); } mix++; } while (--i); #ifdef DEBUGSOUND gDebugMixCount = 0; #endif for (whichStereo = 0; whichStereo <= stereo; whichStereo++) { short volumeLimit = 0; /* ** Go through channels, asking the volume for this side. */ mix = infoTable; i = maxChannels; do { if (mix->active) { volumeLimit += (mix->volume = mix->active->CalcVolume(whichStereo)); } mix++; } while (--i); volumeLimit >>= 5; if (volumeLimit) { mix = infoTable; i = maxChannels; do { if (mix->active && volumeLimit > mix->volume) { mix->volume = 0; } mix++; } while (--i); } /* ** Insertion sort according to volume. */ sort = sortSpace[whichStereo] + 2; i = maxChannels; while (--i) { inSort = sort++; while (inSort[-1]->volume < inSort[0]->volume) { mix = inSort[0]; inSort[0] = inSort[-1]; inSort[-1] = mix; inSort--; } } /* ** Select as many of the loudest sounds that fit. */ volumeTotal = 0; sort = sortSpace[whichStereo] + 1; i = maxMix; do { mix = *sort; if (mix->volume) { volumeTotal += mix->volume; if (volumeTotal >= volumeMax) { mix->volume += volumeMax - volumeTotal; if (mix->volume) sort++; volumeTotal = volumeMax; break; } } else break; sort++; } while (--i); sort--; while (volumeTotal > 0) { mix = *sort--; volumeTotal -= mix->volume; mix->active->WriteFrame(whichStereo, mix->volume); #ifdef DEBUGSOUND gDebugMixCount++; #endif } } mix = infoTable; i = maxChannels; if (hushFlag) { do { if (mix->active) { mix->release = mix->active; mix->active = NULL; mix->volume = 0; } mix++; } while (--i); hushFlag = false; } else { do { if (mix->active && mix->active->EndFrame()) { mix->release = mix->active; mix->active = NULL; mix->volume = 0; } mix++; } while (--i); } InterleaveStereoChannels(mixTo[0], mixTo[1], (WordSample *)stream, soundBufferSize); }
25.396491
102
0.550843
rherriman
e7c8958dc2beaffff8a59eb2d4072ef8b2a3bd22
1,114
cpp
C++
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
1
2022-02-11T12:49:49.000Z
2022-02-11T12:49:49.000Z
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
null
null
null
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
null
null
null
#include "index_buffer.h" #include "staging_buffer.h" #include "gfx/graphics.h" #include "gfx/buffers/command_buffer.h" IndexBuffer::IndexBuffer(const void* data, VkDeviceSize count, IndexType index_type, VmaMemoryUsage memory_usage) : Buffer(count * indexTypeSize(index_type), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, memory_usage), index_type(index_type) { setData(data, count * indexTypeSize(index_type)); } void IndexBuffer::bind(VkDeviceSize offset) { Graphics::getActiveCommandBuffer().bindIndexBuffer(buffer, offset, indexType(index_type)); } VkIndexType IndexBuffer::indexType(IndexType index_type) { switch (index_type) { case IndexType::UINT16: return VK_INDEX_TYPE_UINT16; case IndexType::UINT32: return VK_INDEX_TYPE_UINT32; } SK_ERROR("Unsupported index type specified: {0}.", index_type); return VkIndexType(0); } size_t IndexBuffer::indexTypeSize(IndexType index_type) { switch (index_type) { case IndexType::UINT16: return 2; case IndexType::UINT32: return 4; } SK_ERROR("Unsoppurted index type specified: {0}.", index_type); return 0; }
26.52381
113
0.777379
GeorgeAzma
e7cb1b6abec8324c260fbf8ecc7489fc23aa1f9f
780
cpp
C++
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
// CharacterCounting.cpp // Programa para contar los caracteres contenidos en un string #include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { char str[100]; int i, j, n, k, o; i=0; j=0; k=0; o=0; puts("Introduce una frase"); gets(str); n=strlen(str); while(str[i]!='\0') { if((str[i]>=65) &&(str[i]<97)) j++; if((str[i]>=97) &&(str[i]<122)) k++; if(str[i]==' ') o++; i++; } std::cout << "El numero total de letras es: " << n << std::endl; std::cout << "El numero de letras mayusculas es: " << j << std::endl; std::cout << "El numero de letras minusculas es: " << k << std::endl; std::cout << "El numero de espacios en blanco es: " << o << std::endl; system("pause"); return 0; }
16.595745
71
0.553846
Gabroide
e7d5a48fc6a783714974803c80fcd00436f6473c
3,002
cpp
C++
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
1
2016-10-21T08:14:26.000Z
2016-10-21T08:14:26.000Z
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
null
null
null
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
null
null
null
#include "gui/qrsystemtray.h" #include <QtCore/qdebug.h> #include <QtCore/qmap.h> #include <QtWidgets/qsystemtrayicon.h> #include <QtWidgets/qaction.h> #include <QtWidgets/qmenu.h> #include <QtWidgets/qapplication.h> #include "db/qrtblsystemtray.h" #include "db/qrtblframeconfig.h" NS_CHAOS_BASE_BEGIN class QrSystemTrayPrivate{ QR_DECLARE_PUBLIC(QrSystemTray) public: static QrSystemTrayPrivate *dInstance(); public: QrSystemTrayPrivate(QWidget* parent); ~QrSystemTrayPrivate(); bool initTray(); QAction *getAction(const QString& key); public: QWidget* parent; QMenu trayMenu; QSystemTrayIcon systemTray; QMap<QString, QAction*> actions; public: static QrSystemTray* qInstance; }; QrSystemTray* QrSystemTrayPrivate::qInstance = nullptr; QrSystemTrayPrivate *QrSystemTrayPrivate::dInstance(){ Q_ASSERT(nullptr != QrSystemTrayPrivate::qInstance); return QrSystemTrayPrivate::qInstance->d_func(); } QrSystemTrayPrivate::QrSystemTrayPrivate(QWidget *parent) : parent(parent) {} QrSystemTrayPrivate::~QrSystemTrayPrivate() {} QAction *QrSystemTrayPrivate::getAction(const QString &key) { Q_ASSERT(actions.contains(key)); return actions[key]; } bool QrSystemTrayPrivate::initTray() { QVector<QrSystemlTrayData> trayDatas; if (! QrTbSystemlTrayHelper::getTrayList(&trayDatas)) { return false; } QMap<QString, QString> systemtrayValues; if (! Qters::QrFrame::QrTblFrameConfigHelper::getKeyValuesByType("systemtray", &systemtrayValues)) { return false; } if ("false" == systemtrayValues["use"]) { qDebug() << "database config deside not use system tray"; return false; } systemTray.setIcon(QIcon(systemtrayValues["icon"])); systemTray.setToolTip(systemtrayValues["tooltip"]); trayMenu.clear(); Q_FOREACH(QrSystemlTrayData data, trayDatas) { auto action = new QAction(data.text, parent); action->setIcon(QIcon(data.icon)); if (! data.visible) { action->setVisible(false); } trayMenu.addAction(action); actions[data.key] = action; if (data.separator) { trayMenu.addSeparator(); } } systemTray.setContextMenu(&trayMenu); systemTray.show(); QObject::connect( qApp, &QApplication::aboutToQuit, [this](){ systemTray.hide(); }); return true; } NS_CHAOS_BASE_END USING_NS_CHAOS_BASE; QrSystemTray::QrSystemTray(QWidget* parent) :d_ptr(new QrSystemTrayPrivate(parent)) { QrSystemTrayPrivate::qInstance = this; d_ptr->initTray(); } bool QrSystemTray::qrconnect(const QString &key, const QObject *receiver, const char *member) { auto action = QrSystemTrayPrivate::dInstance()->getAction(key); if (nullptr == action) { return false; } QObject::connect(action, SIGNAL(triggered(bool)), receiver, member); return true; }
24.606557
104
0.675217
Qters
e7d5fe6d99e8f0be14b02a2fecc0be859f659a67
181
cpp
C++
src/test/resources/cpp/function_ptr.cpp
shahrzadav/codyze
c075e8c874f8bef52037d3538166150a488f1607
[ "Apache-2.0" ]
58
2020-04-18T19:26:32.000Z
2022-03-23T20:37:18.000Z
src/test/resources/cpp/function_ptr.cpp
shahrzadav/codyze
c075e8c874f8bef52037d3538166150a488f1607
[ "Apache-2.0" ]
409
2020-04-06T08:29:20.000Z
2022-03-31T17:46:54.000Z
src/test/resources/cpp/function_ptr.cpp
shahrzadav/codyze
c075e8c874f8bef52037d3538166150a488f1607
[ "Apache-2.0" ]
13
2020-05-04T05:36:02.000Z
2022-01-29T09:24:16.000Z
#include <iostream> class A { public: void fun() { std::cout << "Hello" << std::endl; } }; int main() { A a; void (A::* f_ptr) () = &A::fun; (a.*f_ptr)(); }
12.066667
40
0.453039
shahrzadav
e7d68cfba12d0c5cc12915b0739af0e174083928
6,140
cpp
C++
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
2
2018-01-14T17:47:22.000Z
2021-11-15T10:34:24.000Z
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
23
2017-07-31T19:43:00.000Z
2018-11-11T18:51:28.000Z
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
null
null
null
#include "PG/physics/PhysicsWorld.h" #include "PG/physics/PhysicsBody.h" #include "PG/app/GameConstants.h" #include "PG/entities/TilePositionCalculator.h" #include "PG/core/RectUtils.h" #include "PG/core/PointUtils.h" #include "PG/core/SizeUtils.h" #include "PG/core/MathsUtils.h" #include <array> namespace PG { namespace { const size_t kNumCoordsToTest = 9; using TileCoordsToTest = std::array<TileCoord, kNumCoordsToTest>; //-------------------------------------------------------- TileCoordsToTest getCollisionTestCoords(const TileCoord& bodyTileCoord) { TileCoordsToTest coordsToTest; for (auto& coordToTest : coordsToTest) { coordToTest = bodyTileCoord; } auto coordToTestIt = coordsToTest.begin(); // Aligned points ++coordToTestIt; coordToTestIt->y -= 1; ++coordToTestIt; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x -= 1; ++coordToTestIt; coordToTestIt->x += 1; // Diagonal points ++coordToTestIt; coordToTestIt->x -= 1; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x += 1; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x -= 1; coordToTestIt->y -= 1; ++coordToTestIt; coordToTestIt->x += 1; coordToTestIt->y -= 1; return coordsToTest; } // Don't allow passing through tiles // Better detection of whether collision is above/below or left/right? //-------------------------------------------------------- void findIntersectionAndResolveForBody(PhysicsBody& body, const Rect& geometryRect) { const Rect desiredRect(body.desiredPosition, body.bounds.size); const auto intersection = RectUtils::getIntersection(desiredRect, geometryRect); if (!RectUtils::isEmpty(intersection)) { Point removeIntersectionPt; Point adjustedVelocity; if (intersection.size.height < intersection.size.width) { const bool collisionBelow = (desiredRect.origin.y <= geometryRect.origin.y); if (collisionBelow) { body.hasHitGround(); } const int dir = collisionBelow ? -1 : 1; removeIntersectionPt = Point(0, dir * intersection.size.height); adjustedVelocity = Point(body.velocity.x, 0); } else { const int dir = (desiredRect.origin.x < geometryRect.origin.x) ? -1 : 1; removeIntersectionPt = Point(dir * intersection.size.width, 0); adjustedVelocity = Point(0, body.velocity.y); } body.velocity = adjustedVelocity; body.desiredPosition = PointUtils::addPoints(body.desiredPosition, removeIntersectionPt); } } //-------------------------------------------------------- void resolveCollisionAtCoord(const TileCoord& coordToTest, const DataGrid<bool>& levelGeometry, PhysicsBody& body) { if (coordToTest.x < 0 || coordToTest.x >= levelGeometry.getWidth() || coordToTest.y < 0 || coordToTest.y >= levelGeometry.getHeight() || !levelGeometry.at(coordToTest.x, coordToTest.y)) { return; } TilePositionCalculator tilePosCalc; const Rect tileRect(tilePosCalc.calculatePoint(coordToTest), Size(GameConstants::tileSize(), GameConstants::tileSize())); findIntersectionAndResolveForBody(body, tileRect); } //-------------------------------------------------------- void applyForcesToBody(PhysicsBody& body, const PhysicsWorldParams& params, float dt) { const auto gravityStep = SizeUtils::scaleSize(params.gravity, dt); const auto forwardStep = PointUtils::scalePoint(params.forward, dt); // Gravity and X friction followed by movement if (!body.isFreeMoving) { body.velocity = PointUtils::addToPoint(body.velocity, gravityStep); body.velocity = Point(body.velocity.x * params.friction, body.velocity.y); if (body.jumpToConsume && body.onGround) { body.velocity = PointUtils::addPoints(body.velocity, params.jumpForce); body.jumpToConsume = false; body.onGround = false; } } else { body.velocity = Point(body.velocity.x * params.friction, body.velocity.y * params.friction); if (body.movingUp) { body.velocity = PointUtils::subtractPoints(body.velocity, PointUtils::swapValues(forwardStep)); } if (body.movingDown) { body.velocity = PointUtils::addPoints(body.velocity, PointUtils::swapValues(forwardStep)); } } // Horizontal movement always the same if (body.movingRight) { body.velocity = PointUtils::addPoints(body.velocity, forwardStep); } if (body.movingLeft) { body.velocity = PointUtils::subtractPoints(body.velocity, forwardStep); } // Clamp velocity auto clampedVelX = MathsUtils::clamp(body.velocity.x, params.minMovement.x, params.maxMovement.x); auto clampedVelY = MathsUtils::clamp(body.velocity.y, params.minMovement.y, params.maxMovement.y); body.velocity = Point(clampedVelX, clampedVelY); // Apply velocity auto velocityStep = PointUtils::scalePoint(body.velocity, dt); body.desiredPosition = PointUtils::addPoints(body.bounds.origin, velocityStep); } } //-------------------------------------------------------- void PhysicsWorld::applyPhysicsForBody(PhysicsBody& body, const DataGrid<bool>& levelGeometry, float dt) const { applyForcesToBody(body, m_Params, dt); TilePositionCalculator tilePosCalc; const auto bodyTileCoord = tilePosCalc.calculateTileCoord(body.desiredPosition); // Collision detection const auto coordsToTest = getCollisionTestCoords(bodyTileCoord); for (size_t i = 0; i < coordsToTest.size(); ++i) { resolveCollisionAtCoord(coordsToTest[i], levelGeometry, body); } // Apply updated desired position body.setPosition(body.desiredPosition); } //-------------------------------------------------------- void PhysicsWorld::findCollisionsWithBody(const PhysicsBody& body, const std::vector<PhysicsBody>& bodiesToCheck, PhysicsWorldCallback& callback) const { for (size_t nthBody = 0; nthBody < bodiesToCheck.size(); ++nthBody) { if (!RectUtils::isEmpty(RectUtils::getIntersection(body.bounds, bodiesToCheck[nthBody].bounds))) { callback.bodiesDidCollide(body, bodiesToCheck[nthBody], (int)nthBody); } } } }
29.238095
123
0.669055
mcdreamer
e7d6cb36c09282359e3ab5b7cc06ba1989389fd0
1,269
cxx
C++
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
4
2020-12-14T18:07:28.000Z
2021-04-21T18:10:26.000Z
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
11
2020-07-21T03:27:10.000Z
2021-03-22T20:24:44.000Z
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
3
2020-12-14T17:40:07.000Z
2022-03-18T15:43:10.000Z
#include <apex/sqlite/connection.hpp> #include <apex/sqlite/memory.hpp> #include <apex/sqlite/table.hpp> #include <apex/sqlite/error.hpp> #include <apex/core/memory.hpp> #include <apex/memory/out.hpp> #include <sqlite3.h> namespace apex::sqlite { void default_delete<sqlite3>::operator () (sqlite3* ptr) noexcept { sqlite3_close_v2(ptr); } //connection::connection (::std::filesystem::path const& path) noexcept(false) : // resource_type { } //{ // sqlite3_open_v2(path.c_str(), out_ptr(static_cast<resource_type&>(*this)), SQLITE_OPEN_READONLY, nullptr); // throw ::std::runtime_error("Not yet implemented"); //} void plugin (connection& conn, std::string_view name, std::shared_ptr<table> item) noexcept(false) { auto destructor = [] (void* ptr) noexcept { auto pointer = static_cast<std::shared_ptr<table>*>(ptr); apex::destroy_at(pointer); deallocate(pointer); }; auto db = conn.get(); auto module = item->module(); auto aux = ::new (allocate(sizeof(item))) std::shared_ptr<table>(item); if (not aux) { throw std::system_error(error::not_enough_memory); } auto result = sqlite3_create_module_v2(db, name.data(), module, aux, destructor); if (result) { throw std::system_error(error(result)); } } } /* namespace apex::sqlite */
34.297297
110
0.704492
slurps-mad-rips
e7d95f2a857ad6a08d8098f6ce262a5ba9c33277
1,669
cpp
C++
Code/peek_recv.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
Code/peek_recv.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
Code/peek_recv.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
/** @author heweibright@gmail.com * @date 2021/9/3 11:06 * Copyright (c) All rights reserved. */ #include <iostream> #include <unistd.h> #include <cstdlib> #include <cstring> #include <sys/socket.h> #include <arpa/inet.h> const int BUF_SIZE = 1024; void error_handling(const char *msg) { std::cerr << msg << '\n'; std::terminate(); } int main(int argc, char *argv[]) { if (argc != 2) { std::cout << "Usage: " << argv[0] << " <port>\n"; std::terminate(); } int acpt_sock, recv_sock; struct sockaddr_in acpt_addr; if ((acpt_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) error_handling("socket() error"); memset(&acpt_addr, 0, sizeof(acpt_addr)); acpt_addr.sin_family = PF_INET; acpt_addr.sin_addr.s_addr = htonl(INADDR_ANY); acpt_addr.sin_port = htons(atoi(argv[1])); if (bind(acpt_sock, reinterpret_cast<sockaddr *>(&acpt_addr), sizeof(acpt_addr)) == -1) error_handling("bind() error"); if (listen(acpt_sock, 5) == -1) error_handling("listen() error"); if ((recv_sock = accept(acpt_sock, 0, 0)) == -1) error_handling("accept() error"); ssize_t len; char buf[BUF_SIZE]; while ((len = recv(recv_sock, buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT)) != -1 && len == 0); if (len == -1) error_handling("recv() error"); buf[len] = '\0'; std::cout << "Buffering " << len << " bytes: " << buf << '\n'; if ((len = recv(recv_sock, buf, sizeof(buf), 0)) == -1) error_handling("recv() error"); buf[len] = '\0'; std::cout << "Read again: " << buf << '\n'; close(acpt_sock); close(recv_sock); return 0; }
27.816667
97
0.584781
hewei-nju
e7dab0aec55c610adbe8dc2f3a51df4ee13a9827
17,150
cpp
C++
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
8
2020-04-22T09:46:14.000Z
2022-03-17T00:09:38.000Z
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
1
2020-08-11T07:24:14.000Z
2020-10-05T12:47:05.000Z
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
null
null
null
// This file is part of the Robotic Template Library (RTL), a C++ // template library for usage in robotic research and applications // under the MIT licence: // // Copyright 2020 Brno University of Technology // // 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. // // Contact person: Ales Jelinek <Ales.Jelinek@ceitec.vutbr.cz> #include <gtest/gtest.h> #include <rtl/Transformation.h> #include <rtl/Test.h> #include <vector> #include <typeinfo> #include <iostream> #include <chrono> #include "tf_test/key_generator.h" #include "tf_test/tf_comparison.h" #include "rtl/io/StdLib.h" TEST(t_tf_tree, key_generator) { rtl::test::Types<TestKeyGenerator, TYPES> keyGenTest(static_cast<size_t>(10)); } ////////////////////////// /// Tests ////////////////////////// template<int N, typename dtype, typename T> struct TestInit { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); tree.clear(); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); } }; TEST(t_tf_tree, init) { [[maybe_unused]]auto keyGenTest = rtl::test::RangeTypesTypes<TestInit, 2, 4, float, double>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestConstructors { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_copy(origin); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); auto tree_copy_root_address = &tree_copy.root(); ASSERT_TRUE(&tree.root() != tree_copy_root_address); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_move(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>{origin}); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); } }; TEST(t_tf_tree, constructors) { [[maybe_unused]]auto constructorTests = rtl::test::RangeTypesTypes<TestConstructors, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> void fill_tree_insert(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>& tree, std::vector<T> keys) { auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); for (size_t i = 1 ; i < keys.size() ; i++) { auto tf = rtl::RigidTfND<N, dtype>::random(generator); tree.insert(keys.at(i), tf, keys.at(i-1)); auto tf2 = tree.at(keys.at(i)).tf(); bool res = CompareTfsEqual<N, dtype>(tf, tf2); ASSERT_EQ(res, true); } } template<int N, typename dtype, typename T> struct TestInsert { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); } }; TEST(t_tf_tree, insert) { [[maybe_unused]]auto insertTest = rtl::test::RangeTypesTypes<TestInsert, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestClear { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); tree.clear(); // root should stay ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); } }; TEST(t_tf_tree, clear) { [[maybe_unused]]auto clearTest = rtl::test::RangeTypesTypes<TestClear, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestContains { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); for (size_t i = 1 ; i < keys.size() ; i++) { ASSERT_EQ(tree.contains(keys.at(i)), false); } fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); for (const auto& key : keys) { ASSERT_EQ(tree.contains(key), true); } } }; TEST(t_tf_tree, contains) { [[maybe_unused]]auto containsTest = rtl::test::RangeTypesTypes<TestContains, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestErase { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); for (typename std::vector<T>::iterator it = keys.end() - 1; it > keys.begin(); it--) { tree.erase(*it); } ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); { size_t i = 0; for (typename std::vector<T>::iterator it = keys.end() - 1; it > keys.begin(); it--) { ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size() - i); tree.erase(*it); for (typename std::vector<T>::iterator it2 = (keys.end() - 1); it2 > keys.begin(); it2--) { if (it2 >= it){ ASSERT_EQ(tree.contains(*it2), false); } else { ASSERT_EQ(tree.contains(*it2), true); } } i++; } } } }; TEST(t_tf_tree, erase) { [[maybe_unused]]auto eraseTest = rtl::test::RangeTypesTypes<TestErase, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestErase2 { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); tree.erase(keys.at(1)); for (size_t i = 0 ; i < keys.size() ; i++) { if (i > 0) { ASSERT_EQ(tree.contains(keys.at(i)), false); } else { ASSERT_EQ(tree.contains(keys.at(i)), true); } } } }; TEST(t_tf_tree, erase_2) { [[maybe_unused]]auto erase2Test = rtl::test::RangeTypesTypes<TestErase2, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct RootTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); ASSERT_EQ(tree.root().key(), origin); ASSERT_EQ(tree.root().children().size(), 0); ASSERT_EQ(tree.root().depth(), 0); ASSERT_EQ(tree.root().key() , tree.root().parent()->key()); } }; TEST(t_tf_tree, root) { [[maybe_unused]]auto rootTest = rtl::test::RangeTypesTypes<RootTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct AtTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); for (const auto& key : keys) { ASSERT_EQ(tree.at(key).key(), key); ASSERT_EQ(tree[key].key(), key); ASSERT_EQ( &tree[key], &tree.at(key)); } } }; TEST(t_tf_tree, at) { [[maybe_unused]]auto atTest = rtl::test::RangeTypesTypes<AtTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TreeStructureTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); fill_tree_insert(tree, keys); for (size_t i = 0 ; i < keys.size() ; i++) { auto& node1 = tree.at(keys.at(i)); auto& node2 = tree[keys.at(i)]; ASSERT_EQ( &node1, &node2); ASSERT_EQ( node1.depth(), i); if(i > 0) { const auto& parent = tree[keys.at(i-1)]; auto node_parent = node1.parent(); ASSERT_EQ( node_parent, &parent); } } } }; TEST(t_tf_tree, tree_structure) { [[maybe_unused]]auto treeStructureTest = rtl::test::RangeTypesTypes<TreeStructureTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestTfFromTo { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); auto tf1 = rtl::RigidTfND<N, dtype>::random(generator); auto tf2 = rtl::RigidTfND<N, dtype>::random(generator); auto tf3 = rtl::RigidTfND<N, dtype>::random(generator); auto tf4 = rtl::RigidTfND<N, dtype>::random(generator); auto tf5 = rtl::RigidTfND<N, dtype>::random(generator); auto tf6 = rtl::RigidTfND<N, dtype>::random(generator); auto tf7 = rtl::RigidTfND<N, dtype>::random(generator); auto tf8 = rtl::RigidTfND<N, dtype>::random(generator); auto tf9 = rtl::RigidTfND<N, dtype>::random(generator); /* * * / tf2 - tf5 - tf9 * / \ tf6 * origin * \ * \ tf1 - tf3 - tf7 * \ \ tf8 * \ tf4 */ tree.insert(key_1, tf1, origin); tree.insert(key_2, tf2, origin); tree.insert(key_3, tf3, key_1); tree.insert(key_4, tf4, key_1); tree.insert(key_5, tf5, key_2); tree.insert(key_6, tf6, key_2); tree.insert(key_7, tf7, key_3); tree.insert(key_8, tf8, key_3); tree.insert(key_9, tf9, key_5); auto identity = rtl::RigidTfND<N, dtype>::identity(); auto tfChain = tree.tf(key_8, key_9); std::cout << tf1 << std::endl; auto cumulated = tfChain(identity); auto cumulated2 = tf9(tf5(tf2(tf1.inverted()(tf3.inverted()(tf8.inverted()))))); ASSERT_EQ(CompareTfsEqual(cumulated, cumulated2), true); } }; TEST(t_tf_tree, tree_tf_from_to) { [[maybe_unused]]auto tfFromToTest = rtl::test::RangeTypesTypes<TestTfFromTo, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct APITest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_copy(tree); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_move(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>{origin}); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); tree_copy.clear(); tree_move.clear(); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); tree_copy = tree; tree_move = rtl::TfTree<T, rtl::RigidTfND<N, dtype>>(origin); ASSERT_EQ(tree.contains(key_1), false); tree.insert(key_1, rtl::RigidTfND<N, dtype>::identity(), origin); ASSERT_EQ(tree.contains(key_1), true); tree.erase(key_1); ASSERT_EQ(tree.contains(key_1), false); ASSERT_EQ(tree.root().key(), origin); auto new_tf = rtl::RigidTfND<N, dtype>::identity(); tree[origin].tf() = new_tf; tree.at(origin).tf() = new_tf; auto rootNode_1 = tree[origin]; auto rootNode_2 = tree[origin]; auto rootNode_3 = tree.at(origin); auto rootNode_4 = tree.at(origin); tree.clear(); ASSERT_EQ(tree.root().key(), origin); } }; TEST(t_tf_tree, api_test) { [[maybe_unused]]auto apiTest = rtl::test::RangeTypesTypes<APITest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename K> struct GeneralTFTest { static void testFunction() { auto keyGen = KeysGenerator<K>{keyN}; auto keys = keyGen.generateKyes(); auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); using General3DTf = rtl::GeneralTf<rtl::RigidTfND<3,double>, rtl::TranslationND<3, double>, rtl::RotationND<3, double>>; rtl::TfTree<std::string, General3DTf> generalTree{origin}; auto rigid = rtl::RigidTfND<3, double>::random(generator); auto rot = rtl::RotationND<3, double>::random(generator); auto trans = rtl::TranslationND<3, double>::random(generator); /* origin / \ trans rot / \ 1 2 / rigidTf / 3 */ generalTree.insert(key_1, trans, origin); generalTree.insert(key_2, rot, origin); generalTree.insert(key_3, rigid, key_1); auto chain_3_2 = generalTree.tf(key_3, key_2); auto tf_3_2 = rot(trans.inverted()(rigid.inverted())); ASSERT_EQ(CompareTfsEqual((rtl::RigidTfND<3, double>) chain_3_2.squash(), tf_3_2 ), true); } }; TEST(t_tf_tree, generalTfTest) { [[maybe_unused]]auto generalTfTests = rtl::test::RangeTypesTypes<GeneralTFTest, RANGE_AND_DTYPES>::with<std::string>{}; } TEST(t_tf_tree, str_cmp_vs_stc_hash) { auto keyGen = KeysGenerator<std::string>{2}; auto keys = keyGen.generateKyes(); auto a = origin; auto b = key_1; auto t1 = std::chrono::high_resolution_clock::now(); for(size_t i = 0 ; i < 10000000 ; i++) { if( a == b ) {} } auto t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); std::cout << "Str cmp duration: " << duration << " ms" << std::endl; auto hasher = std::hash<std::string>{}; t1 = std::chrono::high_resolution_clock::now(); for(size_t i = 0 ; i < 10000000 ; i++) { auto ha = hasher(a); auto hb = hasher(b); if( ha == hb ) {} } t2 = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); std::cout << "Str hash and int cmp duration: " << duration << " ms" << std::endl;; } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
31.181818
128
0.593703
Robotics-BUT
e7dc104fac5aba661f0f9a7f0b3db94052f413c2
10,700
hxx
C++
main/sc/source/filter/inc/xelink.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sc/source/filter/inc/xelink.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sc/source/filter/inc/xelink.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SC_XELINK_HXX #define SC_XELINK_HXX #include "markdata.hxx" #include "xllink.hxx" #include "xerecord.hxx" #include "xehelper.hxx" #include "xeformula.hxx" #include "externalrefmgr.hxx" class ScRange; struct ScSingleRefData; struct ScComplexRefData; /* ============================================================================ Classes for export of different kinds of internal/external references. - 3D cell and cell range links - External cell and cell range links - External defined names - Macro calls - Add-in functions - DDE links - OLE object links ============================================================================ */ // Excel sheet indexes ======================================================== /** Stores the correct Excel sheet index for each Calc sheet. @descr The class knows all sheets which will not exported (i.e. external link sheets, scenario sheets). */ class XclExpTabInfo : protected XclExpRoot { public: /** Initializes the complete buffer from the current exported document. */ explicit XclExpTabInfo( const XclExpRoot& rRoot ); /** Returns true, if the specified Calc sheet will be exported. */ bool IsExportTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is used to store external cell contents. */ bool IsExternalTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is visible and will be exported. */ bool IsVisibleTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is selected and will be exported. */ bool IsSelectedTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is the displayed (active) sheet. */ bool IsDisplayedTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is displayed in right-to-left mode. */ bool IsMirroredTab( SCTAB nScTab ) const; /** Returns the Calc name of the specified sheet. */ const String& GetScTabName( SCTAB nScTab ) const; /** Returns the Excel sheet index for a given Calc sheet. */ sal_uInt16 GetXclTab( SCTAB nScTab ) const; /** Returns the Calc sheet index of the nSortedTab-th entry in the sorted sheet names list. */ SCTAB GetRealScTab( SCTAB nSortedScTab ) const; //UNUSED2009-05 /** Returns the index of the passed Calc sheet in the sorted sheet names list. */ //UNUSED2009-05 SCTAB GetSortedScTab( SCTAB nScTab ) const; /** Returns the number of Calc sheets. */ inline SCTAB GetScTabCount() const { return mnScCnt; } /** Returns the number of Excel sheets to be exported. */ inline sal_uInt16 GetXclTabCount() const { return mnXclCnt; } /** Returns the number of external linked sheets. */ inline sal_uInt16 GetXclExtTabCount() const { return mnXclExtCnt; } /** Returns the number of exported selected sheets. */ inline sal_uInt16 GetXclSelectedCount() const { return mnXclSelCnt; } /** Returns the Excel index of the active, displayed sheet. */ inline sal_uInt16 GetDisplayedXclTab() const { return mnDisplXclTab; } /** Returns the Excel index of the first visible sheet. */ inline sal_uInt16 GetFirstVisXclTab() const { return mnFirstVisXclTab; } private: /** Returns true, if any of the passed flags is set for the specified Calc sheet. */ bool GetFlag( SCTAB nScTab, sal_uInt8 nFlags ) const; /** Sets or clears (depending on bSet) all passed flags for the specified Calc sheet. */ void SetFlag( SCTAB nScTab, sal_uInt8 nFlags, bool bSet = true ); /** Searches for sheets not to be exported. */ void CalcXclIndexes(); /** Sorts the names of all tables and stores the indexes of the sorted indexes. */ void CalcSortedIndexes(); private: /** Data structure with infoemation about one Calc sheet. */ struct XclExpTabInfoEntry { String maScName; sal_uInt16 mnXclTab; sal_uInt8 mnFlags; inline explicit XclExpTabInfoEntry() : mnXclTab( 0 ), mnFlags( 0 ) {} }; typedef ::std::vector< XclExpTabInfoEntry > XclExpTabInfoVec; typedef ::std::vector< SCTAB > ScTabVec; XclExpTabInfoVec maTabInfoVec; /// Array of Calc sheet index information. SCTAB mnScCnt; /// Count of Calc sheets. sal_uInt16 mnXclCnt; /// Count of Excel sheets to be exported. sal_uInt16 mnXclExtCnt; /// Count of external link sheets. sal_uInt16 mnXclSelCnt; /// Count of selected and exported sheets. sal_uInt16 mnDisplXclTab; /// Displayed (active) sheet. sal_uInt16 mnFirstVisXclTab; /// First visible sheet. ScTabVec maFromSortedVec; /// Sorted Calc sheet index -> real Calc sheet index. ScTabVec maToSortedVec; /// Real Calc sheet index -> sorted Calc sheet index. }; // Export link manager ======================================================== class XclExpLinkManagerImpl; /** Stores all data for internal/external references (the link table). */ class XclExpLinkManager : public XclExpRecordBase, protected XclExpRoot { public: explicit XclExpLinkManager( const XclExpRoot& rRoot ); virtual ~XclExpLinkManager(); /** Searches for an EXTERNSHEET index for the given Calc sheet. @descr See above for the meaning of EXTERNSHEET indexes. @param rnExtSheet (out-param) Returns the EXTERNSHEET index. @param rnXclTab (out-param) Returns the Excel sheet index. @param nScTab The Calc sheet index to process. param pRefLogEntry If not 0, data about the external link is stored here. */ void FindExtSheet( sal_uInt16& rnExtSheet, sal_uInt16& rnXclTab, SCTAB nScTab, XclExpRefLogEntry* pRefLogEntry = 0 ); /** Searches for an EXTERNSHEET index for the given Calc sheet range. @descr See above for the meaning of EXTERNSHEET indexes. @param rnExtSheet (out-param) Returns the EXTERNSHEET index. @param rnFirstXclTab (out-param) Returns the Excel sheet index of the first sheet. @param rnXclTab (out-param) Returns the Excel sheet index of the last sheet. @param nFirstScTab The first Calc sheet index to process. @param nLastScTab The last Calc sheet index to process. param pRefLogEntry If not 0, data about the external link is stored here. */ void FindExtSheet( sal_uInt16& rnExtSheet, sal_uInt16& rnFirstXclTab, sal_uInt16& rnLastXclTab, SCTAB nFirstScTab, SCTAB nLastScTab, XclExpRefLogEntry* pRefLogEntry = 0 ); /** Searches for a special EXTERNSHEET index for the own document. */ sal_uInt16 FindExtSheet( sal_Unicode cCode ); void FindExtSheet( sal_uInt16 nFileId, const String& rTabName, sal_uInt16 nXclTabSpan, sal_uInt16& rnExtSheet, sal_uInt16& rnFirstSBTab, sal_uInt16& rnLastSBTab, XclExpRefLogEntry* pRefLogEntry = NULL ); /** Stores the cell with the given address in a CRN record list. */ void StoreCell( const ScSingleRefData& rRef ); /** Stores all cells in the given range in a CRN record list. */ void StoreCellRange( const ScComplexRefData& rRef ); void StoreCell( sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef ); void StoreCellRange( sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef ); /** Finds or inserts an EXTERNNAME record for an add-in function name. @param rnExtSheet (out-param) Returns the index of the EXTSHEET structure for the add-in function name. @param rnExtName (out-param) Returns the 1-based EXTERNNAME record index. @return true = add-in function inserted; false = error (i.e. not supported in current BIFF). */ bool InsertAddIn( sal_uInt16& rnExtSheet, sal_uInt16& rnExtName, const String& rName ); /** InsertEuroTool */ bool InsertEuroTool( sal_uInt16& rnExtSheet, sal_uInt16& rnExtName, const String& rName ); /** Finds or inserts an EXTERNNAME record for DDE links. @param rnExtSheet (out-param) Returns the index of the EXTSHEET structure for the DDE link. @param rnExtName (out-param) Returns the 1-based EXTERNNAME record index. @return true = DDE link inserted; false = error (i.e. not supported in current BIFF). */ bool InsertDde( sal_uInt16& rnExtSheet, sal_uInt16& rnExtName, const String& rApplic, const String& rTopic, const String& rItem ); bool InsertExtName( sal_uInt16& rnExtSheet, sal_uInt16& rnExtName, const String& rUrl, const String& rName, const ScExternalRefCache::TokenArrayRef pArray ); /** Writes the entire Link table. */ virtual void Save( XclExpStream& rStrm ); private: typedef ScfRef< XclExpLinkManagerImpl > XclExpLinkMgrImplPtr; XclExpLinkMgrImplPtr mxImpl; }; // ============================================================================ #endif
49.082569
115
0.619159
Grosskopf
e7dcb2b460b4edcbb916fd0fbe0f247cf0c112eb
784
cc
C++
bluetooth/newblued/main.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
bluetooth/newblued/main.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
null
null
null
bluetooth/newblued/main.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright 2018 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 <brillo/flag_helper.h> #include <brillo/syslog_logging.h> #include "bluetooth/common/dbus_daemon.h" #include "bluetooth/newblued/newblue.h" #include "bluetooth/newblued/newblue_daemon.h" int main(int argc, char** argv) { brillo::FlagHelper::Init(argc, argv, "newblued, the Chromium OS Newblue daemon."); brillo::InitLog(brillo::kLogToSyslog | brillo::kLogToStderrIfTty); bluetooth::DBusDaemon daemon(std::make_unique<bluetooth::NewblueDaemon>( std::make_unique<bluetooth::Newblue>( std::make_unique<bluetooth::LibNewblue>()))); return daemon.Run(); }
34.086957
74
0.716837
emersion
e7dd038a07f541672ecdbee54894256ccb613089
2,899
cpp
C++
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
/* A Harshad or Niven number is a number that is divisible by the sum of its digits. 201 is a Harshad number because it is divisible by 3 (the sum of its digits.) When we truncate the last digit from 201, we get 20, which is a Harshad number. When we truncate the last digit from 20, we get 2, which is also a Harshad number. Let's call a Harshad number that, while recursively truncating the last digit, always results in a Harshad number a right truncatable Harshad number. Also: 201/3=67 which is prime. Let's call a Harshad number that, when divided by the sum of its digits, results in a prime a strong Harshad number. Now take the number 2011 which is prime. When we truncate the last digit from it we get 201, a strong Harshad number that is also right truncatable. Let's call such primes strong, right truncatable Harshad primes. You are given that the sum of the strong, right truncatable Harshad primes less than 10000 is 90619. Find the sum of the strong, right truncatable Harshad primes less than 1014. Solution comment: Quite fast, <100 ms. Hard to optimize further. Starting with all single digit numbers, which are Harshads, we can add digits that produces new Harshads. If adding a digit does not give a new Harshad, then it is either because we just hit a boring number, or it could be that we hit a prime. If this prime, without its last digit added happens to be a strong Harshad (and also truncatable by design) then the prime is a strong right truncatable Harshad prime. This problem really put the eulertools to the test, showing overflow issues in pow_mod, which is used in the Miller-Rabbin primality test. I don't think this is solvable without that test btw., as the numbers are way to big to test by trial division. Now there should be no overflow issues left, as handling of it is explicitly done when needed. I really don't agree with the 10% difficulty of this one, clearly much harder than many other problems in the 30-40% range. */ #include <iostream> #include "timing.hpp" #include "primes.hpp" using euler::primes::is_prime; using Int = uint64_t; Int sum = 0; void build_strong_Harshad_prime(Int base, Int base_digit_sum, int depth) { if (depth < 1) return; bool base_is_strong = is_prime(base / base_digit_sum); for (Int digit = 0; digit <= 9; ++digit) { Int x = base * 10 + digit; Int digit_sum = base_digit_sum + digit; if (x % digit_sum != 0) { if ( base_is_strong and is_prime(x)) { sum += x; } continue; } build_strong_Harshad_prime(x, digit_sum, depth - 1); } } int main() { euler::Timer timer {}; constexpr Int digits = 14; for (Int base = 1; base <= 9; ++base) { build_strong_Harshad_prime(base, base, digits - 1); } std::cout << "Answer: " << sum << std::endl; timer.stop(); }
34.511905
79
0.709555
bsamseth
e7df344610a036fa37f3a557b41d52afea50ac7d
2,027
cpp
C++
TAO/tao/Incoming_Message_Queue.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/Incoming_Message_Queue.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/Incoming_Message_Queue.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: Incoming_Message_Queue.cpp 91628 2010-09-07 11:11:12Z johnnyw $ #include "tao/Incoming_Message_Queue.h" #include "tao/Queued_Data.h" #include "tao/debug.h" #include "ace/Log_Msg.h" #include "ace/Malloc_Base.h" #if !defined (__ACE_INLINE__) # include "tao/Incoming_Message_Queue.inl" #endif /* __ACE_INLINE__ */ TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_Incoming_Message_Queue::~TAO_Incoming_Message_Queue (void) { CORBA::ULong const sz = this->size_; // Delete all the nodes left behind for (CORBA::ULong i = 0; i < sz; ++i) { TAO_Queued_Data *qd = this->dequeue_head (); TAO_Queued_Data::release (qd); } } TAO_Queued_Data * TAO_Incoming_Message_Queue::dequeue_head (void) { if (this->size_ == 0) return 0; // Get the node on the head of the queue... TAO_Queued_Data * const head = this->last_added_->next (); // Reset the head node.. this->last_added_->next (head->next ()); // Decrease the size and reset last_added_ if empty if (--this->size_ == 0) this->last_added_ = 0; return head; } TAO_Queued_Data * TAO_Incoming_Message_Queue::dequeue_tail (void) { // This is a bit painful stuff... if (this->size_ == 0) return 0; // Get the node on the head of the queue... TAO_Queued_Data *head = this->last_added_->next (); while (head->next () != this->last_added_) { head = head->next (); } // Put the head in tmp. head->next (this->last_added_->next ()); TAO_Queued_Data *ret_qd = this->last_added_; this->last_added_ = head; // Decrease the size if (--this->size_ == 0) this->last_added_ = 0; return ret_qd; } int TAO_Incoming_Message_Queue::enqueue_tail (TAO_Queued_Data *nd) { if (this->size_ == 0) { this->last_added_ = nd; this->last_added_->next (this->last_added_); } else { nd->next (this->last_added_->next ()); this->last_added_->next (nd); this->last_added_ = nd; } ++this->size_; return 0; } TAO_END_VERSIONED_NAMESPACE_DECL
20.474747
71
0.653182
cflowe
e7e04f2e48b35efebb79ea7a8852920c557ecd42
1,921
cpp
C++
Game/src/game/Kamikaze.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
3
2019-10-04T19:44:44.000Z
2021-07-27T15:59:39.000Z
Game/src/game/Kamikaze.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
1
2019-07-20T05:36:31.000Z
2019-07-20T22:22:49.000Z
Game/src/game/Kamikaze.cpp
aminere/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
null
null
null
/* Amine Rehioui Created: November 05th 2011 */ #include "ShootTest.h" #include "Kamikaze.h" namespace shoot { DEFINE_OBJECT(Kamikaze); DEFINE_OBJECT(KamikazeSettings); //! constructor KamikazeSettings::KamikazeSettings() : m_fDuration(1.5f) { } //! serializes the entity to/from a PropertyStream void KamikazeSettings::Serialize(PropertyStream& stream) { super::Serialize(stream); stream.Serialize(PT_Float, "Duration", &m_fDuration); } //! constructor Kamikaze::Kamikaze() : m_vDirection(Vector3::Create(0.0f, -1.0f, 0.0f)) , m_fTimer(1.5f) { } //! called during the initialization of the entity void Kamikaze::Init() { super::Init(); if(Player* pPlayer = Player::Instance()) { Vector3 vPosition = pPlayer->GetPosition() + GetSpawningPoint(); SetAbsolutePosition(vPosition); } if(KamikazeSettings* pSettings = static_cast<KamikazeSettings*>(m_Settings.Get())) { m_fTimer = pSettings->m_fDuration; } } //! called during the update of the entity void Kamikaze::Update() { super::Update(); if(m_HitPoints < 0) { return; } KamikazeSettings* pSettings = static_cast<KamikazeSettings*>(m_Settings.Get()); if(m_fTimer > 0.0f) { Vector3 vPosition = GetTransformationMatrix().GetTranslation(); Vector3 vPlayerMeshPos = Player::Instance()->GetMeshEntity()->GetTransformationMatrix().GetTranslation(); f32 fInterpolator = pSettings->m_fHomingFactor*g_fDeltaTime; fInterpolator = Math::Clamp(fInterpolator, 0.0f, 1.0f); Vector3 vDirectionToPlayer = (vPlayerMeshPos-vPosition).Normalize(); m_vDirection = ((vDirectionToPlayer-m_vDirection)*fInterpolator + m_vDirection).Normalize(); f32 fAngle = Math::ATan2(-m_vDirection.X, -m_vDirection.Y)*Math::RadToDegFactor; SetRotation(Vector3::Create(0.0f, 0.0f, fAngle)); m_fTimer -= g_fDeltaTime; } Translate(m_vDirection*pSettings->m_fSpeed*g_fDeltaTime); } }
22.337209
108
0.71317
franticsoftware
e7e43276a194c619ccf2813db3479e093ae732c5
7,324
cpp
C++
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
1
2021-07-21T03:19:55.000Z
2021-07-21T03:19:55.000Z
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
null
null
null
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
1
2021-07-21T03:20:01.000Z
2021-07-21T03:20:01.000Z
// GaugeConnect.cpp #include <MSFS/MSFS.h> #include <MSFS/MSFS_WindowsTypes.h> #include <MSFS/Legacy/gauges.h> #include <SimConnect.h> #include <cstring> #include "GaugeConnect.h" struct Expression { bool valid; double value; char* expression; UINT32 expr_len; Expression(void) : valid(false), expression(0), expr_len(0) { }; ~Expression() { remove(); }; void remove(void) { if (valid && expression) delete[] expression; valid = false; expression = 0; }; }; Expression* exprs = 0; size_t num_exprs = 0; enum GaugeInputCommands { GISetExpr, GIEvaluate, }; enum GaugeOutputResults { GIError, GIOk, GIMore, GIComplete, }; struct GaugeInputStruct { UINT32 sequence; UINT16 command; UINT16 param; char data[248]; }; struct GaugeOutputStruct { UINT32 sequence; UINT16 result; UINT16 count; struct { INT16 index; INT16 valid; FLOAT64 value; } values[20]; }; enum Event : DWORD { GaugeInput, GaugeOutput, }; enum SCData : DWORD { GaugeInputData, GaugeOutputData, }; enum SCRequest : DWORD { GaugeInputReq, GaugeInputCD, GaugeOutputReq, GaugeOutputCD, }; enum SCGroup : DWORD { GaugeConnectGroup, }; HANDLE sim = 0; ID gvar; template<typename T> void sim_recv(T* ev, DWORD data, void* ctx) { fprintf(stderr, "[GaugeConnect] unhandled RECV type %ld\n", ev->dwID); fflush(stderr); } #define RECV(tn) case SIMCONNECT_RECV_ID_##tn: sim_recv(static_cast<SIMCONNECT_RECV_##tn*>(recv), data, ctx); return #define RECV_FUNC(tn) template<> void sim_recv(SIMCONNECT_RECV_##tn* ev, DWORD data, void* ctx) RECV_FUNC(EXCEPTION) { fprintf(stderr, "[GaugeConnect] SimConnect exception %ld\n", ev->dwException); fflush(stderr); } RECV_FUNC(OPEN) { printf("[GaugeConnect] Open (%s)\n", ev->szApplicationName);; } RECV_FUNC(CLIENT_DATA) { switch (ev->dwRequestID) { case GaugeInputReq: { const GaugeInputStruct& inp = *reinterpret_cast<GaugeInputStruct*>(&ev->dwData); GaugeOutputStruct out; out.sequence = inp.sequence; out.result = GIError; switch (inp.command) { case GISetExpr: { if (inp.param >= num_exprs) { size_t nn = (inp.param+256) & ~255; Expression* ne = new Expression[nn]; if(ne) { if (exprs) { std::memcpy(ne, exprs, num_exprs*sizeof(Expression)); std::memset(exprs, 0, num_exprs*sizeof(Expression)); delete[] exprs; } exprs = ne; num_exprs = nn; } } if (exprs && inp.param < num_exprs) { Expression& e = exprs[inp.param]; e.remove(); if ((e.expression = new char[strlen(inp.data)+1])) { strcpy(e.expression, inp.data); e.valid = true; out.result = GIOk; // printf("[GaugeConnect] expression %d registered (%s)\n", int(inp.param), inp.data); // fflush(stdout); } else e.valid = false; } } break; case GIEvaluate: { out.result = GIMore; out.count = 0; for (int i = 0; i < inp.param; i++) { UINT16 index = reinterpret_cast<const UINT16*>(inp.data + inp.param * sizeof(FLOAT64))[i]; FLOAT64 value = reinterpret_cast<const FLOAT64*>(inp.data)[i]; if (index < num_exprs && exprs[index].valid) { auto& v = out.values[out.count++]; char* str = 0; int vi; v.index = index; set_named_variable_value(gvar, value); v.valid = execute_calculator_code(exprs[index].expression, &v.value, (SINT32*)0, (PCSTRINGZ * )0); // printf("[GaugeConnect] eval '%s': returns %g ('%s')\n", exprs[index].expression, v.value, str ? str : "<no string>"); // fflush(stdout); } if (out.count == 20) { SimConnect_SetClientData(sim, GaugeOutputCD, GaugeOutputData, 0, 0, sizeof(GaugeOutputStruct), &out); out.count = 0; } } out.result = GIComplete; } break; } SimConnect_SetClientData(sim, GaugeOutputCD, GaugeOutputData, 0, 0, sizeof(GaugeOutputStruct), &out); break; } } } RECV_FUNC(SYSTEM_STATE) { printf("[GaugeConnect] System state: %g '%s'\n", ev->fFloat, ev->szString); fflush(stdout); } RECV_FUNC(QUIT) { } RECV_FUNC(EVENT_FILENAME) { switch (ev->uEventID) { default: fprintf(stderr, "[GaugeConnect] unhandled event %ld (filename)\n", ev->uEventID); fflush(stderr); break; } } RECV_FUNC(EVENT) { switch (ev->uEventID) { default: fprintf(stderr, "[GaugeConnect] unhandled event %ld\n", ev->uEventID); fflush(stderr); break; } } void CALLBACK sim_recv(SIMCONNECT_RECV* recv, DWORD data, void* ctx) { switch (recv->dwID) { RECV(EVENT_FRAME); RECV(EVENT_FILENAME); RECV(EVENT); RECV(EXCEPTION); RECV(CLIENT_DATA); RECV(SYSTEM_STATE); RECV(SIMOBJECT_DATA); RECV(OPEN); RECV(QUIT); default: fprintf(stderr, "[GaugeConnect] unknown recv? (%ld)\n", recv->dwID); fflush(stderr); break; } } extern "C" MSFS_CALLBACK void module_init(void) { gvar = register_named_variable("GCVAL"); if (SimConnect_Open(&sim, "GaugeConnect Module", 0, 0, 0, 0) != S_OK) { fprintf(stderr, "[GaugeConnect] Unable to open SimConnect.\n"); return; } if (SimConnect_MapClientDataNameToID(sim, "org.uberbox.gauge.input", GaugeInputCD) != S_OK) fprintf(stderr, "[GaugeConnect] MapClientDataNameToID(org.uberbox.gauge.input) failed\n"); if(SimConnect_CreateClientData(sim, GaugeInputCD, sizeof(GaugeInputStruct), 0) != S_OK) fprintf(stderr, "[GaugeConnect] CreateClientData(org.uberbox.gauge.input) failed\n"); if (SimConnect_MapClientDataNameToID(sim, "org.uberbox.gauge.output", GaugeOutputCD) != S_OK) fprintf(stderr, "[GaugeConnect] MapClientDataNameToID(org.uberbox.gauge.output) failed\n"); if(SimConnect_CreateClientData(sim, GaugeOutputCD, sizeof(GaugeOutputStruct), SIMCONNECT_CREATE_CLIENT_DATA_FLAG_READ_ONLY) != S_OK) fprintf(stderr, "[GaugeConnect] CreateClientData(org.uberbox.gauge.output) failed\n"); SimConnect_MapClientEventToSimEvent(sim, GaugeInput, "org.uberbox.gauge.input"); SimConnect_MapClientEventToSimEvent(sim, GaugeOutput, "org.uberbox.gauge.output"); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 0, SIMCONNECT_CLIENTDATATYPE_INT32); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 4, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 6, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 8, 248); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 0, SIMCONNECT_CLIENTDATATYPE_INT32); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 4, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 6, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 8, sizeof(GaugeOutputStruct)-8); SimConnect_CallDispatch(sim, sim_recv, NULL); SimConnect_RequestClientData(sim, GaugeInputCD, GaugeInputReq, GaugeInputData, SIMCONNECT_CLIENT_DATA_PERIOD_ON_SET, SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_DEFAULT); fflush(stderr); printf("[GaugeConnect] Module started!\n"); } extern "C" MSFS_CALLBACK void module_deinit(void) { printf("[GaugeConnect] Module going away. :-(\n"); if (!sim) return; SimConnect_Close(sim); }
28.061303
164
0.685554
brion
e7e8f43ab3bc37214f81a307791266a6fffe32ef
341
cpp
C++
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
null
null
null
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
null
null
null
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
1
2019-06-16T19:00:31.000Z
2019-06-16T19:00:31.000Z
#include "EntTeleportAction.hpp" namespace ub { EntTeleportAction::EntTeleportAction(World* world, glm::vec2 destination) : ScriptAction(world), m_destination(destination) { } void EntTeleportAction::Initialize() { } void EntTeleportAction::Update(float dt) { m_world->MoveEnt(1, m_destination); m_complete = true; } }
15.5
77
0.727273
Mr-1337
e7eae52e56931502dd1699a15e56f123e6279b66
559
cpp
C++
src/tests/kits/app/bmessagequeue/MessageQueueTest.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/tests/kits/app/bmessagequeue/MessageQueueTest.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/tests/kits/app/bmessagequeue/MessageQueueTest.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
#include "../common.h" #include "AddMessageTest1.h" #include "AddMessageTest2.h" #include "ConcurrencyTest1.h" #include "ConcurrencyTest2.h" #include "FindMessageTest1.h" Test *MessageQueueTestSuite() { TestSuite *testSuite = new TestSuite(); testSuite->addTest(AddMessageTest1::suite()); testSuite->addTest(AddMessageTest2::suite()); testSuite->addTest(ConcurrencyTest1::suite()); // testSuite->addTest(ConcurrencyTest2::suite()); // Causes an "Abort" for some reason... testSuite->addTest(FindMessageTest1::suite()); return(testSuite); }
20.703704
89
0.735242
Kirishikesan
e7ec48c5dc2a6d4ffe8b131612214e9de530f484
420
cpp
C++
Online Judges/URI/1987/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/1987/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/1987/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 qtdNumbers, sum; string number; bool stopped; while(cin >> qtdNumbers >> number) { sum = 0; while(qtdNumbers--) { sum +=(number[qtdNumbers] - '0'); } if(sum % 3 == 0) { cout << sum << " sim\n"; } else { cout << sum << " nao\n"; } } return 0; }
17.5
45
0.430952
AnneLivia
e7eddc82f37df2a9dd86f8058ebcf131a0bf6f69
2,142
hpp
C++
kernel/lib/elf.hpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
207
2020-05-27T21:57:28.000Z
2022-02-26T15:17:27.000Z
kernel/lib/elf.hpp
ethan4984/crepOS
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
3
2020-07-26T18:14:05.000Z
2020-12-09T05:32:07.000Z
kernel/lib/elf.hpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
17
2020-07-05T19:08:48.000Z
2021-10-13T12:30:13.000Z
#ifndef ELF_HPP_ #define ELF_HPP_ #include <mm/vmm.hpp> #include <string.hpp> #include <fs/fd.hpp> namespace elf { constexpr size_t elf_signature = 0x464C457F; constexpr size_t elf64 = 0x2; constexpr size_t ei_class = 0x4; constexpr size_t ei_data = 0x5; constexpr size_t ei_version = 0x6; constexpr size_t ei_osabi = 0x7; constexpr size_t abi_system_v = 0x0; constexpr size_t abi_linux = 0x3; constexpr size_t little_endian = 0x1; constexpr size_t mach_x86_64 = 0x3e; struct aux { uint64_t at_entry; uint64_t at_phdr; uint64_t at_phent; uint64_t at_phnum; }; constexpr size_t at_entry = 10; constexpr size_t at_phdr = 20; constexpr size_t at_phent = 21; constexpr size_t at_phnum = 22; struct elf64_phdr { uint32_t p_type; uint32_t p_flags; uint64_t p_offset; uint64_t p_vaddr; uint64_t p_paddr; uint64_t p_filesz; uint64_t p_memsz; uint64_t p_align; }; constexpr size_t pt_null = 0x0; constexpr size_t pt_load = 0x1; constexpr size_t pt_dynamic = 0x2; constexpr size_t pt_interp = 0x3; constexpr size_t pt_note = 0x4; constexpr size_t pt_shlib = 0x5; constexpr size_t pt_phdr = 0x6; constexpr size_t pt_lts = 0x7; constexpr size_t pt_loos = 0x60000000; constexpr size_t pt_hois = 0x6fffffff; constexpr size_t pt_loproc = 0x70000000; constexpr size_t pt_hiproc = 0x7fffffff; struct elf64_shdr { uint32_t sh_name; uint32_t sh_type; uint64_t sh_flags; uint64_t sh_addr; uint64_t sh_offset; uint64_t sh_size; uint32_t sh_link; uint32_t sh_info; uint64_t sh_addr_align; uint64_t sh_entsize; }; struct file { file(vmm::pmlx_table *page_map, aux *aux_cur, fs::fd &file, uint64_t base, lib::string **ld_path); struct [[gnu::packed]] { uint8_t ident[16]; uint16_t type; uint16_t machine; uint32_t version; uint64_t entry; uint64_t phoff; uint64_t shoff; uint32_t flags; uint16_t hdr_size; uint16_t phdr_size; uint16_t ph_num; uint16_t shdr_size; uint16_t sh_num; uint16_t shstrndx; } hdr; size_t status; }; }; #endif
21.636364
102
0.704949
ethan4984
e7f00603063bc356ee35f2dd4e5a891475b981ee
387
cpp
C++
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int length, width, height; double percetage; cin >> length >> width >> height >> percetage; double volumeInSM = length * width * height; double liters = volumeInSM / 1000; double unusedLiters = liters * percetage / 100.0; double usedLiters = liters - unusedLiters; cout << usedLiters << endl; }
19.35
53
0.648579
kostadinmarkov99
e7f4315c365569ee6ce9a3393bc227c62b6a2fc9
9,001
cpp
C++
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
1
2021-06-14T09:34:08.000Z
2021-06-14T09:34:08.000Z
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
null
null
null
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
null
null
null
#include "StdAfx.h" #include "UIGuildBankForm.h" #include "uiform.h" #include "uilabel.h" #include "uiformmgr.h" #include "uigoodsgrid.h" #include "NetProtocol.h" #include "uiboxform.h" #include "uiEquipForm.h" #include "UIGoodsGrid.h" #include "uiItemCommand.h" #include "uiform.h" #include "uiBoatForm.h" #include "packetcmd.h" #include "Character.h" #include "GameApp.h" #include "StringLib.h" namespace GUI { //======================================================================= // CGuildBankMgr 's Members //======================================================================= bool CGuildBankMgr::Init() //用户银行信息初始化 { CFormMgr &mgr = CFormMgr::s_Mgr; frmBank = mgr.Find("frmManage");// 查找NPC银行存储表单 if ( !frmBank) { LG("gui", g_oLangRec.GetString(438)); return false; } grdBank = dynamic_cast<CGoodsGrid*>(frmBank->Find("guildBank")); labGuildMoney = dynamic_cast<CLabel*>(frmBank->Find("labGuildMoney")); btnGoldTake = dynamic_cast<CTextButton*>(frmBank->Find("btngoldtake")); btnGoldPut = dynamic_cast<CTextButton*>(frmBank->Find("btngoldput")); grdBank->evtBeforeAccept = CUIInterface::_evtDragToGoodsEvent; grdBank->evtSwapItem = _evtBankToBank; btnGoldPut->evtMouseClick=_OnClickGoldPut; btnGoldTake->evtMouseClick=_OnClickGoldTake; return true; } void CGuildBankMgr::UpdateGuildGold(const char* value){ labGuildMoney->SetCaption(StringSplitNum(value)); } void CGuildBankMgr::_OnClickGoldPut(CGuiData *pSender, int x, int y, DWORD key){ g_stUIBox.ShowNumberBox(_EnterGoldPut, g_stUIBoat.GetHuman()->getGameAttr()->get(ATTR_GD), "Enter Gold", false); } void CGuildBankMgr::_EnterGoldPut(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey){ if( nMsgType!=CForm::mrYes ) { return; } stNumBox* kItemPriceBox = (stNumBox*)pSender->GetForm()->GetPointer(); if (!kItemPriceBox) return; int value = kItemPriceBox->GetNumber(); if( value<=0 ) { g_pGameApp->MsgBox( g_oLangRec.GetString(451) ); return; } CS_GuildBankGiveGold(value); } void CGuildBankMgr::_OnClickGoldTake(CGuiData *pSender, int x, int y, DWORD key){ g_stUIBox.ShowNumberBox(_EnterGoldTake, 2000000000-(g_stUIBoat.GetHuman()->getGameAttr()->get(ATTR_GD)), "Enter Gold", false); } void CGuildBankMgr::_EnterGoldTake(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey){ if( nMsgType!=CForm::mrYes ) { return; } stNumBox* kItemPriceBox = (stNumBox*)pSender->GetForm()->GetPointer(); if (!kItemPriceBox) return; int value = kItemPriceBox->GetNumber(); if( value<=0 ) { g_pGameApp->MsgBox( g_oLangRec.GetString(451) ); return; } CS_GuildBankTakeGold(value); } void CGuildBankMgr::_evtOnClose( CForm* pForm, bool& IsClose ) // 关闭用户银行 { CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_CLOSE_BANK, NULL); CFormMgr::s_Mgr.SetEnableHotKey(HOTKEY_BANK, true); // 西门文档修改 } //------------------------------------------------------------------------- void CGuildBankMgr::ShowBank() // 显示物品 { // 保存服务器传来的物品 if (!g_stUIBoat.GetHuman()) // 找人物 return; char szBuf[32]; sprintf(szBuf, "%s%s", g_stUIBoat.GetHuman()->getName(), g_oLangRec.GetString(440));//显示人物名及专用 //labCharName->SetCaption(szBuf);//设置标题名字 frmBank->Show(); // 打开玩家的物品栏 if (!g_stUIEquip.GetItemForm()->GetIsShow()) { int nLeft, nTop; nLeft = frmBank->GetX2(); nTop = frmBank->GetY(); g_stUIEquip.GetItemForm()->SetPos(nLeft, nTop); //物品放置位置 g_stUIEquip.GetItemForm()->Refresh(); //更新物品栏 g_stUIEquip.GetItemForm()->Show(); //保存在物品栏 } CFormMgr::s_Mgr.SetEnableHotKey(HOTKEY_BANK, false); // 西门文档修改 } //------------------------------------------------------------------------- bool CGuildBankMgr::PushToBank(CGoodsGrid& rkDrag, CGoodsGrid& rkSelf, int nGridID, CCommandObj& rkItem) { #define EQUIP_TYPE 0 #define BANK_TYPE 1 // 设置发送拖动物品的服务器信息 m_kNetBank.chSrcType = EQUIP_TYPE; m_kNetBank.sSrcID = rkDrag.GetDragIndex(); //m_kNetBank.sSrcNum = ; 数量在回调函数中设置 m_kNetBank.chTarType = BANK_TYPE; m_kNetBank.sTarID = nGridID; // 判断物品是否是可重叠的物品 CItemCommand* pkItemCmd = dynamic_cast<CItemCommand*>(&rkItem); if (!pkItemCmd) return false; CItemRecord* pkItemRecord = pkItemCmd->GetItemInfo(); if (!pkItemRecord) return false; //if(pkItemRecord->sType == 59 && m_kNetBank.sSrcID == 1) //{ // g_pGameApp->MsgBox("您的精灵正在使用中\n请更换到其它位置才可放入仓库"); // return false; // 第二格的精灵不允许拖入银行 //} // if(pkItemRecord->lID == 2520 || pkItemRecord->lID == 2521) if( pkItemRecord->lID == 2520 || pkItemRecord->lID == 2521 || pkItemRecord->lID == 6341 || pkItemRecord->lID == 6343 || pkItemRecord->lID == 6347 || pkItemRecord->lID == 6359 || pkItemRecord->lID == 6370 || pkItemRecord->lID == 6371 || pkItemRecord->lID == 6373 || pkItemRecord->lID >= 6376 && pkItemRecord->lID <= 6378 || pkItemRecord->lID >= 6383 && pkItemRecord->lID <= 6385 )// modify by ning.yan 20080820 策划绵羊、李恒等提需求,增加一些道具不准存银行 { //g_pGameApp->MsgBox(g_oLangRec.GetString(958)); // "该道具不允许存入银行!请重新选择" g_pGameApp->MsgBox(g_oLangRec.GetString(958)); // "该道具不允许存入银行!请重新选择" return false; } if ( pkItemCmd->GetItemInfo()->GetIsPile() && pkItemCmd->GetTotalNum() > 1 ) { /*存放多个物品*/ m_pkNumberBox = g_stUIBox.ShowNumberBox(_MoveItemsEvent, pkItemCmd->GetTotalNum(), g_oLangRec.GetString(441), false); if (m_pkNumberBox->GetNumber() < pkItemCmd->GetTotalNum()) return false; else return true; } else { /*存放单个物品*/ g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); return true; //char buf[256] = { 0 }; //sprintf(buf, "您确认放入银行\n[%s]?", pkItemCmd->GetName()); //g_stUIBox.ShowSelectBox(_MoveAItemEvent, buf, true); //return true; } } //------------------------------------------------------------------------- bool CGuildBankMgr::PopFromBank(CGoodsGrid& rkDrag, CGoodsGrid& rkSelf, int nGridID, CCommandObj& rkItem) { // 设置发送拖动物品的服务器信息 m_kNetBank.chSrcType = BANK_TYPE ; m_kNetBank.sSrcID = rkDrag.GetDragIndex(); //m_kNetBank.sSrcNum = ; 数量在回掉函数中设置 m_kNetBank.chTarType = EQUIP_TYPE; m_kNetBank.sTarID = nGridID; // 判断物品是否是可重叠的物品 CItemCommand* pkItemCmd = dynamic_cast<CItemCommand*>(&rkItem); if (!pkItemCmd) return false; if ( pkItemCmd->GetItemInfo()->GetIsPile() && pkItemCmd->GetTotalNum() > 1 ) { /*取出多个物品*/ m_pkNumberBox = g_stUIBox.ShowNumberBox( _MoveItemsEvent, pkItemCmd->GetTotalNum(), g_oLangRec.GetString(442), false); if (m_pkNumberBox->GetNumber() < pkItemCmd->GetTotalNum()) return false; else return true; } else { /*存放单个物品*/ g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); return true; //char buf[256] = { 0 }; //sprintf(buf, "您确认取出\n[%s]?", pkItemCmd->GetName()); //g_stUIBox.ShowSelectBox(_MoveAItemEvent, buf, true); //return true; } } //------------------------------------------------------------------------- void CGuildBankMgr::_MoveItemsEvent(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey) // 多个物品移动 { if(nMsgType != CForm::mrYes) // 玩家是否同意拖动 return; int num = g_stUIGuildBank.m_pkNumberBox->GetNumber();// 拖动物品数 if ( num > 0 ) { g_stUIGuildBank.m_kNetBank.sSrcNum = num; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } } //------------------------------------------------------------------------- void CGuildBankMgr::_MoveAItemEvent(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey) // 单个道具移动 { if(nMsgType != CForm::mrYes) return; g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank));//更新银行信息 CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } //------------------------------------------------------------------------- void CGuildBankMgr::CloseForm() // 关闭道具栏表单 { if (frmBank->GetIsShow()) { frmBank->Close(); g_stUIEquip.GetItemForm()->Close(); } } //------------------------------------------------------------------------- void CGuildBankMgr::_evtBankToBank(CGuiData *pSender,int nFirst, int nSecond, bool& isSwap) // 用于用户银行表单中道具互换 { isSwap = false; if( !g_stUIBoat.GetHuman() ) return; g_stUIGuildBank.m_kNetBank.chSrcType = BANK_TYPE ; g_stUIGuildBank.m_kNetBank.sSrcID = nSecond; g_stUIGuildBank.m_kNetBank.sSrcNum = 0; g_stUIGuildBank.m_kNetBank.chTarType = BANK_TYPE; g_stUIGuildBank.m_kNetBank.sTarID = nFirst; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } } // end of namespace GUI
31.582456
128
0.651039
ruuuubi
e7f603ac6f13bee4c23a336e65ebf2c1e5f4ece4
4,597
hpp
C++
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
2
2018-08-20T08:56:11.000Z
2019-07-09T07:27:45.000Z
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
null
null
null
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------------------------------------------------------- // Copyright (c) 2018 Juho Lepistö // // 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. //----------------------------------------------------------------------------------------------------------------------------- //! @file ASch_System.hpp //! @author Juho Lepistö <juho.lepisto(a)gmail.com> //! @date 20 Aug 2018 //! //! @class System //! @brief Generic system control class for ASch. //! //! This class implements system control functions and handles generic system level events like ticks and system errors. #ifndef ASCH_SYSTEM_HPP_ #define ASCH_SYSTEM_HPP_ //----------------------------------------------------------------------------------------------------------------------------- // 1. Include Dependencies //----------------------------------------------------------------------------------------------------------------------------- #include <Utils_Types.hpp> #include <Hal_System.hpp> //----------------------------------------------------------------------------------------------------------------------------- // 2. Typedefs, Structs, Enums and Constants //----------------------------------------------------------------------------------------------------------------------------- namespace ASch { /// @brief This is a system error enum. enum class SysError { invalidParameters = 0, //!< A function was called with invalid parameters. bufferOverflow, //!< A buffer has overflown. insufficientResources, //!< System resources (e.g. task quota) has ran out. accessNotPermitted, //!< An attempt to access blocked resource has occurred. assertFailure, //!< A debug assert has failed. unknownError //!< An unknown error. Should never occur. }; } //----------------------------------------------------------------------------------------------------------------------------- // 3. Inline Functions //----------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------- // 4. Global Function Prototypes //----------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------- // 5. Class Declaration //----------------------------------------------------------------------------------------------------------------------------- namespace ASch { //! @class System //! @brief Generic system control class for ASch. //! This class implements system control functions and handles generic system level events like ticks and system errors. class System { public: explicit System(void) {}; /// @brief This fuction raises a system error. /// @param error - Error type. static void Error(SysError error); /// @brief This function enables reset on error. static void EnableResetOnSystemError(void); /// @brief This fuction initialises the system, e.f. clocks and other base peripherals. static void Init(void); /// @brief This function runs pre-start configuration functions. static void PreStartConfig(void); private: static bool resetOnError; }; } // namespace ASch #endif // ASCH_SYSTEM_HPP_
45.068627
127
0.474005
JuhoL
e7f60c2f38799f660ad85b4e9de2bbd6da832a41
1,843
cpp
C++
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
#include <Ledger.h> #include <LedgerSessionData.h> #include <LedgerSession.h> #include <LedgerCommands.h> Ledger::Ledger() { // libLedger one-time setup? } std::unique_ptr<LedgerSession> Ledger::LoadJournal(const std::string& fname) { std::unique_ptr<LedgerSession> sess; WithInstance([&] (Ledger& instance) { sess = std::make_unique<LedgerSession>(instance); instance.SwitchToSession(*sess); const char ** env = const_cast<const char**>(environ); sess->Data().sess.set_flush_on_next_data_file(true); ledger::process_environment(env, "LEDGER_", sess->Data().report); sess->Data().sess.set_flush_on_next_data_file(true); bool initialised = false; try { sess->Data().sess.read_journal(fname); initialised = true; } catch (ledger::error_count& ec) { sess->BadJournal(instance, ec.what()); } catch (const std::runtime_error& err) { sess->BadJournal(instance, err.what()); } if (initialised) { sess->SessionInitialised(instance); } }); return sess; } void Ledger::WithInstance(const std::function<void(Ledger &instance)> &cb) { static Ledger instance; std::unique_lock<std::mutex> lock(instance.globalLock); cb(instance); } void Ledger::SwitchToSession(LedgerSession&sess) { ledger::set_session_context(&sess.Data().sess); ledger::scope_t::default_scope = &sess.Data().report; ledger::scope_t::empty_scope = &sess.Data().emptyScope; } void Ledger::WithSession(LedgerSession &sess, const std::function<void(LedgerCommands &)>& task) { WithInstance([&] (Ledger& instance) { instance.SwitchToSession(sess); LedgerCommands cmdHandler(instance, sess); task(cmdHandler); }); }
29.253968
78
0.637005
LAHumphreys