hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
5cd7ef85cc0f79f1a687a8251f748c188ba13323
774
cpp
C++
C++/Esercizi/pag.154_es.7_.cpp
Daniele-Tentoni/esercizi_ripetizioni
a8b59b4ead3d6a7459103b91c53017a7495d9e82
[ "MIT" ]
null
null
null
C++/Esercizi/pag.154_es.7_.cpp
Daniele-Tentoni/esercizi_ripetizioni
a8b59b4ead3d6a7459103b91c53017a7495d9e82
[ "MIT" ]
null
null
null
C++/Esercizi/pag.154_es.7_.cpp
Daniele-Tentoni/esercizi_ripetizioni
a8b59b4ead3d6a7459103b91c53017a7495d9e82
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main () { int N ; do { cout << "Inserire quantita' di numeri che si vogliono calcolare fino ad un massimo di 100 unita' : " <<endl ; cin >> N ; } while ( N >= 100) ; int numeriInseriti [ N ] ; int numeriElevati [ N ] ; int differenze [ N ] ; for ( int i = 0 ; i < N ; i++ ) { cout << "Digitare "<<( i + 1)<<"' numero : " ; cin >> numeriInseriti [ i ]; numeriElevati [ i ] = numeriInseriti [ i ] * numeriInseriti [ i ] ; differenze [ i ] = numeriElevati [ i ] - numeriInseriti [ i ] ; } for ( int i = 0 ; i < N ; i++ ) { cout << "la differenza tra il quadrato del "<< (i + 1) << "' numero e del " << ( i + 1) << "' numero e' : "<<differenze [ i ]<<endl ; } system ( "pause") ; }
20.918919
136
0.528424
Daniele-Tentoni
5cdeead0f9a6259ded2b4382a1f9c4f585a51e8b
1,213
cpp
C++
CSES_Problem_Set/Tree_Algorithms/Subtree_Queries.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
4
2021-08-25T10:53:32.000Z
2021-09-30T03:25:50.000Z
CSES_Problem_Set/Tree_Algorithms/Subtree_Queries.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
null
null
null
CSES_Problem_Set/Tree_Algorithms/Subtree_Queries.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
null
null
null
// Author: __BruteForce__ #include <bits/stdc++.h> using namespace std; typedef long long int64; #define MAX_N 200005 int n, q, pos = 0; int val[MAX_N]; int start[MAX_N], finish[MAX_N]; vector<int> adj[MAX_N]; int64 bit[MAX_N]; void update(int p, int v) { for (int i = p; i <= n; i += i & -i) bit[i] += v; } int64 getSum(int p) { int64 sum = 0; for (int i = p; i; i -= i & -i) sum += bit[i]; return sum; } void dfs(int u, int par) { start[u] = ++pos; update(pos, val[u]); for (int v: adj[u]) { if (v == par) continue; dfs(v, u); } finish[u] = pos; } int main() { cin.tie(0)->sync_with_stdio(false); cin >> n >> q; for (int u = 1; u <= n; u++) cin >> val[u]; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } dfs(1, 0); while (q--) { int id, s, x; cin >> id; if (id == 1) { cin >> s >> x; update(start[s], x - val[s]); val[s] = x; } else { cin >> s; cout << getSum(finish[s]) - getSum(start[s] - 1) << "\n"; } } }
18.378788
69
0.437758
hoanghai1803
5ce55175b543dc77cc188db1e77e36d92efe5302
936
cpp
C++
leetcode/cpp/1024-Video-Stitching.cpp
liu-chunhou/OnlineJudge
b79c8e05acf05411d8cf172214aa42e49cc20867
[ "MIT" ]
null
null
null
leetcode/cpp/1024-Video-Stitching.cpp
liu-chunhou/OnlineJudge
b79c8e05acf05411d8cf172214aa42e49cc20867
[ "MIT" ]
null
null
null
leetcode/cpp/1024-Video-Stitching.cpp
liu-chunhou/OnlineJudge
b79c8e05acf05411d8cf172214aa42e49cc20867
[ "MIT" ]
null
null
null
#include <vector> #include <algorithm> #include <climits> using namespace std; class Solution { public: int videoStitching(vector<vector<int>>& clips, int T) { sort(clips.begin(), clips.end(), cmp); vector<int> dp(clips.size(), INT_MAX); for(int i=0; i<dp.size(); ++i){ if(clips[i][0]==0)dp[i]=1; else{ for(int j=0; j<i; ++j){ if(dp[j]!=-1 && clips[i][0]<=clips[j][1] && dp[j]+1<=dp[i]){ dp[i] = dp[j]+1; } } if(dp[i]==INT_MAX)dp[i]=-1; } } int cur = INT_MAX; for(int i=0; i<dp.size(); ++i){ if(clips[i][1]>=T && dp[i]!=-1 && dp[i]<cur)cur=dp[i]; } return cur==INT_MAX?-1:cur; } static bool cmp(vector<int>& a, vector<int> &b){ return (a[1] < b[1]) || (a[1]==b[1] && a[0]<b[0]); } };
29.25
80
0.419872
liu-chunhou
5ce804db7fc3524a82d563a0c1d032abc8d28bf5
385
cpp
C++
dllmain.cpp
KingfuChan/MTEPlugIn-for-EuroScope
b81a3fed2fa040816ac3aa506957e00867a4a8d9
[ "MIT" ]
2
2021-08-20T00:44:45.000Z
2021-08-20T11:58:05.000Z
dllmain.cpp
KingfuChan/MTEPlugIn-for-EuroScope
b81a3fed2fa040816ac3aa506957e00867a4a8d9
[ "MIT" ]
null
null
null
dllmain.cpp
KingfuChan/MTEPlugIn-for-EuroScope
b81a3fed2fa040816ac3aa506957e00867a4a8d9
[ "MIT" ]
null
null
null
// dllmain.cpp #include "pch.h" #include <EuroScopePlugIn.h> #include "MTEPlugin.h" // Interface for EuroScope plugin loading CMTEPlugIn* pMyPlugIn = nullptr; void __declspec (dllexport) EuroScopePlugInInit(EuroScopePlugIn::CPlugIn** ppPlugInInstance) { *ppPlugInInstance = pMyPlugIn = new CMTEPlugIn; } void __declspec (dllexport) EuroScopePlugInExit(void) { delete pMyPlugIn; }
20.263158
64
0.779221
KingfuChan
5cea57b0d14eb3f46355bb2c743f568a69cfd616
1,646
hpp
C++
cpp/lazperf/detail/field_rgb10.hpp
gdt/laz-perf
916901f3583bd858e0e2e0cf4e628f27e78ea5e9
[ "Apache-2.0" ]
null
null
null
cpp/lazperf/detail/field_rgb10.hpp
gdt/laz-perf
916901f3583bd858e0e2e0cf4e628f27e78ea5e9
[ "Apache-2.0" ]
null
null
null
cpp/lazperf/detail/field_rgb10.hpp
gdt/laz-perf
916901f3583bd858e0e2e0cf4e628f27e78ea5e9
[ "Apache-2.0" ]
null
null
null
/* =============================================================================== PROGRAMMERS: martin.isenburg@rapidlasso.com - http://rapidlasso.com uday.karan@gmail.com - Hobu, Inc. COPYRIGHT: (c) 2007-2014, martin isenburg, rapidlasso - tools to catch reality (c) 2014, Uday Verma, Hobu, Inc. This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: =============================================================================== */ namespace lazperf { namespace detail { class Rgb10Base { protected: Rgb10Base(); bool have_last_; las::rgb last; models::arithmetic m_byte_used; models::arithmetic m_rgb_diff_0; models::arithmetic m_rgb_diff_1; models::arithmetic m_rgb_diff_2; models::arithmetic m_rgb_diff_3; models::arithmetic m_rgb_diff_4; models::arithmetic m_rgb_diff_5; }; class Rgb10Compressor : public Rgb10Base { public: Rgb10Compressor(encoders::arithmetic<OutCbStream>&); const char *compress(const char *buf); private: encoders::arithmetic<OutCbStream>& enc_; }; class Rgb10Decompressor : public Rgb10Base { public: Rgb10Decompressor(decoders::arithmetic<InCbStream>&); char *decompress(char *buf); private: decoders::arithmetic<InCbStream>& dec_; }; } // namespace detail } // namespace lazperf
22.861111
79
0.652491
gdt
5cead4436e4a6c550ce455ed588ff2c3a115c433
3,618
cc
C++
src/lib/tests/common_test.cc
cstrotm/queryperfpp
9afd7c5aa9dd908897b01e3f8a8686760356fd9b
[ "0BSD" ]
8
2015-12-27T18:44:41.000Z
2021-11-01T21:52:06.000Z
src/lib/tests/common_test.cc
cstrotm/queryperfpp
9afd7c5aa9dd908897b01e3f8a8686760356fd9b
[ "0BSD" ]
3
2016-04-29T14:31:46.000Z
2018-04-13T20:26:52.000Z
src/lib/tests/common_test.cc
cstrotm/queryperfpp
9afd7c5aa9dd908897b01e3f8a8686760356fd9b
[ "0BSD" ]
3
2015-02-06T04:23:59.000Z
2020-04-15T09:12:53.000Z
// Copyright (C) 2012 JINMEI Tatuya // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #include <common_test.h> #include <util/buffer.h> #include <dns/name.h> #include <dns/message.h> #include <dns/opcode.h> #include <dns/rcode.h> #include <dns/rrtype.h> #include <dns/rrclass.h> #include <gtest/gtest.h> using namespace bundy::dns; using namespace bundy::util; namespace Queryperf { namespace unittest { size_t default_expected_rr_counts[4] = {1, 0, 0, 0}; void queryMessageCheck(const void* data, size_t data_len, qid_t expected_qid, const Name& expected_qname, RRType expected_qtype, bool expected_edns, bool expected_dnssec, RRClass expected_qclass) { EXPECT_NE(0, data_len); ASSERT_NE(static_cast<const void*>(NULL), data); Message msg(Message::PARSE); InputBuffer buffer(data, data_len); msg.fromWire(buffer); queryMessageCheck(msg, expected_qid, expected_qname, expected_qtype, default_expected_rr_counts, expected_edns, expected_dnssec, expected_qclass); } void queryMessageCheck(const Message& msg, qid_t expected_qid, const Name& expected_qname, RRType expected_qtype, const size_t expected_rr_counts[4], bool expected_edns, bool expected_dnssec, RRClass expected_qclass) { EXPECT_EQ(Opcode::QUERY(), msg.getOpcode()); EXPECT_EQ(Rcode::NOERROR(), msg.getRcode()); EXPECT_EQ(expected_qid, msg.getQid()); EXPECT_FALSE(msg.getHeaderFlag(Message::HEADERFLAG_QR)); EXPECT_FALSE(msg.getHeaderFlag(Message::HEADERFLAG_AA)); EXPECT_FALSE(msg.getHeaderFlag(Message::HEADERFLAG_TC)); EXPECT_TRUE(msg.getHeaderFlag(Message::HEADERFLAG_RD)); EXPECT_FALSE(msg.getHeaderFlag(Message::HEADERFLAG_RA)); EXPECT_FALSE(msg.getHeaderFlag(Message::HEADERFLAG_AD)); EXPECT_FALSE(msg.getHeaderFlag(Message::HEADERFLAG_CD)); EXPECT_EQ(expected_rr_counts[0], msg.getRRCount(Message::SECTION_QUESTION)); EXPECT_EQ(expected_rr_counts[1], msg.getRRCount(Message::SECTION_ANSWER)); EXPECT_EQ(expected_rr_counts[2], msg.getRRCount(Message::SECTION_AUTHORITY)); // Note: getRRCount doesn't take into account EDNS in this context EXPECT_EQ(expected_rr_counts[3], msg.getRRCount(Message::SECTION_ADDITIONAL)); QuestionIterator qit = msg.beginQuestion(); ASSERT_FALSE(qit == msg.endQuestion()); EXPECT_EQ(expected_qname, (*qit)->getName()); EXPECT_EQ(expected_qtype, (*qit)->getType()); EXPECT_EQ(expected_qclass, (*qit)->getClass()); EXPECT_EQ(expected_edns, msg.getEDNS() != NULL); if (msg.getEDNS()) { if (expected_dnssec) { EXPECT_TRUE(msg.getEDNS()->getDNSSECAwareness()); } else { EXPECT_FALSE(msg.getEDNS()->getDNSSECAwareness()); } } } } // end of unittest } // end of Queryperf
38.903226
80
0.70398
cstrotm
5ceebbd0ad1dfd0b01b69773fd8490557562c8ad
2,735
cpp
C++
tests/unit/memory_with_allocator.test.cpp
eullerborges/flexclass
953eb84c5d106bdc1d321c5b979c423097ae50b8
[ "MIT" ]
27
2020-09-18T01:46:13.000Z
2021-10-30T21:33:58.000Z
tests/unit/memory_with_allocator.test.cpp
eullerborges/flexclass
953eb84c5d106bdc1d321c5b979c423097ae50b8
[ "MIT" ]
18
2020-10-01T23:49:26.000Z
2021-10-29T19:36:05.000Z
tests/unit/memory_with_allocator.test.cpp
eullerborges/flexclass
953eb84c5d106bdc1d321c5b979c423097ae50b8
[ "MIT" ]
4
2020-10-02T00:32:06.000Z
2020-10-25T16:26:13.000Z
#include <catch.hpp> #include <flexclass.hpp> #include <cstring> #include <unordered_map> struct AllocTrack { void* allocate(std::size_t sz) { m_allocd += sz; auto mem = ::operator new(sz); m_ptr2sz[(uintptr_t)mem] = sz; return mem; } void deallocate(void* ptr) { auto it = m_ptr2sz.find((uintptr_t)ptr); CHECK(it != m_ptr2sz.end()); m_deallocd += it->second; m_freeCount++; m_ptr2sz.erase(it); ::operator delete(ptr); } void resetCounters() { m_allocd = m_deallocd = m_freeCount = 0; } std::size_t m_allocd {0}; std::size_t m_deallocd {0}; std::size_t m_freeCount {0}; std::unordered_map<uintptr_t, std::size_t> m_ptr2sz; }; TEST_CASE( "Allocate and destroy", "[allocator]" ) { struct Message { auto fc_handles() { return fc::make_tuple(&data); } std::string str; fc::Array<char> data; }; auto numChars = 1000; auto expectedSize = sizeof(std::string) + sizeof(char*) + numChars*sizeof(char); AllocTrack alloc; auto m = fc::make<Message>(fc::withAllocator, alloc, numChars)("SmallMsg"); CHECK(alloc.m_allocd == expectedSize); CHECK(alloc.m_freeCount == 0); alloc.resetCounters(); fc::destroy(m, alloc); CHECK(alloc.m_allocd == 0); CHECK(alloc.m_freeCount == 1); } TEST_CASE( "Allocate and destroy but forcing sized char", "[allocator]" ) { struct Message { auto fc_handles() { return fc::make_tuple(&data); } std::string str; fc::Range<char> data; }; auto numChars = 1000; auto expectedSize = sizeof(std::string) + 2*sizeof(char*) + numChars*sizeof(char); AllocTrack alloc; auto m = fc::make<Message>(fc::withAllocator, alloc, numChars)("SmallMsg"); CHECK(alloc.m_allocd == expectedSize); CHECK(alloc.m_freeCount == 0); alloc.resetCounters(); fc::destroy(m, alloc); CHECK(alloc.m_allocd == 0); CHECK(alloc.m_freeCount == 1); } TEST_CASE( "Allocate and destroy but using an adjacent array", "[allocator]" ) { struct Message : public fc::AdjacentArray<char> { auto fc_handles() { return fc::make_tuple(&data()); } std::string str; fc::AdjacentArray<char>& data() { return *this; } }; auto numChars = 1000; auto expectedSize = sizeof(std::string) + numChars*sizeof(char); AllocTrack alloc; auto r = fc::make<Message>(fc::withAllocator, alloc, numChars)("SmallMsg"); CHECK(alloc.m_allocd == expectedSize); CHECK(alloc.m_freeCount == 0); alloc.resetCounters(); fc::destroy(r, alloc); CHECK(alloc.m_allocd == 0); CHECK(alloc.m_freeCount == 1); }
23.577586
86
0.609872
eullerborges
5cf22eccaf2239ec953b9e42b226e398da99a1f8
3,701
cpp
C++
src/var_.cpp
hhijazi/PowerTools
daaa2d3e92be452f9c6e77e5c9fc446670fcfc84
[ "Apache-2.0" ]
15
2015-12-03T04:14:56.000Z
2021-09-03T23:56:23.000Z
src/var_.cpp
hhijazi/PowerTools
daaa2d3e92be452f9c6e77e5c9fc446670fcfc84
[ "Apache-2.0" ]
2
2016-05-09T05:27:56.000Z
2016-05-10T11:26:03.000Z
src/var_.cpp
hhijazi/PowerTools
daaa2d3e92be452f9c6e77e5c9fc446670fcfc84
[ "Apache-2.0" ]
11
2015-09-18T12:49:47.000Z
2021-05-20T21:53:26.000Z
// // var_.cpp // PowerTools++ // // Created by Hassan Hijazi on 20/12/2014. // Copyright (c) 2014 NICTA. All rights reserved. // #include <iostream> #include <stdio.h> #include <string> #include "PowerTools++/var.h" #include <PowerTools++/Constraint.h> using namespace std; var_::var_():var_(NULL, -1){}; var_::var_(string name):var_(NULL, name){}; var_::var_(int idx):var_(NULL, idx){}; var_::var_(Model* model, string name):var_(model, name, -1){}; var_::var_(Model* model, int idx):_model(model), _idx(idx), _type(longreal), _dval(0){}; var_::var_(Model* model, string name, int idx){ _name = name; _model = model; _idx = idx; _type = longreal; _dval = 0; }; var_& var_::operator=(const var_& v){ _model = v._model; _idx = v._idx; _name = v._name; _type = v._type; _dval = v._dval; _bounded_down = v._bounded_down; _bounded_up = v._bounded_up; for (auto c:v._cstrs){ addConstraint(c.second); } for (auto id:v._hess){ _hess.insert(id); } return *this; } /* Destructor */ var_::~var_(){ }; /* Accessors */ bool var_::is_bounded_above() const{ return _bounded_up; }; bool var_::is_bounded_below() const{ return _bounded_down; }; bool var_::is_constant() const{ return (_type==constant); }; bool var_::is_int() const{ return (_type==integ); }; bool var_::is_binary() const{ return (_type==binary); }; bool var_::is_real() const{ return (_type==real); }; bool var_::is_longreal() const{ return (_type==longreal); }; int var_::get_idx() const{ return _idx; }; VarType var_::get_type() const{ return _type; }; Constraint* var_::get_Constraint(int idx) const{ return _cstrs.find(idx)->second; }; /* Modifiers */ void var_::set_idx(int idx){ _idx = idx; }; bool var_::addConstraint(Constraint* c){ if(_cstrs.insert(std::pair<int, Constraint*> (c->get_idx(),c)).second) return true; else cerr << "Cannot add constraint\n"; exit(-1); }; bool var_::delConstraint(Constraint* c){ map<int,Constraint*>::iterator it = _cstrs.find(c->get_idx()); if(it==_cstrs.end()) return false; else _cstrs.erase(it); return true; }; bool var_::addObjective(Objective* obj){ return true; }; bool var_::delObjective(Objective* obj){ return true; }; /* Operators */ Quadratic operator+(double cst, var_& v){ Quadratic res(v); return res+=cst; }; Quadratic operator-(double cst, var_& v){ return -1*v+cst; }; Quadratic operator*(double cst, var_& v){ return Quadratic(v)*=cst; }; Quadratic operator/(double cst, var_& v){ return Quadratic(v)*=1/cst; }; Quadratic operator+(var_& v1, var_& v2){ Quadratic res(v1); return res+=v2; }; Quadratic operator-(var_& v1, var_& v2){ Quadratic res; res += v1; return res-=v2; }; Quadratic operator*(var_& v1, var_& v2){ return Quadratic(v1)*=v2; }; Function operator/(var_& v1, var_& v2){ return Function(v1)/=v2; }; Function sin(var_& v){ return sin(Function(v)); }; Function cos(var_& v){ return cos(Function(v)); }; //Function var_::operator^(int p){ // Function res(*this); // if(p==2) { // res *= res; // return res; // } // res = res^p; // return res; //} Quadratic var_::operator^(int p){ assert(p==2); Quadratic res(*this); Quadratic res_(*this); return res*=res_; } /* Output */ void var_::print() const { cout << _name; }; void var_::print_type() const { cout << "var" << _idx << ": "; if(is_binary()) cout << "binary"; if(is_real()) cout << "real"; if(is_int()) cout << "integer"; };
17.879227
88
0.600919
hhijazi
5cf359b579d2951ae453f5f8eac80926e15aa167
4,098
cpp
C++
platforms/linux/Sem.cpp
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
2
2021-05-06T19:56:26.000Z
2021-05-27T16:41:56.000Z
platforms/linux/Sem.cpp
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
54
2021-03-30T18:45:12.000Z
2022-03-17T20:13:04.000Z
platforms/linux/Sem.cpp
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
1
2021-05-14T16:34:08.000Z
2021-05-14T16:34:08.000Z
/* * Copyright (c) 2021, University of Washington * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the University of Washington nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF WASHINGTON AND CONTRIBUTORS * “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /****************************************************************************** * INCLUDES ******************************************************************************/ #include "OsApi.h" #include <assert.h> #include <errno.h> #include <poll.h> #include <semaphore.h> #include <pthread.h> /****************************************************************************** * PUBLIC METHODS ******************************************************************************/ /*---------------------------------------------------------------------------- * Constructor *----------------------------------------------------------------------------*/ Sem::Sem() { sem_init(&semId, 0, 0); } /*---------------------------------------------------------------------------- * Destructor *----------------------------------------------------------------------------*/ Sem::~Sem() { sem_destroy(&semId); } /*---------------------------------------------------------------------------- * give *----------------------------------------------------------------------------*/ void Sem::give(void) { sem_post(&semId); } /*---------------------------------------------------------------------------- * take *----------------------------------------------------------------------------*/ bool Sem::take(int timeout_ms) { int status = 1; /* Perform Take */ if(timeout_ms > 0) { /* Build Time Structure */ struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += (time_t) (timeout_ms / 1000) ; ts.tv_nsec += (timeout_ms % 1000) * 1000000L ; if(ts.tv_nsec >= 1000000000L ) { ts.tv_nsec -= 1000000000L ; ts.tv_sec++ ; } /* Loop until Timeout or Success */ do { status = sem_timedwait(&semId, &ts); } while(status == -1 && errno == EINTR); } else if(timeout_ms == IO_CHECK) { /* Non-Blocking Attempt */ do { status = sem_trywait(&semId); } while(status == -1 && errno == EINTR); } else if(timeout_ms == IO_PEND) { /* Block Forever until Success */ do { status = sem_wait(&semId); } while(status == -1 && errno == EINTR); } else { status = PARM_ERR_RC; } /* Return Status */ if(status == 0) return true; else return false; }
33.867769
80
0.487555
ICESat2-SlideRule
5cf5939f1184fc57a929bf4079a75277e251615c
1,283
cpp
C++
AtCoder/ABC156/Bouquet/main.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
1
2020-05-24T02:27:05.000Z
2020-05-24T02:27:05.000Z
AtCoder/ABC156/Bouquet/main.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
null
null
null
AtCoder/ABC156/Bouquet/main.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <fstream> #define DEV 1 using std::cin; using std::cout; using std::endl; using std::terminate; template<class T> inline T pow(T base, T exponent, T mod) { if (exponent == 0) return 1; if (exponent % 2 == 1) { return base * pow(base, exponent - 1, mod) % mod; } else { T tmp = pow(base, exponent / 2, mod); return (tmp * tmp) % mod; } } void solve() { long n, a, b; cin >> n >> a >> b; long mod = 1e9 + 7; long ans = pow(2l, n, mod) - 1; long X = 1; for (int i = n; i >= n - (a - 1); --i) { X *= i; X %= mod; } long Y = 1; for (int i = 1; i <= a; ++i) { Y *= i; Y %= mod; } ans += mod; ans -= X * pow(Y, mod - 2, mod) % mod; X = 1; for (int i = n; i >= n - (b - 1); --i) { X *= i; X %= mod; } Y = 1; for (int i = 1; i <= b; ++i) { Y *= i; Y %= mod; } ans += mod; ans -= X * pow(Y, mod - 2, mod) % mod; cout << ans % mod << endl; } int main() { #ifdef DEV std::ifstream in("input"); cin.rdbuf(in.rdbuf()); int t; cin >> t; for (int x = 1; x <= t; ++x) { solve(); } #else solve(); #endif return 0; }
16.448718
59
0.423227
t-mochizuki
5cf6d19204377680799ad3b8f7702a19d681c449
598
cc
C++
raytracer_oneweek/src/generate-ppm.cc
yans0ng/computer-graphics-is-fun
91667479e79968cdbc08de47f7fc91e8c42c600f
[ "MIT" ]
null
null
null
raytracer_oneweek/src/generate-ppm.cc
yans0ng/computer-graphics-is-fun
91667479e79968cdbc08de47f7fc91e8c42c600f
[ "MIT" ]
null
null
null
raytracer_oneweek/src/generate-ppm.cc
yans0ng/computer-graphics-is-fun
91667479e79968cdbc08de47f7fc91e8c42c600f
[ "MIT" ]
null
null
null
#include <fstream> int main() { const int nx = 200; const int ny = 100; std::ofstream image("hello.ppm"); image << "P3\n" << nx << " " << ny << "\n255\n"; for (int j = ny - 1; j >= 0; j--) { for (int i = 0; i < nx; i++) { float r = static_cast<float>(i) / static_cast<float>(nx); float g = static_cast<float>(j) / static_cast<float>(ny); float b = 0.2; int ir = static_cast<int>(255.99 * r); int ig = static_cast<int>(255.99 * g); int ib = static_cast<int>(255.99 * b); image << ir << " " << ig << " " << ib << '\n'; } } return 0; }
28.47619
63
0.496656
yans0ng
9dc9e00a80bca5eab7ee6ad660e9cdf192e25980
387
hpp
C++
alphavantagecpp/include/alphavantagecpp/api/forex/FX_DAILY.hpp
mesinger/alphavantagecpp
2e97d602be6677f99ccff4fc241955f6e5a6dbb8
[ "MIT" ]
2
2019-11-05T22:15:09.000Z
2019-11-08T09:09:01.000Z
alphavantagecpp/include/alphavantagecpp/api/forex/FX_DAILY.hpp
mesinger/alphavantagecpp
2e97d602be6677f99ccff4fc241955f6e5a6dbb8
[ "MIT" ]
1
2019-11-10T14:34:45.000Z
2019-11-10T14:34:45.000Z
alphavantagecpp/include/alphavantagecpp/api/forex/FX_DAILY.hpp
mesinger/alphavantagecpp
2e97d602be6677f99ccff4fc241955f6e5a6dbb8
[ "MIT" ]
null
null
null
#pragma once #include "alphavantagecpp/api/AlphaVantageRequest.hpp" namespace av { class FX_DAILY : public AlphaVantageRequest { public: FX_DAILY(const std::string& from_symbol, const std::string& to_symbol, const std::string& key, const std::string& outputsize = API_OUTPUTSIZE_COMPACT, const std::string& datatype = API_DATATYPE_JSON); virtual ~FX_DAILY() = default; }; }
24.1875
202
0.754522
mesinger
9dcb155dfbe089a24669823e6d24875ad7a3545d
8,022
cpp
C++
test/wait_multiplexer_test.cpp
taylorb-microsoft/winss
ede93f84a5d9585502db5190f2ec6365858f695a
[ "Apache-2.0" ]
52
2017-01-05T23:39:38.000Z
2020-06-04T03:00:11.000Z
test/wait_multiplexer_test.cpp
morganstanley/winss
ede93f84a5d9585502db5190f2ec6365858f695a
[ "Apache-2.0" ]
24
2017-01-05T05:07:34.000Z
2018-03-09T00:50:58.000Z
test/wait_multiplexer_test.cpp
morganstanley/winss
ede93f84a5d9585502db5190f2ec6365858f695a
[ "Apache-2.0" ]
7
2016-12-27T20:55:20.000Z
2018-03-09T00:32:19.000Z
/* * Copyright 2016-2017 Morgan Stanley * * 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 <chrono> #include <thread> #include <functional> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "winss/winss.hpp" #include "winss/wait_multiplexer.hpp" #include "winss/handle_wrapper.hpp" #include "winss/event_wrapper.hpp" #include "mock_interface.hpp" #include "mock_windows_interface.hpp" using ::testing::_; using ::testing::NiceMock; using ::testing::Return; using ::testing::InvokeWithoutArgs; namespace winss { class WaitMultiplexerTest : public testing::Test { }; TEST_F(WaitMultiplexerTest, WaitTimeoutItemOrdering) { auto now = std::chrono::system_clock::now(); auto later = now + std::chrono::milliseconds(5000); auto callback1 = [](winss::WaitMultiplexer&) {}; auto callback2 = [](winss::WaitMultiplexer&) {}; winss::WaitTimeoutItem item1({ "", now, callback1 }); winss::WaitTimeoutItem item2({ "", later, callback2 }); EXPECT_LT(item1, item2); } TEST_F(WaitMultiplexerTest, RemoveTriggered) { winss::WaitMultiplexer multiplexer; winss::HandleWrapper handle1(reinterpret_cast<HANDLE>(10000), false); winss::HandleWrapper handle2(reinterpret_cast<HANDLE>(20000), false); auto callback1 = [](winss::WaitMultiplexer&, const winss::HandleWrapper&) {}; auto callback2 = [](winss::WaitMultiplexer&, const winss::HandleWrapper&) {}; EXPECT_FALSE(multiplexer.RemoveTriggeredCallback(handle1)); multiplexer.AddTriggeredCallback(handle1, callback1); multiplexer.AddTriggeredCallback(handle2, callback2); EXPECT_TRUE(multiplexer.RemoveTriggeredCallback(handle1)); EXPECT_FALSE(multiplexer.RemoveTriggeredCallback(handle1)); } TEST_F(WaitMultiplexerTest, RemoveTimeout) { winss::WaitMultiplexer multiplexer; auto callback = [](winss::WaitMultiplexer&) {}; multiplexer.AddTimeoutCallback(1000, callback, "test1"); multiplexer.AddTimeoutCallback(1001, callback, "test2"); EXPECT_NE(INFINITE, multiplexer.GetTimeout()); EXPECT_TRUE(multiplexer.RemoveTimeoutCallback("test1")); EXPECT_FALSE(multiplexer.RemoveTimeoutCallback("test1")); EXPECT_NE(INFINITE, multiplexer.GetTimeout()); EXPECT_TRUE(multiplexer.RemoveTimeoutCallback("test2")); EXPECT_EQ(INFINITE, multiplexer.GetTimeout()); } TEST_F(WaitMultiplexerTest, GetTimeoutEmpty) { winss::WaitMultiplexer multiplexer; auto callback = [](winss::WaitMultiplexer&) {}; multiplexer.AddTimeoutCallback(0, callback, "test1"); EXPECT_EQ(0, multiplexer.GetTimeout()); } TEST_F(WaitMultiplexerTest, StartEmpty) { winss::WaitMultiplexer multiplexer; EXPECT_EQ(0, multiplexer.Start());; } TEST_F(WaitMultiplexerTest, Start) { MockInterface<winss::MockWindowsInterface> windows; winss::WaitMultiplexer multiplexer; int init = 0; auto callback1 = [&init](winss::WaitMultiplexer&) { init++; }; int triggered = 0; auto callback2 = [&triggered](winss::WaitMultiplexer&, const winss::HandleWrapper&) { triggered++; }; auto callback3 = [&triggered](winss::WaitMultiplexer&, const winss::HandleWrapper&) { triggered++; }; EXPECT_CALL(*windows, WaitForMultipleObjects(_, _, _, _)) .WillOnce(Return(WAIT_OBJECT_0 + 1)) .WillOnce(Return(WAIT_FAILED)); HANDLE handle1 = reinterpret_cast<HANDLE>(10000); winss::HandleWrapper wrapper1(handle1, false); HANDLE handle2 = reinterpret_cast<HANDLE>(20000); winss::HandleWrapper wrapper2(handle2, false); multiplexer.AddInitCallback(callback1); multiplexer.AddTriggeredCallback(wrapper1, callback2); multiplexer.AddTriggeredCallback(wrapper2, callback3); EXPECT_EQ(0, multiplexer.Start()); EXPECT_EQ(1, init); EXPECT_EQ(1, triggered); } TEST_F(WaitMultiplexerTest, StartTimeoutEmpty) { MockInterface<winss::MockWindowsInterface> windows; winss::WaitMultiplexer multiplexer; EXPECT_CALL(*windows, WaitForMultipleObjects(_, _, _, _)) .WillOnce(Return(WAIT_OBJECT_0)); int timeout = 0; auto callback = [&timeout](winss::WaitMultiplexer&) { timeout++; }; multiplexer.AddTimeoutCallback(0, callback); HANDLE handle = reinterpret_cast<HANDLE>(10000); winss::HandleWrapper wrapper(handle, false); int triggered = 0; auto callback2 = [&triggered](winss::WaitMultiplexer&, const winss::HandleWrapper&) { triggered++; }; multiplexer.AddTriggeredCallback(wrapper, callback2); EXPECT_EQ(0, multiplexer.Start()); EXPECT_EQ(1, timeout); EXPECT_EQ(1, triggered); } TEST_F(WaitMultiplexerTest, StartTimeout) { MockInterface<winss::MockWindowsInterface> windows; winss::WaitMultiplexer multiplexer; EXPECT_CALL(*windows, WaitForMultipleObjects(_, _, _, _)) .WillOnce(Return(WAIT_TIMEOUT)) .WillOnce(Return(WAIT_FAILED)); HANDLE handle1 = reinterpret_cast<HANDLE>(10000); winss::HandleWrapper wrapper1(handle1, false); int timeout = 0; auto callback = [&timeout](winss::WaitMultiplexer&) { timeout++; }; multiplexer.AddTimeoutCallback(100, callback); HANDLE handle = reinterpret_cast<HANDLE>(10000); winss::HandleWrapper wrapper(handle, false); int triggered = 0; auto callback2 = [&triggered](winss::WaitMultiplexer&, const winss::HandleWrapper&) { triggered++; }; multiplexer.AddTriggeredCallback(wrapper, callback2); EXPECT_EQ(0, multiplexer.Start()); EXPECT_EQ(1, timeout); EXPECT_EQ(0, triggered); } TEST_F(WaitMultiplexerTest, StartWhenStopped) { winss::WaitMultiplexer multiplexer; int init = 0; auto callback1 = [&init](winss::WaitMultiplexer&) { init++; }; int stop = 0; auto callback2 = [&stop](winss::WaitMultiplexer&) { stop++; }; multiplexer.AddInitCallback(callback1); multiplexer.AddStopCallback(callback2); multiplexer.Stop(5); EXPECT_TRUE(multiplexer.IsStopping()); EXPECT_FALSE(multiplexer.HasStarted()); EXPECT_EQ(5, multiplexer.Start()); EXPECT_EQ(0, init); EXPECT_EQ(1, stop); } TEST_F(WaitMultiplexerTest, Stop) { MockInterface<winss::MockWindowsInterface> windows; winss::WaitMultiplexer multiplexer; EXPECT_CALL(*windows, WaitForMultipleObjects(_, _, _, _)) .WillOnce(Return(WAIT_OBJECT_0)); auto callback1 = [&multiplexer](winss::WaitMultiplexer&, const winss::HandleWrapper&) { multiplexer.Stop(5); }; HANDLE handle1 = reinterpret_cast<HANDLE>(10000); winss::HandleWrapper wrapper1(handle1, false); auto callback2 = [&multiplexer, &wrapper1](winss::WaitMultiplexer&) { multiplexer.RemoveTriggeredCallback(wrapper1); }; multiplexer.AddTriggeredCallback(wrapper1, callback1); multiplexer.AddStopCallback(callback2); multiplexer.Start(); EXPECT_EQ(5, multiplexer.GetReturnCode()); } TEST_F(WaitMultiplexerTest, CloseWaitTriggeredCallback) { MockInterface<winss::MockWindowsInterface> windows; windows->SetupDefaults(); winss::EventWrapper close_event; winss::WaitMultiplexer multiplexer; multiplexer.AddCloseEvent(close_event, 10); std::thread bt([](winss::EventWrapper* evt) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); evt->Set(); }, &close_event); multiplexer.Start(); bt.join(); EXPECT_EQ(10, multiplexer.GetReturnCode()); } } // namespace winss
30.044944
74
0.705061
taylorb-microsoft
9de05338670faed0ba4acde4c12f4500001a0cca
1,614
cpp
C++
Codeforces-Gym/102082A/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
Codeforces-Gym/102082A/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
Codeforces-Gym/102082A/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <bits/stdc++.h> using namespace std; #define SIZE 1010 vector<string> arr[SIZE]; bool cmp(const vector<string> & fst, const vector<string> & snd) { const auto isNum = [](const string & s) { return s[0] >= '0' && s[0] <= '9'; }; int siz = min(fst.size(), snd.size()); for (int i = 0; i < siz; i++) { if (isNum(fst[i]) && isNum(snd[i])) { if (fst[i].size() != snd[i].size()) return fst[i].size() < snd[i].size(); if (fst[i] != snd[i]) return fst[i] < snd[i]; } else if (!isNum(fst[i]) && !isNum(snd[i])) { if (fst[i] != snd[i]) return fst[i] < snd[i]; } else { return isNum(fst[i]); } } return fst.size() <= snd.size(); } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int len; cin >> len; for (int t = 0; t <= len; t++) { string str; cin >> str; int siz = str.size(); string cnt; for (int i = 0; i < siz; i++) { if (str[i] >= '0' && str[i] <= '9') { cnt.push_back(str[i]); continue; } if (cnt.size()) { arr[t].push_back(cnt); cnt.clear(); } cnt.push_back(str[i]); arr[t].push_back(cnt); cnt.clear(); } if (cnt.size()) arr[t].push_back(cnt); } for (int i = 1; i <= len; i++) cout << (cmp(arr[0], arr[i]) ? '+' : '-') << '\n'; return 0; }
29.345455
84
0.401487
codgician
9de5e902a4607854c3bc230c02958dbf367c35cf
22
cpp
C++
src/ErrLib.cpp
TechnikJ/ErrLib
eb2bd9d2b9a01b766a6363e5da737cdc64127940
[ "MIT" ]
null
null
null
src/ErrLib.cpp
TechnikJ/ErrLib
eb2bd9d2b9a01b766a6363e5da737cdc64127940
[ "MIT" ]
null
null
null
src/ErrLib.cpp
TechnikJ/ErrLib
eb2bd9d2b9a01b766a6363e5da737cdc64127940
[ "MIT" ]
null
null
null
#include "ErrLib.hpp"
11
21
0.727273
TechnikJ
9de7ddc7bd36ff6e2b93f967f0a59f43f57cf068
716
cpp
C++
Neural/src/Neural/Renderer/Renderer.cpp
cypexxjulius/Neural
34f2ff2128a530f0952f18d13b22dc5d8b935db8
[ "Apache-2.0" ]
null
null
null
Neural/src/Neural/Renderer/Renderer.cpp
cypexxjulius/Neural
34f2ff2128a530f0952f18d13b22dc5d8b935db8
[ "Apache-2.0" ]
null
null
null
Neural/src/Neural/Renderer/Renderer.cpp
cypexxjulius/Neural
34f2ff2128a530f0952f18d13b22dc5d8b935db8
[ "Apache-2.0" ]
null
null
null
#include "nlpch.h" #include "OrthographicCamera.h" #include "VertexArray.h" #include "Shader.h" #include "Renderer.h" namespace Neural { Renderer::SceneData* Renderer::s_SceneData = new Renderer::SceneData(); void Renderer::beginScene(OrthographicCamera& camera) { s_SceneData->ViewProjMatrix = camera.getViewProjectionMatrix(); } void Renderer::endScene() { } void Renderer::submit(const Ref<Shader>& shader, const Ref<VertexArray>& vertexArray, const glm::mat4& transform) { shader->bind(); shader->uploadUniformMat4("u_ViewProjection", s_SceneData->ViewProjMatrix); shader->uploadUniformMat4("u_Transform", transform); vertexArray->bind(); RenderCommand::drawIndexed(vertexArray); } }
23.096774
114
0.747207
cypexxjulius
9de83bffddba5a98e8c9d991b51dc1427923ad7d
486
cpp
C++
tests/layer.cpp
thechrisyoon08/NeuralNetworks
b47eb6425341c0d0e8278431aaf8b64143ce921f
[ "MIT" ]
1
2018-12-30T05:11:59.000Z
2018-12-30T05:11:59.000Z
tests/layer.cpp
thechrisyoon08/sANNity
b47eb6425341c0d0e8278431aaf8b64143ce921f
[ "MIT" ]
null
null
null
tests/layer.cpp
thechrisyoon08/sANNity
b47eb6425341c0d0e8278431aaf8b64143ce921f
[ "MIT" ]
null
null
null
#include "../include/layer.h" #include <iostream> #include <vector> int main(){ neuralnet::Layer one(3, 4, "linear", "glorot"); neuralnet::Layer two(4, 3, "linear", "glorot"); std::vector<double> input = {0.3, 0.3, 1.0}; one.feed(input); std::cout << "\n"; one.pass_forward(two); std::cout << "\n"; std::cout << one.gradients(); // std::cout << one.get_weights(); // std::cout << "\n"; // std::cout << two.get_weights(); return 0; }
25.578947
51
0.545267
thechrisyoon08
9df4ef4884be5f36159cb4f228ee0abe52d4865a
18,017
cpp
C++
MetroChart.cpp
majioa/metro
a75426fdbc23569330be842cb1f3b3fd8b2178a9
[ "MIT" ]
null
null
null
MetroChart.cpp
majioa/metro
a75426fdbc23569330be842cb1f3b3fd8b2178a9
[ "MIT" ]
null
null
null
MetroChart.cpp
majioa/metro
a75426fdbc23569330be842cb1f3b3fd8b2178a9
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "MetroChart.h" #pragma package(smart_init) //--------------------------------------------------------------------------- // ValidCtrCheck is used to assure that the components created do not have // any pure virtual functions. // static inline void ValidCtrCheck(TMetroChart *) { new TMetroChart(NULL); } //--------------------------------------------------------------------------- __fastcall TMetroChart::TMetroChart(TComponent* Owner) : TGraphicControl(Owner) { FBkgndBmp = new Graphics::TBitmap(); FChartBmp = new Graphics::TBitmap(); FLegendBmp = new Graphics::TBitmap(); FCoeff = TFloatPoint(1,1); } //--------------------------------------------------------------------------- __fastcall TMetroChart::~TMetroChart() { delete FLegendBmp; delete FChartBmp; delete FBkgndBmp; } //--------------------------------------------------------------------------- void __fastcall TMetroChart::Paint() { if(!FMetroData || !FShow) return; if(!FBkgndBmp->Empty) Canvas->BrushCopy(ClientRect,FBkgndBmp,::Rect(0,0,FBkgndBmp->Width,FBkgndBmp->Height),clBackground); else { Canvas->Pen->Color = FMetroData->Color; Canvas->Brush->Color = FMetroData->Color; Canvas->Brush->Style = bsSolid; Canvas->Rectangle(ClientRect); } //TODO: Change Brush copy to TImageList TRect rect = ::Rect(0,0,FChartBmp->Width,FChartBmp->Height); Canvas->BrushCopy(rect,FChartBmp,rect,FMetroData->Color); // Canvas->CopyRect(ClientRect,FChartBmp->Canvas,rect); if(FLegend) { TRect r = ::Rect(0,0,FLegendBmp->Width,FLegendBmp->Height); if(FMetroData->LegendOrient == otHorz) rect = ::Rect(0,rect.Bottom,FLegendBmp->Width,rect.Bottom + FLegendBmp->Height); else rect = ::Rect(rect.Right,0,rect.Right + FLegendBmp->Width,FLegendBmp->Height); Canvas->BrushCopy(rect,FLegendBmp,r,FMetroData->Color); } } //--------------------------------------------------------------------------- void __fastcall TMetroChart::SetMetroData(TMetroData * value) { if(FMetroData == value) return; FMetroData = value; FMetroData->OnAfterLoading = LoadComplete; if(!FMetroData->Empty) LoadComplete(this); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::LoadComplete(TObject * Sender) { FShow = true; if(FMetroData->Background.IsEmpty()) Color = FMetroData->Color; else FBkgndBmp->LoadFromFile(FMetroData->Background); if(!FMetroData->VisibleName.IsEmpty()) { int w = Canvas->TextWidth(FMetroData->VisibleName), h = Canvas->TextHeight(FMetroData->VisibleName); Canvas->Brush->Style = bsClear; Canvas->TextOut((Width - w) / 2, (Height - h) / 2,FMetroData->VisibleName); } MapChartData(); if(FLegend) MapLegendData(); Refresh(); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::SetCoeff(TFloatPoint value) { if(FCoeff.x == value.x && FCoeff.y == value.y) return; FCoeff = value; FChartBmp->Canvas->Font->Size = Canvas->Font->Size * FCoeff.y; MapChartData(); Refresh(); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::MapChartData() { HANDLE i; HLINE k; TColor color; //show train passages FChartBmp->Width = FMetroData->ChartWidth * FCoeff.x; FChartBmp->Height = FMetroData->ChartHeight * FCoeff.y; FChartBmp->Canvas->Brush->Color = FMetroData->Color; FChartBmp->Canvas->FillRect(::Rect(0,0,FChartBmp->Width,FChartBmp->Height)); FMetroData->FindInit(); while ((k = FMetroData->FindLine()) != hNull) { color = FMetroData->GetColor(k); while((i = FMetroData->FindTrainPsg(k)) != hNull) PaintTrain(FChartBmp, FMetroData->CoordsOfPassage(i), color, FMetroData->GetPassageDirection(i)); } //show stations and station names FMetroData->FindInit(); TPoint p; while ((k = FMetroData->FindLine()) != hNull) { color = FMetroData->GetColor(k); while((i = FMetroData->FindStation(k)) != hNull) { p = FMetroData->CoordsOfStation(i); PaintStation(FChartBmp, p, color); PaintStationName(FChartBmp, p, FMetroData->AngleOfStationName(i),FMetroData->CaptionOf(i)); } } //show walk passages FMetroData->FindInit(); while ((i = FMetroData->FindWalkPsg()) != hNull) PaintWalk(FChartBmp, FMetroData->CoordsOfPassage(i),0); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::MapLegendData() { TColor color; float l1, l2, l3, l; int px, py, cols, rows, wd, j1 = 0, j2 = 0, n = 1; HLINE k; TPoint p1, p2; TRect r1, r2; if(!FMetroData) return; if(FMetroData->LegendOrient == loHorz) { cols = FMetroData->LegendCols; l = Width / cols; } else { cols = FMetroData->LegendRows; l = Height / cols; } if(FMetroData->LegendNameAlign != naRight && FMetroData->LegendNameAlign != naLeft) FMetroData->LegendNameAlign = naRight; rows = Ceil((float)(FMetroData->Lines + 1) / cols); wd = (FMetroParams->StationParams + 5) * 2 * FCoeff.x; l1 = l / 8; if(2 * wd > l1) l1 = wd * 2; l2 = l1 / 2 + (l - l1) * (int) (FMetroData->LegendNameAlign == naLeft); if(FMetroData->LegendNameAlign == naLeft) n = -1; l3 = l1 / 2 * n; if(FMetroData->LegendOrient == otHorz) { FLegendBmp->Width = Width; FLegendBmp->Height = rows * wd; } else { FLegendBmp->Width = rows * wd; FLegendBmp->Height = Height; } // FLegendBmp->Canvas->Brush->Color = FMetroData->Color; FLegendBmp->Canvas->Brush->Color = (TColor) 0xffff00; FLegendBmp->Canvas->FillRect(::Rect(0,0,FLegendBmp->Width,FLegendBmp->Height)); FMetroData->FindInit(); while ((k = FMetroData->FindLine()) != hNull) { color = FMetroData->GetColor(k); px = l2 + l * j1; py = wd / 2 + wd * j2; if(FMetroData->LegendOrient == otHorz) { p1 = Point(px, py); p2 = Point(px + l3, py); r1 = ::Rect(px - l3, py, px, py); r2 = ::Rect(px + l3, py, px, py); } else { p1 = Point(py, px); p2 = Point(py, px + l3); r1 = ::Rect(py, px - l3, py, px); r2 = ::Rect(py, px + l3, py, px); } PaintTrialTrain(FLegendBmp, r1, color); PaintTrialTrain(FLegendBmp, r2, color); PaintStation(FLegendBmp, p1, color); PaintLineName(FLegendBmp, p2, FMetroData->LegendNameAlign, FMetroData->CaptionOf(k)); if(++j1 == cols) { j1 = 0; if(++j2 == rows) j2 = 0; } } px = l2 / 2 + l * j1; py = wd / 2 + wd * j2; if(FMetroData->LegendOrient == loHorz) { p1 = Point(px , py); p2 = Point(px + wd / 2, py); } else { p1 = Point(py, px); p2 = Point(py, px + wd / 2); } HSTATION st1, st2; FMetroData->FindInit(); HPASSAGE i = FMetroData->FindWalkPsg(); if(i != hNull || FMetroData->GetPassageStations(i,st1,st2)) { PaintStation(FLegendBmp, p1, FMetroData->GetColor(FMetroData->GetLine(st1))); PaintStation(FLegendBmp, p2, FMetroData->GetColor(FMetroData->GetLine(st2))); PaintWalk(FLegendBmp, ::Rect(p1.x, p1.y, p2.x, p2.y),0); } if(FMetroData->LegendOrient == loHorz) FMetroData->LegendRows = rows; else FMetroData->LegendCols = rows; } //--------------------------------------------------------------------------- void __fastcall TMetroChart::PaintStation(Graphics::TBitmap *bmp, TPoint p, TColor color) { int r; if(FMetroData->StationBorder) bmp->Canvas->Pen->Color = FMetroData->StationBorderColor; if (FMetroData->StationBlank) { r = FMetroParams->StationRadius + FMetroParams->StationBlank; if(!FMetroData->StationBorder) bmp->Canvas->Pen->Color = FMetroData->StationBlankColor; bmp->Canvas->Brush->Color = FMetroData->StationBlankColor; bmp->Canvas->Ellipse(Rect(p.x - r, p.y - r, p.x + r + 1, p.y + r + 1,FCoeff)); bmp->Canvas->Pen->Color = color; } else if(!FMetroData->StationBorder) bmp->Canvas->Pen->Color = color; r = FMetroParams->StationRadius; bmp->Canvas->Brush->Color = color; bmp->Canvas->Ellipse(Rect(p.x - r, p.y - r, p.x + r + 1, p.y + r + 1,FCoeff)); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::PaintStationName(Graphics::TBitmap *bmp, TPoint p, unsigned int a, AnsiString name) { if(a == -1) return; if(a >= 360) { if(bmp->Height / 2 < p.y) a = 180; else a = 0; if(bmp->Width / 2 < p.x) a += 90; else a += 270; if(a >= 360) a %= 360; } long double sin, cos; SinCos(Pi * a / 180, sin, cos); TRect l = GetCalcRect(::Rect(p.x, p.y, p.x, p.y), FMetroParams->StationRadius + FMetroParams->StationBlank + FMetroParams->StationShift, sin, cos); bmp->Canvas->Font->Color = FMetroData->MetroObjectNameColor; TFontStyles fs; fs << fsItalic << fsBold; bmp->Canvas->Font->Style = fs; if(a == 180 || !a) l.Top -= abs(bmp->Canvas->Font->Height) / 2 + 1; if(a == 90 || a == 270) l.Left -= bmp->Canvas->TextWidth(name) / 2 + 1; if(a > 180) l.Top -= abs(bmp->Canvas->Font->Height); if(a < 90 || a > 270) l.Left -= bmp->Canvas->TextWidth(name); bmp->Canvas->Brush->Style = bsClear; bmp->Canvas->TextOut(l.Left, l.Top, name); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::PaintTrain(Graphics::TBitmap *bmp, TRect r, TColor color, TPassageDirection dir) { PaintRect(bmp, r, FMetroParams->LineWidth, FMetroParams->StationRadius, FMetroParams->StationBlank + FMetroParams->StationShift,color, rmCutEdges, dir); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::PaintWalk(Graphics::TBitmap *bmp, TRect r, int angle) { if(angle >= 360) return; if(!angle || angle == 180) return PaintRect(bmp, r, FMetroParams->PassageWidth, FMetroParams->StationRadius + 1, FMetroParams->StationBlank, FMetroData->WalkPsgColor, rmShowBorder, pdWalkTwoDirectional); //convert r; TRect l = ChordRect(r,angle); if(angle > 180) Canvas->Arc(l.Left, l.Top, l.Right, l.Bottom, r.Right, r.Bottom, r.Left, r.Top); else Canvas->Arc(l.Left, l.Top, l.Right, l.Bottom, r.Left, r.Top, r.Right, r.Bottom); l = ChordRect(r,angle); if(angle > 180) Canvas->Arc(l.Left, l.Top, l.Right, l.Bottom, r.Right, r.Bottom, r.Left, r.Top); else Canvas->Arc(l.Left, l.Top, l.Right, l.Bottom, r.Left, r.Top, r.Right, r.Bottom); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::PaintRect(Graphics::TBitmap *bmp, TRect r, int len, int shift, int blank, TColor color, TShowRectMode mode, TPassageDirection dir) { int x1, y1; long double a, sina, cosa; if(r.Left - r.Right) a = ArcTan2((r.Top - r.Bottom),(r.Left - r.Right)); else { a = Pi / 2; if(r.Top - r.Bottom < 0) a = -a; } SinCos(a,sina,cosa); TRect l = GetCalcRect(r, shift, sina, cosa); // x1 = Round(len * sina / 2); // y1 = Round(len * cosa / 2); x1 = Floor(len * sina / 2); y1 = Floor(len * cosa / 2); TPoint p[4]; p[0] = Point((l.Left + x1) * FCoeff.x, (l.Top - y1) * FCoeff.y); p[1] = Point((l.Left - x1) * FCoeff.x, (l.Top + y1) * FCoeff.y); p[2] = Point((l.Right - x1) * FCoeff.x, (l.Bottom + y1) * FCoeff.y); p[3] = Point((l.Right + x1) * FCoeff.x, (l.Bottom - y1) * FCoeff.y); bmp->Canvas->Pen->Color = color; bmp->Canvas->Brush->Color = color; bmp->Canvas->Polygon(p,3); switch(mode) { case rmCutEdges: bmp->Canvas->Pen->Color = FMetroData->Color; bmp->Canvas->Brush->Color = FMetroData->Color; CutFwdEdge(bmp, r, shift, blank, x1, y1); CutBwdEdge(bmp, r, shift, blank, x1, y1); break; case rmCutFwdEdge: bmp->Canvas->Pen->Color = FMetroData->Color; bmp->Canvas->Brush->Color = FMetroData->Color; CutFwdEdge(bmp, r, shift, blank, x1, y1); break; case rmCutBwdEdge: bmp->Canvas->Pen->Color = FMetroData->Color; bmp->Canvas->Brush->Color = FMetroData->Color; CutBwdEdge(bmp, r, shift, blank, x1, y1); break; case rmShowBorder: bmp->Canvas->Pen->Color = FMetroData->StationBorderColor; bmp->Canvas->MoveTo (p[0].x, p[0].y); bmp->Canvas->Pixels[p[3].x][p[3].y] = bmp->Canvas->Pen->Color; bmp->Canvas->LineTo (p[3].x, p[3].y); bmp->Canvas->MoveTo (p[2].x, p[2].y); bmp->Canvas->Pixels[p[1].x][p[1].y] = bmp->Canvas->Pen->Color; bmp->Canvas->LineTo (p[1].x, p[1].y); } switch(dir) { case pdForwardOnly: PaintTriangle(bmp, (r.Left + r.Right) / 2, (r.Top + r.Bottom) / 2, x1, y1, true); break; case pdBackwardOnly: PaintTriangle(bmp, (r.Left + r.Right) / 2, (r.Top + r.Bottom) / 2, x1, y1, false); break; case pdDifferentWays: PaintTriangle(bmp, r.Left + (r.Right - r.Left) / 3, r.Top + (r.bottom - r.Top) / 3, x1, y1, true); PaintTriangle(bmp, r.Right - (r.Right - r.Left) / 3, r.Bottom - (r.bottom - r.Top) / 3, x1, y1, false); } } //--------------------------------------------------------------------------- void __fastcall TMetroChart::PaintTriangle(Graphics::TBitmap *bmp, int lx, int ly, int x1, int y1, bool fl) { TPoint p[3]; bmp->Canvas->Pen->Color = FMetroData->Color; bmp->Canvas->Brush->Color = FMetroData->Color; p[0] = Point((lx - x1) * FCoeff.x, (ly - y1) * FCoeff.y); p[1] = Point((lx + x1) * FCoeff.x, (ly + y1) * FCoeff.y); if(fl) p[2] = Point((lx + y1) * FCoeff.x, (ly + x1) * FCoeff.y); else p[2] = Point((lx - y1) * FCoeff.x, (ly - x1) * FCoeff.y); bmp->Canvas->Polygon(p,2); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::PaintLineName(Graphics::TBitmap *bmp, TPoint p, TNameAlign na, AnsiString name) { if(na == naLeft) p.x -= bmp->Canvas->TextWidth(name); p.y -= abs(bmp->Canvas->Font->Height) / 2 + 1; bmp->Canvas->Brush->Style = bsClear; bmp->Canvas->TextOut(p.x, p.y, name); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::PaintTrialTrain(Graphics::TBitmap *bmp, TRect r, TColor color) { PaintRect(bmp, r, FMetroParams->LineWidth, FMetroParams->StationRadius, FMetroParams->StationBlank + FMetroParams->StationShift, color, rmCutEdges, pdTwoDirectional); // PaintRect(bmp, r, FMetroParams->LineWidth, FMetroParams->StationRadius, FMetroParams->StationBlank + FMetroParams->StationShift, color, rmCutBwdEdge, pdTwoDirectional); } //--------------------------------------------------------------------------- TRect __fastcall TMetroChart::GetCalcRect(TRect r, int len, long double sin, long double cos) { // int x1 = Round(len * cos), y1 = Round(len * sin); int x1 = Floor(len * cos), y1 = Floor(len * sin); return ::Rect(r.Left - x1, r.Top - y1, r.Right + x1, r.Bottom + y1); } //--------------------------------------------------------------------------- TRect __fastcall TMetroChart::Rect(int left, int top, int right, int bottom, TFloatPoint coeff) { return ::Rect(left * coeff.x, top * coeff.y, right * coeff.x, bottom * coeff.y); } //--------------------------------------------------------------------------- TRect __fastcall TMetroChart::ChordRect(TRect r, int angle) { Extended d, a, b, x, y, sin, cos, beta; TRect l; int xl = r.Right - r.Left, yl = r.Bottom - r.Top; SinCos(((long double) angle) * Pi / 360, sin, cos);//360 is 180 * 2 ( Pi / 360 = (Pi / 180) / 2) a = Power(Power(xl, 2) + Power(yl, 2), 0.5) / 2; d = 2 * a / sin; b = a * cos / 2 / sin; if(yl) beta = ArcTan2(xl, yl); else { if(xl < 0) beta = 3 * Pi / 2; else beta = Pi / 2; } SinCos(beta, sin, cos); x = (r.Left + r.Right) / 2 - b * sin; y = (r.Top + r.Bottom) / 2 + b * cos; return ::Rect(Floor(x - d), Floor(y - d), Floor(x + d), Floor(y + d)); } //--------------------------------------------------------------------------- void __fastcall TMetroChart::SetMetroParams(TMetroParams * value) { if(FMetroParams == value) return; FMetroParams = value; } //--------------------------------------------------------------------------- void __fastcall TMetroChart::SetLegend(bool value) { if(FLegend == value) return; FLegend = value; if(value) MapLegendData(); } //--------------------------------------------------------------------------- namespace Metrochart { void __fastcall PACKAGE Register() { TComponentClass classes[1] = {__classid(TMetroChart)}; RegisterComponents("Metro", classes, 0); } } void __fastcall TMetroChart::CutFwdEdge(Graphics::TBitmap *bmp, TRect r, int shift, int blank, int x1, int y1) { TRect l = Rect(r.Left - shift - blank, r.Top - shift - blank, r.Left + shift + blank, r.Top + shift + blank, FCoeff); bmp->Canvas->Chord(l.Left, l.Top, l.Right, l.Bottom, r.Left + x1, r.Top - y1, r.Left - x1, r.Top + y1); } void __fastcall TMetroChart::CutBwdEdge(Graphics::TBitmap * bmp, TRect r, int shift, int blank, int x1, int y1) { TRect l = Rect(r.Right - shift - blank, r.Bottom - shift - blank, r.Right + shift + blank, r.Bottom + shift + blank, FCoeff); bmp->Canvas->Chord(l.Left, l.Top, l.Right, l.Bottom, r.Right - x1, r.Bottom + y1, r.Right + x1, r.Bottom - y1); }
35.962076
181
0.546206
majioa
9df64fb4a86a6e9eca441217b5ce8707fb221dc7
3,780
cpp
C++
main_app/src/mainapp.cpp
cracked-machine/BassStationSequencerSW
aefe63fa85440165dceb9cef65ec1a68a514ec02
[ "MIT" ]
null
null
null
main_app/src/mainapp.cpp
cracked-machine/BassStationSequencerSW
aefe63fa85440165dceb9cef65ec1a68a514ec02
[ "MIT" ]
21
2021-12-12T10:19:07.000Z
2022-03-11T13:42:13.000Z
main_app/src/mainapp.cpp
cracked-machine/BassStationSequencerSW
aefe63fa85440165dceb9cef65ec1a68a514ec02
[ "MIT" ]
null
null
null
// MIT License // Copyright (c) 2022 Chris Sutton // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "mainapp.hpp" #include <sequence_manager.hpp> #include <timer_manager.hpp> #include <adp5587.hpp> #include <file_manager.hpp> #ifdef __cplusplus extern "C" { #endif void error_handler() { while(true) { } } void mainapp() { // initialise the timer used for system wide microsecond timeout if (stm32::TimerManager::initialise(TIM6) == false) { error_handler(); } // setup fatfs support for uSDCard fatfs::DiskioProtocolSPI fatfs_spi_interface ( SPI2, std::make_pair(GPIOB, GPIO_BSRR_BS8), // sck - PB8 std::make_pair(GPIOB, GPIO_BSRR_BS7), // mosi - PB7 std::make_pair(GPIOD, GPIO_BSRR_BS3), // miso - PD3 std::make_pair(GPIOD, GPIO_BSRR_BS2), // cs - PD2 RCC_APBENR1_SPI2EN ); bass_station::FileManager spi_fm(fatfs_spi_interface); // Timer peripheral for sequencer manager rotary encoder control TIM_TypeDef *sequencer_encoder_timer = TIM1; // SPI peripheral for SSD1306 display driver serial communication ssd1306::DriverSerialInterface<STM32G0_ISR> ssd1306_spi_interface( SPI1, std::make_pair(GPIOA, GPIO_BSRR_BS0), // PA0 - DC std::make_pair(GPIOA, GPIO_BSRR_BS3), // PA3 - Reset STM32G0_ISR::dma1_ch2); // I2C peripheral for keypad manager serial communication I2C_TypeDef *ad5587_keypad_i2c = I2C3; // keypad debounce timer TIM_TypeDef *general_purpose_debounce_timer = TIM17; // I2C periperhal for synth output control switch serial communication I2C_TypeDef *adg2188_control_sw_i2c = I2C2; // std::pair<GPIO_TypeDef*, uint16_t> test (GPIOB, GPIO_BSRR_BS9); // SPI peripheral for TLC5955 LED driver serial communication tlc5955::DriverSerialInterface tlc5955_spi_interface( SPI2, std::make_pair(GPIOB, GPIO_BSRR_BS9), // latch port+pin std::make_pair(GPIOB, GPIO_BSRR_BS7), // mosi port+pin std::make_pair(GPIOB, GPIO_BSRR_BS8), // sck port+pin std::make_pair(TIM4, TIM_CCER_CC1E), // gsclk timer+channel RCC_IOPENR_GPIOBEN, // for enabling GPIOB clock RCC_APBENR1_SPI2EN // for enabling SPI2 clock ); // The USART and Timer used to send the MIDI heartbeat midi_stm32::DeviceInterface<STM32G0_ISR> midi_usart_interface( USART5, STM32G0_ISR::usart5 ); // initialise the sequencer bass_station::SequenceManager sequencer( std::make_pair(TIM3, STM32G0_ISR::tim3), // Timer peripheral for sequencer manager tempo control sequencer_encoder_timer, ssd1306_spi_interface, ad5587_keypad_i2c, general_purpose_debounce_timer, adg2188_control_sw_i2c, tlc5955_spi_interface, midi_usart_interface); sequencer.main_loop(); // we should never get past here } #ifdef __cplusplus } #endif
30.983607
98
0.749735
cracked-machine
9df76540d7179aaef4dc1250d4c396d84784ab38
2,665
cpp
C++
src/OpcUaStackCore/Utility/CSV.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaStackCore/Utility/CSV.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaStackCore/Utility/CSV.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2016 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include <boost/tokenizer.hpp> #include "OpcUaStackCore/Base/Log.h" #include "OpcUaStackCore/Utility/CSV.h" #define MAX_LINE_LEN 1000000 namespace OpcUaStackCore { CSV::CSV(void) : delimiter_(",") , fileName_("") , ifFile_() , ofFile_() , lineNumber_(0) { } CSV::~CSV(void) { close(); } void CSV::delimiter(const std::string& delimiter) { delimiter_ = delimiter; } bool CSV::open(const std::string& fileName, Mode mode) { fileName_ = fileName; if (mode == M_Read) { ifFile_.open(fileName_.c_str(), std::ifstream::in); if (!ifFile_.is_open()) { Log(Error, "open csv file error for reading") .parameter("FileName", fileName_); fileName_ = ""; return false; } } else { ofFile_.open(fileName_.c_str(), std::ofstream::out); if (!ofFile_.is_open()) { Log(Error, "open csv file error for writing") .parameter("FileName", fileName_); fileName_ = ""; return false; } } lineNumber_ = 0; return true; } bool CSV::close(void) { if (ifFile_.is_open()) { ifFile_.close(); } if (ofFile_.is_open()) { ofFile_.close(); } return true; } CSV::State CSV::readLine(Line& line) { lineNumber_++; char lineBuffer[MAX_LINE_LEN]; if (!ifFile_.getline(lineBuffer, MAX_LINE_LEN)) { return S_EndOfFile; } std::string str(lineBuffer); std::vector<std::string> vec; boost::escaped_list_separator<char> els("\\", delimiter_, "\""); boost::tokenizer<boost::escaped_list_separator<char> > tok(str, els); boost::tokenizer<boost::escaped_list_separator<char> >::iterator it; for(it=tok.begin(); it!=tok.end(); ++it) { line.push_back(*it); } return S_Ok; } CSV::State CSV::writeLine(Line& line) { for (uint32_t idx=0; idx<line.size(); idx++) { if (idx != 0) { ofFile_ << ","; } ofFile_ << "\"" << line[idx] << "\""; } ofFile_ << std::endl; return S_Ok; } uint32_t CSV::lineNumber(void) { return lineNumber_; } }
20.343511
86
0.660788
gianricardo
9df95a8f14f8281fad16d08d19df2f078ae04ada
1,357
cpp
C++
lemonade2.3 (OrderManager)/OrderManager.cpp
sspony/stuff
25ab31954873cbbcfec6bf6dcb688e6433891f4e
[ "MIT" ]
null
null
null
lemonade2.3 (OrderManager)/OrderManager.cpp
sspony/stuff
25ab31954873cbbcfec6bf6dcb688e6433891f4e
[ "MIT" ]
null
null
null
lemonade2.3 (OrderManager)/OrderManager.cpp
sspony/stuff
25ab31954873cbbcfec6bf6dcb688e6433891f4e
[ "MIT" ]
null
null
null
#include "orderManager.h" OrderManager::OrderManager(std::vector<std::vector<std::string>>& csvData) { if (ITEM_LOG) std::clog << "\n\n***** [INFO] - OrderManager.cpp - OrderManager(....) START\n"; for (auto row : csvData) { try { orderList.push_back(std::move(Order(row))); } catch (const std::string& e) { std::cerr << e << "\n"; } } if (ITEM_LOG) std::clog << "***** [INFO] - OrderManager.cpp - OrderManager(....) END\n\n"; } void OrderManager::print() { if (ORDER_LOG) std::clog << "\n\n***** [INFO] - OrderManager.cpp - print() START\n"; for (auto t : orderList) { t.print(); } if (ORDER_LOG) std::clog << "***** [INFO] - OrderManager.cpp - print() END\n\n"; } void OrderManager::graph(std::string & fileName) { std::string f = fileName + ".gv"; std::fstream os(f, std::ios::out | std::ios::trunc); os << "digraph taskGraph {\n"; for (auto o : orderList) { o.graph(os); } os << "}\n"; os.close(); // linux command //std::string cmd = std::string("dot -Tpng ") + fileName + ".gv > " + fileName + ".gv.png"; // windows command std::string cmd = "\"C:\\Program Files (x86)\\Graphviz2.38\\bin\\dot.exe\" -Tpng " + fileName + ".gv -o " + fileName + ".gv.png"; std::cout << "\n***** running: " << cmd << "\n"; system(cmd.c_str()); std::cout << "\n"; }
25.603774
131
0.551953
sspony
9dfef309c7718711bf3750e3a46ccae911a0c580
3,673
cpp
C++
mysqlparser/base/profiling.cpp
aasthakm/qapla
f98ca92adbca75fee28587e540b8c851809c7a62
[ "BSD-4-Clause" ]
4
2020-12-13T15:02:40.000Z
2021-07-16T06:23:38.000Z
mysqlparser/base/profiling.cpp
aasthakm/qapla
f98ca92adbca75fee28587e540b8c851809c7a62
[ "BSD-4-Clause" ]
null
null
null
mysqlparser/base/profiling.cpp
aasthakm/qapla
f98ca92adbca75fee28587e540b8c851809c7a62
[ "BSD-4-Clause" ]
null
null
null
/* * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; version 2 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "base/profiling.h" #include "base/log.h" #include "base/string_utilities.h" #include <cmath> DEFAULT_LOG_DOMAIN("Profiling") namespace base { TimeAccumulator create_global_ta() { TimeAccumulator _ta; return _ta; } StopWatch create_global_sw() { StopWatch _sw; return _sw; } TimeAccumulator GlobalTA::_tacc = create_global_ta(); StopWatch GlobalSW::_sw = create_global_sw(); //----------------- Time Check -------------------------------------------------------- std::string StopWatch::format_time(clock_t time) { float s = ((float)time) / ((float)CLOCKS_PER_SEC); int m = (int)(s / 60); s -= (m*60); int h = m / 60; m -= (h*60); return base::strfmt("%02d:%02d:%02.3f", h, m, s); } void StopWatch::start(const std::string& message) { _initialized = true; _start = clock(); _lap_start = _start; log_debug("---> %s - [STARTED] %s\n", format_time(0).data(), message.data()); } //------------------------------------------------------------------------------------- void StopWatch::lap(const std::string& message) { if (_initialized) { _end = clock(); clock_t diff = _end - _lap_start; log_debug("---> %s - [LAP] %s\n", format_time(diff).data(), message.data()); _lap_start = _end; } } void StopWatch::stop(const std::string& message) { if (_initialized) { _end = clock(); clock_t diff = _end - _start; log_debug("---> %s - [COMPLETED] %s\n", format_time(diff).data(), message.data()); } } //----------------- Time Profiler ----------------------------------------------------- void TimeAccumulator::add(const std::string& id) { _accumulators[id] = 0; _starts[id] = 0; } //------------------------------------------------------------------------------------- void TimeAccumulator::on(const std::string& id) { clock_t current = clock(); _starts[id] = current; } //------------------------------------------------------------------------------------- void TimeAccumulator::off(const std::string& id) { clock_t current = clock(); double diff = current - _starts[id]; double acc = _accumulators[id]; acc += diff; _accumulators[id] = acc; } //------------------------------------------------------------------------------------- void TimeAccumulator::dump(const std::string& message) { std::map<std::string, double>::const_iterator index, end = _accumulators.end(); log_debug("Dumping data for : %s\n", message.data()); for(index = _accumulators.begin(); index != end; index++) { log_debug("--->Time on accumulator %s : %lf\n", index->first.data(), index->second / CLOCKS_PER_SEC); } } //------------------------------------------------------------------------------------- void TimeAccumulator::clear() { _accumulators.clear(); _starts.clear(); } //------------------------------------------------------------------------------------- } //namespace base
27.616541
105
0.544242
aasthakm
3b05356b87afe0ff0801412838c6c00b0dcea67c
33
cpp
C++
src/engine/flat_base.cpp
tanaka141/c10t
3cc0ac4cdb7f09767d16632539db747be8a3eb21
[ "BSD-3-Clause" ]
48
2015-01-27T15:18:23.000Z
2022-02-12T16:26:18.000Z
src/engine/flat_base.cpp
tanaka141/c10t
3cc0ac4cdb7f09767d16632539db747be8a3eb21
[ "BSD-3-Clause" ]
17
2015-12-16T04:26:12.000Z
2022-02-09T07:52:19.000Z
src/engine/flat_base.cpp
tanaka141/c10t
3cc0ac4cdb7f09767d16632539db747be8a3eb21
[ "BSD-3-Clause" ]
14
2015-01-16T00:15:44.000Z
2022-03-21T08:36:02.000Z
#include "engine/flat_base.hpp"
11
31
0.757576
tanaka141
3b09664ea655aaff9008427a637829297e6aefe4
48,726
cpp
C++
compiler/codegen_llvm/lib/lumen/EIR/IR/EIROps.cpp
Tuxified/lumen
e0683aa6de440d1dfd8b7e590ab9742c0d1429b7
[ "Apache-2.0" ]
null
null
null
compiler/codegen_llvm/lib/lumen/EIR/IR/EIROps.cpp
Tuxified/lumen
e0683aa6de440d1dfd8b7e590ab9742c0d1429b7
[ "Apache-2.0" ]
null
null
null
compiler/codegen_llvm/lib/lumen/EIR/IR/EIROps.cpp
Tuxified/lumen
e0683aa6de440d1dfd8b7e590ab9742c0d1429b7
[ "Apache-2.0" ]
null
null
null
#include "lumen/EIR/IR/EIROps.h" #include "lumen/EIR/IR/EIRAttributes.h" #include "lumen/EIR/IR/EIRTypes.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Diagnostics.h" #include "mlir/IR/FunctionImplementation.h" #include "mlir/IR/Matchers.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/OperationSupport.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/TypeUtilities.h" #include "mlir/IR/Value.h" #include "mlir/Support/LLVM.h" #include "mlir/Support/LogicalResult.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Casting.h" #include "llvm/Support/SMLoc.h" #include <iterator> #include <vector> using namespace lumen; using namespace lumen::eir; using ::llvm::ArrayRef; using ::llvm::SmallVector; using ::llvm::StringRef; using ::llvm::dyn_cast_or_null; using ::llvm::cast; using ::llvm::isa; using ::mlir::OpOperand; namespace lumen { namespace eir { //===----------------------------------------------------------------------===// // eir.func //===----------------------------------------------------------------------===// static ParseResult parseFuncOp(OpAsmParser &parser, OperationState &result) { auto buildFuncType = [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results, mlir::impl::VariadicFlag, std::string &) { return builder.getFunctionType(argTypes, results); }; return mlir::impl::parseFunctionLikeOp( parser, result, /*allowVariadic=*/false, buildFuncType); } static void print(OpAsmPrinter &p, FuncOp &op) { FunctionType fnType = op.getType(); mlir::impl::printFunctionLikeOp(p, op, fnType.getInputs(), /*isVariadic=*/false, fnType.getResults()); } FuncOp FuncOp::create(Location location, StringRef name, FunctionType type, ArrayRef<NamedAttribute> attrs) { OperationState state(location, FuncOp::getOperationName()); OpBuilder builder(location->getContext()); FuncOp::build(builder, state, name, type, attrs); return cast<FuncOp>(Operation::create(state)); } void FuncOp::build(OpBuilder &builder, OperationState &result, StringRef name, FunctionType type, ArrayRef<NamedAttribute> attrs, ArrayRef<MutableDictionaryAttr> argAttrs) { result.addRegion(); result.addAttribute(SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)); result.addAttribute("type", TypeAttr::get(type)); result.attributes.append(attrs.begin(), attrs.end()); if (argAttrs.empty()) { return; } if (argAttrs.empty()) return; unsigned numInputs = type.getNumInputs(); assert(numInputs == argAttrs.size() && "expected as many argument attribute lists as arguments"); SmallString<8> argAttrName; for (unsigned i = 0, e = numInputs; i != e; ++i) if (auto argDict = argAttrs[i].getDictionary(builder.getContext())) result.addAttribute(getArgAttrName(i, argAttrName), argDict); } Block *FuncOp::addEntryBlock() { assert(empty() && "function already has an entry block"); auto *entry = new Block(); push_back(entry); entry->addArguments(getType().getInputs()); return entry; } LogicalResult FuncOp::verifyType() { auto type = getTypeAttr().getValue(); if (!type.isa<FunctionType>()) return emitOpError("requires '" + getTypeAttrName() + "' attribute of function type"); return success(); } Region *FuncOp::getCallableRegion() { return &body(); } ArrayRef<Type> FuncOp::getCallableResults() { assert(!isExternal() && "invalid callable"); return getType().getResults(); } //===----------------------------------------------------------------------===// // eir.call_indirect //===----------------------------------------------------------------------===// namespace { /// Fold indirect calls that have a constant function as the callee operand. struct SimplifyIndirectCallWithKnownCallee : public OpRewritePattern<CallIndirectOp> { using OpRewritePattern<CallIndirectOp>::OpRewritePattern; LogicalResult matchAndRewrite(CallIndirectOp indirectCall, PatternRewriter &rewriter) const override { // Check that the callee is a constant callee. FlatSymbolRefAttr calledFn; if (!matchPattern(indirectCall.getCallee(), ::mlir::m_Constant(&calledFn))) return failure(); // Replace with a direct call. rewriter.replaceOpWithNewOp<CallOp>(indirectCall, calledFn, indirectCall.getResultTypes(), indirectCall.getArgOperands()); return success(); } }; } // end anonymous namespace. void CallIndirectOp::getCanonicalizationPatterns( OwningRewritePatternList &results, MLIRContext *context) { results.insert<SimplifyIndirectCallWithKnownCallee>(context); } //===----------------------------------------------------------------------===// // eir.br //===----------------------------------------------------------------------===// /// Given a successor, try to collapse it to a new destination if it only /// contains a passthrough unconditional branch. If the successor is /// collapsable, `successor` and `successorOperands` are updated to reference /// the new destination and values. `argStorage` is an optional storage to use /// if operands to the collapsed successor need to be remapped. static LogicalResult collapseBranch(Block *&successor, ValueRange &successorOperands, SmallVectorImpl<Value> &argStorage) { // Check that the successor only contains a unconditional branch. if (std::next(successor->begin()) != successor->end()) return failure(); // Check that the terminator is an unconditional branch. BranchOp successorBranch = dyn_cast<BranchOp>(successor->getTerminator()); if (!successorBranch) return failure(); // Check that the arguments are only used within the terminator. for (BlockArgument arg : successor->getArguments()) { for (Operation *user : arg.getUsers()) if (user != successorBranch) return failure(); } // Don't try to collapse branches to infinite loops. Block *successorDest = successorBranch.getDest(); if (successorDest == successor) return failure(); // Update the operands to the successor. If the branch parent has no // arguments, we can use the branch operands directly. OperandRange operands = successorBranch.getOperands(); if (successor->args_empty()) { successor = successorDest; successorOperands = operands; return success(); } // Otherwise, we need to remap any argument operands. for (Value operand : operands) { BlockArgument argOperand = operand.dyn_cast<BlockArgument>(); if (argOperand && argOperand.getOwner() == successor) argStorage.push_back(successorOperands[argOperand.getArgNumber()]); else argStorage.push_back(operand); } successor = successorDest; successorOperands = argStorage; return success(); } namespace { /// Simplify a branch to a block that has a single predecessor. This effectively /// merges the two blocks. struct SimplifyBrToBlockWithSinglePred : public OpRewritePattern<BranchOp> { using OpRewritePattern<BranchOp>::OpRewritePattern; LogicalResult matchAndRewrite(BranchOp op, PatternRewriter &rewriter) const override { // Check that the successor block has a single predecessor. Block *succ = op.getDest(); Block *opParent = op.getOperation()->getBlock(); if (succ == opParent || !llvm::hasSingleElement(succ->getPredecessors())) return failure(); // Merge the successor into the current block and erase the branch. rewriter.mergeBlocks(succ, opParent, op.getOperands()); rewriter.eraseOp(op); return success(); } }; /// br ^bb1 /// ^bb1 /// br ^bbN(...) /// /// -> br ^bbN(...) /// struct SimplifyPassThroughBr : public OpRewritePattern<BranchOp> { using OpRewritePattern<BranchOp>::OpRewritePattern; LogicalResult matchAndRewrite(BranchOp op, PatternRewriter &rewriter) const override { Block *dest = op.getDest(); ValueRange destOperands = op.getOperands(); SmallVector<Value, 4> destOperandStorage; // Try to collapse the successor if it points somewhere other than this // block. if (dest == op.getOperation()->getBlock() || failed(collapseBranch(dest, destOperands, destOperandStorage))) return failure(); // Create a new branch with the collapsed successor. rewriter.replaceOpWithNewOp<BranchOp>(op, dest, destOperands); return success(); } }; } // namespace void BranchOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { results.insert<SimplifyBrToBlockWithSinglePred, SimplifyPassThroughBr>(context); } Optional<MutableOperandRange> BranchOp::getMutableSuccessorOperands( unsigned index) { assert(index == 0 && "invalid successor index"); return destOperandsMutable(); } Block *BranchOp::getSuccessorForOperands(ArrayRef<Attribute>) { return dest(); } //===----------------------------------------------------------------------===// // eir.cond_br //===----------------------------------------------------------------------===// namespace { /// eir.cond_br true, ^bb1, ^bb2 -> br ^bb1 /// eir.cond_br false, ^bb1, ^bb2 -> br ^bb2 /// struct SimplifyConstCondBranchPred : public OpRewritePattern<CondBranchOp> { using OpRewritePattern<CondBranchOp>::OpRewritePattern; LogicalResult matchAndRewrite(CondBranchOp condbr, PatternRewriter &rewriter) const override { if (matchPattern(condbr.getCondition(), mlir::m_NonZero())) { // True branch taken. rewriter.replaceOpWithNewOp<BranchOp>(condbr, condbr.getTrueDest(), condbr.getTrueOperands()); return success(); } else if (matchPattern(condbr.getCondition(), mlir::m_Zero())) { // False branch taken. rewriter.replaceOpWithNewOp<BranchOp>(condbr, condbr.getFalseDest(), condbr.getFalseOperands()); return success(); } return failure(); } }; /// cond_br %cond, ^bb1, ^bb2 /// ^bb1 /// br ^bbN(...) /// ^bb2 /// br ^bbK(...) /// /// -> cond_br %cond, ^bbN(...), ^bbK(...) /// struct SimplifyPassThroughCondBranch : public OpRewritePattern<CondBranchOp> { using OpRewritePattern<CondBranchOp>::OpRewritePattern; LogicalResult matchAndRewrite(CondBranchOp condbr, PatternRewriter &rewriter) const override { Block *trueDest = condbr.trueDest(), *falseDest = condbr.falseDest(); ValueRange trueDestOperands = condbr.getTrueOperands(); ValueRange falseDestOperands = condbr.getFalseOperands(); SmallVector<Value, 4> trueDestOperandStorage, falseDestOperandStorage; // Try to collapse one of the current successors. LogicalResult collapsedTrue = collapseBranch(trueDest, trueDestOperands, trueDestOperandStorage); LogicalResult collapsedFalse = collapseBranch(falseDest, falseDestOperands, falseDestOperandStorage); if (failed(collapsedTrue) && failed(collapsedFalse)) return failure(); // Create a new branch with the collapsed successors. rewriter.replaceOpWithNewOp<CondBranchOp>(condbr, condbr.getCondition(), trueDest, trueDestOperands, falseDest, falseDestOperands); return success(); } }; /// cond_br %cond, ^bb1(A, ..., N), ^bb1(A, ..., N) /// -> br ^bb1(A, ..., N) /// /// cond_br %cond, ^bb1(A), ^bb1(B) /// -> %select = select %cond, A, B /// br ^bb1(%select) /// struct SimplifyCondBranchIdenticalSuccessors : public OpRewritePattern<CondBranchOp> { using OpRewritePattern<CondBranchOp>::OpRewritePattern; LogicalResult matchAndRewrite(CondBranchOp condbr, PatternRewriter &rewriter) const override { // Check that the true and false destinations are the same and have the same // operands. Block *trueDest = condbr.trueDest(); if (trueDest != condbr.falseDest()) return failure(); // If all of the operands match, no selects need to be generated. OperandRange trueOperands = condbr.getTrueOperands(); OperandRange falseOperands = condbr.getFalseOperands(); if (trueOperands == falseOperands) { rewriter.replaceOpWithNewOp<BranchOp>(condbr, trueDest, trueOperands); return success(); } // Otherwise, if the current block is the only predecessor insert selects // for any mismatched branch operands. if (trueDest->getUniquePredecessor() != condbr.getOperation()->getBlock()) return failure(); // Generate a select for any operands that differ between the two. SmallVector<Value, 8> mergedOperands; mergedOperands.reserve(trueOperands.size()); Value condition = condbr.getCondition(); for (auto it : llvm::zip(trueOperands, falseOperands)) { if (std::get<0>(it) == std::get<1>(it)) mergedOperands.push_back(std::get<0>(it)); else mergedOperands.push_back(rewriter.create<mlir::SelectOp>( condbr.getLoc(), condition, std::get<0>(it), std::get<1>(it))); } rewriter.replaceOpWithNewOp<BranchOp>(condbr, trueDest, mergedOperands); return success(); } }; struct SimplifyCondBranchToUnreachable : public OpRewritePattern<CondBranchOp> { using OpRewritePattern<CondBranchOp>::OpRewritePattern; LogicalResult matchAndRewrite(CondBranchOp condbr, PatternRewriter &rewriter) const override { Block *trueDest = condbr.trueDest(); Block *falseDest = condbr.falseDest(); // Determine if either branch goes to a block with a single operation bool trueIsCandidate = std::next(trueDest->begin()) == trueDest->end(); bool falseIsCandidate = std::next(falseDest->begin()) == falseDest->end(); // If neither are candidates for this transformation, we're done if (!trueIsCandidate && !falseIsCandidate) return failure(); // Determine if either branch contains an unreachable // Check that the terminator is an unconditional branch. Operation *trueOp = trueDest->getTerminator(); assert(trueOp && "expected terminator"); Operation *falseOp = falseDest->getTerminator(); assert(falseOp && "expected terminator"); UnreachableOp trueUnreachable = dyn_cast<UnreachableOp>(trueOp); UnreachableOp falseUnreachable = dyn_cast<UnreachableOp>(falseOp); // If neither terminator are unreachables, there is nothing to do if (!trueUnreachable && !falseUnreachable) return failure(); // If both blocks are unreachable, then we can replace this // branch operation with an unreachable as well if (trueUnreachable && falseUnreachable) { rewriter.replaceOpWithNewOp<UnreachableOp>(condbr); return success(); } Block *unreachable; Block *reachable; Operation *reachableOp; OperandRange reachableOperands = trueUnreachable ? condbr.getFalseOperands() : condbr.getTrueOperands(); Block *opParent = condbr.getOperation()->getBlock(); if (trueUnreachable) { unreachable = trueDest; reachable = falseDest; reachableOp = falseOp; } else { unreachable = falseDest; reachable = trueDest; reachableOp = trueOp; } // If the reachable block is a return, we can collapse this operation // to a return rather than a branch if (auto ret = dyn_cast<ReturnOp>(reachableOp)) { if (reachable->getUniquePredecessor() == opParent) { // If the reachable block is only reachable from here, merge the blocks rewriter.eraseOp(condbr); rewriter.mergeBlocks(reachable, opParent, reachableOperands); return success(); } else { // If the reachable block has multiple predecessors, but the // return only references operands reachable from this block, // then replace the condbr with a copy of the return SmallVector<Value, 4> destOperandStorage; auto retOperands = ret.operands(); for (Value operand : retOperands) { BlockArgument argOperand = operand.dyn_cast<BlockArgument>(); if (argOperand && argOperand.getOwner() == reachable) { // The operand is a block argument in the reachable block, // remap it to the successor operand we have in this block destOperandStorage.push_back( reachableOperands[argOperand.getArgNumber()]); } else if (operand.getParentBlock() == reachable) { // The operand is constructed in the reachable block, // so we can't proceed without cloning the block into // this block return failure(); } else { // The operand is from parent scope, we can safely reference it destOperandStorage.push_back(operand); } } rewriter.replaceOpWithNewOp<ReturnOp>(condbr, destOperandStorage); return success(); } } // The reachable block doesn't contain a return, so instead replace // the condbr with an unconditional branch rewriter.replaceOpWithNewOp<BranchOp>(condbr, reachable, reachableOperands); return success(); } }; } // end anonymous namespace. void CondBranchOp::getCanonicalizationPatterns( OwningRewritePatternList &results, MLIRContext *context) { results.insert<SimplifyConstCondBranchPred, SimplifyPassThroughCondBranch, SimplifyCondBranchIdenticalSuccessors, SimplifyCondBranchToUnreachable>(context); } Optional<MutableOperandRange> CondBranchOp::getMutableSuccessorOperands( unsigned index) { assert(index < getNumSuccessors() && "invalid successor index"); return index == trueIndex ? trueDestOperandsMutable() : falseDestOperandsMutable(); } Block *CondBranchOp::getSuccessorForOperands(ArrayRef<Attribute> operands) { if (IntegerAttr condAttr = operands.front().dyn_cast_or_null<IntegerAttr>()) return condAttr.getValue().isOneValue() ? trueDest() : falseDest(); return nullptr; } //===----------------------------------------------------------------------===// // eir.return //===----------------------------------------------------------------------===// static LogicalResult verify(ReturnOp op) { auto function = cast<FuncOp>(op.getParentOp()); // The operand number and types must match the function signature. const auto &results = function.getType().getResults(); if (op.getNumOperands() != results.size()) return op.emitOpError("has ") << op.getNumOperands() << " operands, but enclosing function returns " << results.size(); for (unsigned i = 0, e = results.size(); i != e; ++i) if (op.getOperand(i).getType() != results[i]) return op.emitError() << "type of return operand " << i << " (" << op.getOperand(i).getType() << ") doesn't match function result type (" << results[i] << ")"; return success(); } //===----------------------------------------------------------------------===// // eir.is_type //===----------------------------------------------------------------------===// static LogicalResult verify(IsTypeOp op) { auto typeAttr = op.getAttrOfType<TypeAttr>("type"); if (!typeAttr) return op.emitOpError("requires type attribute named 'type'"); return success(); } //===----------------------------------------------------------------------===// // eir.cast //===----------------------------------------------------------------------===// static bool areCastCompatible(OpaqueTermType srcType, OpaqueTermType destType) { // Casting an immediate to an opaque term is always allowed if (destType.isOpaque()) return srcType.isImmediate(); // Casting an opaque term to any term type is always allowed if (srcType.isOpaque()) return true; // A cast must be to an immediate-sized type if (!destType.isImmediate()) return false; // Box-to-box casts are always allowed if (srcType.isBox() & destType.isBox()) return true; // Only header types can be boxed if (destType.isBox() && !srcType.isBoxable()) return false; // Only support casts between compatible types if (srcType.isNumber() && !destType.isNumber()) return false; if (srcType.isInteger() && !destType.isInteger()) return false; if (srcType.isFloat() && !destType.isFloat()) return false; if (srcType.isList() && !destType.isList()) return false; if (srcType.isBinary() && !destType.isBinary()) return false; // All other casts are supported return true; } static LogicalResult verify(CastOp op) { auto opType = op.getOperand().getType(); auto resType = op.getType(); if (auto opTermType = opType.dyn_cast_or_null<OpaqueTermType>()) { if (auto resTermType = resType.dyn_cast_or_null<OpaqueTermType>()) { if (!areCastCompatible(opTermType, resTermType)) { return op.emitError("operand type ") << opType << " and result type " << resType << " are not cast compatible"; } return success(); } return op.emitError( "invalid cast type for CastOp, expected term type, got ") << resType; } return op.emitError( "invalid operand type for CastOp, expected term type, got ") << opType; } //===----------------------------------------------------------------------===// // eir.match //===----------------------------------------------------------------------===// void lowerPatternMatch(OpBuilder &builder, Location loc, Value selector, ArrayRef<MatchBranch> branches) { auto numBranches = branches.size(); assert(numBranches > 0 && "expected at least one branch in a match"); auto *context = builder.getContext(); auto *currentBlock = builder.getInsertionBlock(); auto *region = currentBlock->getParent(); auto selectorType = selector.getType(); // Save our insertion point in the current block auto startIp = builder.saveInsertionPoint(); // Create blocks for all match arms bool needsFallbackBranch = true; SmallVector<Block *, 3> blocks; // The first match arm is evaluated in the current block, so we // handle it specially blocks.reserve(numBranches); blocks.push_back(currentBlock); if (branches[0].isCatchAll()) { needsFallbackBranch = false; } // All other match arms need blocks for the evaluation of their patterns for (auto &branch : branches.take_back(numBranches - 1)) { if (branch.isCatchAll()) { needsFallbackBranch = false; } Block *block = builder.createBlock(region); block->addArgument(selectorType); blocks.push_back(block); } // Create fallback block, if needed, after all other match blocks, so // that after all other conditions have been tried, we branch to an // unreachable to force a trap Block *failed = nullptr; if (needsFallbackBranch) { failed = builder.createBlock(region); failed->addArgument(selectorType); builder.create<eir::UnreachableOp>(loc); } // Restore our original insertion point builder.restoreInsertionPoint(startIp); // Save the current insertion point, which we'll restore when lowering is // complete auto finalIp = builder.saveInsertionPoint(); // Common types used below auto termType = builder.getType<TermType>(); auto i1Ty = builder.getI1Type(); // Used whenever we need a set of empty args below ArrayRef<Value> emptyArgs{}; // For each branch, populate its block with the predicate and // appropriate conditional branching instruction to either jump // to the success block, or to the next branches' block (or in // the case of the last branch, the 'failed' block) for (unsigned i = 0; i < numBranches; i++) { auto &b = branches[i]; Location branchLoc = b.getLoc(); bool isLast = i == numBranches - 1; Block *block = blocks[i]; // Set our insertion point to the end of the pattern block builder.setInsertionPointToEnd(block); // Get the selector value in this block, // in the case of the first block, its our original // input selector value Value selectorArg; if (i == 0) { selectorArg = selector; } else { selectorArg = block->getArgument(0); } ArrayRef<Value> withSelectorArgs{selectorArg}; // Store the next pattern to try if this one fails // If this is the last pattern, we validate that the // branch either unconditionally succeeds, or branches to // an unreachable op Block *nextPatternBlock = nullptr; if (!isLast) { nextPatternBlock = blocks[i + 1]; } else if (needsFallbackBranch) { nextPatternBlock = failed; } auto dest = b.getDest(); auto baseDestArgs = b.getDestArgs(); auto numBaseDestArgs = baseDestArgs.size(); // Ensure the destination block argument types are propagated for (unsigned i = 0; i < baseDestArgs.size(); i++) { BlockArgument arg = dest->getArgument(i); auto destArg = baseDestArgs[i]; auto destArgTy = destArg.getType(); if (arg.getType() != destArgTy) arg.setType(destArgTy); } switch (b.getPatternType()) { case MatchPatternType::Any: { // This unconditionally branches to its destination builder.create<BranchOp>(branchLoc, dest, baseDestArgs); break; } case MatchPatternType::Cons: { assert(nextPatternBlock != nullptr && "last match block must end in unconditional branch"); auto cip = builder.saveInsertionPoint(); // 1. Split block, and conditionally branch to split if is_cons, // otherwise the next pattern Block *split = builder.createBlock(region, Region::iterator(nextPatternBlock)); builder.restoreInsertionPoint(cip); auto consType = builder.getType<ConsType>(); auto boxedConsType = builder.getType<BoxType>(consType); auto isConsOp = builder.create<IsTypeOp>(branchLoc, selectorArg, boxedConsType); auto isConsCond = isConsOp.getResult(); auto ifOp = builder.create<CondBranchOp>(branchLoc, isConsCond, split, emptyArgs, nextPatternBlock, withSelectorArgs); // 2. In the split, extract head and tail values of the cons cell builder.setInsertionPointToEnd(split); auto castOp = builder.create<CastOp>(branchLoc, selectorArg, boxedConsType); auto boxedCons = castOp.getResult(); auto getHeadOp = builder.create<GetElementPtrOp>(branchLoc, boxedCons, 0); auto getTailOp = builder.create<GetElementPtrOp>(branchLoc, boxedCons, 1); auto headPointer = getHeadOp.getResult(); auto tailPointer = getTailOp.getResult(); auto headLoadOp = builder.create<LoadOp>(branchLoc, headPointer); auto headLoadResult = headLoadOp.getResult(); auto tailLoadOp = builder.create<LoadOp>(branchLoc, tailPointer); auto tailLoadResult = tailLoadOp.getResult(); // 3. Unconditionally branch to the destination, with head/tail as // additional destArgs unsigned i = numBaseDestArgs > 0 ? numBaseDestArgs - 1 : 0; dest->getArgument(i++).setType(headLoadResult.getType()); dest->getArgument(i).setType(tailLoadResult.getType()); SmallVector<Value, 2> destArgs( {baseDestArgs.begin(), baseDestArgs.end()}); destArgs.push_back(headLoadResult); destArgs.push_back(tailLoadResult); builder.create<BranchOp>(branchLoc, dest, destArgs); break; } case MatchPatternType::Tuple: { assert(nextPatternBlock != nullptr && "last match block must end in unconditional branch"); auto *pattern = b.getPatternTypeOrNull<TuplePattern>(); // 1. Split block, and conditionally branch to split if is_tuple w/arity // N, otherwise the next pattern auto cip = builder.saveInsertionPoint(); Block *split = builder.createBlock(region, Region::iterator(nextPatternBlock)); builder.restoreInsertionPoint(cip); auto arity = pattern->getArity(); auto tupleType = builder.getType<eir::TupleType>(arity); auto boxedTupleType = builder.getType<BoxType>(tupleType); auto isTupleOp = builder.create<IsTypeOp>(branchLoc, selectorArg, boxedTupleType); auto isTupleCond = isTupleOp.getResult(); auto ifOp = builder.create<CondBranchOp>(branchLoc, isTupleCond, split, emptyArgs, nextPatternBlock, withSelectorArgs); // 2. In the split, extract the tuple elements as values builder.setInsertionPointToEnd(split); auto castOp = builder.create<CastOp>(branchLoc, selectorArg, boxedTupleType); auto boxedTuple = castOp.getResult(); unsigned ai = numBaseDestArgs > 0 ? numBaseDestArgs - 1 : 0; SmallVector<Value, 2> destArgs( {baseDestArgs.begin(), baseDestArgs.end()}); destArgs.reserve(arity); for (int64_t i = 0; i < arity; i++) { auto getElemOp = builder.create<GetElementPtrOp>(branchLoc, boxedTuple, i + 1); auto elemPtr = getElemOp.getResult(); auto elemLoadOp = builder.create<LoadOp>(branchLoc, elemPtr); auto elemLoadResult = elemLoadOp.getResult(); dest->getArgument(ai++).setType(elemLoadResult.getType()); destArgs.push_back(elemLoadResult); } // 3. Unconditionally branch to the destination, with the tuple elements // as additional destArgs builder.create<BranchOp>(branchLoc, dest, destArgs); break; } case MatchPatternType::MapItem: { assert(nextPatternBlock != nullptr && "last match block must end in unconditional branch"); // 1. Split block twice, and conditionally branch to the first split if // is_map, otherwise the next pattern auto cip = builder.saveInsertionPoint(); Block *split2 = builder.createBlock(region, Region::iterator(nextPatternBlock)); Block *split = builder.createBlock(region, Region::iterator(split2)); builder.restoreInsertionPoint(cip); auto *pattern = b.getPatternTypeOrNull<MapPattern>(); auto key = pattern->getKey(); auto mapType = BoxType::get(builder.getType<MapType>()); auto isMapOp = builder.create<IsTypeOp>(branchLoc, selectorArg, mapType); auto isMapCond = isMapOp.getResult(); auto ifOp = builder.create<CondBranchOp>( branchLoc, isMapCond, split, emptyArgs, nextPatternBlock, withSelectorArgs); // 2. In the split, call runtime function `is_map_key` to confirm // existence of the key in the map, // then conditionally branch to the second split if successful, // otherwise the next pattern builder.setInsertionPointToEnd(split); auto hasKeyOp = builder.create<MapIsKeyOp>(branchLoc, selectorArg, key); auto hasKeyCond = hasKeyOp.getResult(); builder.create<CondBranchOp>(branchLoc, hasKeyCond, split2, emptyArgs, nextPatternBlock, withSelectorArgs); // 3. In the second split, call runtime function `map_get` to obtain the // value for the key builder.setInsertionPointToEnd(split2); auto mapGetOp = builder.create<MapGetKeyOp>(branchLoc, selectorArg, key); auto valueTerm = mapGetOp.getResult(); unsigned i = numBaseDestArgs > 0 ? numBaseDestArgs - 1 : 0; dest->getArgument(i).setType(valueTerm.getType()); // 4. Unconditionally branch to the destination, with the key's value as // an additional destArg SmallVector<Value, 2> destArgs(baseDestArgs.begin(), baseDestArgs.end()); destArgs.push_back(valueTerm); builder.create<BranchOp>(branchLoc, dest, destArgs); break; } case MatchPatternType::IsType: { assert(nextPatternBlock != nullptr && "last match block must end in unconditional branch"); // 1. Conditionally branch to destination if is_<type>, otherwise the // next pattern auto *pattern = b.getPatternTypeOrNull<IsTypePattern>(); auto expectedType = pattern->getExpectedType(); auto isTypeOp = builder.create<IsTypeOp>(branchLoc, selectorArg, expectedType); auto isTypeCond = isTypeOp.getResult(); builder.create<CondBranchOp>(branchLoc, isTypeCond, dest, baseDestArgs, nextPatternBlock, withSelectorArgs); break; } case MatchPatternType::Value: { assert(nextPatternBlock != nullptr && "last match block must end in unconditional branch"); // 1. Conditionally branch to dest if the value matches the selector, // passing the value as an additional destArg auto *pattern = b.getPatternTypeOrNull<ValuePattern>(); auto expected = pattern->getValue(); auto isEq = builder.create<CmpEqOp>(branchLoc, selectorArg, expected, /*strict=*/true); auto isEqCond = isEq.getResult(); builder.create<CondBranchOp>(branchLoc, isEqCond, dest, baseDestArgs, nextPatternBlock, withSelectorArgs); break; } case MatchPatternType::Binary: { // 1. Split block, and conditionally branch to split if is_bitstring (or // is_binary), otherwise the next pattern // 2. In the split, conditionally branch to destination if construction // of the head value succeeds, // otherwise the next pattern // NOTE: The exact semantics depend on the binary specification type, // and what is optimal in terms of checks. The success of the overall // branch results in two additional destArgs being passed to the // destination block, the decoded entry (head), and the rest of the // binary (tail) auto *pattern = b.getPatternTypeOrNull<BinaryPattern>(); auto spec = pattern->getSpec(); auto size = pattern->getSize(); Operation *op; switch (spec.tag) { case BinarySpecifierType::Integer: { auto payload = spec.payload.i; bool isSigned = payload.isSigned; auto endianness = payload.endianness; auto unit = payload.unit; op = builder.create<BinaryMatchIntegerOp>( branchLoc, selectorArg, isSigned, endianness, unit, size); break; } case BinarySpecifierType::Utf8: { op = builder.create<BinaryMatchUtf8Op>(branchLoc, selectorArg, size); break; } case BinarySpecifierType::Utf16: { auto endianness = spec.payload.es.endianness; op = builder.create<BinaryMatchUtf16Op>(branchLoc, selectorArg, endianness, size); break; } case BinarySpecifierType::Utf32: { auto endianness = spec.payload.es.endianness; op = builder.create<BinaryMatchUtf32Op>(branchLoc, selectorArg, endianness, size); break; } case BinarySpecifierType::Float: { auto payload = spec.payload.f; op = builder.create<BinaryMatchFloatOp>( branchLoc, selectorArg, payload.endianness, payload.unit, size); break; } case BinarySpecifierType::Bytes: case BinarySpecifierType::Bits: { auto payload = spec.payload.us; op = builder.create<BinaryMatchRawOp>(branchLoc, selectorArg, payload.unit, size); break; } default: llvm::outs() << "binary match type: " << ((unsigned)spec.tag) << "\n"; llvm::report_fatal_error("unknown binary match type"); } Value matched = op->getResult(0); Value rest = op->getResult(1); Value success = op->getResult(2); unsigned i = numBaseDestArgs > 0 ? numBaseDestArgs - 1 : 0; dest->getArgument(i++).setType(matched.getType()); dest->getArgument(i).setType(rest.getType()); SmallVector<Value, 2> destArgs(baseDestArgs.begin(), baseDestArgs.end()); destArgs.push_back(matched); destArgs.push_back(rest); builder.create<CondBranchOp>(branchLoc, success, dest, destArgs, nextPatternBlock, withSelectorArgs); break; } default: llvm_unreachable("unexpected match pattern type!"); } } builder.restoreInsertionPoint(finalIp); } //===----------------------------------------------------------------------===// // Constant*Op //===----------------------------------------------------------------------===// static ParseResult parseConstantOp(OpAsmParser &parser, OperationState &result) { Attribute valueAttr; if (parser.parseOptionalAttrDict(result.attributes) || parser.parseAttribute(valueAttr, "value", result.attributes)) return failure(); auto type = valueAttr.getType(); // Add the attribute type to the list. return parser.addTypeToList(type, result.types); } template <typename ConstantOp> static void printConstantOp(OpAsmPrinter &p, ConstantOp &op) { p << op.getOperationName() << ' '; p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"value"}); if (op.getAttrs().size() > 1) p << ' '; p << op.getValue(); } template <typename ConstantOp> static LogicalResult verifyConstantOp(ConstantOp &) { // TODO return success(); } OpFoldResult ConstantIntOp::fold(ArrayRef<Attribute> operands) { assert(operands.empty() && "constant has no operands"); return getValue(); } OpFoldResult ConstantBigIntOp::fold(ArrayRef<Attribute> operands) { assert(operands.empty() && "constant has no operands"); return getValue(); } OpFoldResult ConstantFloatOp::fold(ArrayRef<Attribute> operands) { assert(operands.empty() && "constant has no operands"); return getValue(); } OpFoldResult ConstantAtomOp::fold(ArrayRef<Attribute> operands) { assert(operands.empty() && "constant has no operands"); return getValue(); } OpFoldResult ConstantNilOp::fold(ArrayRef<Attribute> operands) { assert(operands.empty() && "constant has no operands"); return getValue(); } OpFoldResult ConstantNoneOp::fold(ArrayRef<Attribute> operands) { assert(operands.empty() && "constant has no operands"); return getValue(); } //===----------------------------------------------------------------------===// // eir.neg //===----------------------------------------------------------------------===// /// Matches a ConstantIntOp /// The matcher that matches a constant numeric operation and binds the constant /// value. struct constant_apint_op_binder { APIntAttr::ValueType *bind_value; /// Creates a matcher instance that binds the value to bv if match succeeds. constant_apint_op_binder(APIntAttr::ValueType *bv) : bind_value(bv) {} bool match(Operation *op) { Attribute attr; if (!mlir::detail::constant_op_binder<Attribute>(&attr).match(op)) return false; auto type = op->getResult(0).getType(); if (auto opaque = type.dyn_cast_or_null<OpaqueTermType>()) { if (opaque.isFixnum()) return mlir::detail::attr_value_binder<APIntAttr>(bind_value) .match(attr); if (opaque.isBox()) { auto box = type.cast<BoxType>(); if (box.getBoxedType().isInteger()) return mlir::detail::attr_value_binder<APIntAttr>(bind_value) .match(attr); } } return false; } }; /// The matcher that matches a constant numeric operation and binds the constant /// value. struct constant_apfloat_op_binder { APFloatAttr::ValueType *bind_value; /// Creates a matcher instance that binds the value to bv if match succeeds. constant_apfloat_op_binder(APFloatAttr::ValueType *bv) : bind_value(bv) {} bool match(Operation *op) { Attribute attr; if (!mlir::detail::constant_op_binder<Attribute>(&attr).match(op)) return false; auto type = op->getResult(0).getType(); if (auto opaque = type.dyn_cast_or_null<OpaqueTermType>()) { if (opaque.isFloat()) return mlir::detail::attr_value_binder<APFloatAttr>(bind_value) .match(attr); } return false; } }; inline constant_apint_op_binder m_ConstInt(APIntAttr::ValueType *bind_value) { return constant_apint_op_binder(bind_value); } inline constant_apfloat_op_binder m_ConstFloat( APFloatAttr::ValueType *bind_value) { return constant_apfloat_op_binder(bind_value); } namespace { /// Fold negations of constants into negated constants struct ApplyConstantNegations : public OpRewritePattern<NegOp> { using OpRewritePattern<NegOp>::OpRewritePattern; LogicalResult matchAndRewrite(NegOp op, PatternRewriter &rewriter) const override { auto rhs = op.rhs(); APInt intVal; auto intPattern = mlir::m_Op<CastOp>(m_ConstInt(&intVal)); if (matchPattern(rhs, intPattern)) { auto castOp = dyn_cast<CastOp>(rhs.getDefiningOp()); auto castType = castOp.getType(); intVal.negate(); if (castOp.getSourceType().isa<FixnumType>()) { auto newInt = rewriter.create<ConstantIntOp>(op.getLoc(), intVal); rewriter.replaceOpWithNewOp<CastOp>(op, newInt.getResult(), castType); } else { auto newInt = rewriter.create<ConstantBigIntOp>(op.getLoc(), intVal); rewriter.replaceOpWithNewOp<CastOp>(op, newInt.getResult(), castType); } return success(); } APFloat fltVal(0.0); auto floatPattern = mlir::m_Op<CastOp>(m_ConstFloat(&fltVal)); if (matchPattern(rhs, floatPattern)) { auto castType = dyn_cast<CastOp>(rhs.getDefiningOp()).getType(); APFloat newFltVal = -fltVal; auto newFlt = rewriter.create<ConstantFloatOp>(op.getLoc(), newFltVal); rewriter.replaceOpWithNewOp<CastOp>(op, newFlt.getResult(), castType); return success(); } return failure(); } }; } // end anonymous namespace void NegOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { results.insert<ApplyConstantNegations>(context); } //===----------------------------------------------------------------------===// // MallocOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, MallocOp op) { p << MallocOp::getOperationName(); OpaqueTermType boxedType = op.getAllocType(); p.printOperands(op.getOperands()); p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"type"}); p << " : " << BoxType::get(boxedType); } static ParseResult parseMallocOp(OpAsmParser &parser, OperationState &result) { BoxType type; llvm::SMLoc loc = parser.getCurrentLocation(); SmallVector<OpAsmParser::OperandType, 1> opInfo; SmallVector<Type, 1> types; if (parser.parseOperandList(opInfo)) return failure(); if (!opInfo.empty() && parser.parseColonTypeList(types)) return failure(); // Parse the optional dimension operand, followed by a box type. if (parser.resolveOperands(opInfo, types, loc, result.operands) || parser.parseOptionalAttrDict(result.attributes) || parser.parseColonType(type)) return failure(); result.types.push_back(type); return success(); } static LogicalResult verify(MallocOp op) { auto type = op.getResult().getType().dyn_cast<BoxType>(); if (!type) return op.emitOpError("result must be a box type"); OpaqueTermType boxedType = type.getBoxedType(); if (!boxedType.isBoxable()) return op.emitOpError("boxed type must be a boxable type"); auto operands = op.getOperands(); if (operands.empty()) { // There should be no dynamic dimensions in the boxed type if (boxedType.isTuple()) { auto tuple = boxedType.cast<TupleType>(); if (tuple.hasDynamicShape()) return op.emitOpError( "boxed type has dynamic extent, but no dimension operands were " "given"); } } else { // There should be exactly as many dynamic dimensions as there are operands, // and those operands should be of integer type if (!boxedType.isTuple()) return op.emitOpError( "only tuples are allowed to have dynamic dimensions"); auto tuple = boxedType.cast<TupleType>(); if (tuple.hasStaticShape()) return op.emitOpError( "boxed type has static extent, but dimension operands were given"); if (tuple.getArity() != operands.size()) return op.emitOpError( "number of dimension operands does not match the number of dynamic " "dimensions"); } return success(); } namespace { /// Fold malloc operations with no uses. Malloc has side effects on the heap, /// but can still be deleted if it has zero uses. struct SimplifyDeadMalloc : public OpRewritePattern<MallocOp> { using OpRewritePattern<MallocOp>::OpRewritePattern; LogicalResult matchAndRewrite(MallocOp alloc, PatternRewriter &rewriter) const override { if (alloc.use_empty()) { rewriter.eraseOp(alloc); return success(); } return failure(); } }; } // end anonymous namespace. void MallocOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { results.insert<SimplifyDeadMalloc>(context); } int64_t calculateAllocSize(unsigned pointerSizeInBits, BoxType boxType) { auto boxedType = boxType.getBoxedType(); if (boxedType.isTuple()) { auto tuple = boxedType.cast<TupleType>(); return tuple.getSizeInBytes(); } else if (boxedType.isNonEmptyList()) { return 2 * (pointerSizeInBits / 8); } assert(false && "unimplemented boxed type in calculateAllocSize"); } //===----------------------------------------------------------------------===// // eir.invoke //===----------------------------------------------------------------------===// Optional<MutableOperandRange> InvokeOp::getMutableSuccessorOperands( unsigned index) { assert(index < getNumSuccessors() && "invalid successor index"); return index == okIndex ? llvm::None : Optional(errDestOperandsMutable()); } //===----------------------------------------------------------------------===// // eir.invoke_closure //===----------------------------------------------------------------------===// Optional<MutableOperandRange> InvokeClosureOp::getMutableSuccessorOperands( unsigned index) { assert(index < getNumSuccessors() && "invalid successor index"); return index == okIndex ? okDestOperandsMutable() : errDestOperandsMutable(); } //===----------------------------------------------------------------------===// // eir.yield.check //===----------------------------------------------------------------------===// Optional<MutableOperandRange> YieldCheckOp::getMutableSuccessorOperands( unsigned index) { assert(index < getNumSuccessors() && "invalid successor index"); return index == trueIndex ? trueDestOperandsMutable() : falseDestOperandsMutable(); } Block *YieldCheckOp::getSuccessorForOperands(ArrayRef<Attribute> operands) { if (IntegerAttr condAttr = operands.front().dyn_cast_or_null<IntegerAttr>()) return condAttr.getValue().isOneValue() ? trueDest() : falseDest(); return nullptr; } //===----------------------------------------------------------------------===// // TableGen Output //===----------------------------------------------------------------------===// #define GET_OP_CLASSES #include "lumen/EIR/IR/EIROps.cpp.inc" } // namespace eir } // namespace lumen
39.16881
80
0.627878
Tuxified
3b09f701844df2680a34a670cdd5bc400ebc5d6f
2,312
cpp
C++
lib/src/Delphi/Syntax/Expressions/DelphiAssignmentExpressionSyntax.cpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
lib/src/Delphi/Syntax/Expressions/DelphiAssignmentExpressionSyntax.cpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
50
2021-06-30T20:01:50.000Z
2021-11-28T16:21:26.000Z
lib/src/Delphi/Syntax/Expressions/DelphiAssignmentExpressionSyntax.cpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
#include "Delphi/Syntax/Expressions/DelphiAssignmentExpressionSyntax.hpp" #include <cassert> #include "interlinck/Core/Syntax/ISyntaxToken.hpp" #include "interlinck/Core/Syntax/SyntaxKinds.hpp" #include "Core/Support/SyntaxFactory.hpp" namespace interlinck::Delphi::Syntax { using Core::Support::SyntaxFactory; using namespace Core::Syntax; DelphiAssignmentExpressionSyntax::DelphiAssignmentExpressionSyntax(const DelphiExpressionSyntax* leftExpression, const ISyntaxToken* colonEqualToken, const DelphiExpressionSyntax* rightExpression) noexcept : DelphiExpressionSyntax{SyntaxKind::AssignmentExpression}, _leftExpression{leftExpression}, _colonEqualToken{colonEqualToken}, _rightExpression{rightExpression} { setPosition(_leftExpression->position()); adjustWidthAndFlags(_leftExpression); adjustWidthAndFlags(_colonEqualToken); adjustWidthAndFlags(_rightExpression); } SyntaxVariant DelphiAssignmentExpressionSyntax::child(il_size index) const noexcept { assert(index < childCount()); switch (index) { case 0: return SyntaxVariant::asNode(_leftExpression); case 1: return SyntaxVariant::asToken(_colonEqualToken); case 2: return SyntaxVariant::asNode(_rightExpression); default: return SyntaxVariant::empty(); } } const DelphiAssignmentExpressionSyntax* DelphiAssignmentExpressionSyntax::create(SyntaxFactory& syntaxFactory, const DelphiExpressionSyntax* leftExpression, const ISyntaxToken* colonEqualToken, const DelphiExpressionSyntax* rightExpression) noexcept { assert(leftExpression != nullptr); assert(colonEqualToken != nullptr); assert(colonEqualToken->syntaxKind() == SyntaxKind::ColonEqualToken); assert(rightExpression != nullptr); return syntaxFactory.syntaxNode<DelphiAssignmentExpressionSyntax>(leftExpression, colonEqualToken, rightExpression); } } // end namespace interlinck::Delphi::Syntax
42.814815
136
0.660035
henrikfroehling
3b0a007766c0ce9bd10a33233ea1f12ada2d030d
1,526
cpp
C++
Nowcoder/890A/dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
Nowcoder/890A/dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
Nowcoder/890A/dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <bits/stdc++.h> using namespace std; #define SIZE 510 int arr[SIZE]; double dp[2][SIZE][SIZE], dp1[SIZE][SIZE]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int len, lowLim, uppLim; cin >> len >> lowLim >> uppLim; for (int i = 1; i <= len; i++) cin >> arr[i]; memset(dp, 0, sizeof(dp)); dp[0][0][0] = 1; for (int i = 1; i <= len; i++) { dp[i & 1][0][0] = 1; for (int j = 1; j <= i; j++) { for (int k = 1; k <= uppLim; k++) dp[i & 1][j][k] = dp[(i & 1) ^ 1][j][k]; for (int k = arr[i]; k <= uppLim; k++) dp[i & 1][j][k] += dp[(i & 1) ^ 1][j - 1][k - arr[i]] * j / (len - j + 1); } } double ans = 0; for (int i = 1; i <= len; i++) { for (int k = 0; k <= uppLim; k++) dp1[0][k] = dp[len & 1][0][k]; for (int j = 1; j <= len; j++) { for (int k = 0; k < arr[i]; k++) dp1[j][k] = dp[len & 1][j][k]; for (int k = arr[i]; k <= uppLim; k++) dp1[j][k] = dp[len & 1][j][k] - dp1[j - 1][k - arr[i]] * j / (len - j + 1); } int leftLim = max(0, lowLim - arr[i] + 1), rightLim = min(uppLim - arr[i], lowLim); for (int k = leftLim; k <= rightLim; k++) for (int j = 1; j < len; j++) ans += dp1[j - 1][k] / (len - j + 1); } cout << fixed << setprecision(12) << ans << '\n'; return 0; }
31.791667
92
0.385321
codgician
3b11268763ec5d19dd4911723548dc1ea738580b
441
cpp
C++
luahost/main.cpp
motoyang/spdlogger4Lua
97e2dde72ca04e80aa1fbe8eba42daeb059dd518
[ "MIT" ]
null
null
null
luahost/main.cpp
motoyang/spdlogger4Lua
97e2dde72ca04e80aa1fbe8eba42daeb059dd518
[ "MIT" ]
null
null
null
luahost/main.cpp
motoyang/spdlogger4Lua
97e2dde72ca04e80aa1fbe8eba42daeb059dd518
[ "MIT" ]
null
null
null
#include "luahost_global.h" void lua_test1() { auto ls = Luapp::create(); ls->openLibs(); // 执行auto1.lua中定义的函数f ls->doFile("auto1.lua"); ls->dispatchToLua2("f", 1, 2.2, "3.3"); // 取回lua中函数f的执行结果 std::string resutl; ls->popN(resutl); std::cout << "this is c function: " << resutl << std::endl; } int main(int argc, char *argv[]) { UNUSED(argc); UNUSED(argv); lua_test1(); return 0; }
16.333333
63
0.569161
motoyang
3b16643df4e3eb0d916c11c50d2663a6ce64b818
566
cpp
C++
ch10/GuiTest/testableform.cpp
cjchng/Computer-Vision-with-OpenCV-3-and-Qt5
816dc4d827fcef91012bcf6804f086fafa0b74dc
[ "MIT" ]
273
2017-10-20T15:43:15.000Z
2022-03-29T14:56:45.000Z
ch10/GuiTest/testableform.cpp
cjchng/Computer-Vision-with-OpenCV-3-and-Qt5
816dc4d827fcef91012bcf6804f086fafa0b74dc
[ "MIT" ]
14
2018-01-27T00:19:18.000Z
2020-08-18T08:30:32.000Z
ch10/GuiTest/testableform.cpp
cjchng/Computer-Vision-with-OpenCV-3-and-Qt5
816dc4d827fcef91012bcf6804f086fafa0b74dc
[ "MIT" ]
169
2017-11-24T11:47:29.000Z
2022-03-21T12:54:47.000Z
#include "testableform.h" #include "ui_testableform.h" TestableForm::TestableForm(QWidget *parent) : QWidget(parent), ui(new Ui::TestableForm) { ui->setupUi(this); this->nextBtn = ui->nextBtn; this->infoLabel = ui->infoLabel; } TestableForm::~TestableForm() { delete ui; } void TestableForm::on_nextBtn_pressed() { if(ui->infoLabel->text().trimmed().isEmpty()) { ui->infoLabel->setText("1"); } else { int n = ui->infoLabel->text().toInt(); ui->infoLabel->setText(QString::number(n*2)); } }
18.258065
53
0.611307
cjchng
3b21b9ea32d42ab68a8dad610d2bb7693fd0a746
1,317
cpp
C++
include/src/auton.cpp
Mao-Zedong1893/2019-2020-tower-takeover
6733b6e4780cb2230e9b5ca78747f167eb9f5d70
[ "MIT" ]
null
null
null
include/src/auton.cpp
Mao-Zedong1893/2019-2020-tower-takeover
6733b6e4780cb2230e9b5ca78747f167eb9f5d70
[ "MIT" ]
null
null
null
include/src/auton.cpp
Mao-Zedong1893/2019-2020-tower-takeover
6733b6e4780cb2230e9b5ca78747f167eb9f5d70
[ "MIT" ]
null
null
null
#include "main.h" #include "globals.hpp" #include "tray.h" #include "auton.hpp" void moveStaight(float objective) { int tickDistance = (objective/12.6)*900; while (rightFront.get_position () > objective) { pros::delay(10); leftBack.move_velocity(100); leftFront.move_velocity(100); rightBack.move_velocity(100); rightFront.move_velocity(100); } } void rotateCW(float objAngle) { gyro.reset(); // move motors to turn while (gyro.get_value() < objAngle) { pros::delay(10); rightBack.move_velocity(-100); rightFront.move_velocity(-100); leftBack.move_velocity(100); leftFront.move_velocity(100); } } void rotateCCW(float objAngle) { gyro.reset(); // move motors to turn while (gyro.get_value() > objAngle) { pros::delay(10); rightBack.move_velocity(100); rightFront.move_velocity(100); leftBack.move_velocity(-100); leftFront.move_velocity(-100); } } void tilterRaise() { int anglePower = 50; tilter(anglePower); if (angleAdjuster.get_position() >= 3917) { angleAdjuster.move_velocity(0); } } void tilterLower() { int anglePower = -50; tilter(anglePower); if (angleAdjuster.get_position() <= 0) { angleAdjuster.move_velocity(0); } /* void routineBlue1() { moveStaight(12); rotateCCW(180); rotateCW(180); } */
19.367647
50
0.678815
Mao-Zedong1893
3b21fef232552c1f7d6603364ef84e7c25f1359e
2,691
hpp
C++
ublox_dgnss_node/include/ublox_dgnss_node/ubx/nav/ubx_nav_posllh.hpp
wouter-heerwegh/ublox_dgnss
31acafc8a71dfba639c4b6cd96c6ae617d2fad17
[ "Apache-2.0" ]
2
2021-07-21T20:03:21.000Z
2022-01-10T02:51:24.000Z
ublox_dgnss_node/include/ublox_dgnss_node/ubx/nav/ubx_nav_posllh.hpp
rossvonfange/ublox_dgnss
bb2b4829b8180fae05d6f8f9a0c6f04f072e356d
[ "Apache-2.0" ]
2
2021-07-21T16:38:26.000Z
2021-10-12T06:39:37.000Z
ublox_dgnss_node/include/ublox_dgnss_node/ubx/nav/ubx_nav_posllh.hpp
rossvonfange/ublox_dgnss
bb2b4829b8180fae05d6f8f9a0c6f04f072e356d
[ "Apache-2.0" ]
2
2021-09-10T14:11:01.000Z
2022-01-10T19:33:34.000Z
// Copyright 2021 Australian Robotics Supplies & Technology // // 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 UBLOX_DGNSS_NODE__UBX__NAV__UBX_NAV_POSLLH_HPP_ #define UBLOX_DGNSS_NODE__UBX__NAV__UBX_NAV_POSLLH_HPP_ #include <unistd.h> #include <memory> #include <tuple> #include <string> #include "ublox_dgnss_node/ubx/ubx.hpp" #include "ublox_dgnss_node/ubx/utils.hpp" namespace ubx::nav::posllh { class NavPosLLHPayload : UBXPayload { public: static const msg_class_t MSG_CLASS = UBX_NAV; static const msg_id_t MSG_ID = UBX_NAV_POSLLH; u4_t iTOW; // ms - GPS Time of week of the navigation epoch. i4_t lon; // deg scale 1e-7 - longitude i4_t lat; // deg scale ie-7 = latitude i4_t height; // mm - Height above ellipsoid i4_t hMSL; // mm - Height above mean sea level u4_t hAcc; // mm - Horizontal accuracy estimate u4_t vAcc; // mm - Vertical accuracy estimate public: NavPosLLHPayload() : UBXPayload(MSG_CLASS, MSG_ID) {} NavPosLLHPayload(ch_t * payload_polled, u2_t size) : UBXPayload(MSG_CLASS, MSG_ID) { payload_.clear(); payload_.reserve(size); payload_.resize(size); memcpy(payload_.data(), payload_polled, size); iTOW = buf_offset<u4_t>(&payload_, 0); lon = buf_offset<i4_t>(&payload_, 4); lat = buf_offset<i4_t>(&payload_, 8); height = buf_offset<i4_t>(&payload_, 12); hMSL = buf_offset<i4_t>(&payload_, 16); hAcc = buf_offset<u4_t>(&payload_, 20); vAcc = buf_offset<u4_t>(&payload_, 24); } std::tuple<u1_t *, size_t> make_poll_payload() { payload_.clear(); return std::make_tuple(payload_.data(), payload_.size()); } std::string to_string() { std::ostringstream oss; oss << "iTOW: " << iTOW; oss << std::fixed; oss << std::setprecision(7); oss << " lon: " << lon << " " << lon * 1e-7; oss << " lat: " << lat << " " << lat * 1e-7; oss << std::setprecision(0); oss << " height: " << height; oss << " hMSL: " << hMSL; oss << " hAcc: " << hAcc; oss << " vAcc: " << vAcc; return oss.str(); } }; } // namespace ubx::nav::posllh #endif // UBLOX_DGNSS_NODE__UBX__NAV__UBX_NAV_POSLLH_HPP_
32.421687
75
0.668525
wouter-heerwegh
3b26ae330c4ccb3c928aac89c120041017df918b
961
hpp
C++
include/Nemu/WebFramework/Views.hpp
nemu-cpp/web-server
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
[ "MIT" ]
null
null
null
include/Nemu/WebFramework/Views.hpp
nemu-cpp/web-server
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
[ "MIT" ]
null
null
null
include/Nemu/WebFramework/Views.hpp
nemu-cpp/web-server
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
[ "MIT" ]
null
null
null
/* Copyright (c) 2019-2022 Xavier Leclercq Released under the MIT License See https://github.com/nemu-cpp/web-framework/blob/main/LICENSE.txt */ #ifndef _NEMU_CPP_WEBFRAMEWORK_VIEWS_HPP_ #define _NEMU_CPP_WEBFRAMEWORK_VIEWS_HPP_ #include "TemplateEngine.hpp" #include "TemplateEngineProfile.hpp" #include <map> #include <memory> namespace Nemu { /// A list of templating engines and their associated settings. class Views { public: Views(); Views(std::shared_ptr<TemplateEngineProfile> defaultProfile); void setDefaultProfile(std::shared_ptr<TemplateEngineProfile> profile); void set(const std::string& name, std::shared_ptr<TemplateEngineProfile> profile); TemplateEngineProfile& defaultProfile(); TemplateEngineProfile& profile(const std::string& name); private: std::shared_ptr<TemplateEngineProfile> m_defaultProfile; std::map<std::string, std::shared_ptr<TemplateEngineProfile>> m_profiles; }; } #endif
24.641026
86
0.764828
nemu-cpp
3b2747c81729794c87adf3375c1dd4ded79070d9
6,202
cpp
C++
basecode/compiler/elements/argument_list.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
32
2018-05-14T23:26:54.000Z
2020-06-14T10:13:20.000Z
basecode/compiler/elements/argument_list.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
79
2018-08-01T11:50:45.000Z
2020-11-17T13:40:06.000Z
basecode/compiler/elements/argument_list.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
14
2021-01-08T05:05:19.000Z
2022-03-27T14:56:56.000Z
// ---------------------------------------------------------------------------- // // Basecode Bootstrap Compiler // Copyright (C) 2018 Jeff Panici // All rights reserved. // // This software source file is licensed under the terms of MIT license. // For details, please read the LICENSE file. // // ---------------------------------------------------------------------------- #include <common/bytes.h> #include <compiler/session.h> #include "type.h" #include "identifier.h" #include "initializer.h" #include "declaration.h" #include "argument_pair.h" #include "argument_list.h" #include "composite_type.h" #include "symbol_element.h" #include "procedure_type.h" #include "type_reference.h" #include "binary_operator.h" #include "identifier_reference.h" namespace basecode::compiler { argument_list::argument_list( compiler::module* module, compiler::block* parent_scope) : element(module, parent_scope, element_type_t::argument_list) { } void argument_list::clear() { _elements.clear(); _argument_index.clear(); } size_t argument_list::size() const { auto size = _elements.size(); auto variadic_args = variadic_arguments(); if (variadic_args != nullptr) size += (variadic_args->size() - 1); return size; } bool argument_list::as_ffi_arguments( compiler::session& session, vm::function_value_list_t& args) const { return recurse_ffi_arguments(session, _elements, args); } bool argument_list::on_apply_fold_result( compiler::element* e, const fold_result_t& fold_result) { auto index = find_index(e->id()); if (index == -1) { return false; } replace(static_cast<size_t>(index), fold_result.element); return true; } compiler::element* argument_list::replace( size_t index, compiler::element* item) { auto old = _elements[index]; _elements[index] = item; return old; } bool argument_list::recurse_ffi_arguments( compiler::session& session, const element_list_t& elements, vm::function_value_list_t& args) const { for (compiler::element* arg : elements) { if (arg->element_type() == element_type_t::argument_list) { auto arg_list = dynamic_cast<compiler::argument_list*>(arg); auto success = recurse_ffi_arguments(session, arg_list->elements(), args); if (!success) return false; continue; } infer_type_result_t type_result {}; if (!arg->infer_type(session, type_result)) return false; vm::function_value_t value {}; value.type = type_result.inferred_type->to_ffi_type(); if (value.type == vm::ffi_types_t::struct_type) { auto composite_type = dynamic_cast<compiler::composite_type*>(type_result.inferred_type); if (composite_type == nullptr) return false; for (auto fld : composite_type->fields().as_list()) { vm::function_value_t fld_value; fld_value.name = fld->identifier()->symbol()->name(); fld_value.type = fld->identifier()->type_ref()->type()->to_ffi_type(); value.fields.push_back(fld_value); } } args.push_back(value); } return true; } void argument_list::remove(common::id_t id) { auto item = find(id); if (item == nullptr) return; std::remove( _elements.begin(), _elements.end(), item); } bool argument_list::is_foreign_call() const { return _is_foreign_call; } uint64_t argument_list::allocated_size() const { return _allocated_size; } void argument_list::is_foreign_call(bool value) { _is_foreign_call = value; } void argument_list::allocated_size(size_t size) { _allocated_size = size; } void argument_list::add(compiler::element* item) { _elements.emplace_back(item); } int32_t argument_list::find_index(common::id_t id) { for (size_t i = 0; i < _elements.size(); i++) { if (_elements[i]->id() == id) return static_cast<int32_t>(i); } return -1; } const element_list_t& argument_list::elements() const { return _elements; } compiler::element* argument_list::find(common::id_t id) { auto it = std::find_if( _elements.begin(), _elements.end(), [&id](auto item) { return item->id() == id; }); if (it == _elements.end()) return nullptr; return *it; } void argument_list::elements(const element_list_t& value) { _elements = value; } void argument_list::on_owned_elements(element_list_t& list) { for (auto element : _elements) list.emplace_back(element); } compiler::element* argument_list::param_at_index(size_t index) { if (index < _elements.size()) return _elements[index]; return nullptr; } compiler::argument_list* argument_list::variadic_arguments() const { if (_elements.empty()) return nullptr; auto last_arg = _elements.back(); if (last_arg != nullptr && last_arg->element_type() == element_type_t::argument_list) { return dynamic_cast<compiler::argument_list*>(last_arg); } return nullptr; } void argument_list::argument_index(const argument_index_map_t& value) { _argument_index = value; } compiler::element* argument_list::param_by_name(const std::string& name) { auto it = _argument_index.find(name); if (it == _argument_index.end()) return nullptr; return _elements[it->second]; } };
31.323232
105
0.564495
Alaboudi1
3b370e9bb67836d1d3e4c8a5e2246318199be1ef
2,346
cpp
C++
SampleGame/Shrektris/Server.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
null
null
null
SampleGame/Shrektris/Server.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
null
null
null
SampleGame/Shrektris/Server.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
1
2019-06-16T19:00:31.000Z
2019-06-16T19:00:31.000Z
#include "Server.hpp" #include "Lobby.hpp" #include "Gameplay.hpp" void Server::processPacket(UDPpacket* packet) { bool val = false; using namespace cage::networking::packets; using namespace cage::networking; unsigned char* bytes = packet->data; std::cout << "got packets\n\n"; switch ((PacketType)bytes[0]) { case PacketType::QUERY: { QueryResponse response; std::string temp = name; SDL_memcpy(response.name, temp.c_str(), 16); m_serverSocket.Send((char*)&response, sizeof(response), packet->address); } break; case PacketType::CONNECTION_REQUEST: { addClient(Endpoint(packet->address)); ConnectionAccept accept; accept.playerID = m_nextClient; m_connections[m_nextClient] = std::make_unique<ServerConnection>(&m_serverSocket, Endpoint(packet->address)); m_connections[m_nextClient]->Send(&accept, sizeof(accept)); RosterSync sync; SDL_memcpy(sync.lobbyName, name.c_str(), 16); sync.players[0] = true; for (int i = 0; i < m_connections.size(); i++) sync.players[i + 1] = m_connections[i] != nullptr; SendAll(&sync, sizeof(sync)); m_lobby->acceptConnection(m_nextClient); m_nextClient++; } break; case PacketType::BOARD_SYNC: { BoardSync sync; SDL_memcpy(&sync, packet->data, sizeof(sync)); m_gameplay->boardSync(sync); break; } case PacketType::PLAYER_PIECE_POS: { PlayerPiecePos pos; SDL_memcpy(&pos, packet->data, sizeof(pos)); SendAll(&pos, sizeof(pos)); m_gameplay->playerSync(pos); break; } } } Server::Server(unsigned int port, Lobby* lobby) : m_serverSocket(port), m_nextClient(1), m_lobby(lobby), m_gameplay(nullptr) { std::cout << "Starting Shrektris game server on port " << port << std::endl; } Server::~Server() { std::cout << "Closing Shrektris game server" << std::endl; } void Server::SendAll(void* data, size_t size) { for (auto& connection : m_connections) if (connection) { connection->Send(data, size); } } void Server::addClient(cage::networking::Endpoint) { } void Server::Listen() { UDPpacket* packet = SDLNet_AllocPacket(2048); if(m_serverSocket.Receive(packet)) processPacket(packet); SDLNet_FreePacket(packet); } void Server::UpdateTimeouts(float dt) { for (auto& connection : m_connections) if (connection && !connection->AdvanceTimeout(dt)) { std::cout << "Connection timed out" << std::endl; } }
22.342857
124
0.702046
Mr-1337
3b385a4fdb3c2d032b8bbbca10e99d8246155de2
1,348
cpp
C++
Source/RPG/RPGGameInstance.cpp
oxmoss/TutoRPGUE
f19a279bc11052de85d388ebe53656ecd43a5027
[ "MIT" ]
null
null
null
Source/RPG/RPGGameInstance.cpp
oxmoss/TutoRPGUE
f19a279bc11052de85d388ebe53656ecd43a5027
[ "MIT" ]
null
null
null
Source/RPG/RPGGameInstance.cpp
oxmoss/TutoRPGUE
f19a279bc11052de85d388ebe53656ecd43a5027
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "RPGGameInstance.h" void URPGGameInstance::Init() { if(this->isInitialized) return; this->isInitialized = true; this->PartyMembers.Empty(); // locate characters asset UDataTable* characters = Cast<UDataTable>(StaticLoadObject( UDataTable::StaticClass(), NULL, TEXT("DataTable'/Game/Ressources/DataTables/RPG_CharacterInfo.RPG_CharacterInfo'")) ); if(characters == NULL) { UE_LOG(LogTemp, Error, TEXT("Characters data table not found!" ) ); return; } /* // locate character FCharacterInfo* row = characters->FindRow<FCharacterInfo>(TEXT("C1"), TEXT("LookupCharacterClass")); if(row == NULL) { UE_LOG(LogTemp, Error, TEXT("Character ID 'C1' not found!") ); return; } // add character to party this->PartyMembers.Add(UGameCharacter::CreateGameCharacter(row, this)); //*/ TArray<FName> RowNames = characters->GetRowNames(); for(auto& name : RowNames) { FCharacterInfo* row = characters->FindRow<FCharacterInfo>(name, TEXT("LookupCharacterClass")); if(row == NULL) { UE_LOG(LogTemp, Error, TEXT("Character ID not found!")); return; } // add character to party this->PartyMembers.Add(UGameCharacter::CreateGameCharacter(row, this)); } } void URPGGameInstance::PrepareReset() { this->isInitialized = false; }
25.433962
180
0.717359
oxmoss
3b3875a0350a152029346ce1581512ebd3eafffa
7,736
cpp
C++
src/prod/src/Store/StoreFactory.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
1
2020-06-15T04:33:36.000Z
2020-06-15T04:33:36.000Z
src/prod/src/Store/StoreFactory.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
src/prod/src/Store/StoreFactory.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; namespace Store { StringLiteral const TraceComponent("StoreFactory"); ErrorCode StoreFactory::CreateLocalStore( StoreFactoryParameters const & parameters, ILocalStoreSPtr & store) { HealthReport unused; return CreateLocalStore(parameters, store, unused); } ErrorCode StoreFactory::CreateLocalStore( StoreFactoryParameters const & parameters, ILocalStoreSPtr & store, __out HealthReport & healthReport) { switch (parameters.Type) { case StoreType::Local: { auto error = CreateEseLocalStore(parameters, store); if (error.IsSuccess()) { error = HandleEseMigration(parameters); } if (error.IsSuccess()) { healthReport = CreateHealthyReport(parameters, ProviderKind::ESE); } else { healthReport = CreateUnhealthyReport(parameters, ProviderKind::ESE, error.Message); } return error; } case StoreType::TStore: { CreateTSLocalStore(parameters, store); auto error = HandleTStoreMigration(parameters); if (error.IsSuccess()) { healthReport = CreateHealthyReport(parameters, ProviderKind::TStore); } else { healthReport = CreateUnhealthyReport(parameters, ProviderKind::TStore, error.Message); } return ErrorCodeValue::Success; } default: Assert::CodingError("Unknown type {0}", static_cast<int>(parameters.Type)); } } ErrorCode StoreFactory::CreateEseLocalStore(StoreFactoryParameters const & parameters, __out ILocalStoreSPtr & store) { #ifdef PLATFORM_UNIX UNREFERENCED_PARAMETER(parameters); UNREFERENCED_PARAMETER(store); return ErrorCode(ErrorCodeValue::NotImplemented, L"ESE not supported in Linux for RA"); #else auto error = Directory::Create2(parameters.DirectoryPath); if (!error.IsSuccess()) { return error; } EseLocalStoreSettings settings; settings.StoreName = parameters.FileName; settings.AssertOnFatalError = parameters.AssertOnFatalError; store = make_shared<EseLocalStore>( parameters.DirectoryPath, settings, EseLocalStore::LOCAL_STORE_FLAG_NONE); return ErrorCodeValue::Success; #endif } void StoreFactory::CreateTSLocalStore(StoreFactoryParameters const & parameters, __out ILocalStoreSPtr & store) { store = make_shared<TSLocalStore>( make_unique<TSReplicatedStoreSettings>(parameters.DirectoryPath), parameters.KtlLogger); } ErrorCode StoreFactory::HandleEseMigration(StoreFactoryParameters const & parameters) { if (parameters.KtlLogger.get() == nullptr) { // // Expected in RA unit tests // Trace.WriteInfo(TraceComponent, "KtlLogger is null - skipping TStore database files check"); return ErrorCodeValue::Success; } ILocalStoreSPtr store; CreateTSLocalStore(parameters, store); auto tstoreCasted = dynamic_cast<TSLocalStore*>(store.get()); auto sharedLogFilePath = parameters.KtlLogger->SystemServicesSharedLogSettings->Settings.Path; if (File::Exists(sharedLogFilePath)) { if (parameters.AllowMigration) { Trace.WriteInfo(TraceComponent, "Deleting TStore database files for migration since '{0}' exists", sharedLogFilePath); return tstoreCasted->DeleteDatabaseFiles(sharedLogFilePath); } else { auto msg = wformatString(StringResource::Get ( IDS_RA_STORE_ESE_MIGRATION_BLOCKED ), sharedLogFilePath); Trace.WriteWarning(TraceComponent, "{0}", msg); return ErrorCode(ErrorCodeValue::OperationFailed, move(msg)); } } return ErrorCodeValue::Success; } ErrorCode StoreFactory::HandleTStoreMigration(StoreFactoryParameters const & parameters) { #ifdef PLATFORM_UNIX UNREFERENCED_PARAMETER(parameters); return ErrorCodeValue::Success; #else ILocalStoreSPtr store; auto error = CreateEseLocalStore(parameters, store); if (!error.IsSuccess()) { return error; } auto eseCasted = dynamic_cast<EseLocalStore*>(store.get()); auto eseDirectory = eseCasted->Directory; auto eseFileName = eseCasted->FileName; auto edbFilePath = Path::Combine(eseDirectory, eseFileName); if (File::Exists(edbFilePath)) { if (parameters.AllowMigration) { Trace.WriteInfo(TraceComponent, "Deleting '{0}' for migration since '{1}' exists", eseDirectory, edbFilePath); error = eseCasted->Cleanup(); } else { auto msg = wformatString(StringResource::Get ( IDS_RA_STORE_TSTORE_MIGRATION_BLOCKED ), edbFilePath); Trace.WriteWarning(TraceComponent, "{0}", msg); error = ErrorCode(ErrorCodeValue::OperationFailed, move(msg)); } } return error; #endif } HealthReport StoreFactory::CreateHealthyReport( StoreFactoryParameters const & parameters, ProviderKind::Enum providerKind) { EntityHealthInformationSPtr entity; AttributeList attributes; CreateHealthReportAttributes(parameters, entity, attributes); return HealthReport::CreateSystemHealthReport( SystemHealthReportCode::RA_StoreProviderHealthy, move(entity), wformatString(StringResource::Get( IDS_RA_STORE_PROVIDER_HEALTHY ), providerKind), move(attributes)); } HealthReport StoreFactory::CreateUnhealthyReport( StoreFactoryParameters const & parameters, ProviderKind::Enum providerKind, wstring const & details) { EntityHealthInformationSPtr entity; AttributeList attributes; CreateHealthReportAttributes(parameters, entity, attributes); return HealthReport::CreateSystemHealthReport( SystemHealthReportCode::RA_StoreProviderUnhealthy, move(entity), wformatString(StringResource::Get( IDS_RA_STORE_PROVIDER_UNHEALTHY ), providerKind, details), move(attributes)); } void StoreFactory::CreateHealthReportAttributes( StoreFactoryParameters const & parameters, __out EntityHealthInformationSPtr & entity, __out AttributeList & attributes) { auto const & nodeInstance = parameters.NodeInstance; auto const & nodeName = parameters.NodeName; entity = EntityHealthInformation::CreateNodeEntityHealthInformation( nodeInstance.Id.IdValue, nodeName, nodeInstance.InstanceId); attributes.AddAttribute(*HealthAttributeNames::NodeId, wformatString(nodeInstance.Id)); attributes.AddAttribute(*HealthAttributeNames::NodeInstanceId, wformatString(nodeInstance.InstanceId)); } }
33.059829
134
0.62668
vishnuk007
3b42d6a331948f8c24427f2268dd26920f63756f
1,931
cc
C++
count/empirical_data_test.cc
hmusta/libcount
5208c9fccb97e7eae089740a70f9f3ad82ae3ac1
[ "Apache-2.0" ]
20
2017-01-17T11:57:46.000Z
2022-02-19T01:24:03.000Z
count/empirical_data_test.cc
hmusta/libcount
5208c9fccb97e7eae089740a70f9f3ad82ae3ac1
[ "Apache-2.0" ]
3
2016-01-30T18:49:48.000Z
2017-03-07T18:17:33.000Z
count/empirical_data_test.cc
hmusta/libcount
5208c9fccb97e7eae089740a70f9f3ad82ae3ac1
[ "Apache-2.0" ]
4
2016-01-30T18:43:10.000Z
2020-02-22T09:03:25.000Z
// Copyright 2015 The libcount Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. See the AUTHORS file for names of // contributors. #include "count/empirical_data.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "count/hll_data.h" #include "count/hll_limits.h" using libcount::HLL_MIN_PRECISION; using libcount::HLL_MAX_PRECISION; using libcount::ValidTableEntries; // Ensure that the empirical data set is sorted properly. int main(int argc, char* argv[]) { // Sweep through all precision levels. for (int p = HLL_MIN_PRECISION; p <= HLL_MAX_PRECISION; ++p) { // The arrays are zero indexed; calculate the array index for the // associated precision level. const int precision_index = p - HLL_MIN_PRECISION; // How many valid entries will there be? const int kMax = 201; const int size = ValidTableEntries(ESTIMATE_DATA[precision_index], kMax); double last = 0.0; for (int i = 0; i < size; ++i) { const double curr = ESTIMATE_DATA[precision_index][i]; // Iff we assert here, the empirical estimate data is not sorted. This // is a serious problem because the linear interpolation algorithm // assumes that the estimate values increase monotonically with their // array index. assert(curr >= last); if (curr < last) { return EXIT_FAILURE; } last = curr; } } return EXIT_SUCCESS; }
34.482143
77
0.706888
hmusta
3b4389f9f98c323f7fbca4e9591af692afb0f075
217
cpp
C++
android-31/android/provider/Telephony.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/provider/Telephony.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/provider/Telephony.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./Telephony.hpp" namespace android::provider { // Fields // QJniObject forward Telephony::Telephony(QJniObject obj) : JObject(obj) {} // Constructors // Methods } // namespace android::provider
14.466667
55
0.691244
YJBeetle
8dc7d438cc625a211906a4000fb850da04d38323
2,251
cpp
C++
Source/Visualizers/VisualizerWaveform.cpp
MatthewCech/ASCIIPlayer
8c0948fcf10320f156fdecb34a526cf71f9484f9
[ "BSD-3-Clause" ]
5
2018-02-03T19:49:30.000Z
2020-09-07T12:29:19.000Z
Source/Visualizers/VisualizerWaveform.cpp
MatthewCech/ASCIIPlayer
8c0948fcf10320f156fdecb34a526cf71f9484f9
[ "BSD-3-Clause" ]
9
2018-02-27T06:37:12.000Z
2020-03-25T05:43:56.000Z
Source/Visualizers/VisualizerWaveform.cpp
MatthewCech/ASCIIPlayer
8c0948fcf10320f156fdecb34a526cf71f9484f9
[ "BSD-3-Clause" ]
2
2018-02-09T06:47:21.000Z
2019-05-12T07:04:01.000Z
#include "VisualizerWaveform.hpp" #include <Core\AudioSystem.hpp> namespace ASCIIPlayer { // Constructor VisualizerWaveform::VisualizerWaveform() : ASCIIVisualizer(CONSOLE_WIDTH_FUNC, AUDIODATA_WAVEFORM) , startingWidth_(CONSOLE_WIDTH_FUNC) , width_(startingWidth_) , height_(CONSOLE_HEIGHT_FUNC) { RConsole::Canvas::SetCursorVisible(false); } // Called when the window is resized void VisualizerWaveform::OnResize(int newWidth, int newHeight) { RConsole::Canvas::ReInit(newWidth, newHeight); RConsole::Canvas::ForceClearEverything(); width_ = newWidth; height_ = newHeight; RConsole::Canvas::SetCursorVisible(false); } // Draw Bars bool VisualizerWaveform::Update(float* data, float volume, bool isActive) { // Before anything else, catch or correct any problematic values. if (volume < 0.01f) volume = 1; // Set up some sweet numbers const char symbol = static_cast<unsigned char>(219); // Solid box character on windows. This doesn't really work well on different OSs. const int halfHeight = height_ / 2; // Half-way point on the console visually const float heightScalar = 5.4f; // Arbitrary value determining the max vertical offset. Used to be 6, but was scaled for volume of .9 by default. const float heightMinimum = 2; // Arbitrary value determining smallest vertical offset. Chosen for visual appeal - creates 2 bottom and 1 top line. const float volumeScale = 1.0f / volume; // For volume values smaller than 1, it's good to normalize the data. int offset = (width_ - startingWidth_) / 2; if (offset < 0) offset = 0; // For every X position, calculate the Y position based on waveform data and variables above. for (int i = 0; i < width_ && i < startingWidth_; ++i) { for (int j = 0; j < data[i] * heightScalar * volumeScale + heightMinimum; ++j) // Y position { const int xPos = i; RConsole::Canvas::Draw(symbol, i + offset, halfHeight + j, RConsole::BLUE); RConsole::Canvas::Draw(symbol, i + offset, halfHeight - j, RConsole::LIGHTBLUE); } } return true; } } #undef WAVEFORM_SIZE
37.516667
173
0.666371
MatthewCech
8dcb96f88cc32640d0f188192200e2345d7d29ab
1,363
cpp
C++
15/15.42/main.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
null
null
null
15/15.42/main.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
2
2020-08-15T17:33:00.000Z
2021-07-05T14:18:26.000Z
15/15.42/main.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
1
2020-08-15T17:24:54.000Z
2020-08-15T17:24:54.000Z
#include <iostream> #include <cstdlib> #include <fstream> #include "TextQuery.h" #include <vector> #include "Query.h" #include <string> #include "Query_parser.h" #include <utility> #include <stdexcept> int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "USAGE: " << argv[0] << " [FILE]\n"; return EXIT_FAILURE; } std::ifstream infile(argv[1]); if (!infile) { std::cerr << "Failed to open \"" << argv[1] << "\".\n"; return EXIT_FAILURE; } TextQuery tq(infile); std::vector<Query> history; std::string current_string; std::cout << R"(A '\' at the beginning followed by an integer causes history expansion. Anything else causes the '\' at the beginning to be ignored. Type your query: )"; while (std::getline(std::cin, current_string) && !current_string.empty()) { try { auto current_query = strToQuery(current_string, history); print(std::cout, current_query.eval(tq)); history.push_back(std::move(current_query)); } catch (const std::invalid_argument &err) { std::cout << err.what() << '\n'; } catch (const std::out_of_range &err) { std::cout << "Invalid history expansion attempt!\n"; } std::cout << "Type your query (Empty line to quit): "; } return EXIT_SUCCESS; }
31.697674
91
0.596478
kousikpramanik
8dd4142d71c7aff9701617d4aea6421d6c0dab3d
463
cpp
C++
lib/src/btj_global_pointers.cpp
GValiente/botijo
ed00a2843e65a489febb838e452790db8e4ec2c8
[ "MIT" ]
1
2020-11-17T09:07:26.000Z
2020-11-17T09:07:26.000Z
lib/src/btj_global_pointers.cpp
GValiente/botijo
ed00a2843e65a489febb838e452790db8e4ec2c8
[ "MIT" ]
null
null
null
lib/src/btj_global_pointers.cpp
GValiente/botijo
ed00a2843e65a489febb838e452790db8e4ec2c8
[ "MIT" ]
1
2018-11-15T08:23:11.000Z
2018-11-15T08:23:11.000Z
/* * botijo (c) 2018 Gustavo Valiente gustavo.valiente.m@gmail.com * * MIT License, see LICENSE file. */ #include "btj_global_pointers.h" #include "btj_graphics_impl.h" namespace btj { GlobalPointers gb; void GlobalPointers::setup(Core* _core, GraphicsImpl* _graphics, KeyboardImpl* _keyboard) noexcept { core = _core; graphics = _graphics; layers = &_graphics->_layers; textures = &*_graphics->_textures; keyboard = _keyboard; } }
17.807692
98
0.706263
GValiente
8ddb1eefbaa49f99581ee9a277aa72d843cf64ea
2,888
cpp
C++
receivefile.cpp
shuzibanshou/woniu
c668ec81813207473f366248f21e7a39e246c32c
[ "MIT" ]
null
null
null
receivefile.cpp
shuzibanshou/woniu
c668ec81813207473f366248f21e7a39e246c32c
[ "MIT" ]
null
null
null
receivefile.cpp
shuzibanshou/woniu
c668ec81813207473f366248f21e7a39e246c32c
[ "MIT" ]
null
null
null
#include "receivefile.h" #include "ui_receivefile.h" receiveFile::receiveFile(QWidget *parent) : QDialog(parent),ui(new Ui::Dialog) { //ui一定要记得初始化 ui->setupUi(this); //禁用窗口右上角关闭按钮 //this->setWindowFlag(Qt::WindowCloseButtonHint, false); connect(this, SIGNAL(acceptFile()), parent, SLOT(acceptFile())); connect(this, SIGNAL(rejectFile()), parent, SLOT(rejectFile())); connect(this, SIGNAL(modifySaveFilePath(QString)), parent, SLOT(modifySaveFilePath(QString))); //ui->acceptFile->installEventFilter(this); //ui->rejectFile->installEventFilter(this); //installEventFilter(this); } void receiveFile::setIPv4(QString ipv4) { ui->senderIPv4->setText(ipv4); } void receiveFile::setFileName(QString fileName) { ui->receiveFileName->setText(fileName); } void receiveFile::setFileSize(QString fileSize) { ui->receiveFileSize->setText(formateFileSize(fileSize)); } /** * 格式化输出文件大小 * @brief receiveFile::formateFileSize * @param fileSize * @return */ QString receiveFile::formateFileSize(QString fileSize) { float num = fileSize.toFloat(); QStringList list; list << "KB" << "MB" << "GB" << "TB"; QStringListIterator i(list); QString unit("bytes"); while(num >= 1024.0 && i.hasNext()) { unit = i.next(); num /= 1024.0; } return QString().setNum(num,'f',2)+" "+unit; } /** * 设置UI控件显示的文件默认保存目录 * @brief receiveFile::setSaveFilePath * @return */ void receiveFile::setSaveFilePath(QString m_saveFilePath) { saveFilePath = m_saveFilePath; ui->saveFilePath->setText(saveFilePath); } /** * 选择接收文件存储目录 * @brief receiveFile::on_modifySaveFilePath_clicked */ void receiveFile::on_modifySaveFilePath_clicked() { //文件夹路径 saveFilePath = QFileDialog::getExistingDirectory(this, "更改接收文件存储路径","/"); if(!saveFilePath.isEmpty()){ ui->saveFilePath->setText(saveFilePath); emit modifySaveFilePath(saveFilePath); } } /** * 接收新文件 * @brief receiveFile::on_acceptFile_clicked */ void receiveFile::on_acceptFile_clicked() { //先检测目录是否存在 不存在则尝试创建目录 QDir dir(saveFilePath); if(!dir.exists() && !dir.mkpath(saveFilePath)){ QMessageBox::warning(this, tr("提示"),tr("该目录不存在,且无法创建\n请检查权限并手动创建"),QMessageBox::Ok,QMessageBox::Ok); return; } //向父窗口发送接收文件消息 accept = 1; emit acceptFile(); //关闭弹窗 this->close(); } /** * 拒收新文件 * @brief receiveFile::on_pushButton_3_clicked */ void receiveFile::on_rejectFile_clicked() { //关闭弹窗 this->close(); } /** * 监控窗口关闭 * @brief receiveFile::closeEvent * @param event */ void receiveFile::closeEvent(QCloseEvent *event) { Q_UNUSED(event) if(accept != 1){ //向父窗口发送拒收文件消息 emit rejectFile(); } } //bool receiveFile::eventFilter(QObject *obj, QEvent *event) //{ // qDebug() << obj << event; // return QDialog::eventFilter(obj,event); //}
22.215385
108
0.66759
shuzibanshou
8ddd1b8998321dc6e68d8528ae3b071036d83f0a
249
cpp
C++
MonteCarlo_option_obj/EuroCall.cpp
harshvardhan-ranvir-singh/CPP-Design-For-Quantitative-Finance
7d42fef013768d1520cf6f3fc4a642ea2ab2deae
[ "MIT" ]
null
null
null
MonteCarlo_option_obj/EuroCall.cpp
harshvardhan-ranvir-singh/CPP-Design-For-Quantitative-Finance
7d42fef013768d1520cf6f3fc4a642ea2ab2deae
[ "MIT" ]
null
null
null
MonteCarlo_option_obj/EuroCall.cpp
harshvardhan-ranvir-singh/CPP-Design-For-Quantitative-Finance
7d42fef013768d1520cf6f3fc4a642ea2ab2deae
[ "MIT" ]
1
2021-09-22T12:18:45.000Z
2021-09-22T12:18:45.000Z
// // Created by Harshvardhan Singh on 23/10/2021. // #include "EuroCall.h" #include <algorithm> // for std::max EuroCall::EuroCall(double X, double T) : X_(X), T_(T) {} double EuroCall::ComputePO(double S) { return std::max(0.0, S - X_); }
16.6
56
0.64257
harshvardhan-ranvir-singh
8dde5800aa8ff2b8719c920b08f09548dc663083
6,605
hpp
C++
Result.hpp
mercere99/Wordle
cbfc104f049f0737422d3f90e3decfb96df8e8e0
[ "MIT" ]
null
null
null
Result.hpp
mercere99/Wordle
cbfc104f049f0737422d3f90e3decfb96df8e8e0
[ "MIT" ]
null
null
null
Result.hpp
mercere99/Wordle
cbfc104f049f0737422d3f90e3decfb96df8e8e0
[ "MIT" ]
null
null
null
#ifndef WORDLE_RESULT_HPP #define WORDLE_RESULT_HPP #include "emp/base/array.hpp" #include "emp/base/error.hpp" #include "emp/bits/BitVector.hpp" #include "emp/math/math.hpp" class Result { public: static constexpr size_t MAX_WORD_SIZE = 15; enum PositionResult { NOWHERE, ELSEWHERE, HERE, NONE }; // Return the number of IDs for a given length result. static constexpr size_t CalcNumIDs(size_t result_size) { return emp::Pow<size_t>(3, result_size); } private: using results_t = emp::vector<PositionResult>; results_t results; size_t id; /// Return a result array where each index is an associated (unique) possible result set. static const results_t & LookupResult(const size_t result_size, const size_t result_id) { emp_assert( result_size < MAX_WORD_SIZE ); emp_assert( result_id < CalcNumIDs(result_size) ); static emp::array< emp::vector<results_t>, MAX_WORD_SIZE > result_matrix; emp::vector<results_t> & result_vector = result_matrix[result_size]; // If this is our first time requsting the result array, generate it. if (result_vector.size() == 0) { const size_t num_IDs = CalcNumIDs(result_size); result_vector.resize(num_IDs); for (size_t id = 0; id < num_IDs; ++id) { result_vector[id].resize(result_size); size_t tmp_id = id; for (size_t pos = result_size-1; pos < result_size; --pos) { const size_t magnitude = static_cast<size_t>(emp::Pow(3, static_cast<int>(pos))); const size_t cur_result = tmp_id / magnitude; result_vector[id][pos] = static_cast<PositionResult>(cur_result); tmp_id -= cur_result * magnitude; } } } return result_vector[result_id]; } /// Assume that we have results, calculate the associated ID. void CalcID() { emp_assert(results.size() > 0 && results.size() < MAX_WORD_SIZE, results.size()); size_t base = 1; id = 0; for (PositionResult r : results) { id += static_cast<size_t>(r) * base; base *= 3; } emp_assert(id < CalcNumIDs(results.size()), id); } /// Assume that we have an ID, lookup the correct results. void CalcResults() { results = LookupResult(results.size(), id); } void CalcResults(size_t result_size) { results = LookupResult(result_size, id); } /// Convert a results string of 'N's, 'E's, and 'W's into a Results object. void FromString(const std::string & result_str) { results.resize(result_str.size()); for (size_t i=0; i < result_str.size(); ++i) { switch (result_str[i]) { case 'N': case 'n': results[i] = NOWHERE; break; case 'E': case 'e': results[i] = ELSEWHERE; break; case 'H': case 'h': results[i] = HERE; break; default: // @CAO Use exception? results[i] = NONE; }; } CalcID(); } public: /// Default constructor (to make arrays of results easier to deal with) Result() : id(0) {} /// Create a result by id. Result(size_t result_size, size_t _id) : id(_id) { emp_assert( id < CalcNumIDs(result_size), id ); CalcResults(result_size); } /// Create a result by a result array. Result(const results_t & _results) : results(_results) { CalcID(); } /// Create a result by a result string. Result(const std::string & result_str) { FromString(result_str); } /// Create a result by an guess and answer pair. Result(const std::string & guess, const std::string & answer) { emp_assert(guess.size() == answer.size()); results.resize(guess.size()); emp::BitVector used(answer.size()); // Test perfect matches. for (size_t i = 0; i < guess.size(); ++i) { if (guess[i] == answer[i]) { results[i] = HERE; used.Set(i); } } // Test offset matches. for (size_t i = 0; i < guess.size(); ++i) { if (guess[i] == answer[i]) continue; // already matched. bool found = false; for (size_t j = 0; j < answer.size(); ++j) { // seek a match elsewhere in answer! if (!used.Has(j) && guess[i] == answer[j]) { results[i] = ELSEWHERE; // found letter elsewhere! used.Set(j); // make sure this letter is noted as used. found = true; break; // move on to next letter; we found this one. } } if (!found) results[i] = NOWHERE; } CalcID(); // Now that we know the symbols, figure out the ID. } Result(const Result & result) = default; Result(Result && result) = default; Result & operator=(const std::string & result_str) { FromString(result_str); return *this; } Result & operator=(const Result & result) = default; Result & operator=(Result && result) = default; size_t GetID() const { return id; } size_t GetSize() const { return results.size(); } size_t size() const { return results.size(); } bool operator==(const Result & in) const { return size() == in.size() && id == in.id; } bool operator!=(const Result & in) const { return size() != in.size() || id != in.id;; } bool operator< (const Result & in) const { return size()==in.size() ? id < in.id : size() < in.size(); } bool operator<=(const Result & in) const { return size()==in.size() ? id <= in.id : size() < in.size(); } bool operator> (const Result & in) const { return size()==in.size() ? id > in.id : size() > in.size(); } bool operator>=(const Result & in) const { return size()==in.size() ? id >= in.id : size() > in.size(); } PositionResult operator[](size_t id) const { return results[id]; } // Test if this result is valid for the given word. bool IsValid(const std::string & word) const { // Result must be the correct size. if (word.size() != results.size()) return false; // Disallow letters marked "NOWHERE" that are subsequently marked "ELSEWHERE" // (other order is okay). for (size_t pos = 0; pos < results.size()-1; ++pos) { if (results[pos] == NOWHERE) { for (size_t pos2 = pos+1; pos2 < results.size(); ++pos2) { if (results[pos2] == ELSEWHERE && word[pos] == word[pos2]) return false; } } } return true; } std::string ToString( const std::string & here="H", const std::string & elsewhere="E", const std::string & nowhere="N" ) const { std::string out; // = emp::to_string(id, "-"); for (auto x : results) { if (x == HERE) out += here; else if (x == ELSEWHERE) out += elsewhere; else if (x == NOWHERE) out += nowhere; } return out; } }; #endif
37.528409
107
0.609084
mercere99
8dde639de721ad96d24406ac96ce80366761bd29
683
cpp
C++
AdvancedMap/kern_start.cpp
notjosh/AdvancedMap
dcbf81aa2e0fa1746555bbe4c256468faf4f5bce
[ "MIT" ]
5
2021-09-18T13:46:28.000Z
2021-11-02T17:39:39.000Z
AdvancedMap/kern_start.cpp
notjosh/AdvancedMap
dcbf81aa2e0fa1746555bbe4c256468faf4f5bce
[ "MIT" ]
1
2021-09-18T13:37:34.000Z
2021-09-18T13:37:34.000Z
AdvancedMap/kern_start.cpp
notjosh/AdvancedMap
dcbf81aa2e0fa1746555bbe4c256468faf4f5bce
[ "MIT" ]
null
null
null
#include <Headers/plugin_start.hpp> #include <Headers/kern_api.hpp> #include "AdvancedMap.hpp" static AdvancedMapPlugin advancedMap; static const char *bootargOff[] { "-advmapoff" }; static const char *bootargDebug[] { "-advmapdbg" }; static const char *bootargBeta[] { "-advmapbeta" }; PluginConfiguration ADDPR(config) { xStringify(PRODUCT_NAME), parseModuleVersion(xStringify(MODULE_VERSION)), LiluAPI::AllowNormal, bootargOff, arrsize(bootargOff), bootargDebug, arrsize(bootargDebug), bootargBeta, arrsize(bootargBeta), KernelVersion::Ventura, KernelVersion::Ventura, []() { advancedMap.init(); } };
18.459459
51
0.686676
notjosh
8de1da8392aa067370b5def08c1e257f51b56be8
13,165
cpp
C++
11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/transforms.cpp
EatAllBugs/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
14
2021-09-01T14:25:45.000Z
2022-02-21T08:49:57.000Z
11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/transforms.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
null
null
null
11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/transforms.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
3
2021-10-10T00:58:29.000Z
2022-01-23T13:16:09.000Z
/* * Copyright (c) 2008 Radu Bogdan Rusu <rusu -=- cs.tum.edu> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: transforms.cpp 23275 2009-08-28 20:27:09Z mariusmuja $ * */ /** \author Radu Bogdan Rusu */ #include <point_cloud_mapping/geometry/angles.h> #include <point_cloud_mapping/geometry/transforms.h> #include <point_cloud_mapping/geometry/nearest.h> #include <Eigen/SVD> namespace cloud_geometry { namespace transforms { /** * See header file */ bool getPointsRigidTransformation(const sensor_msgs::PointCloud& pc_a_, const sensor_msgs::PointCloud& pc_b_, Eigen::Matrix4d &transformation) { assert (pc_a_.get_points_size()==pc_b_.get_points_size()); sensor_msgs::PointCloud pc_a = pc_a_; sensor_msgs::PointCloud pc_b = pc_b_; // translate both point cloud so that their centroid will be in origin geometry_msgs::Point32 centroid_a; geometry_msgs::Point32 centroid_b; nearest::computeCentroid(pc_a, centroid_a); nearest::computeCentroid(pc_b, centroid_b); for (size_t i=0;i<pc_a.get_points_size();++i) { pc_a.points[i].x -= centroid_a.x; pc_a.points[i].y -= centroid_a.y; pc_a.points[i].z -= centroid_a.z; } for (size_t i=0;i<pc_b.get_points_size();++i) { pc_b.points[i].x -= centroid_b.x; pc_b.points[i].y -= centroid_b.y; pc_b.points[i].z -= centroid_b.z; } // solve for rotation Eigen::Matrix3d correlation; correlation.setZero(); for (size_t i=0;i<pc_a.get_points_size();++i) { correlation(0,0) += pc_a.points[i].x * pc_b.points[i].x; correlation(0,1) += pc_a.points[i].x * pc_b.points[i].y; correlation(0,2) += pc_a.points[i].x * pc_b.points[i].z; correlation(1,0) += pc_a.points[i].y * pc_b.points[i].x; correlation(1,1) += pc_a.points[i].y * pc_b.points[i].y; correlation(1,2) += pc_a.points[i].y * pc_b.points[i].z; correlation(2,0) += pc_a.points[i].z * pc_b.points[i].x; correlation(2,1) += pc_a.points[i].z * pc_b.points[i].y; correlation(2,2) += pc_a.points[i].z * pc_b.points[i].z; } Eigen::JacobiSVD<Eigen::Matrix3d> svd(correlation); Eigen::Matrix3d Ut = svd.matrixU().transpose(); Eigen::Matrix3d V = svd.matrixV(); Eigen::Matrix3d X = V*Ut; double det = X.determinant(); if (det<0) { V.col(2) = -V.col(2); X = V*Ut; } transformation.setZero(); transformation.topLeftCorner<3,3>() = X; transformation(3,3) = 1; sensor_msgs::PointCloud pc_rotated_a; transformPoints(pc_a_.points, pc_rotated_a.points, transformation); geometry_msgs::Point32 centroid_rotated_a; nearest::computeCentroid(pc_rotated_a, centroid_rotated_a); transformation(0,3) = centroid_b.x - centroid_rotated_a.x; transformation(1,3) = centroid_b.y - centroid_rotated_a.y; transformation(2,3) = centroid_b.z - centroid_rotated_a.z; return true; } /** * See header file */ bool getPointsRigidTransformation(const sensor_msgs::PointCloud& pc_a_, const std::vector<int>& indices_a, const sensor_msgs::PointCloud& pc_b_, const std::vector<int>& indices_b, Eigen::Matrix4d &transformation) { assert (indices_a.size()==indices_b.size()); sensor_msgs::PointCloud pc_a; sensor_msgs::PointCloud pc_b; getPointCloud(pc_a_, indices_a, pc_a); getPointCloud(pc_b_, indices_b, pc_b); // translate both point cloud so that their centroid will be in origin geometry_msgs::Point32 centroid_a; geometry_msgs::Point32 centroid_b; nearest::computeCentroid(pc_a, centroid_a); nearest::computeCentroid(pc_b, centroid_b); for (size_t i=0;i<pc_a.get_points_size();++i) { pc_a.points[i].x -= centroid_a.x; pc_a.points[i].y -= centroid_a.y; pc_a.points[i].z -= centroid_a.z; } for (size_t i=0;i<pc_b.get_points_size();++i) { pc_b.points[i].x -= centroid_b.x; pc_b.points[i].y -= centroid_b.y; pc_b.points[i].z -= centroid_b.z; } // solve for rotation Eigen::Matrix3d correlation; correlation.setZero(); for (size_t i=0;i<pc_a.get_points_size();++i) { correlation(0,0) += pc_a.points[i].x * pc_b.points[i].x; correlation(0,1) += pc_a.points[i].x * pc_b.points[i].y; correlation(0,2) += pc_a.points[i].x * pc_b.points[i].z; correlation(1,0) += pc_a.points[i].y * pc_b.points[i].x; correlation(1,1) += pc_a.points[i].y * pc_b.points[i].y; correlation(1,2) += pc_a.points[i].y * pc_b.points[i].z; correlation(2,0) += pc_a.points[i].z * pc_b.points[i].x; correlation(2,1) += pc_a.points[i].z * pc_b.points[i].y; correlation(2,2) += pc_a.points[i].z * pc_b.points[i].z; } Eigen::JacobiSVD<Eigen::Matrix3d> svd(correlation); Eigen::Matrix3d Ut = svd.matrixU().transpose(); Eigen::Matrix3d V = svd.matrixV(); Eigen::Matrix3d X = V*Ut; double det = X.determinant(); if (det<0) { V.col(2) = -V.col(2); X = V*Ut; } transformation.setZero(); transformation.topLeftCorner<3,3>() = X; transformation(3,3) = 1; sensor_msgs::PointCloud pc_rotated_a; getPointCloud(pc_a_, indices_a, pc_a); transformPoints(pc_a.points, pc_rotated_a.points, transformation); geometry_msgs::Point32 centroid_rotated_a; nearest::computeCentroid(pc_rotated_a, centroid_rotated_a); transformation(0,3) = centroid_b.x - centroid_rotated_a.x; transformation(1,3) = centroid_b.y - centroid_rotated_a.y; transformation(2,3) = centroid_b.z - centroid_rotated_a.z; // transformation.setIdentity(); // transformation(0,3) = centroid_b.x - centroid_a.x; // transformation(1,3) = centroid_b.y - centroid_a.y; // transformation(2,3) = centroid_b.z - centroid_a.z; return true; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** \brief Obtain a 4x4 rigid transformation matrix (with translation) * \param plane_a the normalized coefficients of the first plane * \param plane_b the normalized coefficients of the second plane * \param tx the desired translation on x-axis * \param ty the desired translation on y-axis * \param tz the desired translation on z-axis * \param transformation the resultant transformation matrix */ void getPlaneToPlaneTransformation (const std::vector<double> &plane_a, const std::vector<double> &plane_b, float tx, float ty, float tz, Eigen::Matrix4d &transformation) { double angle = cloud_geometry::angles::getAngleBetweenPlanes (plane_a, plane_b); // Compute the rotation axis R = Nplane x (0, 0, 1) geometry_msgs::Point32 r_axis; r_axis.x = plane_a[1]*plane_b[2] - plane_a[2]*plane_b[1]; r_axis.y = plane_a[2]*plane_b[0] - plane_a[0]*plane_b[2]; r_axis.z = plane_a[0]*plane_b[1] - plane_a[1]*plane_b[0]; if (r_axis.z < 0) angle = -angle; // Build a normalized quaternion double s = sin (0.5 * angle) / sqrt (r_axis.x * r_axis.x + r_axis.y * r_axis.y + r_axis.z * r_axis.z); double x = r_axis.x * s; double y = r_axis.y * s; double z = r_axis.z * s; double w = cos (0.5 * angle); // Convert the quaternion to a 3x3 matrix double ww = w * w; double xx = x * x; double yy = y * y; double zz = z * z; double wx = w * x; double wy = w * y; double wz = w * z; double xy = x * y; double xz = x * z; double yz = y * z; transformation (0, 0) = xx - yy - zz + ww; transformation (0, 1) = 2*(xy - wz); transformation (0, 2) = 2*(xz + wy); transformation (0, 3) = tx; transformation (1, 0) = 2*(xy + wz); transformation (1, 1) = -xx + yy -zz + ww; transformation (1, 2) = 2*(yz - wx); transformation (1, 3) = ty; transformation (2, 0) = 2*(xz - wy); transformation (2, 1) = 2*(yz + wx); transformation (2, 2) = -xx -yy + zz + ww; transformation (2, 3) = tz; transformation (3, 0) = 0; transformation (3, 1) = 0; transformation (3, 2) = 0; transformation (3, 3) = 1; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** \brief Obtain a 4x4 rigid transformation matrix (with translation) * \param plane_a the normalized coefficients of the first plane * \param plane_b the normalized coefficients of the second plane * \param tx the desired translation on x-axis * \param ty the desired translation on y-axis * \param tz the desired translation on z-axis * \param transformation the resultant transformation matrix */ void getPlaneToPlaneTransformation (const std::vector<double> &plane_a, const geometry_msgs::Point32 &plane_b, float tx, float ty, float tz, Eigen::Matrix4d &transformation) { double angle = cloud_geometry::angles::getAngleBetweenPlanes (plane_a, plane_b); // Compute the rotation axis R = Nplane x (0, 0, 1) geometry_msgs::Point32 r_axis; r_axis.x = plane_a[1]*plane_b.z - plane_a[2]*plane_b.y; r_axis.y = plane_a[2]*plane_b.x - plane_a[0]*plane_b.z; r_axis.z = plane_a[0]*plane_b.y - plane_a[1]*plane_b.x; if (r_axis.z < 0) angle = -angle; // Build a normalized quaternion double s = sin (0.5 * angle) / sqrt (r_axis.x * r_axis.x + r_axis.y * r_axis.y + r_axis.z * r_axis.z); double x = r_axis.x * s; double y = r_axis.y * s; double z = r_axis.z * s; double w = cos (0.5 * angle); // Convert the quaternion to a 3x3 matrix double ww = w * w; double xx = x * x; double yy = y * y; double zz = z * z; double wx = w * x; double wy = w * y; double wz = w * z; double xy = x * y; double xz = x * z; double yz = y * z; transformation (0, 0) = xx - yy - zz + ww; transformation (0, 1) = 2*(xy - wz); transformation (0, 2) = 2*(xz + wy); transformation (0, 3) = tx; transformation (1, 0) = 2*(xy + wz); transformation (1, 1) = -xx + yy -zz + ww; transformation (1, 2) = 2*(yz - wx); transformation (1, 3) = ty; transformation (2, 0) = 2*(xz - wy); transformation (2, 1) = 2*(yz + wx); transformation (2, 2) = -xx -yy + zz + ww; transformation (2, 3) = tz; transformation (3, 0) = 0; transformation (3, 1) = 0; transformation (3, 2) = 0; transformation (3, 3) = 1; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** \brief Convert an axis-angle representation to a 3x3 rotation matrix * \note The formula is given by: A = I * cos (th) + ( 1 - cos (th) ) * axis * axis' - E * sin (th), where * E = [0 -axis.z axis.y; axis.z 0 -axis.x; -axis.y axis.x 0] * \param axis the axis * \param angle the angle * \param rotation the resultant rotation */ void convertAxisAngleToRotationMatrix (const geometry_msgs::Point32 &axis, double angle, Eigen::Matrix3d &rotation) { double cos_a = cos (angle); double sin_a = sin (angle); double cos_a_m = 1.0 - cos_a; double a_xy = axis.x * axis.y * cos_a_m; double a_xz = axis.x * axis.z * cos_a_m; double a_yz = axis.y * axis.z * cos_a_m; double s_x = sin_a * axis.x; double s_y = sin_a * axis.y; double s_z = sin_a * axis.z; rotation (0, 0) = cos_a + axis.x * axis.x * cos_a_m; rotation (0, 1) = a_xy - s_z; rotation (0, 2) = a_xz + s_y; rotation (1, 0) = a_xy + s_z; rotation (1, 1) = cos_a + axis.y * axis.y * cos_a_m; rotation (1, 2) = a_yz - s_x; rotation (2, 0) = a_xz - s_y; rotation (2, 1) = a_yz + s_x; rotation (2, 2) = cos_a + axis.z * axis.z * cos_a_m; } } }
39.534535
162
0.617547
EatAllBugs
8de77de2a0eb078c675441f27e08f562f9ebbcf3
9,761
cxx
C++
src/sound/sn76477.cxx
ascottix/tickle
de3b7df8a6e719b7682398ac689a7e439b40876f
[ "MIT" ]
1
2021-05-31T21:09:50.000Z
2021-05-31T21:09:50.000Z
src/sound/sn76477.cxx
ascottix/tickle
de3b7df8a6e719b7682398ac689a7e439b40876f
[ "MIT" ]
null
null
null
src/sound/sn76477.cxx
ascottix/tickle
de3b7df8a6e719b7682398ac689a7e439b40876f
[ "MIT" ]
null
null
null
/* SN76477 sound chip emulation Copyright (c) 2004-2010,2011 Alessandro Scotti */ #include <math.h> #include "sn76477.h" const unsigned LFSR_MASK = 0x30009; const double MaxExternalVcoControl = 2.35; SN76477::SN76477() { sampling_rate_ = 0; enabled_ = false; env_c_ = 0; // Not connected (disables attack and decay) noise_shift_register_ = 1; // Any (17-bits) nonzero value noise_output_ = 0; oneshot_period_ = 0; slf_output_ = 0; vco_alternate_index_ = 3; vco_half_period_index_ = 0; vco_output_ = 0; update_flags_ = ufUpdateAll; setAmplifier( 1.0, 3.4 ); // Set default volume to slightly less than half setMixer( snMixer_None ); // Disable output // Setup envelopes envelope_mask_[snEnv_VCO] = 0x00; // Toggled by VCO update envelope_mask_[snEnv_MixerOnly] = 0xFF; // Always set envelope_mask_[snEnv_OneShot] = 0; // Will be set by enabled bit envelope_mask_[snEnv_AlternateVCO] = 0; // Will be set by VCO update envelope_ = snEnv_MixerOnly; } void SN76477::setNoiseFilter( double r, double c ) { noise_r_ = r; noise_c_ = c; update_flags_ |= ufNoise; } double SN76477::getNoiseFreqFromRes( double r ) { r /= 1000.0; double f = 783000.0 / pow(r, 0.9); if( r <= 100 ) { f = 759395.0 / pow(r, 0.887); // More accurate for this range } return f; } void SN76477::setNoiseClock( double r ) { setExternalNoiseClock( getNoiseFreqFromRes(r) ); } void SN76477::setExternalNoiseClock( double freq ) { noise_freq_ = freq; update_flags_ |= ufNoise; } void SN76477::setMixer( unsigned mixer ) { static unsigned MixerMask[8] = { 0xFFFF00, // VCO 0xFF00FF, // SLF 0x00FFFF, // Noise 0x00FF00, // VCO/Noise 0x0000FF, // SLF/Noise 0x000000, // SLF/VCO/Noise 0xFF0000, // SLF/VCO 0xFFFFFF // None }; mixer_ = mixer & 0x07; unsigned m = MixerMask[mixer_]; vco_mixer_mask_ = m & 0xFF; slf_mixer_mask_ = (m >> 8) & 0xFF; noise_mixer_mask_ = (m >> 16) & 0xFF; } void SN76477::setSLF( double r, double c ) { slf_r_ = r; slf_c_ = c; update_flags_ |= ufSLF; } void SN76477::refreshParameters() { if( update_flags_ & ufSLF ) { slf_half_period_ = (unsigned) (0.5 + (slf_r_ * slf_c_ * sampling_rate_ / 0.64) / 2); slf_offset_ = 0; } if( update_flags_ & ufVCO_RC ) { vco_max_period_ = (unsigned) (0.5 + vco_r_ * vco_c_ * sampling_rate_ / 0.64); // Minimum frequency vco_min_period_ = vco_max_period_ / 10; vco_offset_ = 0; } if( update_flags_ & ufVCO_PF ) { // Note: duty cycle percentage is rescaled to 512 if( (vco_f_ != 0) && (vco_p_ != 0) ) { vco_duty_cycle_ = (unsigned) ((vco_p_ * 256.0) / vco_f_); // Clip duty cycle between 18% and 50% if( vco_duty_cycle_ > 256 ) { vco_duty_cycle_ = 256; } else if( vco_duty_cycle_ < 92 ) { vco_duty_cycle_ = 92; } } else { vco_duty_cycle_ = 256; } if( ! vco_select_ ) { unsigned t = vco_min_period_ + (unsigned) (vco_f_ * (vco_max_period_-vco_min_period_) / MaxExternalVcoControl); if( t > vco_max_period_ ) { t = vco_max_period_; } vco_half_period_[0] = t * vco_duty_cycle_ / 512; vco_half_period_[1] = t - vco_half_period_[0]; } } if( update_flags_ & ufOneShot ) { // Compute one-shot duration in samples oneshot_period_ = (unsigned) (0.8 * oneshot_r_ * oneshot_c_ * sampling_rate_); } if( update_flags_ & ufEnvelope ) { // Initialize filter so that output is unchanged envelope_coeff_b_[0] = 0; envelope_coeff_b_[1] = 0; // Apply filters that are correctly defined if( (env_r_attack_ > 0) && (env_c_ > 0) ) { double d = env_r_attack_ * env_c_ * sampling_rate_; envelope_coeff_b_[1] = exp( -1/d ); } if( (env_r_decay_ > 0) && (env_c_ > 0) ) { double d = env_r_decay_ * env_c_ * sampling_rate_; envelope_coeff_b_[0] = exp( -1/d ); } envelope_coeff_a_[0] = 1 - envelope_coeff_b_[0]; envelope_coeff_a_[1] = 1 - envelope_coeff_b_[1]; } if( update_flags_ & ufNoise ) { noise_half_period_ = (unsigned) (0.5 + (sampling_rate_ / noise_freq_) / 2); double d = noise_r_ * noise_c_ * sampling_rate_; noise_rc_b_ = exp( -1/d ); noise_rc_a_ = 1 - noise_rc_b_; noise_rc_y_ = 0; } update_flags_ = 0; } void SN76477::setVCO( double r, double c, double p, double f ) { if( (r != vco_r_) || (c != vco_c_) ) { vco_r_ = r; vco_c_ = c; update_flags_ |= ufVCO_RC; } if( (vco_f_ != f) || (vco_p_ != p) ) { vco_f_ = f; vco_p_ = p; update_flags_ |= ufVCO_PF; } } void SN76477::setVCO_Select( int source ) { if( vco_select_ != source ) { vco_select_ = source; update_flags_ |= ufVCO_PF; } } void SN76477::setOneShot( double r, double c ) { oneshot_r_ = r; oneshot_c_ = c; update_flags_ |= ufOneShot; } void SN76477::setEnvelope( int envelope ) { envelope_ = envelope; } void SN76477::setEnvelopeControl( double r_attack, double r_decay, double c ) { env_r_attack_ = r_attack; env_r_decay_ = r_decay; env_c_ = c; update_flags_ |= ufEnvelope; } void SN76477::setAmplifier( int max ) { if( max > 255 ) { max = 255; } for( int i=0; i<256; i++ ) { volume_table_[i] = (int) (i * max / 255); } } void SN76477::setAmplifier( double rf, double rg ) { amp_rf_ = rf; amp_rg_ = rg; setAmplifier( (int) ((3.4 * rf / rg) * 255 / 2.5) ); } void SN76477::enableOutput( bool enabled ) { if( enabled_ != enabled ) { enabled_ = enabled; if( enabled_ ) { envelope_y_ = 0; // No previous output // Trigger one-shot oneshot_offset_ = oneshot_period_; envelope_mask_[snEnv_OneShot] = 0xFF; } } } void SN76477::playSound( int * buffer, int len, unsigned samplingRate ) { if( ! enabled_ ) { return; } // Refresh parameters if something has changed since last call if( sampling_rate_ != samplingRate ) { sampling_rate_ = samplingRate; update_flags_ = ufUpdateAll; } if( update_flags_ ) { refreshParameters(); } // Play the sound while( len > 0 ) { // Update SLF if( slf_offset_ >= slf_half_period_ ) { // Invert output slf_offset_ = 0; slf_output_ ^= 0xFF; } // Update VCO if( vco_select_ ) { // Internal control: SLF modulates VCO frequency unsigned o = slf_output_ ? slf_offset_ : slf_half_period_ - slf_offset_; unsigned t = vco_min_period_ + (unsigned) (o * (vco_max_period_-vco_min_period_) / slf_half_period_); vco_half_period_[0] = t * vco_duty_cycle_ / 512; vco_half_period_[1] = t - vco_half_period_[0]; } if( vco_offset_ >= vco_half_period_[vco_half_period_index_] ) { // Invert output vco_offset_ = 0; vco_output_ ^= 0xFF; vco_half_period_index_ ^= 1; // Update envelope masks envelope_mask_[snEnv_VCO] ^= 0xFF; if( vco_alternate_index_ ) { envelope_mask_[snEnv_AlternateVCO] = 0x00; vco_alternate_index_--; } else { envelope_mask_[snEnv_AlternateVCO] = 0xFF; vco_alternate_index_ = 3; } } // Update noise if( noise_offset_ >= noise_half_period_ ) { if( noise_shift_register_ & 1 ) { noise_shift_register_ ^= LFSR_MASK; noise_output_ = 0xFF; } else { noise_output_ = 0x00; } noise_shift_register_ >>= 1; noise_offset_ = 0; } // Bump offsets slf_offset_++; vco_offset_++; noise_offset_++; // Update one-shot timer if( oneshot_offset_ ) { if( --oneshot_offset_ == 0 ) { envelope_mask_[snEnv_OneShot] = 0x00; } } // Compute envelope unsigned e = envelope_mask_[envelope_]; if( e ^ envelope_value_ ) { // Envelope changed, select attack/decay coefficients accordingly envelope_a_ = envelope_coeff_a_[e & 0x01]; envelope_b_ = envelope_coeff_b_[e & 0x01]; envelope_value_ = e; } // Apply attack/decay filter envelope_y_ = envelope_a_ * e + envelope_b_ * envelope_y_; e = (unsigned) envelope_y_; // Mix SLF, VCO and Noise according to mixer settings unsigned s = (vco_output_ | vco_mixer_mask_) & (slf_output_ | slf_mixer_mask_) & (noise_output_ | noise_mixer_mask_); // Combine mixer output with envelope and write to output buffer *buffer++ = volume_table_[s & e]; len--; } }
27.038781
126
0.543797
ascottix
8defcde9cd7b691147616742be87f8857600f3b3
2,401
cpp
C++
lib/cpp/ScopedLock.cpp
kubasejdak/osal
6e43ba761572444b2f56b529e501f40c00d4e718
[ "BSD-2-Clause" ]
1
2021-09-12T21:05:45.000Z
2021-09-12T21:05:45.000Z
lib/cpp/ScopedLock.cpp
kubasejdak/osal
6e43ba761572444b2f56b529e501f40c00d4e718
[ "BSD-2-Clause" ]
2
2020-01-24T18:00:15.000Z
2020-02-03T21:15:54.000Z
lib/cpp/ScopedLock.cpp
kubasejdak/osal
6e43ba761572444b2f56b529e501f40c00d4e718
[ "BSD-2-Clause" ]
2
2020-06-15T16:27:58.000Z
2021-09-12T21:05:49.000Z
///////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @copyright BSD 2-Clause License /// /// Copyright (c) 2020-2021, Kuba Sejdak <kuba.sejdak@gmail.com> /// 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. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" /// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE /// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE /// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL /// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR /// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER /// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE /// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// ///////////////////////////////////////////////////////////////////////////////////// #include "osal/ScopedLock.hpp" namespace osal { ScopedLock::ScopedLock(Mutex& mutex) : m_mutex(mutex) { lock(); } ScopedLock::ScopedLock(Mutex& mutex, Timeout timeout) : m_mutex(mutex) { timedLock(timeout); } ScopedLock::~ScopedLock() { unlock(); } std::error_code ScopedLock::lock() { auto error = m_mutex.lock(); if (!error) m_locked = true; return error; } std::error_code ScopedLock::timedLock(Timeout timeout) { auto error = m_mutex.timedLock(timeout); if (!error) m_locked = true; return error; } std::error_code ScopedLock::unlock() { auto error = m_mutex.unlock(); if (!error) m_locked = false; return error; } } // namespace osal
29.280488
85
0.658892
kubasejdak
8df5b12f2f17060a6e07c79700118dc8448465eb
1,706
hpp
C++
include/test/channelmanager.hpp
AnotherFoxGuy/settings
cc2fb43ad515e8ff7349e2eb4ddeb3fb96337b1a
[ "MIT" ]
3
2017-09-05T12:25:52.000Z
2021-06-20T12:50:22.000Z
include/test/channelmanager.hpp
AnotherFoxGuy/settings
cc2fb43ad515e8ff7349e2eb4ddeb3fb96337b1a
[ "MIT" ]
9
2017-04-07T19:03:58.000Z
2020-08-15T14:02:29.000Z
lib/settings/include/test/channelmanager.hpp
Functioneel/chatterino7
81a52498b6850626223f96fa81c3e847c23ee25d
[ "MIT" ]
3
2018-05-27T22:07:09.000Z
2021-02-12T12:44:46.000Z
#pragma once #include "test/channel.hpp" #include <array> namespace pajlada { namespace test { constexpr int NUM_CHANNELS = 5; class ChannelManager { public: ChannelManager() : channels{{ {0}, // {1}, // {2}, // {3}, // {4} /*, // {5}, // {6}, // {7}, // {8}, // {9}, // {10}, // {11}, // {12}, // {13}, // {14}, // {15}, // {16}, // {17}, // {18}, // {19}, // {20}, // {21}, // {22}, // {23}, // {24}, // {25}, // {26}, // {27}, // {28}, // {29}, // {30}, // {31}, // {32}, // {33}, // {34}, // {35}, // {36}, // {37}, // {38}, // {39}, // {40}, // {41}, // {42}, // {43}, // {44}, // {45}, // {46}, // {47}, // {48}, // {49} // */ }} { } std::array<IndexedChannel, NUM_CHANNELS> channels; }; } // namespace test } // namespace pajlada
22.155844
54
0.178781
AnotherFoxGuy
8dfcdfd164816a9437725701fc407555d961a4b2
5,318
hpp
C++
Axis/Graphics/Include/Axis/RenderPass.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-23T14:51:51.000Z
2022-01-23T14:51:51.000Z
Axis/Graphics/Include/Axis/RenderPass.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
null
null
null
Axis/Graphics/Include/Axis/RenderPass.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-10T21:01:54.000Z
2022-01-10T21:01:54.000Z
/// \copyright Simmypeet - Copyright (C) /// This file is subject to the terms and conditions defined in /// file 'LICENSE', which is part of this source code package. #ifndef AXIS_GRAPHICS_RENDERPASS_HPP #define AXIS_GRAPHICS_RENDERPASS_HPP #pragma once #include "../../../System/Include/Axis/List.hpp" #include "DeviceChild.hpp" #include "GraphicsCommon.hpp" namespace Axis { namespace Graphics { /// \brief Specifies how the content should be treated at the first use of subpass. enum class LoadOperation : Uint8 { /// \brief Previous content of the image will be preserved. Load, /// \brief Content will be cleared with specified constant value. Clear, /// \brief The content will be undefined it might be cleared or preserved, depends on the implementation. DontCare, /// \brief Required for enum reflection. MaximumEnumValue = DontCare, }; /// \brief Specifies how the content should be treated at the last use of subpass. enum class StoreOperation : Uint8 { /// \brief The content will be written into the memory. Store, /// \brief The content is not needed after the rendering, and might be discarded. DontCare, /// \brief Required for enum reflection. MaximumEnumValue = DontCare, }; /// \brief The attachment which will be used in RenderPass. struct RenderPassAttachment final { /// \brief Format of the texture view. TextureFormat Format = {}; /// \brief Specifies the number of image sampling. Uint32 Samples = {}; /// \brief LoadOperation to use with Color and Depth attachment (If provided). LoadOperation ColorDepthLoadOperation = {}; /// \brief StoreOperation to use with Color and Depth attachment (If provided). StoreOperation ColorDepthStoreOperation = {}; /// \brief LoadOperation to use with Stencil attachment (If provided). LoadOperation StencilLoadOperation = {}; /// \brief StoreOperation to use with Stencil attachment (If provided). StoreOperation StencilStoreOperation = {}; /// \brief The resource state of attachment will be in when render pass instance begin. ResourceStateFlags InitialState = {}; /// \brief The resource state of attachment will be transited into when the render pass instance ended. ResourceStateFlags FinalState = {}; }; /// \brief Reference (index) to the render pass's attachments. struct AttachmentReference final { /// \brief Specified that this attachment reference won't be used. static constexpr Uint32 Unused = ~0U; /// \brief Index reference corresponding in the RenderPass's attachments array. Uint32 Index = {}; /// \brief The layout of texture view will to be transited to in the subpass. ResourceStateFlags SubpassState = {}; }; /// \brief RenderPass's Subpass specification struct SubpassDescription final { /// \brief References to the RenderTarget attachments, The array correspond to the out index in fragment shader. System::List<AttachmentReference> RenderTargetReferences = {}; /// \brief References to the Input attachments. System::List<AttachmentReference> InputReferences = {}; /// \brief Reference to the DepthStencil attachments. AttachmentReference DepthStencilReference = {}; }; /// \brief Specifies memory and execution dependencies between the subpasses struct SubpassDependency final { /// \brief Specifies to implicit(external) subpass. static constexpr Uint32 SubpassExternal = (~0); /// \brief The index of dependant subpass in the dependency. (after) Uint32 DestSubpassIndex = {}; /// \brief The index of source subpass in the dependency. (before) Uint32 SourceSubpassIndex = {}; /// \brief At which stage of destination subpass to start waiting for the source subpass. (after) PipelineStageFlags DestStages = {}; /// \brief At which stage of source subpass for destination subpass to wait for. (before) PipelineStageFlags SourceStages = {}; /// \brief At which memory access stage of destination subpass to start waiting for the source subpass. (after) AccessMode DestAccessMode = {}; /// \brief At which memory access stage of source subpass for destination subpass to wait for. (before) AccessMode SourceAccessMode = {}; }; /// \brief Description of IRenderPass resource. struct RenderPassDescription final { /// \brief Specifies all attachments which Subpasses will reference to. System::List<RenderPassAttachment> Attachments = {}; /// \brief All subpasses contained in the RenderPass. System::List<SubpassDescription> Subpasses = {}; /// \brief All dependencies contained in the RenderPass. System::List<SubpassDependency> Dependencies = {}; }; /// \brief Represents collections of Subpasses and Attachments and describes how attachments will be use over the courses of Subpasses. /// This contains the informations needed to finish the rendering operations. class AXIS_GRAPHICS_API IRenderPass : public DeviceChild { public: /// \brief The description of IRenderPass resource. const RenderPassDescription Description; protected: /// \brief Constructor IRenderPass(const RenderPassDescription& Description); }; } // namespace Graphics } // namespace Axis #endif // AXIS_GRAPHICS_RENDERPASS_HPP
33.872611
135
0.723956
SimmyPeet
8dfd31b4a4284561e2be3c8249c39aa883893e2e
13,223
cpp
C++
src/lib/client/CommandVolumeRequestBases.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
1
2021-05-21T21:10:09.000Z
2021-05-21T21:10:09.000Z
src/lib/client/CommandVolumeRequestBases.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
12
2021-06-12T16:42:30.000Z
2022-02-01T18:44:42.000Z
src/lib/client/CommandVolumeRequestBases.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018-2021 Grant Erickson * 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. * */ /** * @file * This file implements derivable objects for HLX client volume data * model properties mutation command request buffers. * */ #include "CommandVolumeRequestBases.hpp" #include <string> #include <LogUtilities/LogUtilities.hpp> #include <OpenHLX/Utilities/Assert.hpp> #include <OpenHLX/Common/CommandBuffer.hpp> #include <OpenHLX/Common/OutputStringStream.hpp> using namespace HLX::Common; using namespace HLX::Model; namespace HLX { namespace Client { namespace Command { static const char kVolumeProperty = 'V'; /** * @brief * This is the class initializer for a volume level mutation * request operation. * * This initializes a volume level property mutation request * operation against a specific object identifier * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume level mutation request is to be * made against. For example, "O" for a zone * object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume level * mutation request is to be made against. * @param[in] aOperation A pointer to a null-terminated C string * representing the mutation request * operation to perform. * * @retval kStatus_Success If successful. * */ Status VolumeRequestBasis :: Init(const char *aObject, const IdentifierModel::IdentifierType &aIdentifier, const char *aOperation) { return (PropertyRequestBasis::Init(kVolumeProperty, aObject, aIdentifier, aOperation)); } /** * @brief * This is the class initializer for a volume level increase * mutation request operation. * * This initializes a volume level property increase mutation request * operation against a specific object identifier * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume level increase mutation request is * to be made against. For example, "O" for * a zone object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume level * increase mutation request is to be made * against. * * @retval kStatus_Success If successful. * */ Status VolumeIncreaseRequestBasis :: Init(const char *aObject, const IdentifierModel::IdentifierType &aIdentifier) { static const char * const kVolumeIncreaseOperation = "U"; return (VolumeRequestBasis::Init(aObject, aIdentifier, kVolumeIncreaseOperation)); } /** * @brief * This is the class initializer for a volume level decrease * mutation request operation. * * This initializes a volume level property decrease mutation request * operation against a specific object identifier * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume level decrease mutation request is * to be made against. For example, "O" for * a zone object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume level * decrease mutation request is to be made * against. * * @retval kStatus_Success If successful. * */ Status VolumeDecreaseRequestBasis :: Init(const char *aObject, const IdentifierModel::IdentifierType &aIdentifier) { static const char * const kVolumeDecreaseOperation = "D"; return (VolumeRequestBasis::Init(aObject, aIdentifier, kVolumeDecreaseOperation)); } /** * @brief * This is the class initializer for a volume level set mutation * request operation. * * This initializes a volume level property set mutation request * operation against a specific object identifier * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume level set mutation request is * to be made against. For example, "O" for * a zone object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume level * set mutation request is to be made * against. * @param[in] aLevel An immutable reference to the * volume level to set. * * @retval kStatus_Success If successful. * */ Status VolumeSetRequestBasis :: Init(const char *aObject, const IdentifierType &aIdentifier, const LevelType &aLevel) { return (VolumeBufferBasis::Init(*this, aObject, aIdentifier, aLevel)); } /** * @brief * This is the class initializer for a volume fixed/locked state * set mutation request operation. * * This initializes a volume fixed/locked state property set mutation * request operation against a specific object identifier * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume fixed/locked state set mutation * request is to be made against. For * example, "O" for a zone object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume fixed/locked * state set mutation request is to be made * against. * @param[in] aFixed An immutable reference to the volume * fixed/locked state to set. * * @retval kStatus_Success If successful. * */ Status VolumeFixedRequestBasis :: Init(const char *aObject, const IdentifierType &aIdentifier, const FixedType &aFixed) { return (VolumeFixedBufferBasis::Init(*this, aObject, aIdentifier, aFixed)); } /** * @brief * This is the class initializer for a volume mute mutation request * operation. * * This initializes a volume mute property mutation request operation * against a specific object identifier. * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume mute mutation request is to be * made against. For example, "O" for a zone * object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume mute * mutation request is to be made against. * @param[in] aOperation A pointer to a null-terminated C string * representing the mutation request * operation to perform. * * @retval kStatus_Success If successful. * */ Status VolumeMuteRequestBasis :: Init(const char *aObject, const IdentifierModel::IdentifierType &aIdentifier, const char *aOperation) { OutputStringStream lIdentifierStream; std::string lBuffer; lIdentifierStream << aIdentifier; // Compose the buffer. lBuffer = kVolumeProperty; lBuffer += aOperation; lBuffer += aObject; lBuffer += lIdentifierStream.str(); return (RequestBasis::Init(lBuffer.c_str(), lBuffer.size())); } /** * @brief * This is the class initializer for a volume mute set * (assert/enable) mutation request operation. * * This initializes a volume mute property set (assert/enable) * mutation request operation against a specific object identifier * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume mute set (assert/enable) mutation * request is to be made against. For * example, "O" for a zone object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume mute * set (assert/enable) mutation request is * to be made against. * * @retval kStatus_Success If successful. * */ Status VolumeMuteSetRequestBasis :: Init(const char *aObject, const IdentifierModel::IdentifierType &aIdentifier) { static const MuteType kMute = true; return (VolumeMuteBufferBasis::Init(*this, aObject, aIdentifier, kMute)); } /** * @brief * This is the class initializer for a volume mute set * (deassert/disable) mutation request operation. * * This initializes a volume mute property set (deassert/disable) * mutation request operation against a specific object identifier * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume mute set (deassert/disable) * mutation request is to be made * against. For example, "O" for a zone * object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume mute set * (deassert/disable) mutation request is to * be made against. * * @retval kStatus_Success If successful. * */ Status VolumeMuteClearRequestBasis :: Init(const char *aObject, const IdentifierModel::IdentifierType &aIdentifier) { static const MuteType kMute = true; return (VolumeMuteBufferBasis::Init(*this, aObject, aIdentifier, !kMute)); } /** * @brief * This is the class initializer for a volume mute toggle (flip) * mutation request operation. * * This initializes a volume mute property toggle (flip) * mutation request operation against a specific object identifier * * @param[in] aObject A pointer to a null-terminated C string * representing the object for which the * volume mute toggle (flip) mutation * request is to be made against. For * example, "O" for a zone object. * @param[in] aIdentifier A reference to the specific object * identifier which the volume mute * toggle (flip) mutation request is to be * made against. * * @retval kStatus_Success If successful. * */ Status VolumeMuteToggleRequestBasis :: Init(const char *aObject, const IdentifierModel::IdentifierType &aIdentifier) { static const char * const kMuteToggleOperation = "MT"; return (VolumeMuteRequestBasis::Init(aObject, aIdentifier, kMuteToggleOperation)); } }; // namespace Command }; // namespace Client }; // namespace HLX
36.029973
88
0.557362
gerickson
5c00b2c022f8defc64c07d892b5f42eb3bea012d
2,557
cpp
C++
src/playercastspellaction.cpp
mikelukas/errantry
e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c
[ "MIT" ]
1
2018-05-11T16:09:35.000Z
2018-05-11T16:09:35.000Z
src/playercastspellaction.cpp
mikelukas/errantry
e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c
[ "MIT" ]
null
null
null
src/playercastspellaction.cpp
mikelukas/errantry
e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c
[ "MIT" ]
null
null
null
#include <sstream> #include "logging/log.h" #include "playercastspellaction.h" PlayerCastSpellAction::PlayerCastSpellAction(Player& player, Monster& monster) : CastSpellAction(player, monster), spellChooser(player.getSpellsForLocale(BATTLE), player) { } bool PlayerCastSpellAction::setupSpellChoice() { //postcondition: asks the player to choose a spell, and sets spellChoice //with that spell if the player has enough MP to cast it. If the player //cancels choosing, aborts this CastSpellAction, completely. //returns true if spell can be cast and setup should move on to next step, //and false if we should stay on this step. //Get spell choice first spellChooser.run(); if(spellChooser.canceled()) { setAborted(true); return false; } spellChoice = spellChooser.getChoice(); if(!caster.hasEnoughMpFor(spellChoice)) { std::stringstream noMpMsg; noMpMsg<<"Not enough MP to cast '"<<spellChoice->getName()<<"'."; log(noMpMsg.str()); return false; } return true; } bool PlayerCastSpellAction::setupTargetChoice() { //postcondition: gets eligible targets for the chosen spell, and asks //the player to choose from them if there is more than 1. If there is only //one, automatically chooses the spell's target without asking. //returns true if this CastSpellAction should move on to the next setup step //and false if it should move back to the previous one. //Prepare target list based on spell's eligible targts vector<Character*>* eligibleTargets = new vector<Character*>(); const set<int> eligibleTargetOptions = spellChoice->getEligibleTargets(); for(set<int>::const_iterator it = eligibleTargetOptions.begin(); it != eligibleTargetOptions.end(); it++) { switch(*it) { case PLAYER: eligibleTargets->push_back(&caster); break; case MONSTER: eligibleTargets->push_back(&enemy); break; } } //sanity check that there are actually eligible targets if(eligibleTargets->empty()) { log("WARNING: No eligible targets for this spell! This is a bug; spell shouldn't be eligible to cast in this location."); delete eligibleTargets; return false; } //If there is only 1 eligible target, don't bother asking player for target choice. if(eligibleTargets->size() == 1) { spellTarget = (*eligibleTargets)[0]; delete eligibleTargets; return true; } //Ask player to select a target for the spell TargetChooser targetChooser(eligibleTargets); targetChooser.run(); if(targetChooser.canceled()) { return false; } spellTarget = targetChooser.getChoice(); return true; }
27.793478
123
0.737583
mikelukas
5c02228ba5fec5340a9531313f1c63cb67e9ead2
1,263
cpp
C++
Pattern printing/Letter_M.cpp
acheiveer/CPP-Questions-and-Solutions
17097bfb25a75568122ce313d571cb473d55fdf3
[ "MIT" ]
42
2021-09-26T18:02:52.000Z
2022-03-15T01:52:15.000Z
Pattern printing/Letter_M.cpp
acheiveer/CPP-Questions-and-Solutions
17097bfb25a75568122ce313d571cb473d55fdf3
[ "MIT" ]
404
2021-09-24T19:55:10.000Z
2021-11-03T05:47:47.000Z
Pattern printing/Letter_M.cpp
acheiveer/CPP-Questions-and-Solutions
17097bfb25a75568122ce313d571cb473d55fdf3
[ "MIT" ]
140
2021-09-22T20:50:04.000Z
2022-01-22T16:59:09.000Z
/* CPP Program to print Letter M ##@@ @@## ## @@ @@ ## ## @@ @@ ## ## ## ## ## ## ## ## ## ## ## ## Letter M can be broken down into 3 parts - full length first ## column - half length V letter - full length last ## column */ #include <bits/stdc++.h> using namespace std; int main() { int level = 8; int vLevel = level/2; int firstSpaces = 0, lastSpaces = 0, midSpaces = 0; int i, cols = 2 * vLevel + 2; //for printing pattern till last row for (i = 0; i < level; ++i) { cout << "##"; if (i < vLevel -1) { firstSpaces = i; lastSpaces = i; midSpaces = cols - firstSpaces - lastSpaces - 4; //for @@ and @@ //print leading spaces cout << string(firstSpaces, ' '); //print @@ cout << "@@"; //print mid spaces cout << string(midSpaces, ' '); //print @@ cout << "@@"; //print last spaces; cout << string(lastSpaces, ' '); } else if (i == vLevel -1) { //last level of V cout << string(i + 1, ' ') << "##" << string(i + 1, ' '); } else { cout << string(cols, ' '); } cout << "##"; cout << endl; } return 0; }
20.047619
72
0.441013
acheiveer
5c055bd69d4f9e223b296493ef7ba41c2b4af786
275
cpp
C++
cheats/hooks/getColorModulation.cpp
Bartis1313/csgo
2af92e14406182bd0b3c15c0143a67e7d1908d02
[ "MIT" ]
54
2021-11-15T13:39:51.000Z
2022-03-21T17:13:28.000Z
cheats/hooks/getColorModulation.cpp
Bartis1313/csgo
2af92e14406182bd0b3c15c0143a67e7d1908d02
[ "MIT" ]
24
2021-11-08T06:59:34.000Z
2022-03-17T05:17:03.000Z
cheats/hooks/getColorModulation.cpp
Bartis1313/csgo
2af92e14406182bd0b3c15c0143a67e7d1908d02
[ "MIT" ]
10
2021-11-10T06:52:14.000Z
2022-02-02T17:09:20.000Z
#include "hooks.hpp" #include "../features/visuals/world.hpp" #include "../globals.hpp" void __fastcall hooks::getColorModulation::hooked(FAST_ARGS, float* r, float* g, float* b) { original(thisptr, r, g, b); world.modulateWorld(thisptr, r, g, b, globals::isShutdown); }
25
90
0.709091
Bartis1313
5c0b2e728bda762e0156bc0a624df0de9de774cf
1,834
cpp
C++
src/authentication.cpp
rampageX/azure-http-proxy
260cef1304bf266896ee4ae693418258535745fb
[ "MIT" ]
213
2015-02-07T06:26:07.000Z
2022-02-27T08:24:04.000Z
src/authentication.cpp
rampageX/azure-http-proxy
260cef1304bf266896ee4ae693418258535745fb
[ "MIT" ]
15
2015-02-22T10:53:35.000Z
2018-08-25T09:12:34.000Z
src/authentication.cpp
rampageX/azure-http-proxy
260cef1304bf266896ee4ae693418258535745fb
[ "MIT" ]
92
2015-02-16T12:29:47.000Z
2020-10-20T12:00:49.000Z
/* * authentication.cpp: * * Copyright (C) 2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <algorithm> #include <iterator> #include "authentication.hpp" #include "base64.hpp" namespace azure_proxy { authentication::authentication() { } auth_result authentication::auth_basic(const std::string::const_iterator begin, const std::string::const_iterator end) const { std::string authorization; try { azure_proxy::encoding::base64_decode(begin, end, std::back_inserter(authorization)); } catch (const azure_proxy::encoding::decode_base64_error&) { return auth_result::error; } auto colon_pos = authorization.find(':'); if (colon_pos == std::string::npos) { return auth_result::error; } std::string username(authorization.begin(), authorization.begin() + colon_pos); std::string password(authorization.begin() + colon_pos + 1, authorization.end()); auto iter = this->users_map.find(username); if (iter != this->users_map.end() && std::get<1>(*iter) == password) { return auth_result::ok; } return auth_result::incorrect; } auth_result authentication::auth(const std::string& value) const { if (value.size() > 6 && std::equal(value.begin(), value.begin() + 6, "Basic ")) { return this->auth_basic(value.begin() + 6, value.end()); } else { return auth_result::error; } } void authentication::add_user(const std::string& username, const std::string& password) { this->users_map[username] = password; } void authentication::remove_all_users() { this->users_map.clear(); } authentication& authentication::get_instance() { static authentication instance; return instance; } } // namespace azure_proxy
26.57971
125
0.649945
rampageX
5c0f6bf7002b4ac5f6a4833e97797a40e5781e39
1,062
cpp
C++
src/bits_of_matcha/Loader.cpp
matcha-ai/matcha-engine
2ddc2a1dbe8b646176bf761b85720e94fc6b7cf9
[ "MIT" ]
null
null
null
src/bits_of_matcha/Loader.cpp
matcha-ai/matcha-engine
2ddc2a1dbe8b646176bf761b85720e94fc6b7cf9
[ "MIT" ]
null
null
null
src/bits_of_matcha/Loader.cpp
matcha-ai/matcha-engine
2ddc2a1dbe8b646176bf761b85720e94fc6b7cf9
[ "MIT" ]
1
2022-03-17T12:14:27.000Z
2022-03-17T12:14:27.000Z
#include "bits_of_matcha/Loader.h" #include "matcha/dataset" #include "matcha/tensor" #include "bits_of_matcha/engine/ops/LoadCsv.h" #include "bits_of_matcha/engine/ops/LoadImage.h" #include <filesystem> namespace matcha { Loader::Loader(const std::string& file) : file_(file) {} Loader load(const std::string& file) { return Loader(file); } Loader::operator Dataset() { return dataset::Csv {file_}; } Loader::operator tensor() { std::filesystem::path path(file_); std::string ext = path.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), tolower); if (ext == ".csv") { auto op = new engine::ops::LoadCsv(file_); auto out = engine::ref(op->outputs[0]); engine::send(op); return out; } else if (ext == ".png" || ext == ".jpg" || ext == ".jpeg") { auto op = new engine::ops::LoadImage(file_); auto out = engine::ref(op->outputs[0]); engine::send(op); return out; } else { throw std::runtime_error("unsupported import format: " + ext); } } Loader::operator Flow() { return {}; } }
20.823529
66
0.638418
matcha-ai
5c1027f7b69dc32cb3526f0f8ae62c187324dc63
9,313
cpp
C++
problems_051-100/euler_88.cpp
sedihub/project_euler
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
[ "Apache-2.0" ]
null
null
null
problems_051-100/euler_88.cpp
sedihub/project_euler
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
[ "Apache-2.0" ]
null
null
null
problems_051-100/euler_88.cpp
sedihub/project_euler
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
[ "Apache-2.0" ]
null
null
null
/* PROBLEM: Euler 88 A natural number, N, that can be written as the sum and product of a given set of at least two natural numbers, {a1, a2, ... , ak} is called a product-sum number: N = a1 + a2 + ... + ak = a1 × a2 × ... × ak. For example, 6 = 1 + 2 + 3 = 1 × 2 × 3. For a given set of size, k, we shall call the smallest N with this property a minimal product- sum number. The minimal product-sum numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows. k=2: 4 = 2 × 2 = 2 + 2 k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3 k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4 k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2 k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6 Hence for 2≤k≤6, the sum of all the minimal product-sum numbers is 4+6+8+12 = 30; note that 8 is only counted once in the sum. In fact, as the complete set of minimal product-sum numbers for 2≤k≤12 is {4, 6, 8, 12, 15, 16}, the sum is 61. What is the sum of all the minimal product-sum numbers for 2 ≤ k ≤ 12000? SOLUTION: Clearly brute-force solution is not going to get anywhere. So, instead of finding these, we try to generate them. Since we are interested in the smallest of such product-sum natural numbers, we start from 1 and for each non-prime number, N, consider all possible ways of decomposing it into divisors larger than 1. The difference between the number and the sum of those divisors provides a product sum. We keep the smallest ones in a map. To generate the divisors efficiently, I will use dynamic programming: For n, I first fine its greatest divisor. If this greatest divisor is a prime number, there is only one way to write n in terms of its divisors. If n's greatest divisor is not a prime number, then we must have already encountered it. The decompositions of n are then can be obtained from those of its greatest divisor. Once we have the decompositions, we can compute the length of the corresponding product-sums as outlined above. ANSWER: 7587457 **/ #include <iostream> #include <iomanip> #include <vector> #include <set> #include <map> #include <iterator> #include <algorithm> typedef unsigned long int ULInt; typedef std::vector<ULInt> ULIntVec; typedef std::vector<ULInt>::iterator ULIntVecIt; typedef std::vector<ULInt>::const_iterator ULIntConstVecIt; typedef std::set<ULInt> ULIntSet; typedef std::set<ULInt>::iterator ULIntSetIt; typedef std::set<ULInt>::const_iterator ULIntConstSetIt; typedef std::set<ULInt>::reverse_iterator ULIntSetRit; typedef std::map<ULInt, ULInt> ULIntMap; typedef std::map<ULInt, ULInt>::iterator ULIntMapIt; typedef std::map<ULInt, ULInt>::const_iterator ULIntConstMapIt; ULIntSet set_of_primes(ULInt upper_limit) /* Returns all the primes in the range (1, upper_limit) **/ { ULIntSet primes; primes.insert(2); primes.insert(3); primes.insert(5); ULIntSetIt it; ULInt n; bool is_prime; ULInt k = 6; while (*primes.rbegin() < upper_limit) { // n % 6 = 1 case: n = k + 1; is_prime = true; for (it = primes.begin(); it != primes.end() && (*it) * (*it) <= n; it++) { if (n % *it == 0) { is_prime = false; break; } } if (is_prime) { primes.insert(n); } // // n % 6 = 5 case: n = k + 5; is_prime = true; for (it = primes.begin(); it != primes.end() && (*it) * (*it) <= n; it++) { if (n % *it == 0) { is_prime = false; break; } } if (is_prime) { primes.insert(n); } // k += 6; } while (*primes.rbegin() > upper_limit) { primes.erase(*primes.rbegin()); } return primes; } ULIntMap decompose(ULInt n, const ULIntVec& primes) { ULIntMap decomposition; for (ULIntConstVecIt it = primes.begin(); it != primes.end() && n >= *it; it++) { if (n % *it == 0) { decomposition[*it] = 1; n /= *it; while (n % *it == 0) { decomposition[*it] += 1; n /= *it; } } } return decomposition; } void print(const ULIntVec& vec, bool comma=false) { if (comma) { std::cout << "\t"; ULIntConstVecIt it = vec.begin(); std::cout << *it; it++; while (it != vec.end()) { std::cout << ", " << *it; it++; } } else { for (ULIntConstVecIt it = vec.begin(); it != vec.end(); it++) { std::cout << "\t" << *it << std::endl; } } } int main() { const ULInt MAX_LENGTH = 12000; // 12; // 6; const ULInt MAX_N = 2 * MAX_LENGTH + 1; // MAX_LENGTH 2s is a solution! const bool VERBOSE = !true; ULIntSet primes = set_of_primes(MAX_N); ULIntMap product_sums; // A map of product-sum length to smallest instance. std::map<ULInt, std::set<ULIntVec> > divisor_decomps; ULInt n = 4; ULInt gd, p; ULInt largest_continuous_length = 1; ULInt temp_length; while (largest_continuous_length < MAX_LENGTH && n < MAX_N) { if (primes.find(n) != primes.end()) { n++; continue; } else { // Find the greatest divisor of n: for (ULIntSetIt it = primes.begin(); it != primes.end(); it++) { if (n % *it == 0) { gd = n / *it; // Since *it is the smallest prime factor, this fraction is gd. p = *it; // Smallest prime divisor of n; break; } } if (VERBOSE) { std::cout << n << " = " << p << " * " << gd << std::endl; } // This will always have to be there! divisor_decomps[n].insert(ULIntVec({p, gd})); // Check if we have this in divisor_decomps: if (divisor_decomps.find(gd) != divisor_decomps.end()) { for (std::set<ULIntVec>::iterator sit = divisor_decomps[gd].begin(); sit != divisor_decomps[gd].end(); sit++) { // Append to the previous decompositions: ULIntVec temp_vec(*sit); temp_vec.push_back(p); std::sort(temp_vec.begin(), temp_vec.end()); divisor_decomps[n].insert(temp_vec); // // Multiply to each of the previous values: ULInt idx = 0; while (idx < sit->size()) { // Skip duplicates: while ((idx + 1) < sit->size() && (*sit)[idx] == (*sit)[idx + 1]) { idx++; } ULIntVec temp_vec(*sit); temp_vec[idx] *= p; std::sort(temp_vec.begin(), temp_vec.end()); divisor_decomps[n].insert(temp_vec); idx++; } } // Finally, compute lengths based on the decompositions: for (std::set<ULIntVec>::iterator sit = divisor_decomps[n].begin(); sit != divisor_decomps[n].end(); sit++) { temp_length = n; for (ULIntConstVecIt vit = sit->begin(); vit != sit->end(); vit++) { temp_length -= (*vit - 1); } if (product_sums.find(temp_length) != product_sums.end()) { // If we have encountered a product_sum of the same length, update with the smaller. product_sums[temp_length] = std::min(n, product_sums[temp_length]); } else { // If we have not encountered this length, store it. product_sums[temp_length] = n; } if (VERBOSE) { print(*sit, true); std::cout << "\n\t" << temp_length << std::endl; } } if (VERBOSE) { std::cout << std::endl; } } else { // If we have not already visited it, then it must be a prime! if (primes.find(gd) == primes.end()) { std::cout << "ERROR: " << gd << " is neither a prime nor already visited!" << std::endl; throw; } temp_length = n - (p + gd) + 2; if (product_sums.find(temp_length) != product_sums.end()) { // If we have encountered a product_sum of the same length, update with the smaller. product_sums[temp_length] = std::min(n, product_sums[temp_length]); } else { // If we have not encountered this length, store it. product_sums[temp_length] = n; } if (VERBOSE) { print(*divisor_decomps[n].begin(), true); std::cout << "\n\t" << temp_length << std::endl << std::endl; } } } // Updated the largest length that we have all values before it: while (product_sums.find(largest_continuous_length + 1) != product_sums.end()) { largest_continuous_length++; // std::cout << "\t\t\t*** " << largest_continuous_length << " *** " << std::endl; } n++; } // Print the sum of unique minimal product-sum numbers: ULInt sum = 0; ULIntSet already_visited; for (ULIntMapIt mit = product_sums.begin(); mit != product_sums.end(); mit++) { if (mit->first > MAX_LENGTH) { break; } if (already_visited.find(mit->second) == already_visited.end()) { already_visited.insert(mit->second); sum += mit->second; } if (VERBOSE) { std::cout << std::setw(10) << mit->first << std::setw(10) << mit->second << std::endl; } } std::cout << "Sum of smallest product-sum numbers below " << MAX_LENGTH << " is " << sum << std::endl; return 0; }
30.634868
102
0.567164
sedihub
5c107da0f85e8d5d17223bff21d79ca53016a57d
23,011
hpp
C++
test/test_solver.hpp
ultinate/masked-sudoku
0e0bcdcf6c1701c52cab204ea4ffac392793b92b
[ "MIT" ]
null
null
null
test/test_solver.hpp
ultinate/masked-sudoku
0e0bcdcf6c1701c52cab204ea4ffac392793b92b
[ "MIT" ]
null
null
null
test/test_solver.hpp
ultinate/masked-sudoku
0e0bcdcf6c1701c52cab204ea4ffac392793b92b
[ "MIT" ]
null
null
null
#include <bitset> #include "../sTest/test.h" #include "../board.hpp" #include "../parser.hpp" #include "../slicer.hpp" #include "../solver.hpp" #include "../visualizer.hpp" /** * solver unit tests */ mask ** getTestSlice() { mask *slice = new mask[N]; slice[0] = 0b000000001; slice[1] = 0b000000011; slice[2] = 0b100000100; slice[3] = 0b100000000; slice[4] = 0b100000001; slice[5] = 0b111110111; slice[6] = 0b100110001; slice[7] = 0b100010001; slice[8] = 0b111110011; mask **slicePtr = new mask*[N]; for (int i = 0; i < N; i++) { slicePtr[i] = &slice[i]; } return slicePtr; } mask ** getTestSliceRow() { mask *slice = new mask[N]; slice[0] = 0b111101111; slice[1] = 0b111101111; slice[2] = 0b111101111; slice[3] = 0b111101111; slice[4] = 0b111111111; slice[5] = 0b111101111; slice[6] = 0b111101111; slice[7] = 0b111101111; slice[8] = 0b111101111; mask **slicePtr = new mask*[N]; for (int i = 0; i < N; i++) { slicePtr[i] = &slice[i]; } return slicePtr; } mask ** getTestSliceFull() { mask *slice = new mask[N]; slice[0] = 0b111111111; slice[1] = 0b111111111; slice[2] = 0b111111111; slice[3] = 0b111111111; slice[4] = 0b111111111; slice[5] = 0b111111111; slice[6] = 0b111111111; slice[7] = 0b111111111; slice[8] = 0b111111111; mask **slicePtr = new mask*[N]; for (int i = 0; i < N; i++) { slicePtr[i] = &slice[i]; } return slicePtr; } mask * getTestBoard() { std::string input = "123......" "456......" "789......" "........." "........." "........." "........." "........." "........."; Parser *parser = new Parser(input); parser->parse(); mask *board = parser->getBoard(); return board; } void test_OverlapSolver_boxToColumn() { std::string input = "........." "2........" "3........" "4........" "5........" "6........" "7......89" ".34......" ".56......"; Parser *parser = new Parser(input); parser->parse(); mask *board = parser->getBoard(); SolverInterface *solver = new OverlapSolver; solver->solveBoard(board); std::string expected = "........." "2........" "3........" "4........" "5........" "6........" "7......89" ".34......" ".56......"; TEST(expected == Visualizer::printBoardMini(board)); delete parser; } void test_EliminateSolver_box() { std::string input = "123......" "456......" "78......." "........." "........." "........." "........." "........." "........."; Parser *parser = new Parser(input); parser->parse(); mask *board = parser->getBoard(); SlicerInterface *slicer = new BoxSlicer(); SliceSolverInterface *solver = new EliminateSolver(); solver->solveAllSlices(slicer, board); std::string expected = "123......" "456......" "789......" "........." "........." "........." "........." "........." "........."; TEST(expected == Visualizer::printBoardMini(board)); delete parser; } void test_solvers_combined() { std::string input = "12...69.." "45...9..." "78......." "........." "........." "........." "........." "........." "........."; Parser *parser = new Parser(input); parser->parse(); mask *board = parser->getBoard(); SlicerInterface *slicer = new HorizontalSlicer(); SliceSolverInterface *solver = new EliminateSolver(); solver->solveAllSlices(slicer, board); slicer = new BoxSlicer(); solver->solveAllSlices(slicer, board); solver = new DetermineSolver(); slicer = new BoxSlicer(); solver->solveAllSlices(slicer, board); solver = new EliminateSolver(); slicer = new BoxSlicer(); solver->solveAllSlices(slicer, board); std::string expected = "123..69.." "456..9..." "789......" "........." "........." "........." "........." "........." "........."; TEST(expected == Visualizer::printBoardMini(board)); delete parser; } void test_EliminateSolver_horizontal() { std::string input = "12345678." "........." "........." "........." "........." "........." "........." "........." "........."; Parser *parser = new Parser(input); parser->parse(); mask *board = parser->getBoard(); SlicerInterface *slicer = new HorizontalSlicer(); SliceSolverInterface *solver = new EliminateSolver(); solver->solveAllSlices(slicer, board); std::string expected = "123456789" "........." "........." "........." "........." "........." "........." "........." "........."; TEST(expected == Visualizer::printBoardMini(board)); delete parser; } void test_EliminateSolver_vertical() { std::string input = "........." "........2" "........3" "........4" "........5" "........6" "........7" "........8" "........9"; Parser *parser = new Parser(input); parser->parse(); mask *board = parser->getBoard(); SlicerInterface *slicer = new VerticalSlicer(); SliceSolverInterface *solver = new EliminateSolver(); solver->solveAllSlices(slicer, board); std::string expected = "........1" "........2" "........3" "........4" "........5" "........6" "........7" "........8" "........9"; TEST(expected == Visualizer::printBoardMini(board)); } void test_EliminateSolver_horizontalVertical() { std::string input = "6........" "........2" "........3" "........4" "........5" "1........" "........7" "........8" "........9"; Parser *parser = new Parser(input); parser->parse(); mask *board = parser->getBoard(); SlicerInterface *slicer = new HorizontalSlicer(); SliceSolverInterface *solver = new EliminateSolver(); solver->solveAllSlices(slicer, board); slicer = new VerticalSlicer(); solver->solveAllSlices(slicer, board); std::string expected = "6.......1" "........2" "........3" "........4" "........5" "1.......6" "........7" "........8" "........9"; TEST(expected == Visualizer::printBoardMini(board)); } void test_EliminateSolver_solveSlice() { mask **slice = getTestSlice(); // have we got the slice correctly? TEST(*slice[0] == 0b000000001); TEST(*slice[1] == 0b000000011); TEST(*slice[2] == 0b100000100); TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b100000001); TEST(*slice[5] == 0b111110111); TEST(*slice[6] == 0b100110001); TEST(*slice[7] == 0b100010001); TEST(*slice[8] == 0b111110011); // let's solve it EliminateSolver es; es.solveSlice(slice); TEST(*slice[0] == 0b000000001); TEST(*slice[1] == 0b000000010); TEST(*slice[2] == 0b000000100); TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b000000000); TEST(*slice[5] == 0b011100100); TEST(*slice[6] == 0b000100000); TEST(*slice[7] == 0b000010000); TEST(*slice[8] == 0b011100000); /* for (int i = 0; i < N; i++) { std::bitset<9> b(slice[i]); std::cout << "slice " << i << ": " << b << std::endl; } */ } void test_EliminateSolver_solveSlice_2() { mask **slice = getTestSliceRow(); EliminateSolver es; es.solveSlice(slice); // no change TEST(*slice[0] == 0b111101111); TEST(*slice[1] == 0b111101111); TEST(*slice[2] == 0b111101111); TEST(*slice[3] == 0b111101111); TEST(*slice[4] == 0b111111111); TEST(*slice[5] == 0b111101111); TEST(*slice[6] == 0b111101111); TEST(*slice[7] == 0b111101111); TEST(*slice[8] == 0b111101111); } void test_DetermineSolver_solveSlice() { mask **slice = getTestSliceRow(); DetermineSolver ds; ds.solveSlice(slice); TEST(*slice[0] == 0b111101111); TEST(*slice[1] == 0b111101111); TEST(*slice[2] == 0b111101111); TEST(*slice[3] == 0b111101111); TEST(*slice[4] == 0b000010000); // changed TEST(*slice[5] == 0b111101111); TEST(*slice[6] == 0b111101111); TEST(*slice[7] == 0b111101111); TEST(*slice[8] == 0b111101111); } void test_DetermineSolver_solveSliceNoChange() { mask **slice = getTestSliceFull(); mask **slicePtr = slice; mask **sliceBefore = getTestSliceRow(); // initialize with any values DetermineSolver ds; ds.manager->deepCopySlice(sliceBefore, slicePtr); ds.solveSlice(slicePtr); TEST(ds.manager->areSliceValuesEqual(slicePtr, sliceBefore)); } void test_EliminateSolver_solveSliceNoChange() { mask **slice = getTestSliceFull(); mask **slicePtr = slice; mask **sliceBefore = getTestSliceRow(); // initialize with any values EliminateSolver es; es.manager->BoardManager::deepCopySlice(sliceBefore, slicePtr); es.solveSlice(slicePtr); TEST(es.manager->areSliceValuesEqual(slicePtr, sliceBefore)); } void test_EliminateSolver_eliminate() { mask **slice = getTestSlice(); EliminateSolver es; es.eliminate(slice, 1, 0); TEST(*slice[0] == 0b000000001); TEST(*slice[1] == 0b000000010); TEST(*slice[2] == 0b100000100); TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b100000000); TEST(*slice[5] == 0b111110110); TEST(*slice[6] == 0b100110000); TEST(*slice[7] == 0b100010000); TEST(*slice[8] == 0b111110010); // eliminating number "4" will not change anything es.eliminate(slice, 4, 0); TEST(*slice[0] == 0b000000001); TEST(*slice[1] == 0b000000010); TEST(*slice[2] == 0b100000100); TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b100000000); TEST(*slice[5] == 0b111110110); TEST(*slice[6] == 0b100110000); TEST(*slice[7] == 0b100010000); TEST(*slice[8] == 0b111110010); // eliminating number "5" will change two boxes es.eliminate(slice, 3, 5); TEST(*slice[0] == 0b000000001); TEST(*slice[1] == 0b000000010); TEST(*slice[2] == 0b100000000); // changed TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b100000000); TEST(*slice[5] == 0b111110110); // changed TEST(*slice[6] == 0b100110000); TEST(*slice[7] == 0b100010000); TEST(*slice[8] == 0b111110010); } void test_SolverInterface_transposeSlice() { mask **slice = getTestSlice(); BoardManager manager; mask **sliceT = manager.transposeSlice(slice); TEST(*sliceT[0] == 0b001111111); TEST(*sliceT[1] == 0b000001001); TEST(*sliceT[2] == 0b000001001); TEST(*sliceT[3] == 0b000001101); TEST(*sliceT[4] == 0b000001111); TEST(*sliceT[5] == 0b000000000); TEST(*sliceT[6] == 0b001001000); TEST(*sliceT[7] == 0b010001001); } void test_SolverInterface_transposeSliceTwice() { mask **slice = getTestSlice(); BoardManager manager; mask **sliceT = manager.transposeSlice(slice); mask **sliceTT = manager.transposeSlice(sliceT); TEST(manager.areSliceValuesEqual(slice, sliceTT)); TEST(!(manager.areSlicesEqual(slice, sliceTT))); } void test_SolverInterface_transposeSlice_simple() { mask **slice = getTestSlice(); *slice[0] = 0b111101111; *slice[1] = 0b111101111; *slice[2] = 0b111101111; *slice[3] = 0b111101111; *slice[4] = 0b111111111; *slice[5] = 0b111101111; *slice[6] = 0b111101111; *slice[7] = 0b111101111; *slice[8] = 0b111101111; BoardManager manager; mask **sliceT = manager.transposeSlice(slice); TEST(*sliceT[0] == 0b111111111); TEST(*sliceT[1] == 0b111111111); TEST(*sliceT[2] == 0b111111111); TEST(*sliceT[3] == 0b111111111); TEST(*sliceT[4] == 0b000010000); TEST(*sliceT[5] == 0b111111111); TEST(*sliceT[6] == 0b111111111); TEST(*sliceT[7] == 0b111111111); TEST(*sliceT[8] == 0b111111111); } void test_SolverInterface_copySlice() { mask **slice = getTestSliceFull(); TEST(*slice[0] == 0b111111111); TEST(*slice[1] == 0b111111111); TEST(*slice[2] == 0b111111111); TEST(*slice[3] == 0b111111111); TEST(*slice[4] == 0b111111111); TEST(*slice[5] == 0b111111111); TEST(*slice[6] == 0b111111111); TEST(*slice[7] == 0b111111111); TEST(*slice[8] == 0b111111111); mask **sliceCopy = new mask*[N]; BoardManager manager; manager.copySlice(sliceCopy, slice); for (int i = 0; i < N; i++) { TEST(*sliceCopy[i] == 0b111111111); } TEST(manager.areSliceValuesEqual(slice, sliceCopy)); TEST(manager.areSlicesEqual(slice, sliceCopy)); } void test_SolverInterface_deepCopySlice() { mask **slice = getTestSliceRow(); mask **sliceCopy = new mask*[N]; for (int i = 0; i < N; i++) { sliceCopy[i] = new mask; } BoardManager manager; manager.deepCopySlice(sliceCopy, slice); // values must be equal TEST(*sliceCopy[0] == 0b111101111); TEST(*sliceCopy[1] == 0b111101111); TEST(*sliceCopy[2] == 0b111101111); TEST(*sliceCopy[3] == 0b111101111); TEST(*sliceCopy[4] == 0b111111111); TEST(*sliceCopy[5] == 0b111101111); TEST(*sliceCopy[6] == 0b111101111); TEST(*sliceCopy[7] == 0b111101111); TEST(*sliceCopy[8] == 0b111101111); // pointers must not be equal for (int i = 0; i < N; i++) { TEST(sliceCopy[i] != slice[i]); } TEST(manager.areSliceValuesEqual(slice, sliceCopy)); TEST(!(manager.areSlicesEqual(slice, sliceCopy))); } void test_SolverInterface_deepCopyBoard() { mask *board = getTestBoard(); std::string expected = "123......" "456......" "789......" "........." "........." "........." "........." "........." "........."; TEST(expected == Visualizer::printBoardMini(board)); mask *boardCopy = new mask[N*N]; for (int i = 0; i < N*N; i++) { boardCopy[i] = 0x1; } BoardManager manager; manager.deepCopyBoard(boardCopy, board); // values must be equal TEST(expected == Visualizer::printBoardMini(boardCopy)); TEST(boardCopy[0] == 0b000000001); TEST(boardCopy[1] == 0b000000010); TEST(boardCopy[2] == 0b000000100); TEST(boardCopy[3] == 0b111111111); TEST(boardCopy[4] == 0b111111111); TEST(boardCopy[5] == 0b111111111); TEST(boardCopy[6] == 0b111111111); TEST(boardCopy[7] == 0b111111111); TEST(boardCopy[8] == 0b111111111); TEST(boardCopy[9] == 0b000001000); TEST(boardCopy[80] == 0b111111111); // pointers must not be equal TEST(boardCopy != board); } void test_SolverInterface_areSlicesEqual_equalAddresses() { mask **slice = getTestSliceFull(); mask **sliceCopy = new mask*[N]; BoardManager manager; manager.copySlice(sliceCopy, slice); TEST(manager.areSlicesEqual(slice, sliceCopy)); TEST(manager.areSliceValuesEqual(slice, sliceCopy)); } void test_SolverInterface_areSlicesEqual_equalValues() { mask **slice = getTestSliceFull(); mask **sliceCopy = getTestSliceFull(); BoardManager manager; TEST(!(manager.areSlicesEqual(slice, sliceCopy))); TEST(manager.areSliceValuesEqual(slice, sliceCopy)); *sliceCopy[0] = 0b111111110; TEST(!(manager.areSlicesEqual(slice, sliceCopy))); TEST(!(manager.areSliceValuesEqual(slice, sliceCopy))); } void test_SolverInterface_isSliceSolved() { mask *slice = new mask[N]; slice[0] = 0b100000100; slice[1] = 0b010000000; slice[2] = 0b001000000; slice[3] = 0b000100000; slice[4] = 0b000010000; slice[5] = 0b000001000; slice[6] = 0b000000100; slice[7] = 0b000000010; slice[8] = 0b000000001; mask **slicePtr = new mask*[N]; for (int i = 0; i < N; i++) { slicePtr[i] = &slice[i]; } // not solved yet BoardManager manager; TEST(!manager.isSliceSolved(slicePtr)); TEST(manager.isSliceLegal(slicePtr)); // correctly solved slice[0] = 0b100000000; TEST(manager.isSliceSolved(slicePtr)); TEST(manager.isSliceLegal(slicePtr)); // solved, but illegal slice[0] = 0b000000001; TEST(!manager.isSliceSolved(slicePtr)); TEST(!manager.isSliceLegal(slicePtr)); } void test_SolverInterface_isBoardSolved_solvedLegal() { std::string input = "491786325" "735294816" "826531479" "368172594" "142359687" "579468132" "954823761" "287615943" "613947258"; Parser *parser = new Parser(input); int parseResult = parser->parse(); mask *board = parser->getBoard(); TEST(0 == parseResult); BoardManager manager; TEST(manager.isBoardSolved(board)); TEST(manager.isBoardLegal(board)); } void test_SolverInterface_isBoardSolved_notSolvedLegal() { std::string input = "..37..4.6" "...3.5..." "92..6.8.." ".5...2..4" "..1...6.." "4..98..7." ".3..71..8" "..4...7.2" "..6...1.3"; Parser *parser = new Parser(input); int parseResult = parser->parse(); mask *board = parser->getBoard(); TEST(0 == parseResult); BoardManager manager; TEST(!manager.isBoardSolved(board)); TEST(manager.isBoardLegal(board)); } void test_SolverInterface_isBoardSolved_solvedIllegal() { std::string input = "999999999" "735294816" "826531479" "368172594" "142359687" "579468132" "954823761" "287615943" "613947258"; Parser *parser = new Parser(input); int parseResult = parser->parse(); mask *board = parser->getBoard(); TEST(0 == parseResult); BoardManager manager; TEST(!manager.isBoardSolved(board)); TEST(!manager.isBoardLegal(board)); } void test_SolverInterface_isBoardSolved_notSolvedIllegal() { std::string input = "..36..4.6" "...3.5..." "92..6.8.." ".5...2..4" "..1...6.." "4..98..7." ".3..71..8" "..4...7.2" "..6...1.3"; Parser *parser = new Parser(input); int parseResult = parser->parse(); mask *board = parser->getBoard(); TEST(0 == parseResult); BoardManager manager; TEST(!manager.isBoardSolved(board)); TEST(!manager.isBoardLegal(board)); } void test_BoardManager_isInsideList() { mask **slice = getTestSlice(); mask *element = slice[3]; BoardManager manager; TEST(manager.isInsideList(element, slice, N)); element = new mask; TEST(!manager.isInsideList(element, slice, N)); slice = getTestSlice(); mask **sliceOther = getTestSlice(); element = slice[3]; TEST(!manager.isInsideList(element, sliceOther, N)); } void test_OverlapSolver_getListOfOverlaps_noOverlap() { mask **slice = getTestSlice(); mask **sliceTarget = getTestSlice(); // candidate "2" appears in three potential positions of _slice_ // let's assume no overlap between the two slices. int candidate = 2; mask **listOfOverlaps = getTestSlice(); // initialize with any value OverlapSolver solver; int length = solver.getListOfOverlaps(candidate, listOfOverlaps, slice, sliceTarget); TEST(0 == length); } void test_OverlapSolver_getListOfOverlaps_noCandidateInOverlap() { mask **slice = getTestSlice(); mask **sliceTarget = getTestSlice(); // candidate "2" appears in three potential positions of _slice_ // let's assume overlap between the two slices, however, in other positions int candidate = 2; sliceTarget[0] = slice[2]; sliceTarget[1] = slice[3]; sliceTarget[2] = slice[4]; mask **listOfOverlaps = getTestSlice(); // initialize with any value OverlapSolver solver; int length = solver.getListOfOverlaps(candidate, listOfOverlaps, slice, sliceTarget); TEST(0 == length); } void test_OverlapSolver_getListOfOverlaps_threeOverlapWithCandidate() { mask **slice = getTestSlice(); mask **sliceTarget = getTestSlice(); // initialize with any value // candidate "2" appears in three potential positions of _slice_ // let's assume these three positions also overlap with _sliceTarget_ int candidate = 2; sliceTarget[0] = slice[1]; sliceTarget[1] = slice[5]; sliceTarget[2] = slice[8]; mask **listOfOverlaps = getTestSlice(); // initialize with any value OverlapSolver solver; int length = solver.getListOfOverlaps(candidate, listOfOverlaps, slice, sliceTarget); TEST(3 == length); } void test_OverlapSolver_eliminate_exceptNothing() { mask **slice = getTestSlice(); // have we got the slice correctly? TEST(*slice[0] == 0b000000001); TEST(*slice[1] == 0b000000011); TEST(*slice[2] == 0b100000100); TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b100000001); TEST(*slice[5] == 0b111110111); TEST(*slice[6] == 0b100110001); TEST(*slice[7] == 0b100010001); TEST(*slice[8] == 0b111110011); OverlapSolver solver; mask **sliceOther = new mask*[N]; solver.eliminate(slice, 1, sliceOther, 0); TEST(*slice[0] == 0b000000000); TEST(*slice[1] == 0b000000010); TEST(*slice[2] == 0b100000100); TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b100000000); TEST(*slice[5] == 0b111110110); TEST(*slice[6] == 0b100110000); TEST(*slice[7] == 0b100010000); TEST(*slice[8] == 0b111110010); } void test_OverlapSolver_eliminate_exceptOne() { mask **slice = getTestSlice(); OverlapSolver solver; mask **sliceOther = new mask*[N]; sliceOther[0] = slice[3]; solver.eliminate(slice, 9, sliceOther, 1); TEST(*slice[0] == 0b000000001); TEST(*slice[1] == 0b000000011); TEST(*slice[2] == 0b000000100); TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b000000001); TEST(*slice[5] == 0b011110111); TEST(*slice[6] == 0b000110001); TEST(*slice[7] == 0b000010001); TEST(*slice[8] == 0b011110011); } void test_OverlapSolver_eliminate_exceptAll() { mask **slice = getTestSlice(); OverlapSolver solver; mask **sliceOther = new mask*[N]; BoardManager manager; manager.copySlice(sliceOther, slice); solver.eliminate(slice, 1, sliceOther, N); TEST(*slice[0] == 0b000000001); TEST(*slice[1] == 0b000000011); TEST(*slice[2] == 0b100000100); TEST(*slice[3] == 0b100000000); TEST(*slice[4] == 0b100000001); TEST(*slice[5] == 0b111110111); TEST(*slice[6] == 0b100110001); TEST(*slice[7] == 0b100010001); TEST(*slice[8] == 0b111110011); }
28.408642
79
0.568424
ultinate
5c13470fce1f7d418e3b9beed7a761aa53e74318
357
cpp
C++
mcare_server/test/test_Mola.cpp
KatSchrier/mcare
cd9ecc6e130ed94e1fe8a1881178c7729625fbb3
[ "MIT" ]
1
2021-08-21T02:21:00.000Z
2021-08-21T02:21:00.000Z
mcare_server/test/test_Mola.cpp
KatSchrier/mcare
cd9ecc6e130ed94e1fe8a1881178c7729625fbb3
[ "MIT" ]
null
null
null
mcare_server/test/test_Mola.cpp
KatSchrier/mcare
cd9ecc6e130ed94e1fe8a1881178c7729625fbb3
[ "MIT" ]
2
2021-09-04T00:21:03.000Z
2022-02-05T08:43:48.000Z
// test_Mola.cpp // Created by Robin Rowe 2021-08-15 // MIT Open Source #include <iostream> #include "../Mola.h" using namespace std; int main(int argc,char* argv[]) { cout << "Testing Mola" << endl; Mola mola; if(!mola) { cout << "Mola failed on operator!" << endl; return 1; } cout << mola << endl; cout << "Mola Passed!" << endl; return 0; }
17.85
46
0.621849
KatSchrier
5c1709aa15c6ac0ffff73553361d13cba82cfa11
25,593
cc
C++
src/common/reimu_trie.cc
milkcat/MilkCat
a31c5c7f2ceba0ba3aea9fa88f9da5e9caddacea
[ "MIT" ]
84
2015-01-17T09:44:41.000Z
2020-02-14T06:32:26.000Z
src/common/reimu_trie.cc
milkcat/MilkCat
a31c5c7f2ceba0ba3aea9fa88f9da5e9caddacea
[ "MIT" ]
2
2016-06-27T08:00:53.000Z
2017-02-09T06:15:28.000Z
src/common/reimu_trie.cc
milkcat/MilkCat
a31c5c7f2ceba0ba3aea9fa88f9da5e9caddacea
[ "MIT" ]
29
2015-01-17T09:48:43.000Z
2020-03-06T08:30:18.000Z
// // The MIT License (MIT) // // Copyright 2013-2014 The MilkCat Project Developers // // 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. // // reimu_trie.cc --- Created at 2014-10-16 // Reimu x Marisa :P // #include "common/reimu_trie.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <vector> #define _assert(x) #define XOR(a, b) ((a) ^ (b)) #define CALC_BASE_FROM_TO_AND_LABEL(to, label) ((to) ^ (label)) #define CALC_LABEL_FROM_BASE_AND_TO(base, to) ((base) ^ (to)) #define NODE_INDEX_TO_BLOCK_INDEX(node_idx) ((node_idx) >> 8) #define BLOCK_INDEX_TO_FIRST_NODE_INDEX(node_idx) ((node_idx) << 8) #define CLOSED_THRESHOLD 1 namespace milkcat { class ReimuTrie::Impl { public: Impl(); ~Impl(); // These functions are same to functions in ReimuTrie:: static Impl *Open(const char *filename); int32 Get(const char *key, int32 default_value) const; void Put(const char *key, int32 value); bool Save(const char *filename); int size() const; bool Check(); void SetArray(void *array); void *array() const { return reinterpret_cast<void *>(array_); } bool Traverse( int *from, const char *key, int32 *value, int32 default_value) const; bool Traverse(int *from, char ch, int32 *value, int32 default_value) const; private: class Node; class Block; enum { kBlockLinkListEnd = -1, kBaseNone = -1 }; // To create the first block void Initialize(); // Internal functions for `Check` int CheckBlock(int block_idx); bool CheckList(int head, std::vector<bool> *block_bitmap); // Returns the next index from `from` with character ch int Next(int from, uint8 label); // Removes an empty from block void PopEmptyNode(int node_idx); // Add the node back to the empty list of block void PushEmptyNode(int node_idx); // Transfers a block to another block link list void TransferBlock(int block_idx, int *from_list, int *to_list); // Returns an empty node int FindEmptyNode(); // Resolves conflict int ResolveConflict(int *from, int base, uint8 label); // Count the number of children for a base node int ChildrenCount(int from_idx, int base_idx); // Add a new block and its nodes into the trie int AddBlock(); // Find a empty place that contains each child in `child`. Returns the base // node index int FindEmptyRange(uint8 *child, int count); // Enumerates each child in the sub tree of base_idx, stores them into child // and returns the child number int EnumerateChild(int from_idx, int base_idx, uint8 *child); // Moves each child (in `child`) of `base` into `new_base` void MoveSubTree(int from, int base, int new_base, uint8 *child, int child_count); // Dumps the values in block, just for debugging void DumpBlock(int block_idx); // Restores the block data for `Put` void Restore(); Node *array_; Block *block_; int size_; int capacity_; int open_block_head_; int closed_block_head_; int full_block_head_; bool use_external_array_; }; // Stores block data. A block is a sequence of 256 nodes class ReimuTrie::Impl::Block { public: Block(); // `previous` field, previous node in the chain void set_previous(int previous) { previous_ = previous; } int previous() const { return previous_; }; // `next` field, next node in the chain void set_next(int next) { next_ = next; } int next() const { return next_; }; // `empty_head` field, first empty node of the block void set_empty_head(int empty_head) { empty_head_ = empty_head; } int empty_head() const { return empty_head_; } // `empty_number` field void set_empty_number(int empty_number) { empty_number_ = empty_number; } int empty_number() const { return empty_number_; }; private: int previous_; int next_; int empty_head_; int empty_number_; }; // A (base, check) pair of double array trie class ReimuTrie::Impl::Node { public: // `base` related functions void set_base(int32 base) { base_ = base; }; int32 base() const { _assert(base_ >= kBaseNone); return base_; } void set_previous(int32 previous) { base_ = -previous; } int32 previous() const { _assert(base_ < 0); return -base_; } void set_value(int32 value) { base_ = value; } int32 value() const { _assert(check_ >= 0); return base_; } // `check` related functions void set_check(int32 check) { check_ = check; } int32 check() const { return check_; } void set_next(int32 next) { check_ = -next; } int32 next() const { _assert(check_ < 0); return -check_; } // Returns true if current node is empty bool empty() const { return check_ < 0; } int32 base_; int32 check_; }; ReimuTrie::ReimuTrie() { impl_ = new ReimuTrie::Impl(); } ReimuTrie::~ReimuTrie() { delete impl_; } ReimuTrie::int32 ReimuTrie::Get(const char *key, int32 default_value) const { return impl_->Get(key, default_value); } void ReimuTrie::Put(const char *key, int32 value) { impl_->Put(key, value); } ReimuTrie *ReimuTrie::Open(const char *filename) { Impl *impl = Impl::Open(filename); if (impl != NULL) { ReimuTrie *self = new ReimuTrie(); delete self->impl_; self->impl_ = impl; return self; } else { return NULL; } } bool ReimuTrie::Save(const char *filename) { return impl_->Save(filename); } int ReimuTrie::size() const { return impl_->size(); } void ReimuTrie::_Check() { impl_->Check(); } void ReimuTrie::SetArray(void *array) { impl_->SetArray(array); } bool ReimuTrie::Traverse( int *from, const char *key, int32 *value, int32 default_value) const { return impl_->Traverse(from, key, value, default_value); } bool ReimuTrie::Traverse( int *from, char ch, int32 *value, int32 default_value) const { return impl_->Traverse(from, ch, value, default_value); } void *ReimuTrie::array() const { return impl_->array(); } ReimuTrie::Impl::Block::Block(): previous_(0), next_(0), empty_head_(0), empty_number_(256) { } ReimuTrie::Impl::Impl(): array_(NULL), block_(NULL), size_(0), capacity_(0), open_block_head_(kBlockLinkListEnd), closed_block_head_(kBlockLinkListEnd), full_block_head_(kBlockLinkListEnd), use_external_array_(false) { } ReimuTrie::Impl::~Impl() { if (use_external_array_ == false) free(array_); array_ = NULL; free(block_); block_ = NULL; } int ReimuTrie::Impl::size() const { return size_ * sizeof(Node); } void ReimuTrie::Impl::Initialize() { size_ = 256; capacity_ = 256; array_ = reinterpret_cast<Node *>(malloc(size_ * sizeof(Node))); block_ = reinterpret_cast<Block *>( malloc(NODE_INDEX_TO_BLOCK_INDEX(size_) * sizeof(Block))); array_[0].set_base(0); array_[0].set_check(-1); array_[1].set_previous(255); array_[1].set_next(2); for (int i = 2; i < 255; ++i) { array_[i].set_previous(i - 1); array_[i].set_next(i + 1); } array_[255].set_next(1); array_[255].set_previous(254); block_[0] = Block(); block_[0].set_empty_number(255); block_[0].set_empty_head(1); } void ReimuTrie::Impl::Restore() { int block_num = NODE_INDEX_TO_BLOCK_INDEX(size_); block_ = reinterpret_cast<Block *>(malloc(block_num * sizeof(Block))); for (int block_idx = 0; block_idx < block_num; ++block_idx) { block_[block_idx] = Block(); // `empty_head` and `empty_number` field int first_node = BLOCK_INDEX_TO_FIRST_NODE_INDEX(block_idx); int empty = 0; for (int node_idx = first_node; node_idx < first_node + 256; ++node_idx) { if (array_[node_idx].empty() && node_idx != 0) { if (empty == 0) block_[block_idx].set_empty_head(node_idx); empty++; } } block_[block_idx].set_empty_number(empty); // Put into block linklist if (empty == 0) { TransferBlock(block_idx, NULL, &full_block_head_); } else if (empty <= CLOSED_THRESHOLD) { TransferBlock(block_idx, NULL, &closed_block_head_); } else { TransferBlock(block_idx, NULL, &open_block_head_); } } } bool ReimuTrie::Impl::Save(const char *filename) { FILE *fd = fopen(filename, "wb"); if (fd == NULL) return false; int write_size = static_cast<int>(fwrite(array_, sizeof(Node), size_, fd)); fclose(fd); if (write_size == size_) { return true; } else { return false; } } ReimuTrie::Impl *ReimuTrie::Impl::Open(const char *filename) { FILE *fd = fopen(filename, "rb"); if (fd == NULL) return NULL; Impl *impl = new Impl(); fseek(fd, 0, SEEK_END); impl->size_ = ftell(fd) / sizeof(Node); impl->capacity_ = impl->size_; impl->array_ = reinterpret_cast<Node *>(malloc(impl->size_ * sizeof(Node))); fseek(fd, 0, SEEK_SET); int read_size = static_cast<int>( fread(impl->array_, sizeof(Node), impl->size_, fd)); fclose(fd); if (read_size == impl->size_) { return impl; } else { delete impl; return NULL; } } bool ReimuTrie::Impl::Traverse( int *from, const char *key, int32 *value, int32 default_value) const { if (array_ == NULL) return false; const uint8 *p = reinterpret_cast<const uint8 *>(key); int to, base; while (*p != 0) { base = array_[*from].base(); to = XOR(base, *p); if (array_[to].check() != *from) return false; *from = to; ++p; } to = XOR(array_[*from].base(), 0); if (array_[to].check() != *from) { *value = default_value; } else { *value = array_[to].value(); } return true; } bool ReimuTrie::Impl::Traverse( int *from, char ch, int32 *value, int32 default_value) const { if (array_ == NULL) return false; uint8 ch_u8 = static_cast<uint8>(ch); int base = array_[*from].base(); int to = XOR(base, ch_u8); if (array_[to].check() != *from) return false; *from = to; to = XOR(array_[*from].base(), 0); if (array_[to].check() != *from) { *value = default_value; } else { *value = array_[to].value(); } return true; } ReimuTrie::int32 ReimuTrie::Impl::Get(const char *key, int32 default_value) const { int from = 0; int32 value; bool path_exists = Traverse(&from, key, &value, default_value); if (path_exists == false) return default_value; return value; } void ReimuTrie::Impl::Put(const char *key, int32 value) { if (use_external_array_ == true) { // External array is read only return ; } else if (array_ == NULL) { Initialize(); } else if (block_ == NULL) { Restore(); } _assert(*key != '\0'); const uint8 *p = reinterpret_cast<const uint8 *>(key); int from = 0, to; while (*p != 0) { from = Next(from, *p); ++p; } to = Next(from, 0); array_[to].set_value(value); } int ReimuTrie::Impl::AddBlock() { if (size_ == capacity_) { capacity_ += capacity_; array_ = reinterpret_cast<Node *>( realloc(array_, capacity_ * sizeof(Node))); block_ = reinterpret_cast<Block *>( realloc(block_, NODE_INDEX_TO_BLOCK_INDEX(capacity_) * sizeof(Block))); } int block_idx = NODE_INDEX_TO_BLOCK_INDEX(size_); block_[block_idx] = Block(); block_[block_idx].set_empty_head(size_); // Build empty node linklist array_[size_].set_previous(size_ + 255); array_[size_].set_next(size_ + 1); for (int i = 1; i < 255; ++i) { array_[size_ + i].set_next(size_ + i + 1); array_[size_ + i].set_previous(size_ + i - 1); } array_[size_ + 255].set_previous(size_ + 254); array_[size_ + 255].set_next(size_); TransferBlock(block_idx, NULL, &open_block_head_); size_ += 256; return NODE_INDEX_TO_BLOCK_INDEX(size_) - 1; } int ReimuTrie::Impl::FindEmptyNode() { if (closed_block_head_ != kBlockLinkListEnd) { return block_[closed_block_head_].empty_head(); } if (open_block_head_ != kBlockLinkListEnd) { return block_[open_block_head_].empty_head(); } return BLOCK_INDEX_TO_FIRST_NODE_INDEX(AddBlock()); } int ReimuTrie::Impl::FindEmptyRange(uint8 *child, int count) { if (open_block_head_ != kBlockLinkListEnd) { int block_idx = open_block_head_; // Traverse the opened block linklist do { if (block_[block_idx].empty_number() >= count) { // Traverse the nodes in block, find the qualified base node int first_node_idx = BLOCK_INDEX_TO_FIRST_NODE_INDEX(block_idx); for (int base = first_node_idx; base < first_node_idx + 256; ++base) { int i = 0; for (; i < count; ++i) { // Node - 0 is the special node, always left empty if (XOR(base, child[i]) == 0) break; if (array_[XOR(base, child[i])].empty() == false) break; } // `it == labels.end()` indicates an empty range founded if (i == count) return base; } } block_idx = block_[block_idx].next(); } while (block_idx != open_block_head_); } return BLOCK_INDEX_TO_FIRST_NODE_INDEX(AddBlock()); } int ReimuTrie::Impl::Next(int from, uint8 label) { int base = array_[from].base(); int to; if (kBaseNone == base) { // Node `from` have no base value to = FindEmptyNode(); array_[from].set_base(CALC_BASE_FROM_TO_AND_LABEL(to, label)); PopEmptyNode(to); array_[to].set_base(kBaseNone); array_[to].set_check(from); } else { to = XOR(base, label); if (array_[to].empty()) { // Luckily, `to` is an empty node PopEmptyNode(to); array_[to].set_base(kBaseNone); array_[to].set_check(from); } else if (array_[to].check() != from) { // Conflict detected! int new_base = ResolveConflict(&from, base, label); to = XOR(new_base, label); PopEmptyNode(to); array_[to].set_base(kBaseNone); array_[to].set_check(from); } // Else, `label` child of node `from` already exists, do nothing } return to; } void ReimuTrie::Impl::PopEmptyNode(int node_idx) { _assert(array_[node_idx].empty()); int block_idx = NODE_INDEX_TO_BLOCK_INDEX(node_idx); int empty_number = block_[block_idx].empty_number(); block_[block_idx].set_empty_number(empty_number - 1); if (empty_number == 1) { // Last node in the block TransferBlock(block_idx, &closed_block_head_, &full_block_head_); } else { Node *node = array_ + node_idx; // Remove the node from empty node linklist in block _assert(array_[node->previous()].empty()); array_[node->previous()].set_next(node->next()); _assert(array_[node->next()].empty()); array_[node->next()].set_previous(node->previous()); // Change empty head if (block_[block_idx].empty_head() == node_idx) { block_[block_idx].set_empty_head(node->next()); } // Transfer into closed blocklist when only remians one empty slot if (empty_number == 1 + CLOSED_THRESHOLD) { TransferBlock(block_idx, &open_block_head_, &closed_block_head_); } } } void ReimuTrie::Impl::PushEmptyNode(int node_idx) { int block_idx = NODE_INDEX_TO_BLOCK_INDEX(node_idx); Node *node = array_ + node_idx; int empty_number = block_[block_idx].empty_number(); block_[block_idx].set_empty_number(empty_number + 1); if (empty_number == 0) { // Current block is full TransferBlock(block_idx, &full_block_head_, &closed_block_head_); node->set_previous(node_idx); node->set_next(node_idx); block_[block_idx].set_empty_head(node_idx); } else { // Add the node to the tail of empty linklist int empty_head = block_[block_idx].empty_head(); node->set_next(empty_head); node->set_previous(array_[empty_head].previous()); array_[node->previous()].set_next(node_idx); array_[node->next()].set_previous(node_idx); if (empty_number == CLOSED_THRESHOLD) { TransferBlock(block_idx, &closed_block_head_, &open_block_head_); } } } void ReimuTrie::Impl::TransferBlock(int block_idx, int *from_list, int *to_list) { // Never transfer block `0` if (block_idx == 0) return; Block *block = block_ + block_idx; if (from_list != NULL) { // Transfer out from `from_list` if (block->next() == block_idx) { _assert(*from_list == block_idx); *from_list = kBlockLinkListEnd; } else { // Remove the block from linklist block_[block->previous()].set_next(block->next()); block_[block->next()].set_previous(block->previous()); if (*from_list == block_idx) *from_list = block->next(); } } // Transfer into `to_list` if (kBlockLinkListEnd == *to_list) { // `to_list` is NULL block->set_previous(block_idx); block->set_next(block_idx); *to_list = block_idx; } else { // Add the block into the tail of `to_list` int head_idx = *to_list; int tail_idx = block_[head_idx].previous(); block_[head_idx].set_previous(block_idx); block->set_next(head_idx); block_[tail_idx].set_next(block_idx); block->set_previous(tail_idx); } } int ReimuTrie::Impl::EnumerateChild(int from_idx, int base_idx, uint8 *child) { int count = 0; for (int label = 0; label < 256; ++label) { if (array_[XOR(base_idx, label)].check() == from_idx) { child[count] = static_cast<uint8>(label); count++; } } return count; } void ReimuTrie::Impl::MoveSubTree(int from, int base, int new_base, uint8 *child, int child_count) { for (int i = 0; i < child_count; ++i) { uint8 label = child[i]; int child_idx = XOR(base, label); _assert(array_[child_idx].check() == from); int new_child_idx = XOR(new_base, label); _assert(array_[child_idx].empty() == false); _assert(array_[new_child_idx].empty()); PopEmptyNode(new_child_idx); array_[new_child_idx] = array_[child_idx]; // Change the check value of the children of `array_[child_idx]` int child_base = array_[child_idx].base(); for (int i = 0; i < 256; ++i) { int grandson_idx = XOR(child_base, i); // `grandson_idx` may larger than size_ when child_base is a value node if (grandson_idx > size_) continue; if (array_[grandson_idx].check() == child_idx) { array_[grandson_idx].set_check(new_child_idx); } } PushEmptyNode(child_idx); } } int ReimuTrie::Impl::ResolveConflict(int *from, int base, uint8 label) { int node_idx = XOR(base, label); int conflicted_from = array_[node_idx].check(); int conflicted_base; _assert(conflicted_from != node_idx); if (conflicted_from == node_idx) { // When it is a value node conflicted_base = conflicted_from; } else { conflicted_base = array_[conflicted_from].base(); } _assert(NODE_INDEX_TO_BLOCK_INDEX(conflicted_base) == NODE_INDEX_TO_BLOCK_INDEX(base)); // Determine which tree to remove uint8 child[256]; uint8 conflicted_child[256]; int child_count = EnumerateChild(*from, base, child); int conflicted_child_count = EnumerateChild( conflicted_from, conflicted_base, conflicted_child); int new_base; if (child_count + 1 > conflicted_child_count) { // Move the conflicted sub tree new_base = FindEmptyRange(conflicted_child, conflicted_child_count); array_[conflicted_from].set_base(new_base); MoveSubTree(conflicted_from, conflicted_base, new_base, conflicted_child, conflicted_child_count); // When the from node has been moved if (array_[*from].empty()) { int from_label = CALC_LABEL_FROM_BASE_AND_TO(conflicted_base, *from); *from = XOR(new_base, from_label); } return base; } else { // Move current sub tree // Append `label` into `child` to find the empty place including `label` child[child_count] = label; new_base = FindEmptyRange(child, child_count + 1); array_[*from].set_base(new_base); MoveSubTree(*from, base, new_base, child, child_count); return new_base; } } bool ReimuTrie::Impl::CheckList(int head, std::vector<bool> *block_bitmap) { std::vector<bool> &bitmap = *block_bitmap; if (head != kBlockLinkListEnd) { int block_idx = head; do { int empty = CheckBlock(block_idx); if (head == open_block_head_) { assert(empty > CLOSED_THRESHOLD); } else if (head == closed_block_head_) { assert(empty > 0 && empty <= CLOSED_THRESHOLD); } else if (head == full_block_head_) { assert(empty == 0); } else { assert(false); } bitmap[block_idx] = true; // Checks the `previous` and `next` link between blocks assert(block_[block_[block_idx].next()].previous() == block_idx); block_idx = block_[block_idx].next(); } while (block_idx != head); } return true; } int ReimuTrie::Impl::CheckBlock(int block_idx) { int node_idx_start = BLOCK_INDEX_TO_FIRST_NODE_INDEX(block_idx); int empty = 0; for (int i = node_idx_start; i < node_idx_start + 256; ++i) { Node *node = array_ + i; // `node_idx_start` == 0 is the special first node if (node->check() < 0 && i != 0) { empty++; assert(node->previous() > 0); // Checks the `next` and `previous` between empty nodes Node *previous_node = array_ + node->previous(); Node *next_node = array_ + node->next(); assert(previous_node->next() == i); assert(next_node->previous() == i); } else if (node->check() >= 0) { assert(node->base() >= kBaseNone); if (node->check() != 0) assert(array_[node->check()].empty() == false); } } // Check `empty_number` assert(block_[block_idx].empty_number() == empty); return empty; } bool ReimuTrie::Impl::Check() { std::vector<bool> block_bitmap; int block_num = NODE_INDEX_TO_BLOCK_INDEX(size_); block_bitmap.resize(block_num, false); CheckList(open_block_head_, &block_bitmap); CheckList(closed_block_head_, &block_bitmap); CheckList(full_block_head_, &block_bitmap); // Ensures every block is in blocklist except block `0` for (int i = 1; i < block_num; ++i) { assert(block_bitmap[i]); } return true; } void ReimuTrie::Impl::SetArray(void *array) { delete array_; array_ = reinterpret_cast<Node *>(array); delete block_; block_ = NULL; size_ = 0; capacity_ = 0; open_block_head_ = kBlockLinkListEnd; closed_block_head_ = kBlockLinkListEnd; full_block_head_ = kBlockLinkListEnd; use_external_array_ = true; } void ReimuTrie::Impl::DumpBlock(int block_idx) { printf("BLOCK: %d\n", block_idx); printf("node_idx = %d\n", BLOCK_INDEX_TO_FIRST_NODE_INDEX(block_idx)); printf("empty_number = %d\n", block_[block_idx].empty_number()); printf("-------\n"); for (int node_idx = BLOCK_INDEX_TO_FIRST_NODE_INDEX(block_idx); node_idx < BLOCK_INDEX_TO_FIRST_NODE_INDEX(block_idx) + 256; ++node_idx) { printf("%d %d %d\n", node_idx, array_[node_idx].base_, array_[node_idx].check_); } printf("-------\n"); } } // namespace milkcat reimu_trie_t *reimutrie_open(const char *filename) { return reinterpret_cast<reimu_trie_t *>( milkcat::ReimuTrie::Open(filename)); } reimu_trie_t *reimutrie_new() { return reinterpret_cast<reimu_trie_t *>(new milkcat::ReimuTrie()); } void reimutrie_delete(reimu_trie_t *trie) { milkcat::ReimuTrie *reimu_trie = reinterpret_cast<milkcat::ReimuTrie *>(trie); delete reimu_trie; } void reimutrie_put(reimu_trie_t *trie, const char *key, int32_t value) { milkcat::ReimuTrie *reimu_trie = reinterpret_cast<milkcat::ReimuTrie *>(trie); reimu_trie->Put(key, value); } int32_t reimutrie_get(reimu_trie_t *trie, const char *key, int32_t default_value) { milkcat::ReimuTrie *reimu_trie = reinterpret_cast<milkcat::ReimuTrie *>(trie); return reimu_trie->Get(key, default_value); } bool reimutrie_traverse(reimu_trie_t *trie, int32_t *from, char ch, int32_t *value, int32_t default_value) { milkcat::ReimuTrie *reimu_trie = reinterpret_cast<milkcat::ReimuTrie *>(trie); return reimu_trie->Traverse(from, ch, value, default_value); } bool reimutrie_save(reimu_trie_t *trie, const char *filename) { milkcat::ReimuTrie *reimu_trie = reinterpret_cast<milkcat::ReimuTrie *>(trie); return reimu_trie->Save(filename); }
30.760817
80
0.650998
milkcat
5c19eb60eb123415931a0ca6424311e75bec98fb
4,447
cpp
C++
mytools/compiler/Tokenizer.cpp
kingnak/nand2tetris
120be8f04251b88e519f1bac838c40fd4c1b68e1
[ "MIT" ]
null
null
null
mytools/compiler/Tokenizer.cpp
kingnak/nand2tetris
120be8f04251b88e519f1bac838c40fd4c1b68e1
[ "MIT" ]
null
null
null
mytools/compiler/Tokenizer.cpp
kingnak/nand2tetris
120be8f04251b88e519f1bac838c40fd4c1b68e1
[ "MIT" ]
null
null
null
#include "Tokenizer.h" #include "ParserBase.h" #include <sstream> using namespace std; const map<string, Tokenizer::Keyword> Tokenizer::s_keywords{ { "class", Tokenizer::Keyword::Class }, { "method", Tokenizer::Keyword::Method }, { "function", Tokenizer::Keyword::Function }, { "constructor", Tokenizer::Keyword::Constructor }, { "int", Tokenizer::Keyword::Int }, { "boolean", Tokenizer::Keyword::Boolean }, { "char", Tokenizer::Keyword::Char }, { "void", Tokenizer::Keyword::Void }, { "var", Tokenizer::Keyword::Var }, { "static", Tokenizer::Keyword::Static }, { "field", Tokenizer::Keyword::Field }, { "let", Tokenizer::Keyword::Let }, { "do", Tokenizer::Keyword::Do }, { "while", Tokenizer::Keyword::While }, { "if", Tokenizer::Keyword::If }, { "else", Tokenizer::Keyword::Else }, { "return", Tokenizer::Keyword::Return }, { "true", Tokenizer::Keyword::True }, { "false", Tokenizer::Keyword::False }, { "null", Tokenizer::Keyword::Null }, { "this", Tokenizer::Keyword::This } }; Tokenizer::Tokenizer(istream &in) : m_in(in) , m_token(TokenType::Nothing) , m_keyword(Keyword::None) , m_sym('\0') , m_int(0) , m_pushBack('\0') , m_line(1) , m_pos(0) { } bool Tokenizer::hasMoreTokens() const { return !hasError() && m_token != TokenType::End; } void Tokenizer::advance() { if (m_token == TokenType::End) { setError("Parse beyond end of stream"); return; } if (m_token == TokenType::Error) { return; } do { char c = readChar(); if (isspace(c)) continue; if (c == '\0') { m_token = TokenType::End; return; } switch (c) { case '+': case '-': case '*': case '~': case '&': case '|': case '=': case '.': case ',': case '{': case '}': case '(': case ')': case '[': case ']': case '<': case '>': case ';': m_sym = c; m_token = TokenType::Symbol; return; case '/': c = readChar(); if (c == '/') { skipComment(); break; } else if (c == '*') { skipBlockComment(); break; } else { m_sym = '/'; m_token = TokenType::Symbol; pushBackChar(c); return; } case '"': parseString(); return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': pushBackChar(c); parseNumber(); return; default: if (isalpha(c) || c == '_') { pushBackChar(c); parseIdentifier(); auto it = s_keywords.find(m_str); if (it != s_keywords.end()) { m_token = TokenType::Keyword; m_keyword = it->second; return; } m_token = TokenType::Identifier; return; } setError(string("Unknown character: ") + c); return; } } while (true); } char Tokenizer::readChar() { m_pos++; if (m_pushBack != '\0') { char c = m_pushBack; m_pushBack = '\0'; return c; } int c = m_in.get(); if (c < 0) { if (m_in.bad()) setError("I/O Error"); return '\0'; } if (c == '\n') { m_line++; m_pos = 0; } return char(c); } void Tokenizer::pushBackChar(char c) { if (m_pushBack != '\0') { setError("Internal Error: push back"); return; } m_pushBack = c; m_pos--; } void Tokenizer::skipComment() { while (readChar() != '\n'); } void Tokenizer::skipBlockComment() { char c1 = readChar(); char c2 = readChar(); while (!(c1 == '*' && c2 == '/') && !hasError()) { c1 = c2; c2 = readChar(); } } void Tokenizer::parseString() { m_token = TokenType::StringConst; m_str.clear(); char c = readChar(); while (c != '"' && c != '\0' && c != '\n') { m_str.push_back(c); c = readChar(); } if (c != '"') { setError("End of line in string constant"); } } void Tokenizer::parseNumber() { m_token = TokenType::IntConst; m_str.clear(); char c = readChar(); while (isdigit(c)) { m_str.push_back(c); c = readChar(); } pushBackChar(c); bool ok; m_int = ParserBase::parseNumber(m_str, &ok); if (!ok) { setError("Invalid number"); } } void Tokenizer::parseIdentifier() { m_str.clear(); char c = readChar(); while (isalnum(c) || c == '_') { m_str.push_back(c); c = readChar(); } pushBackChar(c); } void Tokenizer::setError(const string &err) { m_token = TokenType::Error; if (!hasError()) m_err = err; } string Tokenizer::error() const { if (hasError()) { stringstream ss; ss << "Line " << m_line << ", col " << m_pos << ": " << m_err; return ss.str(); } return string(); } bool Tokenizer::hasError() const { return m_err.length() > 0; }
17.646825
64
0.572521
kingnak
5c1da5d7f606deff5526d3c4f211ae9c2a98a046
538
cpp
C++
DirectX2D11/Scenes/InventoryScene.cpp
GyumLee/DirectX2D11
7a92946241ad177c7efac5609e831bc7f0b06908
[ "Apache-2.0" ]
null
null
null
DirectX2D11/Scenes/InventoryScene.cpp
GyumLee/DirectX2D11
7a92946241ad177c7efac5609e831bc7f0b06908
[ "Apache-2.0" ]
null
null
null
DirectX2D11/Scenes/InventoryScene.cpp
GyumLee/DirectX2D11
7a92946241ad177c7efac5609e831bc7f0b06908
[ "Apache-2.0" ]
null
null
null
#include "Framework.h" #include "InventoryScene.h" InventoryScene::InventoryScene() { DataManager::Get(); store = new Store(); store->position = { 300, CENTER_Y }; inventory = new Inventory(); inventory->position = { WIN_WIDTH - 300, CENTER_Y }; store->SetInventory(inventory); } InventoryScene::~InventoryScene() { DataManager::Delete(); delete store; delete inventory; } void InventoryScene::Update() { store->Update(); inventory->Update(); } void InventoryScene::Render() { store->Render(); inventory->Render(); }
14.944444
53
0.693309
GyumLee
5c22b0ad1c6992b1b6d8d1fa26834687bb0ec9dd
1,079
hpp
C++
third_party/boost/simd/function/if_plus.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/function/if_plus.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/function/if_plus.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_IF_PLUS_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_IF_PLUS_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-boolean This function object conditionally returns @c x+y (respectively @c x) if @c c is @ref True (respectively @ref False) @par Header <boost/simd/function/if_plus.hpp> @par Example: @snippet if_plus.cpp if_plus @par Possible output: @snippet if_plus.txt if_plus **/ Value1 if_plus(Value0 const& c, Value1 const& x, Value1 const& y); } } #endif #include <boost/simd/function/scalar/if_plus.hpp> #include <boost/simd/function/simd/if_plus.hpp> #endif
25.093023
100
0.586654
SylvainCorlay
5c23acfe6cdd06e964103fcc92b31afe6fd1dcf6
2,194
cpp
C++
muse_mcl_2d_gridmaps/src/providers/probability_gridmap_provider.cpp
doge-of-the-day/muse_mcl_2d
4cb53120e78780ccc7a7a62d40278fd075d2a54d
[ "BSD-3-Clause" ]
4
2019-06-01T14:08:29.000Z
2019-11-07T02:01:53.000Z
muse_mcl_2d_gridmaps/src/providers/probability_gridmap_provider.cpp
cogsys-tuebingen/muse_mcl_2d
dc053c61208a6ec740b70cea81aaf3c466c1c3b4
[ "BSD-3-Clause" ]
null
null
null
muse_mcl_2d_gridmaps/src/providers/probability_gridmap_provider.cpp
cogsys-tuebingen/muse_mcl_2d
dc053c61208a6ec740b70cea81aaf3c466c1c3b4
[ "BSD-3-Clause" ]
6
2019-03-04T01:46:02.000Z
2020-09-30T01:58:22.000Z
#include "probability_gridmap_provider.h" #include <cslibs_gridmaps/static_maps/conversion/convert_probability_gridmap.hpp> #include <class_loader/register_macro.hpp> CLASS_LOADER_REGISTER_CLASS(muse_mcl_2d_gridmaps::ProbabilityGridmapProvider, muse_mcl_2d::MapProvider2D) namespace muse_mcl_2d_gridmaps { std::shared_ptr<ProbabilityGridmapProvider::state_space_t const> ProbabilityGridmapProvider::getStateSpace() const { std::unique_lock<std::mutex> l(map_mutex_); return map_; } void ProbabilityGridmapProvider::waitForStateSpace() const { std::unique_lock<std::mutex> l(map_mutex_); if (!map_) notify_.wait(l); } void ProbabilityGridmapProvider::setup(ros::NodeHandle &nh) { auto param_name = [this](const std::string &name){return name_ + "/" + name;}; topic_ = nh.param<std::string>(param_name("topic"), "/map"); source_ = nh.subscribe(topic_, 1, &ProbabilityGridmapProvider::callback, this); } void ProbabilityGridmapProvider::callback(const nav_msgs::OccupancyGridConstPtr &msg) { if(!msg) { ROS_ERROR_STREAM("[" << name_ << "]: Received nullptr from ros!"); return; } if(msg->info.height == 0 || msg->info.width == 0 || msg->info.resolution == 0) { ROS_ERROR_STREAM("[" << name_ << "]: Received empty map from ros!"); return; } auto load = [this, msg]() { if(!map_ || cslibs_time::Time(msg->info.map_load_time.toNSec()) > map_->getStamp()) { ROS_INFO_STREAM("[" << name_ << "]: Loading map [" << msg->info.width << " x " << msg->info.height << "]"); ProbabilityGridmap::map_t::Ptr map; cslibs_gridmaps::static_maps::conversion::from<double,double>(*msg, map); std::unique_lock<std::mutex> l(map_mutex_); map_.reset(new ProbabilityGridmap(map, msg->header.frame_id)); ROS_INFO_STREAM("[" << name_ << "]: Loaded map."); l.unlock(); notify_.notify_all(); } }; worker_ = std::thread(load); } }
37.827586
123
0.602097
doge-of-the-day
5c2caa7f897b98ff33bda0eab6cdb5aeefdc7df6
2,229
cpp
C++
Pod/Classes/algorithms/complex/polartocartesian.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
Pod/Classes/algorithms/complex/polartocartesian.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
Pod/Classes/algorithms/complex/polartocartesian.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "polartocartesian.h" using namespace std; using namespace essentia; using namespace standard; const char* PolarToCartesian::name = "PolarToCartesian"; const char* PolarToCartesian::description = DOC("This algorithm converts an array of complex numbers from its polar form to its cartesian form through the Euler formula:\n" " z = x + i*y = |z|(cos(α) + i sin(α))\n" " where x = Real part, y = Imaginary part,\n" " and |z| = modulus = magnitude, α = phase\n" "\n" "An exception is thrown if the size of the magnitude vector does not match the size of the phase vector.\n" "\n" "References:\n" " [1] Polar coordinate system - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Polar_coordinates"); void PolarToCartesian::compute() { const vector<Real>& magnitude = _magnitude.get(); const vector<Real>& phase = _phase.get(); vector<complex<Real> >& complexVec = _complex.get(); if (magnitude.size() != phase.size()) { ostringstream msg; msg << "PolarToCartesian: Could not merge magnitude array (size " << magnitude.size() << ") with phase array (size " << phase.size() << ") because of their different sizes"; throw EssentiaException(msg); } complexVec.resize(magnitude.size()); for (int i=0; i<int(magnitude.size()); ++i) { complexVec[i] = complex<Real>(magnitude[i] * cos(phase[i]), magnitude[i] * sin(phase[i])); } }
38.431034
172
0.694033
jbloit
5c37288b92b93be83773d600d5162b18b4b3f6fd
2,012
hpp
C++
include/Sirius/Renderer/Utils/VertexArray.hpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
null
null
null
include/Sirius/Renderer/Utils/VertexArray.hpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
null
null
null
include/Sirius/Renderer/Utils/VertexArray.hpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
null
null
null
#pragma once #include "srspch.hpp" #include "Buffer.hpp" namespace Sirius { ///////////////////////////////////////// /// @brief Vertex array abstraction class class VertexArray { private: std::vector<Ref<VertexBuffer>> vertexBuffers; Ref<IndexBuffer> indexBuffer; public: uint32_t vtxArrID; ////////////////////////////////////////// /// @brief Creates an OpenGL vertex array. VertexArray(); /////////////////////////////////////////////////////// /// @brief Creates an OpenGL vertex array from a vertex /// buffer and an index buffer. /// /// @param vb The vertex buffer /// @param ib The index buffer VertexArray(const Ref<VertexBuffer>& vb, const Ref<IndexBuffer>& ib); //////////////////////////////// /// @brief Bind the vertex array void bind() const; ////////////////////////////////// /// @brief Unbind the vertex array void unbind() const; ////////////////////////////////////////////////////// /// @brief Add a vertex buffer /// @param vertexBuffer A pointer to a vertex buffer void addVertexBuffer(const Ref<VertexBuffer>& vertexBuffer); /////////////////////////////////////////////////// /// @brief Set the index buffer /// @param indexBuffer A pointer to the index buffer void setIndexBuffer( const Ref<IndexBuffer>& indexBuffer); ///////////////////////////////// /// @brief Get the vertex buffers const std::vector<Ref<VertexBuffer>>& getVertexBuffers() const { return vertexBuffers; } /////////////////////////////// /// @brief Get the index buffer const Ref<IndexBuffer>& getIndexBuffer() const { return indexBuffer; } }; }
32.983607
100
0.430915
xam4lor
5c3741577ba3958b20f6d8ef0ede177b1294626c
3,343
cpp
C++
lovela/StandardCDeclarations.cpp
florgard/lovela
cf5dc270c91c642ffbb4f5fed110c3862a1310b2
[ "MIT" ]
null
null
null
lovela/StandardCDeclarations.cpp
florgard/lovela
cf5dc270c91c642ffbb4f5fed110c3862a1310b2
[ "MIT" ]
null
null
null
lovela/StandardCDeclarations.cpp
florgard/lovela
cf5dc270c91c642ffbb4f5fed110c3862a1310b2
[ "MIT" ]
null
null
null
import CodeGenerator.Cpp; import Utility; import <string>; import <string_view>; import <vector>; import <map>; import <algorithm>; void StandardCDeclarations::GetHeader(std::vector<std::wstring>& headers, std::wstring_view function) { // TODO: Add more if needed, these are extracted from https://www.tutorialspoint.com/c_standard_library/index.htm static const std::map<std::string, std::string> declarations{ {"acos", "math.h"}, {"asin", "math.h"}, {"atan", "math.h"}, {"atan2", "math.h"}, {"cos", "math.h"}, {"cosh", "math.h"}, {"sin", "math.h"}, {"sinh", "math.h"}, {"tanh", "math.h"}, {"exp", "math.h"}, {"frexp", "math.h"}, {"ldexp", "math.h"}, {"log", "math.h"}, {"log10", "math.h"}, {"modf", "math.h"}, {"pow", "math.h"}, {"sqrt", "math.h"}, {"ceil", "math.h"}, {"fabs", "math.h"}, {"floor", "math.h"}, {"fmod", "math.h"}, {"fclose", "stdio.h"}, {"clearerr", "stdio.h"}, {"feof", "stdio.h"}, {"ferror", "stdio.h"}, {"fflush", "stdio.h"}, {"fgetpos", "stdio.h"}, {"fopen", "stdio.h"}, {"fread", "stdio.h"}, {"freopen", "stdio.h"}, {"fseek", "stdio.h"}, {"fsetpos", "stdio.h"}, {"ftell", "stdio.h"}, {"fwrite", "stdio.h"}, {"remove", "stdio.h"}, {"rename", "stdio.h"}, {"rewind", "stdio.h"}, {"setbuf", "stdio.h"}, {"setvbuf", "stdio.h"}, {"tmpfile", "stdio.h"}, {"tmpnam", "stdio.h"}, {"fprintf", "stdio.h"}, {"printf", "stdio.h"}, {"sprintf", "stdio.h"}, {"vfprintf", "stdio.h"}, {"vprintf", "stdio.h"}, {"vsprintf", "stdio.h"}, {"fscanf", "stdio.h"}, {"scanf", "stdio.h"}, {"sscanf", "stdio.h"}, {"fgetc", "stdio.h"}, {"fgets", "stdio.h"}, {"fputc", "stdio.h"}, {"fputs", "stdio.h"}, {"getc", "stdio.h"}, {"getchar", "stdio.h"}, {"gets", "stdio.h"}, {"putc", "stdio.h"}, {"putchar", "stdio.h"}, {"puts", "stdio.h"}, {"ungetc", "stdio.h"}, {"perror", "stdio.h"}, {"atof", "stdlib.h"}, {"atoi", "stdlib.h"}, {"atol", "stdlib.h"}, {"strtod", "stdlib.h"}, {"strtol", "stdlib.h"}, {"strtoul", "stdlib.h"}, {"calloc", "stdlib.h"}, {"free", "stdlib.h"}, {"malloc", "stdlib.h"}, {"realloc", "stdlib.h"}, {"abort", "stdlib.h"}, {"atexit", "stdlib.h"}, {"exit", "stdlib.h"}, {"getenv", "stdlib.h"}, {"system", "stdlib.h"}, {"bsearch", "stdlib.h"}, {"qsort", "stdlib.h"}, {"abs", "stdlib.h"}, {"div", "stdlib.h"}, {"labs", "stdlib.h"}, {"ldiv", "stdlib.h"}, {"rand", "stdlib.h"}, {"srand", "stdlib.h"}, {"mblen", "stdlib.h"}, {"mbstowcs", "stdlib.h"}, {"mbtowc", "stdlib.h"}, {"wcstombs", "stdlib.h"}, {"wctomb", "stdlib.h"}, {"memchr", "string.h"}, {"memcmp", "string.h"}, {"memcpy", "string.h"}, {"memmove", "string.h"}, {"memset", "string.h"}, {"strcat", "string.h"}, {"strncat", "string.h"}, {"strchr", "string.h"}, {"strcmp", "string.h"}, {"strncmp", "string.h"}, {"strcoll", "string.h"}, {"strcpy", "string.h"}, {"strncpy", "string.h"}, {"strcspn", "string.h"}, {"strerror", "string.h"}, {"strlen", "string.h"}, {"strpbrk", "string.h"}, {"strrchr", "string.h"}, {"strspn", "string.h"}, {"strstr", "string.h"}, {"strtok", "string.h"}, {"strxfrm", "string.h"}, }; auto iter = declarations.find(to_string(function)); if (iter != declarations.end()) { headers.emplace_back(to_wstring(iter->second)); } }
24.580882
114
0.521089
florgard
5c37b0446ed312f5a6cb68a9b052a6f613d958bc
10,611
cpp
C++
DGEngine.core.modules/src/Parser/Utils/ParseUtilsVal.cpp
dgcor/DGEngine-Modules
02bd3dab724b8d634b8054cbf079ca4f27a7a8dc
[ "Zlib" ]
1
2021-08-19T10:24:40.000Z
2021-08-19T10:24:40.000Z
DGEngine.core.modules/src/Parser/Utils/ParseUtilsVal.cpp
dgcor/DGEngine-Modules
02bd3dab724b8d634b8054cbf079ca4f27a7a8dc
[ "Zlib" ]
null
null
null
DGEngine.core.modules/src/Parser/Utils/ParseUtilsVal.cpp
dgcor/DGEngine-Modules
02bd3dab724b8d634b8054cbf079ca4f27a7a8dc
[ "Zlib" ]
1
2021-08-19T10:24:47.000Z
2021-08-19T10:24:47.000Z
module dgengine.parser.utils.val; import dgengine.gameutils; import dgengine.json.utils; import dgengine.parser.utils; import dgengine.parser.predicate; import dgengine.sfml.utils; import dgengine.utils.utils; namespace Parser { using namespace rapidjson; Anchor getAnchorVal(const Value& elem, Anchor val) { if (elem.IsString() == true) { return GameUtils::getAnchor(elem.GetStringView(), val); } else if (elem.IsArray() == true) { Anchor ret = Anchor::None; for (const auto& arrElem : elem) { ret |= GameUtils::getAnchor(getStringViewVal(arrElem), val); } return ret; } return val; } BindingFlags getBindingFlagsVal(const Value& elem, BindingFlags val) { if (elem.IsString() == true) { return GameUtils::getBindingFlags(elem.GetStringView(), val); } else if (elem.IsArray() == true) { BindingFlags ret = BindingFlags::OnChange; for (const auto& arrElem : elem) { ret |= GameUtils::getBindingFlags(getStringViewVal(arrElem), val); } return ret; } return val; } BlendMode getBlendModeVal(const Value& elem, BlendMode val) { if (elem.IsString() == true) { return GameUtils::getBlendMode(elem.GetStringView(), val); } return val; } bool getBoolVal(const Value& elem, bool val) { if (elem.IsBool() == true) { return elem.GetBool(); } return val; } double getDoubleVal(const Value& elem, double val) { if (elem.IsDouble() == true) { return elem.GetDouble(); } return val; } float getFloatVal(const Value& elem, float val) { if (elem.IsFloat() == true) { return elem.GetFloat(); } return val; } int getIntVal(const Value& elem, int val) { if (elem.IsInt() == true) { return elem.GetInt(); } return val; } int64_t getInt64Val(const Value& elem, int64_t val) { if (elem.IsInt64() == true) { return elem.GetInt64(); } return val; } const char* getStringCharVal(const Value& elem, const char* val) { if (elem.IsString() == true) { return elem.GetString(); } return val; } std::string getStringVal(const Value& elem, const std::string_view val) { if (elem.IsString() == true) { return elem.GetStringStr(); } else if (elem.IsInt64() == true) { return Utils::toString(elem.GetInt64()); } else if (elem.IsDouble() == true) { return Utils::toString(elem.GetDouble()); } return std::string(val); } std::string_view getStringViewVal(const Value& elem, const std::string_view val) { if (elem.IsString() == true) { return elem.GetStringView(); } return val; } unsigned getUIntVal(const Value& elem, unsigned val) { if (elem.IsUint() == true) { return elem.GetUint(); } return val; } uint64_t getUInt64Val(const Value& elem, uint64_t val) { if (elem.IsUint64() == true) { return elem.GetUint64(); } return val; } std::pair<uint32_t, uint32_t> getFramesVal(const Value& elem, const std::pair<uint32_t, uint32_t>& val) { return getRange1Val<std::pair<uint32_t, uint32_t>, uint32_t>(elem, val); } sf::Vector2f getPositionVal(const Value& elem, const sf::Vector2f& size, const sf::Vector2u& refSize) { float x = 0.f; float y = 0.f; if (elem.IsArray() == true && elem.Size() > 1) { if (elem[0].IsNumber() == true) { x = elem[0].GetFloat(); } else if (elem[0].IsString() == true) { switch (GameUtils::getHorizontalAlignment(elem[0].GetStringView())) { case HorizontalAlign::Left: default: break; case HorizontalAlign::Center: x = std::round((((float)refSize.x) / 2.f) - (size.x / 2.f)); break; case HorizontalAlign::Right: x = ((float)refSize.x) - size.x; break; } } if (elem[1].IsNumber() == true) { y = elem[1].GetFloat(); } else if (elem[1].IsString() == true) { switch (GameUtils::getVerticalAlignment(elem[1].GetStringView())) { case VerticalAlign::Top: default: break; case VerticalAlign::Center: y = std::round((((float)refSize.y) / 2.f) - (size.y / 2.f)); break; case VerticalAlign::Bottom: y = ((float)refSize.y) - size.y; break; } } } return { x, y }; } sf::IntRect getIntRectVal(const Value& elem, const sf::IntRect& val) { if (elem.IsArray() == true && elem.Size() >= 4) { return sf::IntRect( getNumberVal<int>(elem[0]), getNumberVal<int>(elem[1]), getNumberVal<int>(elem[2]), getNumberVal<int>(elem[3]) ); } else if (elem.IsArray() == true && elem.Size() >= 2) { return sf::IntRect( 0, 0, getNumberVal<int>(elem[0]), getNumberVal<int>(elem[1]) ); } return val; } sf::FloatRect getFloatRectVal(const Value& elem, const sf::FloatRect& val) { if (elem.IsArray() == true && elem.Size() >= 4) { return sf::FloatRect( getNumberVal<float>(elem[0]), getNumberVal<float>(elem[1]), getNumberVal<float>(elem[2]), getNumberVal<float>(elem[3]) ); } else if (elem.IsArray() == true && elem.Size() >= 2) { return sf::FloatRect( 0.f, 0.f, getNumberVal<float>(elem[0]), getNumberVal<float>(elem[1]) ); } return val; } sf::Color getColorVal(const Value& elem, const sf::Color& val) { if (elem.IsString() == true) { return SFMLUtils::stringToColor(elem.GetStringView()); } else if (elem.IsUint() == true) { return SFMLUtils::rgbaToColor(elem.GetUint()); } return val; } sf::Keyboard::Key getKeyCodeVal(const Value& elem, sf::Keyboard::Key val) { if (elem.IsInt() == true) { return GameUtils::getKeyCode(elem.GetInt(), val); } else if (elem.IsString() == true) { return GameUtils::getKeyCode(elem.GetStringView(), val); } return val; } sf::Time getTimeVal(const Value& elem, const sf::Time& val) { if (elem.IsUint() == true) { return sf::milliseconds(elem.GetUint()); } else if (elem.IsFloat() == true) { return sf::seconds(elem.GetFloat()); } else if (elem.IsString() == true) { int h = 0, m = 0, s = 0, ms = 0; auto sv = Utils::splitStringIn2(elem.GetStringView(), '.'); if (sv.second.empty() == false) { ms = Utils::strtoi(sv.second); } sv = Utils::splitStringIn2(sv.first, ':'); if (sv.second.empty() == false) { auto sv2 = Utils::splitStringIn2(sv.second, ':'); if (sv2.second.empty() == false) { h = Utils::strtoi(sv.first); m = Utils::strtoi(sv2.first); s = Utils::strtoi(sv2.second); } else { m = Utils::strtoi(sv.first); s = Utils::strtoi(sv2.first); } } else { s = Utils::strtoi(sv.first); } auto totalms = (((h * 3600) + (m * 60) + s) * 1000) + (ms * 100); return sf::milliseconds(totalms); } return val; } IgnoreResource getIgnoreResourceVal(const Value& elem, IgnoreResource val) { if (elem.IsBool() == true) { if (elem.GetBool() == true) { return IgnoreResource::Draw | IgnoreResource::Update; } else { return IgnoreResource::None; } } else if (elem.IsString() == true) { return GameUtils::getIgnoreResource(elem.GetStringView(), val); } return val; } InputEventType getInputEventTypeVal(const Value& elem, InputEventType val) { if (elem.IsBool() == true) { if (elem.GetBool() == true) { return InputEventType::All; } else { return InputEventType::None; } } else if (elem.IsString() == true) { return GameUtils::getInputEventType(elem.GetStringView(), val); } else if (elem.IsArray() == true) { InputEventType ret = InputEventType::None; for (const auto& arrElem : elem) { ret |= GameUtils::getInputEventType(arrElem.GetStringView(), val); } return ret; } return val; } Number32 getMinMaxNumber32Val(const Value& elem) { Number32 num; if (elem.IsInt() == true) { num.setInt32(elem.GetInt()); } if (elem.IsUint() == true) { num.setUInt32(elem.GetUint()); } if (elem.IsFloat() == true) { num.setFloat(elem.GetFloat()); } else if (elem.IsBool() == true) { num.setInt32((int32_t)elem.GetBool()); } else if (elem.IsString() == true) { if (elem.GetStringView() == "min") { num.setInt32(std::numeric_limits<int32_t>::min()); } else if (elem.GetStringView() == "max") { num.setInt32(std::numeric_limits<int32_t>::max()); } } return num; } const Value& getQueryVal(const Value* elem, const Value& query) { if (elem != nullptr) { return JsonUtils::query(*elem, query); } return query; } const Value& getQueryVal(const Value& elem, const Value& query) { return JsonUtils::query(elem, query); } ReplaceVars getReplaceVarsVal(const Value& elem, ReplaceVars val) { if (elem.IsBool() == true) { if (elem.GetBool() == false) { return ReplaceVars::None; } else { return ReplaceVars::String; } } else if (elem.IsString() == true) { return getReplaceVars(elem.GetStringView(), val); } return val; } bool getVariableVal(const Value& elem, Variable& var) { if (elem.IsString() == true) { var.emplace<std::string>(elem.GetStringStr()); } else if (elem.IsInt64() == true) { var.emplace<int64_t>(elem.GetInt64()); } else if (elem.IsDouble() == true) { var.emplace<double>(elem.GetDouble()); } else if (elem.IsBool() == true) { var.emplace<bool>(elem.GetBool()); } else { return false; } return true; } Variable getVariableVal(const Value& elem) { Variable var; getVariableVal(elem, var); return var; } std::vector<std::pair<std::string, Variable>> getVariables(const Value& elem) { std::vector<std::pair<std::string, Variable>> vars; for (auto it = elem.MemberBegin(); it != elem.MemberEnd(); ++it) { auto key = it->name.GetStringView(); if (key.empty() == false) { Variable var; if (getVariableVal(it->value, var) == true) { vars.push_back(std::make_pair(std::string(key), var)); } } } return vars; } UnorderedStringMap<Variable> getVariablesMap(const Value& elem) { UnorderedStringMap<Variable> vars; for (auto it = elem.MemberBegin(); it != elem.MemberEnd(); ++it) { auto key = it->name.GetStringView(); if (key.empty() == false) { Variable var; if (getVariableVal(it->value, var) == true) { vars.insert(std::make_pair(key, var)); } } } return vars; } VarOrPredicate getVarOrPredicateVal(Game& game, const rapidjson::Value& elem) { if (elem.IsObject() == true) { return VarOrPredicate(getPredicateObj(game, elem)); } return VarOrPredicate(getVariableVal(elem)); } }
20.288719
81
0.613703
dgcor
5c3b630dacaa098dda0a50cffad9679d2c93e5ff
2,147
cpp
C++
src/phidgets_encoder_node.cpp
umigv/phidgets_encoder
7021372bda7fd0ef92d2ce26e88a79d1ecf542b5
[ "BSD-3-Clause" ]
null
null
null
src/phidgets_encoder_node.cpp
umigv/phidgets_encoder
7021372bda7fd0ef92d2ce26e88a79d1ecf542b5
[ "BSD-3-Clause" ]
null
null
null
src/phidgets_encoder_node.cpp
umigv/phidgets_encoder
7021372bda7fd0ef92d2ce26e88a79d1ecf542b5
[ "BSD-3-Clause" ]
null
null
null
#include "encoder_state_publisher.h" // umigv::EncoderStatePublisher #include <ros/ros.h> #include <sensor_msgs/JointState.h> #include <umigv_utilities/types.hpp> #include <umigv_utilities/utility.hpp> // umigv::blocking_shutdown #include <umigv_utilities/exceptions.hpp> // umigv::ParameterNotFoundException, // umigv::PhidgetException #include <umigv_utilities/rosparam.hpp> // umigv:get_parameter_or, // umigv::get_parameter_fatal #include <string> // operator""s #include <tuple> // std::tuple using namespace umigv::types; std::tuple<int, f64, std::string> get_defaultable_parameters(ros::NodeHandle &handle) { using namespace std::literals; return std::tuple<int, f64, std::string>{ umigv::get_parameter_or(handle, "serial_number", -1), umigv::get_parameter_or(handle, "frequency", 100.0), umigv::get_parameter_or(handle, "frame_id", "encoders"s) }; } int main(int argc, char *argv[]) { ros::init(argc, argv, "phidgets_encoder_node"); ros::NodeHandle handle; ros::NodeHandle private_handle{ "~" }; int serial_number; f64 frequency; std::string frame_id; std::tie(serial_number, frequency, frame_id) = get_defaultable_parameters(private_handle); f64 rads_per_tick; try { rads_per_tick = umigv::get_parameter_fatal<f64>(private_handle, "rads_per_tick"); } catch (const umigv::ParameterNotFoundException &e) { ROS_FATAL_STREAM("parameter '" << e.parameter() << "' not found"); umigv::blocking_shutdown(); } try { umigv::EncoderStatePublisher state_publisher{ handle.advertise<sensor_msgs::JointState>("wheel_state", 10), umigv::RobotCharacteristics().with_frame(std::move(frame_id)) .with_rads_per_tick(rads_per_tick) .with_serial_number(serial_number) }; auto publish_timer = handle.createTimer(ros::Rate(frequency), &umigv::EncoderStatePublisher::publish_state, &state_publisher); ros::spin(); } catch (const umigv::PhidgetsException &e) { ROS_FATAL_STREAM(e.what() << ": " << e.error_description() << " (" << e.error_code() << ")"); umigv::blocking_shutdown(); } }
29.819444
79
0.699115
umigv
5c4384220dacca3b2d630c0a5ee775a4263a67cc
2,158
cpp
C++
game/server/entities/CRotDoor.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
83
2016-06-10T20:49:23.000Z
2022-02-13T18:05:11.000Z
game/server/entities/CRotDoor.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
26
2016-06-16T22:27:24.000Z
2019-04-30T19:25:51.000Z
game/server/entities/CRotDoor.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
58
2016-06-10T23:52:33.000Z
2021-12-30T02:30:50.000Z
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "entities/DoorConstants.h" #include "CBaseDoor.h" #include "CRotDoor.h" LINK_ENTITY_TO_CLASS( func_door_rotating, CRotDoor ); void CRotDoor::Spawn( void ) { Precache(); // set the axis of rotation CBaseToggle::AxisDir( this ); // check for clockwise rotation if( GetSpawnFlags().Any( SF_DOOR_ROTATE_BACKWARDS ) ) SetMoveDir( GetMoveDir() * -1 ); //m_flWait = 2; who the hell did this? (sjb) m_vecAngle1 = GetAbsAngles(); m_vecAngle2 = GetAbsAngles() + GetMoveDir() * m_flMoveDistance; ASSERTSZ( m_vecAngle1 != m_vecAngle2, "rotating door start/end positions are equal" ); if( GetSpawnFlags().Any( SF_DOOR_PASSABLE ) ) SetSolidType( SOLID_NOT ); else SetSolidType( SOLID_BSP ); SetMoveType( MOVETYPE_PUSH ); SetAbsOrigin( GetAbsOrigin() ); SetModel( GetModelName() ); if( GetSpeed() == 0 ) SetSpeed( 100 ); // DOOR_START_OPEN is to allow an entity to be lighted in the closed position // but spawn in the open position if( GetSpawnFlags().Any( SF_DOOR_START_OPEN ) ) { // swap pos1 and pos2, put door at pos2, invert movement direction SetAbsAngles( m_vecAngle2 ); Vector vecSav = m_vecAngle1; m_vecAngle2 = m_vecAngle1; m_vecAngle1 = vecSav; SetMoveDir( GetMoveDir() * -1 ); } m_toggle_state = TS_AT_BOTTOM; if( GetSpawnFlags().Any( SF_DOOR_USE_ONLY ) ) { SetTouch( NULL ); } else // touchable button SetTouch( &CRotDoor::DoorTouch ); } void CRotDoor::SetToggleState( int state ) { if( state == TS_AT_TOP ) SetAbsAngles( m_vecAngle2 ); else SetAbsAngles( m_vecAngle1 ); SetAbsOrigin( GetAbsOrigin() ); }
25.690476
87
0.715477
xalalau
5c43b3a30db5a49e1c5d73ba8a2816eb6d76c908
494
hpp
C++
Structural-patterns/2_Bridge/src/devices/idevice.hpp
PP189B/Design-patterns-practice
3fd7f9a3fa85dcf1e48680662d9bc3ac41796b69
[ "MIT" ]
null
null
null
Structural-patterns/2_Bridge/src/devices/idevice.hpp
PP189B/Design-patterns-practice
3fd7f9a3fa85dcf1e48680662d9bc3ac41796b69
[ "MIT" ]
null
null
null
Structural-patterns/2_Bridge/src/devices/idevice.hpp
PP189B/Design-patterns-practice
3fd7f9a3fa85dcf1e48680662d9bc3ac41796b69
[ "MIT" ]
null
null
null
#pragma once #include <inttypes.h> namespace Devices { class IDevice { public: virtual uint8_t getVolume() const = 0; virtual void setVolume(uint8_t vol) = 0; virtual uint16_t getChannel() const = 0; virtual void setChannel(uint16_t vol) = 0; virtual bool isEnabled() const = 0; virtual void enable() = 0; virtual void disable() = 0; virtual void listen() const = 0; }; //!class IDevice } //!namespace Devices
19.76
51
0.603239
PP189B
5c507bf1513cf7b489e97c05a561aaca8d628f9c
1,893
cpp
C++
src/bind/solution/route.cpp
jonathf/pyvroom
7f7c755c763ddc416455ea8c5168b53ae1477084
[ "BSD-2-Clause" ]
13
2021-12-28T13:04:45.000Z
2022-01-06T22:05:51.000Z
src/bind/solution/route.cpp
VROOM-Project/pyvroom
7f7c755c763ddc416455ea8c5168b53ae1477084
[ "BSD-2-Clause" ]
26
2022-01-06T09:36:45.000Z
2022-03-26T11:43:14.000Z
src/bind/solution/route.cpp
VROOM-Project/pyvroom
7f7c755c763ddc416455ea8c5168b53ae1477084
[ "BSD-2-Clause" ]
4
2022-01-06T14:34:56.000Z
2022-03-29T11:53:48.000Z
#include <pybind11/pybind11.h> #include "structures/vroom/solution/route.cpp" namespace py = pybind11; void init_route(py::module_ &m) { py::class_<vroom::Route>(m, "Route") .def(py::init<>()) .def(py::init([](vroom::Id vehicle, std::vector<vroom::Step> &steps, vroom::Cost cost, vroom::Duration setup, vroom::Duration service, vroom::Duration duration, vroom::Duration waiting_time, vroom::Priority priority, const vroom::Amount &delivery, const vroom::Amount &pickup, const std::string &profile, const std::string &description, const vroom::Violations &violations) { return new vroom::Route(vehicle, std::move(steps), cost, setup, service, duration, waiting_time, priority, delivery, pickup, profile, description, std::move(violations)); })) .def_readwrite("vehicle", &vroom::Route::vehicle) .def_readonly("steps", &vroom::Route::steps) .def_readwrite("cost", &vroom::Route::cost) .def_readwrite("setup", &vroom::Route::setup) .def_readwrite("service", &vroom::Route::service) .def_readwrite("duration", &vroom::Route::duration) .def_readwrite("waiting_time", &vroom::Route::waiting_time) .def_readwrite("priority", &vroom::Route::priority) .def_readwrite("delivery", &vroom::Route::delivery) .def_readwrite("pickup", &vroom::Route::pickup) .def_readwrite("profile", &vroom::Route::profile) .def_readwrite("description", &vroom::Route::description) .def_readwrite("violations", &vroom::Route::violations) .def_readwrite("geometry", &vroom::Route::geometry) .def_readwrite("distance", &vroom::Route::distance); }
47.325
80
0.595351
jonathf
5c55c3b008d46ab61ab635e68909a600d393232c
758
cpp
C++
Leetcode/Binary_Search/sqrtx.cpp
susantabiswas/competitive_coding
49163ecdc81b68f5c1bd90988cc0dfac34ad5a31
[ "MIT" ]
2
2021-04-29T14:44:17.000Z
2021-10-01T17:33:22.000Z
Leetcode/Binary_Search/sqrtx.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
null
null
null
Leetcode/Binary_Search/sqrtx.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
1
2021-10-01T17:33:29.000Z
2021-10-01T17:33:29.000Z
/* https://leetcode.com/problems/sqrtx/submissions/ We use binary search for this. We set the lower limit as 0 and upper limit as n/2. n/2 ensures that the range covers all possible candidates for sq root, since sq root is m * m, so n/2 * n/2 > n and hence covers all. TC: O(logn) */ class Solution { public: int mySqrt(int x) { if(x <= 1) return x; int low = 0, high = ceil(x / 2); while(low < high) { // rounded ceil int mid = low + (high - low + 1) / 2; long long sq = (long long)mid * mid; if(sq <= x) low = mid; else high = mid - 1; } return low; } };
24.451613
91
0.477573
susantabiswas
5c56db2f73a99cfda90716d8a216c0b741dfae5f
1,982
hpp
C++
receiver/adi.hpp
JCYang/ya_uftp
b6a6dac7969371583c76ad90ef5ebf0c4ae66bdf
[ "BSL-1.0" ]
null
null
null
receiver/adi.hpp
JCYang/ya_uftp
b6a6dac7969371583c76ad90ef5ebf0c4ae66bdf
[ "BSL-1.0" ]
null
null
null
receiver/adi.hpp
JCYang/ya_uftp
b6a6dac7969371583c76ad90ef5ebf0c4ae66bdf
[ "BSL-1.0" ]
null
null
null
#pragma once #ifndef YA_UFTP_RECEIVER_ADI_HPP_ #define YA_UFTP_RECEIVER_ADI_HPP_ #include "api_binder.hpp" #include "boost/asio.hpp" namespace ya_uftp{ namespace receiver{ namespace task{ enum class initiate_result{ already_monitoring, just_started, failed_max_tasks_monitoring }; enum status { waiting_registration_confirm, waiting_fileinfo, receiving_data, complete }; struct progress { std::uint32_t session_id; status current_status; api::fs::path current_file; using listener = std::function<void(progress )>; }; struct parameters{ using interface_name = api::variant<int, std::string, boost::asio::ip::address>; std::vector<api::fs::path> destination_dirs; api::optional<std::vector<api::fs::path>> temp_dirs; bool inplace_tmp_file = false; boost::asio::ip::address public_multicast_addr = boost::asio::ip::make_address_v4("230.4.4.1"); std::size_t udp_buffer_size = 256 * 1024; std::uint16_t listen_port = 1044; std::uint8_t packets_ttl = 1; api::optional<std::uint32_t> client_id; std::vector<interface_name> interfaces_ids; std::chrono::milliseconds grtt = std::chrono::milliseconds(500); std::chrono::microseconds min_grtt = std::chrono::milliseconds(100); std::chrono::milliseconds max_grtt = std::chrono::seconds(15); bool follow_symbolic_link = false; bool quit_on_error = false; // ------ start of Not-Yet-Supported features ------ bool enforce_encryption = false; api::optional<std::vector<std::uint8_t>> finger_print; // ------ end of Not-Yet-Supported features ------ parameters(); parameters(const parameters&); parameters(parameters&&); parameters& operator=(const parameters&); parameters& operator=(parameters&&); ~parameters(); }; } } } #endif
28.314286
99
0.642785
JCYang
5c5909a0f3f444b73a584bec90102ebd0ed4410a
2,453
cpp
C++
4. Brown/3 Week/8. Arithmetic expression 2/main.cpp
freeraisor/yandexcplusplus
9708fdb6cd7e039672ebc2e77f131fbc7a765750
[ "MIT" ]
14
2019-08-29T12:34:07.000Z
2022-03-09T13:31:18.000Z
4. Brown/3 Week/8. Arithmetic expression 2/main.cpp
freeraisor/yandexcplusplus
9708fdb6cd7e039672ebc2e77f131fbc7a765750
[ "MIT" ]
null
null
null
4. Brown/3 Week/8. Arithmetic expression 2/main.cpp
freeraisor/yandexcplusplus
9708fdb6cd7e039672ebc2e77f131fbc7a765750
[ "MIT" ]
8
2020-09-10T11:40:03.000Z
2022-03-24T00:34:38.000Z
#include "Common.h" #include "../../../MyUtils/MyTestFramework/TestFramework.h" #include <sstream> using namespace std; string Print(const Expression* e) { if (!e) { return "Null expression provided"; } stringstream output; output << e->ToString() << " = " << e->Evaluate(); return output.str(); } namespace Expressions { class Value : public Expression { public: explicit Value(int value) : value_(value) {} int Evaluate() const override { return value_; } std::string ToString() const override { return std::to_string(value_); } private: int value_; }; class Sum : public Expression { public: Sum(std::unique_ptr<Expression> left, std::unique_ptr<Expression> right) : left_(std::move(left)), right_(std::move(right)) {} int Evaluate() const override { return left_->Evaluate() + right_->Evaluate(); } std::string ToString() const override { return "(" + left_->ToString() + ")+(" + right_->ToString() + ")"; } private: std::unique_ptr<Expression> left_, right_; }; class Product : public Expression { public: Product(std::unique_ptr<Expression> left, std::unique_ptr<Expression> right) : left_(std::move(left)), right_(std::move(right)) {} int Evaluate() const override { return left_->Evaluate() * right_->Evaluate(); } std::string ToString() const override { return "(" + left_->ToString() + ")*(" + right_->ToString() + ")"; } private: std::unique_ptr<Expression> left_, right_; }; } ExpressionPtr Value(int value) { return std::make_unique<Expressions::Value>(Expressions::Value(value)); } ExpressionPtr Sum(ExpressionPtr left, ExpressionPtr right) { return std::make_unique<Expressions::Sum>(Expressions::Sum(std::move(left), std::move(right))); } ExpressionPtr Product(ExpressionPtr left, ExpressionPtr right) { return std::make_unique<Expressions::Product>(Expressions::Product(std::move(left), std::move(right))); } void Test() { ExpressionPtr e1 = Product(Value(2), Sum(Value(3), Value(4))); ASSERT_EQUAL(Print(e1.get()), "(2)*((3)+(4)) = 14"); ExpressionPtr e2 = Sum(move(e1), Value(5)); ASSERT_EQUAL(Print(e2.get()), "((2)*((3)+(4)))+(5) = 19"); ASSERT_EQUAL(Print(e1.get()), "Null expression provided"); } int main() { TestRunner tr; RUN_TEST(tr, Test); return 0; }
28.195402
108
0.622095
freeraisor
5c5ad90202e57f7f4315361e7a89f1e30522e2df
5,016
cc
C++
src/client_manager.cc
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
src/client_manager.cc
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
src/client_manager.cc
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
#include "client_manager.hh" #include "buffer_manager.hh" #include "color_registry.hh" #include "command_manager.hh" #include "event_manager.hh" #include "file.hh" #include "user_interface.hh" #include "window.hh" namespace Kakoune { ClientManager::ClientManager() = default; ClientManager::~ClientManager() = default; String ClientManager::generate_name() const { for (int i = 0; true; ++i) { String name = "unnamed" + to_string(i); if (validate_client_name(name)) return name; } } Client* ClientManager::create_client(std::unique_ptr<UserInterface>&& ui, const String& init_commands) { Buffer& buffer = **BufferManager::instance().begin(); WindowAndSelections ws = get_free_window(buffer); Client* client = new Client{std::move(ui), std::move(ws.window), std::move(ws.selections), generate_name()}; m_clients.emplace_back(client); try { CommandManager::instance().execute(init_commands, client->context()); } catch (Kakoune::runtime_error& error) { client->context().print_status({ error.what(), get_color("Error") }); client->context().hooks().run_hook("RuntimeError", error.what(), client->context()); } catch (Kakoune::client_removed&) { m_clients.pop_back(); return nullptr; } client->ui().set_input_callback([client, this]() { try { client->handle_available_input(); } catch (Kakoune::runtime_error& error) { client->context().print_status({ error.what(), get_color("Error") }); client->context().hooks().run_hook("RuntimeError", error.what(), client->context()); } catch (Kakoune::client_removed&) { ClientManager::instance().remove_client(*client); } }); return client; } void ClientManager::remove_client(Client& client) { for (auto it = m_clients.begin(); it != m_clients.end(); ++it) { if (it->get() == &client) { m_clients.erase(it); return; } } kak_assert(false); } WindowAndSelections ClientManager::get_free_window(Buffer& buffer) { for (auto it = m_free_windows.begin(), end = m_free_windows.end(); it != end; ++it) { auto& w = it->window; if (&w->buffer() == &buffer) { w->forget_timestamp(); WindowAndSelections res = std::move(*it); m_free_windows.erase(it); return res; } } return WindowAndSelections{ std::unique_ptr<Window>{new Window{buffer}}, DynamicSelectionList{buffer, { Selection{ {}, {} } } } }; } void ClientManager::add_free_window(std::unique_ptr<Window>&& window, SelectionList selections) { Buffer& buffer = window->buffer(); m_free_windows.push_back({ std::move(window), DynamicSelectionList{ buffer, std::move(selections) } }); } void ClientManager::ensure_no_client_uses_buffer(Buffer& buffer) { for (auto& client : m_clients) { client->context().forget_jumps_to_buffer(buffer); if (&client->context().buffer() != &buffer) continue; if (client->context().is_editing()) throw runtime_error("client '" + client->context().name() + "' is inserting in '" + buffer.display_name() + '\''); // change client context to edit the first buffer which is not the // specified one. As BufferManager stores buffer according to last // access, this selects a sensible buffer to display. for (auto& buf : BufferManager::instance()) { if (buf != &buffer) { client->context().change_buffer(*buf); break; } } } auto end = std::remove_if(m_free_windows.begin(), m_free_windows.end(), [&buffer](const WindowAndSelections& ws) { return &ws.window->buffer() == &buffer; }); m_free_windows.erase(end, m_free_windows.end()); } bool ClientManager::validate_client_name(const String& name) const { auto it = find_if(m_clients, [&](const std::unique_ptr<Client>& client) { return client->context().name() == name; }); return it == m_clients.end(); } Client* ClientManager::get_client_ifp(const String& name) { for (auto& client : m_clients) { if (client->context().name() == name) return client.get(); } return nullptr; } Client& ClientManager::get_client(const String& name) { Client* client = get_client_ifp(name); if (not client) throw runtime_error("no client named: " + name); return *client; } void ClientManager::redraw_clients() const { for (auto& client : m_clients) client->redraw_ifn(); } }
29.505882
134
0.578549
nojhan
5c6046bdf8d9756fe06c5e103bcc3792ca9c0d76
4,884
cpp
C++
src/wledctrl/wledctrl.cpp
Pliskin707/WLED_Trigger_ESP01
8ae8dfa9a0cab1ba4eea677ee5de725acd74289c
[ "MIT" ]
null
null
null
src/wledctrl/wledctrl.cpp
Pliskin707/WLED_Trigger_ESP01
8ae8dfa9a0cab1ba4eea677ee5de725acd74289c
[ "MIT" ]
null
null
null
src/wledctrl/wledctrl.cpp
Pliskin707/WLED_Trigger_ESP01
8ae8dfa9a0cab1ba4eea677ee5de725acd74289c
[ "MIT" ]
null
null
null
#include "wledctrl.hpp" namespace wledTrigger { enum LorOverrideType {off, untilLiveEnds, untilReboot}; wledControl::wledControl (const IPAddress &WLEDIP) { this->_url = "http://" + WLEDIP.toString() + "/json"; this->_initFilter(this->_filter); } wledControl::wledControl(const char * const WLEDIP) { this->_url = "http://" + String(WLEDIP) + "/json"; this->_initFilter(this->_filter); } void wledControl::_initFilter (StaticJsonDocument<256> &filter) { filter.clear(); // from "state" filter["on"] = true; filter["bri"] = true; filter["ps"] = true; filter["lor"] = true; // from "info" filter["live"] = true; } bool wledControl::updateStatus (void) { bool getStateSuccess = false, getInfoSuccess = false; int result; HTTPClient http; JsonVariant jVal; // temporary values (get saved if all requests are successful) bool isOn = false, isLive = false; int brightness = -1, liveDataOverride = -1, preset = -1; // client settings http.setTimeout(3000); http.useHTTP10(true); // this is required, so "deserializeJson()" can read the stream directly // get "state" data http.begin(this->_client, this->_url + "/state"); result = http.GET(); dprintf("GET state result: %d\n", result); if (result == 200) // == OK { DeserializationError error = deserializeJson(this->_doc, http.getStream(), DeserializationOption::Filter(this->_filter)); if (error) { dprintf("Deserialization failed: %s\n", error.c_str()); } else { do { jVal = this->_doc["on"]; if (jVal.is<bool>()) isOn = jVal.as<bool>(); else break; jVal = this->_doc["bri"]; if (jVal.is<int>()) brightness = jVal.as<int>(); else break; jVal = this->_doc["lor"]; if (jVal.is<int>()) liveDataOverride = jVal.as<int>(); else break; jVal = this->_doc["ps"]; if (jVal.is<int>()) preset = jVal.as<int>(); else break; getStateSuccess = true; } while (false); } } // get "info" data http.begin(this->_client, this->_url + "/info"); result = http.GET(); dprintf("GET info result: %d\n", result); if (result == 200) // == OK { DeserializationError error = deserializeJson(this->_doc, http.getStream(), DeserializationOption::Filter(this->_filter)); if (error) { dprintf("Deserialization failed: %s\n", error.c_str()); } else { do { jVal = this->_doc["live"]; if (jVal.is<bool>()) isLive = jVal.as<bool>(); else break; getInfoSuccess = true; } while (false); } } http.end(); // save values if (getStateSuccess && getInfoSuccess) { this->_isOn = isOn; this->_isLive = isLive; this->_brightness = brightness; // save the previously active preset so it can be restored later if (liveDataOverride == LorOverrideType::off) { dprintf("Saving actual settings: Preset = %d, Power = %s\n", preset, (isOn ? "ON":"OFF")); this->_preset = preset; this->_wasOn = isOn; } return true; } return false; } bool wledControl::setPreset (const int presetNumber) { auto &doc = this->_doc; doc.clear(); doc["on"] = true; // not required? always turns on doc["tt"] = 0; // transition time (for this call) doc["ps"] = presetNumber; doc["lor"] = LorOverrideType::untilLiveEnds; // live data override String json; serializeJson(doc, json); HTTPClient http; http.begin(this->_client, this->_url); const int result = http.POST(json); dprintf("POST response (%d): %s\n", result, http.getString().c_str()); return result == 200; } bool wledControl::resetLiveDataOverride (void) { auto &doc = this->_doc; doc.clear(); doc["lor"] = LorOverrideType::off; // live data override if ((this->_preset >= 0) && this->_wasOn) doc["ps"] = this->_preset; // restore doc["on"] = this->_wasOn || this->_isLive; String json; serializeJson(doc, json); HTTPClient http; http.begin(this->_client, this->_url); const int result = http.POST(json); dprintf("LOR reset response (%d): %s\n", result, http.getString().c_str()); return result == 200; } }
25.570681
129
0.525594
Pliskin707
5c66d915f1f87f0fe5271979b08f763d6a54e03c
1,895
cpp
C++
3DEngine/Math/Vector2.cpp
EricDDK/3DEngineEEE
cf7832e69ba03111d54093b1f797eaabab3455e1
[ "MIT" ]
5
2019-07-23T03:21:04.000Z
2020-08-28T09:09:08.000Z
3DEngine/Math/Vector2.cpp
EricDDK/3DEngineEEE
cf7832e69ba03111d54093b1f797eaabab3455e1
[ "MIT" ]
null
null
null
3DEngine/Math/Vector2.cpp
EricDDK/3DEngineEEE
cf7832e69ba03111d54093b1f797eaabab3455e1
[ "MIT" ]
3
2019-07-25T01:36:02.000Z
2020-02-15T08:11:19.000Z
#include "Math/Vector2.h" #include <cmath> #include "MathCommon.h" ENGINE_NAMESPACE_START Vector2::Vector2() { x = 0.0f; y = 0.0f; } Vector2::~Vector2() { } Vector2::Vector2(float tX, float tY) { x = tX; y = tY; } Vector2::Vector2(const Vector2& v) { set(v); } Vector2 Vector2::operator=(const Vector2& v) { set(v); return *this; } void Vector2::set(float tX, float tY) { x = tX; y = tY; } void Vector2::set(const Vector2& v) { x = v.x; y = v.y; } Vector2 Vector2::operator+(const Vector2& v) const { return Vector2(x + v.x, y + v.y); } Vector2 Vector2::operator-(const Vector2& v) const { return Vector2(x - v.x, y - v.y); } float Vector2::operator*(const Vector2& v) const { return x * v.x + y * v.y; } Vector2 Vector2::operator*(float scale) const { return Vector2(x * scale, y * scale); } Vector2 Vector2::operator+=(const Vector2& v) { x += v.x; y += v.y; return *this; } Vector2 Vector2::operator-=(const Vector2& v) { x -= v.x; y -= v.y; return *this; } Vector2 Vector2::operator*=(const Vector2& v) { x *= v.x; y *= v.y; return *this; } Vector2 Vector2::operator*=(float scale) { x *= scale; y *= scale; return *this; } bool Vector2::operator==(const Vector2& v) { return x == v.x && y == v.y; } bool Vector2::operator!=(const Vector2& v) { return !((*this) == v); } Vector2 Vector2::lerp(const Vector2& other, float alpha) const { return *this * (1.f - alpha) + other * alpha; } float Vector2::lengthSq() { return x * x + y * y; } float Vector2::length() { float n = x * x + y * y; return std::sqrt(n); } void Vector2::normalize() { float n = x * x + y * y; if (n == 1.0f) return; n = std::sqrt(n); if (n < MATH_TOLERANCE) return; n = 1.0f / n; x *= n; y *= n; } float Vector2::dot(const Vector2& a, const Vector2& b) { return (a.x * b.x + a.y * b.y); } const Vector2 Vector2::Zero(0.0f ,0.0f); ENGINE_NAMESPACE_END
13.439716
62
0.605805
EricDDK
5c67372d7b5d998a9a48a0cad154c5510025ef95
2,168
cpp
C++
game/server/entities/CRotButton.cpp
sohl-modders/SOHLEnhanced
71358d28bf65ba600f268368d2e4521c4158da72
[ "Unlicense" ]
null
null
null
game/server/entities/CRotButton.cpp
sohl-modders/SOHLEnhanced
71358d28bf65ba600f268368d2e4521c4158da72
[ "Unlicense" ]
null
null
null
game/server/entities/CRotButton.cpp
sohl-modders/SOHLEnhanced
71358d28bf65ba600f268368d2e4521c4158da72
[ "Unlicense" ]
null
null
null
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "entities/DoorConstants.h" #include "CBaseButton.h" #include "CRotButton.h" LINK_ENTITY_TO_CLASS( func_rot_button, CRotButton ); void CRotButton::Spawn( void ) { const char* pszSound; //---------------------------------------------------- //determine sounds for buttons //a sound of 0 should not make a sound //---------------------------------------------------- pszSound = ButtonSound( m_sounds ); PrecacheSound( pszSound ); pev->noise = ALLOC_STRING( pszSound ); // set the axis of rotation CBaseToggle::AxisDir( this ); // check for clockwise rotation if( GetSpawnFlags().Any( SF_DOOR_ROTATE_BACKWARDS ) ) SetMoveDir( GetMoveDir() * -1 ); SetMoveType( MOVETYPE_PUSH ); if( GetSpawnFlags().Any( SF_ROTBUTTON_NOTSOLID ) ) SetSolidType( SOLID_NOT ); else SetSolidType( SOLID_BSP ); SetModel( GetModelName() ); if( GetSpeed() == 0 ) SetSpeed( 40 ); if( m_flWait == 0 ) m_flWait = 1; if( GetHealth() > 0 ) { SetTakeDamageMode( DAMAGE_YES ); } m_toggle_state = TS_AT_BOTTOM; m_vecAngle1 = GetAbsAngles(); m_vecAngle2 = GetAbsAngles() + GetMoveDir() * m_flMoveDistance; ASSERTSZ( m_vecAngle1 != m_vecAngle2, "rotating button start/end positions are equal" ); m_fStayPushed = m_flWait == -1; m_fRotating = true; // if the button is flagged for USE button activation only, take away it's touch function and add a use function if( !GetSpawnFlags().Any( SF_BUTTON_TOUCH_ONLY ) ) { SetTouch( NULL ); SetUse( &CRotButton::ButtonUse ); } else // touchable button SetTouch( &CRotButton::ButtonTouch ); //SetTouch( ButtonTouch ); }
26.765432
113
0.678967
sohl-modders
5c687d6802fd46de7aba340671ede5ff3cbb43b2
2,520
cpp
C++
src/main.cpp
juliantorreno/opengl-demo
c199c487907833e52ff5c3083aed51956e6ac693
[ "MIT" ]
2
2018-01-06T19:27:07.000Z
2018-10-11T07:07:10.000Z
src/main.cpp
jtorreno/opengl-demo
c199c487907833e52ff5c3083aed51956e6ac693
[ "MIT" ]
8
2018-01-03T13:45:25.000Z
2018-01-08T01:35:49.000Z
src/main.cpp
juliantorreno/opengl-demo
c199c487907833e52ff5c3083aed51956e6ac693
[ "MIT" ]
null
null
null
#include "camera.hpp" #include "glsl_program.hpp" #include "renderer.hpp" #include "shader.hpp" #include "model.hpp" #include "texture.hpp" #include "window.hpp" #include <GLFW/glfw3.h> struct point { double x, y; }; point operator-(point const& lhs, point const& rhs) { return { lhs.x - rhs.x, lhs.y - rhs.y }; } point mouse_position(GLFWwindow* window) { double x, y; glfwGetCursorPos(window, &x, &y); return {x, y}; } point mouse_delta(GLFWwindow* window) { static point last_pos = mouse_position(window); point pos = mouse_position(window); point delta = last_pos - pos; last_pos = pos; return delta; } auto main() -> int { ogld::window window("opengl-demo", 1600_px * 900_px); ogld::renderer<ogld::model> renderer; ogld::model cube{ogld::obj_mesh("../opengl-demo/res/models/cube.obj"), {ogld::texture()}, {0, 0, 0}}; ogld::model suzanne{ogld::obj_mesh("../opengl-demo/res/models/suzanne.obj"), {ogld::texture("../opengl-demo/res/textures/white.png")}, {0, 3, 0}}; renderer.render_list.push_back(cube); renderer.render_list.push_back(suzanne); glm::vec3 position{0, 4, 4}; ogld::camera camera(position, {0, 2, 0}, 60, {0, 1, 0}); float horizontal_angle = 3.14159; float vertical_angle = 0; while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS) { double start = glfwGetTime(); renderer(camera); window.refresh(); float elapsed_time = glfwGetTime() - start; auto delta = mouse_delta(window); horizontal_angle += 0.005 * delta.x; vertical_angle += 0.005 * delta.y; glm::vec3 direction{std::cos(vertical_angle) * std::sin(horizontal_angle), std::sin(vertical_angle), std::cos(vertical_angle) * std::cos(horizontal_angle)}; glm::vec3 right{std::sin(horizontal_angle - 3.14159 / 2.0), 0, std::cos(horizontal_angle - 3.14159 / 2.0)}; glm::vec3 up = glm::cross(right, direction); auto const sensitivity = 5.f; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { position += direction * elapsed_time * sensitivity; } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { position -= direction * elapsed_time * sensitivity; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { position += right * elapsed_time * sensitivity; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { position -= right * elapsed_time * sensitivity; } camera.update(position, position + direction, 60, up); } }
33.157895
164
0.649603
juliantorreno
5c70e39e1f090db7df01f608d5ac5b81574e75b0
1,482
cpp
C++
LeetCode/ThousandTwo/1040-move_stone_until_consecutive_2.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1040-move_stone_until_consecutive_2.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1040-move_stone_until_consecutive_2.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 1040. 移动石子直到连续 II 在一个长度无限的数轴上,第 i 颗石子的位置为 stones[i]。 如果一颗石子的位置最小/最大,那么该石子被称作端点石子。 每个回合,你可以将一颗端点石子拿起并移动到一个未占用的位置,使得该石子不再是一颗端点石子。 值得注意的是,如果石子像 stones = [1,2,5] 这样,你将无法移动位于位置 5 的端点石子,因为无论将它移动到任何位置(例如 0 或 3),该石子都仍然会是端点石子。 当你无法进行任何移动时,即,这些石子的位置连续时,游戏结束。 要使游戏结束,你可以执行的最小和最大移动次数分别是多少? 以长度为 2 的数组形式返回答案:answer = [minimum_moves, maximum_moves] 。 示例 1: 输入:[7,4,9] 输出:[1,2] 解释: 我们可以移动一次,4 -> 8,游戏结束。 或者,我们可以移动两次 9 -> 5,4 -> 6,游戏结束。 示例 2: 输入:[6,5,4,3,10] 输出:[2,3] 解释: 我们可以移动 3 -> 8,接着是 10 -> 7,游戏结束。 或者,我们可以移动 3 -> 7, 4 -> 8, 5 -> 9,游戏结束。 注意,我们无法进行 10 -> 2 这样的移动来结束游戏,因为这是不合要求的移动。 示例 3: 输入:[100,101,104,102,103] 输出:[0,0] 提示: 3 <= stones.length <= 10^4 1 <= stones[i] <= 10^9 stones[i] 的值各不相同。 */ // https://leetcode.com/problems/moving-stones-until-consecutive-ii/discuss/289357/c%2B%2B-with-picture // 抄的 vector<int> numMovesStonesII(vector<int>& A) { int n = static_cast<int>(A.size()); sort(A.begin(), A.end()); int hi = max(A[n - 1] - A[1] - n + 2, A[n - 2] - A[0] - n + 2); int lo = n; for (int i = 0, k = 0; k < n; ++k) { while (A[k] - A[i] + 1 > n) ++i; int store = k - i + 1; if (store == n - 1 && A[k] - A[i] == n - 2) lo = min(lo, 2); else lo = min(lo, n - store); } return vector<int>{ lo, hi }; } int main() { vector<int> a = { 7, 4, 9 }, b = { 6, 5, 4, 3, 10 }, c = { 100, 101, 104, 102, 103 }; output(numMovesStonesII(a), "%d"); output(numMovesStonesII(b), "%d"); output(numMovesStonesII(c), "%d"); }
20.027027
103
0.596491
Ginkgo-Biloba
5c72b398c85525339d8b14cee2c4ab31ef4f225a
5,746
cpp
C++
src/tv_inpainting_app/main_tv_inpainting.cpp
shilinjupt/22
f4d885ffacacbb5c131d008c193ebec8b80cfb64
[ "BSD-3-Clause" ]
18
2015-01-14T23:06:15.000Z
2021-06-09T15:18:07.000Z
src/tv_inpainting_app/main_tv_inpainting.cpp
shilinjupt/22
f4d885ffacacbb5c131d008c193ebec8b80cfb64
[ "BSD-3-Clause" ]
null
null
null
src/tv_inpainting_app/main_tv_inpainting.cpp
shilinjupt/22
f4d885ffacacbb5c131d008c193ebec8b80cfb64
[ "BSD-3-Clause" ]
3
2015-03-05T20:39:08.000Z
2019-09-04T11:55:43.000Z
// Copyright (c) 2012 D'ANGELO Emmanuel // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list of conditions // and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its contributors may be used // to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <CDS.hpp> #include <iostream> #include <string> #include <unistd.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cds; int main(int argc, char * const argv[]) { if (argc < 2) { std::cerr << "Missing image!\n"; std::cerr << "Usage: " << argv[0] << "[-d -i iterations] anImage\n"; return EXIT_FAILURE; } int iterations = 100; bool use_diffusion = false; bool separate_windows = false; int option; while ((option = getopt(argc, argv, "di:s")) != -1) { switch (option) { case 'd': use_diffusion = true; break; case 'i': iterations = atoi(optarg); break; case 's': separate_windows = true; break; default: break; } } // Read an image from the command line cv::Mat inputImage = cv::imread(argv[argc-1], 0); if (!inputImage.data) { std::cerr << "Error reading: " << argv[argc-1] << "\n"; return EXIT_FAILURE; } cv::Mat inputImage32; inputImage.convertTo(inputImage32, CV_32F, 1.0/255.0); cv::Size frameSize = inputImage.size(); // Generate various masks std::cout << "Generating masks...\n"; std::vector<cv::Mat> masks; cv::Mat randomMask50; CreateRandomMask(frameSize, 0.5, randomMask50); masks.push_back(randomMask50); cv::Mat randomMask90; CreateRandomMask(frameSize, 0.9, randomMask90); masks.push_back(randomMask90); cv::Mat rowMask; CreateInterleavedRowsMask(frameSize, rowMask); masks.push_back(rowMask); cv::Rect rectangle; float npix = 0.5*inputImage.size().area(); npix = std::sqrt(npix); int radius = (int)std::floor(npix); rectangle = cv::Rect(MAX(0, (inputImage.cols-radius)/2), MAX(0, (inputImage.rows-radius)/2), MIN(radius, (inputImage.cols-radius)/2), MIN(radius, (inputImage.rows-radius)/2)); cv::Mat rectMask; CreateRectangularMask(frameSize, rectangle, rectMask); masks.push_back(rectMask); // Generate the corresponding masked images std::cout << "Masking images...\n"; std::vector<cv::Mat> maskedInputs(masks.size()); for (int i = 0; i < masks.size(); ++i) { cv::multiply(inputImage32, masks[i], maskedInputs[i]); } // For each image, reconstruct it std::cout << "Reconstruction...\n"; std::vector<cv::Mat> reconstructionResults(masks.size()); for (int i = 0; i < masks.size(); ++i) { // Diffuse if (use_diffusion) { TvDiffusion(maskedInputs[i], reconstructionResults[i], iterations, 10); } else { TvInpainting(maskedInputs[i], masks[i], reconstructionResults[i], iterations); } } // SNR measures std::vector<double> snr_before; std::vector<double> snr_after; for (int i = 0; i < maskedInputs.size(); ++i) { snr_before.push_back(cds::SNR(maskedInputs[i], inputImage32)); snr_after.push_back(cds::SNR(reconstructionResults[i], inputImage32)); } // OK, time for show off ! std::cout << "All done, displaying...\n"; for (int i = 0; i < maskedInputs.size(); ++i) { std::cout << "Masked SNR = " << snr_before[i]; std::cout << "\tReconstruction SNR = " << snr_after[i]; std::cout << std::endl; } if (separate_windows == false) { cv::Mat composite; ComposeSidebySide(maskedInputs[0], reconstructionResults[0], composite); RescaleAndDisplay(composite, "Random 50"); ComposeSidebySide(maskedInputs[1], reconstructionResults[1], composite); RescaleAndDisplay(composite, "Random 90"); ComposeSidebySide(maskedInputs[2], reconstructionResults[2], composite); RescaleAndDisplay(composite, "Lines"); ComposeSidebySide(maskedInputs[3], reconstructionResults[3], composite); RescaleAndDisplay(composite, "Rectangle mask"); } else { RescaleAndDisplay(maskedInputs[0], "Random 50"); RescaleAndDisplay(reconstructionResults[0], "Inpainting 50"); RescaleAndDisplay(maskedInputs[1], "Random 90"); RescaleAndDisplay(reconstructionResults[1], "Inpainting 90"); RescaleAndDisplay(maskedInputs[2], "Lines"); RescaleAndDisplay(reconstructionResults[2], "Lines-Inpainted"); RescaleAndDisplay(maskedInputs[3], "Rectangle mask"); RescaleAndDisplay(reconstructionResults[3], "Rectangle Inpainting"); } // Wait std::cout << "All done. Press a key to exit!\n"; cv::waitKey(); // Exit return EXIT_SUCCESS; }
30.402116
109
0.707623
shilinjupt
f07721fcfc9b484bd457ec638f60979a85d61101
5,240
cpp
C++
rmw_opendds_cpp/src/rmw_subscription.cpp
adamsj-oci/rmw_opendds
444f32cfc7730150fa6ad353ac1a2bbd23597cc0
[ "Apache-2.0" ]
7
2019-06-29T09:39:31.000Z
2021-06-23T03:20:06.000Z
rmw_opendds_cpp/src/rmw_subscription.cpp
adamsj-oci/rmw_opendds
444f32cfc7730150fa6ad353ac1a2bbd23597cc0
[ "Apache-2.0" ]
33
2018-12-14T10:49:42.000Z
2021-05-26T16:09:53.000Z
rmw_opendds_cpp/src/rmw_subscription.cpp
adamsj-oci/rmw_opendds
444f32cfc7730150fa6ad353ac1a2bbd23597cc0
[ "Apache-2.0" ]
16
2019-06-29T09:39:39.000Z
2020-05-29T20:18:39.000Z
// Copyright 2014-2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <rmw_opendds_cpp/DDSSubscriber.hpp> #include <rmw_opendds_cpp/OpenDDSNode.hpp> #include <rmw_opendds_cpp/identifier.hpp> #include <rmw_opendds_cpp/qos.hpp> #include <rmw_opendds_cpp/types.hpp> // Uncomment this to get extra console output about discovery. // #define DISCOVERY_DEBUG_LOGGING 1 #include <dds/DCPS/DataReaderImpl_T.h> #include <dds/DCPS/DomainParticipantImpl.h> #include <dds/DCPS/Marked_Default_Qos.h> #include <rmw/allocators.h> #include <rmw/error_handling.h> #include <rmw/impl/cpp/macros.hpp> #include <rmw/rmw.h> #include <string> extern "C" { rmw_ret_t rmw_init_subscription_allocation( const rosidl_message_type_support_t * type_support, const rosidl_runtime_c__Sequence__bound * message_bounds, rmw_subscription_allocation_t * allocation) { // Unused in current implementation. (void) type_support; (void) message_bounds; (void) allocation; RMW_SET_ERROR_MSG("unimplemented"); return RMW_RET_ERROR; } rmw_ret_t rmw_fini_subscription_allocation(rmw_subscription_allocation_t * allocation) { // Unused in current implementation. (void) allocation; RMW_SET_ERROR_MSG("unimplemented"); return RMW_RET_ERROR; } void clean_subscription(rmw_subscription_t * subscription) { if (subscription) { auto dds_subscriber = static_cast<DDSSubscriber*>(subscription->data); if (dds_subscriber) { DDSSubscriber::Raf::destroy(dds_subscriber); subscription->data = nullptr; } rmw_subscription_free(subscription); } } rmw_subscription_t * create_initial_subscription(const rmw_subscription_options_t * subscription_options) { rmw_subscription_t * subscription = rmw_subscription_allocate(); if (!subscription) { throw std::runtime_error("failed to allocate subscription"); } subscription->implementation_identifier = opendds_identifier; subscription->data = nullptr; subscription->topic_name = nullptr; if (subscription_options) { subscription->options = *subscription_options; } else { subscription->options.rmw_specific_subscription_payload = nullptr; subscription->options.ignore_local_publications = false; } subscription->can_loan_messages = false; return subscription; } rmw_subscription_t * rmw_create_subscription( const rmw_node_t * node, const rosidl_message_type_support_t * type_supports, const char * topic_name, const rmw_qos_profile_t * rmw_qos, const rmw_subscription_options_t * subscription_options) { auto dds_node = OpenDDSNode::from(node); if (!dds_node) { return nullptr; // error set } rmw_subscription_t * subscription = nullptr; try { subscription = create_initial_subscription(subscription_options); auto dds_sub = DDSSubscriber::Raf::create(dds_node->dp(), type_supports, topic_name, rmw_qos); if (!dds_sub) { throw std::runtime_error("DDSSubscriber failed"); } subscription->data = dds_sub; subscription->topic_name = dds_sub->topic_name().c_str(); dds_node->add_sub(dds_sub->instance_handle(), dds_sub->topic_name(), dds_sub->topic_type()); return subscription; } catch (const std::exception& e) { RMW_SET_ERROR_MSG(e.what()); } catch (...) { RMW_SET_ERROR_MSG("rmw_create_subscription failed"); } clean_subscription(subscription); return nullptr; } rmw_ret_t rmw_subscription_count_matched_publishers( const rmw_subscription_t * subscription, size_t * publisher_count) { if (!publisher_count) { RMW_SET_ERROR_MSG("publisher_count is null"); return RMW_RET_INVALID_ARGUMENT; } auto dds_sub = DDSSubscriber::from(subscription); if (dds_sub) { *publisher_count = dds_sub->matched_publishers(); return RMW_RET_OK; } return RMW_RET_ERROR; } rmw_ret_t rmw_subscription_get_actual_qos( const rmw_subscription_t * subscription, rmw_qos_profile_t * qos) { if (!qos) { RMW_SET_ERROR_MSG("qos is null"); return RMW_RET_INVALID_ARGUMENT; } auto dds_sub = DDSSubscriber::from(subscription); return dds_sub ? dds_sub->get_rmw_qos(*qos) : RMW_RET_ERROR; } rmw_ret_t rmw_destroy_subscription(rmw_node_t * node, rmw_subscription_t * subscription) { auto dds_node = OpenDDSNode::from(node); if (!dds_node) { return RMW_RET_ERROR; // error set } if (!dds_node->dp()) { RMW_SET_ERROR_MSG("DomainParticipant is null"); return RMW_RET_ERROR; } auto dds_sub = DDSSubscriber::from(subscription); if (!dds_sub) { return RMW_RET_ERROR; // error set } bool ret = dds_node->remove_sub(dds_sub->instance_handle()); if (ret) { clean_subscription(subscription); } return ret ? RMW_RET_OK : RMW_RET_ERROR; } } // extern "C"
29.772727
105
0.749427
adamsj-oci
f079621991da03cb60ccdc57af99f2086abf17c1
4,121
cpp
C++
source/GrassShader.cpp
Tomash667/carpglib
c8701b170e4e2cbdb4d52fe3b7c8529afb3e97ed
[ "MIT" ]
4
2019-08-18T19:33:04.000Z
2021-08-07T02:12:54.000Z
source/GrassShader.cpp
Tomash667/carpglib
c8701b170e4e2cbdb4d52fe3b7c8529afb3e97ed
[ "MIT" ]
5
2019-08-14T05:45:56.000Z
2021-03-15T07:47:24.000Z
source/GrassShader.cpp
Tomash667/carpglib
c8701b170e4e2cbdb4d52fe3b7c8529afb3e97ed
[ "MIT" ]
2
2019-10-05T02:36:35.000Z
2021-02-15T20:20:09.000Z
#include "Pch.h" #include "GrassShader.h" #include "Camera.h" #include "DirectX.h" #include "Mesh.h" #include "Render.h" #include "Scene.h" #include "SceneManager.h" struct VsGlobals { Matrix matViewProj; }; struct PsGlobals { Vec4 fogColor; Vec4 fogParams; Vec4 ambientColor; }; //================================================================================================= GrassShader::GrassShader() : deviceContext(app::render->GetDeviceContext()), vertexShader(nullptr), pixelShader(nullptr), layout(nullptr), vsGlobals(nullptr), psGlobals(nullptr), vb(nullptr), vbSize(0) { } //================================================================================================= void GrassShader::OnInit() { Render::ShaderParams params; params.name = "grass"; params.decl = VDI_GRASS; params.vertexShader = &vertexShader; params.pixelShader = &pixelShader; params.layout = &layout; app::render->CreateShader(params); vsGlobals = app::render->CreateConstantBuffer(sizeof(VsGlobals)); psGlobals = app::render->CreateConstantBuffer(sizeof(PsGlobals)); } //================================================================================================= void GrassShader::OnRelease() { SafeRelease(vertexShader); SafeRelease(pixelShader); SafeRelease(layout); SafeRelease(vsGlobals); SafeRelease(psGlobals); SafeRelease(vb); vbSize = 0; } //================================================================================================= void GrassShader::Prepare(Scene* scene, Camera* camera) { assert(scene && camera); app::render->SetBlendState(Render::BLEND_NO); app::render->SetDepthState(Render::DEPTH_YES); app::render->SetRasterState(Render::RASTER_NO_CULLING); deviceContext->VSSetShader(vertexShader, nullptr, 0); deviceContext->VSSetConstantBuffers(0, 1, &vsGlobals); deviceContext->PSSetShader(pixelShader, nullptr, 0); deviceContext->PSSetConstantBuffers(0, 1, &psGlobals); ID3D11SamplerState* sampler = app::render->GetSampler(); deviceContext->PSSetSamplers(0, 1, &sampler); deviceContext->IASetInputLayout(layout); // set matrix { ResourceLock lock(vsGlobals); VsGlobals& vsg = *lock.Get<VsGlobals>(); vsg.matViewProj = camera->mat_view_proj.Transpose(); } // set pixel shader globals { ResourceLock lock(psGlobals); PsGlobals& psg = *lock.Get<PsGlobals>(); psg.ambientColor = scene->GetAmbientColor(); psg.fogColor = scene->GetFogColor(); psg.fogParams = scene->GetFogParams(); } } //================================================================================================= void GrassShader::ReserveVertexBuffer(uint vertexCount) { if(vertexCount <= vbSize) return; SafeRelease(vb); vbSize = vertexCount; D3D11_BUFFER_DESC desc = {}; desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = sizeof(Matrix) * vertexCount; desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; V(app::render->GetDevice()->CreateBuffer(&desc, nullptr, &vb)); SetDebugName(vb, "GrassVb"); } //================================================================================================= void GrassShader::Draw(Mesh* mesh, const vector<const vector<Matrix>*>& patches, uint count) { assert(mesh->vertex_decl == VDI_DEFAULT); ReserveVertexBuffer(count); ID3D11Buffer* vbs[2] = { mesh->vb, vb }; uint size[2] = { sizeof(VDefault), sizeof(Matrix) }; uint offset[2] = { 0, 0 }; deviceContext->IASetInputLayout(layout); deviceContext->IASetVertexBuffers(0, 2, vbs, size, offset); deviceContext->IASetIndexBuffer(mesh->ib, DXGI_FORMAT_R16_UINT, 0); // setup instancing data { ResourceLock lock(vb); Matrix* m = lock.Get<Matrix>(); int index = 0; for(vector< const vector<Matrix>* >::const_iterator it = patches.begin(), end = patches.end(); it != end; ++it) { const vector<Matrix>& vm = **it; memcpy(&m[index], &vm[0], sizeof(Matrix) * vm.size()); index += vm.size(); } } // draw for(Mesh::Submesh& sub : mesh->subs) { deviceContext->PSSetShaderResources(0, 1, &sub.tex->tex); deviceContext->DrawIndexedInstanced(sub.tris * 3, count, sub.first * 3, 0, 0); } }
28.818182
138
0.61587
Tomash667
f07c2afe96a5b8c9f5427a67ff1abfa0f98316dd
3,600
cpp
C++
curves/hermiteinterp.cpp
kujenga/curves
03857442c7b200a9206f6cfaadeb648047e578fe
[ "MIT" ]
1
2020-09-30T07:18:44.000Z
2020-09-30T07:18:44.000Z
curves/hermiteinterp.cpp
kujenga/curves
03857442c7b200a9206f6cfaadeb648047e578fe
[ "MIT" ]
null
null
null
curves/hermiteinterp.cpp
kujenga/curves
03857442c7b200a9206f6cfaadeb648047e578fe
[ "MIT" ]
null
null
null
// // hermiteinterp.cpp // curves // // Created by Aaron Taylor on 10/12/14. // Copyright (c) 2014 Aaron Taylor. All rights reserved. // #include "hermiteinterp.h" void HermiteInterp::addControlPoint(float2 newPoint) { controlPoints.push_back(newPoint); controlPoints.push_back(float2(0.2,0.2)); } void HermiteInterp::drawControlPointTangents() { // draw tangent points and lines to them int siz = (int)controlPoints.size(); for (int i = 0; i < siz; i+=2) { float2 curP = controlPoints.at(i); float2 curT = controlPoints.at(i+1) + curP; glBegin(GL_LINE_STRIP); glLineWidth(0.1); glVertex2d(curP.x, curP.y); glVertex2d(curT.x, curT.y); glEnd(); } } void HermiteInterp::drawControlPoints() { glPushMatrix(); performTransformations(); // inverse of line colors for markers if (selected) { glColor3d(1.0-selectedColor.r, 1.0-selectedColor.g, 1.0-selectedColor.b); } else { glColor3d(1.0-lineColor.r, 1.0-lineColor.g, 1.0-lineColor.b); } drawControlPointTangents(); // draw points at control points int siz = (int)controlPoints.size(); float2 last; for (int i = 0; i < siz; i++) { glBegin(GL_POLYGON); // inverse of line colors for markers if (selected) { glColor3d(1.0-selectedColor.r, 1.0-selectedColor.g, 1.0-selectedColor.b); } else { glColor3d(1.0-lineColor.r, 1.0-lineColor.g, 1.0-lineColor.b); } float2 cur = controlPoints.at(i); // tangent points are at odd indicies, move them if so if (i%2 != 0) { glColor3d(1.0, 0.0, 0.0); cur += last; } glVertex2d(cur.x - TRACKER_SIZE, cur.y); glVertex2d(cur.x, cur.y + TRACKER_SIZE); glVertex2d(cur.x + TRACKER_SIZE, cur.y); glVertex2d(cur.x, cur.y - TRACKER_SIZE); glEnd(); last = cur; } glPopMatrix(); } int HermiteInterp::currentControlPoint(float2 test) { float2 last; for (int i = 0; i < controlPoints.size(); i++) { float2 cur = controlPoints.at(i); // tangent points are at odd indicies, move them if so if (i%2 != 0) { cur += last; } if (pointMatch(cur, test)) { return i; } last = cur; } return -1; } void HermiteInterp::moveControlPoint(int i, float2 pos) { // adjusts tangent points if (i%2 != 0) { pos -= controlPointVectorElement(i-1); } Freeform::moveControlPoint(i, pos); } float2 cubicHermiteSplineFunc(float t, float2 p0, float2 m0, float2 p1, float2 m1) { float h00 = 2.0*t*t*t - 3.0*t*t + 1.0; float h10 = t*t*t - 2.0*t*t + t; float h01 = -2.0*t*t*t + 3.0*t*t; float h11 = t*t*t - t*t; return p0*h00 + m0*h10*5 + p1*h01 + m1*h11*3; } float2 HermiteInterp::getPoint(float t) { if (controlPointVectorSize() < 4) { return controlPoints.at(0); } float numPoints = (float)controlPointVectorSize(); float numEdges = numPoints/2-1; int curPoint = 2*(int)floorf(t * numEdges); float2 p0 = controlPointVectorElement(curPoint); float2 m0 = controlPointVectorElement(curPoint+1); float2 p1 = controlPointVectorElement(curPoint+2); float2 m1 = controlPointVectorElement(curPoint+3); // scale t to the current subdivision float ts = t*numEdges-(float)curPoint/2; return cubicHermiteSplineFunc(ts, p0, m0, p1, m1); } float2 HermiteInterp::getDerivative(float t) { return float2(); }
27.272727
85
0.598333
kujenga
f07c7f0c9b9e5ce25fe9c3ec63e8e21e1c4a2548
1,570
cpp
C++
src/double.cpp
geofflangdale/scans
f64b5b4f895803df792ab9f589f3f90b731c32bb
[ "BSD-3-Clause" ]
3
2018-06-19T06:43:42.000Z
2021-07-16T04:44:58.000Z
src/double.cpp
geofflangdale/scans
f64b5b4f895803df792ab9f589f3f90b731c32bb
[ "BSD-3-Clause" ]
null
null
null
src/double.cpp
geofflangdale/scans
f64b5b4f895803df792ab9f589f3f90b731c32bb
[ "BSD-3-Clause" ]
null
null
null
#include <memory> #include <set> #include "scans.h" #include "double.h" #include "vermicelli.h" #include "shufti.h" #include "truffle.h" using namespace std; // note: we could make all 9 variations here, but the other 4 aren't that interesting typedef DoubleMatcher<Vermicelli, &Vermicelli::vermicelli_op, Vermicelli, &Vermicelli::vermicelli_op> DVerm; typedef DoubleMatcher<Shufti, &Shufti::shufti_op, Shufti, &Shufti::shufti_op> DShufti; typedef DoubleMatcher<Truffle, &Truffle::truffle_op, Truffle, &Truffle::truffle_op> DTruffle; typedef DoubleMatcher<Shufti, &Shufti::shufti_op, Vermicelli, &Vermicelli::vermicelli_op> ShufVerm; typedef DoubleMatcher<Vermicelli, &Vermicelli::vermicelli_op, Shufti, &Shufti::shufti_op> VermShuf; std::unique_ptr<WrapperBase> get_wrapper_dverm(const DoubleCharsetWorkload & in) { return make_unique<Wrapper<DVerm>>(DVerm(in)); } std::unique_ptr<WrapperBase> get_wrapper_dshufti(const DoubleCharsetWorkload & in) { return make_unique<Wrapper<DShufti>>(DShufti(in)); } std::unique_ptr<WrapperBase> get_wrapper_dtruffle(const DoubleCharsetWorkload & in) { return make_unique<Wrapper<DTruffle>>(DTruffle(in)); } std::unique_ptr<WrapperBase> get_wrapper_shufverm(const DoubleCharsetWorkload & in) { return make_unique<Wrapper<ShufVerm>>(ShufVerm(in)); } std::unique_ptr<WrapperBase> get_wrapper_vermshuf(const DoubleCharsetWorkload & in) { return make_unique<Wrapper<VermShuf>>(VermShuf(in)); }
32.708333
85
0.724204
geofflangdale
f07fc86a8cc083aee778b32c3e1ff46e5075124f
602
cpp
C++
LeetCode/findAllDuplicates.cpp
hardiksinghnegi/PracticeSnippets
a34c44e9f824630a2a4865d094e1d6ee33ef65ad
[ "Apache-2.0" ]
null
null
null
LeetCode/findAllDuplicates.cpp
hardiksinghnegi/PracticeSnippets
a34c44e9f824630a2a4865d094e1d6ee33ef65ad
[ "Apache-2.0" ]
null
null
null
LeetCode/findAllDuplicates.cpp
hardiksinghnegi/PracticeSnippets
a34c44e9f824630a2a4865d094e1d6ee33ef65ad
[ "Apache-2.0" ]
null
null
null
static int __ = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }(); class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> dupVal; int inpSize = nums.size(); if(nums.size()<2){ return dupVal; } for(int i=0;i<nums.size();++i){ if(nums[abs(nums[i])-1] <0){ dupVal.push_back(abs(nums[i])); } else{ nums[abs(nums[i])-1] *=-1; } } return dupVal; } };
20.758621
51
0.423588
hardiksinghnegi
f084c3cb4fde6402a96f67ee4b85a645dca08be4
413
cpp
C++
03_vectors/main.cpp
acc-cosc-1337-spring-2019/midterm-spring-2019-hillarywyatt
8e7a30f3c89a3a3247424955c4c4c6eeb5760ed7
[ "MIT" ]
null
null
null
03_vectors/main.cpp
acc-cosc-1337-spring-2019/midterm-spring-2019-hillarywyatt
8e7a30f3c89a3a3247424955c4c4c6eeb5760ed7
[ "MIT" ]
null
null
null
03_vectors/main.cpp
acc-cosc-1337-spring-2019/midterm-spring-2019-hillarywyatt
8e7a30f3c89a3a3247424955c4c4c6eeb5760ed7
[ "MIT" ]
null
null
null
#include "dna_consensus.h" #include <iostream> int main() { vector <string> rosalind = { "ATCCAGCT", "GGGCAACT", "ATGGATCT", "AAGCAACC", "TTGGAACT", "ATGCCATT", "ATGGCACT" }; vector <int> number_sequences = most_common_letter(rosalind); vector <string> consensus = dna_consensus(number_sequences); std::cout << "DNA Consensus of Rosalind: "; for (auto c : consensus) { std::cout << c; } }
19.666667
67
0.663438
acc-cosc-1337-spring-2019
f085bf13250c88c16bc5ae6a50def1856f7bd431
981
cpp
C++
src/rgb.cpp
Agata-Les/rgb-hsv-fantastic-converter
e1e9c8181f2fd2aada98f73f180b5b196c78a234
[ "Apache-2.0" ]
1
2018-07-16T20:15:44.000Z
2018-07-16T20:15:44.000Z
src/rgb.cpp
Agata-Les/rgb-hsv-fantastic-converter
e1e9c8181f2fd2aada98f73f180b5b196c78a234
[ "Apache-2.0" ]
2
2018-07-17T18:04:56.000Z
2018-08-17T18:53:01.000Z
src/rgb.cpp
Agata-Les/rgb-hsv-fantastic-converter
e1e9c8181f2fd2aada98f73f180b5b196c78a234
[ "Apache-2.0" ]
null
null
null
#include "rgb.h" #include <algorithm> bool RGB::operator ==(const RGB & rhs) const { return this->Red == rhs.Red && this->Green == rhs.Green && this->Blue == rhs.Blue; } bool RGB::operator !=(const RGB & rhs) const { return this->Red != rhs.Red || this->Green != rhs.Green || this->Blue != rhs.Blue; } std::ostream & operator <<(std::ostream & stream, const RGB & rgbColour) { return stream<<"{ "<<rgbColour.Red<<", "<<rgbColour.Green<<", "<<rgbColour.Blue<<" }"; } unsigned short int RGB::calculateMin() { return std::min(std::min(Red, Blue), Green); } unsigned short int RGB::calculateMax() { return std::max(std::max(Red, Blue), Green); } const unsigned short int RGB::getRed() const { return Red; } const unsigned short int RGB::getGreen() const { return Green; } const unsigned short int RGB::getBlue() const { return Blue; } const unsigned short int RGB::getMax() const { return maximum; } const unsigned short int RGB::getMin() const { return minimum; }
18.509434
87
0.66157
Agata-Les
f0931297ce43191e1d8ca35aec82f5f834cc411a
4,093
cpp
C++
steel/Source/Steel/Application.cpp
samstalhandske/steel
6b501515c619b4a127884da88a4e53c1419727dd
[ "Apache-2.0" ]
null
null
null
steel/Source/Steel/Application.cpp
samstalhandske/steel
6b501515c619b4a127884da88a4e53c1419727dd
[ "Apache-2.0" ]
null
null
null
steel/Source/Steel/Application.cpp
samstalhandske/steel
6b501515c619b4a127884da88a4e53c1419727dd
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "Application.hpp" #include "Steel/Debug/Log.hpp" #include <glad/glad.h> #include "Input.hpp" namespace Steel { Application* Application::myInstance = nullptr; static GLenum ShaderDataTypeToOpenGLBaseType(ShaderDataType aType) { switch (aType) { case Steel::ShaderDataType::Float: return GL_FLOAT; case Steel::ShaderDataType::Float2: return GL_FLOAT; case Steel::ShaderDataType::Float3: return GL_FLOAT; case Steel::ShaderDataType::Float4: return GL_FLOAT; case Steel::ShaderDataType::Mat3: return GL_FLOAT; case Steel::ShaderDataType::Mat4: return GL_FLOAT; case Steel::ShaderDataType::Int: return GL_INT; case Steel::ShaderDataType::Int2: return GL_INT; case Steel::ShaderDataType::Int3: return GL_INT; case Steel::ShaderDataType::Int4: return GL_INT; case Steel::ShaderDataType::Bool: return GL_BOOL; } STEEL_ENGINE_ASSERT(false, "Failed converting shader data type to opengl"); return 0; } Application::Application() { STEEL_ENGINE_ASSERT(!myInstance, "Instance of Application already exists! There can only be one!"); myInstance = this; myWindow = std::unique_ptr<Window>(Window::Create()); myWindow->SetEventCallback(BIND_EVENT_FN(Application::OnEvent)); myImGuiLayer = new ImGuiLayer(); PushOverlay(myImGuiLayer); glGenVertexArrays(1, &myVertexArray); glBindVertexArray(myVertexArray); float vertices[7 * 3] = { -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.0f, 0.5f, 0.8f, 0.7f, 1.0f, 0.0f, 0.5f, 0.0f, 1.f, 0.9f, 0.5f, 1.0f }; myVertexBuffer.reset(VertexBuffer::Create(vertices, sizeof(vertices))); BufferLayout layout = { { ShaderDataType::Float3, "position" }, { ShaderDataType::Float4, "color" } }; myVertexBuffer->SetLayout(layout); uint32_t index = 0; for (auto& element : myVertexBuffer->GetLayout().GetElements()) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, element.GetComponentCount(), ShaderDataTypeToOpenGLBaseType(element.type), (element.normalized ? GL_TRUE : GL_FALSE), layout.GetStride(), (const void*)element.offset); index++; } uint32_t indices[3] = { 0, 1, 2 }; myIndexBuffer.reset(IndexBuffer::Create(indices, sizeof(indices) / sizeof(uint32_t))); std::string vertexSrc = R"( #version 330 core layout(location = 0) in vec3 position; layout(location = 1) in vec4 color; out vec3 v_Position; out vec4 v_Color; void main() { v_Position = position; v_Color = color; gl_Position = vec4(position, 1.0); } )"; std::string fragmentSrc = R"( #version 330 core layout(location = 0) out vec4 color; in vec3 v_Position; in vec4 v_Color; void main() { color = vec4(v_Position * 0.5 + 0.5, 1.0); color = v_Color; } )"; myShader.reset(new Shader(vertexSrc, fragmentSrc)); STEEL_ENGINE_INFO("Application initialized!"); } Application::~Application() { } void Application::Run() { while (myIsRunning) { glClearColor(0.117f, 0.247f, 0.35f, 1); glClear(GL_COLOR_BUFFER_BIT); myShader->Bind(); glBindVertexArray(myVertexArray); glDrawElements(GL_TRIANGLES, myIndexBuffer->GetCount(), GL_UNSIGNED_INT, nullptr); for (Layer* layer : myLayerStack) { layer->OnUpdate(); } myImGuiLayer->Begin(); for (Layer* layer : myLayerStack) layer->OnImGuiRender(); myImGuiLayer->End(); myWindow->OnUpdate(); } } void Application::OnEvent(Event& e) { EventDispatcher dispatcher(e); dispatcher.Dispatch<WindowCloseEvent>(BIND_EVENT_FN(Application::OnWindowClose)); for (auto it = myLayerStack.end(); it != myLayerStack.begin();) { (*--it)->OnEvent(e); if (e.Handled) break; } } void Application::PushLayer(Layer* aLayer) { myLayerStack.PushLayer(aLayer); aLayer->OnAttach(); } void Application::PushOverlay(Layer* aLayer) { myLayerStack.PushOverlay(aLayer); aLayer->OnAttach(); } bool Application::OnWindowClose(WindowCloseEvent& e) { myIsRunning = false; return true; } }
21.887701
101
0.683118
samstalhandske
f095dd72e43104a1ed2af4dcd95e1c7b9917f8e9
3,769
cpp
C++
Escape Room Client/src/core/Inventory.cpp
Daninjakiwi/Escape-Room-Client
a67328feb4ec51e1d8d681804ae9831deb9c2181
[ "MIT" ]
null
null
null
Escape Room Client/src/core/Inventory.cpp
Daninjakiwi/Escape-Room-Client
a67328feb4ec51e1d8d681804ae9831deb9c2181
[ "MIT" ]
null
null
null
Escape Room Client/src/core/Inventory.cpp
Daninjakiwi/Escape-Room-Client
a67328feb4ec51e1d8d681804ae9831deb9c2181
[ "MIT" ]
null
null
null
#pragma once #include "core/Inventory.hpp" #include <algorithm> #include "ui/MultiLineLabel.hpp" InventoryItem::InventoryItem(const std::string& name, const std::string& description, const std::string& thumbnail_path) : name(name), description(description), thumbnail(thumbnail_path) { } Inventory::Inventory() : m_selected(nullptr) {} Inventory::~Inventory() { for (auto item : m_items) { delete item; } } void Inventory::AddItem(const std::string& name, const std::string& description, const std::string& thumbnail_path) { m_items.emplace_back(new InventoryItem(name, description, thumbnail_path)); } bool Inventory::HasItem(const std::string& name) { auto found = std::find_if(m_items.begin(), m_items.end(), [&name](const InventoryItem* item) {return item->name == name; }); if (found != m_items.end()) { return true; } return false; } void Inventory::Draw(volt::Window& window) { volt::Vec2 size = { (float)window.getSize().x, (float)window.getSize().y }; volt::Vec2 mouse_pos = { (float)window.getMousePos().x, (float)window.getMousePos().y }; volt::Quad main_panel({ 0.1f * size.width, 0.05f * size.height }, { 0.8f * size.width, 0.8f * size.height }, {0.1f,0.1f,0.1f,0.67f}); window.drawQuad(main_panel, SEPERATE); if (m_selected) { volt::Font* font = volt::Font::get(volt::fonts::SEGOE); float text_width = font->widthOf(m_selected->name, size.height * 0.10f); MultiLineLabel desc(m_selected->description, "width: " + std::to_string((main_panel.size.width * 0.98f) - (main_panel.size.height * 0.80f)) + "px;height: 64%;left: " + std::to_string(main_panel.pos.x + (main_panel.size.width * 0.03f) + (main_panel.size.height * 0.80f)) + "px;bottom: 30%;text-size: 0.06h;text-colour:#FFFFFF;"); Environment env; env.window = &window; desc.Update(env); desc.Draw(window); window.drawString(m_selected->name, { main_panel.pos.x + (main_panel.size.width / 2.0f) - (text_width / 2.0f), main_panel.pos.y + (main_panel.size.height * 0.90f)}, size.height * 0.10f, volt::fonts::SEGOE, {1.0f,1.0f,1.0f,1.0f}); window.drawTexture(m_selected->thumbnail, { main_panel.pos.x + (main_panel.size.width * 0.01f), main_panel.pos.y + (main_panel.size.height * 0.02f) }, {main_panel.size.height * 0.80f,main_panel.size.height * 0.80f }); volt::Vec4 col = { 1.0f,1.0f,1.0f,1.0f }; if (mouse_pos.x >= main_panel.pos.x + (main_panel.size.width * 0.02f) && mouse_pos.x <= main_panel.pos.x + (main_panel.size.width * 0.02f) + font->widthOf("Back", 0.06f * size.height)) { if (mouse_pos.y >= main_panel.pos.y + (main_panel.size.height * 0.87f) && mouse_pos.y <= main_panel.pos.y + (main_panel.size.height * 0.93f)) { col = { 0.07f,0.53f, 0.66f,1.0f }; if (window.isMouseJustPressed()) { m_selected = nullptr; } } } window.drawString("Back", { main_panel.pos.x + (main_panel.size.width * 0.02f), main_panel.pos.y + (main_panel.size.height * 0.9f) }, 0.06f * size.height, volt::fonts::SEGOE, col); } else { for (int i = 0; i < m_items.size(); i++) { float px = main_panel.pos.x + (0.02f * main_panel.size.width) + (0.14f * (float)(i % 7) * main_panel.size.width); float py = (0.65f * size.height) - ((float)(i / 7) * 0.14f * main_panel.size.width); float sx = main_panel.size.width * 0.12f; window.drawTexture(m_items[i]->thumbnail, { px, py }, { main_panel.size.width * 0.12f,main_panel.size.width * 0.12f }); if (mouse_pos.x >= px && mouse_pos.x <= px + sx && mouse_pos.y >= py && mouse_pos.y <= py + sx) { volt::Quad hover({ px, py }, { sx,sx }, { 0.2f,0.2f,0.2f,0.5f }); window.drawQuad(hover, SEPERATE); if (window.isMouseJustPressed()) { m_selected = m_items[i]; } } } } } const std::vector<InventoryItem*>& Inventory::GetItems() { return m_items; }
44.341176
330
0.662245
Daninjakiwi
f098b4a0927f716620a6d1d01e2bc83ad9a91d84
2,204
hpp
C++
src/vendor/dispatcher/extra/timer.hpp
cyrusccy/Karabiner-Elements
90f83e487a0b6c671bc76f48c01e91fb28ae67c2
[ "Unlicense" ]
null
null
null
src/vendor/dispatcher/extra/timer.hpp
cyrusccy/Karabiner-Elements
90f83e487a0b6c671bc76f48c01e91fb28ae67c2
[ "Unlicense" ]
null
null
null
src/vendor/dispatcher/extra/timer.hpp
cyrusccy/Karabiner-Elements
90f83e487a0b6c671bc76f48c01e91fb28ae67c2
[ "Unlicense" ]
null
null
null
#pragma once // (C) Copyright Takayama Fumihiko 2018. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) // `pqrs::dispatcher::extra::timer` can be used safely in a multi-threaded environment. #include "dispatcher/extra/dispatcher_client.hpp" namespace pqrs { namespace dispatcher { namespace extra { // Usage Note: // // We must not destroy a timer before dispatcher_client is detached. // (It causes that dispatcher might access the released timer.) // timer calls `abort` if you destroy timer while // dispatcher_client is attached in order to avoid the above case. class timer final { public: timer(dispatcher_client& dispatcher_client) : dispatcher_client_(dispatcher_client), current_function_id_(0), interval_(std::chrono::milliseconds(0)) { } ~timer(void) { if (dispatcher_client_.attached()) { // Do not release timer before `dispatcher_client_` is detached. abort(); } } void start(const std::function<void(void)>& function, std::chrono::milliseconds interval) { dispatcher_client_.enqueue_to_dispatcher([this, function, interval] { ++current_function_id_; function_ = function; interval_ = interval; call_function(current_function_id_); }); } void stop(void) { dispatcher_client_.enqueue_to_dispatcher([this] { ++current_function_id_; function_ = nullptr; interval_ = std::chrono::milliseconds(0); }); } private: // This method is executed in the dispatcher thread. void call_function(int function_id) { if (current_function_id_ != function_id) { return; } if (function_) { function_(); } dispatcher_client_.enqueue_to_dispatcher( [this, function_id] { call_function(function_id); }, dispatcher_client_.when_now() + interval_); } dispatcher_client& dispatcher_client_; int current_function_id_; std::function<void(void)> function_; std::chrono::milliseconds interval_; }; } // namespace extra } // namespace dispatcher } // namespace pqrs
27.209877
89
0.666062
cyrusccy
f09cbe9800fcdf2f065ab130edc625dcd494001a
7,935
hh
C++
dune/hdd/linearelliptic/problems/interfaces.hh
tobiasleibner/dune-hdd
35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26
[ "BSD-2-Clause" ]
1
2020-02-08T04:10:59.000Z
2020-02-08T04:10:59.000Z
dune/hdd/linearelliptic/problems/interfaces.hh
tobiasleibner/dune-hdd
35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26
[ "BSD-2-Clause" ]
11
2018-07-31T08:29:42.000Z
2019-06-28T08:53:34.000Z
dune/hdd/linearelliptic/problems/interfaces.hh
tobiasleibner/dune-hdd
35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26
[ "BSD-2-Clause" ]
1
2020-02-08T04:11:02.000Z
2020-02-08T04:11:02.000Z
// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_INTERFACES_HH #define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_INTERFACES_HH #include <vector> #include <ostream> #include <dune/stuff/common/disable_warnings.hh> # include <dune/grid/common/gridview.hh> # include <dune/grid/io/file/vtk.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/string.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/functions/default.hh> #include <dune/pymor/parameters/base.hh> #include <dune/pymor/functions/interfaces.hh> namespace Dune { namespace HDD { namespace LinearElliptic { namespace Problems { // forward, needed for with_mu() template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class Default; } // namespace Problems template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class ProblemInterface : public Pymor::Parametric { typedef ProblemInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType; public: typedef EntityImp EntityType; typedef DomainFieldImp DomainFieldType; static const unsigned int dimDomain = domainDim; typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = rangeDim; typedef Problems::Default< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > NonparametricType; typedef Pymor::AffinelyDecomposableFunctionInterface < EntityType, DomainFieldType, dimDomain, RangeFieldType, 1, 1 > DiffusionFactorType; typedef Pymor::AffinelyDecomposableFunctionInterface < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > DiffusionTensorType; typedef Pymor::AffinelyDecomposableFunctionInterface < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > FunctionType; typedef typename FunctionType::DomainType DomainType; static const bool available = false; static std::string static_id() { return "hdd.linearelliptic.problem"; } ProblemInterface(const Pymor::ParameterType tt = Pymor::ParameterType()) : Pymor::Parametric(tt) {} ProblemInterface(const Pymor::Parametric& other) : Pymor::Parametric(other) {} virtual std::string type() const { return "hdd.linearelliptic.problem"; } virtual const std::shared_ptr< const DiffusionFactorType >& diffusion_factor() const = 0; virtual const std::shared_ptr< const DiffusionTensorType >& diffusion_tensor() const = 0; virtual const std::shared_ptr< const FunctionType >& force() const = 0; virtual const std::shared_ptr< const FunctionType >& dirichlet() const = 0; virtual const std::shared_ptr< const FunctionType >& neumann() const = 0; template< class G > void visualize(const GridView< G >& grid_view, std::string filename, const bool subsampling = true, const VTK::OutputType vtk_output_type = VTK::appendedraw) const { std::unique_ptr< VTKWriter< GridView< G > > > vtk_writer = subsampling ? DSC::make_unique< SubsamplingVTKWriter< GridView< G > > >(grid_view, VTK::nonconforming) : DSC::make_unique< VTKWriter< GridView< G > > >(grid_view, VTK::nonconforming); add_visualizations_(grid_view, *vtk_writer); if (!diffusion_factor()->parametric() && !diffusion_tensor()->parametric()) { auto diffusion = Stuff::Functions::make_product(diffusion_factor()->affine_part(), diffusion_tensor()->affine_part(), "diffusion"); auto diffusion_adapter = std::make_shared< Stuff::Functions::VisualizationAdapter < GridView< G >, dimDomain, dimDomain > >(*diffusion); vtk_writer->addVertexData(diffusion_adapter); vtk_writer->write(filename, vtk_output_type); } else vtk_writer->write(filename, vtk_output_type); } // ... visualize(...) const virtual void report(std::ostream& out, std::string prefix = "") const { out << prefix << "problem '" << type() << "':" << std::endl; out << prefix << " diffusion_factor:" << std::endl; diffusion_factor()->report(out, prefix + " "); out << "\n" << prefix << " diffusion_tensor:" << std::endl; diffusion_tensor()->report(out, prefix + " "); out << "\n" << prefix << " force:" << std::endl; force()->report(out, prefix + " "); out << "\n"<< prefix << " dirichlet:" << std::endl; dirichlet()->report(out, prefix + " "); out << "\n" << prefix << " neumann:" << std::endl; neumann()->report(out, prefix + " "); } // ... report(...) std::shared_ptr< NonparametricType > with_mu(const Pymor::Parameter mu = Pymor::Parameter()) const { if (mu.type() != this->parameter_type()) DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, "mu is " << mu.type() << ", should be " << this->parameter_type() << "!"); return std::make_shared< NonparametricType >(diffusion_factor()->with_mu(this->map_parameter(mu, "diffusion_factor")), diffusion_tensor()->with_mu(this->map_parameter(mu, "diffusion_tensor")), force()->with_mu(this->map_parameter(mu, "force")), dirichlet()->with_mu(this->map_parameter(mu, "dirichlet")), neumann()->with_mu(this->map_parameter(mu, "neumann"))); } // ... with_mu(...) private: template< class GridViewType, class VTKWriterType > void add_visualizations_(const GridViewType& grid_view, VTKWriterType& vtk_writer) const { add_function_visualization_(grid_view, *diffusion_factor(), vtk_writer); add_function_visualization_(grid_view, *diffusion_tensor(), vtk_writer); add_function_visualization_(grid_view, *force(), vtk_writer); add_function_visualization_(grid_view, *dirichlet(), vtk_writer); add_function_visualization_(grid_view, *neumann(), vtk_writer); } // ... add_visualizations_(...) template< class GridViewType, class F, class VTKWriterType > void add_function_visualization_(const GridViewType& /*grid_view*/, const F& function, VTKWriterType& vtk_writer) const { typedef Stuff::Functions::VisualizationAdapter< GridViewType, F::dimRange, F::dimRangeCols > VisualizationAdapter; for (DUNE_STUFF_SSIZE_T qq = 0; qq < function.num_components(); ++qq) vtk_writer.addVertexData(std::make_shared< VisualizationAdapter >(*(function.component(qq)))); if (function.has_affine_part()) vtk_writer.addVertexData(std::make_shared< VisualizationAdapter >(*(function.affine_part()))); } // ... add_function_visualization_(...) private: template< class T > friend std::ostream& operator<<(std::ostream& /*out*/, const ThisType& /*problem*/); }; // ProblemInterface template< class E, class D, int d, class R, int r > std::ostream& operator<<(std::ostream& out, const ProblemInterface< E, D, d, R, r >& problem) { problem.report(out); return out; } // ... operator<<(...) } // namespace LinearElliptic } // namespace HDD } // namespace Dune #include "default.hh" #endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_INTERFACES_HH
42.207447
121
0.652804
tobiasleibner
f09f8945d6951e59bf2b56e54385fdfbc4b55bb1
843
cpp
C++
LeetCode/1000/436.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/1000/436.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/1000/436.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <algorithm> using std::vector; using std::pair; class Solution { public: vector<int> findRightInterval(vector<vector<int>>& intervals) { vector<pair<int, int>> VP; VP.reserve(20000); int cnt = 0; for (const auto& x: intervals) { VP.push_back({x[0], cnt++}); } std::sort(VP.begin(), VP.end()); vector<int> res; res.reserve(20000); auto cmp = [](const auto& item, const auto& target) { return item.first < target; }; for (const auto& x: intervals) { auto p = std::lower_bound(VP.begin(), VP.end(), x[1], cmp); if (p != VP.end()) res.push_back(p->second); else res.push_back(-1); } return res; } };
27.193548
71
0.491103
K-ona
f0a79591453fdaac06b0b67dd0420227ccb01674
3,909
cpp
C++
Lab-Assignments/Data-Structure-Lab/Assignment-4/question-3.cpp
Hics0000/Console-Based-Cpp-Programs
6a7658a302d19b9d623ff7c5de5bc456c2d5ab69
[ "MIT" ]
null
null
null
Lab-Assignments/Data-Structure-Lab/Assignment-4/question-3.cpp
Hics0000/Console-Based-Cpp-Programs
6a7658a302d19b9d623ff7c5de5bc456c2d5ab69
[ "MIT" ]
1
2021-10-05T17:00:52.000Z
2021-10-05T17:00:52.000Z
Lab-Assignments/Data-Structure-Lab/Assignment-4/question-3.cpp
Hics0000/Console-Based-Cpp-Programs
6a7658a302d19b9d623ff7c5de5bc456c2d5ab69
[ "MIT" ]
7
2021-06-13T08:15:26.000Z
2021-10-05T17:02:10.000Z
#include <iostream> using namespace std; template <class T> class Node { public: int data; Node<T> *Next; }; template <class T> class MyVector { public: Node<T> *Head; int count; MyVector() { Head = NULL; count = 0; } Node<T> *createNode(int n) //CREATE NODE { Node<T> *tmp = new Node<T>; tmp->data = n; tmp->Next = NULL; count++; return tmp; } void Assign(int n, int position) //INSERT IN BETWEEN { Node<T> *temp = createNode(n), *nex = Head; if (position <= count) { for (int i = 0; i < position - 1; i++) { nex = nex->Next; } Node<T> *tempp = nex->Next; nex->Next = temp; temp->Next = tempp; } } void Push_Back(int n) //INSERT AT THE END { Node<T> *temp = createNode(n); if (Head == NULL) { Head = temp; } else { Node<T> *curr = Head; while (curr->Next != NULL) { curr = curr->Next; } curr->Next = temp; } } void display() //DISPLAY NODE { cout << "\nList: "; Node<T> *temp = Head; while (temp != NULL) { cout << temp->data << " "; temp = temp->Next; } } void Pop_Back() //DELETE FROM THE END { if (Head == NULL) { cout << "\nList is empty."; return; } else if (Head->Next == NULL) { cout << endl << Head->data; delete Head; Head = NULL; return; } else { Node<T> *temp = Head; while (temp->Next->Next != NULL) temp = temp->Next; cout << endl << temp->data; delete temp->Next; temp->Next = NULL; } count--; } void Clear() //DELETE FROM THE END { if (Head == NULL) { cout << "\nList is empty."; return; } else if (Head->Next == NULL) { delete Head; Head = NULL; return; } else { Pop_Back(); Clear(); } } void Erase(int position) //DELETE FROM A POSITION { Node<T> *temp = Head; if (position <= count) { for (int i = 0; i < position - 1; i++) { temp = temp->Next; } Node<T> *tempp = temp->Next; delete tempp; temp = temp->Next; } count--; } //Size Function Is Used to tell the current Size or NUmber of elements saved in myvector int Size() { return count; } //Resize Function Used To Increase Or Decrease the Storage Size Of MyVector void Resize(int n) { if (n > count) { while (n >= count) { Push_Back(-1); } } else if (n < count) { Pop_Back(); } else { cout << "\n\nSize of MyVector Is Already " << n; } cout << "Final "; display(); } }; int main() { MyVector<int> ll; int n; cin >> n; for (int i = 0; i < n; i++) { ll.Push_Back(rand() % (n + 1)); } cout << endl << "Size Of MyVector= " << ll.Size(); ll.display(); int random = rand() % 10; cout << "\n\nRandom Position Selected To Insert Value Is " << random; ll.Assign(rand() % (n + 100), random); cout << endl; ll.display(); //Pop_back Funtion Calling ll.Pop_Back(); ll.Clear(); ll.display(); return 0; }
20.253886
92
0.403428
Hics0000
f0a91e2d73609fa5a426aa3665f4da43c50708d4
27,534
cpp
C++
WPWIV/WPWIV/Texture.cpp
ACskyline/Wave-Particles-with-Interactive-Vortex
99ed54e231971bfece26f61dfe38b9b75f809fde
[ "MIT" ]
197
2018-12-10T00:19:50.000Z
2022-03-30T08:38:50.000Z
WPWIV/WPWIV/Texture.cpp
ACskyline/Wave-Particles-with-Interactive-Vortex
99ed54e231971bfece26f61dfe38b9b75f809fde
[ "MIT" ]
1
2019-01-17T15:50:09.000Z
2019-01-18T23:11:38.000Z
WPWIV/WPWIV/Texture.cpp
ACskyline/Wave-Particles-with-Interactive-Vortex
99ed54e231971bfece26f61dfe38b9b75f809fde
[ "MIT" ]
12
2019-01-14T03:36:50.000Z
2022-01-23T19:56:30.000Z
#include "Texture.h" Texture::Texture(const wstring& _fileName) : fileName(_fileName), imageData(nullptr), textureBuffer(nullptr) { } Texture::Texture() : Texture(L"no file") { } Texture::~Texture() { ReleaseBuffer(); ReleaseBufferCPU(); } void Texture::ReleaseBuffer() { SAFE_RELEASE(textureBuffer); } void Texture::ReleaseBufferCPU() { if (imageData != nullptr) { delete imageData; imageData = nullptr; } } bool Texture::LoadTextureBuffer() { // load the image, create a texture resource and descriptor heap // Load the image from file int imageSize = LoadImageDataFromFile(&imageData, textureDesc, fileName.c_str(), imageBytesPerRow); // make sure we have data if (imageSize <= 0) { return false; } return true; } bool Texture::LoadTextureBufferFromFile(const wstring& _fileName) { // load the image, create a texture resource and descriptor heap // Load the image from file int imageSize = LoadImageDataFromFile(&imageData, textureDesc, _fileName.c_str(), imageBytesPerRow); // make sure we have data if (imageSize <= 0) { return false; } return true; } bool Texture::CreateTextureBuffer(ID3D12Device* device) { HRESULT hr; // create a default heap where the upload heap will copy its contents into (contents being the texture) hr = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), // a default heap D3D12_HEAP_FLAG_NONE, // no flags &textureDesc, // the description of our texture D3D12_RESOURCE_STATE_COPY_DEST, // We will copy the texture from the upload heap to here, so we start it out in a copy dest state nullptr, // used for render targets and depth/stencil buffers IID_PPV_ARGS(&textureBuffer)); if (FAILED(hr)) { return false; } //textureBuffer->SetName(L"Texture Buffer Resource Heap"); textureBuffer->SetName(fileName.c_str()); return true; } bool Texture::UpdateTextureBuffer(ID3D12Device* device) { HRESULT hr; ID3D12CommandQueue* immediateCopyCommandQueue; ID3D12CommandAllocator* immediateCopyCommandAllocator; ID3D12GraphicsCommandList* immediateCopyCommandList; ID3D12Resource* immediateCopyBuffer; ID3D12Fence* fence; HANDLE fenceEvent; // a handle to an event when our fence is unlocked by the gpu UINT64 fenceValue; // this value is incremented each frame. each fence will have its own value // -- Create fence related resources -- // fenceValue = 0; // set the initial fence value to 0 hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); if (FAILED(hr)) { return false; } fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (fenceEvent == nullptr) { return false; } // -- Create a direct command queue -- // D3D12_COMMAND_QUEUE_DESC cqDesc = {}; cqDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; cqDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; // direct means the gpu can directly execute this command queue hr = device->CreateCommandQueue(&cqDesc, IID_PPV_ARGS(&immediateCopyCommandQueue)); // create the command queue if (FAILED(hr)) { return false; } immediateCopyCommandQueue->SetName(L"texture immediate copy"); // -- Create a command allocator -- // hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&immediateCopyCommandAllocator)); if (FAILED(hr)) { return false; } // -- Create a command list -- // hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, immediateCopyCommandAllocator, NULL, IID_PPV_ARGS(&immediateCopyCommandList)); if (FAILED(hr)) { return false; } UINT64 textureUploadBufferSize; // this function gets the size an upload buffer needs to be to upload a texture to the gpu. // each row must be 256 byte aligned except for the last row, which can just be the size in bytes of the row // eg. textureUploadBufferSize = ((((width * numBytesPerPixel) + 255) & ~255) * (height - 1)) + (width * numBytesPerPixel); //textureUploadBufferSize = (((imageBytesPerRow + 255) & ~255) * (textureDesc.Height - 1)) + imageBytesPerRow; device->GetCopyableFootprints(&textureDesc, 0, 1, 0, nullptr, nullptr, nullptr, &textureUploadBufferSize); // -- Creaete an upload buffer -- // hr = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), // upload heap D3D12_HEAP_FLAG_NONE, // no flags &CD3DX12_RESOURCE_DESC::Buffer(textureUploadBufferSize), // resource description for a buffer (storing the image data in this heap just to copy to the default heap) D3D12_RESOURCE_STATE_GENERIC_READ, // We will copy the contents from this heap to the default heap above nullptr, IID_PPV_ARGS(&immediateCopyBuffer)); if (FAILED(hr)) { return false; } immediateCopyBuffer->SetName(L"texture upload buffer"); // store vertex buffer in upload heap D3D12_SUBRESOURCE_DATA textureData = {}; textureData.pData = imageData; // pointer to our image data textureData.RowPitch = imageBytesPerRow; // size of all our triangle vertex data textureData.SlicePitch = static_cast<LONG_PTR>(imageBytesPerRow) * static_cast<LONG_PTR>(textureDesc.Height); // also the size of our triangle vertex data // Now we copy the upload buffer contents to the default heap UpdateSubresources(immediateCopyCommandList, textureBuffer, immediateCopyBuffer, 0, 0, 1, &textureData); // transition the texture default heap to a pixel shader resource (we will be sampling from this heap in the pixel shader to get the color of pixels) immediateCopyCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(textureBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Format = textureDesc.Format; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = 1; immediateCopyCommandList->Close(); ID3D12CommandList* commandLists[] = { immediateCopyCommandList }; immediateCopyCommandQueue->ExecuteCommandLists(_countof(commandLists), commandLists); // -- Use fence to wait until finish -- // fenceValue++; hr = immediateCopyCommandQueue->Signal(fence, fenceValue); if (FAILED(hr)) { return false; } if (fence->GetCompletedValue() < fenceValue) { // we have the fence create an event which is signaled once the fence's current value is "fenceValue" hr = fence->SetEventOnCompletion(fenceValue, fenceEvent); if (FAILED(hr)) { return false; } // We will wait until the fence has triggered the event that it's current value has reached "fenceValue". once it's value // has reached "fenceValue", we know the command queue has finished executing WaitForSingleObject(fenceEvent, INFINITE); } // -- Release -- // SAFE_RELEASE(fence); SAFE_RELEASE(immediateCopyCommandQueue); SAFE_RELEASE(immediateCopyCommandAllocator); SAFE_RELEASE(immediateCopyCommandList); SAFE_RELEASE(immediateCopyBuffer); return true; } ID3D12Resource* Texture::GetTextureBuffer() { return textureBuffer; } D3D12_SHADER_RESOURCE_VIEW_DESC Texture::GetSrvDesc() { return srvDesc; } //void Texture::ReleaseBufferCPU() //{ // free(imageData); //} wstring Texture::GetName() { return fileName; } bool Texture::InitTexture(ID3D12Device* device) { if (!CreateTextureBuffer(device)) { printf("CreateTextureBuffer failed\n"); return false; } if (!UpdateTextureBuffer(device)) { printf("UpdateTextureBuffer failed\n"); return false; } return true; } int Texture::LoadImageDataFromFile(BYTE** imageData, D3D12_RESOURCE_DESC& resourceDescription, LPCWSTR filename, int &bytesPerRow) { HRESULT hr; // we only need one instance of the imaging factory to create decoders and frames IWICImagingFactory *wicFactory = NULL; // reset decoder, frame and converter since these will be different for each image we load IWICBitmapDecoder *wicDecoder = NULL; IWICBitmapFrameDecode *wicFrame = NULL; IWICFormatConverter *wicConverter = NULL; bool imageConverted = false; if (wicFactory == NULL) { // Initialize the COM library hr = CoInitialize(NULL); if (FAILED(hr)) return 0; // create the WIC factory hr = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wicFactory) ); if (FAILED(hr)) return 0; } // load a decoder for the image hr = wicFactory->CreateDecoderFromFilename( filename, // Image we want to load in NULL, // This is a vendor ID, we do not prefer a specific one so set to null GENERIC_READ, // We want to read from this file WICDecodeMetadataCacheOnLoad, // We will cache the metadata right away, rather than when needed, which might be unknown &wicDecoder // the wic decoder to be created ); if (FAILED(hr)) return 0; // get image from decoder (this will decode the "frame") hr = wicDecoder->GetFrame(0, &wicFrame); if (FAILED(hr)) return 0; // get wic pixel format of image WICPixelFormatGUID pixelFormat; hr = wicFrame->GetPixelFormat(&pixelFormat); if (FAILED(hr)) return 0; // get size of image UINT textureWidth, textureHeight; hr = wicFrame->GetSize(&textureWidth, &textureHeight); if (FAILED(hr)) return 0; // we are not handling sRGB types in this tutorial, so if you need that support, you'll have to figure // out how to implement the support yourself // convert wic pixel format to dxgi pixel format DXGI_FORMAT dxgiFormat = GetDXGIFormatFromWICFormat(pixelFormat); // if the format of the image is not a supported dxgi format, try to convert it if (dxgiFormat == DXGI_FORMAT_UNKNOWN) { // get a dxgi compatible wic format from the current image format WICPixelFormatGUID convertToPixelFormat = GetConvertToWICFormat(pixelFormat); // return if no dxgi compatible format was found if (convertToPixelFormat == GUID_WICPixelFormatDontCare) return 0; // set the dxgi format dxgiFormat = GetDXGIFormatFromWICFormat(convertToPixelFormat); // create the format converter hr = wicFactory->CreateFormatConverter(&wicConverter); if (FAILED(hr)) return 0; // make sure we can convert to the dxgi compatible format BOOL canConvert = FALSE; hr = wicConverter->CanConvert(pixelFormat, convertToPixelFormat, &canConvert); if (FAILED(hr) || !canConvert) return 0; // do the conversion (wicConverter will contain the converted image) hr = wicConverter->Initialize(wicFrame, convertToPixelFormat, WICBitmapDitherTypeErrorDiffusion, 0, 0, WICBitmapPaletteTypeCustom); if (FAILED(hr)) return 0; // this is so we know to get the image data from the wicConverter (otherwise we will get from wicFrame) imageConverted = true; } int bitsPerPixel = GetDXGIFormatBitsPerPixel(dxgiFormat); // number of bits per pixel bytesPerRow = (textureWidth * bitsPerPixel) / 8; // number of bytes in each row of the image data int imageSize = bytesPerRow * textureHeight; // total image size in bytes // allocate enough memory for the raw image data, and set imageData to point to that memory *imageData = (BYTE*)malloc(imageSize); // copy (decoded) raw image data into the newly allocated memory (imageData) if (imageConverted) { // if image format needed to be converted, the wic converter will contain the converted image hr = wicConverter->CopyPixels(0, bytesPerRow, imageSize, *imageData); if (FAILED(hr)) return 0; } else { // no need to convert, just copy data from the wic frame hr = wicFrame->CopyPixels(0, bytesPerRow, imageSize, *imageData); if (FAILED(hr)) return 0; } // now describe the texture with the information we have obtained from the image resourceDescription = {}; resourceDescription.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; resourceDescription.Alignment = 0; // may be 0, 4KB, 64KB, or 4MB. 0 will let runtime decide between 64KB and 4MB (4MB for multi-sampled textures) resourceDescription.Width = textureWidth; // width of the texture resourceDescription.Height = textureHeight; // height of the texture resourceDescription.DepthOrArraySize = 1; // if 3d image, depth of 3d image. Otherwise an array of 1D or 2D textures (we only have one image, so we set 1) resourceDescription.MipLevels = 1; // Number of mipmaps. We are not generating mipmaps for this texture, so we have only one level resourceDescription.Format = dxgiFormat; // This is the dxgi format of the image (format of the pixels) resourceDescription.SampleDesc.Count = 1; // This is the number of samples per pixel, we just want 1 sample resourceDescription.SampleDesc.Quality = 0; // The quality level of the samples. Higher is better quality, but worse performance resourceDescription.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // The arrangement of the pixels. Setting to unknown lets the driver choose the most efficient one resourceDescription.Flags = D3D12_RESOURCE_FLAG_NONE; // no flags // return the size of the image. remember to delete the image once your done with it (in this tutorial once its uploaded to the gpu) return imageSize; } // get the dxgi format equivilent of a wic format DXGI_FORMAT Texture::GetDXGIFormatFromWICFormat(WICPixelFormatGUID& wicFormatGUID) { if (wicFormatGUID == GUID_WICPixelFormat128bppRGBAFloat) return DXGI_FORMAT_R32G32B32A32_FLOAT; else if (wicFormatGUID == GUID_WICPixelFormat64bppRGBAHalf) return DXGI_FORMAT_R16G16B16A16_FLOAT; else if (wicFormatGUID == GUID_WICPixelFormat64bppRGBA) return DXGI_FORMAT_R16G16B16A16_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat32bppRGBA) return DXGI_FORMAT_R8G8B8A8_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat32bppBGRA) return DXGI_FORMAT_B8G8R8A8_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat32bppBGR) return DXGI_FORMAT_B8G8R8X8_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat32bppRGBA1010102XR) return DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat32bppRGBA1010102) return DXGI_FORMAT_R10G10B10A2_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat16bppBGRA5551) return DXGI_FORMAT_B5G5R5A1_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat16bppBGR565) return DXGI_FORMAT_B5G6R5_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat32bppGrayFloat) return DXGI_FORMAT_R32_FLOAT; else if (wicFormatGUID == GUID_WICPixelFormat16bppGrayHalf) return DXGI_FORMAT_R16_FLOAT; else if (wicFormatGUID == GUID_WICPixelFormat16bppGray) return DXGI_FORMAT_R16_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat8bppGray) return DXGI_FORMAT_R8_UNORM; else if (wicFormatGUID == GUID_WICPixelFormat8bppAlpha) return DXGI_FORMAT_A8_UNORM; else return DXGI_FORMAT_UNKNOWN; } // get a dxgi compatible wic format from another wic format WICPixelFormatGUID Texture::GetConvertToWICFormat(WICPixelFormatGUID& wicFormatGUID) { if (wicFormatGUID == GUID_WICPixelFormatBlackWhite) return GUID_WICPixelFormat8bppGray; else if (wicFormatGUID == GUID_WICPixelFormat1bppIndexed) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat2bppIndexed) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat4bppIndexed) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat8bppIndexed) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat2bppGray) return GUID_WICPixelFormat8bppGray; else if (wicFormatGUID == GUID_WICPixelFormat4bppGray) return GUID_WICPixelFormat8bppGray; else if (wicFormatGUID == GUID_WICPixelFormat16bppGrayFixedPoint) return GUID_WICPixelFormat16bppGrayHalf; else if (wicFormatGUID == GUID_WICPixelFormat32bppGrayFixedPoint) return GUID_WICPixelFormat32bppGrayFloat; else if (wicFormatGUID == GUID_WICPixelFormat16bppBGR555) return GUID_WICPixelFormat16bppBGRA5551; else if (wicFormatGUID == GUID_WICPixelFormat32bppBGR101010) return GUID_WICPixelFormat32bppRGBA1010102; else if (wicFormatGUID == GUID_WICPixelFormat24bppBGR) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat24bppRGB) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat32bppPBGRA) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat32bppPRGBA) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat48bppRGB) return GUID_WICPixelFormat64bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat48bppBGR) return GUID_WICPixelFormat64bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat64bppBGRA) return GUID_WICPixelFormat64bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat64bppPRGBA) return GUID_WICPixelFormat64bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat64bppPBGRA) return GUID_WICPixelFormat64bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat48bppRGBFixedPoint) return GUID_WICPixelFormat64bppRGBAHalf; else if (wicFormatGUID == GUID_WICPixelFormat48bppBGRFixedPoint) return GUID_WICPixelFormat64bppRGBAHalf; else if (wicFormatGUID == GUID_WICPixelFormat64bppRGBAFixedPoint) return GUID_WICPixelFormat64bppRGBAHalf; else if (wicFormatGUID == GUID_WICPixelFormat64bppBGRAFixedPoint) return GUID_WICPixelFormat64bppRGBAHalf; else if (wicFormatGUID == GUID_WICPixelFormat64bppRGBFixedPoint) return GUID_WICPixelFormat64bppRGBAHalf; else if (wicFormatGUID == GUID_WICPixelFormat64bppRGBHalf) return GUID_WICPixelFormat64bppRGBAHalf; else if (wicFormatGUID == GUID_WICPixelFormat48bppRGBHalf) return GUID_WICPixelFormat64bppRGBAHalf; else if (wicFormatGUID == GUID_WICPixelFormat128bppPRGBAFloat) return GUID_WICPixelFormat128bppRGBAFloat; else if (wicFormatGUID == GUID_WICPixelFormat128bppRGBFloat) return GUID_WICPixelFormat128bppRGBAFloat; else if (wicFormatGUID == GUID_WICPixelFormat128bppRGBAFixedPoint) return GUID_WICPixelFormat128bppRGBAFloat; else if (wicFormatGUID == GUID_WICPixelFormat128bppRGBFixedPoint) return GUID_WICPixelFormat128bppRGBAFloat; else if (wicFormatGUID == GUID_WICPixelFormat32bppRGBE) return GUID_WICPixelFormat128bppRGBAFloat; else if (wicFormatGUID == GUID_WICPixelFormat32bppCMYK) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat64bppCMYK) return GUID_WICPixelFormat64bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat40bppCMYKAlpha) return GUID_WICPixelFormat64bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat80bppCMYKAlpha) return GUID_WICPixelFormat64bppRGBA; #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) else if (wicFormatGUID == GUID_WICPixelFormat32bppRGB) return GUID_WICPixelFormat32bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat64bppRGB) return GUID_WICPixelFormat64bppRGBA; else if (wicFormatGUID == GUID_WICPixelFormat64bppPRGBAHalf) return GUID_WICPixelFormat64bppRGBAHalf; #endif else return GUID_WICPixelFormatDontCare; } // get the number of bits per pixel for a dxgi format int Texture::GetDXGIFormatBitsPerPixel(DXGI_FORMAT& dxgiFormat) { if (dxgiFormat == DXGI_FORMAT_R32G32B32A32_FLOAT) return 128; else if (dxgiFormat == DXGI_FORMAT_R16G16B16A16_FLOAT) return 64; else if (dxgiFormat == DXGI_FORMAT_R16G16B16A16_UNORM) return 64; else if (dxgiFormat == DXGI_FORMAT_R8G8B8A8_UNORM) return 32; else if (dxgiFormat == DXGI_FORMAT_B8G8R8A8_UNORM) return 32; else if (dxgiFormat == DXGI_FORMAT_B8G8R8X8_UNORM) return 32; else if (dxgiFormat == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) return 32; else if (dxgiFormat == DXGI_FORMAT_R10G10B10A2_UNORM) return 32; else if (dxgiFormat == DXGI_FORMAT_B5G5R5A1_UNORM) return 16; else if (dxgiFormat == DXGI_FORMAT_B5G6R5_UNORM) return 16; else if (dxgiFormat == DXGI_FORMAT_R32_FLOAT) return 32; else if (dxgiFormat == DXGI_FORMAT_R16_FLOAT) return 16; else if (dxgiFormat == DXGI_FORMAT_R16_UNORM) return 16; else if (dxgiFormat == DXGI_FORMAT_R8_UNORM) return 8; else if (dxgiFormat == DXGI_FORMAT_A8_UNORM) return 8; return -1; } /////////////////////////////////////////////////////////////// /////////////// RENDER TEXTURE STARTS FROM HERE /////////////// /////////////////////////////////////////////////////////////// RenderTexture::RenderTexture(int _width, int _height, DXGI_FORMAT format, bool _supportDepth) : RenderTexture(_width, _height, L"no name", format, _supportDepth) { } RenderTexture::RenderTexture(int _width, int _height, const wstring& _fileName, DXGI_FORMAT format, bool _supportDepth) : width(_width), height(_height), supportDepth(_supportDepth), depthStencilBuffer(nullptr), resourceState(D3D12_RESOURCE_STATE_RENDER_TARGET), Texture(_fileName.c_str()) { textureDesc = {}; textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; textureDesc.Alignment = 0; // may be 0, 4KB, 64KB, or 4MB. 0 will let runtime decide between 64KB and 4MB (4MB for multi-sampled textures) textureDesc.Width = width; // width of the texture textureDesc.Height = height; // height of the texture textureDesc.DepthOrArraySize = 1; // if 3d image, depth of 3d image. Otherwise an array of 1D or 2D textures (we only have one image, so we set 1) textureDesc.MipLevels = 1; // Number of mipmaps. We are not generating mipmaps for this texture, so we have only one level textureDesc.Format = format; // This is the dxgi format of the image (format of the pixels) textureDesc.SampleDesc.Count = 1; // This is the number of samples per pixel, we just want 1 sample textureDesc.SampleDesc.Quality = 0; // The quality level of the samples. Higher is better quality, but worse performance textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // The arrangement of the pixels. Setting to unknown lets the driver choose the most efficient one textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS; depthStencilBufferDesc = {}; depthStencilBufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; depthStencilBufferDesc.Alignment = 0; // may be 0, 4KB, 64KB, or 4MB. 0 will let runtime decide between 64KB and 4MB (4MB for multi-sampled textures) depthStencilBufferDesc.Width = width; // width of the texture depthStencilBufferDesc.Height = height; // height of the texture depthStencilBufferDesc.DepthOrArraySize = 1; // if 3d image, depth of 3d image. Otherwise an array of 1D or 2D textures (we only have one image, so we set 1) depthStencilBufferDesc.MipLevels = 0; // Number of mipmaps. We are not generating mipmaps for this texture, so we have only one level depthStencilBufferDesc.Format = DXGI_FORMAT_D32_FLOAT; // This is the dxgi format of the image (format of the pixels) depthStencilBufferDesc.SampleDesc.Count = 1; // This is the number of samples per pixel, we just want 1 sample depthStencilBufferDesc.SampleDesc.Quality = 0; // The quality level of the samples. Higher is better quality, but worse performance depthStencilBufferDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // The arrangement of the pixels. Setting to unknown lets the driver choose the most efficient one depthStencilBufferDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; } RenderTexture::~RenderTexture() { ReleaseBuffers(); } void RenderTexture::ReleaseBuffers() { SAFE_RELEASE(depthStencilBuffer); SAFE_RELEASE(textureBuffer); } bool RenderTexture::CreateTextureBuffer(ID3D12Device* device) { HRESULT hr; D3D12_CLEAR_VALUE colorOptimizedClearValue = {}; colorOptimizedClearValue.Format = textureDesc.Format; colorOptimizedClearValue.Color[0] = 0.0f; colorOptimizedClearValue.Color[1] = 0.0f; colorOptimizedClearValue.Color[2] = 0.0f; colorOptimizedClearValue.Color[3] = 0.0f; hr = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &textureDesc, D3D12_RESOURCE_STATE_RENDER_TARGET, &colorOptimizedClearValue, IID_PPV_ARGS(&textureBuffer)); if (FAILED(hr)) { return false; } textureBuffer->SetName(fileName.c_str()); //////////////////////////////////////////////////////////////////// if (supportDepth) { D3D12_CLEAR_VALUE depthOptimizedClearValue = {}; depthOptimizedClearValue.Format = DXGI_FORMAT_D32_FLOAT; depthOptimizedClearValue.DepthStencil.Depth = 1.0f; depthOptimizedClearValue.DepthStencil.Stencil = 0; hr = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_D32_FLOAT, width, height, 1, 0, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),//depthStencilBufferDesc,// D3D12_RESOURCE_STATE_DEPTH_WRITE, &depthOptimizedClearValue, IID_PPV_ARGS(&depthStencilBuffer) ); if (FAILED(hr)) { return false; } depthStencilBuffer->SetName(fileName.c_str()); } return true; } bool RenderTexture::UpdateTextureBuffer(ID3D12Device* device) { HRESULT hr; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Format = textureDesc.Format; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = 1; //Render Target View Desc rtvDesc.Format = textureDesc.Format; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = 0; //Stencil Depth View Desc //if you want to bind null dsv desciptor, you need to create the dsv //if you want to create the dsv, you need a initialized dsvDesc to avoid the debug layer throwing out error dsvDesc.Format = DXGI_FORMAT_D32_FLOAT; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; dsvDesc.Flags = D3D12_DSV_FLAG_NONE; dsvDesc.Texture2D.MipSlice = 0; return true; } void RenderTexture::UpdateViewport() { viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = width; viewport.Height = height; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; } void RenderTexture::UpdateScissorRect() { scissorRect.left = 0; scissorRect.top = 0; scissorRect.right = width; scissorRect.bottom = height; } void RenderTexture::SetRtvHandle(CD3DX12_CPU_DESCRIPTOR_HANDLE _rtvHandle) { rtvHandle = _rtvHandle; } void RenderTexture::SetDsvHandle(CD3DX12_CPU_DESCRIPTOR_HANDLE _dsvHandle) { dsvHandle = _dsvHandle; } void RenderTexture::SetResourceState(D3D12_RESOURCE_STATES _resourceState) { resourceState = _resourceState; } bool RenderTexture::SupportDepth() { return supportDepth; } ID3D12Resource* RenderTexture::GetDepthStencilBuffer() { // make sure to create null descriptor for render textures which does not support depth return supportDepth ? depthStencilBuffer : nullptr; } D3D12_VIEWPORT RenderTexture::GetViewport() { return viewport; } D3D12_RECT RenderTexture::GetScissorRect() { return scissorRect; } CD3DX12_CPU_DESCRIPTOR_HANDLE RenderTexture::GetRtvHandle() { return rtvHandle; } CD3DX12_CPU_DESCRIPTOR_HANDLE RenderTexture::GetDsvHandle() { return dsvHandle; } D3D12_RENDER_TARGET_VIEW_DESC RenderTexture::GetRtvDesc() { return rtvDesc; } D3D12_DEPTH_STENCIL_VIEW_DESC RenderTexture::GetDsvDesc() { return dsvDesc; } D3D12_RESOURCE_STATES RenderTexture::GetResourceState() { return resourceState; } CD3DX12_RESOURCE_BARRIER RenderTexture::TransitionToResourceState(D3D12_RESOURCE_STATES _resourceState) { #ifdef MY_DEBUG if (resourceState == _resourceState) __debugbreak(); #endif CD3DX12_RESOURCE_BARRIER result; result = CD3DX12_RESOURCE_BARRIER::Transition(textureBuffer, resourceState, _resourceState); resourceState = _resourceState; return result; } bool RenderTexture::InitTexture(ID3D12Device* device) { UpdateViewport(); UpdateScissorRect(); if (!CreateTextureBuffer(device)) { printf("CreateTextureBuffer failed\n"); return false; } if (!UpdateTextureBuffer(device)) { printf("UpdateTextureBuffer failed\n"); return false; } return true; }
38.348189
176
0.779509
ACskyline
f0a9baabd160436a7bfa90dd0ddc3fd74d0c4b83
1,238
cpp
C++
src/scenes/SFPC/EstherKnowltonScene/EstherKnowltonScene.cpp
roymacdonald/ReCoded
3bcb3d579cdd17381e54a508a1e4ef9e3d5bc4f1
[ "MIT" ]
64
2017-06-12T19:24:08.000Z
2022-01-27T19:14:48.000Z
src/scenes/EstherKnowltonScene/EstherKnowltonScene.cpp
colaplate/recoded
934e1184c7502d192435c406e56b8a2106e9b6b4
[ "MIT" ]
10
2017-06-13T10:38:39.000Z
2017-11-15T11:21:05.000Z
src/scenes/EstherKnowltonScene/EstherKnowltonScene.cpp
colaplate/recoded
934e1184c7502d192435c406e56b8a2106e9b6b4
[ "MIT" ]
24
2017-06-11T08:14:46.000Z
2020-04-16T20:28:46.000Z
#include "EstherKnowltonScene.h" void EstherKnowltonScene::setup(){ // setup pramaters // if your original code use an ofxPanel instance dont use it here, instead // add your parameters to the "parameters" instance as follows. // param was declared in EstherKnowltonScene.h //parameters.add(param.set("param", 5, 0, 100)); img.load("scenes/EstherKnowltonScene/N00004808.jpg"); img.setImageType(OF_IMAGE_GRAYSCALE); float width = ofGetWidth(); parameters.add(posX1.set("posX1", -10, -25, 0)); parameters.add(rotation.set("rotation", 150, 0, ofGetWidth())); parameters.add(alpha.set("alpha", 140, 0, 255)); setAuthor("Esther Bouquet"); setOriginalArtist("Ken Knowlton"); loadCode("scenes/EstherKnowltonScene/exampleCode.cpp"); } void EstherKnowltonScene::update(){ } void EstherKnowltonScene::draw(){ ofSetRectMode(OF_RECTMODE_CENTER); for (int i = 0; i < img.getWidth(); i=i+20) { for (int j = 0; j < img.getHeight(); j=j+20) { ofColor c = img.getColor(i, j); float bright = c.getBrightness(); ofPushMatrix(); ofTranslate(i, j); ofRotateZ(ofMap(bright, 0, 255, 0, rotation)); ofSetColor(255, alpha); ofDrawLine(posX1, 0, 5, 0); ofPopMatrix(); } } }
21.344828
75
0.67609
roymacdonald
f0acc41b5c7997fc60ff1a09f1db5a62f954c419
3,777
h++
C++
core/proxy_property.h++
rubenvb/skui
5bda2d73232eb7a763ba9d788c7603298767a7d7
[ "MIT" ]
19
2016-10-13T22:44:31.000Z
2021-12-28T20:28:15.000Z
core/proxy_property.h++
rubenvb/skui
5bda2d73232eb7a763ba9d788c7603298767a7d7
[ "MIT" ]
1
2021-05-16T15:15:22.000Z
2021-05-16T17:01:26.000Z
core/proxy_property.h++
rubenvb/skui
5bda2d73232eb7a763ba9d788c7603298767a7d7
[ "MIT" ]
4
2017-03-07T05:37:02.000Z
2018-06-05T03:14:48.000Z
/** * The MIT License (MIT) * * Copyright © 2017-2019 Ruben Van Boxem * * 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. **/ /* * Proxy Property * Property that wraps an external resource. * Note: the changed signal is only emitted when the value is changed through * the proxy_property. */ #ifndef SKUI_CORE_PROXY_PROPERTY_H #define SKUI_CORE_PROXY_PROPERTY_H #include "core/signal.h++" #include <functional> #include <istream> #include <ostream> namespace skui::core { template<typename T> class proxy_property { public: using value_type = T; using reference = std::add_lvalue_reference_t<T>; using const_reference = std::add_lvalue_reference_t<std::add_const_t<value_type>>; using rvalue_reference = std::add_rvalue_reference_t<value_type>; template<typename Setter, typename Getter> proxy_property(const_reference value, Setter setter, Getter getter) : set{setter} , get{getter} { set(value); } template<typename Setter, typename Getter> proxy_property(Setter setter, Getter getter) : set{setter} , get{getter} {} proxy_property& operator=(const_reference& other) { const bool changed = other != static_cast<const_reference>(*this); if(set) set(other); if(changed) value_changed.emit(other); return *this; } const proxy_property& operator=(const_reference& other) const { const bool changed = other != static_cast<const_reference>(*this); if(set) set(other); if(changed) value_changed.emit(other); return *this; } operator value_type() const { return get ? get() : value_type{}; } bool operator==(const_reference other) const { return get ? get() == other : false; } bool operator!=(const_reference other) const { return get ? get() != other : false; } bool operator< (const_reference other) const { return get ? get() < other : false; } bool operator<=(const_reference other) const { return get ? get() <= other : false; } bool operator> (const_reference other) const { return get ? get() > other : false; } bool operator>=(const_reference other) const { return get ? get() >= other : false; } signal<value_type> value_changed; private: std::function<void(const T&)> set; std::function<T()> get; }; template<typename T> std::ostream& operator<<(std::ostream& os, const proxy_property<T>& prop) { return os << static_cast<const T&>(prop); } template<typename ValueType> std::istream& operator>>(std::istream& os, proxy_property<ValueType>& property) { ValueType result; os >> result; if(os) property = std::move(result); return os; } } #endif
31.214876
89
0.688907
rubenvb
f0b020f430f7d0c243afef5780e6816fe50faa44
1,610
cpp
C++
luogu/P1522.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
1
2020-07-24T03:07:08.000Z
2020-07-24T03:07:08.000Z
luogu/P1522.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
null
null
null
luogu/P1522.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
null
null
null
// // Created by yangtao on 19-11-25. // #include <cstdio> #include <cmath> #include <cstring> #include <iostream> #include <algorithm> #define inf 0x3f3f3f3f3f3f3f3f using namespace std; const int N = 155; double d[N][N], d1[N]; int z[2][N]; int n; double m1, m2 = inf; void floyd() { for(int k = 1; k <= n; k++) { for(int i = 1; i <=n ; i++) { for(int j = 1; j <=n ;j++) { if(d[i][j] > d[i][k] + d[k][j]) d[i][j] = d[i][k] + d[k][j]; } } } } double dis(int x, int y) { int dx = z[0][x] - z[0][y]; int dy = z[1][x] - z[1][y]; return sqrt(dx * dx + dy * dy); } int main() { memset(d, 0x3f, sizeof( d) ); cin >> n; for(int i = 1; i <=n ; i++) { scanf("%d%d", &z[0][i], &z[1][i]); } char t; for(int i = 1 ; i <= n; i++ ) { for(int j = 1; j <= n ; j++) { cin >> t; if (i == j) { d[i][j] = 0; } else if(t == '1') { d[i][j] = dis(i, j); } else { d[i][j] = inf; } } } floyd(); for(int i = 1; i <= n; i++) { for(int j = 1; j<=n ; j++) { if(d[i][j] != inf) d1[i] = max(d1[i], d[i][j]); // 找到从i出发最长一条路径记录在d1[i]中 m1 = max(m1, d1[i]); // 找到牧场里最长的一条路径 } } for (int i = 0; i <= n ; ++i) { for (int j = 0; j <= n; ++j) { if(d[i][j] == inf) { m2 = min(m2, d1[i] + dis(i, j) + d1[j]); } } } printf("%.6f", max(m1, m2)); return 0; }
20.641026
84
0.360248
delphi122
f0ba52f401d75d124eeb3bb1e24443c726e10ea7
972
hpp
C++
addons/misc/CfgEventHandlers.hpp
kellerkompanie/kellerkompanie-medical
b66076217c1c08b6464ec19c15eef72c91bb5cfb
[ "MIT" ]
null
null
null
addons/misc/CfgEventHandlers.hpp
kellerkompanie/kellerkompanie-medical
b66076217c1c08b6464ec19c15eef72c91bb5cfb
[ "MIT" ]
1
2019-03-26T00:56:20.000Z
2019-03-26T00:56:20.000Z
addons/misc/CfgEventHandlers.hpp
kellerkompanie/kellerkompanie-medical
b66076217c1c08b6464ec19c15eef72c91bb5cfb
[ "MIT" ]
null
null
null
class Extended_PreInit_EventHandlers { class ADDON { init = QUOTE(call COMPILE_FILE(XEH_preInit)); disableModuload = true; }; }; class Extended_Init_EventHandlers { class CAManBase { class ADDON { init = QUOTE(_this call COMPILE_FILE(XEH_init)); }; }; class Land_IntravenStand_01_empty_F { class ADDON { init = QUOTE((_this select 0) setVariable [ARR_3(QQGVAR(stand), [], true)]); }; }; class Land_IntravenStand_01_1bag_F { class ADDON { init = QUOTE((_this select 0) setVariable [ARR_3(QQGVAR(stand), [1000], true)]); }; }; class Land_IntravenStand_01_2bags_F { class ADDON { init = QUOTE((_this select 0) setVariable [ARR_3(QQGVAR(stand), [ARR_2(1000, 1000)], true)]); }; }; }; class Extended_PostInit_EventHandlers { class ADDON { init = QUOTE(call COMPILE_FILE(XEH_postInit)); }; };
27.771429
105
0.597737
kellerkompanie
f0bac7bcf17c1ec31334cc88dbc6b0f66e195e24
2,325
hxx
C++
AccountingManager.hxx
resiprocate/legacy-b2bua
5684967725fc3faf6d609d6db956d855c1f9426d
[ "SGI-B-2.0", "CECILL-B" ]
3
2016-03-24T12:49:36.000Z
2019-03-20T08:35:11.000Z
AccountingManager.hxx
resiprocate/legacy-b2bua
5684967725fc3faf6d609d6db956d855c1f9426d
[ "SGI-B-2.0", "CECILL-B" ]
null
null
null
AccountingManager.hxx
resiprocate/legacy-b2bua
5684967725fc3faf6d609d6db956d855c1f9426d
[ "SGI-B-2.0", "CECILL-B" ]
2
2019-07-23T10:41:20.000Z
2021-01-21T02:15:46.000Z
#ifndef __AccountingManager_h #define __AccountingManager_h #include "rutil/Data.h" namespace b2bua { class AccountingManager { public: // Call has entered system virtual void onCallStart() = 0; // Call has been authorised virtual void onCallAuthorise() = 0; // Call has connected virtual void onCallConnect() = 0; // A route has failed virtual void onCallRouteFail() = 0; // All routes have been tried and failed, or the call was not authorised virtual void onCallFail() = 0; // The call connected and completed successfully virtual void onCallFinish() = 0; }; } #endif /* ==================================================================== * * Copyright 2012 Daniel Pocock. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the author(s) nor the names of any contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * ==================================================================== * * */
33.695652
77
0.697204
resiprocate