blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
394591e9ba139a02f3a76910829bdbad9a9d8f8c
29cd8de734117b5fb81d4bc568ac9b45b4e2cd82
/744.cpp
cbf106f152316e870706d703204d07d25d32e68f
[]
no_license
vedantpople4/problem_solving_cpp
386eacd11ea307e3e9bf2ce86b78043573d67b9c
ebe4599ad9eba332fccec9aec0b63ecad930813b
refs/heads/master
2022-07-28T22:21:17.659296
2022-07-11T13:10:20
2022-07-11T13:10:20
228,216,495
1
3
null
2020-10-25T15:58:32
2019-12-15T16:38:00
C++
UTF-8
C++
false
false
287
cpp
744.cpp
class Solution { public: char nextGreatestLetter(vector<char>& letters, char target) { int ans = upper_bound(letters.begin(), letters.end(), target) - letters.begin(); if(ans>=0 and ans<letters.size()) return letters[ans]; else return letters[0]; } };
02573b6a17c6c92b346ee112fa2527b82f7d1034
a25a7f46d5c3b0e90620607ab0288a416d68e37c
/tuplex/codegen/include/ApplyVisitor.h
225dc622f917cab4ff9360a7cfe41ab9b063aa1c
[ "Apache-2.0" ]
permissive
cacoderquan/tuplex
886ec24a03e12135bb39e960cd247f7526c72917
9a919cbaeced536c2a20ba970c14f719a3b6c31e
refs/heads/master
2023-08-21T06:10:15.902884
2021-10-25T16:41:57
2021-10-25T16:41:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,363
h
ApplyVisitor.h
//--------------------------------------------------------------------------------------------------------------------// // // // Tuplex: Blazing Fast Python Data Science // // // // // // (c) 2017 - 2021, Tuplex team // // Created by Leonhard Spiegelberg first on 1/1/2021 // // License: Apache 2.0 // //--------------------------------------------------------------------------------------------------------------------// #ifndef TUPLEX_APPLYVISITOR_H #define TUPLEX_APPLYVISITOR_H #include "IPrePostVisitor.h" namespace tuplex { /*! * helper class to execute lambda function for all nodes of a specific type fulfilling some predicate */ class ApplyVisitor : public IPrePostVisitor { protected: std::function<bool(const ASTNode*)> _predicate; std::function<void(ASTNode&)> _func; void postOrder(ASTNode *node) override { if(_predicate(node)) _func(*node); } void preOrder(ASTNode *node) override {} public: ApplyVisitor() = delete; /*! * create a new ApplyVisitor * @param predicate visit only nodes which return true * @param func call this function on every node which satisfies the predicate * @param followAll whether to visit all nodes, or only follow the normal-case path */ ApplyVisitor(std::function<bool(const ASTNode*)> predicate, std::function<void(ASTNode&)> func, bool followAll=true) : _predicate(predicate), _func(func), _followAll(followAll) {} // speculation so far only on ifelse branches void visit(NIfElse* ifelse) override { if(!_followAll) { // speculation on? bool speculate = ifelse->annotation().numTimesVisited > 0; auto visit_t = whichBranchToVisit(ifelse); auto visit_ifelse = std::get<0>(visit_t); auto visit_if = std::get<1>(visit_t); auto visit_else = std::get<2>(visit_t); // only one should be true, logical xor if(speculate && (!visit_if != !visit_else)) { if(visit_if) { ifelse->_expression->accept(*this); ifelse->_then->accept(*this); } if(visit_else && ifelse->_else) { ifelse->_expression->accept(*this); ifelse->_else->accept(*this); } return; } } IPrePostVisitor::visit(ifelse); } private: bool _followAll; }; } #endif //TUPLEX_FORCETYPEVISITOR_H
183c55ace9c72d63b7be2e2aac7553e10f3775c6
a575586dcb56f7b52378a368390ecfc2dd238e78
/class_pointer.cpp
abe62561ff534a5813771dee51fca6392241fe95
[]
no_license
monp97/cpp
89aa1b0da07d17a09ed85a371089d4ee7ca5fdbe
7ec467e62fd1eec14fdcc841a768135432c8c18b
refs/heads/master
2021-04-25T14:00:38.017459
2017-12-11T02:43:46
2017-12-11T02:43:46
110,008,005
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
class_pointer.cpp
#include<iostream> using namespace std; class point{ private: int marks; public: void get() { cout<<"enter"; cin>>marks; } void display() { cout<<marks<<endl; } }; int main() { point *p=new point[3]; p->get(); p->display(); return 0; }
35c105807914a896f1ea5880861438c7f338a0ed
b1344e8317465a5e290d5bf050aa6e3ed77e1014
/OpenGL Tutorial/OpenGL Tutorial/VertexArray.cpp
377c9e21122f9f8f6df05e0527d836f0737adf1c
[]
no_license
zerowanghao/OpenGL-Learning
1974eeaf206682ecafdb851ce447adcadc7cc615
53afdf77855492c3fa17153630979a0135a43eb1
refs/heads/master
2021-08-24T15:26:53.442671
2017-12-10T06:58:41
2017-12-10T06:58:41
113,636,697
0
0
null
null
null
null
UTF-8
C++
false
false
732
cpp
VertexArray.cpp
#include "VertexArray.h" namespace Renderer { VertexArray::VertexArray() { glGenVertexArrays(1, &mVertexArrayID); } VertexArray::~VertexArray() { glDeleteVertexArrays(1, &mVertexArrayID); for (size_t i = 0; i < mBuffers.size(); i++) { delete mBuffers[i]; } } void VertexArray::enable() const { glBindVertexArray(mVertexArrayID); } void VertexArray::disable() const { glBindVertexArray(0); } void VertexArray::addBuffer(Buffer * pBuffer, GLuint pIndex) { enable(); pBuffer->enable(); glEnableVertexAttribArray(pIndex); glVertexAttribPointer(pIndex, pBuffer->getComponentCount(), GL_FLOAT, GL_FALSE, 0, 0); mBuffers.push_back(pBuffer); pBuffer->disable(); disable(); } };
d5169a65610d85443b8ec59ad228c225dd5b8701
24b4b6cbef5ff3988d2ca18abacba9181c338c51
/basic_heap.cpp
228fdd10fca7b3ea39437c705c31123880240758
[]
no_license
singhalyash8080/codes-for-dsa-practice
edd5aa01fde5a35ec75cbcfe76fd21b36be9c944
a8f91f9836f52e9fe10b0b08832696ee623f543a
refs/heads/master
2023-08-06T03:32:14.397248
2021-09-18T12:46:50
2021-09-18T12:46:50
343,876,207
0
0
null
null
null
null
UTF-8
C++
false
false
2,118
cpp
basic_heap.cpp
#include <bits/stdc++.h> using namespace std; #define int long long int void yashio(); // max and mean heap using the same class class Heap{ vector <int> v; bool minHeap; bool compare(int a, int b){ if(minHeap){ return a<b; } else{ return a>b; } } public: Heap(int defaultSize=10,bool type = true){ v.reserve(defaultSize); v.push_back(-1); minHeap = type; } void push(int d){ v.push_back(d); int idx = v.size() - 1; int parent = idx/2; // keep pushing to the top till you reach a root node or stop midway because we found an appropriate pos while(idx > 1 and compare(v[idx],v[parent])){ swap(v[idx],v[parent]); idx = parent; parent = parent/2; } } void heapify(int idx){ int left = 2*idx; int right = left + 1; int min_idx = idx; int last = v.size() - 1; if(left<=last and compare(v[left],v[idx])){ min_idx = left; } if(right<=last and compare(v[right],v[min_idx])){ min_idx = right; } if(min_idx!=idx){ swap(v[idx],v[min_idx]); heapify(min_idx); } } void pop(){ int last = v.size() - 1; swap(v[1],v[last]); v.pop_back(); heapify(1); } int top(){ return v[1]; } bool empty(){ // 1 because we have -1 as the extra element return v.size()==1; } }; void solve() { Heap h; int n; cin>>n; for (int i = 0; i < n; ++i) { int no; cin>>no; h.push(no); } while(!h.empty()){ cout<<h.top()<<" "; h.pop(); } } signed main() { yashio(); int T = 1; //cin>>T; while(T--) { solve(); } } void yashio() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input999.txt", "r", stdin); freopen("output999.txt", "w", stdout); #endif }
a9b5b16876ab0cc55e4750ffbbe1a6e6653a434d
e5529d3d1fe1fe76eef924cb0879d6e062f9ecfb
/mpi/cross-gpu/main.cpp
2be978685a22c40f7f2d72c5d7c3e2d4f3b8214e
[]
no_license
yuq/compute
b09b2a94a479c9eb8a9e651c59b287ef9d875800
91b3727ee3d80d1b61c957d2d3b743ac442c8dec
refs/heads/master
2023-06-07T20:51:03.061806
2023-05-27T03:57:48
2023-05-27T03:57:48
150,856,469
3
1
null
null
null
null
UTF-8
C++
false
false
1,786
cpp
main.cpp
#include <stdio.h> #include <assert.h> #include <stdlib.h> #include <mpi.h> #include <hip/hip_runtime.h> #define CHECK(cmd) \ { \ hipError_t error = cmd; \ if (error != hipSuccess) { \ fprintf(stderr, "error: '%s'(%d) at %s:%d\n", \ hipGetErrorString(error), error,__FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } #define BUFFER_SIZE 0x400000 void sender(void) { hipDeviceProp_t props; CHECK(hipGetDeviceProperties(&props, 0)); CHECK(hipSetDevice(0)); printf("info: running on device %s\n", props.name); char *h_buffer = (char *)malloc(BUFFER_SIZE); assert(h_buffer); memset(h_buffer, 0x23, BUFFER_SIZE); char *d_buffer; CHECK(hipMalloc(&d_buffer, BUFFER_SIZE)); CHECK(hipMemcpy(d_buffer, h_buffer, BUFFER_SIZE, hipMemcpyHostToDevice)); MPI_Send(d_buffer, BUFFER_SIZE, MPI_CHAR, 0, 0, MPI_COMM_WORLD); } void receiver(void) { hipDeviceProp_t props; CHECK(hipGetDeviceProperties(&props, 1)); CHECK(hipSetDevice(1)); printf("info: running on device %s\n", props.name); char *d_buffer; CHECK(hipMalloc(&d_buffer, BUFFER_SIZE)); MPI_Status status; MPI_Recv(d_buffer, BUFFER_SIZE, MPI_CHAR, 1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); char *result = (char *)malloc(BUFFER_SIZE); assert(result); CHECK(hipMemcpy(result, d_buffer, BUFFER_SIZE, hipMemcpyDeviceToHost)); for (int i = 0; i < BUFFER_SIZE; i++) { if (result[i] != 0x23) { printf("fail\n"); return; } } printf("pass\n"); } int main(int argc, char **argv) { int pid=-1, np=-1; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &pid); MPI_Comm_size(MPI_COMM_WORLD, &np); MPI_Barrier(MPI_COMM_WORLD); if (pid) sender(); else receiver(); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); return 0; }
237529602826ccda5c9dee0e16e3bc0c9130f5b9
2992e854a02cbc10d57c85c7d4b07a7e3e2ab7d4
/백준/Silver/2579. 계단 오르기/계단 오르기.cc
2e3427b839f63691e73d8a8164cd74e592e4253b
[ "MIT" ]
permissive
getCurrentThread/Algorithm
81794cc42f7037ccf0c0e46da23a53ff226e4580
f86ee8d5467e595fe5121542c6a31a1239ba08ef
refs/heads/master
2023-04-28T08:10:41.140117
2023-04-16T13:44:48
2023-04-16T13:44:48
237,871,919
0
0
MIT
2022-01-09T10:33:08
2020-02-03T02:42:44
null
UTF-8
C++
false
false
545
cc
계단 오르기.cc
#include <iostream> #include <algorithm> #define MAX 300 using namespace std; int n; int stair[MAX+1]; int dp[MAX+1]; int func(int n) { dp[0] = stair[0]; dp[1] = stair[0] + stair[1]; dp[2] = max(stair[0] + stair[2], stair[1] + stair[2]); for (int i = 3; i < n; i++) { dp[i] = max(dp[i - 2] + stair[i] ,dp[i - 3] + stair[i - 1] + stair[i]); } return dp[n-1]; } int main() { scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%d", &stair[i]); } printf("%d", func(n)); return 0; }
5f37395550008039ce3bac18622a7cb8005bc9f5
ed75b1d4d9eb83a98f0688ae90418a8399c5cf7c
/Contests/Codechef/accepted/voters.cpp
8372a3885ba21184a0c3916fd6108ef45e22a00e
[]
no_license
vivekp/C-and-Cplusplus-Programs
df762698dcb1a4f3e0e378bf9f71ddb837ea959d
a79e49d57ce590bd1de4e31e56bae0db095eeca1
refs/heads/master
2016-08-08T03:22:10.805674
2011-11-11T14:39:23
2011-11-11T14:53:19
2,756,339
1
2
null
null
null
null
UTF-8
C++
false
false
537
cpp
voters.cpp
/* * CODE: VOTERS */ #include <iostream> #include <map> #include <iterator> using namespace std; typedef map< int, int , less<int> > Map; int main() { Map id; int N1, N2, N3; cin >> N1 >> N2 >> N3; long total = N1 + N2 + N3; int key; long count = 0; for(int i = 0 ; i < total; ++i) { cin >> key; if(id[key] == 1) count++; id[key]++; } cout << count << endl; Map::iterator iter; for (iter = id.begin(); iter != id.end(); iter++ ) { if ( (iter->second) >= 2) cout << iter->first << endl; } return 0; }
87ad7938fd8954e6ebeb8a3f4c6c0122c948dc49
53697ba06cea725839a5011b8a1adbea852e8a7f
/dynamic_programming/17_dp_coin_min_coins.cpp
305383ef53ec56754a67b404d8aa112f35e89d21
[]
no_license
harshithkrpt/algorithms
4b712ad7fe259d9197a9be41860738bd63b772a5
751b162f8ca370a29715c2850ce776b902e751c3
refs/heads/master
2020-07-31T12:36:50.218165
2020-06-21T18:03:06
2020-06-21T18:03:06
210,606,507
0
0
null
null
null
null
UTF-8
C++
false
false
590
cpp
17_dp_coin_min_coins.cpp
#include<bits/stdc++.h> using namespace std; int minCoins(int coins[],int m,int V) { int table[V+1]; // o coins are required to make the sum 0 table[0] = 0; for(int i=1;i<=V;i++) table[i] = INT_MAX; for(int i=1;i<=V;i++) { for(int j=0;j<m;j++) { if(coins[j] <= i) { int sub_res = table[i-coins[j]]; if(sub_res != INT_MAX && sub_res + 1 < table[i]) { table[i] = sub_res + 1; } } } } return table[V]; } int main() { int coins[] = {9,6,5,1}; int m = sizeof(coins)/sizeof(coins[0]); int v = 11; cout << minCoins(coins,m,v); return 0; }
5a1746ad629440c1544f9651dead24ddd0bd5c35
3113b3ed92063987040a652a1ca19231c33afc2c
/Stone Age/Stone Age - Qt Application/model/Places/HutPlace.cpp
ea9d0512fa56c7d522eda0b5cd498585956ba9d2
[]
no_license
kristofleroux/uh-ogp1-project
1e61a198219e6d7ee62b3a67847e40ccc34b66ba
90047d39eb4cc14df9815decc472caf86a05d7b5
refs/heads/master
2022-01-24T23:07:06.643206
2019-07-16T08:44:41
2019-07-16T08:44:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
HutPlace.cpp
#include "HutPlace.h" #include "../../config.h" #include "../PlayerBoard.h" #include "../Player.h" #include "../Game.h" #include "../PlayerBoardItems/Worker.h" #include "../PlayerBoardItems/Workers.h" // Constructor HutPlace::HutPlace(QString name, int maximumWorkerAmount, Game* game) : Place (name, maximumWorkerAmount, game) {} // Utils void HutPlace::calculateMaterials(Player *player, int currentWorkers) { PlayerBoard* playerBoard{player->getPlayerBoard()}; playerBoard->getWorkers()->increaseWorkersCapacity(currentWorkers/2); playerBoard->updatePlayerBoard(); }
439c7a429f85d1c058bdeb5f823f4982f849a85f
2f48a6e0779d24d309d42220912320c0afa415d7
/boost/numeric/ublasx/operation/sum.hpp
3a022c7efd8899c460cae0e77dd129e07c1e9841
[ "BSL-1.0" ]
permissive
sguazt/boost-ublasx
da6cbca6d8a0a85db1c64f7beb93dbf0da013ecd
21c9b393d33a6ec2a8071ba8d48680073d766409
refs/heads/master
2021-01-21T21:45:36.712354
2021-01-06T10:26:05
2021-01-06T10:26:05
5,560,736
8
1
BSL-1.0
2020-12-28T18:31:16
2012-08-26T14:43:05
C++
UTF-8
C++
false
false
11,907
hpp
sum.hpp
/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */ /** * \file boost/numeric/ublasx/operation/sum.hpp * * \brief The \c sum operation. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * Copyright (c) 2010, Marco Guazzone * * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_NUMERIC_UBLASX_OPERATION_SUM_HPP #define BOOST_NUMERIC_UBLASX_OPERATION_SUM_HPP #include <boost/numeric/ublas/detail/config.hpp> #include <boost/numeric/ublas/expression_types.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/numeric/ublasx/operation/begin.hpp> #include <boost/numeric/ublasx/operation/end.hpp> #include <boost/numeric/ublasx/operation/num_columns.hpp> #include <boost/numeric/ublasx/operation/num_rows.hpp> #include <boost/numeric/ublasx/operation/size.hpp> #include <boost/numeric/ublas/traits.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_expression.hpp> #include <cstddef> namespace boost { namespace numeric { namespace ublasx { using namespace ::boost::numeric::ublas; //@{ Declarations //XXX: already implemented in vector_expression.hpp ///** // * \brief Compute the sum of the elements of the given vector expression. // * \tparam VectorExprT The type of the vector expression. // * \param ve The vector expression whose elements are summed up. // * \return The sum of the elements of the vector expression. // * // * \author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt; // */ //template <typename VectorExprT> //typename vector_traits<VectorExprT>::value_type sum(vector_expression<VectorExprT> const& ve); using ::boost::numeric::ublas::sum; /** * \brief Compute the sum of the elements of the given matrix expression. * \tparam MatrixExprT The type of the matrix expression. * \param ve The matrix expression whose elements are summed up. * \return The sum of the elements of the matrix expression. * * \author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt; */ template <typename MatrixExprT> typename matrix_traits<MatrixExprT>::value_type sum_all(matrix_expression<MatrixExprT> const& me); /** * \brief Compute the sum of the elements over each column of the given matrix * expression. * \tparam MatrixExprT The type of the matrix expression. * \param me The matrix expression whose elements are summed up by row. * \return A vector containing the sum of the elements over each column in the * given matrix expression. * * \author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt; */ template <typename MatrixExprT> vector<typename matrix_traits<MatrixExprT>::value_type> sum(matrix_expression<MatrixExprT> const& me); /** * \brief Compute the sum of the elements over each column in the given matrix * expression. * \tparam MatrixExprT The type of the matrix expression. * \param me The matrix expression whose elements are summed up by row. * \return A vector containing the sum of the elements over each column in the * given matrix expression. * * \author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt; */ template <typename MatrixExprT> vector<typename matrix_traits<MatrixExprT>::value_type> sum_rows(matrix_expression<MatrixExprT> const& me); /** * \brief Compute the sum of the elements over each row in the given matrix * expression. * \tparam MatrixExprT The type of the matrix expression. * \param me The matrix expression whose elements are summed up by column. * \return A vector containing the sum of the elements over each row in the * given matrix expression. * * \author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt; */ template <typename MatrixExprT> vector<typename matrix_traits<MatrixExprT>::value_type> sum_columns(matrix_expression<MatrixExprT> const& me); /** * \brief Compute the sum of the elements of the given matrix expression along * the given dimension tag. * \tparam MatrixExprT The type of the matrix expression. * \param me The matrix expression whose elements are summed up by the given * dimension. * \return A vector containing the sum of the elements along the given dimension * in the given matrix expression. * * \author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt; */ template <typename TagT, typename MatrixExprT> vector<typename matrix_traits<MatrixExprT>::value_type> sum_by_tag(matrix_expression<MatrixExprT> const& me); //@} Declarations namespace detail { //@{ Declarations /** * \brief Auxiliary class for computing the sum of the elements along the given * dimension for a container of the given category. * \tparam Dim The dimension number (starting from 1). * \tparam CategoryT The category type (e.g., vector_tag). */ template < ::std::size_t Dim, typename CategoryT> struct sum_by_dim_impl; /** * \brief Auxiliary class for computing the sum of the elements along the given * dimension tag for a container of the given category. * \tparam TagT The dimension tag type (e.g., tag::major). * \tparam CategoryT The category type (e.g., vector_tag). * \tparam OrientationT The orientation category type (e.g., row_major_tag). */ template <typename TagT, typename CategoryT, typename OrientationT> struct sum_by_tag_impl; //@} Declarations //@{ Definitions template <> struct sum_by_dim_impl<1, vector_tag> { template <typename VectorExprT> BOOST_UBLAS_INLINE static vector<typename vector_traits<VectorExprT>::value_type> apply(vector_expression<VectorExprT> const& ve) { typedef typename vector_traits<VectorExprT>::value_type value_type; vector<value_type> res(1); res(0) = sum(ve); return res; } }; template <> struct sum_by_dim_impl<1, matrix_tag> { template <typename MatrixExprT> BOOST_UBLAS_INLINE static vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me) { return sum_rows(me); } }; template <> struct sum_by_dim_impl<2, matrix_tag> { template <typename MatrixExprT> BOOST_UBLAS_INLINE static vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me) { return sum_columns(me); } }; template <> struct sum_by_tag_impl<tag::major, matrix_tag, row_major_tag> { template <typename MatrixExprT> BOOST_UBLAS_INLINE static vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me) { return sum_rows(me); } }; template <> struct sum_by_tag_impl<tag::minor, matrix_tag, row_major_tag> { template <typename MatrixExprT> BOOST_UBLAS_INLINE static vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me) { return sum_columns(me); } }; template <> struct sum_by_tag_impl<tag::leading, matrix_tag, row_major_tag> { template <typename MatrixExprT> BOOST_UBLAS_INLINE static vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me) { return sum_columns(me); } }; template <> struct sum_by_tag_impl<tag::major, matrix_tag, column_major_tag> { template <typename MatrixExprT> BOOST_UBLAS_INLINE static vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me) { return sum_columns(me); } }; template <> struct sum_by_tag_impl<tag::minor, matrix_tag, column_major_tag> { template <typename MatrixExprT> BOOST_UBLAS_INLINE static vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me) { return sum_rows(me); } }; template <> struct sum_by_tag_impl<tag::leading, matrix_tag, column_major_tag> { template <typename MatrixExprT> BOOST_UBLAS_INLINE static vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me) { return sum_rows(me); } }; template <typename TagT> struct sum_by_tag_impl<TagT, matrix_tag, unknown_orientation_tag>: sum_by_tag_impl<TagT, matrix_tag, row_major_tag> { // Empty }; //@} Definitions } // Namespace detail //@{ Definitions //XXX: already implemented in vector_expression.hpp //template <typename VectorExprT> //BOOST_UBLAS_INLINE //typename vector_traits<VectorExprT>::value_type sum(vector_expression<VectorExprT> const& ve) //{ // typedef typename vector_traits<VectorExprT>::const_iterator iterator_type;; // typedef typename vector_traits<VectorExprT>::value_type value_type; // // iterator_type it_end = end(ve); // value_type s = 0; // // for (iterator_type it = begin(ve); it != it_end; ++it) // { // s += *it; // } // // return s; //} template <typename MatrixExprT> BOOST_UBLAS_INLINE typename matrix_traits<MatrixExprT>::value_type sum_all(matrix_expression<MatrixExprT> const& me) { typedef typename matrix_traits<MatrixExprT>::size_type size_type; typedef typename matrix_traits<MatrixExprT>::value_type value_type; size_type nr = num_rows(me); size_type nc = num_columns(me); value_type s = 0; for (size_type r = 0; r < nr; ++r) { for (size_type c = 0; c < nc; ++c) { s += me()(r,c); } } return s; } template <typename MatrixExprT> BOOST_UBLAS_INLINE vector<typename matrix_traits<MatrixExprT>::value_type> sum(matrix_expression<MatrixExprT> const& me) { return sum_rows(me); } template <typename MatrixExprT> BOOST_UBLAS_INLINE vector<typename matrix_traits<MatrixExprT>::value_type> sum_rows(matrix_expression<MatrixExprT> const& me) { typedef typename matrix_traits<MatrixExprT>::size_type size_type; typedef typename matrix_traits<MatrixExprT>::value_type value_type; size_type nr = num_rows(me); size_type nc = num_columns(me); vector<value_type> s(nc); size_type j = 0; for (size_type c = 0; c < nc; ++c) { //s(j++) = sum(column(me, c)); //FIXME: don't work value_type cs = 0; for (size_type r = 0; r < nr; ++r) { cs += me()(r,c); } s(j++) = cs; } return s; } template <typename MatrixExprT> BOOST_UBLAS_INLINE vector<typename matrix_traits<MatrixExprT>::value_type> sum_columns(matrix_expression<MatrixExprT> const& me) { typedef typename matrix_traits<MatrixExprT>::size_type size_type; typedef typename matrix_traits<MatrixExprT>::value_type value_type; size_type nr = num_rows(me); size_type nc = num_columns(me); vector<value_type> s(nr); size_type j = 0; for (size_type r = 0; r < nr; ++r) { //s(j++) = sum(row(me, r)); // FIXME don't work value_type rs = 0; for (size_type c = 0; c < nc; ++c) { rs += me()(r,c); } s(j++) = rs; } return s; } template <size_t Dim, typename VectorExprT> BOOST_UBLAS_INLINE vector<typename vector_traits<VectorExprT>::value_type> sum(vector_expression<VectorExprT> const& ve) { return detail::sum_by_dim_impl<Dim, vector_tag>::template apply(ve); } template <size_t Dim, typename MatrixExprT> BOOST_UBLAS_INLINE vector<typename matrix_traits<MatrixExprT>::value_type> sum(matrix_expression<MatrixExprT> const& me) { return detail::sum_by_dim_impl<Dim, matrix_tag>::template apply(me); } template <typename TagT, typename MatrixExprT> //template <typename MatrixExprT, typename TagT> BOOST_UBLAS_INLINE vector<typename matrix_traits<MatrixExprT>::value_type> sum_by_tag(matrix_expression<MatrixExprT> const& me) { return detail::sum_by_tag_impl<TagT, matrix_tag, typename matrix_traits<MatrixExprT>::orientation_category>::template apply(me); } //@} Definitions }}} // Namespace boost::numeric::ublasx #endif // BOOST_NUMERIC_UBLASX_OPERATION_SUM_HPP
cf60aa3baa6dd9ead1c15f243ed9e2ca0a928c56
2258b10e8d10343a9dc057019bd8d94ee6d81f6f
/Zara/Parser/IParserState.hpp
c7bd9397135346d94783cffa7e608aea269e77cc
[]
no_license
d0rj/Zara
1e0d19140a2da8d57b46a322a8f5ccfa9f4536e6
010044009dd97fc33fb0406afffde3e9a4c2e155
refs/heads/master
2023-02-06T14:44:55.794736
2020-12-23T17:08:16
2020-12-23T17:08:16
258,433,907
0
0
null
null
null
null
UTF-8
C++
false
false
146
hpp
IParserState.hpp
#pragma once #include <string> #include <vector> namespace Zara { class IParserState { public: virtual void NextChar(char ch) = 0; }; }
444694b0e4492e40bbe7a1184e47e1778d5d8049
79625fb9eeba05cf4dfc124c2f69d73e2a383d31
/db/detail/transaction.hpp
bcb5027f0fa85b86c75b42e7406c4086b5b9f1fe
[ "MIT" ]
permissive
beikehanbao23/bark
f152c4a4c697316d160f1b1b09731f40441e47ba
e4cd481183aba72ec6cf996eff3ac144c88b79b6
refs/heads/master
2023-03-23T00:47:39.777260
2021-01-16T10:10:23
2021-01-16T10:10:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
671
hpp
transaction.hpp
// Andrew Naplavkov #ifndef BARK_DB_TRANSACTION_HPP #define BARK_DB_TRANSACTION_HPP namespace bark::db { template <class T> class transaction { T& as_mixin() { return static_cast<T&>(*this); } protected: void set_autocommit(bool autocommit) { if (autocommit_ != autocommit) { exec(as_mixin(), autocommit ? "ROLLBACK" : "BEGIN"); autocommit_ = autocommit; } } void commit() { if (!autocommit_) { exec(as_mixin(), "COMMIT"); exec(as_mixin(), "BEGIN"); } } private: bool autocommit_ = true; }; } // namespace bark::db #endif // BARK_DB_TRANSACTION_HPP
4808de6b26fd85475c553b26a12a415a66a72a84
9f9eaffc00ceead522382e4c4dd485eca114896e
/Chapter12/12_4.cpp
6ee3f3cda0045c1cc656bc61477283c4bfc00d25
[]
no_license
sarahannali/elementsofprogramming
f62757476b229e36d5015069f80800bd010b4bdc
6bf6cf5c6e6a6168ea1169fd1234641cbd7b8f5c
refs/heads/master
2022-11-10T18:01:45.169195
2020-07-06T00:19:55
2020-07-06T00:19:55
275,467,608
0
0
null
null
null
null
UTF-8
C++
false
false
443
cpp
12_4.cpp
#include <iostream> #include <vector> using namespace std; int IntRoot(int square) { int L = 0, U = square; while (L <= U) { int M = L + (U - L) / 2; if ((M * M) > square) { U = M - 1; } else if ((M * M) < square) { L = M + 1; } else { return M; } } return U; } int main() { cout << IntRoot(300); }
77b822c13a15d5c9df197a0d59f81da2bd15fc22
ddc210a05032afc83109cb5690e1203a5b481c97
/include/tcprelay.hpp
90b1fbd13562dc60450a3484dc46e470d4a81310
[]
no_license
litao91/shadowc
63ea4c662df9439bdbe249b77e6364886807527a
51235b9b443d69a5da72bef4412b518c42b70b0c
refs/heads/master
2020-06-10T01:16:10.094704
2017-05-18T12:17:23
2017-05-18T12:17:23
76,118,357
1
0
null
null
null
null
UTF-8
C++
false
false
1,309
hpp
tcprelay.hpp
#ifndef SHADOW_C_TCPRELAY_H__ #define SHADOW_C_TCPRELAY_H__ #include "eventloop.hpp" #include "asyncdns.hpp" namespace tcprelay { class TCPRelay; class TCPRelayHandler; typedef std::map<int, TCPRelayHandler*> fd_to_handlers_t; class TCPRelayHandler { public: TCPRelayHandler( TCPRelay* tcp_relay, fd_to_handlers_t* fd_to_handlers, eventloop::EventLoop* loop, int local_sock, asyncdns::DNSResolver* dns_resolver); ~TCPRelayHandler(); void handle_event(const epoll_event* evt); private: TCPRelay* tcp_relay; int local_socket; asyncdns::DNSResolver* dns_resolver; fd_to_handlers_t* fd_to_handlers; }; /** * TCPRelay, server only */ class TCPRelay: public eventloop::EventHandler { public: TCPRelay(asyncdns::DNSResolver* dns_resolver, const char* server, const char* server_port); virtual ~TCPRelay(); void add_to_loop(eventloop::EventLoop* loop); virtual void handle_event(const epoll_event* evt); private: void sweep_timeout(); int server_socket; eventloop::EventLoop* loop; bool closed; fd_to_handlers_t fd_to_handlers; asyncdns::DNSResolver* dns_resolver; }; } #endif
16a8824d61c86cc4412d00a929bd3ace4477015c
74837c92508b3190f8639564eaa7fa4388679f1d
/xic/include/fio_nametab.h
f6be32f60cb3193d76618e76c01207fb9f222c8a
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
frankhoff/xictools
35d49a88433901cc9cb88b1cfd3e8bf16ddba71c
9ff0aa58a5f5137f8a9e374a809a1cb84bab04fb
refs/heads/master
2023-03-21T13:05:38.481014
2022-09-18T21:51:41
2022-09-18T21:51:41
197,598,973
1
0
null
2019-07-18T14:07:13
2019-07-18T14:07:13
null
UTF-8
C++
false
false
6,013
h
fio_nametab.h
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * Xic Integrated Circuit Layout and Schematic Editor * * * *========================================================================* $Id:$ *========================================================================*/ #ifndef FIO_NAMETAB_H #define FIO_NAMETAB_H #include "fio_cxfact.h" //----------------------------------------------------------------------------- // nametab_t // This is a hash table used in cCHD and in the archive read // functions. The elements are symref_t that are allocated and // deallocated through cx_fact_t. //----------------------------------------------------------------------------- // Table element for numtab_t. // struct nt_t { friend struct numtab_t; uintptr_t tab_key() { return (num); } void set_tab_next(nt_t *n) { next = n; } nt_t *tab_next() { return (next); } private: uintptr_t num; nt_t *next; symref_t *symref; }; struct nametab_t; // CIF symbol number hash table. // struct numtab_t { numtab_t() { nt_table = new itable_t<nt_t>; } inline numtab_t(nametab_t*); ~numtab_t() { delete nt_table; } symref_t *get(int k) { nt_t *n = nt_table->find(k); return (n ? n->symref : 0); } void add(symref_t *p) { int num = p->get_num(); nt_t *e = nt_table->find(num); if (!e) { e = nt_elts.new_element(); e->num = num; e->next = 0; e->symref = p; nt_table->link(e, false); nt_table = nt_table->check_rehash(); } } private: itable_t<nt_t> *nt_table; eltab_t<nt_t> nt_elts; }; // The names in the nametab (symref_t names) are all hashed in the // string table, so address comparisons are used for equality testing. struct nametab_t : public cxfact_t { friend struct namegen_t; nametab_t(DisplayMode m) { nm_table = new itable_t<symref_t>; nm_elec_mode = (m == Electrical); } ~nametab_t() { delete nm_table; } void add(symref_t *srf) { if (!srf) return; nm_table->link(srf, false); nm_table = nm_table->check_rehash(); } symref_t *get(CDcellName name) { if (name) return (nm_table->find((uintptr_t)name)); return (0); } symref_t *unlink(symref_t *srf) { return (nm_table->unlink(srf)); } size_t memuse() { size_t base = sizeof(this) + sizeof(itable_t<symref_t>) + (nm_table->hashwidth() - 1)*sizeof(symref_t*); base += data_memuse(); return (base); } private: itable_t<symref_t> *nm_table; bool nm_elec_mode; // Set when this table references Electrical cells. }; struct namegen_t : tgen_t<symref_t> { namegen_t(nametab_t *st) : tgen_t<symref_t>(st->nm_table) { } }; inline numtab_t::numtab_t(nametab_t *nametab) { nt_table = new itable_t<nt_t>; namegen_t ngen(nametab); symref_t *sref; while ((sref = ngen.next()) != 0) { nt_t *n = nt_elts.new_element(); n->num = sref->get_num(); n->symref = sref; n->set_tab_next(0); nt_table->link(n, false); nt_table = nt_table->check_rehash(); } } #endif
00836556d70e8c3ce0cf20c5f5c656a1d3140b5e
1bdce38606736fd064a44fdb4aefb3d51aeb5724
/client/ftpclient/globalsettings.cpp
69b4ab2c13926663b758a9e0624625f3449e960b
[]
no_license
llylly/FTP_Project
fbb7c5dc0c0cedc33bc88a00a6296b476cdc42b8
5cae5b03501d305b392c6e5ce05b157f219a873b
refs/heads/master
2021-07-25T01:18:14.789214
2016-12-18T14:03:10
2016-12-18T14:03:10
109,551,291
0
0
null
null
null
null
UTF-8
C++
false
false
365
cpp
globalsettings.cpp
#include "globalsettings.h" GlobalSettings::GlobalSettings() { } sockaddr *GlobalSettings::genSockAddr(char *_ip, ushort _port) { sockaddr_in *myaddr = new sockaddr_in(); myaddr->sin_family = AF_INET; myaddr->sin_port = htons(_port); myaddr->sin_addr.s_addr = inet_addr(_ip); memset(&(myaddr->sin_zero), 0, 8); return (sockaddr*)myaddr; }
05c5037df2774fefa94ef22ac8cbbcf063b858ac
c690bb35e6f0aab50b57737189354281c75cf3a9
/백준알고리즘/단계별로 풀어보기/15. 동적 계획법1/P_Number_2579.cpp
48065dc85baf5778f45fbda90fce87d37372bf0f
[]
no_license
lazybones1/Algorithms
e8abf1bb0e3065012fa4b32b2d8794a17833eded
458ca23761f72cdb7bd5c279f53d3f4e195964a7
refs/heads/master
2021-05-23T15:46:41.207332
2020-08-20T11:00:10
2020-08-20T11:00:10
253,366,607
0
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
P_Number_2579.cpp
#include <iostream> #include <cmath> #include <algorithm> using namespace std; int n; int dp[300]; int stairs[300]; int ans() { for (int i = 0; i < n; i++) { if (i == 0) { dp[i] = stairs[i]; } else if (i == 1) { dp[i] = max(stairs[i-1] + stairs[i], stairs[i]); } else if (i == 2) { dp[2] = max(stairs[i-2] + stairs[i], stairs[i-1] + stairs[i]); } else dp[i] = max(dp[i - 2] + stairs[i], dp[i - 3] + stairs[i - 1] + stairs[i]); } return dp[n-1]; } int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> stairs[i]; } int answer = ans(); cout << answer; return 0; }
8a583adb5cd90e394f5037ae16562973bd4cded1
e61a0ebe93280719d9bb34cac52d772f0d814e5f
/BC2016_7_23/A.cpp
f7b0bb38421de1b53ac99c73ceca7bc9d955982a
[]
no_license
zhouwangyiteng/ACM_code
ba5df2215500a1482cf21362160ddbf71be0196d
ca3e888bd4908287dd822471333a38c24b0a05db
refs/heads/master
2020-04-12T06:35:10.160246
2017-04-22T07:44:09
2017-04-22T07:44:09
61,373,600
0
0
null
null
null
null
UTF-8
C++
false
false
1,218
cpp
A.cpp
/************************************************************************* > File Name: A.cpp > Author: > Mail: > Blog: > Created Time: 2016年07月23日 星期六 19时11分09秒 ************************************************************************/ #include <iostream> #include <cstdio> #include <vector> #include <map> #include <queue> #include <stack> #include <algorithm> #include <cmath> #include <ctime> #include <string> #include <cstring> #include <set> #include <bitset> using namespace std; #define X first #define Y second #define ll long long #define INF 0x3f3f3f #define MAXN 100000 #define PB(X) push_back(X) #define MP(X,Y) make_pair(X,Y) #define REP(x,y) for(int x=0;x<y;x++) #define RDP(x,y) for(int x=y;x>=0;x--) #define RRP(x,L,R) for(int x=L;x<=R;x++) #define CLR(A,X) memset(A,X,sizeof(A)) ll t,n,m,ans; ll pow(ll a,ll n) { ll res=1; while(n) { if(n&1) res=res*a; a=a*a; n>>=1; } return res; } int main() { cin>>t; while(t--) { cin>>n>>m; ans=0; if(m>(int)(log(1.0*n)/log(2.0)+1)) m=(int)(log(1.0*n)/log(2.0)+1); while(m>=0) { ll tmp=pow(2,m); if(tmp<=n) { ans+=n/tmp; n=n%tmp; } m--; } cout<<ans<<endl; } return 0; }
fae8898b8eb163a32dea3d549a0467ca423d10bf
97163be23ec46d35737c9e41aa34107479d1e323
/Dynamic Programming/minimumNumberOfJumps.cpp
4266ebe86e83f09e2d9fdd156cc94e1412bca2da
[]
no_license
Kamrul-Hasan-1971/Code
54612faea047f523306158bd936850a2c599ef3e
7ca4da7b1e23a3c3fef06f598f11ba83054373ae
refs/heads/master
2023-09-02T09:06:05.462951
2021-11-05T06:53:18
2021-11-05T06:53:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
872
cpp
minimumNumberOfJumps.cpp
#include <iostream> #include <algorithm> #include <climits> #include <cstring> using namespace std; long int minSteps(int i, long int minimumSteps[], int arr[], int n){ if(minimumSteps[i] != -1) return minimumSteps[i]; if(arr[i] == 0) return minimumSteps[i] = INT_MAX; long int minimumStep = INT_MAX; for(int j = 1; j <= arr[i]; j++){ if(i+j == n-1) return minimumSteps[i] = 1; minimumStep = min(minimumStep,minSteps(i+j,minimumSteps,arr,n)); } return minimumSteps[i] = 1 + minimumStep; } int main(){ int t; cin >> t; while(t--){ int n,i; cin >> n; int arr[n]; for(i = 0; i < n; i++) cin >> arr[i]; long int minimumSteps[n]; memset(minimumSteps,-1,sizeof(minimumSteps)); long int minimumStep = minSteps(0,minimumSteps,arr,n); if(minimumStep > 1e7) cout << -1 << "\n"; else cout << minimumStep << "\n"; } }
ad20e6e0fc73e41fcd71bdf25a878362983b9f45
2cdd1bdd1f8e3febe7e0be2efd9a490b3b3cb14e
/Return the longest run of 1s for a given integer n's binary representation.cpp
7c63bdf783caab723b5cfb3239d2c55d3ad9c692
[]
no_license
ashiscs/C-
4a33168e80877d4a1429fa352588b0a9c3dc2fdf
0e2a1bd15f7ed2b722ec84ced69cc877b51951eb
refs/heads/master
2020-09-03T16:00:39.949895
2020-05-10T15:38:38
2020-05-10T15:38:38
219,504,612
1
0
null
null
null
null
UTF-8
C++
false
false
237
cpp
Return the longest run of 1s for a given integer n's binary representation.cpp
#include<iostream> using namespace std; int main() { int n,flag=0; cout<<"Enter a number\n"; cin>>n; while(n!=0) { n=(n&(n<<1)); flag++; } cout<<"Result:"<<flag; return 0; }
88f40dc11db8a9beddcf534d3fd15bde1ab8a9e6
8642c2865a417d402f12ff38e417874dac4ed0f5
/test_factory_2.cpp
b46398b5cc34e9caa12c1bdf64f8ee7a701503c3
[]
no_license
Neplex/symmetrical-guacamole
23fcac0b0ce407600a22fc5fd39d5117cc85832f
f5cf165f15ae3897172c78dc2e3fcdeba479cacf
refs/heads/master
2021-05-01T01:00:27.297999
2016-12-02T14:33:18
2016-12-02T14:33:18
75,391,197
0
0
null
null
null
null
UTF-8
C++
false
false
751
cpp
test_factory_2.cpp
/*! * \file * \brief * This module provides more tests for the factory. * * \author PASD * \date 2016 */ #include <iostream> #include "factory_shape.hpp" #include <assert.h> #define NDEBUG 1 using namespace std; int main() { Factory_Shape &s_f = Factory_Shape::ref(); U_Sh_d_Stack c_s; c_s.push(s_f.create_shape("square", c_s)); c_s.push(10); c_s.push(s_f.create_shape("scale", c_s)); c_s.push(s_f.create_shape("circle", c_s)); c_s.push(20); c_s.push(s_f.create_shape("scale", c_s)); c_s.push(s_f.create_shape("difference", c_s)); Shape *s = c_s.pop_shape(); assert(NULL != s); cout << s->contains(0, 0) << ' ' << s->contains(-1, 1) << ' ' << s->contains(2, 2) << ' ' << endl; delete s; return 0; }
37a6e8c875078e6227d8c1d53a483637ac4b7eae
148b778983b0df3328adb85cdb5e046c8be6a4d6
/2_math/prime_sum.cpp
4c336822296818c55e3d19a7fe02bbaffe1132b4
[]
no_license
mascai/exercise
9dcbdca7038ca9b02b1bf9abc0ead354f4e06ba1
c58912261126ae3ed4b44cb466344f4b8c4d8c6c
refs/heads/master
2023-06-24T12:15:32.170458
2023-06-08T18:20:19
2023-06-08T18:20:19
95,127,196
1
1
null
null
null
null
UTF-8
C++
false
false
383
cpp
prime_sum.cpp
bool is_prime(int n) { if (n < 2) { return false; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } vector<int> Solution::primesum(int n) { for (int i = 2; i <= n / 2; i++) { if (is_prime(i) && is_prime(n - i)) { return {i, n - i}; } } return {}; }
5f84e32003391463e3d982d1f863429ed6aed3d7
3927eb7aaa3cfa45ffc57f0a7a6b00417a720fea
/URI/01259-pares_e_impares.cpp
2b8d54471ac875ccdbeace3ea2f798e96e5b3226
[]
no_license
jbsilva/Programming_Challenges
c2e5ee12bf3d2f17ce9b907447cd2c27d6198d7f
889274951b1bbb048e8ea3a4843fac97ce6a95e3
refs/heads/main
2021-07-07T06:13:04.748780
2021-05-02T20:29:38
2021-05-02T20:29:38
49,593,340
2
2
null
null
null
null
UTF-8
C++
false
false
1,286
cpp
01259-pares_e_impares.cpp
// ============================================================================ // // Filename: 01259-pares_e_impares.cpp // // Description: URI 1259 - Pares e Ímpares // // Version: 1.0 // Created: 29/Oct/2012 15:11:22 // Revision: none // Compiler: g++ // // Author: Julio Batista Silva (351202), julio(at)juliobs.com // Company: UFSCar // // ============================================================================ #include <cstdio> #include <cstdlib> inline int comp_int(const void* a, const void* b) { // Nao vai dar overlow, pois a > 0 e b > 0 return (*(int*)a - * (int*)b); } int main() { int n, num, qtd_p = 0, qtd_i = 0; int pares[1000001], impares[1000001]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &num); if (num % 2) { impares[qtd_i] = num; qtd_i++; } else { pares[qtd_p] = num; qtd_p++; } } qsort(pares, qtd_p, sizeof(int), comp_int); qsort(impares, qtd_i, sizeof(int), comp_int); for (int i = 0; i < qtd_p; i++) printf("%d\n", pares[i]); for (int i = qtd_i - 1; i >= 0; i--) printf("%d\n", impares[i]); return 0; }
a574d02640bc386c99ab7568b787ddfa6e81de1b
6f689340d42631bcdadcadf0fee78245e427f702
/Untitled2.cpp
0f9e104544c2d3927039d9a4fe62e663046aa2d9
[]
no_license
lythaiho/LapTrinh
788c6aadb13541d2e14500acc42dec3f4714c075
768b3c6ac1cd63eb6ff4a7d442e0fe56169542e5
refs/heads/master
2020-05-16T16:33:47.004189
2019-07-10T09:41:13
2019-07-10T09:41:13
183,166,052
0
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
Untitled2.cpp
#include<stdio.h> int isPrime(int a){ if(a<=1){ return 0; } else{ int dem=0; for(int i=1;i<a;i++){ if(a%i==0){ dem++; } } if(dem=1){ return 1; }else{ return 0; } } } int main(){ int n,m; printf("n = "); scanf("%d",&n); printf("m = "); scanf("%d",&m); for(int j=n;j<m;j++){ if(isPrime(j)==1){ printf("%d \n",j); } } }
ea76e17403b633b3b4b0dd0c8cb694b41d1b017b
cbd5b0ad46993204ac0d04e0338b17c3bebbb1d6
/ED2_2018-PARTE_2/include/Deputado.h
de090b11bc744029adede230e85d155e0e0409a5
[]
no_license
avmhdt/Trabalho_ED2_Final
aae21e183d8a5345ca573a3432cb06558ae47dfa
b8d5bb194f6f938ebfbc34c63cbe7437b16d7145
refs/heads/master
2020-04-01T08:46:08.014173
2018-10-15T03:15:59
2018-10-15T03:15:59
153,045,952
0
1
null
null
null
null
UTF-8
C++
false
false
1,290
h
Deputado.h
#include <iostream> #ifndef DEPUTADO_H #define DEPUTADO_H using namespace std; class Deputado { public: Deputado(); Deputado(string nome, int id, string partido, int valor); ~Deputado(); void setNome_deputado(string nome); void setPartido(string partido); void setId(int id); void setValor(int valor); void setBugged_date(string bugged_date); void setReceipt_date(string receipt_date); void setEstado(string estado); void setReceipt_social_security_number(string receipt_social_security_number); void setReceipt_description(string receipt_description); void setEstablishment_name(string establishment_name); string getNome_deputado(); string getPartido(); int getId(); int getValor(); string getBugged_date(); string getReceipt_date(); string getEstado(); string getReceipt_social_security_number(); string getReceipt_description(); string getEstablishment_name(); private: string nome; string partido; int id; int valor; string bugged_date; string receipt_date; string estado; string receipt_social_security_number; string receipt_description; string establishment_name; }; #endif // DEPUTADO_H
43dc4e6b011aa5af97e0a5df7b3748d0ea2d2994
73d5d540041a20ec61a750bd12d1f2644947544d
/2-5-list-1/main.cpp
35322ed573d49d190f250f006a98db5c65e2f57f
[]
no_license
TuringZhu/opengl-learn
a1492339f6260635aa1c0b77a11f33c063c6cfae
217ed1e8f1fca701c30b9f824ba9172b6510f3e2
refs/heads/main
2023-07-14T15:19:27.543642
2021-08-20T14:03:09
2021-08-20T14:03:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
main.cpp
#include <GLUT/glut.h> // (or others, depending on the system in use) void init () { glClearColor (1.0, 1.0, 1.0, 0.0); // Set display-window color to white. glMatrixMode (GL_PROJECTION); // Set projection parameters. gluOrtho2D (0.0, 200.0, 0.0, 150.0); } void lineSegment () { glClear (GL_COLOR_BUFFER_BIT); // Clear display window. glColor3f (0.0, 0.4, 0.2); // Set line segment color to green. glBegin (GL_LINES); glVertex2i (180, 15); // Specify line-segment geometry. glVertex2i (10, 145); glEnd ( ); glFlush ( ); // Process all OpenGL routines as quickly as possible. } int main (int argc, char** argv) { glutInit(&argc, argv); // Initialize GLUT. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Set display mode. glutInitWindowPosition(50, 100); // Set top-left display-window position. glutInitWindowSize(400, 300); // Set display-window width and height. glutCreateWindow("An Example OpenGL Program"); // Create display window. init(); // Execute initialization procedure. glutDisplayFunc(lineSegment);// Send graphics to display window. glutMainLoop();// Display everything and wait. return 0; }
03e80e637b46873a6ea6a0e664b9c3222b557c95
82bad6410ff283be97c7d39510eb9ca7b10715b6
/src/RA_AchievementSet.cpp
5fd6c0c2e2f3ea1092f1da308a855fc109e847b3
[ "MIT" ]
permissive
gdeOo/RAIntegration
09cd88c92ad48da04363590777468a37b9738b97
19c2e4b98941b2800f65635c357b45d82b51da3d
refs/heads/master
2020-06-08T05:34:57.908923
2019-06-19T02:37:18
2019-06-19T02:37:18
193,168,478
0
0
null
2019-06-21T22:53:32
2019-06-21T22:53:31
null
UTF-8
C++
false
false
3,344
cpp
RA_AchievementSet.cpp
#include "RA_AchievementSet.h" #include "RA_Core.h" #include "RA_Dlg_Achievement.h" // RA_httpthread.h #include "RA_Dlg_AchEditor.h" // RA_httpthread.h #include "RA_md5factory.h" #include "data\GameContext.hh" #include "data\UserContext.hh" #include "services\AchievementRuntime.hh" #include "services\IAudioSystem.hh" #include "services\IConfiguration.hh" #include "services\ILocalStorage.hh" #include "services\ServiceLocator.hh" #include "ui\viewmodels\MessageBoxViewModel.hh" #include "ui\viewmodels\OverlayManager.hh" AchievementSet* g_pCoreAchievements = nullptr; AchievementSet* g_pUnofficialAchievements = nullptr; AchievementSet* g_pLocalAchievements = nullptr; AchievementSet::Type g_nActiveAchievementSet = AchievementSet::Type::Core; AchievementSet* g_pActiveAchievements = g_pCoreAchievements; _Use_decl_annotations_ void RASetAchievementCollection(AchievementSet::Type Type) { if (g_nActiveAchievementSet == Type) return; auto& pAchievementRuntime = ra::services::ServiceLocator::GetMutable<ra::services::AchievementRuntime>(); for (size_t i = 0U; i < g_pActiveAchievements->NumAchievements(); ++i) { const auto& pAchievement = g_pActiveAchievements->GetAchievement(i); if (pAchievement.Active()) pAchievementRuntime.DeactivateAchievement(pAchievement.ID()); } g_nActiveAchievementSet = Type; switch (Type) { case AchievementSet::Type::Core: g_pActiveAchievements = g_pCoreAchievements; break; default: case AchievementSet::Type::Unofficial: g_pActiveAchievements = g_pUnofficialAchievements; break; case AchievementSet::Type::Local: g_pActiveAchievements = g_pLocalAchievements; break; } for (size_t i = 0U; i < g_pActiveAchievements->NumAchievements(); ++i) { auto& pAchievement = g_pActiveAchievements->GetAchievement(i); if (pAchievement.Active()) { // deactivate and reactivate to re-register the achievement with the runtime pAchievement.SetActive(false); pAchievement.SetActive(true); } } } bool AchievementSet::RemoveAchievement(const Achievement* pAchievement) { auto pIter = m_Achievements.begin(); while (pIter != m_Achievements.end()) { if (*pIter == pAchievement) { m_Achievements.erase(pIter); return true; } ++pIter; } return false; } Achievement* AchievementSet::Find(unsigned int nAchievementID) const noexcept { for (auto pAchievement : m_Achievements) if (pAchievement && pAchievement->ID() == nAchievementID) return pAchievement; return nullptr; } size_t AchievementSet::GetAchievementIndex(const Achievement& Ach) { for (size_t nOffset = 0; nOffset < g_pActiveAchievements->NumAchievements(); ++nOffset) { if (&Ach == &GetAchievement(nOffset)) return nOffset; } // Not found return ra::to_unsigned(-1); } void AchievementSet::Clear() noexcept { m_Achievements.clear(); } bool AchievementSet::HasUnsavedChanges() const noexcept { for (auto pAchievement : m_Achievements) { if (pAchievement && pAchievement->Modified()) return true; } return false; }
906e8452da42f643f13ea5e3215599285ca1725c
b5715c5b480271bfd798b731003b3b4a99b92a60
/Source/helper.h
847b09b6e5d6236adcabc664cef6245ee7bae443
[]
no_license
EmilyLijm2009/TheHolograms
a30e6fbc3f36c8160af7279526b7da101024a181
be86e9a201e0a9911a5602948a54b0be5a8879ac
refs/heads/master
2021-07-12T01:30:02.770536
2017-10-11T13:37:15
2017-10-11T13:37:15
106,540,518
0
0
null
null
null
null
UTF-8
C++
false
false
133
h
helper.h
#pragma once typedef int ActorId; class Vec3 { private: float m_x, m_y, m_z; public: Vec3(); Vec3(float x, float y, float z); };
53f972a6ac91b7e0ea32d4a87e13e8cce524c8ee
97c82dabd88d00ecf2107002e1867bd684d2ed6d
/backend.cpp
eedce9dbf9d41863dce7fc079a473c3474ced847
[]
no_license
IvanVasilyev/InTime
d643d3ac5f2de5a0faf581a790047515d387f8d6
296a3596b6e85203ea1fbaade0e24ae0a6ae51cc
refs/heads/master
2020-04-22T04:31:26.827160
2019-04-14T21:33:25
2019-04-14T21:33:25
170,126,097
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
backend.cpp
#include "backend.h" BackEnd::BackEnd(QObject *parent) : QObject (parent) { } QString BackEnd::userName() { return m_userName; } void BackEnd::setUserName(const QString &userName) { if(userName == m_userName) return; m_userName = userName; emit userNameChanged(); }
e4f17c318a15ba5a892679b295ec595880319393
d62d179f9ad43ed22cee561a97c589c90c178cec
/modules/boost/simd/sdk/include/boost/simd/sdk/simd/io.hpp
6e80db604c48cea72ac311f6a9905d71a39a6d65
[ "BSL-1.0" ]
permissive
timblechmann/nt2
89385373c14add7e2df48c9114a93e37a8e6e0cf
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
refs/heads/master
2021-01-16T23:49:00.220699
2013-03-11T09:31:23
2013-03-11T09:31:23
8,702,183
2
0
null
null
null
null
UTF-8
C++
false
false
1,100
hpp
io.hpp
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_SDK_SIMD_IO_HPP_INCLUDED #define BOOST_SIMD_SDK_SIMD_IO_HPP_INCLUDED #include <boost/simd/sdk/simd/native.hpp> #include <boost/fusion/sequence/io/out.hpp> namespace boost { namespace simd { ////////////////////////////////////////////////////////////////////////////// // Stream insertion for swar types ////////////////////////////////////////////////////////////////////////////// template<class S,class E> inline std::ostream& operator<<( std::ostream& os, native<S,E> const & v ) { return boost::fusion::operators::operator<<(os, v); } } } #endif
c4f8e9de517bbd27cc61495008f522d55b4bab64
1ddb37f8e6d2be48d893d9285f426c1e90c33566
/tracker/capture/KinectDisparityCompressor.cpp
8276759ae8b7196e10533f90d6ee3c80097b8799
[ "Apache-2.0" ]
permissive
ttykkala/recon
bd0ce04c78c637648cdceed594661b5059ffaf62
fe73b0f1023ff177e6870ed1426604e380e078b7
refs/heads/master
2021-01-13T09:03:55.094792
2017-06-24T13:46:41
2017-06-24T13:46:41
70,162,184
2
0
null
null
null
null
UTF-8
C++
false
false
3,317
cpp
KinectDisparityCompressor.cpp
/* Copyright 2016 Tommi M. Tykkälä 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 "KinectDisparityCompressor.h" // compress 2x2 disparity blocks using max filter // rationale: in run time 640->320 compression is done in anycase with 2x2 block max filter // the 2x2 blocks here must match runtime 2x2 blocks! void compressDisparity2(Mat &hiresD, Mat &loresD) { unsigned short *dPtr = (unsigned short*)hiresD.ptr(); unsigned short *dLowPtr = (unsigned short*)loresD.ptr(); int widthLow = loresD.cols; int heightLow = loresD.rows; assert(widthLow*2 == hiresD.cols && heightLow*2 == hiresD.rows); int offset = 0; // fill first row of low res disparity by half 2x2 block maximum for (int i = 0; i < widthLow; i++, offset++) { int i2 = 2*i; dLowPtr[offset] = MAX(dPtr[i2],dPtr[i2+1]); } int width = 2*widthLow; // fill full 2x2 blocks by max value for (int j = 1; j < heightLow-1; j++) { for (int i = 0; i < widthLow; i++, offset++) { int i2 = 2*i; int j2 = 2*j-1; int offset2 = i2 + j2 * width; unsigned short m1 = MAX(dPtr[offset2],dPtr[offset2+1]); unsigned short m2 = MAX(dPtr[offset2+width],dPtr[offset2+1+width]); dLowPtr[offset] = MAX(m1,m2); } } // fill last row of low res disparity by half 2x2 block maximum for (int i = 0; i < widthLow; i++, offset++) { int offset2 = 2*i + (2*heightLow-1)*width; dLowPtr[offset] = MAX(dPtr[offset2],dPtr[offset2+1]); } } // decompress 2x2 disparity blocks using 2x2 replication // rationale: in run time 640->320 compression is done in anycase with 2x2 block max filter // the 2x2 blocks here must match runtime 2x2 blocks! void decompressDisparity2(Mat &loresD, Mat &hiresD) { unsigned short *dPtr = (unsigned short*)hiresD.ptr(); unsigned short *dLowPtr = (unsigned short*)loresD.ptr(); int widthLow = loresD.cols; int heightLow = loresD.rows; assert(widthLow*2 == hiresD.cols && heightLow*2 == hiresD.rows); int offset = 0; // fill first row of low res disparity by half 2x2 block maximum for (int i = 0; i < widthLow; i++, offset++) { int i2 = 2*i; dPtr[i2] = dLowPtr[offset]; dPtr[i2+1] = dLowPtr[offset]; } int width = 2*widthLow; // fill full 2x2 blocks by max value for (int j = 1; j < heightLow-1; j++) { for (int i = 0; i < widthLow; i++, offset++) { int i2 = 2*i; int j2 = 2*j-1; int offset2 = i2 + j2 * width; dPtr[offset2] = dLowPtr[offset]; dPtr[offset2+1] = dLowPtr[offset]; dPtr[offset2+width] = dLowPtr[offset]; dPtr[offset2+width+1] = dLowPtr[offset]; } } // fill last row of low res disparity by half 2x2 block maximum for (int i = 0; i < widthLow; i++, offset++) { int offset2 = 2*i + (2*heightLow-1)*width; dPtr[offset2] = dLowPtr[offset]; dPtr[offset2+1] = dLowPtr[offset]; } }
3d57c0fcb1accefcd60fce33cb4bff81ba3e23e0
fde3cc872adfe3fe3383e16e3897125f2c2be8b7
/motorController.ino
6852ef3ae90b44a312f6729aebbec514c651fa80
[]
no_license
rafiqul713/Ardunio-Code
f806ad2ed2ca1f7fd454b5104e88fd708219fa3f
9b7e3df8eaed486ad2fb52d82218643e383e43b1
refs/heads/master
2020-04-09T06:10:45.179745
2018-12-02T22:28:37
2018-12-02T22:28:37
160,101,485
0
0
null
null
null
null
UTF-8
C++
false
false
495
ino
motorController.ino
#include <AFMotor.h> //import your motor shield library AF_DCMotor motor1(1,MOTOR12_64KHZ); // set up motors. AF_DCMotor motor2(2, MOTOR12_8KHZ); void setup() { Serial.begin(9600); // begin serial communitication Serial.println("Motor test!"); motor1.setSpeed(255); //set the speed of the motors, between 0-255 motor2.setSpeed (255); } void loop() { motor1.setSpeed(255); motor2.setSpeed (255); motor1.run(FORWARD); motor2.run(BACKWARD); }
cf4891001595b963a647475dc350dde7b5ea47ee
e7c2a4498c511740b173a3cfeaf0509e55f45114
/Underworld2d/Underworld2d/MapHandler.h
7aa5c89e7b300ab79c4bafbe95b76595f104cbd6
[]
no_license
CrimsonNynja/UnderWorld2d-Engine
29a3fceb5d501dc8024946623896191421847c52
3b39a6eae30b3fcdc8b8878a19f5d8932973c9cd
refs/heads/master
2020-04-21T17:28:55.684220
2019-12-17T11:39:38
2019-12-17T11:39:38
169,736,641
0
0
null
null
null
null
UTF-8
C++
false
false
1,408
h
MapHandler.h
#pragma once #include <string> #include <map> #include <vector> #include <tmxlite/TileLayer.hpp> #include <tmxlite/Map.hpp> #include <tmxlite/Layer.hpp> #include <SFML/Graphics.hpp> #include "TextureHandler.h" //TODO this should load the map, anddisplay it in chunks to save on runtime memory class MapHandler { public: MapHandler() {}; MapHandler(std::string file); /* loads the given tmx file into the the tmx::map and sets the map property variables */ bool loadMap(std::string file); /* sets the size of a chunk */ void setChunkSize(sf::Vector2f); void setChunkSize(float x, float y); //private: /* the loaded tmx map instance */ tmx::Map map; //unsigned tmxVersion; /* The size of the map in tile units, width x height */ sf::Vector2i mapSize; /* The size of the tile in pixels, width x height */ sf::Vector2i tileSize; unsigned tileCount; sf::Color backgroundColor; /* the size of a chunk in tile units, width x height */ sf::Vector2f chunkSize; /* The number of chunks in the map */ unsigned chuckCount; /* the global bounds of the map, where it starts and ends */ sf::FloatRect globalBounds; std::map<std::string, sf::Texture*> tileSets; }; class Chunk final : public sf::Transformable, sf::Drawable { public: Chunk(); private: unsigned char opacity; unsigned int tileCount; std::vector<tmx::TileLayer::Tile> tiles; std::vector<sf::Color> tileColors; };
ddaea66915db2d74d29d2db287496da4e89547e1
202b96b76fc7e3270b7a4eec77d6e1fd7d080b12
/platforms/posix/try/LowLevelFile.ot
c18df1533225fc294a58054f784f7a39879df468
[]
no_license
prestocore/browser
4a28dc7521137475a1be72a6fbb19bbe15ca9763
8c5977d18f4ed8aea10547829127d52bc612a725
refs/heads/master
2016-08-09T12:55:21.058966
1995-06-22T00:00:00
1995-06-22T00:00:00
51,481,663
98
66
null
null
null
null
UTF-8
C++
false
false
780
ot
LowLevelFile.ot
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ group "posix.pi.lowlevelfile"; require POSIX_OK_FILE; import "pi.oplowlevelfile"; import "pi.oplowlevelfileasync"; group "posix.util.lowlevelfile"; require POSIX_OK_FILE; import "util.opfile.opfile"; import "util.opfile.opmemfile"; import "util.opfile.opslotfile"; import "util.zipload"; import "util.filefun"; // group "posix.lowlevelfile"; // TODO: write a test that SafeReplace can move from /tmp/ to $HOME/, i.e. cross-device. // TODO: write tests for file-name de/serialization (c.f. SystemInfo.ot). // Any other implementation-specific tests ?
07565a0d395567a453e6cea011aa455b153251fc
56345c289644498f96d79dcdbee0476ea4342daa
/lc238.cpp
b1fb0c6476f9f49c95177503923bf0170a5ce7b9
[]
no_license
boyima/Leetcode
8023dd39d06bcb3ebb4c35c45daa193c78ce2bfe
0802822e1cbf2ab45931d31017dbd8167f3466cc
refs/heads/master
2020-12-13T06:35:00.834628
2019-11-05T22:27:50
2019-11-05T22:27:50
47,539,183
0
1
null
null
null
null
UTF-8
C++
false
false
565
cpp
lc238.cpp
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n = nums.size(); vector<int> res(n, 1); if(n == 1) return res; //products before res[i]; for(int i = 1; i < nums.size(); i++){ res[i] = res[i - 1] * nums[i - 1]; } int product = 1; //products after res[i] * products before res[i]; for(int i = nums.size() - 2; i >= 0; i--){ product = product * nums[i + 1]; res[i] = res[i] * product; } return res; } };
e59734984b0a86dfad4dbd40a63ab022e6321a31
badcf1716456393f144ff123ebab3ab6ceb36e0e
/src/RCube/Core/Graphics/MeshGen/Sphere.cpp
cd7e12449781cd75f206d34b799faac287002a1b
[ "BSD-3-Clause" ]
permissive
Ahdhn/RCube
35507ea8f0789bd01ae0f065c35ae4cfca50f240
e64ecfdae7154587e89806c23a11a6f0164e3167
refs/heads/master
2021-08-28T07:28:36.104407
2020-07-27T01:43:35
2020-07-27T01:43:35
220,858,987
0
0
BSD-3-Clause
2019-11-10T22:20:27
2019-11-10T22:20:26
null
UTF-8
C++
false
false
2,801
cpp
Sphere.cpp
#include "RCube/Core/Graphics/MeshGen/Sphere.h" #include "RCube/Core/Graphics/MeshGen/Box.h" #include "glm/gtc/constants.hpp" namespace rcube { TriangleMeshData icoSphere(float radius, unsigned int subdivisions) { // Golden ratio const float t = (1.0f + std::sqrt(5.0f)) / 2.0f; // Vertices of a icosahedron std::vector<glm::vec3> verts = {{-1, t, 0}, {1, t, 0}, {-1, -t, 0}, {1, -t, 0}, {0, -1, t}, {0, 1, t}, {0, -1, -t}, {0, 1, -t}, {t, 0, -1}, {t, 0, 1}, {-t, 0, -1}, {-t, 0, 1}}; // Faces of the icosahedron std::vector<glm::uvec3> faces = {{0, 11, 5}, {0, 5, 1}, {0, 1, 7}, {0, 7, 10}, {0, 10, 11}, {1, 5, 9}, {5, 11, 4}, {11, 10, 2}, {10, 7, 6}, {7, 1, 8}, {3, 9, 4}, {3, 4, 2}, {3, 2, 6}, {3, 6, 8}, {3, 8, 9}, {4, 9, 5}, {2, 4, 11}, {6, 2, 10}, {8, 6, 7}, {9, 8, 1}}; // Subdivision for (unsigned int sub = 0; sub < subdivisions; ++sub) { size_t orig_num_faces = faces.size(); for (size_t idx = 0; idx < orig_num_faces; ++idx) { unsigned int i = faces[idx][0]; unsigned int j = faces[idx][1]; unsigned int k = faces[idx][2]; const glm::vec3 &a = verts[i]; const glm::vec3 &b = verts[j]; const glm::vec3 &c = verts[k]; glm::vec3 ab = (a + b) / 2.f; glm::vec3 bc = (b + c) / 2.f; glm::vec3 ca = (c + a) / 2.f; verts.insert(verts.end(), {ab, bc, ca}); unsigned int ij = verts.size() - 3; unsigned int jk = verts.size() - 2; unsigned int ki = verts.size() - 1; faces.insert(faces.end(), {{i, ij, ki}, {ij, j, jk}, {ki, jk, k}}); faces[idx] = {jk, ki, ij}; } } // Make each vertex to lie on the sphere and find its normal std::vector<glm::vec3> normals; normals.reserve(verts.size()); for (auto &v : verts) { auto norm_v = glm::normalize(v); normals.push_back(norm_v); v = norm_v * radius; } TriangleMeshData data; data.vertices = verts; data.indices = faces; data.normals = normals; data.indexed = true; return data; } TriangleMeshData cubeSphere(float radius, unsigned int n_segments) { TriangleMeshData data = box(1, 1, 1, n_segments, n_segments, n_segments); assert(data.vertices.size() == data.normals.size()); for (size_t i = 0; i < data.vertices.size(); ++i) { glm::vec3 norm_v = glm::normalize(data.vertices[i]); data.vertices[i] = norm_v * radius; data.normals[i] = norm_v; } return data; } } // namespace rcube
53f96e15f3e54ca24812f327b770324ec667fd7f
7e309f67cafe5528eaab8757fa34dd9c59355195
/Algorithms/PopulatingNextRightPointersInEachNodeII/populatingNextRightPointersInEachNodeII.cc
a65a65980399650a9a108123418c4708c5be99b8
[]
no_license
xusiwei/leetcode
56cc827020ab5a9373d7b4221e8ae82734b01e7e
80f0c2b2a89843df2ea3adb12828991ad8534373
refs/heads/master
2021-04-22T13:26:46.577996
2020-05-24T17:06:12
2020-05-24T17:06:12
36,977,056
5
0
null
null
null
null
UTF-8
C++
false
false
3,663
cc
populatingNextRightPointersInEachNodeII.cc
/* copyright xu(xusiwei1236@163.com), all right reserved. Populating Next Right Pointers in Each Node II =============================================== Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tree could be any binary tree? Would your previous solution still work? Note: You may only use constant extra space. For example, Given the following binary tree, 1 / \ 2 3 / \ \ 4 5 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL */ #include <queue> #include <stdio.h> using namespace std; struct TreeLinkNode { int val; TreeLinkNode *left, *right, *next; TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} TreeLinkNode(int x, TreeLinkNode* L, TreeLinkNode* R) : val(x), left(L), right(R), next(NULL) {} }; /** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { if(root == NULL) return; queue<TreeLinkNode*> q; TreeLinkNode *prev, *last; prev = last = root; q.push(root); while(!q.empty()) { TreeLinkNode* p = q.front(); q.pop(); prev->next = p; if(p->left ) q.push(p->left); if(p->right) q.push(p->right); if(p == last) { // meets last of current level // now, q contains all nodes of next level last = q.back(); p->next = NULL; // cut down. prev = q.front(); } else { prev = p; } } } // constant space // key point: we can use `next` pointer to help us represent // the buffering queue of level order traversal. void connect2(TreeLinkNode *root) { if(root == NULL) return; TreeLinkNode *head, *tail; TreeLinkNode *prev, *last; head = tail = NULL; prev = last = root; #define push(p) \ if(head == NULL) { head = tail = p; } \ else { tail->next = p; tail = p; } push(root); while(head != NULL) { TreeLinkNode* p = head; head = head->next; // pop prev->next = p; if(p->left ) push(p->left); if(p->right) push(p->right); if(p == last) { last = tail; p->next = NULL; // cut down. prev = head; } else { prev = p; } } #undef push } }; void printLinkTree(TreeLinkNode* root) { TreeLinkNode *head = root, *p = root; while(p) { printf("%d%s", p->val, (p->next) ? "->" : "\n"); if(p->next != NULL) { p = p->next; } else { head = head->left; p = head; } } } int main(int argc, char* argv[]) { TreeLinkNode* root = new TreeLinkNode(1, new TreeLinkNode(2, new TreeLinkNode(4), new TreeLinkNode(5)), new TreeLinkNode(3, new TreeLinkNode(6), new TreeLinkNode(7))); #ifdef CONST_SPACE Solution().connect2(root); #else Solution().connect(root); #endif printLinkTree(root); return 0; }
c2c9edad2857c4708d36d6842f32cf798efc3d5d
559a00d4367374b367d4999167743ec6d7387640
/structures/Graph/Weighted Graph/Multigraph (for Chinese Postman Problem)/WeightedMultigraph.h
b95e7f7d6aea9ed3ad9e00b97253045c5e359b70
[]
no_license
michal367/Algorithms-and-Data-Structures
0cd0787393ebefaef19d5d1056b6d9de321e05d7
4aee40daac9c3292f3e5ac36010cf789354c26c7
refs/heads/master
2023-01-02T18:46:24.144935
2020-10-28T10:42:06
2020-10-28T10:42:06
307,850,924
0
0
null
null
null
null
UTF-8
C++
false
false
33,042
h
WeightedMultigraph.h
#pragma once #include <vector> #include <list> #include <map> #include <stack> #include <queue> #include <algorithm> #include "IndexedPQ.h" #include <iostream> template<class T, class W = int> class WeightedMultigraph{ // undirected/directed weighted multigraph with loops (pseudograph) struct Edges{ std::size_t node; std::vector<W> weights; Edges(std::size_t node) : node(node) {} Edges(std::size_t node, const W& weight) : node(node), weights({weight}) {} Edges(std::size_t node, const std::vector<W>& weights) : node(node), weights(weights) {} bool operator==(const Edges& other) const{ return (node == other.node && weights == other.weights); } }; std::vector<std::list<Edges> > neighbours; std::vector<T> data; public: WeightedMultigraph(); WeightedMultigraph(std::size_t size, const T& value); WeightedMultigraph(std::initializer_list<T> il); WeightedMultigraph(const WeightedMultigraph<T,W>& other); WeightedMultigraph<T,W>& operator=(const WeightedMultigraph<T,W>& other); std::size_t size(); std::size_t nodesAmount(); std::size_t directedEdgesAmount(); std::size_t edgesAmount(); bool empty(); void clear(); T getData(std::size_t node); T& at(std::size_t node); void setData(std::size_t node, const T& value); bool existsDirectedEdge(std::size_t node1, std::size_t node2); std::list<std::pair<std::size_t, std::vector<W> > > getNeighbours(std::size_t node); void addNode(const T& value); void addDirectedEdge(std::size_t node1, std::size_t node2, const W& weight); void addDirectedEdges(std::size_t node1, std::size_t node2, const std::vector<W>& weights); void addEdge(std::size_t node1, std::size_t node2, const W& weight); void removeNode(T value); void removeNodeByIndex(std::size_t index); void removeDirectedEdges(std::size_t node1, std::size_t node2); void removeEdges(std::size_t node1, std::size_t node2); void removeDirectedEdge(std::size_t node1, std::size_t node2, std::size_t index); std::vector<W> getWeights(std::size_t node1, std::size_t node2); void setWeightsDirected(std::size_t node1, std::size_t node2, const std::vector<W>& weight); void setWeights(std::size_t node1, std::size_t node2, const std::vector<W>& weight); void setWeightDirected(std::size_t node1, std::size_t node2, std::size_t weight_index, const W& weight); WeightedMultigraph<T,W> subgraph(const std::vector<std::size_t>& nodes); WeightedMultigraph<T,W> convertToUndirectedMultigraph(); std::pair<std::vector<std::size_t>, W> ChinesePostmanProblemDirected(std::size_t start=0); bool operator==(const WeightedMultigraph<T,W>& other); bool operator!=(const WeightedMultigraph<T,W>& other); void printNodes(); void printValues(); private: std::pair<std::vector<std::size_t>, W> EulerianDirected(std::size_t start=0); void innerEulerianDirected(std::size_t node, std::vector<std::size_t>& result, W& dist); bool CPPstronglyConnectedDirected(); bool innerCPPstronglyConnectedDirected(std::size_t node, std::size_t& node_number, std::size_t* nodes_order, std::size_t* low, bool* on_stack, std::stack<std::size_t>& s, std::size_t& scc_counter); std::pair<std::vector<std::size_t>, std::vector<std::size_t> > CPPdifferentDegreeNodesDirected(); std::vector<W> DijkstraDistances(std::size_t node); std::vector<std::size_t> DijkstraPath(std::size_t node1, std::size_t node2); std::pair<std::vector<std::size_t>,std::vector<std::size_t> > bipartiteSets(); std::vector<std::pair<std::size_t,std::size_t> > maxWeightHungarianAlgorithm(); std::vector<std::pair<std::size_t,std::size_t> > minWeightHungarianAlgorithm(); }; template<class T, class W> WeightedMultigraph<T,W>::WeightedMultigraph() {} template<class T, class W> WeightedMultigraph<T,W>::WeightedMultigraph(std::size_t size, const T& value){ for(std::size_t i=0; i<size; i++){ data.push_back(value); neighbours.push_back(std::list<Edges>()); } } template<class T, class W> WeightedMultigraph<T,W>::WeightedMultigraph(std::initializer_list<T> il){ for(auto it = il.begin(); it != il.end(); it++){ data.push_back(*it); neighbours.push_back(std::list<Edges>()); } } template<class T, class W> WeightedMultigraph<T,W>::WeightedMultigraph(const WeightedMultigraph<T,W>& other){ data = other.data; neighbours = other.neighbours; } template<class T, class W> WeightedMultigraph<T,W>& WeightedMultigraph<T,W>::operator=(const WeightedMultigraph<T,W>& other){ if(this != &other){ data = other.data; neighbours = other.neighbours; } return *this; } template<class T, class W> std::size_t WeightedMultigraph<T,W>::size(){ return data.size(); } template<class T, class W> std::size_t WeightedMultigraph<T,W>::nodesAmount(){ return size(); } template<class T, class W> std::size_t WeightedMultigraph<T,W>::directedEdgesAmount(){ std::size_t amount = 0; for(auto it = neighbours.begin(); it != neighbours.end(); it++) for(auto it2 = it->begin(); it2 != it->end(); it2++) amount += it2->weights.size(); return amount; } template<class T, class W> std::size_t WeightedMultigraph<T,W>::edgesAmount(){ std::list<std::pair<std::pair<std::size_t,std::size_t>, W> > edges; for(std::size_t i=0; i<neighbours.size(); i++) for(auto it = neighbours.at(i).begin(); it != neighbours.at(i).end(); it++) for(auto itw = it->weights.begin(); itw != it->weights.end(); itw++) if(std::find(edges.begin(),edges.end(), std::make_pair(std::make_pair(it->node, i), *itw)) == edges.end()) edges.push_back(std::make_pair(std::make_pair(i, it->node), *itw)); return edges.size(); } template<class T, class W> bool WeightedMultigraph<T,W>::empty(){ return (size() == 0); } template<class T, class W> void WeightedMultigraph<T,W>::clear(){ data.clear(); neighbours.clear(); } template<class T, class W> T WeightedMultigraph<T,W>::getData(std::size_t node){ return data.at(node); } template<class T, class W> T& WeightedMultigraph<T,W>::at(std::size_t node){ return data.at(node); } template<class T, class W> void WeightedMultigraph<T,W>::setData(std::size_t node, const T& value){ data.at(node) = value; } template<class T, class W> bool WeightedMultigraph<T,W>::existsDirectedEdge(std::size_t node1, std::size_t node2){ for(auto it = neighbours.at(node1).begin(); it != neighbours.at(node1).end(); it++) if(it->node == node2) return true; return false; } template<class T, class W> std::list<std::pair<std::size_t, std::vector<W> > > WeightedMultigraph<T,W>::getNeighbours(std::size_t node){ std::list<std::pair<std::size_t, std::vector<W> > > result; for(auto it = neighbours.at(node).begin(); it != neighbours.at(node).end(); it++) result.push_back(std::make_pair(it->node, it->weights)); return result; } template<class T, class W> void WeightedMultigraph<T,W>::addNode(const T& value){ data.push_back(value); neighbours.push_back(std::list<Edges>()); } template<class T, class W> void WeightedMultigraph<T,W>::addDirectedEdge(std::size_t node1, std::size_t node2, const W& weight){ for(auto it = neighbours.at(node1).begin(); it != neighbours.at(node1).end(); it++) if(it->node == node2){ it->weights.push_back(weight); return; } neighbours.at(node1).push_back(Edges(node2, weight)); } template<class T, class W> void WeightedMultigraph<T,W>::addDirectedEdges(std::size_t node1, std::size_t node2, const std::vector<W>& weights){ for(auto it = neighbours.at(node1).begin(); it != neighbours.at(node1).end(); it++) if(it->node == node2){ it->weights.insert(it->weights.end(), weights.begin(),weights.end()); return; } neighbours.at(node1).push_back(Edges(node2, weights)); } template<class T, class W> void WeightedMultigraph<T,W>::addEdge(std::size_t node1, std::size_t node2, const W& weight){ addDirectedEdge(node1, node2, weight); addDirectedEdge(node2, node1, weight); } template<class T, class W> void WeightedMultigraph<T,W>::removeNode(T value){ for(std::size_t i=0; i<data.size(); i++) if(data.at(i) == value){ data.erase(data.begin()+i); neighbours.erase(neighbours.begin()+i); for(auto it = neighbours.begin(); it != neighbours.end(); it++) for(auto it2 = it->begin(); it2 != it->end();) if(it2->node == i){ auto temp = it2; it2++; it->erase(temp); } else{ if(it2->node > i) it2->node--; it2++; } break; } } template<class T, class W> void WeightedMultigraph<T,W>::removeNodeByIndex(std::size_t index){ data.erase(data.begin()+index); neighbours.erase(neighbours.begin()+index); for(auto it = neighbours.begin(); it != neighbours.end(); it++) for(auto it2 = it->begin(); it2 != it->end();) if(it2->node == index){ auto temp = it2; it2++; it->erase(temp); } else{ if(it2->node > index) it2->node--; it2++; } } template<class T, class W> void WeightedMultigraph<T,W>::removeDirectedEdges(std::size_t node1, std::size_t node2){ for(auto it = neighbours.at(node1).begin(); it != neighbours.at(node1).end();) if(it->node == node2){ auto temp = it; it++; neighbours.at(node1).erase(temp); } else it++; } template<class T, class W> void WeightedMultigraph<T,W>::removeEdges(std::size_t node1, std::size_t node2){ removeDirectedEdges(node1, node2); removeDirectedEdges(node2, node1); } template<class T, class W> void WeightedMultigraph<T,W>::removeDirectedEdge(std::size_t node1, std::size_t node2, std::size_t index){ for(auto it = neighbours.at(node1).begin(); it != neighbours.at(node1).end(); it++) if(it->node == node2){ if(index < it->weights.size()){ it->weights.erase(it->weights.begin()+index); if(it->weights.size() == 0) neighbours.at(node1).erase(it); } break; } } template<class T, class W> std::vector<W> WeightedMultigraph<T,W>::getWeights(std::size_t node1, std::size_t node2){ for(auto it = neighbours.at(node1).begin(); it != neighbours.at(node1).end(); it++) if(it->node == node2) return it->weights; return std::vector<W>(); } template<class T, class W> void WeightedMultigraph<T,W>::setWeightsDirected(std::size_t node1, std::size_t node2, const std::vector<W>& weights){ for(auto it = neighbours.at(node1).begin(); it != neighbours.at(node1).end(); it++) if(it->node == node2){ it->weights = weights; break; } } template<class T, class W> void WeightedMultigraph<T,W>::setWeights(std::size_t node1, std::size_t node2, const std::vector<W>& weights){ setWeightDirected(node1, node2, weights); setWeightDirected(node2, node1, weights); } template<class T, class W> void WeightedMultigraph<T,W>::setWeightDirected(std::size_t node1, std::size_t node2, std::size_t weight_index, const W& weight){ for(auto it = neighbours.at(node1).begin(); it != neighbours.at(node1).end(); it++) if(it->node == node2){ if(weight_index < it->weights.size()) it->weights.at(weight_index) = weight; break; } } template<class T, class W> WeightedMultigraph<T,W> WeightedMultigraph<T,W>::subgraph(const std::vector<std::size_t>& nodes){ WeightedMultigraph<T,W> sg; std::map<std::size_t, std::size_t> m; std::size_t i=0; for(auto it = nodes.begin(); it != nodes.end(); it++){ sg.addNode(data.at(*it)); m.insert(std::pair<std::size_t,std::size_t>(*it, i++)); } for(auto it = nodes.begin(); it != nodes.end(); it++){ for(auto it2 = neighbours.at(*it).begin(); it2 != neighbours.at(*it).end(); it2++){ auto mit = m.find(it2->node); if(mit != m.end()){ sg.addDirectedEdges(m.find(*it)->second, mit->second, it2->weights); } } } return sg; } template<class T, class W> WeightedMultigraph<T,W> WeightedMultigraph<T,W>::convertToUndirectedMultigraph(){ WeightedMultigraph<T,W> undig; undig.data.insert(undig.data.end(), data.begin(), data.end()); undig.neighbours.insert(undig.neighbours.begin(), size(), std::list<Edges>()); std::list<std::pair<std::pair<std::size_t,std::size_t>, W> > edges; for(std::size_t i=0; i<neighbours.size(); i++) for(auto it = neighbours.at(i).begin(); it != neighbours.at(i).end(); it++) for(auto itw = it->weights.begin(); itw != it->weights.end(); itw++) if(std::find(edges.begin(),edges.end(), std::make_pair(std::make_pair(it->node, i), *itw)) == edges.end()) edges.push_back(std::make_pair(std::make_pair(i, it->node), *itw)); for(auto it = edges.begin(); it != edges.end(); it++) undig.addEdge(it->first.first, it->first.second, it->second); return undig; } template<class T, class W> std::pair<std::vector<std::size_t>, W> WeightedMultigraph<T,W>::EulerianDirected(std::size_t start){ std::vector<std::size_t> result; W dist = W(); if(start < size()){ WeightedMultigraph<T,W> clone(*this); clone.innerEulerianDirected(start, result, dist); std::reverse(result.begin(), result.end()); } return std::make_pair(result, dist); } template<class T, class W> void WeightedMultigraph<T,W>::innerEulerianDirected(std::size_t node, std::vector<std::size_t>& result, W& dist){ while(neighbours.at(node).size() > 0){ if(neighbours.at(node).front().weights.size() > 0){ // get first neighbour std::size_t v = neighbours.at(node).front().node; dist = dist + neighbours.at(node).front().weights.front(); // delete first neighbour neighbours.at(node).front().weights.erase(neighbours.at(node).front().weights.begin()); innerEulerianDirected(v, result, dist); } else neighbours.at(node).pop_front(); } result.push_back(node); } template<class T, class W> std::pair<std::vector<std::size_t>, W> WeightedMultigraph<T,W>::ChinesePostmanProblemDirected(std::size_t start){ // graph cannot have negative weights // W type must be signed type (for hungarian algorithm) // returns // CPP cycle // distance of cycle std::vector<std::size_t> path; W dist = W(); if(start < size() && CPPstronglyConnectedDirected()){ auto imbalanced = CPPdifferentDegreeNodesDirected(); if(imbalanced.first.size() == 0){ // graph has Eulerian cycle return EulerianDirected(start); } else{ // creating complete bipartite graph with imbalanced vertices // weights of edges are distances of min-dist path WeightedMultigraph<T,W> missingPaths(imbalanced.first.size() + imbalanced.second.size(), W()); for(std::size_t i=0; i<imbalanced.first.size(); i++){ std::vector<W> dist = DijkstraDistances(imbalanced.first.at(i)); for(std::size_t j=0; j<imbalanced.second.size(); j++) missingPaths.addEdge(i, imbalanced.first.size() + j, dist.at(imbalanced.second.at(j))); } // find min-weight max-cardinality matching auto matching = missingPaths.minWeightHungarianAlgorithm(); // add min-weight paths to graph WeightedMultigraph<T,W> temp(*this); for(auto itm = matching.begin(); itm != matching.end(); itm++){ std::size_t first_node = imbalanced.first.at(itm->first); std::size_t second_node = imbalanced.second.at(itm->second - imbalanced.first.size()); std::vector<std::size_t> path = DijkstraPath(first_node, second_node); for(auto itp = path.begin(); itp+1 != path.end(); itp++){ std::vector<W> weights = getWeights(*itp, *(itp+1)); W min_weight = *std::min_element(weights.begin(), weights.end()); temp.addDirectedEdge(*itp, *(itp+1), min_weight); } } // find Eulerian Cycle return temp.EulerianDirected(start); } } return std::make_pair(path, dist); } template<class T, class W> bool WeightedMultigraph<T,W>::CPPstronglyConnectedDirected(){ // returns: does directed graph has all edges in one strongly connected component std::size_t big_components = 0; std::size_t* nodes_order = new std::size_t[size()]; std::size_t* low = new std::size_t[size()]; bool* on_stack = new bool[size()]; std::stack<std::size_t> s; for(std::size_t i=0; i<size(); i++){ nodes_order[i] = 0; on_stack[i] = false; } std::size_t node_number = 0; for(std::size_t i=0; i < size(); i++){ if(nodes_order[i] == 0){ big_components++; if(neighbours.at(i).size() == 0) big_components--; else if(big_components > 1){ delete[] nodes_order; delete[] low; delete[] on_stack; return false; } std::size_t scc_counter = 0; if(innerCPPstronglyConnectedDirected(i, node_number, nodes_order, low, on_stack, s, scc_counter) == false){ delete[] nodes_order; delete[] low; delete[] on_stack; return false; } } } delete[] nodes_order; delete[] low; delete[] on_stack; return true; } template<class T, class W> bool WeightedMultigraph<T,W>::innerCPPstronglyConnectedDirected(std::size_t node, std::size_t& node_number, std::size_t* nodes_order, std::size_t* low, bool* on_stack, std::stack<std::size_t>& s, std::size_t& scc_counter){ // checks if all reachable vertices are in one strongly connected component node_number++; nodes_order[node] = node_number; low[node] = node_number; s.push(node); on_stack[node] = true; for(auto it = neighbours.at(node).begin(); it != neighbours.at(node).end(); it++){ if(nodes_order[it->node] == 0){ innerCPPstronglyConnectedDirected(it->node, node_number, nodes_order, low, on_stack, s, scc_counter); low[node] = std::min(low[node], low[it->node]); } else if(on_stack[it->node] == true) low[node] = std::min(low[node], nodes_order[it->node]); } if(low[node] == nodes_order[node]){ while(!s.empty()){ std::size_t v = s.top(); s.pop(); on_stack[v] = false; if(v == node) break; } scc_counter++; return (scc_counter == 1); } return false; } template<class T, class W> std::pair<std::vector<std::size_t>, std::vector<std::size_t> > WeightedMultigraph<T,W>::CPPdifferentDegreeNodesDirected(){ // returns // vertices with indegree - outdegree > 0 // vertices with outdegree - indegree > 0 std::vector<std::size_t> in, out; int* indegree = new int[size()]; int* outdegree = new int[size()]; for(std::size_t i=0; i<size(); i++){ indegree[i] = 0; outdegree[i] = 0; } for(std::size_t i=0; i<size(); i++){ for(auto it = neighbours.at(i).begin(); it != neighbours.at(i).end(); it++){ outdegree[i] += it->weights.size(); indegree[it->node] += it->weights.size(); } } for(std::size_t node = 0; node < size(); node++){ if(indegree[node] != outdegree[node]){ if(indegree[node] - outdegree[node] > 0) in.insert(in.end(), indegree[node] - outdegree[node], node); else if(outdegree[node] - indegree[node] > 0) out.insert(out.end(), outdegree[node] - indegree[node], node); } } delete[] indegree; delete[] outdegree; return std::make_pair(in,out); } template<class T, class W> std::vector<W> WeightedMultigraph<T,W>::DijkstraDistances(std::size_t node){ // graph must have non-negative edge weights if(node >= size()) return std::vector<W>(); std::vector<W> dist(size(), W()); std::size_t* parent = new std::size_t[size()]; for(std::size_t i=0; i<size(); i++){ //dist[i] = W(); parent[i] = -1; } dist[node] = W(); IndexedPQ<W> ipq(size()); ipq.push(node, dist[node]); while(!ipq.empty()){ std::size_t v = ipq.pop(); for(auto it = neighbours.at(v).begin(); it != neighbours.at(v).end(); it++){ W min_weight = *std::min_element(it->weights.begin(), it->weights.end()); if(dist[v] + min_weight < dist[it->node] || parent[it->node] == -1 && it->node != node){ dist[it->node] = dist[v] + min_weight; parent[it->node] = v; if(ipq.contains(it->node)) ipq.decrease_key(it->node, dist[it->node]); else ipq.push(it->node, dist[it->node]); } } } delete[] parent; return dist; } template<class T, class W> std::vector<std::size_t> WeightedMultigraph<T,W>::DijkstraPath(std::size_t node1, std::size_t node2){ // graph must have non-negative edge weights if(node1 >= size() || node2 >= size()) return std::vector<std::size_t>(); if(node1 == node2) return std::vector<std::size_t>({node1}); W* dist = new W[size()]; std::size_t* parent = new std::size_t[size()]; for(std::size_t i=0; i<size(); i++){ //dist[i] = W(); parent[i] = -1; } dist[node1] = W(); IndexedPQ<W> ipq(size()); ipq.push(node1, dist[node1]); while(!ipq.empty()){ std::size_t v = ipq.pop(); if(v == node2) break; for(auto it = neighbours.at(v).begin(); it != neighbours.at(v).end(); it++){ W min_weight = *std::min_element(it->weights.begin(), it->weights.end()); if(dist[v] + min_weight < dist[it->node] || parent[it->node] == -1 && it->node != node1){ dist[it->node] = dist[v] + min_weight; parent[it->node] = v; if(ipq.contains(it->node)) ipq.decrease_key(it->node, dist[it->node]); else ipq.push(it->node, dist[it->node]); } } } // construct path std::vector<std::size_t> result; if(parent[node2] != -1){ std::size_t v = node2; while(v != -1){ result.push_back(v); v = parent[v]; } std::reverse(result.begin(), result.end()); } delete[] parent; return result; } template<class T, class W> std::pair<std::vector<std::size_t>,std::vector<std::size_t> > WeightedMultigraph<T,W>::bipartiteSets(){ // graph must be undirected std::pair<std::vector<std::size_t>,std::vector<std::size_t> > result; char* color = new char[size()]; for(std::size_t i=0; i < size(); i++) color[i] = 0; std::queue<std::size_t> q; for(std::size_t i=0; i < size(); i++) if(color[i] == 0){ q.push(i); color[i] = 'r'; result.first.push_back(i); while(!q.empty()){ std::size_t v = q.front(); q.pop(); for(auto it = neighbours.at(v).begin(); it != neighbours.at(v).end(); it++){ if(color[it->node] == 0){ if(color[v] == 'r'){ color[it->node] = 'b'; result.second.push_back(it->node); } else{ color[it->node] = 'r'; result.first.push_back(it->node); } q.push(it->node); } else if(color[v] == color[it->node]){ delete[] color; return std::pair<std::vector<std::size_t>,std::vector<std::size_t> >(); } } } } delete[] color; return result; } template<class T, class W> std::vector<std::pair<std::size_t,std::size_t> > WeightedMultigraph<T,W>::maxWeightHungarianAlgorithm(){ // max-weight max-cardinality bipartite matching // graph must be undirected and bipartite // W type must be signed type std::pair<std::vector<std::size_t>, std::vector<std::size_t> > bs = bipartiteSets(); std::vector<std::pair<std::size_t,std::size_t> > result; if(bs.first.size() > 0 && bs.second.size() > 0){ WeightedMultigraph<T,W> completeB(*this); // add dummy nodes while(bs.first.size() < bs.second.size()){ bs.first.push_back(completeB.size()); completeB.addNode(T()); } while(bs.second.size() < bs.first.size()){ bs.second.push_back(completeB.size()); completeB.addNode(T()); } // calculate lower bound for weight of dummy edges // -sum(abs(w)) - 1 W dummy_weight = W(); for(auto it = bs.first.begin(); it != bs.first.end(); it++) for(auto itn = neighbours.at(*it).begin(); itn != neighbours.at(*it).end(); itn++){ W max_weight = *std::max_element(itn->weights.begin(), itn->weights.end()); if(max_weight > W()) dummy_weight = dummy_weight - max_weight; else dummy_weight = dummy_weight + max_weight; } --dummy_weight; // add missing edges for making completeB graph complete bipartite for(auto it = bs.first.begin(); it != bs.first.end(); it++) for(auto it2 = bs.second.begin(); it2 != bs.second.end(); it2++) if(!completeB.existsDirectedEdge(*it, *it2)) completeB.addEdge(*it, *it2, dummy_weight); // set initial labels W* label = new W[completeB.size()]; for(auto it = bs.first.begin(); it != bs.first.end(); it++){ W max = neighbours.at(*it).front().weights.front(); for(auto it2 = completeB.neighbours.at(*it).begin(); it2 != completeB.neighbours.at(*it).end(); it2++){ W max_weight = *std::max_element(it2->weights.begin(), it2->weights.end()); if(max_weight > max) max = max_weight; } label[*it] = max; } for(auto it = bs.second.begin(); it != bs.second.end(); it++) label[*it] = W(); std::size_t* match = new std::size_t[completeB.size()]; std::size_t* parent = new std::size_t[completeB.size()]; for(std::size_t i=0; i<completeB.size(); i++) match[i] = -1; for(auto it = bs.first.begin(); it != bs.first.end();){ std::queue<std::size_t> q; q.push(*it); bool found = false; for(std::size_t i=0; i < completeB.size(); i++) parent[i] = -1; // find augmenting path while(!q.empty()){ std::size_t v = q.front(); q.pop(); for(auto it2 = completeB.neighbours.at(v).begin(); it2 != completeB.neighbours.at(v).end(); it2++){ W max_weight = *std::max_element(it2->weights.begin(), it2->weights.end()); if(parent[it2->node] == -1 && parent[v] != it2->node && label[v] + label[it2->node] == max_weight){ // tight edge parent[it2->node] = v; if(match[it2->node] == -1){ // augment std::size_t u = it2->node; while(u != -1){ match[u] = parent[u]; match[parent[u]] = u; u = parent[parent[u]]; } found = true; break; } else{ std::size_t u = match[it2->node]; parent[u] = it2->node; q.push(u); } } } if(found){ it++; break; } } // not found - update labels if(!found){ // calculate delta // delta = min{l(s) + l(y) - w(s,y)} W delta; bool initialized = false; for(auto itf = bs.first.begin(); itf != bs.first.end(); itf++) for(auto itn = completeB.neighbours.at(*itf).begin(); itn != completeB.neighbours.at(*itf).end(); itn++) if((parent[*itf] != -1 || *itf == *it) && parent[itn->node] == -1){ // visited from first and not visited from second W max_weight = *std::max_element(itn->weights.begin(), itn->weights.end()); W new_delta = label[*itf] + label[itn->node] - max_weight; if(new_delta < delta || !initialized){ delta = new_delta; initialized = true; } } // update labels for(auto itf = bs.first.begin(); itf != bs.first.end(); itf++) if(parent[*itf] != -1 || *itf == *it) label[*itf] = label[*itf] - delta; for(auto its = bs.second.begin(); its != bs.second.end(); its++) if(parent[*its] != -1) label[*its] = label[*its] + delta; } } // collect matching for(auto it = bs.first.begin(); it != bs.first.end(); it++) if(*it < size() && match[*it] < size() && match[*it] != -1 && existsDirectedEdge(*it,match[*it])) result.push_back(std::make_pair(*it, match[*it])); delete[] label; delete[] match; delete[] parent; } return result; } template<class T, class W> std::vector<std::pair<std::size_t,std::size_t> > WeightedMultigraph<T,W>::minWeightHungarianAlgorithm(){ // min-weight max-cardinality bipartite matching // graph must be undirected and bipartite // W type must be signed type // set all weights opposite and run max-weight HA WeightedMultigraph<T,W> temp(*this); for(std::size_t i=0; i<size(); i++) for(auto it = temp.neighbours.at(i).begin(); it != temp.neighbours.at(i).end(); it++) for(auto itw = it->weights.begin(); itw != it->weights.end(); itw++) *itw = -*itw; return temp.maxWeightHungarianAlgorithm(); } template<class T, class W> bool WeightedMultigraph<T,W>::operator==(const WeightedMultigraph<T,W>& other){ return (data == other.data && neighbours == other.neighbours); } template<class T, class W> bool WeightedMultigraph<T,W>::operator!=(const WeightedMultigraph<T,W>& other){ return !(*this == other); } // ============================================ template<class T, class W> void WeightedMultigraph<T,W>::printNodes(){ std::size_t i = 0; for(auto it = data.begin(); it != data.end(); it++, i++){ std::cout << i << ": " << *it << " neighbours: "; for(auto it2 = neighbours.at(i).begin(); it2 != neighbours.at(i).end(); it2++){ std::cout << it2->node << "(w:"; for(auto itw = it2->weights.begin(); itw != it2->weights.end()-1; itw++) std::cout << *itw << ","; std::cout << it2->weights.back(); std::cout << ") "; } std::cout << std::endl; } } template<class T, class W> void WeightedMultigraph<T,W>::printValues(){ std::size_t i = 0; for(auto it = data.begin(); it != data.end(); it++, i++){ std::cout << i << ": " << *it << std::endl; } }
42c5b94ea0c06bdd17ef94fa73e78c64c2ffe586
34a9bba379f2bdb1a156d35ada8ef7eae1937373
/projeto_final_mp.cpp
70766de6f2ce78267af594cfa41552e8235385d8
[]
no_license
satoru27/projeto_mp_unb_2_2016
e23b493748285ff272928ca795e785e161777157
06df1c875c0f80155910ea517d127a8627d2e8aa
refs/heads/master
2020-06-14T22:28:29.307271
2016-12-04T18:09:39
2016-12-04T18:09:39
75,403,548
1
0
null
null
null
null
UTF-8
C++
false
false
1,942
cpp
projeto_final_mp.cpp
// projeto_final_mp.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "social.h" #include <gtest/gtest.h> /** * Testando se a criacao de novos usuarios funciona * Testa constructor e getters */ TEST(Usuario_test, criar) { std::vector<int> coisas = { 1,3,5,6,4 }; Usuario a(22, 'm', "Felipe", coisas, "71929000"); Usuario b(10, 'f', "bla", coisas, "812712828"); Usuario c(30, 'f', "dsdsd", coisas, "71782909"); EXPECT_EQ(22, a.get_idade()); EXPECT_EQ('m', a.get_genero()); EXPECT_EQ("Felipe", a.get_nome()); EXPECT_EQ("71929000", a.get_CEP()); EXPECT_EQ(0, a.get_id()); EXPECT_EQ(1, b.get_id()); EXPECT_EQ(2, c.get_id()); } /** * Testando se as funcoes setters funcionam */ TEST(Usuario_test, setters) { std::vector<int> coisas = { 1,3,5,6,4 }; Usuario a(22, 'm', "Felipe", coisas, "71929000"); a.set_idade(50); a.set_genero('f'); a.set_nome("Filipe"); a.set_cep("77777777"); EXPECT_EQ(50, a.get_idade()); EXPECT_EQ('f', a.get_genero()); EXPECT_EQ("Filipe", a.get_nome()); EXPECT_EQ("77777777", a.get_CEP()); } /** * Testando se os interesses estao funcionando corretamente */ TEST(Usuario_test, interesses) { std::vector<int> coisas = { 1,3,5,6,4 }; Usuario a(22, 'm', "Felipe", coisas, "71929000"); EXPECT_EQ(0, a.get_interesses().size()); a.add_interesse(7); a.add_interesse(9); EXPECT_EQ(2, a.get_interesses().size()); EXPECT_EQ(7, a.get_interesses()[5]); EXPECT_EQ(9, a.get_interesses()[6]); // Testando se o limite de 20 interesses funciona for (int i = 0; i < 25; i++) { a.add_interesse(1); } EXPECT_EQ(20, a.get_interesses().size()); a.delete_interesse(9); EXPECT_EQ(19, a.get_interesses().size()); a.delete_interesse(1); EXPECT_EQ(5, a.get_interesses().size()); } int main(int argc, char ** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
d03da3e67df051f7bc270357e6e0c35db1f74df8
73a2207fd227d4c6bfade73cc0c65583fa412667
/Pacman/Pacman/speedy.h
2c43580f78e17773cb8ae91aee5cbbf7c7e84d25
[]
no_license
Tabbers/Ki_Pacman
e4f8582ef8ae3a3d84bc05ffa7273fc35f4ac75d
8f372b7a04aa8d54c93ceb10025c1392486eca3e
refs/heads/master
2016-08-12T11:33:59.961341
2015-10-18T14:22:36
2015-10-18T14:22:36
43,760,131
0
0
null
null
null
null
UTF-8
C++
false
false
198
h
speedy.h
#pragma once #include "statemachine.h" class Speedy: public StateMachine { public: Speedy(); ~Speedy(); virtual void calculateNewDestination(Vector2, Vector2, char); private: Vector2 home; };
47b823ec7e37c15e0690b341f4432a6b58857988
5521a03064928d63cc199e8034e4ea76264f76da
/fboss/agent/platforms/tests/utils/BcmTestWedge100Platform.cpp
b272c4970215f2bb4ae1544c91de98e86dc034de
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
facebook/fboss
df190fd304e0bf5bfe4b00af29f36b55fa00efad
81e02db57903b4369200eec7ef22d882da93c311
refs/heads/main
2023-09-01T18:21:22.565059
2023-09-01T15:53:39
2023-09-01T15:53:39
31,927,407
925
353
NOASSERTION
2023-09-14T05:44:49
2015-03-09T23:04:15
C++
UTF-8
C++
false
false
1,703
cpp
BcmTestWedge100Platform.cpp
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/platforms/tests/utils/BcmTestWedge100Platform.h" #include "fboss/agent/platforms/common/wedge100/Wedge100PlatformMapping.h" #include "fboss/agent/platforms/tests/utils/BcmTestWedge100Port.h" #include "fboss/agent/platforms/common/utils/Wedge100LedUtils.h" #include "fboss/agent/platforms/wedge/utils/BcmLedUtils.h" namespace facebook::fboss { BcmTestWedge100Platform::BcmTestWedge100Platform( std::unique_ptr<PlatformProductInfo> productInfo) : BcmTestWedgeTomahawkPlatform( std::move(productInfo), std::make_unique<Wedge100PlatformMapping>()) {} std::unique_ptr<BcmTestPort> BcmTestWedge100Platform::createTestPort( PortID id) { return std::make_unique<BcmTestWedge100Port>(id, this); } void BcmTestWedge100Platform::initLEDs(int unit) { BcmTestPlatform::initLEDs( unit, Wedge100LedUtils::defaultLedCode(), Wedge100LedUtils::defaultLedCode()); } bool BcmTestWedge100Platform::verifyLEDStatus(PortID port, bool up) { auto bcmPort = static_cast<BcmTestWedge100Port*>(getPlatformPort(port)); auto expectedVal = Wedge100LedUtils::getExpectedLEDState(bcmPort->numberOfLanes(), up, up); auto currentValue = BcmLedUtils::getWedge100PortStatus(0, port); return (currentValue == static_cast<uint32_t>(expectedVal)) && ((currentValue != 0) == (up == true)); } } // namespace facebook::fboss
63f821ec8147cf4bcbcb9bb56aec9d846f4439b6
183d30ccc4bb09cc89aaacbce9258a73c96d838f
/AveDesk 2.1/AveDeskletFile.h
32936ef5991c8a2fa1919633976ba9381e1542f7
[]
no_license
jackiejohn/AveDesk
6efaa73d6ccd67845eb6f6954a63f412993edbef
8f201dc1e14f65ddcfd1f9d281379f347ed22469
refs/heads/master
2021-05-27T17:50:41.693612
2015-02-21T15:35:43
2015-02-21T15:35:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,655
h
AveDeskletFile.h
// AveDeskletFile.h: Definition of the CAveDeskletFile class // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_AVEDESKLETFILE_H__34C97302_1144_40F0_8D9D_DD05AC7B7017__INCLUDED_) #define AFX_AVEDESKLETFILE_H__34C97302_1144_40F0_8D9D_DD05AC7B7017__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "resource.h" // main symbols #include "avedesk.h" ///////////////////////////////////////////////////////////////////////////// // CAveDeskletFile class CAveDeskletFile : public IDispatchImpl<IAveDeskletFile, &IID_IAveDeskletFile, &LIBID_AveDeskLib>, public ISupportErrorInfo, public CComObjectRoot, public CComCoClass<CAveDeskletFile,&CLSID_AveDeskletFile>, public IDropTarget { public: CAveDeskletFile() {} BEGIN_COM_MAP(CAveDeskletFile) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IAveDeskletFile) COM_INTERFACE_ENTRY(IDropTarget) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() //DECLARE_NOT_AGGREGATABLE(CAveDeskletFile) // Remove the comment from the line above if you don't want your object to // support aggregation. DECLARE_REGISTRY_RESOURCEID(IDR_AveDeskletFile) // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // IAveDeskletFile public: // IDropTarget STDMETHOD(DragEnter)(IDataObject* obj, DWORD dwKeys, POINTL ptl, DWORD* pEffect); STDMETHOD(DragOver)(DWORD dwKeys, POINTL ptl, DWORD * pEffect); STDMETHOD(DragLeave)(); STDMETHOD(Drop)(IDataObject * obj, DWORD dwKeys, POINTL ptl, DWORD *pEffect); }; #endif // !defined(AFX_AVEDESKLETFILE_H__34C97302_1144_40F0_8D9D_DD05AC7B7017__INCLUDED_)
7315c46bc1aea5a268127f890ea3ac898f767c94
afddc057da76a26f489d81baccf3e1e4e043202c
/udc/ast/ReadInteger.cpp
bf2bd16f4162aa630318b08cac8c9a69e12ea23c
[]
no_license
EAirPeter/udc
d2a6df637585da36b617982b4f63d7e20b39319d
8bdff28f44e514ea6456981cb2c31759410ba4b9
refs/heads/master
2020-03-16T09:02:37.240218
2018-07-02T10:48:35
2018-07-02T10:48:35
132,607,475
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
ReadInteger.cpp
#include "../IndentHelper.hpp" #include "ReadInteger.hpp" namespace udc::ast { ReadInteger::ReadInteger(const location &loc) noexcept : ExprBase(loc) {} ReadInteger::~ReadInteger() {} void ReadInteger::Print(std::ostream &os, std::uint32_t cIndent) const { os << Indent(cIndent) << "ReadInteger()"; } }
3b3123a8ccba8371854fc30d7987a676e20697d1
5386915da1b8e7559a8ef726722445d815497a37
/MS_Wissenschaft/MS_Wissenschaft.ino
ff6601b47f27ea4276d9a371b906ae7e9c9fd129
[]
no_license
BaKaRoS/Projekt_BaKaRoS
60089c4951b1052e24cefd1b6789743ff879f27b
1ab7154b466a1134faf74e09f913b6ae8e7aac09
refs/heads/master
2020-03-08T10:29:40.945789
2018-09-10T10:44:15
2018-09-10T10:44:15
128,074,567
1
0
null
2018-04-04T14:31:17
2018-04-04T14:31:17
null
UTF-8
C++
false
false
2,253
ino
MS_Wissenschaft.ino
#include "BLEsimple.h" #include "AccGyro.h" #define FS 10 //sampling rate #define LED_R_PIN 9 #define LED_G_PIN 11 #define LED_B_PIN 10 BLEsimple *ble; String receive_str = ""; //accelerometer AccGyro *accgyro; const uint8_t nrOfDataBytes = 6; byte dataBytes[nrOfDataBytes] = {0, 0, 0, 0, 0, 0}; //time uint32_t t = 0; const uint16_t next = (uint16_t)(1000 / FS); void setup() { Serial.begin(115200); //Serial.println(F("setting up module...")); ble = new BLEsimple("Controller2", 1000000, 4); //Serial.println(F("module is now set up and ready to connect.")); //accelerometer/gyroscope accgyro = new AccGyro(); pinMode(LED_R_PIN, OUTPUT); pinMode(LED_G_PIN, OUTPUT); pinMode(LED_B_PIN, OUTPUT); analogWrite(LED_R_PIN, 255); analogWrite(LED_G_PIN, 255); analogWrite(LED_B_PIN, 255); } void loop() { //send datas via BLE if(ble->isConnected() && millis() > t){ t = millis() + next; //accelerometer & gyroscope accgyro->read(); dataBytes[0] = (byte)(accgyro->getAccX() >> 8); //XACC1 upper byte dataBytes[1] = (byte)accgyro->getAccX(); //XACC2 lower byte dataBytes[2] = (byte)(accgyro->getAccY() >> 8); //YACC1 upper byte dataBytes[3] = (byte)accgyro->getAccY(); //YACC2 lower byte dataBytes[4] = (byte)(accgyro->getAccZ() >> 8); //ZACC1 upper byte dataBytes[5] = (byte)accgyro->getAccZ(); //ZACC2 lower byte ble->sendDataBlock(&dataBytes[0], nrOfDataBytes); //Serial.print(accgyro->getAccX()); //Serial.print(" - "); //Serial.print(accgyro->getAccY()); //Serial.print(" - "); //Serial.print(accgyro->getAccZ()); //Serial.print(" - "); } //receive if(ble->isConnected() && ble->available()){ receive_str = ble->readString(); if(receive_str == "r"){ analogWrite(LED_R_PIN, 0); delay(1000); analogWrite(LED_R_PIN, 255); Serial.println("r"); } if(receive_str == "g"){ analogWrite(LED_G_PIN, 0); delay(1000); analogWrite(LED_G_PIN, 255); Serial.println("g"); } if(receive_str == "b"){ analogWrite(LED_B_PIN, 0); delay(1000); analogWrite(LED_B_PIN, 255); Serial.println("b"); } } }
95d81c24d5fdebe29d4482b98eca09c8833e9cba
3f675146f8244f493409841633d6841380bc1639
/Project1/Bucket.cpp
def3667b66ae399ba07908d73b6628b4f318e477
[]
no_license
Fu4i/Dictionary
05eb39553a28f15489ef4997803beaca33faeb97
1820a92922e81ea1ba92c53627b0cdaf1faef8f9
refs/heads/master
2022-12-17T05:29:03.126680
2020-09-17T11:56:54
2020-09-17T11:56:54
296,312,179
0
0
null
null
null
null
UTF-8
C++
false
false
68
cpp
Bucket.cpp
#include "Bucket.h" Bucket::Bucket() { } Bucket::~Bucket() { }
998de8d4cfc8306ce34d02ccb934dc7a52b33404
091b59690f8916b494de20f6354bab09b5bdbb4a
/Find_All_Substr.cpp
c14ee3a678b99059be1ce7d93fbb45f7736d39ad
[]
no_license
IRON-HAN/hanhan
e1203f9ab537c076f86150322d6e751c9c1555d9
3657b843134aad0b4e8be4ecdded89739b7c51b5
refs/heads/master
2020-08-24T09:11:15.396344
2020-06-17T07:09:32
2020-06-17T07:09:32
216,800,871
1
0
null
null
null
null
UTF-8
C++
false
false
1,460
cpp
Find_All_Substr.cpp
// 查找子串 // 得到所有子串起始处的下标 // 且子串的区间彼此不会重叠 #include <stdio.h> #include <string.h> #define N 30 void Find_All_Index(char *str, char *sub, int *num, int *pos) { int flag = 0; for (int i = 0; i < strlen(str); i++) { if (str[i] == sub[0]) { flag = 1; for (int j = 0; j < strlen(sub); j++) { if ((i + j) >= strlen(str) || str[i + j] != sub[j]) { flag = 0; break; } } } if (flag == 1) { pos[*num] = i; (*num)++; flag = 0; } } return; } int main() { char str1[N * N], str2[N]; gets(str1); gets(str2); int posArray[N]; //存放匹配字符串的位置 int cnt = 0; //记录匹配字符串的个数 int size = strlen(str2); Find_All_Index(str1, str2, &cnt, posArray); int result_Array[N]; result_Array[0] = posArray[0]; int j = 1; int tmp = posArray[0]; for (int i = 1; i < cnt; ++i) { if (posArray[i] - tmp < size) { continue; } else { result_Array[j++] = posArray[i]; tmp = posArray[i]; } } for (int i = 0; i < j; ++i) { printf("%d-%d\n", result_Array[i], result_Array[i] + size - 1); } return 0; }
c23e2bae0849af5db1d849274d86b25c33c814d5
8a25b79aa8f279cb9ec84ae875404bd638bea0e7
/src/FontManager.h
0751fceee8746913e8aec45c7042c8974b62192c
[]
no_license
azhariitd/MyUI
0cb9e20266cfb0a2f81be4ca628d9e9561a0f96c
3a722fa6af458d4a9389aa031d304dae37f05b20
refs/heads/master
2021-01-01T19:15:36.291473
2015-05-25T09:44:16
2015-05-25T09:44:16
29,969,213
0
0
null
null
null
null
UTF-8
C++
false
false
925
h
FontManager.h
#include <vector> #include<GL/glut.h> #include<GL/gl.h> #include<GL/glu.h> #include <ft2build.h> #include <freetype/freetype.h> #include <freetype/ftglyph.h> #include <freetype/ftoutln.h> #include <freetype/fttrigon.h> #include FT_FREETYPE_H #ifndef FONTMGR_INCLUDE__ #define FONTMGR_INCLUDE__ class FontInfo{ private: char fileName[32]; int size; GLuint *textures; GLuint listBase; float *glyphWidth; void MakeTexture(FT_Face face, char ch, GLuint listBase, GLuint *textureId); bool CreateDisplayList(); public: FontInfo(char *fileName_, int size); bool IsFont(char *fileName_, int size); GLuint GetListBase(); void DeleteFont(); float WidthOfString(char* string); void PrintText(char *string); }; class FontManager{ private: static std::vector<FontInfo*> openedFonts; public: FontManager(); FontInfo* OpenFont(char *fileName, int size); void CloseFont(char *fileName, int size); }; #endif
7a501114d2cc25b42d942414c6e23d2098923cd4
d9921b68e2eaf57c857d2d1f7a0e97da69df3b23
/src/db/RsynService.h
8a1769729c8e40d2f7197cce9ecc33f555204169
[ "BSD-3-Clause" ]
permissive
cuhk-eda/cu-gr
111217ea04816d82d8e21a57110ba0d0b414790c
7c6428ad759d4de63be7c5ade97cc0d36f0df0d0
refs/heads/master
2023-03-06T11:39:49.671750
2022-09-22T16:43:01
2022-09-22T16:43:01
224,609,852
103
34
NOASSERTION
2020-11-11T14:39:27
2019-11-28T08:52:13
C++
UTF-8
C++
false
false
599
h
RsynService.h
#pragma once #include "global.h" namespace db { class RsynService { public: Rsyn::PhysicalService* physicalService; // Rsyn::RoutingGuide* routeGuideService; Rsyn::PhysicalDesign physicalDesign; Rsyn::Design design; Rsyn::Module module; void init() { Rsyn::Session session; physicalService = session.getService("rsyn.physical"); // routeGuideService = session.getService("rsyn.routingGuide"); physicalDesign = physicalService->getPhysicalDesign(); design = session.getDesign(); module = design.getTopModule(); } }; }
95031fac5d6a334895599025e4f3b8d710695efb
033ea075704396e3be4b31f27d57e77468e55181
/test/OpenSpaceToolkit/Physics/Environment/Objects/Celestial.test.cpp
38b9ea2ddbb779ef2645943f70f0a8ce2c14e624
[ "Apache-2.0", "MPL-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
open-space-collective/open-space-toolkit-physics
195163d94389c02fa10b2ee5db16660f6742dffa
ea6316e45a1bffb1d22bc124a1f72f5eb3f18456
refs/heads/main
2023-08-11T07:42:09.705555
2023-08-10T17:14:33
2023-08-10T17:14:33
136,835,583
15
3
Apache-2.0
2023-09-14T15:01:46
2018-06-10T18:44:58
C++
UTF-8
C++
false
false
21,669
cpp
Celestial.test.cpp
/// Apache License 2.0 #include <OpenSpaceToolkit/Core/Containers/Map.hpp> #include <OpenSpaceToolkit/Core/Types/Shared.hpp> #include <OpenSpaceToolkit/Core/Types/String.hpp> #include <OpenSpaceToolkit/Core/Types/Weak.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/2D/Objects/Point.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/2D/Objects/Polygon.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Intersection.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Ellipsoid.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/LineString.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Point.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Pyramid.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Segment.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Transformations/Rotations/Quaternion.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/3D/Transformations/Rotations/RotationVector.hpp> #include <OpenSpaceToolkit/Physics/Coordinate/Spherical/LLA.hpp> #include <OpenSpaceToolkit/Physics/Environment.hpp> #include <OpenSpaceToolkit/Physics/Environment/Atmospheric/Earth/Exponential.hpp> #include <OpenSpaceToolkit/Physics/Environment/Ephemerides/Analytical.hpp> #include <OpenSpaceToolkit/Physics/Environment/Gravitational/Spherical.hpp> #include <OpenSpaceToolkit/Physics/Environment/Magnetic/Dipole.hpp> #include <OpenSpaceToolkit/Physics/Environment/Objects/CelestialBodies/Earth.hpp> #include <OpenSpaceToolkit/Physics/Environment/Objects/CelestialBodies/Moon.hpp> #include <OpenSpaceToolkit/Physics/Time/DateTime.hpp> #include <OpenSpaceToolkit/Physics/Time/Duration.hpp> #include <OpenSpaceToolkit/Physics/Time/Instant.hpp> #include <OpenSpaceToolkit/Physics/Time/Interval.hpp> #include <OpenSpaceToolkit/Physics/Time/Scale.hpp> #include <OpenSpaceToolkit/Physics/Units/Derived/Angle.hpp> #include <OpenSpaceToolkit/Physics/Units/Length.hpp> #include <OpenSpaceToolkit/Physics/Units/Mass.hpp> #include <Global.test.hpp> using ostk::core::types::Shared; using ostk::core::types::Real; using ostk::core::types::String; using ostk::math::obj::Vector3d; using ostk::physics::Unit; using ostk::physics::units::Angle; using ostk::physics::units::Length; using ostk::physics::units::Time; using ostk::physics::units::Mass; using ostk::physics::units::Derived; using ostk::physics::data::Vector; using ostk::physics::data::Scalar; using ostk::physics::time::Instant; using ostk::physics::coord::Frame; using ostk::physics::coord::Position; using ostk::physics::coord::spherical::LLA; using ostk::physics::env::obj::Celestial; using ostk::physics::env::Ephemeris; using ostk::physics::env::ephem::Analytical; using GravitationalModel = ostk::physics::environment::gravitational::Model; using MagneticModel = ostk::physics::environment::magnetic::Model; using AtmosphericModel = ostk::physics::environment::atmospheric::Model; using ostk::physics::environment::gravitational::Spherical; using ostk::physics::environment::magnetic::Dipole; using ostk::physics::environment::atmospheric::earth::Exponential; using EarthCelestialBody = ostk::physics::env::obj::celest::Earth; using EarthGravitationalModel = ostk::physics::environment::gravitational::Earth; using EarthMagneticModel = ostk::physics::environment::magnetic::Earth; using EarthAtmosphericModel = ostk::physics::environment::atmospheric::Earth; // TEST (OpenSpaceToolkit_Physics_Environment_Objects_Celestial, Constructor) // { // using ostk::physics::env::Object ; // { // FAIL() ; // } // } TEST(OpenSpaceToolkit_Physics_Environment_Objects_Celestial, accessModel) { const String name = "Some Planet"; const Celestial::Type type = Celestial::Type::Earth; const Derived gravitationalParameter = { 1.0, Derived::Unit::GravitationalParameter(Length::Unit::Meter, Time::Unit::Second) }; const Length equatorialRadius = Length::Kilometers(1000.0); const Real flattening = 0.0; const Real j2 = 0.0; const Real j4 = 0.0; const EarthGravitationalModel::Parameters gravitationalModelParameters = { gravitationalParameter, equatorialRadius, flattening, j2, j4 }; const Shared<Ephemeris> ephemeris = std::make_shared<Analytical>(Frame::ITRF()); { const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, nullptr, nullptr, nullptr, nullptr }; EXPECT_ANY_THROW(celestial.accessGravitationalModel()); EXPECT_ANY_THROW(celestial.accessMagneticModel()); EXPECT_ANY_THROW(celestial.accessAtmosphericModel()); } { const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, ephemeris, nullptr, nullptr, nullptr }; EXPECT_EQ(celestial.accessGravitationalModel(), nullptr); EXPECT_EQ(celestial.accessMagneticModel(), nullptr); EXPECT_EQ(celestial.accessAtmosphericModel(), nullptr); } { const Shared<GravitationalModel> gravitationalModel = std::make_shared<Spherical>(gravitationalModelParameters); const Shared<MagneticModel> magneticModel = std::make_shared<Dipole>(Vector3d {0.0, 0.0, 1.0}); const Shared<AtmosphericModel> atmosphericModel = std::make_shared<Exponential>(); const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, ephemeris, gravitationalModel, magneticModel, atmosphericModel }; EXPECT_NO_THROW(celestial.accessGravitationalModel()); EXPECT_NO_THROW(celestial.accessMagneticModel()); EXPECT_NO_THROW(celestial.accessAtmosphericModel()); } } TEST(OpenSpaceToolkit_Physics_Environment_Objects_Celestial, modelIsDefined) { const String name = "Some Planet"; const Celestial::Type type = Celestial::Type::Earth; const Derived gravitationalParameter = { 1.0, Derived::Unit::GravitationalParameter(Length::Unit::Meter, Time::Unit::Second) }; const Length equatorialRadius = Length::Kilometers(1000.0); const Real flattening = 0.0; const Real j2 = 0.0; const Real j4 = 0.0; const EarthGravitationalModel::Parameters gravitationalModelParameters = { gravitationalParameter, equatorialRadius, flattening, j2, j4 }; const Shared<Ephemeris> ephemeris = std::make_shared<Analytical>(Frame::ITRF()); { const Shared<GravitationalModel> gravitationalModel = std::make_shared<Spherical>(gravitationalModelParameters); const Shared<MagneticModel> magneticModel = std::make_shared<Dipole>(Vector3d {0.0, 0.0, 1.0}); const Shared<AtmosphericModel> atmosphericModel = std::make_shared<Exponential>(); const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, ephemeris, nullptr, nullptr, nullptr }; EXPECT_FALSE(celestial.gravitationalModelIsDefined()); EXPECT_FALSE(celestial.magneticModelIsDefined()); EXPECT_FALSE(celestial.atmosphericModelIsDefined()); } { const Shared<GravitationalModel> undefinedGravitationalModel = std::make_shared<EarthGravitationalModel>(EarthGravitationalModel::Type::Undefined); const Shared<MagneticModel> undefinedMagneticModel = std::make_shared<EarthMagneticModel>(EarthMagneticModel::Type::Undefined); const Shared<AtmosphericModel> undefinedAtmosphericModel = std::make_shared<EarthAtmosphericModel>(EarthAtmosphericModel::Type::Undefined); const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, ephemeris, undefinedGravitationalModel, undefinedMagneticModel, undefinedAtmosphericModel }; EXPECT_FALSE(celestial.gravitationalModelIsDefined()); EXPECT_FALSE(celestial.magneticModelIsDefined()); EXPECT_FALSE(celestial.atmosphericModelIsDefined()); } { const Shared<GravitationalModel> gravitationalModel = std::make_shared<Spherical>(gravitationalModelParameters); const Shared<MagneticModel> magneticModel = std::make_shared<Dipole>(Vector3d {0.0, 0.0, 1.0}); const Shared<AtmosphericModel> atmosphericModel = std::make_shared<Exponential>(); const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, ephemeris, gravitationalModel, magneticModel, atmosphericModel }; EXPECT_TRUE(celestial.gravitationalModelIsDefined()); EXPECT_TRUE(celestial.magneticModelIsDefined()); EXPECT_TRUE(celestial.atmosphericModelIsDefined()); } { const Shared<GravitationalModel> gravitationalModel = std::make_shared<Spherical>(gravitationalModelParameters); const Shared<MagneticModel> magneticModel = std::make_shared<Dipole>(Vector3d {0.0, 0.0, 1.0}); const Shared<AtmosphericModel> atmosphericModel = std::make_shared<Exponential>(); const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, nullptr, gravitationalModel, magneticModel, atmosphericModel }; EXPECT_ANY_THROW(celestial.gravitationalModelIsDefined()); EXPECT_ANY_THROW(celestial.magneticModelIsDefined()); EXPECT_ANY_THROW(celestial.atmosphericModelIsDefined()); } } TEST(OpenSpaceToolkit_Physics_Environment_Objects_Celestial, GetGravitationalFieldAt) { { const String name = "Some Planet"; const Celestial::Type type = Celestial::Type::Earth; const Derived gravitationalParameter = { 1.0, Derived::Unit::GravitationalParameter(Length::Unit::Meter, Time::Unit::Second) }; const Length equatorialRadius = Length::Kilometers(1000.0); const Real flattening = 0.0; const Real j2 = 0.0; const Real j4 = 0.0; const EarthGravitationalModel::Parameters gravitationalModelParameters = { gravitationalParameter, equatorialRadius, flattening, j2, j4 }; const Shared<Ephemeris> ephemeris = std::make_shared<Analytical>(Frame::ITRF()); const Shared<GravitationalModel> gravitationalModel = std::make_shared<Spherical>(gravitationalModelParameters); const Instant instant = Instant::J2000(); const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, ephemeris, gravitationalModel, nullptr, nullptr }; { const Position position = {{1.0, 0.0, 0.0}, Length::Unit::Meter, celestial.accessFrame()}; const Vector gravitationalFieldValue = celestial.getGravitationalFieldAt(position, instant); EXPECT_TRUE(gravitationalFieldValue.isDefined()); EXPECT_TRUE(gravitationalFieldValue.getValue().isNear(Vector3d {-1.0, 0.0, 0.0}, 1e-20)); EXPECT_EQ( Unit::Derived(Derived::Unit::Acceleration(Length::Unit::Meter, Time::Unit::Second)), gravitationalFieldValue.getUnit() ); EXPECT_EQ(Frame::ITRF(), gravitationalFieldValue.getFrame()); } { const Position position = {{0.0, 0.0, 1.0}, Length::Unit::Meter, celestial.accessFrame()}; const Vector gravitationalFieldValue = celestial.getGravitationalFieldAt(position, instant); EXPECT_TRUE(gravitationalFieldValue.isDefined()); EXPECT_TRUE(gravitationalFieldValue.getValue().isNear(Vector3d {0.0, 0.0, -1.0}, 1e-20)); EXPECT_EQ( Unit::Derived(Derived::Unit::Acceleration(Length::Unit::Meter, Time::Unit::Second)), gravitationalFieldValue.getUnit() ); EXPECT_EQ(Frame::ITRF(), gravitationalFieldValue.getFrame()); } { const Position position = {{2.0, 0.0, 0.0}, Length::Unit::Meter, celestial.accessFrame()}; const Vector gravitationalFieldValue = celestial.getGravitationalFieldAt(position, instant); EXPECT_TRUE(gravitationalFieldValue.isDefined()); EXPECT_TRUE(gravitationalFieldValue.getValue().isNear(Vector3d {-0.25, 0.0, 0.0}, 1e-20)); EXPECT_EQ( Unit::Derived(Derived::Unit::Acceleration(Length::Unit::Meter, Time::Unit::Second)), gravitationalFieldValue.getUnit() ); EXPECT_EQ(Frame::ITRF(), gravitationalFieldValue.getFrame()); } } } TEST(OpenSpaceToolkit_Physics_Environment_Objects_Celestial, GetMagneticFieldAt) { { const String name = "Some Planet"; const Celestial::Type type = Celestial::Type::Earth; const Derived gravitationalParameter = { 1.0, Derived::Unit::GravitationalParameter(Length::Unit::Meter, Time::Unit::Second) }; const Length equatorialRadius = Length::Kilometers(1000.0); const Real flattening = 0.0; const Real j2 = 0.0; const Real j4 = 0.0; const Shared<Ephemeris> ephemeris = std::make_shared<Analytical>(Frame::ITRF()); const Shared<MagneticModel> magneticModel = std::make_shared<Dipole>(Vector3d {0.0, 0.0, 1.0}); const Instant instant = Instant::J2000(); const Celestial celestial = { name, type, gravitationalParameter, equatorialRadius, flattening, j2, j4, ephemeris, nullptr, magneticModel, nullptr }; { const Position position = {{1.0, 0.0, 0.0}, Length::Unit::Meter, celestial.accessFrame()}; const Vector magneticFieldValue = celestial.getMagneticFieldAt(position, instant); EXPECT_TRUE(magneticFieldValue.isDefined()); EXPECT_TRUE(magneticFieldValue.getValue().isNear(Vector3d {0.0, 0.0, -1e-07}, 1e-20)); EXPECT_EQ(Unit::Derived(Derived::Unit::Tesla()), magneticFieldValue.getUnit()); EXPECT_EQ(Frame::ITRF(), magneticFieldValue.getFrame()); } { const Position position = {{0.0, 0.0, 1.0}, Length::Unit::Meter, celestial.accessFrame()}; const Vector magneticFieldValue = celestial.getMagneticFieldAt(position, instant); EXPECT_TRUE(magneticFieldValue.isDefined()); EXPECT_TRUE(magneticFieldValue.getValue().isNear(Vector3d {0.0, 0.0, +2e-07}, 1e-20)); EXPECT_EQ(Unit::Derived(Derived::Unit::Tesla()), magneticFieldValue.getUnit()); EXPECT_EQ(Frame::ITRF(), magneticFieldValue.getFrame()); } { const Position position = {{2.0, 0.0, 0.0}, Length::Unit::Meter, celestial.accessFrame()}; const Vector magneticFieldValue = celestial.getMagneticFieldAt(position, instant); EXPECT_TRUE(magneticFieldValue.isDefined()); EXPECT_TRUE(magneticFieldValue.getValue().isNear(Vector3d {0.0, 0.0, -1.25e-08}, 1e-20)); EXPECT_EQ(Unit::Derived(Derived::Unit::Tesla()), magneticFieldValue.getUnit()); EXPECT_EQ(Frame::ITRF(), magneticFieldValue.getFrame()); } } } TEST(OpenSpaceToolkit_Physics_Environment_Objects_Celestial, GetAtmosphericDensityAt) { { const String name = "Some Planet"; const Celestial::Type type = Celestial::Type::Earth; const Derived gravitationalParameter = { 1.0, Derived::Unit::GravitationalParameter(Length::Unit::Meter, Time::Unit::Second) }; const Real j2 = 0.0; const Real j4 = 0.0; const Shared<Ephemeris> ephemeris = std::make_shared<Analytical>(Frame::ITRF()); const Shared<AtmosphericModel> atmosphericModel = std::make_shared<Exponential>(); const Instant instant = Instant::J2000(); const Celestial celestial = { name, type, gravitationalParameter, EarthGravitationalModel::EGM2008.equatorialRadius_, EarthGravitationalModel::EGM2008.flattening_, j2, j4, ephemeris, nullptr, nullptr, atmosphericModel }; { const Position position = { LLA(Angle::Degrees(35.076832), Angle::Degrees(-92.546296), Length::Kilometers(123.0)) .toCartesian( EarthGravitationalModel::EGM2008.equatorialRadius_, EarthGravitationalModel::EGM2008.flattening_ ), Position::Unit::Meter, Frame::ITRF() }; const Scalar atmosphericDensityValue = celestial.getAtmosphericDensityAt(position, instant); EXPECT_TRUE(atmosphericDensityValue.isDefined()); EXPECT_TRUE(atmosphericDensityValue.getValue().isNear(1.77622e-08, 1e-13)); EXPECT_EQ( Unit::Derived(Derived::Unit::MassDensity(Mass::Unit::Kilogram, Length::Unit::Meter)), atmosphericDensityValue.getUnit() ); } { const Position position = { LLA(Angle::Degrees(35.076832), Angle::Degrees(-92.546296), Length::Kilometers(499.0)) .toCartesian( EarthGravitationalModel::EGM2008.equatorialRadius_, EarthGravitationalModel::EGM2008.flattening_ ), Position::Unit::Meter, Frame::ITRF() }; const Scalar atmosphericDensityValue = celestial.getAtmosphericDensityAt(position, instant); EXPECT_TRUE(atmosphericDensityValue.isDefined()); EXPECT_TRUE(atmosphericDensityValue.getValue().isNear(7.08245e-13, 1e-15)); EXPECT_EQ( Unit::Derived(Derived::Unit::MassDensity(Mass::Unit::Kilogram, Length::Unit::Meter)), atmosphericDensityValue.getUnit() ); } { const Position position = { LLA(Angle::Degrees(35.076832), Angle::Degrees(-92.546296), Length::Kilometers(501.0)) .toCartesian( EarthGravitationalModel::EGM2008.equatorialRadius_, EarthGravitationalModel::EGM2008.flattening_ ), Position::Unit::Meter, Frame::ITRF() }; const Scalar atmosphericDensityValue = celestial.getAtmosphericDensityAt(position, instant); EXPECT_TRUE(atmosphericDensityValue.isDefined()); EXPECT_TRUE(atmosphericDensityValue.getValue().isNear(6.85869e-13, 1e-15)); EXPECT_EQ( Unit::Derived(Derived::Unit::MassDensity(Mass::Unit::Kilogram, Length::Unit::Meter)), atmosphericDensityValue.getUnit() ); } { EXPECT_ANY_THROW(celestial.getAtmosphericDensityAt(Position::Undefined(), instant)); } { const Position position = { LLA(Angle::Degrees(35.076832), Angle::Degrees(-92.546296), Length::Kilometers(501.0)) .toCartesian( EarthGravitationalModel::EGM2008.equatorialRadius_, EarthGravitationalModel::EGM2008.flattening_ ), Position::Unit::Meter, Frame::ITRF() }; EXPECT_ANY_THROW(Celestial::Undefined().getAtmosphericDensityAt(position, instant)); } { const Position position = { LLA(Angle::Degrees(35.076832), Angle::Degrees(-92.546296), Length::Kilometers(501.0)) .toCartesian( EarthGravitationalModel::EGM2008.equatorialRadius_, EarthGravitationalModel::EGM2008.flattening_ ), Position::Unit::Meter, Frame::ITRF() }; const Celestial celestialWithoutAtmospheric = { name, type, gravitationalParameter, EarthGravitationalModel::EGM2008.equatorialRadius_, EarthGravitationalModel::EGM2008.flattening_, j2, j4, ephemeris, nullptr, nullptr, nullptr }; EXPECT_ANY_THROW(celestialWithoutAtmospheric.getAtmosphericDensityAt(position, instant)); } { EXPECT_ANY_THROW(celestial.getAtmosphericDensityAt(Position::Undefined(), instant)); } { EXPECT_ANY_THROW(Celestial::Undefined().getAtmosphericDensityAt(Position::Undefined(), instant)); } } }
870fde2f819992bb9ec18154e66cc3e8b6894028
012f0800c635f23d069f0c400768bc58cc1a0574
/hhvm/hhvm-3.17/third-party/thrift/src/thrift/compiler/test/fixtures/refs/gen-cpp/module_types.cpp
16c2632030f175b032dbfff4a6d6580cba101abf
[ "Apache-2.0", "Zend-2.0", "BSD-3-Clause", "PHP-3.01" ]
permissive
chrispcx/es-hhvm
c127840387ee17789840ea788e308b711d3986a1
220fd9627b1b168271112d33747a233a91e8a268
refs/heads/master
2021-01-11T18:13:42.713724
2017-02-07T02:02:10
2017-02-07T02:02:10
79,519,670
5
0
null
null
null
null
UTF-8
C++
false
false
51,450
cpp
module_types.cpp
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "thrift/compiler/test/fixtures/refs/gen-cpp/module_types.h" #include "thrift/compiler/test/fixtures/refs/gen-cpp/module_reflection.h" #include <algorithm> #include <string.h> const typename apache::thrift::detail::TEnumMapFactory<TypedEnum, short>::ValuesToNamesMapType _TypedEnum_VALUES_TO_NAMES = apache::thrift::detail::TEnumMapFactory<TypedEnum, short>::makeValuesToNamesMap(); const typename apache::thrift::detail::TEnumMapFactory<TypedEnum, short>::NamesToValuesMapType _TypedEnum_NAMES_TO_VALUES = apache::thrift::detail::TEnumMapFactory<TypedEnum, short>::makeNamesToValuesMap(); namespace apache { namespace thrift { template<> folly::Range<const std::pair< ::TypedEnum, folly::StringPiece>*> TEnumTraitsBase< ::TypedEnum>::enumerators() { static constexpr const std::pair< ::TypedEnum, folly::StringPiece> storage[2] = { { ::TypedEnum::VAL1, "VAL1"}, { ::TypedEnum::VAL2, "VAL2"}, }; return folly::range(storage); } template<> const char* TEnumTraitsBase< ::TypedEnum>::findName( ::TypedEnum value) { return findName( ::_TypedEnum_VALUES_TO_NAMES, value); } template<> bool TEnumTraitsBase< ::TypedEnum>::findValue(const char* name, ::TypedEnum* out) { return findValue( ::_TypedEnum_NAMES_TO_VALUES, name, out); } }} // apache::thrift uint32_t MyUnion::read(apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == apache::thrift::protocol::T_STOP) { __clear(); } else { switch (fid) { case 1: { if (ftype == apache::thrift::protocol::T_I32) { set_anInteger(); xfer += iprot->readI32(this->value_.anInteger); } else { xfer += iprot->skip(ftype); } break; } case 2: { if (ftype == apache::thrift::protocol::T_STRING) { set_aString(); xfer += iprot->readString(this->value_.aString); } else { xfer += iprot->skip(ftype); } break; } default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); xfer += iprot->readFieldBegin(fname, ftype, fid); if (UNLIKELY(ftype != apache::thrift::protocol::T_STOP)) { using apache::thrift::protocol::TProtocolException; TProtocolException::throwUnionMissingStop(); } } xfer += iprot->readStructEnd(); return xfer; } uint32_t MyUnion::write(apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("MyUnion"); switch (type_) { case Type::anInteger: { xfer += oprot->writeFieldBegin("anInteger", apache::thrift::protocol::T_I32, 1); xfer += oprot->writeI32(this->value_.anInteger); xfer += oprot->writeFieldEnd(); break; } case Type::aString: { xfer += oprot->writeFieldBegin("aString", apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->value_.aString); xfer += oprot->writeFieldEnd(); break; } case Type::__EMPTY__:; } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } const uint64_t MyField::_reflection_id; void MyField::_reflection_register(::apache::thrift::reflection::Schema& schema) { ::module_reflection_::reflectionInitializer_16778989117799402412(schema); } bool MyField::operator == (const MyField & rhs) const { if (__isset.opt_value != rhs.__isset.opt_value) return false; else if (__isset.opt_value && !(opt_value == rhs.opt_value)) return false; if (!(this->value == rhs.value)) return false; if (!(this->req_value == rhs.req_value)) return false; return true; } uint32_t MyField::read(apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; apache::thrift::protocol::TType ftype; int16_t fid; ::apache::thrift::reflection::Schema * schema = iprot->getSchema(); if (schema != nullptr) { ::module_reflection_::reflectionInitializer_16778989117799402412(*schema); iprot->setNextStructType(MyField::_reflection_id); } xfer += iprot->readStructBegin(fname); using apache::thrift::protocol::TProtocolException; bool isset_req_value = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->opt_value); this->__isset.opt_value = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->value); this->__isset.value = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->req_value); isset_req_value = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_req_value) throw TProtocolException(TProtocolException::MISSING_REQUIRED_FIELD, "Required field 'req_value' was not found in serialized data! Struct: MyField"); return xfer; } void MyField::__clear() { opt_value = 0; value = 0; req_value = 0; __isset.__clear(); } uint32_t MyField::write(apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("MyField"); if (this->__isset.opt_value) { xfer += oprot->writeFieldBegin("opt_value", apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64(this->opt_value); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldBegin("value", apache::thrift::protocol::T_I64, 2); xfer += oprot->writeI64(this->value); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("req_value", apache::thrift::protocol::T_I64, 3); xfer += oprot->writeI64(this->req_value); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(MyField &a, MyField &b) { using ::std::swap; (void)a; (void)b; swap(a.opt_value, b.opt_value); swap(a.value, b.value); swap(a.req_value, b.req_value); swap(a.__isset, b.__isset); } void merge(const MyField& from, MyField& to) { using apache::thrift::merge; if (from.__isset.opt_value) { merge(from.opt_value, to.opt_value); to.__isset.opt_value = true; } merge(from.value, to.value); to.__isset.value = to.__isset.value || from.__isset.value; merge(from.req_value, to.req_value); } void merge(MyField&& from, MyField& to) { using apache::thrift::merge; if (from.__isset.opt_value) { merge(std::move(from.opt_value), to.opt_value); to.__isset.opt_value = true; } merge(std::move(from.value), to.value); to.__isset.value = to.__isset.value || from.__isset.value; merge(std::move(from.req_value), to.req_value); } const uint64_t MyStruct::_reflection_id; void MyStruct::_reflection_register(::apache::thrift::reflection::Schema& schema) { ::module_reflection_::reflectionInitializer_7958971832214294220(schema); } MyStruct::MyStruct(const MyStruct& src1) { if (src1.opt_ref) opt_ref.reset(new MyField(*src1.opt_ref)); if (src1.ref) ref.reset(new MyField(*src1.ref)); if (src1.req_ref) req_ref.reset(new MyField(*src1.req_ref)); } bool MyStruct::operator == (const MyStruct & rhs) const { if (bool(opt_ref) != bool(rhs.opt_ref)) return false; else if (bool(opt_ref) && !(*opt_ref == *rhs.opt_ref)) return false; if (bool(ref) != bool(rhs.ref)) return false; else if (bool(ref) && !(*ref == *rhs.ref)) return false; if (bool(req_ref) != bool(rhs.req_ref)) return false; else if (bool(req_ref) && !(*req_ref == *rhs.req_ref)) return false; return true; } uint32_t MyStruct::read(apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; apache::thrift::protocol::TType ftype; int16_t fid; ::apache::thrift::reflection::Schema * schema = iprot->getSchema(); if (schema != nullptr) { ::module_reflection_::reflectionInitializer_7958971832214294220(*schema); iprot->setNextStructType(MyStruct::_reflection_id); } xfer += iprot->readStructBegin(fname); using apache::thrift::protocol::TProtocolException; std::exception_ptr exception; bool isset_req_ref = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == apache::thrift::protocol::T_STRUCT) { try { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->opt_ref)>::type::element_type>::type; std::unique_ptr<element_type> _ptype3(new element_type()); xfer += _ptype3->read(iprot); this->opt_ref = std::move(_ptype3); if (false) { } else if (this->opt_ref->__isset.opt_value) { } else if (this->opt_ref->__isset.value) { } else { this->opt_ref = nullptr; } } catch (const TProtocolException& e) { if (e.getType() != TProtocolException::MISSING_REQUIRED_FIELD) { throw; } exception = std::current_exception(); } } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == apache::thrift::protocol::T_STRUCT) { try { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->ref)>::type::element_type>::type; std::unique_ptr<element_type> _ptype4(new element_type()); xfer += _ptype4->read(iprot); this->ref = std::move(_ptype4); if (false) { } else if (this->ref->__isset.opt_value) { } else if (this->ref->__isset.value) { } else { this->ref = nullptr; } } catch (const TProtocolException& e) { if (e.getType() != TProtocolException::MISSING_REQUIRED_FIELD) { throw; } exception = std::current_exception(); } } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == apache::thrift::protocol::T_STRUCT) { try { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->req_ref)>::type::element_type>::type; std::unique_ptr<element_type> _ptype5(new element_type()); xfer += _ptype5->read(iprot); this->req_ref = std::move(_ptype5); if (false) { } else if (this->req_ref->__isset.opt_value) { } else if (this->req_ref->__isset.value) { } else { this->req_ref = nullptr; } } catch (const TProtocolException& e) { if (e.getType() != TProtocolException::MISSING_REQUIRED_FIELD) { throw; } exception = std::current_exception(); } isset_req_ref = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (exception != std::exception_ptr()) { std::rethrow_exception(exception); } if (!isset_req_ref) throw TProtocolException(TProtocolException::MISSING_REQUIRED_FIELD, "Required field 'req_ref' was not found in serialized data! Struct: MyStruct"); return xfer; } void MyStruct::__clear() { if (opt_ref) opt_ref->__clear(); if (ref) ref->__clear(); if (req_ref) req_ref->__clear(); __isset.__clear(); } uint32_t MyStruct::write(apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("MyStruct"); if (this->opt_ref) { xfer += oprot->writeFieldBegin("opt_ref", apache::thrift::protocol::T_STRUCT, 1); if (this->opt_ref) {xfer += this->opt_ref->write(oprot); } else {oprot->writeStructBegin("MyField"); oprot->writeStructEnd(); oprot->writeFieldStop();} xfer += oprot->writeFieldEnd(); } if (this->ref) { xfer += oprot->writeFieldBegin("ref", apache::thrift::protocol::T_STRUCT, 2); if (this->ref) {xfer += this->ref->write(oprot); } else {oprot->writeStructBegin("MyField"); oprot->writeStructEnd(); oprot->writeFieldStop();} xfer += oprot->writeFieldEnd(); } if (this->req_ref) { xfer += oprot->writeFieldBegin("req_ref", apache::thrift::protocol::T_STRUCT, 3); if (this->req_ref) {xfer += this->req_ref->write(oprot); } else {oprot->writeStructBegin("MyField"); oprot->writeStructEnd(); oprot->writeFieldStop();} xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(MyStruct &a, MyStruct &b) { using ::std::swap; (void)a; (void)b; swap(a.opt_ref, b.opt_ref); swap(a.ref, b.ref); swap(a.req_ref, b.req_ref); swap(a.__isset, b.__isset); } void merge(const MyStruct& from, MyStruct& to) { using apache::thrift::merge; merge(from.opt_ref, to.opt_ref); merge(from.ref, to.ref); merge(from.req_ref, to.req_ref); } void merge(MyStruct&& from, MyStruct& to) { using apache::thrift::merge; merge(std::move(from.opt_ref), to.opt_ref); merge(std::move(from.ref), to.ref); merge(std::move(from.req_ref), to.req_ref); } const uint64_t StructWithUnion::_reflection_id; void StructWithUnion::_reflection_register(::apache::thrift::reflection::Schema& schema) { ::module_reflection_::reflectionInitializer_11295191354176986988(schema); } StructWithUnion::StructWithUnion(const StructWithUnion& src6) { if (src6.u) u.reset(new MyUnion(*src6.u)); aDouble = src6.aDouble; __isset.aDouble = src6.__isset.aDouble; f = src6.f; __isset.f = src6.__isset.f; } bool StructWithUnion::operator == (const StructWithUnion & rhs) const { if (bool(u) != bool(rhs.u)) return false; else if (bool(u) && !(*u == *rhs.u)) return false; if (!(this->aDouble == rhs.aDouble)) return false; if (!(this->f == rhs.f)) return false; return true; } uint32_t StructWithUnion::read(apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; apache::thrift::protocol::TType ftype; int16_t fid; ::apache::thrift::reflection::Schema * schema = iprot->getSchema(); if (schema != nullptr) { ::module_reflection_::reflectionInitializer_11295191354176986988(*schema); iprot->setNextStructType(StructWithUnion::_reflection_id); } xfer += iprot->readStructBegin(fname); using apache::thrift::protocol::TProtocolException; std::exception_ptr exception; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == apache::thrift::protocol::T_STRUCT) { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->u)>::type::element_type>::type; std::unique_ptr<element_type> _ptype8(new element_type()); xfer += _ptype8->read(iprot); this->u = std::move(_ptype8); if (this->u->getType() == MyUnion::Type::__EMPTY__) { this->u = nullptr; } } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == apache::thrift::protocol::T_DOUBLE) { xfer += iprot->readDouble(this->aDouble); this->__isset.aDouble = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == apache::thrift::protocol::T_STRUCT) { try { xfer += this->f.read(iprot); } catch (const TProtocolException& e) { if (e.getType() != TProtocolException::MISSING_REQUIRED_FIELD) { throw; } exception = std::current_exception(); } this->__isset.f = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (exception != std::exception_ptr()) { std::rethrow_exception(exception); } return xfer; } void StructWithUnion::__clear() { if (u) u->__clear(); aDouble = 0; f.__clear(); __isset.__clear(); } uint32_t StructWithUnion::write(apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("StructWithUnion"); if (this->u) { xfer += oprot->writeFieldBegin("u", apache::thrift::protocol::T_STRUCT, 1); if (this->u) {xfer += this->u->write(oprot); } else {oprot->writeStructBegin("MyUnion"); oprot->writeStructEnd(); oprot->writeFieldStop();} xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldBegin("aDouble", apache::thrift::protocol::T_DOUBLE, 2); xfer += oprot->writeDouble(this->aDouble); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("f", apache::thrift::protocol::T_STRUCT, 3); xfer += this->f.write(oprot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(StructWithUnion &a, StructWithUnion &b) { using ::std::swap; (void)a; (void)b; swap(a.u, b.u); swap(a.aDouble, b.aDouble); swap(a.f, b.f); swap(a.__isset, b.__isset); } void merge(const StructWithUnion& from, StructWithUnion& to) { using apache::thrift::merge; merge(from.u, to.u); merge(from.aDouble, to.aDouble); to.__isset.aDouble = to.__isset.aDouble || from.__isset.aDouble; merge(from.f, to.f); to.__isset.f = to.__isset.f || from.__isset.f; } void merge(StructWithUnion&& from, StructWithUnion& to) { using apache::thrift::merge; merge(std::move(from.u), to.u); merge(std::move(from.aDouble), to.aDouble); to.__isset.aDouble = to.__isset.aDouble || from.__isset.aDouble; merge(std::move(from.f), to.f); to.__isset.f = to.__isset.f || from.__isset.f; } const uint64_t RecursiveStruct::_reflection_id; void RecursiveStruct::_reflection_register(::apache::thrift::reflection::Schema& schema) { ::module_reflection_::reflectionInitializer_2826922994162023308(schema); } bool RecursiveStruct::operator == (const RecursiveStruct & rhs) const { if (__isset.mes != rhs.__isset.mes) return false; else if (__isset.mes && !(mes == rhs.mes)) return false; return true; } uint32_t RecursiveStruct::read(apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; apache::thrift::protocol::TType ftype; int16_t fid; ::apache::thrift::reflection::Schema * schema = iprot->getSchema(); if (schema != nullptr) { ::module_reflection_::reflectionInitializer_2826922994162023308(*schema); iprot->setNextStructType(RecursiveStruct::_reflection_id); } xfer += iprot->readStructBegin(fname); using apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == apache::thrift::protocol::T_LIST) { { this->mes.clear(); uint32_t _size10; bool _sizeUnknown11; apache::thrift::protocol::TType _etype14; xfer += iprot->readListBegin(_etype14, _size10, _sizeUnknown11); if (!_sizeUnknown11) { this->mes.resize(_size10); uint32_t _i16; for (_i16 = 0; _i16 < _size10; ++_i16) { xfer += this->mes[_i16].read(iprot); } } else { while (iprot->peekList()) { RecursiveStruct _elem17; xfer += _elem17.read(iprot); this->mes.push_back(_elem17); } } xfer += iprot->readListEnd(); } this->__isset.mes = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } void RecursiveStruct::__clear() { mes.clear(); __isset.__clear(); } uint32_t RecursiveStruct::write(apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("RecursiveStruct"); if (this->__isset.mes) { xfer += oprot->writeFieldBegin("mes", apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(apache::thrift::protocol::T_STRUCT, this->mes.size()); std::vector<RecursiveStruct> ::const_iterator _iter18; for (_iter18 = this->mes.begin(); _iter18 != this->mes.end(); ++_iter18) { xfer += (*_iter18).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(RecursiveStruct &a, RecursiveStruct &b) { using ::std::swap; (void)a; (void)b; swap(a.mes, b.mes); swap(a.__isset, b.__isset); } void merge(const RecursiveStruct& from, RecursiveStruct& to) { using apache::thrift::merge; if (from.__isset.mes) { merge(from.mes, to.mes); to.__isset.mes = true; } } void merge(RecursiveStruct&& from, RecursiveStruct& to) { using apache::thrift::merge; if (from.__isset.mes) { merge(std::move(from.mes), to.mes); to.__isset.mes = true; } } const uint64_t StructWithContainers::_reflection_id; void StructWithContainers::_reflection_register(::apache::thrift::reflection::Schema& schema) { ::module_reflection_::reflectionInitializer_18101585657679500556(schema); } StructWithContainers::StructWithContainers(const StructWithContainers& src19) { if (src19.list_ref) list_ref.reset(new std::vector<int32_t> (*src19.list_ref)); if (src19.set_ref) set_ref.reset(new std::set<int32_t> (*src19.set_ref)); if (src19.map_ref) map_ref.reset(new std::map<int32_t, int32_t> (*src19.map_ref)); if (src19.list_ref_unique) list_ref_unique.reset(new std::vector<int32_t> (*src19.list_ref_unique)); set_ref_shared = src19.set_ref_shared; map_ref_custom = src19.map_ref_custom; list_ref_shared_const = src19.list_ref_shared_const; if (src19.set_custom_ref) set_custom_ref.reset(new std::set<int32_t> (*src19.set_custom_ref)); } bool StructWithContainers::operator == (const StructWithContainers & rhs) const { if (bool(list_ref) != bool(rhs.list_ref)) return false; else if (bool(list_ref) && !(*list_ref == *rhs.list_ref)) return false; if (bool(set_ref) != bool(rhs.set_ref)) return false; else if (bool(set_ref) && !(*set_ref == *rhs.set_ref)) return false; if (bool(map_ref) != bool(rhs.map_ref)) return false; else if (bool(map_ref) && !(*map_ref == *rhs.map_ref)) return false; if (bool(list_ref_unique) != bool(rhs.list_ref_unique)) return false; else if (bool(list_ref_unique) && !(*list_ref_unique == *rhs.list_ref_unique)) return false; if (bool(set_ref_shared) != bool(rhs.set_ref_shared)) return false; else if (bool(set_ref_shared) && !(*set_ref_shared == *rhs.set_ref_shared)) return false; if (bool(map_ref_custom) != bool(rhs.map_ref_custom)) return false; else if (bool(map_ref_custom) && !(*map_ref_custom == *rhs.map_ref_custom)) return false; if (bool(list_ref_shared_const) != bool(rhs.list_ref_shared_const)) return false; else if (bool(list_ref_shared_const) && !(*list_ref_shared_const == *rhs.list_ref_shared_const)) return false; if (bool(set_custom_ref) != bool(rhs.set_custom_ref)) return false; else if (bool(set_custom_ref) && !(*set_custom_ref == *rhs.set_custom_ref)) return false; return true; } uint32_t StructWithContainers::read(apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; apache::thrift::protocol::TType ftype; int16_t fid; ::apache::thrift::reflection::Schema * schema = iprot->getSchema(); if (schema != nullptr) { ::module_reflection_::reflectionInitializer_18101585657679500556(*schema); iprot->setNextStructType(StructWithContainers::_reflection_id); } xfer += iprot->readStructBegin(fname); using apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == apache::thrift::protocol::T_LIST) { { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->list_ref)>::type::element_type>::type; std::unique_ptr<element_type> _ptype26(new element_type()); auto& _rtype27 = *_ptype26; _rtype27.clear(); uint32_t _size21; bool _sizeUnknown22; apache::thrift::protocol::TType _etype25; xfer += iprot->readListBegin(_etype25, _size21, _sizeUnknown22); if (!_sizeUnknown22) { _rtype27.resize(_size21); uint32_t _i28; for (_i28 = 0; _i28 < _size21; ++_i28) { xfer += iprot->readI32(_rtype27[_i28]); } } else { while (iprot->peekList()) { int32_t _elem29; xfer += iprot->readI32(_elem29); _rtype27.push_back(_elem29); } } this->list_ref = std::move(_ptype26); xfer += iprot->readListEnd(); } } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == apache::thrift::protocol::T_SET) { { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->set_ref)>::type::element_type>::type; std::unique_ptr<element_type> _ptype35(new element_type()); auto& _rtype36 = *_ptype35; _rtype36.clear(); uint32_t _size30; bool _sizeUnknown31; apache::thrift::protocol::TType _etype34; xfer += iprot->readSetBegin(_etype34, _size30, _sizeUnknown31); if (!_sizeUnknown31) { uint32_t _i37; for (_i37 = 0; _i37 < _size30; ++_i37) { int32_t _elem38; xfer += iprot->readI32(_elem38); _rtype36.insert(_elem38); } } else { while (iprot->peekSet()) { int32_t _elem39; xfer += iprot->readI32(_elem39); _rtype36.insert(_elem39); } } this->set_ref = std::move(_ptype35); xfer += iprot->readSetEnd(); } } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == apache::thrift::protocol::T_MAP) { { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->map_ref)>::type::element_type>::type; std::unique_ptr<element_type> _ptype45(new element_type()); auto& _rtype46 = *_ptype45; _rtype46.clear(); uint32_t _size40; bool _sizeUnknown41; apache::thrift::protocol::TType _ktype42; apache::thrift::protocol::TType _vtype43; xfer += iprot->readMapBegin(_ktype42, _vtype43, _size40, _sizeUnknown41); if (!_sizeUnknown41) { uint32_t _i47; for (_i47 = 0; _i47 < _size40; ++_i47) { int32_t _key48; xfer += iprot->readI32(_key48); int32_t& _val49 = _rtype46[_key48]; xfer += iprot->readI32(_val49); } } else { while (iprot->peekMap()) { int32_t _key50; xfer += iprot->readI32(_key50); int32_t& _val51 = _rtype46[_key50]; xfer += iprot->readI32(_val51); } } this->map_ref = std::move(_ptype45); xfer += iprot->readMapEnd(); } } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == apache::thrift::protocol::T_LIST) { { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->list_ref_unique)>::type::element_type>::type; std::unique_ptr<element_type> _ptype57(new element_type()); auto& _rtype58 = *_ptype57; _rtype58.clear(); uint32_t _size52; bool _sizeUnknown53; apache::thrift::protocol::TType _etype56; xfer += iprot->readListBegin(_etype56, _size52, _sizeUnknown53); if (!_sizeUnknown53) { _rtype58.resize(_size52); uint32_t _i59; for (_i59 = 0; _i59 < _size52; ++_i59) { xfer += iprot->readI32(_rtype58[_i59]); } } else { while (iprot->peekList()) { int32_t _elem60; xfer += iprot->readI32(_elem60); _rtype58.push_back(_elem60); } } this->list_ref_unique = std::move(_ptype57); xfer += iprot->readListEnd(); } } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == apache::thrift::protocol::T_SET) { { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->set_ref_shared)>::type::element_type>::type; std::unique_ptr<element_type> _ptype66(new element_type()); auto& _rtype67 = *_ptype66; _rtype67.clear(); uint32_t _size61; bool _sizeUnknown62; apache::thrift::protocol::TType _etype65; xfer += iprot->readSetBegin(_etype65, _size61, _sizeUnknown62); if (!_sizeUnknown62) { uint32_t _i68; for (_i68 = 0; _i68 < _size61; ++_i68) { int32_t _elem69; xfer += iprot->readI32(_elem69); _rtype67.insert(_elem69); } } else { while (iprot->peekSet()) { int32_t _elem70; xfer += iprot->readI32(_elem70); _rtype67.insert(_elem70); } } this->set_ref_shared = std::move(_ptype66); xfer += iprot->readSetEnd(); } } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == apache::thrift::protocol::T_MAP) { { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->map_ref_custom)>::type::element_type>::type; std::unique_ptr<element_type> _ptype76(new element_type()); auto& _rtype77 = *_ptype76; _rtype77.clear(); uint32_t _size71; bool _sizeUnknown72; apache::thrift::protocol::TType _ktype73; apache::thrift::protocol::TType _vtype74; xfer += iprot->readMapBegin(_ktype73, _vtype74, _size71, _sizeUnknown72); if (!_sizeUnknown72) { uint32_t _i78; for (_i78 = 0; _i78 < _size71; ++_i78) { int32_t _key79; xfer += iprot->readI32(_key79); int32_t& _val80 = _rtype77[_key79]; xfer += iprot->readI32(_val80); } } else { while (iprot->peekMap()) { int32_t _key81; xfer += iprot->readI32(_key81); int32_t& _val82 = _rtype77[_key81]; xfer += iprot->readI32(_val82); } } this->map_ref_custom = std::move(_ptype76); xfer += iprot->readMapEnd(); } } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == apache::thrift::protocol::T_LIST) { { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->list_ref_shared_const)>::type::element_type>::type; std::unique_ptr<element_type> _ptype88(new element_type()); auto& _rtype89 = *_ptype88; _rtype89.clear(); uint32_t _size83; bool _sizeUnknown84; apache::thrift::protocol::TType _etype87; xfer += iprot->readListBegin(_etype87, _size83, _sizeUnknown84); if (!_sizeUnknown84) { _rtype89.resize(_size83); uint32_t _i90; for (_i90 = 0; _i90 < _size83; ++_i90) { xfer += iprot->readI32(_rtype89[_i90]); } } else { while (iprot->peekList()) { int32_t _elem91; xfer += iprot->readI32(_elem91); _rtype89.push_back(_elem91); } } this->list_ref_shared_const = std::move(_ptype88); xfer += iprot->readListEnd(); } } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == apache::thrift::protocol::T_SET) { { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->set_custom_ref)>::type::element_type>::type; std::unique_ptr<element_type> _ptype97(new element_type()); auto& _rtype98 = *_ptype97; _rtype98.clear(); uint32_t _size92; bool _sizeUnknown93; apache::thrift::protocol::TType _etype96; xfer += iprot->readSetBegin(_etype96, _size92, _sizeUnknown93); if (!_sizeUnknown93) { uint32_t _i99; for (_i99 = 0; _i99 < _size92; ++_i99) { int32_t _elem100; xfer += iprot->readI32(_elem100); _rtype98.insert(_elem100); } } else { while (iprot->peekSet()) { int32_t _elem101; xfer += iprot->readI32(_elem101); _rtype98.insert(_elem101); } } this->set_custom_ref = std::move(_ptype97); xfer += iprot->readSetEnd(); } } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } void StructWithContainers::__clear() { list_ref.reset(new typename decltype(list_ref)::element_type()); set_ref.reset(new typename decltype(set_ref)::element_type()); map_ref.reset(new typename decltype(map_ref)::element_type()); list_ref_unique.reset(new typename decltype(list_ref_unique)::element_type()); set_ref_shared.reset(new typename decltype(set_ref_shared)::element_type()); map_ref_custom.reset(new typename decltype(map_ref_custom)::element_type()); list_ref_shared_const.reset(new typename decltype(list_ref_shared_const)::element_type()); set_custom_ref.reset(new typename decltype(set_custom_ref)::element_type()); __isset.__clear(); } uint32_t StructWithContainers::write(apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("StructWithContainers"); if (this->list_ref) { xfer += oprot->writeFieldBegin("list_ref", apache::thrift::protocol::T_LIST, 1); { if (this->list_ref) { const auto& _rtype102 = *this->list_ref; xfer += oprot->writeListBegin(apache::thrift::protocol::T_I32, _rtype102.size()); std::vector<int32_t> ::const_iterator _iter103; for (_iter103 = _rtype102.begin(); _iter103 != _rtype102.end(); ++_iter103) { xfer += oprot->writeI32((*_iter103)); } xfer += oprot->writeListEnd(); } else { xfer += oprot->writeListBegin(apache::thrift::protocol::T_I32, 0); xfer += oprot->writeListEnd(); } } xfer += oprot->writeFieldEnd(); } if (this->set_ref) { xfer += oprot->writeFieldBegin("set_ref", apache::thrift::protocol::T_SET, 2); { if (this->set_ref) { const auto& _rtype104 = *this->set_ref; xfer += oprot->writeSetBegin(apache::thrift::protocol::T_I32, _rtype104.size()); std::set<int32_t> ::const_iterator _iter105; for (_iter105 = _rtype104.begin(); _iter105 != _rtype104.end(); ++_iter105) { xfer += oprot->writeI32((*_iter105)); } xfer += oprot->writeSetEnd(); } else { xfer += oprot->writeSetBegin(apache::thrift::protocol::T_I32, 0); xfer += oprot->writeListEnd(); } } xfer += oprot->writeFieldEnd(); } if (this->map_ref) { xfer += oprot->writeFieldBegin("map_ref", apache::thrift::protocol::T_MAP, 3); { if (this->map_ref) { const auto& _rtype106 = *this->map_ref; xfer += oprot->writeMapBegin(apache::thrift::protocol::T_I32, apache::thrift::protocol::T_I32, _rtype106.size()); std::map<int32_t, int32_t> ::const_iterator _iter107; for (_iter107 = _rtype106.begin(); _iter107 != _rtype106.end(); ++_iter107) { xfer += oprot->writeI32(_iter107->first); xfer += oprot->writeI32(_iter107->second); } xfer += oprot->writeMapEnd(); } else { xfer += oprot->writeMapBegin(apache::thrift::protocol::T_I32, apache::thrift::protocol::T_I32, 0); xfer += oprot->writeMapEnd(); } } xfer += oprot->writeFieldEnd(); } if (this->list_ref_unique) { xfer += oprot->writeFieldBegin("list_ref_unique", apache::thrift::protocol::T_LIST, 4); { if (this->list_ref_unique) { const auto& _rtype108 = *this->list_ref_unique; xfer += oprot->writeListBegin(apache::thrift::protocol::T_I32, _rtype108.size()); std::vector<int32_t> ::const_iterator _iter109; for (_iter109 = _rtype108.begin(); _iter109 != _rtype108.end(); ++_iter109) { xfer += oprot->writeI32((*_iter109)); } xfer += oprot->writeListEnd(); } else { xfer += oprot->writeListBegin(apache::thrift::protocol::T_I32, 0); xfer += oprot->writeListEnd(); } } xfer += oprot->writeFieldEnd(); } if (this->set_ref_shared) { xfer += oprot->writeFieldBegin("set_ref_shared", apache::thrift::protocol::T_SET, 5); { if (this->set_ref_shared) { const auto& _rtype110 = *this->set_ref_shared; xfer += oprot->writeSetBegin(apache::thrift::protocol::T_I32, _rtype110.size()); std::set<int32_t> ::const_iterator _iter111; for (_iter111 = _rtype110.begin(); _iter111 != _rtype110.end(); ++_iter111) { xfer += oprot->writeI32((*_iter111)); } xfer += oprot->writeSetEnd(); } else { xfer += oprot->writeSetBegin(apache::thrift::protocol::T_I32, 0); xfer += oprot->writeListEnd(); } } xfer += oprot->writeFieldEnd(); } if (this->map_ref_custom) { xfer += oprot->writeFieldBegin("map_ref_custom", apache::thrift::protocol::T_MAP, 6); { if (this->map_ref_custom) { const auto& _rtype112 = *this->map_ref_custom; xfer += oprot->writeMapBegin(apache::thrift::protocol::T_I32, apache::thrift::protocol::T_I32, _rtype112.size()); const std::map<int32_t, int32_t>::const_iterator _iter113; for (_iter113 = _rtype112.begin(); _iter113 != _rtype112.end(); ++_iter113) { xfer += oprot->writeI32(_iter113->first); xfer += oprot->writeI32(_iter113->second); } xfer += oprot->writeMapEnd(); } else { xfer += oprot->writeMapBegin(apache::thrift::protocol::T_I32, apache::thrift::protocol::T_I32, 0); xfer += oprot->writeMapEnd(); } } xfer += oprot->writeFieldEnd(); } if (this->list_ref_shared_const) { xfer += oprot->writeFieldBegin("list_ref_shared_const", apache::thrift::protocol::T_LIST, 7); { if (this->list_ref_shared_const) { const auto& _rtype114 = *this->list_ref_shared_const; xfer += oprot->writeListBegin(apache::thrift::protocol::T_I32, _rtype114.size()); std::vector<int32_t> ::const_iterator _iter115; for (_iter115 = _rtype114.begin(); _iter115 != _rtype114.end(); ++_iter115) { xfer += oprot->writeI32((*_iter115)); } xfer += oprot->writeListEnd(); } else { xfer += oprot->writeListBegin(apache::thrift::protocol::T_I32, 0); xfer += oprot->writeListEnd(); } } xfer += oprot->writeFieldEnd(); } if (this->set_custom_ref) { xfer += oprot->writeFieldBegin("set_custom_ref", apache::thrift::protocol::T_SET, 8); { if (this->set_custom_ref) { const auto& _rtype116 = *this->set_custom_ref; xfer += oprot->writeSetBegin(apache::thrift::protocol::T_I32, _rtype116.size()); std::set<int32_t> ::const_iterator _iter117; for (_iter117 = _rtype116.begin(); _iter117 != _rtype116.end(); ++_iter117) { xfer += oprot->writeI32((*_iter117)); } xfer += oprot->writeSetEnd(); } else { xfer += oprot->writeSetBegin(apache::thrift::protocol::T_I32, 0); xfer += oprot->writeListEnd(); } } xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(StructWithContainers &a, StructWithContainers &b) { using ::std::swap; (void)a; (void)b; swap(a.list_ref, b.list_ref); swap(a.set_ref, b.set_ref); swap(a.map_ref, b.map_ref); swap(a.list_ref_unique, b.list_ref_unique); swap(a.set_ref_shared, b.set_ref_shared); swap(a.map_ref_custom, b.map_ref_custom); swap(a.list_ref_shared_const, b.list_ref_shared_const); swap(a.set_custom_ref, b.set_custom_ref); swap(a.__isset, b.__isset); } void merge(const StructWithContainers& from, StructWithContainers& to) { using apache::thrift::merge; merge(from.list_ref, to.list_ref); merge(from.set_ref, to.set_ref); merge(from.map_ref, to.map_ref); merge(from.list_ref_unique, to.list_ref_unique); merge(from.set_ref_shared, to.set_ref_shared); merge(from.map_ref_custom, to.map_ref_custom); merge(from.list_ref_shared_const, to.list_ref_shared_const); merge(from.set_custom_ref, to.set_custom_ref); } void merge(StructWithContainers&& from, StructWithContainers& to) { using apache::thrift::merge; merge(std::move(from.list_ref), to.list_ref); merge(std::move(from.set_ref), to.set_ref); merge(std::move(from.map_ref), to.map_ref); merge(std::move(from.list_ref_unique), to.list_ref_unique); merge(std::move(from.set_ref_shared), to.set_ref_shared); merge(std::move(from.map_ref_custom), to.map_ref_custom); merge(std::move(from.list_ref_shared_const), to.list_ref_shared_const); merge(std::move(from.set_custom_ref), to.set_custom_ref); } const uint64_t StructWithSharedConst::_reflection_id; void StructWithSharedConst::_reflection_register(::apache::thrift::reflection::Schema& schema) { ::module_reflection_::reflectionInitializer_17232433652683371404(schema); } bool StructWithSharedConst::operator == (const StructWithSharedConst & rhs) const { if (bool(opt_shared_const) != bool(rhs.opt_shared_const)) return false; else if (bool(opt_shared_const) && !(*opt_shared_const == *rhs.opt_shared_const)) return false; if (bool(shared_const) != bool(rhs.shared_const)) return false; else if (bool(shared_const) && !(*shared_const == *rhs.shared_const)) return false; if (bool(req_shared_const) != bool(rhs.req_shared_const)) return false; else if (bool(req_shared_const) && !(*req_shared_const == *rhs.req_shared_const)) return false; return true; } uint32_t StructWithSharedConst::read(apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; apache::thrift::protocol::TType ftype; int16_t fid; ::apache::thrift::reflection::Schema * schema = iprot->getSchema(); if (schema != nullptr) { ::module_reflection_::reflectionInitializer_17232433652683371404(*schema); iprot->setNextStructType(StructWithSharedConst::_reflection_id); } xfer += iprot->readStructBegin(fname); using apache::thrift::protocol::TProtocolException; std::exception_ptr exception; bool isset_req_shared_const = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == apache::thrift::protocol::T_STRUCT) { try { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->opt_shared_const)>::type::element_type>::type; std::unique_ptr<element_type> _ptype119(new element_type()); xfer += _ptype119->read(iprot); this->opt_shared_const = std::move(_ptype119); if (false) { } else if (this->opt_shared_const->__isset.opt_value) { } else if (this->opt_shared_const->__isset.value) { } else { this->opt_shared_const = nullptr; } } catch (const TProtocolException& e) { if (e.getType() != TProtocolException::MISSING_REQUIRED_FIELD) { throw; } exception = std::current_exception(); } } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == apache::thrift::protocol::T_STRUCT) { try { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->shared_const)>::type::element_type>::type; std::unique_ptr<element_type> _ptype120(new element_type()); xfer += _ptype120->read(iprot); this->shared_const = std::move(_ptype120); if (false) { } else if (this->shared_const->__isset.opt_value) { } else if (this->shared_const->__isset.value) { } else { this->shared_const = nullptr; } } catch (const TProtocolException& e) { if (e.getType() != TProtocolException::MISSING_REQUIRED_FIELD) { throw; } exception = std::current_exception(); } } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == apache::thrift::protocol::T_STRUCT) { try { using element_type = typename std::remove_const<typename std::remove_reference<decltype(this->req_shared_const)>::type::element_type>::type; std::unique_ptr<element_type> _ptype121(new element_type()); xfer += _ptype121->read(iprot); this->req_shared_const = std::move(_ptype121); if (false) { } else if (this->req_shared_const->__isset.opt_value) { } else if (this->req_shared_const->__isset.value) { } else { this->req_shared_const = nullptr; } } catch (const TProtocolException& e) { if (e.getType() != TProtocolException::MISSING_REQUIRED_FIELD) { throw; } exception = std::current_exception(); } isset_req_shared_const = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (exception != std::exception_ptr()) { std::rethrow_exception(exception); } if (!isset_req_shared_const) throw TProtocolException(TProtocolException::MISSING_REQUIRED_FIELD, "Required field 'req_shared_const' was not found in serialized data! Struct: StructWithSharedConst"); return xfer; } void StructWithSharedConst::__clear() { opt_shared_const.reset(); shared_const.reset(); req_shared_const.reset(); __isset.__clear(); } uint32_t StructWithSharedConst::write(apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("StructWithSharedConst"); if (this->opt_shared_const) { xfer += oprot->writeFieldBegin("opt_shared_const", apache::thrift::protocol::T_STRUCT, 1); if (this->opt_shared_const) {xfer += this->opt_shared_const->write(oprot); } else {oprot->writeStructBegin("MyField"); oprot->writeStructEnd(); oprot->writeFieldStop();} xfer += oprot->writeFieldEnd(); } if (this->shared_const) { xfer += oprot->writeFieldBegin("shared_const", apache::thrift::protocol::T_STRUCT, 2); if (this->shared_const) {xfer += this->shared_const->write(oprot); } else {oprot->writeStructBegin("MyField"); oprot->writeStructEnd(); oprot->writeFieldStop();} xfer += oprot->writeFieldEnd(); } if (this->req_shared_const) { xfer += oprot->writeFieldBegin("req_shared_const", apache::thrift::protocol::T_STRUCT, 3); if (this->req_shared_const) {xfer += this->req_shared_const->write(oprot); } else {oprot->writeStructBegin("MyField"); oprot->writeStructEnd(); oprot->writeFieldStop();} xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(StructWithSharedConst &a, StructWithSharedConst &b) { using ::std::swap; (void)a; (void)b; swap(a.opt_shared_const, b.opt_shared_const); swap(a.shared_const, b.shared_const); swap(a.req_shared_const, b.req_shared_const); swap(a.__isset, b.__isset); } void merge(const StructWithSharedConst& from, StructWithSharedConst& to) { using apache::thrift::merge; merge(from.opt_shared_const, to.opt_shared_const); merge(from.shared_const, to.shared_const); merge(from.req_shared_const, to.req_shared_const); } void merge(StructWithSharedConst&& from, StructWithSharedConst& to) { using apache::thrift::merge; merge(std::move(from.opt_shared_const), to.opt_shared_const); merge(std::move(from.shared_const), to.shared_const); merge(std::move(from.req_shared_const), to.req_shared_const); }
e71be969331dbc69c06a3235f02c84f68a299d54
5d3ee8d02dc363bce1602bda3dce9b5092956ce7
/Interface/UserAskWhetherHosterWindow/UserAskWhetherHosterWindow.hpp
bf3535f6e3ea1274eff436586ae9740889b756ea
[]
no_license
EMCJava/EMCMeeting
b8fbb4aa51404fc4a6f387c54d92b77d55a75b5a
8e8b41bbb155f999f6b89707c4ba11b41b69ce6b
refs/heads/master
2023-06-10T12:21:19.641472
2020-09-03T14:31:29
2020-09-03T14:31:29
270,252,972
0
0
null
null
null
null
UTF-8
C++
false
false
871
hpp
UserAskWhetherHosterWindow.hpp
// // Created by loyusum on 9/6/2020. // #ifndef EMCMEETING_USERASKWHETHERHOSTERWINDOW_HPP #define EMCMEETING_USERASKWHETHERHOSTERWINDOW_HPP #include <string> #include <vector> #include <memory> #include "../../ToolBox/ToolBox.hpp" #include "../Window/WindowBase.hpp" #include "../UI/Button/Button.hpp" class UserAskWhetherHosterWindow : public WindowBase { public: enum class UserType { Client, Hoster, None }; private: static const std::string sm_font_path; std::vector<Button> m_buttons; UserType m_userType = UserType::None; public: UserAskWhetherHosterWindow(int screen_size_x, int screen_size_y); // return false if window has closed or user had completed to fill in their data bool Update() override; void Close() override; UserType GetType(); }; #endif //EMCMEETING_USERASKWHETHERHOSTERWINDOW_HPP
a80b9ef4afad2a8d273aff6cf902472ff2d93743
10ecbc5cdc572eab75b33f026ff1602c8adbe24b
/rshwub_robot.ino
9d5ebac94874ff9d3527793f5a4e463abf7e4608
[]
no_license
tlillis/rshwub_robot
c8e66c521907a0305f4aea11254edfac5e8da4a4
3888831102d70de4acc26ca60eea49783612f688
refs/heads/main
2023-06-22T16:48:30.956626
2021-07-21T06:03:16
2021-07-21T06:03:16
387,987,352
0
0
null
null
null
null
UTF-8
C++
false
false
3,288
ino
rshwub_robot.ino
#include <AccelStepper.h> #define INTERFACE_TYPE 1 #define NUM_MOTORS 2 #define NUM_ROUTINES 3 // Robot head #define MOTOR1 0 #define DIR_PIN_MOTOR1 2 #define STEP_PIN_MOTOR1 3 // Robot body #define MOTOR2 1 #define DIR_PIN_MOTOR2 4 #define STEP_PIN_MOTOR2 5 // Define motors AccelStepper stepper[NUM_MOTORS]; // Array of different routine functions void (*routines[NUM_ROUTINES])(); /** / ----- Helper Functions ----- **/ // Moves specifed motor to angle with given speed void move_motor_to_angle(int16_t angle, int16_t spd, uint8_t motor_num) { while(stepper[motor_num].currentPosition() != angle) { stepper[motor_num].setSpeed(spd); stepper[motor_num].runSpeed(); } } // Moves motor1 to angle1 and motor2 to angle 2 at the same time // This function is gross but is required for moving both motors at once void move_motors_to_angle(int16_t angle1, int16_t spd1, int16_t angle2, int16_t spd2) { bool done = false; while(!done) { done = true; if(stepper[MOTOR1].currentPosition() != angle1){ stepper[MOTOR1].setSpeed(spd1); stepper[MOTOR1].runSpeed(); done = false; } if(stepper[MOTOR2].currentPosition() != angle2){ stepper[MOTOR2].setSpeed(spd2); stepper[MOTOR2].runSpeed(); done = false; } } } // Reset motor position to 0 void reset_motor(uint8_t motor_num) { stepper[MOTOR1].setCurrentPosition(0); } // Reset all motors positions to 0 void reset_motors() { for(uint8_t i = 0; i < NUM_MOTORS; i++) { stepper[i].setCurrentPosition(0); } } /** / ----- Routines ----- / Routines for the robot to do. When adding define function here. Initialize in setup(). Increment NUM_ROUTINES **/ void move_head_around() { reset_motors(); int spd = random(-700, -300); move_motor_to_angle(-3000, spd, MOTOR1); delay(200); reset_motors(); spd *= -1; move_motor_to_angle(3000, spd, MOTOR1); delay(200); reset_motors(); } void one_at_a_time() { int angle = random(-600, -100); int spd = random(-700, -300); reset_motors(); move_motor_to_angle(angle, spd, MOTOR1); move_motor_to_angle(angle, spd, MOTOR2); delay(100); reset_motors(); angle *= -1; spd *= -1; move_motor_to_angle(angle, spd, MOTOR1); move_motor_to_angle(angle, spd, MOTOR2); delay(100); reset_motors(); } void both_baby() { int angle = random(-600, -100); int spd = random(-700, -300); reset_motors(); move_motors_to_angle(angle, spd, angle, spd); delay(100); reset_motors(); angle *= -1; spd *= -1; move_motors_to_angle(angle, spd, angle, spd); delay(100); reset_motors(); } /** / ----- Core setup and loop ----- **/ void setup() { // Initialize routines routines[0] = move_head_around; routines[1] = one_at_a_time; routines[2] = both_baby; // Set up motors stepper[MOTOR1] = AccelStepper(INTERFACE_TYPE, STEP_PIN_MOTOR1, DIR_PIN_MOTOR1); stepper[MOTOR2] = AccelStepper(INTERFACE_TYPE, STEP_PIN_MOTOR2, DIR_PIN_MOTOR2); // Set the maximum speed in steps per second: for(uint8_t i = 0; i < NUM_MOTORS; i++) { stepper[i].setMaxSpeed(1000); } } void loop() { // Select routine int routine_num = random(0, NUM_ROUTINES); // Call routine routines[routine_num](); // Time between routines delay(2000); }
0534aa409088e2da685254ddf3ac5ec9968e9ada
955129b4b7bcb4264be57cedc0c8898aeccae1ca
/python/mof/cpp/req_get_petcamp_data.h
850d61f70ddd65f538bc4b53bf825e76991f6882
[]
no_license
PenpenLi/Demos
cf270b92c7cbd1e5db204f5915a4365a08d65c44
ec90ebea62861850c087f32944786657bd4bf3c2
refs/heads/master
2022-03-27T07:33:10.945741
2019-12-12T08:19:15
2019-12-12T08:19:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
284
h
req_get_petcamp_data.h
#ifndef MOF_REQ_GET_PETCAMP_DATA_H #define MOF_REQ_GET_PETCAMP_DATA_H class req_get_petcamp_data{ public: void req_get_petcamp_data(void); void decode(ByteArray &); void PacketName(void); void ~req_get_petcamp_data(); void build(ByteArray &); void encode(ByteArray &); } #endif
9e5cc2d8f23d429474470bd3d2f1c1b9f7abccd0
0569a04ed085bbdec4228270e3cfed79684f6494
/Classes/ProgressLayer.cpp
9c1f90329184a63e008062cc304974862f4a2b43
[]
no_license
ZhouC125/cocos2d
6d9e31fe82c7fbcd1be8ab1fae5587ad307f8856
55c769fca989487ff5f46016e200c0080113b850
refs/heads/master
2020-04-27T23:56:18.773969
2019-03-10T09:40:48
2019-03-10T09:40:48
174,797,396
0
0
null
null
null
null
GB18030
C++
false
false
2,505
cpp
ProgressLayer.cpp
#include "constart.h" #include "ProgressLayer.h" #include "DengluScene.h" #include"ui/CocosGUI.h" #include "GameScene.h" #include "GameHall.h" #pragma execution_character_set("utf-8") USING_NS_CC; ProgressLayer * ProgressLayer::scene() { return ProgressLayer::create(); } bool ProgressLayer::init() { if (!Scene::init()) { return false; } schedule(schedule_selector(ProgressLayer::updateReadyTimer), 1, kRepeatForever, 0); // 加载素材 SpriteFrameCache::getInstance()->addSpriteFramesWithFile("lor.plist", "lor.png"); Sprite *tenxun = Sprite::create("fenkuang_bg1.png"); float scaleW = VISIBLE_SIZE.width / tenxun->getBoundingBox().size.width; float scaleH = VISIBLE_SIZE.height / tenxun->getBoundingBox().size.width; tenxun->setScale(scaleW > scaleH ? scaleW : scaleH); tenxun->setPosition(Vec2(VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2)); addChild(tenxun); Sprite *tas = Sprite::create("loadifet.png"); tas->setPosition(Vec2(VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2 - 180)); tas->setScale(0.8); addChild(tas); game = CardGame::getInstance(); return true; } void ProgressLayer::updateReadyTimer(float data) { time += 1; if (time==1) { //获取人物的全部精灵帧 Vector<SpriteFrame *> vectors = getSpriteFrame("s_%d.png", 17); //获取人物精灵帧里的第一帧,做初始化显示 Sprite *person = Sprite::createWithSpriteFrame(vectors.front()); person->setPosition(Vec2(VISIBLE_SIZE.width/2, VISIBLE_SIZE.height/2)); person->setScale(0.8); addChild(person); //创建动画(精灵帧动画) Animation* animation = Animation::createWithSpriteFrames(vectors, 1.f / 8); person->runAction(RepeatForever::create(Animate::create(animation))); } else if (time >4) { this->unschedule(schedule_selector(ProgressLayer::updateReadyTimer)); doi(); } } void ProgressLayer::doi() { if (!game->is_denglu) { auto transition = TransitionMoveInR::create(0.5f, GameHall::create()); Director::getInstance()->replaceScene(transition);//切换场景 } else if (game->is_denglu) { Director::getInstance()->replaceScene(GameScene::scene());//切换场景 } } Vector<SpriteFrame *> ProgressLayer::getSpriteFrame(const char *format, int count) { Vector<SpriteFrame *> vector; //循环每一个精灵帧,添加进Vector中 for (int i = 1; i < count; i++) { SpriteFrame *sf = SpriteFrameCache::getInstance() ->getSpriteFrameByName(StringUtils::format(format, i)); vector.pushBack(sf); } return vector; }
a136d0e8f3cb7461ececc30dd49ba37663fdf7c3
e2c3ad5709359f13f9d93378fadbc0f0116d595f
/GTT/EnemyAim.h
57e514e4b878e63c3094c5a3ea02c84850f614ac
[]
no_license
dagil02/TaxiRevengeDLC
b2bb7ea69bf146ec5f4251ed80ab02acd43e2e9a
b785dd652c435b7495e9aaed2b4a3d1bc4900af7
refs/heads/master
2020-06-02T01:01:49.305137
2019-07-01T17:06:11
2019-07-01T17:06:11
190,985,412
0
0
null
null
null
null
UTF-8
C++
false
false
181
h
EnemyAim.h
#pragma once #include "AimComponent.h" class EnemyAim : public AimComponent { public: EnemyAim(); virtual void update(GameObject* o, Uint32 deltaTime); virtual ~EnemyAim(); };
ef7f0cb2c9d70a548453353e8a98615e07562ac3
011d7ba6ba4730a1c95d1af25a00d1322902f3f1
/InboundMessageDispatcher.cpp
13a1a7eefd9326534a5d39f0053bc84d8d670b22
[]
no_license
gjn/i2pcpp
6c76f4a2dbb377ab8c84dde9d8fd4dd81a65c0e8
22c6845146bbb83cea83a598fdebe9c778667b0f
refs/heads/master
2021-01-16T20:37:34.747884
2013-09-22T13:28:16
2013-09-22T13:28:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,763
cpp
InboundMessageDispatcher.cpp
#include "InboundMessageDispatcher.h" #include <iomanip> #include <boost/bind.hpp> #include <botan/auto_rng.h> #include <botan/zlib.h> #include "i2np/DeliveryStatus.h" #include "i2np/DatabaseStore.h" #include "RouterContext.h" namespace i2pcpp { InboundMessageDispatcher::InboundMessageDispatcher(boost::asio::io_service &ios, RouterContext &ctx) : m_ios(ios), m_ctx(ctx), m_deliveryStatusHandler(ctx), m_dbStoreHandler(ctx), m_dbSearchReplyHandler(ctx), m_variableTunnelBuildHandler(ctx), m_tunnelDataHandler(ctx), m_tunnelGatewayHandler(ctx), m_log(boost::log::keywords::channel = "IMD") {} void InboundMessageDispatcher::messageReceived(RouterHash const from, ByteArray data) { I2P_LOG_SCOPED_RH(m_log, from); std::stringstream s; for(auto c: data) s << std::setw(2) << std::setfill('0') << std::hex << (int)c; I2P_LOG(m_log, debug) << "received data: " << s.str(); I2NP::MessagePtr m = I2NP::Message::fromBytes(data); if(m) { switch(m->getType()) { case I2NP::Message::Type::DELIVERY_STATUS: m_ios.post(boost::bind(&Handlers::Message::handleMessage, m_deliveryStatusHandler, from, m)); break; case I2NP::Message::Type::DB_STORE: m_ios.post(boost::bind(&Handlers::Message::handleMessage, m_dbStoreHandler, from, m)); break; case I2NP::Message::Type::DB_SEARCH_REPLY: m_ios.post(boost::bind(&Handlers::Message::handleMessage, m_dbSearchReplyHandler, from, m)); break; case I2NP::Message::Type::VARIABLE_TUNNEL_BUILD: m_ios.post(boost::bind(&Handlers::Message::handleMessage, m_variableTunnelBuildHandler, from, m)); break; case I2NP::Message::Type::TUNNEL_DATA: m_ios.post(boost::bind(&Handlers::Message::handleMessage, m_tunnelDataHandler, from, m)); break; case I2NP::Message::Type::TUNNEL_GATEWAY: m_ios.post(boost::bind(&Handlers::Message::handleMessage, m_tunnelGatewayHandler, from, m)); break; default: I2P_LOG(m_log, error) << "dropping unhandled message of type " << m->getType(); break; } } } void InboundMessageDispatcher::connectionEstablished(RouterHash const rh, bool inbound) { I2P_LOG_SCOPED_RH(m_log, rh); I2P_LOG(m_log, info) << "session established"; if(inbound) { Botan::AutoSeeded_RNG rng; uint32_t msgId; rng.randomize((unsigned char *)&msgId, sizeof(msgId)); I2NP::MessagePtr m(new I2NP::DeliveryStatus(msgId, Date(2))); m_ctx.getOutMsgDisp().sendMessage(rh, m); // TODO Get this out of here Mapping am; am.setValue("caps", "BC"); am.setValue("host", m_ctx.getDatabase().getConfigValue("ssu_external_ip")); am.setValue("key", m_ctx.getIdentity().getHashEncoded()); am.setValue("port", m_ctx.getDatabase().getConfigValue("ssu_external_port")); RouterAddress a(5, Date(0), "SSU", am); Mapping rm; rm.setValue("coreVersion", "0.9.7"); rm.setValue("netId", "2"); rm.setValue("router.version", "0.9.7"); rm.setValue("stat_uptime", "90m"); rm.setValue("caps", "OR"); RouterInfo myInfo(m_ctx.getIdentity(), Date(), rm); myInfo.addAddress(a); myInfo.sign(m_ctx.getSigningKey()); Botan::Pipe gzPipe(new Botan::Zlib_Compression); gzPipe.start_msg(); gzPipe.write(myInfo.serialize()); gzPipe.end_msg(); unsigned int size = gzPipe.remaining(); ByteArray gzInfoBytes(size); gzPipe.read(gzInfoBytes.data(), size); auto mydsm = std::make_shared<I2NP::DatabaseStore>(myInfo.getIdentity().getHash(), I2NP::DatabaseStore::DataType::ROUTER_INFO, 0, gzInfoBytes); m_ctx.getOutMsgDisp().sendMessage(rh, mydsm); } m_ctx.getSignals().invokePeerConnected(rh); } void InboundMessageDispatcher::connectionFailure(RouterHash const rh) { m_ctx.getSignals().invokeConnectionFailure(rh); } }
d9fd398ff658edab585b6a744ce0c055107bf6fb
e90671c6b1cb69eaf57bd0ab4bbd1bd92ba9aea9
/android/vendored/sdk49/@shopify/react-native-skia/cpp/rnskia/dom/nodes/JsiLineNode.h
2fd74466574535296518e6ef3869412b6eb73bd8
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
expo/expo
72fc802e3b6806789225bdd856031a8d150dd6f5
40f087fc0c0ab22270cfef2673bced44af170c34
refs/heads/main
2023-08-17T01:38:28.442098
2023-08-16T21:43:11
2023-08-16T21:43:11
65,750,241
23,742
5,421
MIT
2023-09-14T21:37:37
2016-08-15T17:14:25
TypeScript
UTF-8
C++
false
false
983
h
JsiLineNode.h
#pragma once #include "JsiDomDrawingNode.h" #include "PointProp.h" #include <memory> namespace RNSkia { class JsiLineNode : public JsiDomDrawingNode, public JsiDomNodeCtor<JsiLineNode> { public: explicit JsiLineNode(std::shared_ptr<RNSkPlatformContext> context) : JsiDomDrawingNode(context, "skLine") {} protected: void draw(DrawingContext *context) override { context->getCanvas()->drawLine( _p1Prop->getDerivedValue()->x(), _p1Prop->getDerivedValue()->y(), _p2Prop->getDerivedValue()->x(), _p2Prop->getDerivedValue()->y(), *context->getPaint()); } void defineProperties(NodePropsContainer *container) override { JsiDomDrawingNode::defineProperties(container); _p1Prop = container->defineProperty<PointProp>("p1"); _p2Prop = container->defineProperty<PointProp>("p2"); _p1Prop->require(); _p2Prop->require(); } private: PointProp *_p1Prop; PointProp *_p2Prop; }; } // namespace RNSkia
248ede9fa746cc06ba31795f9564c73a33fc0559
5e9a30fc5faf29d1244fd66ed793cce30b5672e7
/copy_ctor_for_array_class.cpp
a83d4572fb2e3c01828d09afc5821fbe2d6d3171
[]
no_license
surajombale/c-
8157f6ffd7b28d5615bdcc3f796dd820c7dad7cb
54d883f273e8e74e2fe7399b5fc1fdd259645835
refs/heads/master
2020-04-08T20:19:42.247636
2018-11-29T16:20:48
2018-11-29T16:20:48
159,694,444
0
0
null
null
null
null
UTF-8
C++
false
false
1,559
cpp
copy_ctor_for_array_class.cpp
#include<iostream> using namespace std; namespace Narray { class Array { private: int size; int *arr; public: Array(int size=5) { this->size=size; this->arr=new int(this->size); for(int i=0;i<this->size;i++) { this->arr[i]=0; } cout<<"inside ctor of array class"<<endl; } Array(const Array& other)//using copy ctor { this->size=other.size; this->arr=new int(this->size); for(int i=0;i<this->size;i++) { this->arr[i]=other.arr[i]; } cout<<"inside copy ctor of array class"<<endl; } void operator=(const Array& other)//using = operator { this->~Array(); this->size=other.size; this->arr= new int[this->size]; for(int i=0;i<this->size;i++) { this->arr[i]=other.arr[i]; } cout<<"inside operator overlosding function"<<endl; } void acceptin() { for(int i=0;i<this->size;i++) { cout<<"this->["<<i<<"]"<<endl; cin>>arr[i]; } } void printout() { for(int i=0;i<this->size;i++) { cout<<"this->arr["<<i<<"]::"<<this->arr[i]<<endl; } } ~Array() { if(this->arr!=NULL) delete[] this->arr; this->arr=NULL; } }; } using namespace Narray; int main() { Array a1; cout<<"enter value for a1"<<endl; a1.acceptin(); cout<<"a1::"<<endl; a1.printout(); Array a2(a1); cout<<"a2::"<<endl; a2.printout(); return 0; }
7ab27be2ffbebe42884034513d75a1daef286862
70cda06a2aa4f826e8eb755c2acbd6107ff629eb
/basic exercise/uppgift4.1/uppgift4.1/uppgift4.1.cpp
01663a3172b979b6ff3606b31e1d11def93f9eaa
[]
no_license
UlrikJonasLove/Cpp-Playground
bd05e2f003f78dbc0b42a026099eefc8e5fb8ace
79b31facdee2f970922572868533355944f47c20
refs/heads/master
2023-01-13T12:51:02.968440
2020-11-15T09:01:03
2020-11-15T09:01:03
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
870
cpp
uppgift4.1.cpp
#include <iostream> #include <climits> using namespace std; int main(int argc, const char* argv[]) { cout << "Skriv ett nummer, enter, ett nummer till OSV. Avsluta med att skriva in 0" << endl; cout << "" << endl; int max = INT_MIN; int nMax = INT_MIN; int min = INT_MAX; int sum = 0; int antal = 0; int inp = 0; cout << "Ange ett nummer" << endl; while (true) { cin >> inp; if (inp != 0) { break; } if (inp > max) { nMax = max; max = inp; } if (inp > nMax && inp < max) { nMax = inp; } if (inp < min) { min = inp; } if (sum += inp) { antal++; } } cout << "Summa: " << sum << endl; cout << "Medelvärdet: " << (double)sum / (double)antal << endl; cout << "Största talet: " << max << endl; cout << "Näst största tal: " << nMax << endl; cout << "Minsta talet: " << min << endl; ("pause"); return 0; }
0d9866aee1b546563625bb29c33664527a403d4f
41fda566921957dfeb6e244e67c9802980ec051f
/lobby.cpp
e32994bb4fb243eaae8b2f81189370e1fbe4f864
[]
no_license
blockspacer/Black-Comrade
7f208bfdb978909bf95b51d5256d435b6d541e56
c110b753ab5481f5ea35026427affbcfd0c6fe21
refs/heads/master
2021-04-01T03:01:36.434513
2010-05-12T09:24:20
2010-05-12T09:24:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,112
cpp
lobby.cpp
#include "lobby.h" #include "Kbhit.h" using namespace std; using namespace RakNet; Lobby::Lobby(RakPeerInterface *rp, DiscoveryAgent *da, NetworkRole nr, std::string nick) : pilotTaken(false) , navTaken(false) , engTaken(false) , roleOptionsChanged(true) , nick(nick) , rakPeer(rp) , networkRole(nr) , discoveryAgent(da) , gameRole(NO_GAME_ROLE) , chosenGameRole(NO_GAME_ROLE) {} Lobby::Lobby(RakPeerInterface *rp, DiscoveryAgent *da, NetworkRole nr, std::string nick, std::string gameName) : pilotTaken(false) , navTaken(false) , engTaken(false) , roleOptionsChanged(true) , nick(nick) , rakPeer(rp) , networkRole(nr) , discoveryAgent(da) , gameRole(NO_GAME_ROLE) , chosenGameRole(NO_GAME_ROLE) , gameName(gameName) {} void Lobby::enter() { std::cout << "Welcome to the lobby" << std::endl; if (networkRole == SERVER) offerGameRoleChoices(); } GameRole Lobby::getChosenGameRole() { return gameRole; } bool Lobby::hasChosenRole() { return (gameRole != NO_GAME_ROLE); } string Lobby::getChosenNick() { return nick; } void Lobby::offerGameRoleChoices() { roleOptionsChanged = true; if (gameRole != NO_GAME_ROLE) return; printf("Available roles:\n"); if (!pilotTaken) printf("(P)ilot\n"); if (!navTaken) printf("(N)avigator\n"); if (!engTaken) printf("(E)ngineer\n"); } bool Lobby::connect(string serverAddress, int port) { rakPeer->Connect(serverAddress.c_str(),port,0,0,0); bool connected = false; while(connected != true) { for (packet = rakPeer->Receive(); packet; rakPeer->DeallocatePacket(packet), packet = rakPeer->Receive()) { switch (packet->data[0]) { case ID_CONNECTION_ATTEMPT_FAILED: break; case ID_CONNECTION_REQUEST_ACCEPTED: connected = true; break; } } } return connected; } void Lobby::chooseGameRole(GameRole role) { chosenGameRole = role; } bool Lobby::wait() { roleOptionsChanged = false; if (networkRole == CLIENT) { unsigned char packetID; for (packet = rakPeer->Receive(); packet; rakPeer->DeallocatePacket(packet), packet = rakPeer->Receive()) { RakNet::BitStream dataStream((unsigned char*)packet->data, packet->length, false); dataStream.Read(packetID); switch (packetID) { case START_GAME: printf("We're good to go!\n"); return true; break; case GAME_ROLE_CHOICES: dataStream.Read(pilotTaken); dataStream.Read(navTaken); dataStream.Read(engTaken); offerGameRoleChoices(); break; } } } else if (networkRole == SERVER) { if (rakPeer->NumberOfConnections() < 2) { discoveryAgent->beServer(gameName,pilotTaken,navTaken,engTaken); } else { discoveryAgent->beServer("",pilotTaken,navTaken,engTaken); } process(); if (pilotTaken && navTaken && engTaken) return true; } else if (networkRole == DEVELOPMENTSERVER) { gameRole = PILOT; return true; } checkForRoleChoice(); return false; } void Lobby::checkForRoleChoice() { if (chosenGameRole == NO_GAME_ROLE) return; if (chosenGameRole == PILOT && gameRole == NO_GAME_ROLE && pilotTaken == false) { gameRole = PILOT; pilotTaken = true; printf("You chose to be the Pilot.\n"); roleOptionsChanged = true; } else if (chosenGameRole == NAVIGATOR && gameRole == NO_GAME_ROLE && navTaken == false) { gameRole = NAVIGATOR; navTaken = true; printf("You chose to be the Navigator.\n"); roleOptionsChanged = true; } else if (chosenGameRole == ENGINEER && gameRole == NO_GAME_ROLE && engTaken == false) { gameRole = ENGINEER; engTaken = true; printf("You chose to be the Engineer.\n"); roleOptionsChanged = true; } if (networkRole == CLIENT) { sendGameRoleChoice(gameRole); } else if (networkRole == SERVER) sendGameRoleChoices(); chosenGameRole = NO_GAME_ROLE; } void Lobby::process() { unsigned char packetID; for (packet = rakPeer->Receive(); packet; rakPeer->DeallocatePacket(packet), packet = rakPeer->Receive()) { RakNet::BitStream dataStream((unsigned char*)packet->data, packet->length, false); dataStream.Read(packetID); switch (packetID) { case ID_CONNECTION_ATTEMPT_FAILED: exit(1); break; case ID_NEW_INCOMING_CONNECTION: printf("A new player has connected.\n"); sendGameRoleChoices(packet->systemAddress); break; case GAME_ROLE_CHOICE: bool someoneChosePilot; bool someoneChoseNav; bool someoneChoseEng; dataStream.Read(someoneChosePilot); dataStream.Read(someoneChoseNav); dataStream.Read(someoneChoseEng); pilotTaken = pilotTaken || someoneChosePilot; navTaken = navTaken || someoneChoseNav; engTaken = engTaken || someoneChoseEng; sendGameRoleChoices(); offerGameRoleChoices(); break; } } } void Lobby::sendGameRoleChoices() { RakNet::BitStream dataStream; dataStream.Write(GAME_ROLE_CHOICES); dataStream.Write(pilotTaken); dataStream.Write(navTaken); dataStream.Write(engTaken); rakPeer->Send(&dataStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true); } void Lobby::sendGameRoleChoices(SystemAddress recipient) { RakNet::BitStream dataStream; dataStream.Write(GAME_ROLE_CHOICES); dataStream.Write(pilotTaken); dataStream.Write(navTaken); dataStream.Write(engTaken); rakPeer->Send(&dataStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, recipient, false); } void Lobby::sendGameRoleChoice(GameRole chosenGameRole) { RakNet::BitStream dataStream; dataStream.Write(GAME_ROLE_CHOICE); if (chosenGameRole == PILOT) dataStream.Write(true); else dataStream.Write(false); if (chosenGameRole == NAVIGATOR) dataStream.Write(true); else dataStream.Write(false); if (chosenGameRole == ENGINEER) dataStream.Write(true); else dataStream.Write(false); rakPeer->Send(&dataStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, rakPeer->GetSystemAddressFromIndex(0), false); } void Lobby::sendGameInfo(SystemAddress recipient) { RakNet::BitStream dataStream; dataStream.Write(GAME_INFO); dataStream.Write(pilotTaken); dataStream.Write(navTaken); dataStream.Write(engTaken); rakPeer->Send(&dataStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, recipient, false); }
89db9c7c125f6273671abf5ef96c7a0cc13ca89d
ec513f6b39e45f53dde25fa4c42348eb63ff957c
/smf2js/include/smf-2.11/ResponseStampedLogEntry.h
84ba1eba30fe0d9d90dd60cd4b36e2dc7e2aa0f0
[]
no_license
johnwclemens/test-refator
0b90e4a1c51419f91b00d96869910b4bbef1e766
9fcc2cafe198290f44df4660dbdd55007ef786b0
refs/heads/master
2021-08-14T07:13:42.467804
2017-11-14T22:43:01
2017-11-14T22:43:01
110,752,941
0
0
null
null
null
null
UTF-8
C++
false
false
2,674
h
ResponseStampedLogEntry.h
#ifndef RESPONSESTAMPEDLOGENTRY_H #define RESPONSESTAMPEDLOGENTRY_H #include "StampedLogEntry.h" namespace smf{ //! The ResponseLogEntry class is not thread safe. class ResponseStampedLogEntry { public: ResponseStampedLogEntry(const StampedLogEntry &logEntry); unsigned int SeqNo() const; //! \return Return the date and time in GMT (to the nearest second) that //! the message was sent from the client and received at the server. //! \remark Include: LogServiceResponseHandler.h //! \note The ResponseLogEntry class is not thread safe. //! \post Use DateTimeEntry::DateAsText to retrieve a human readable date. //! See DateTimeEntry.h for other methods. const DateTimeEntry &ServerDateTime() const; //! \return Return the date and time in GMT (to the nearest second) that //! the message was sent from the client and received at the server. //! \remark Include: LogServiceResponseHandler.h //! \note The ResponseLogEntry class is not thread safe. //! \post Use DateTimeEntry::DateAsText to retrieve a human readable date. //! See DateTimeEntry.h for other methods. const DateTimeEntry &ClientDateTime() const; std::string AppName() const; //! \return The process ID of the application/thread that created this log message. //! \remark Include: LogServiceResponseHandler.h unsigned int ProcessId() const; //! \return The thread ID of the application/thread that created this log message. //! \remark Include: LogServiceResponseHandler.h //! \note The ResponseLogEntry class is not thread safe. unsigned int ThreadId() const; //! \brief This returns the severity of the message. //! See LogEntry.h in the SMF-SDK include directory for the definitions. //! \return Return the binary representation //! \remark Include: LogServiceResponseHandler.h //! \note The ResponseLogEntry class is not thread safe. LogEntry::Severity SeverityAsCode() const; //! \brief This returns the severity of the message. //! See LogEntry.h in the SMF-SDK include directory for the definitions. //! \return Returns a human readable representation. //! \remark Include: LogServiceResponseHandler.h //! \note The ResponseLogEntry class is not thread safe. std::string SeverityAsText() const; unsigned int MessageId() const; //! \brief This function returns the log message and any parameters. //! \note The ResponseLogEntry class is not thread safe. LogEntry::Messages Message() const; operator const StampedLogEntry() const; operator const UnstampedLogEntry() const; operator const LogEntry() const; private: const StampedLogEntry &logEntry; }; } #endif
ab81989fd210dd0e474f67a85ce712b95efdb7b8
6126d833bd4522fc2ec6863af045826a72706a28
/maximum-subarray.cpp
c6c090bd3510a27c22e747a13165b76316a6dc02
[]
no_license
naivechen/Lintcode
c21e9cbd542abb9a070fd56173d87a0ca17b04a4
34cf4064a158086f56e5bfab97f763750b17594e
refs/heads/master
2020-07-02T20:47:40.377617
2015-03-06T11:57:39
2015-03-06T11:57:39
30,635,367
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
maximum-subarray.cpp
// http://lintcode.com/zh-cn/problem/maximum-subarray/ class Solution { public: /** * @param nums: A list of integers * @return: A integer indicate the sum of max subarray */ int maxSubArray(vector<int> nums) { // write your code here int len=nums.size(); if(len==0) return 0; int ans=nums[0],tmp=max(0,nums[0]); for(int i=1;i<len;i++) { tmp=max(nums[i]+tmp,nums[i]); ans=max(ans,tmp); } return ans; } };
63fff407cb82a69efe614a12036ccf1a2b6041f6
38ef8b587a72b69593cc71de89e8a53997994c70
/MonsterGame/SourceFile/MsgSocketServer.cpp
ed3ca54d731d088217a4621c91ab48b2b26f036f
[]
no_license
Resurgam-Akane/MonsterGame
c2bd449176de272f9ffb57d08fb4cf82741baaa4
83e3c23a555c921404cec49129e168a4b44b7627
refs/heads/master
2021-01-12T09:07:13.050620
2016-12-18T06:52:43
2016-12-18T06:52:43
76,766,397
0
0
null
null
null
null
GB18030
C++
false
false
2,604
cpp
MsgSocketServer.cpp
#include "MsgSocket.h" #include "Driver.h" #include <iostream> #include <exception> #include <thread> MsgSocket::MsgSocketInit::MsgSocketInit() { WSADATA Ws; if (WSAStartup(MAKEWORD(2, 2), &Ws) != 0) { std::cout << "Init Windows Socket Failed::" << GetLastError() << std::endl; throw std::runtime_error(""); } } MsgSocket::MsgSocketInit::~MsgSocketInit() { WSACleanup(); } MsgSocket::Server::Server() { _ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (_ServerSocket == INVALID_SOCKET) { std::cout << "Create Socket Failed::" << GetLastError() << std::endl; throw std::runtime_error(""); } _LocalAddr.sin_family = AF_INET; inet_pton(AF_INET, IP_ADDRESS, (void *)&(_LocalAddr.sin_addr.s_addr)); _LocalAddr.sin_port = htons(PORT); memset(_LocalAddr.sin_zero, 0x00, 8); //Bind Socket _Ret = bind(_ServerSocket, (struct sockaddr*)&_LocalAddr, sizeof(_LocalAddr)); if (_Ret != 0) { std::cout << "Bind Socket Failed::" << GetLastError() << std::endl; throw std::runtime_error(""); } //listen _Ret = listen(_ServerSocket, 10); if (_Ret != 0) { std::cout << "listen Socket Failed::" << GetLastError() << std::endl; throw std::runtime_error(""); } std::cout << "服务器端启动" << std::endl; } MsgSocket::Server::~Server() { closesocket(_ServerSocket); } void MsgSocket::Server::ServerWork(std::string& content) { while (true) { _AddrLen = sizeof(_ClientAddr); auto _ClientSocket = accept(_ServerSocket, (struct sockaddr*)&_ClientAddr, &_AddrLen); if (_ClientSocket == INVALID_SOCKET) { std::cout << "Accept Failed::" << GetLastError() << std::endl; throw std::runtime_error(""); } std::thread([=]() { int _Ret = 0; char RecvBuffer[MAX_MSGCONTENT_LEN]; char SendBuffer[MAX_MSGCONTENT_LEN]; std::string c; while (true) { //todo: memset(RecvBuffer, 0x00, sizeof(RecvBuffer)); _Ret = recv(_ClientSocket, RecvBuffer, MAX_MSGCONTENT_LEN, 0); if (_Ret == 0 || _Ret == SOCKET_ERROR) { Driver::DealOnlineUser(_ClientSocket); std::cout << "客户端退出" << std::endl; break; } c = RecvBuffer; std::cout << "接收客户端信息为:" << c << std::endl; c = Protocol::CommandDealForServer(c); strcpy(SendBuffer, c.c_str()); Driver::DealOnlineUser(c, _ClientSocket); _Ret = send(_ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0); if (_Ret == SOCKET_ERROR) { std::cout << "Send Info Error::" << GetLastError() << std::endl; throw std::runtime_error(""); } } closesocket(_ClientSocket); } ).detach(); } }
5a79da8739e0fbc811132014ec2f8e0355bff63b
1b7a5437932b5d1a01788d5ce829f9c8706c81fa
/cusp/precond/aggregation/system/detail/generic/evolution_strength.h
ff096bd69c80f685db29f602c48eed239c1cbf3b
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
cusplibrary/cusplibrary
dc8cac129f7fffb8690933c19991dbce55a42deb
dc77579004a5d79a79c9463d7a9621834e73d089
refs/heads/develop
2022-08-16T00:30:16.420240
2018-03-14T07:27:31
2018-03-14T07:27:31
5,534,514
311
119
Apache-2.0
2023-06-25T11:03:21
2012-08-24T01:13:26
C++
UTF-8
C++
false
false
15,617
h
evolution_strength.h
/* * Copyright 2008-2014 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cusp/csr_matrix.h> #include <cusp/format_utils.h> #include <cusp/linear_operator.h> #include <cusp/multiply.h> #include <cusp/transpose.h> #include <cusp/eigen/spectral_radius.h> #include <thrust/functional.h> #include <thrust/iterator/permutation_iterator.h> namespace cusp { namespace precond { namespace aggregation { namespace detail { template<typename ValueType> struct approx_error : public thrust::unary_function<ValueType,ValueType> { __host__ __device__ ValueType operator()(const ValueType scale) const { return abs(1.0 - scale); } }; template<typename ValueType> struct conditional_invert : public thrust::unary_function<ValueType,ValueType> { __host__ __device__ ValueType operator()(const ValueType val) const { return (val != 0.0) ? 1.0 / val : val; } }; template<typename T> struct distance_filter_functor { T epsilon; distance_filter_functor(T epsilon) : epsilon(epsilon) {} __host__ __device__ T operator()(const T& A_val, const T& S_val) const { return (A_val >= (epsilon*S_val)) ? 0 : A_val; } }; template<typename T> struct non_zero_minimum { __host__ __device__ T operator()(const T &lhs, const T &rhs) const { if(lhs == 0) return rhs; if(rhs == 0) return lhs; return lhs < rhs ? lhs : rhs; } }; template<typename ValueType> struct filter_small_ratios_and_large_angles { template<typename Tuple> __host__ __device__ ValueType operator()(const Tuple& t) const { ValueType val = thrust::get<0>(t); bool angle = thrust::get<1>(t); bool ratio = thrust::get<2>(t); return (angle || ratio) ? 0 : val; } }; template<typename ValueType> struct set_perfect : public thrust::unary_function<ValueType,ValueType> { const ValueType eps; set_perfect(void) : eps(std::sqrt(std::numeric_limits<ValueType>::epsilon())) {} __host__ __device__ ValueType operator()(const ValueType val) const { return ((val < eps) && (val != 0)) ? 1e-4 : val; } }; template<typename ValueType> struct Atilde_functor { const ValueType rho_DinvA; Atilde_functor(const ValueType rho_DinvA) : rho_DinvA(rho_DinvA) {} template <typename Tuple> __host__ __device__ ValueType operator()(const Tuple& t) const { int row = thrust::get<0>(t); int col = thrust::get<1>(t); ValueType val = thrust::get<2>(t); ValueType temp = row == col; return temp - (1.0 / rho_DinvA) * val; } }; template<typename ValueType> struct incomplete_inner_functor { const int *Ap, *Aj; const ValueType *Ax, *Ax_t; incomplete_inner_functor(const int *Ap, const int *Aj, const ValueType *Ax, const ValueType *Ax_t) : Ap(Ap), Aj(Aj), Ax(Ax), Ax_t(Ax_t) {} template <typename Tuple> __host__ __device__ ValueType operator()(const Tuple& t) const { ValueType sum = 0.0; int row = thrust::get<0>(t); int col = thrust::get<1>(t); int A_pos = Ap[row]; int A_end = Ap[row+1]; int B_pos = Ap[col]; int B_end = Ap[col+1]; //while not finished with either A[row,:] or B[:,col] while(A_pos < A_end && B_pos < B_end) { int A_j = Aj[A_pos]; int B_j = Aj[B_pos]; if(A_j == B_j) { sum += Ax[A_pos] * Ax_t[B_pos]; A_pos++; B_pos++; } else if (A_j < B_j) { A_pos++; } else { //B_j < A_j B_pos++; } } return sum; } }; template<typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename ArrayType> typename thrust::detail::enable_if_convertible<typename ArrayType::format,cusp::array1d_format>::type evolution_strength_of_connection(thrust::execution_policy<DerivedPolicy> &exec, const MatrixType1& A, MatrixType2& S, const ArrayType& B, double rho_DinvA, const double epsilon, cusp::coo_format) { using namespace thrust::placeholders; typedef typename MatrixType1::index_type IndexType; typedef typename MatrixType1::value_type ValueType; typedef typename MatrixType1::memory_space MemorySpace; const size_t N = A.num_rows; const size_t M = A.num_entries; cusp::array1d<ValueType, MemorySpace> D(N); cusp::array1d<ValueType, MemorySpace> DAtilde(N); cusp::array1d<ValueType, MemorySpace> smallest_per_row(N); cusp::array1d<ValueType, MemorySpace> data(M); cusp::array1d<ValueType, MemorySpace> angle(M); cusp::array1d<ValueType, MemorySpace> Atilde_symmetric(M); cusp::array1d<ValueType, MemorySpace> Atilde_values(M); cusp::array1d<bool, MemorySpace> weak_ratio(M, false); cusp::array1d<bool, MemorySpace> neg_angle(M, false); cusp::array1d<ValueType, MemorySpace> Bmat_forscaling(B); cusp::array1d<ValueType, MemorySpace> Dinv_A_values(A.values); cusp::array1d<ValueType, MemorySpace> Dinv_A_T_values(M); cusp::array1d<IndexType, MemorySpace> A_row_offsets(N + 1); cusp::array1d<IndexType, MemorySpace> permutation(M); // compute symmetric permutation { cusp::array1d<IndexType, MemorySpace> indices(M); thrust::sequence(exec, permutation.begin(), permutation.end()); cusp::copy(exec, A.column_indices, indices); thrust::sort_by_key(exec, indices.begin(), indices.end(), permutation.begin()); } cusp::extract_diagonal(exec, A, D); // scale the rows of D_inv_S by D^-1 thrust::transform(exec, Dinv_A_values.begin(), Dinv_A_values.end(), thrust::make_permutation_iterator(D.begin(), A.row_indices.begin()), Dinv_A_values.begin(), thrust::divides<ValueType>()); if(rho_DinvA == 0.0) { rho_DinvA = cusp::eigen::ritz_spectral_radius( cusp::make_coo_matrix_view(A.num_rows, A.num_cols, A.num_entries, A.row_indices, A.column_indices, Dinv_A_values), 8); } cusp::indices_to_offsets(exec, A.row_indices, A_row_offsets); thrust::transform(exec, thrust::make_zip_iterator(thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin(), Dinv_A_values.begin())), thrust::make_zip_iterator(thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin(), Dinv_A_values.begin())) + M, Dinv_A_values.begin(), Atilde_functor<ValueType>(rho_DinvA)); // Form A^T thrust::gather(exec, permutation.begin(), permutation.end(), Dinv_A_values.begin(), Dinv_A_T_values.begin()); // Use computational shortcut to calculate Atilde^k only at sparsity // pattern of A { cusp::array1d<IndexType,MemorySpace> A_column_indices(A.column_indices); incomplete_inner_functor<ValueType> incomp_op(thrust::raw_pointer_cast(&A_row_offsets[0]), thrust::raw_pointer_cast(&A_column_indices[0]), thrust::raw_pointer_cast(&Dinv_A_values[0]), thrust::raw_pointer_cast(&Dinv_A_T_values[0])); thrust::transform(exec, thrust::make_zip_iterator(thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin())), thrust::make_zip_iterator(thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin())) + M, Atilde_values.begin(), incomp_op); } thrust::replace(exec, Bmat_forscaling.begin(), Bmat_forscaling.end(), 0, 1); cusp::extract_diagonal(exec, cusp::make_coo_matrix_view(A.num_rows, A.num_cols, A.num_entries, A.row_indices, A.column_indices, Atilde_values), DAtilde); cusp::copy(exec, Atilde_values, data); // Scale rows thrust::transform(exec, thrust::constant_iterator<ValueType>(1), thrust::constant_iterator<ValueType>(1) + M, thrust::make_permutation_iterator(DAtilde.begin(), A.row_indices.begin()), Atilde_values.begin(), thrust::multiplies<ValueType>()); // Scale columns thrust::transform(exec, Atilde_values.begin(), Atilde_values.end(), thrust::make_permutation_iterator(Bmat_forscaling.begin(), A.column_indices.begin()), Atilde_values.begin(), thrust::multiplies<ValueType>()); // Calculate angle cusp::blas::xmy(exec, data, Atilde_values, angle); thrust::transform(exec, angle.begin(), angle.end(), thrust::constant_iterator<ValueType>(0), neg_angle.begin(), thrust::less<ValueType>()); // Calculate approximation ratio thrust::transform(exec, Atilde_values.begin(), Atilde_values.end(), data.begin(), Atilde_values.begin(), thrust::divides<ValueType>()); thrust::transform(exec, Atilde_values.begin(), Atilde_values.end(), thrust::constant_iterator<ValueType>(1e-4), weak_ratio.begin(), thrust::less<ValueType>()); // Calculate approximation error thrust::transform(exec, Atilde_values.begin(), Atilde_values.end(), Atilde_values.begin(), approx_error<ValueType>()); // Set small ratios and large angles to weak thrust::transform(exec, thrust::make_zip_iterator(thrust::make_tuple(Atilde_values.begin(), neg_angle.begin(), weak_ratio.begin())), thrust::make_zip_iterator(thrust::make_tuple(Atilde_values.begin(), neg_angle.begin(), weak_ratio.begin())) + M, Atilde_values.begin(), filter_small_ratios_and_large_angles<ValueType>()); // Set near perfect connections to 1e-4 thrust::transform(exec, Atilde_values.begin(), Atilde_values.end(), Atilde_values.begin(), set_perfect<ValueType>()); // symmetrize measure thrust::scatter(exec, Atilde_values.begin(), Atilde_values.end(), permutation.begin(), Dinv_A_T_values.begin()); thrust::transform(exec, Atilde_values.begin(), Atilde_values.end(), Dinv_A_T_values.begin(), Atilde_symmetric.begin(), 0.5 * (_1 + _2)); thrust::scatter(exec, Atilde_symmetric.begin(), Atilde_symmetric.end(), permutation.begin(), Dinv_A_T_values.begin()); // Apply distance filter if(epsilon != std::numeric_limits<ValueType>::infinity()) { thrust::fill(exec, smallest_per_row.begin(), smallest_per_row.end(), std::numeric_limits<ValueType>::max()); thrust::reduce_by_key(exec, A.row_indices.begin(), A.row_indices.end(), Atilde_symmetric.begin(), thrust::make_discard_iterator(), smallest_per_row.begin(), thrust::equal_to<IndexType>(), non_zero_minimum<ValueType>()); thrust::transform(exec, Atilde_symmetric.begin(), Atilde_symmetric.end(), thrust::make_permutation_iterator(smallest_per_row.begin(), A.row_indices.begin()), Atilde_symmetric.begin(), distance_filter_functor<ValueType>(epsilon)); } // Set diagonal to 1.0, as each point is strongly connected to itself thrust::transform_if(exec, Atilde_symmetric.begin(), Atilde_symmetric.end(), thrust::make_transform_iterator( thrust::make_zip_iterator( thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin())), cusp::equal_pair_functor<IndexType>()), Atilde_symmetric.begin(), _1 = ValueType(1), thrust::identity<bool>()); // Symmetrize the final result thrust::scatter(exec, Atilde_symmetric.begin(), Atilde_symmetric.end(), permutation.begin(), Dinv_A_T_values.begin()); thrust::transform(exec, Atilde_symmetric.begin(), Atilde_symmetric.end(), Dinv_A_T_values.begin(), Atilde_symmetric.begin(), _1 + _2); // Count the number of zeros and copy entries into output matrix size_t num_zeros = thrust::count(Atilde_symmetric.begin(), Atilde_symmetric.end(), ValueType(0)); S.resize(N, N, M - num_zeros); thrust::copy_if(exec, thrust::make_zip_iterator(thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin())), thrust::make_zip_iterator(thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin())) + A.num_entries, Atilde_symmetric.begin(), thrust::make_zip_iterator(thrust::make_tuple(S.row_indices.begin(), S.column_indices.begin())), _1 != 0); } template<typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename ArrayType> typename thrust::detail::enable_if_convertible<typename ArrayType::format,cusp::array1d_format>::type evolution_strength_of_connection(thrust::execution_policy<DerivedPolicy> &exec, const MatrixType1& A, MatrixType2& S, const ArrayType& B, double rho_DinvA, const double epsilon, cusp::csr_format) { typedef typename MatrixType1::index_type IndexType; typedef typename MatrixType1::value_type ValueType; typedef typename MatrixType1::memory_space MemorySpace; cusp::array1d<IndexType, MemorySpace> A_row_indices(A.num_entries); cusp::offsets_to_indices(A.row_offsets, A_row_indices); cusp::coo_matrix<IndexType, ValueType, MemorySpace> S_; evolution_strength_of_connection(exec, cusp::make_coo_matrix_view(A.num_rows, A.num_cols, A.num_entries, A_row_indices, A.column_indices, A.values), S_, B, rho_DinvA, epsilon, cusp::coo_format()); cusp::convert(S_, S); } template<typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename ArrayType> typename thrust::detail::enable_if_convertible<typename ArrayType::format,cusp::array1d_format>::type evolution_strength_of_connection(thrust::execution_policy<DerivedPolicy> &exec, const MatrixType1& A, MatrixType2& S, const ArrayType& B, double rho_DinvA, const double epsilon) { typedef typename MatrixType1::format Format; Format format; evolution_strength_of_connection(exec, A, S, B, rho_DinvA, epsilon, format); } } // end namespace detail } // end namespace aggregation } // end namespace precond } // end namespace cusp
04d5ce67fcad0145f23f7e21ce8aac108cd4c607
b3931bc2e18fe54799b805edc1b8934e28606b33
/2013-2014/2term/HomeTask_1/Task_2/arraystack.h
672538aa4cdfe86196216e9979c1d5c56cfc1f82
[]
no_license
maxim-yakupov/University
0830cfa36038bef8932c134a6a035bea76471e90
bcc0f5ed6bf28430f7d740a43867e7cd47271731
refs/heads/master
2021-01-17T13:03:30.068669
2017-01-30T21:55:23
2017-01-30T21:55:23
58,821,128
1
0
null
null
null
null
UTF-8
C++
false
false
1,063
h
arraystack.h
#pragma once #include "stack.h" template <class Type> class ArrayStack:public Stack<Type> { public: ArrayStack<Type>(); ~ArrayStack<Type>(); void push(Type value); Type top() const; void pop(); bool isEmpty() const; void clear(); private: Type array[1000]; unsigned int head; }; /* * * * * * Implementashion of ArrayStack * (cause if I use derivement from template class, * implementashion should be in header file) */ template <class Type> ArrayStack<Type>::ArrayStack() : head(0) { } template <class Type> ArrayStack<Type>::~ArrayStack() { clear(); } template <class Type> void ArrayStack<Type>::push(Type value) { array[head] = value; head++; } template <class Type> Type ArrayStack<Type>::top() const { return array[head - 1]; } template <class Type> void ArrayStack<Type>::pop() { if (head) head--; } template <class Type> bool ArrayStack<Type>::isEmpty() const { return head; } template <class Type> void ArrayStack<Type>::clear() { while (head) { pop(); } }
3ca1d319fe10d022ce8e9925e7c53d73ca9e00be
eb2fc2a30ef1a6ea62c0438ec203a2405c5652c8
/src/common/utils.h
c2143b8ad1b048db72a6c5af97e21fbc1e441f41
[]
no_license
mincore/face_core
0e302a202704f738c1a05016f08c08f82dcdbaa0
5b15c3c9c78659bb448461547b6224a9fe522f58
refs/heads/master
2021-08-07T05:41:56.630294
2017-11-07T16:17:49
2017-11-07T16:17:49
109,857,621
1
1
null
null
null
null
UTF-8
C++
false
false
1,558
h
utils.h
/* =================================================== * Copyright (C) 2017 chenshangping All Right Reserved. * Author: chenshuangping(mincore@163.com) * Filename: utils.h * Created: 2017-06-02 15:24 * Description: * =================================================== */ #ifndef _UTILS_H #define _UTILS_H #include <stdio.h> #include <string> #include <sstream> #include <vector> #include <chrono> class noncopyable { protected: noncopyable() {} ~noncopyable() {} private: noncopyable(const noncopyable&); const noncopyable& operator=(const noncopyable&); }; template <typename T> class singleton: private noncopyable { public: static T* Instance() { static T t; return &t; } }; static inline std::string& strrtrim(std::string& s, const char* t) { s.erase(s.find_last_not_of(t) + 1); return s; } static inline std::string& strltrim(std::string& s, const char* t) { s.erase(0, s.find_first_not_of(t)); return s; } static inline std::string& strtrim(std::string& s, const char* t) { return strltrim(strrtrim(s, t), t); } static void inline strsplit(const char *s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; elems.clear(); while (getline(ss, item, delim)) { elems.push_back(strtrim(item, " \t")); } } static inline long long now() { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now().time_since_epoch() ).count(); } #endif
34166d5911af0bfff66c35c2fd5189591295c674
cf538d1073bb1b9a2449e9e1996f58e74f09fe4b
/fwk4gps 2011/fwk4gps 2011/Design.cpp
fce86c7e54201ae14466a39aa77c0850a1af579d
[]
no_license
ScottDowne/Mesocricetus
5067527dd20c7327591f086e9d0947b03e0818e4
c5360965eda35ec9bb7384717714c232bbd7048f
refs/heads/master
2016-09-10T22:35:44.128648
2011-12-15T19:12:39
2011-12-15T19:12:39
2,526,188
0
1
null
null
null
null
UTF-8
C++
false
false
10,183
cpp
Design.cpp
/* Design Implementation - Model Branch * * Design.cpp * fwk4gps version 2.0 * gam666/dps901 * October 4 2011 * copyright (c) 2011 Chris Szalwinski * distributed under TPL - see ../Licenses.txt */ #include "iContext.h" // for the Context Interface #include "iText.h" // for the Text Interface #include "iSound.h" // for the Sound Interface #include "iLight.h" // for the Light Interface #include "iObject.h" // for the Object Interface #include "iTexture.h" // for the Texture Interface #include "iCamera.h" // for the Camera Interface #include "iGraphic.h" // for the Graphic Interface #include "iCoordinator.h" // for the Coordinator Interface #include "iDisplay.h" // for the Display Interface #include "iSoundCard.h" // for the SoundCard Interface #include "iUtilities.h" // for strcpy() #include "Maze.h" #include <ctime> #include "Design.h" // for the Design class definition #include "MathDefinitions.h" // for MODEL_Z_AXIS #include "ModelSettings.h" // for FLOOR, MOUSE_BUTTON_SCALE, ROLL_SPEED const wchar_t* orient(wchar_t* str, const iFrame* frame, char c, int f = 1); const wchar_t* position(wchar_t* str, const iFrame* frame); //-------------------------------- Design ------------------------------------- // // The Design class implements the game design proper within the model branch // // CreateDesign creates the Design Object // iDesign* CreateDesign(iContext* c) { return new Design(c); } // constructor creates the coordinator object, the display object, and // the sound card object and initializes the instance pointers and the // reference time // Design::Design(iContext* c) : context(c) { coordinator = CreateCoordinator(context); display = CreateDisplay(context); soundCard = CreateSoundCard(context); // pointers to the objects // pointers to the lights pointLight = NULL; // pointers to the sounds // pointers to the text items timerText = NULL; meterText = NULL; midi = NULL; jump = NULL; //maze maze; gameOver = false; // reference time lastUpdate = 0; } // interrogate interrogates the host system for the available configurations // void Design::interrogate(void* hwnd) { display->interrogate(hwnd); } // configure sets the configuration for the display and the sound // card // void Design::configure() { display->configure(); } // setup sets up the host system for the selection configuration // bool Design::setup(void* hwnd) { bool rc = false; // setup the graphics card if (!display->setup(hwnd)) error(L"Design::10 Failed to set up the Display object"); else rc = true; return rc; } // initialize initializes the coordinator, creates the primitive sets, textures, // objects, lights, sounds, cameras, and text items for the initial coordinator, // and initializes the reference time // void Design::initialize(int now) { coordinator->reset(now); startTime = now; timeLeft = TIME_LIMIT; // projection parameters // context->set(GF_FR_NEAR, NEAR_CLIPPING); context->set(GF_FR_FAR, FAR_CLIPPING); context->set(GF_FR_FOV, FIELD_OF_VIEW); // maze --------------------------------------------------------- maze = new Maze(); // cameras ---------------------------------------------------------------- // camera at a distance - in lhs coordinates (camera = CreateCamera(context, maze))->translate((19 + 0.5f) * SCALE, 0.5f * SCALE, 1.5f * SCALE); camera->setRadius(17.8f); // coordinator ------------------------------------------------------------------ Colour wallColor(0.6f, 0.6f, 0.45f); Colour yellow(0.7f, 0.7f, 0.0f); Colour grey(0.7f, 0.7f, 0.7f); Colour turquoise(0, 0.8f, 0.6f); Colour black(0, 0, 0); Reflectivity greyish = Reflectivity(grey); // create textures // create vertex lists // lighting --------------------------------------------------------------- // global ambient light: a little bit of light on everything, for when all // "lights are out" context->set(GF_LT_BKGD, Vector(.2f, .2f, .2f)); // Create far away point-source light //pointLight = CreatePointLight(grey, grey, white, 20000.0f, true); //pointLight->translate(500.f, 1000.f, 100.f * MODEL_Z_AXIS); iLight * spotLight = CreateSpotLight(wallColor, wallColor, wallColor, 200.0f, true, 1, 0.00005f, 0.00001f, .60f, 0, 0.9f); spotLight->translate((19 + 0.5f) * SCALE, 0.5f * SCALE, (1.5f * SCALE) - 5 ); spotLight->attachTo(camera); // audio ------------------------------------------------------------------ midi = CreateSound( L"Crickets (by reinsamba) .xwma", LOCAL_SOUND, true, true, 360 ); midi->translate((1.5f) * SCALE, 0.5f * SCALE, 21.5f * SCALE); jump = CreateSound(L"yippe.wav", GLOBAL_SOUND, false, false); // Heads Up Display ------------------------------------------------------- timerText = CreateText(RelRect(0.0f, 0.0f, 0.42f, 0.2f), L""); meterText = CreateText(RelRect(0.0f, 0.2f, 1.00f, 0.43f), L""); maxDistance = (Vector((1.5f) * SCALE, 0.5f * SCALE, 21.5f * SCALE) - Vector((19 + 0.5f) * SCALE, 0.5f * SCALE, 1.5f * SCALE)).length(); strcpy(meterString, L" ", 1); // reference time lastUpdate = now; } // reset changes the context if any change has been requested and // reinitializes the reference time // void Design::reset(int now) { coordinator->reset(now); // audio ------------------------------------------------------------------ // reset reference time --------------------------------------------------- // lastUpdate = now; } // update updates the position and orientation of each object for time "now" // according to the keys pressed // void Design::update(int now) { static bool jumping = false; static int delta; static int distanceToEnd = 0; coordinator->update(now); timeLeft = (int)(TIME_LIMIT - (difftime(lastUpdate, startTime)/1000)); int condition = maze->checkCondition(); if (!gameOver) { if (timeLeft < 0 && condition <= 0) { gameOver = true; strcpy(timerString, L"You lose...", 11); } else { if (condition == 1) { gameOver = true; strcpy(timerString, L"You win!", 8); } else if (condition == -1) { // reset timer when user is at start point startTime = now; sprintf(timerString, timeLeft, L""); } else { sprintf(timerString, timeLeft, L""); } } int newDistance = ((maxDistance - (Vector(1.5f * SCALE, 0, 21.5f * SCALE) - context->get(GF_CA_POSN)).length())/maxDistance) * 30; if (newDistance != distanceToEnd) { distanceToEnd = newDistance; strcpy(meterString, L"------------------------------", 30); meterString[distanceToEnd] = L'*'; meterString[30] = '\0'; } } // audio ------------------------------------------------------------------ midi->update(); // lighting --------------------------------------------------------------- // coordinator ------------------------------------------------------------------ if (context->pressed(TOGGLE_COLLISION) || context->pressed(X_BUTTON)) { maze->toggleCollision(false); } else { maze->toggleCollision(true); } if (jumping) { if (now - delta > 3100) { jumping = false; } } if (context->pressed(CAM_JUMP) && !jumping) { delta = now; iSound* clone = jump->clone(); clone->play(now); jumping = true; } // reference time lastUpdate = now; } // resize resizes the display // void Design::resize() { display->resize(); } // render renders the coordinator by category // void Design::render() { // update the listener soundCard->update(); // draw the scene and optionally the HUD display->beginDrawFrame(); coordinator->render(OPAQUE_OBJECT); display->set(ALPHA_BLEND, true); coordinator->render(TRANSLUCENT_OBJECT); display->set(ALPHA_BLEND, false); coordinator->render(SOUND); if (coordinator->hudIsOn()) { display->beginDraw(HUD_ALPHA); if (timerText) { timerText->set(timerString); timerText->draw(); } if (meterText) { meterText->set(meterString); meterText->draw(); } display->endDraw(); } display->endDrawFrame(); } // suspends suspends the coordinator // void Design::suspend() { coordinator->suspend(); if (midi) midi->suspend(); if (jump) jump->suspend(); display->suspend(); } // restore re-initializes the reference time // void Design::restore(int now) { display->restore(); if (midi) midi->restore(now); if (jump) jump->restore(now); coordinator->restore(now); lastUpdate = now; } // release releases the coordinator // void Design::release() { coordinator->release(); display->release(); } // destructor destroys the coordinator // Design::~Design() { if (midi) midi->Delete(); if (jump) jump->Delete(); coordinator->Delete(); display->Delete(); soundCard->Delete(); } //-------------------------------- Text Generating Function ------------------- // // orient returns a text string with the orientation of the local c axis // of iFrame* frame // const wchar_t* orient(wchar_t* str, const iFrame* frame, char c, int f) { if (frame) { Vector v = frame->orientation(c); sprintf(str, (int)(f*v.x), (int)(f*v.y), (int)(f*v.z)); } return str; } // position returns a text string with the world position of frame // const wchar_t* position(wchar_t* str, const iFrame* frame) { if (frame) { Vector v = frame->position(); sprintf(str, (int)(v.x), (int)(v.y), (int)(v.z)); } return str; }
c895460b62bb832e711e8e5cf7e00b84707ad168
b837b59bb5dd90dccea3b58acaf8dc7afac105a3
/Code/gpDragAndDrop/DragAndDropApp.cpp
8358cfdd8f856dc72f38562862592d14286a0247
[ "MIT" ]
permissive
Manuzor/GamePhysics
b59d5cc0c9cd8f76181f451041cf3e64f79b9d71
59c7ff68c6bb72a4b3503752debd35c8b98893ce
refs/heads/master
2020-04-10T03:31:11.496973
2015-01-23T20:04:49
2015-01-23T20:04:49
24,562,659
2
0
null
null
null
null
UTF-8
C++
false
false
6,296
cpp
DragAndDropApp.cpp
#include "gpDragAndDrop/PCH.h" #include <Core/Input/InputManager.h> #include "gpDragAndDrop/DragAndDropApp.h" #include "gpCore/Rendering/Rendering.h" #include "gpCore/Rendering/RenderExtractor.h" #include "gpCore/World/World.h" #include "gpCore/Shapes.h" #include "gpCore/Utilities/RandomNumbers.h" static gpWorld* g_pWorld = nullptr; static ezDynamicArray<gpEntity*> g_entities; static const gpScalar g_defaultDamping = 0.001f; static gpRandomNumberGenerator g_rand; static gpEntity* Sphere(const char* name, const gpDisplacement& position) { auto pParticle = gpNew<gpEntity>(); g_entities.PushBack(pParticle); auto& p = Deref(pParticle); gpNameOf(p) = name; gpPositionOf(p) = position; gpMassOf(p) = gpMass((gpScalar)g_rand.GenerateInteger(5, 100)); gpLinearDampingOf(p) = g_defaultDamping; gpShapePtrOf(p) = gpNew<gpSphereShape>(gpValueOf(gpMassOf(p)) * 0.2f); return pParticle; } static void Populate(gpWorld& world) { gpGravityOf(world) = gpLinearAcceleration(gpVec3(0, 0, 0)); auto pShape = gpNew<gpSphereShape>(20.0f); gpScalar offset = 90.0f; gpScalar padding = 75.0f; ezStringBuilder name; for (ezUInt32 x = 0; x < 5; ++x) { for (ezUInt32 y = 0; y < 5; ++y) { name.Format("particle %d, %d", x, y); gpDisplacement d(padding * x + offset, padding * y + offset, 0); auto p = Sphere(name.GetData(), d); gpAddTo(world, Deref(p)); } } } static void Cleanup() { gpDelete(g_pWorld); } enum gpPositionOfOverloadHelper { MouseCursor }; // Call like this: gpPositionOf(MouseCursor) static gpDisplacement gpPositionOf(gpPositionOfOverloadHelper) { float fX; ezInputManager::GetInputSlotState(ezInputSlot_MousePositionX, &fX); fX *= gpWindow::GetWidthCVar()->GetValue(); float fY; ezInputManager::GetInputSlotState(ezInputSlot_MousePositionY, &fY); fY *= gpWindow::GetHeightCVar()->GetValue(); return gpDisplacement(fX, fY, 0.0f); } static bool IsUnderMouseCursor(const gpDisplacement& pos, gpScalar radius) { auto diff = gpPositionOf(MouseCursor) - pos; return gpIsZero(diff) || gpSquaredLengthOf(diff) < gpSquare(radius); } static gpEntity* FindEntityBelowMouseCursor() { for (ezUInt32 i = 0; i < g_entities.GetCount(); ++i) { auto pEntity = g_entities[i]; auto& entity = Deref(pEntity); auto& shape = gpShapeOf(entity); if (IsUnderMouseCursor(gpPositionOf(entity), gpRadiusOf(shape))) { return pEntity; } } return nullptr; } static void Update(gpTime dt) { static bool s_simulationPaused = false; static gpEntity* s_pDraggedObject = nullptr; bool forceStep = ezInputManager::GetInputActionState("Game", "Step") == ezKeyState::Pressed; if(ezInputManager::GetInputActionState("Game", "Pause") == ezKeyState::Pressed) { s_simulationPaused = !s_simulationPaused; if (s_simulationPaused) { ezLog::Info("Pausing simulation."); } else { ezLog::Info("Resuming simulation."); } } if (s_simulationPaused && !forceStep) return; auto dragState = ezInputManager::GetInputActionState("Game", "Drag"); if (dragState == ezKeyState::Pressed) { s_pDraggedObject = FindEntityBelowMouseCursor(); if (s_pDraggedObject) { gpLinearDampingOf(Deref(s_pDraggedObject)) = 0.1f; } } else if (dragState == ezKeyState::Up) { if (s_pDraggedObject) { gpLinearDampingOf(Deref(s_pDraggedObject)) = g_defaultDamping; } s_pDraggedObject = nullptr; } if (s_pDraggedObject && dragState == ezKeyState::Down) { auto diff = gpValueOf(gpPositionOf(MouseCursor) - gpPositionOf(Deref(s_pDraggedObject))); gpApplyLinearImpulseTo(Deref(s_pDraggedObject), gpLinearVelocity(diff * 2.0f)); } gpStepSimulationOf(Deref(g_pWorld), dt); } void gpDragAndDropApp::AfterEngineInit() { SetupFileSystem(); SetupLogging(); LogSystemInformation(); { EZ_LOG_BLOCK("Initialization"); ezTelemetry::CreateServer(); if (ezPlugin::LoadPlugin("ezInspectorPlugin").Failed()) { ezLog::SeriousWarning("Failed to load ezInspectorPlugin."); } SetupWindow(); ezStartup::StartupEngine(); ezClock::SetNumGlobalClocks(); ezClock::Get()->SetTimeStepSmoothing(AddressOf(m_TimeStepSmoother)); m_LastUpdate = ezTime::Now(); SetupInput(); RegisterInputAction("Game", "Drag", ezInputSlot_MouseButton0); RegisterInputAction("Game", "Reset", ezInputSlot_MouseButton1); RegisterInputAction("Game", "Pause", ezInputSlot_KeySpace); RegisterInputAction("Game", "Step", ezInputSlot_KeyReturn); // Poll once to finish input initialization; ezInputManager::PollHardware(); SetupRendering(); } gpRenderExtractor::AddExtractionListener([](gpRenderExtractor* pExtractor){ gpExtractRenderDataOf(Deref(g_pWorld), pExtractor); }); g_pWorld = gpNew<gpWorld>("World"); Populate(Deref(g_pWorld)); } void gpDragAndDropApp::BeforeEngineShutdown() { ::Cleanup(); ezStartup::ShutdownEngine(); Cleanup(); ezPlugin::UnloadPlugin("ezInspectorPlugin"); ezTelemetry::CloseConnection(); } ezApplication::ApplicationExecution gpDragAndDropApp::Run() { m_pWindow->ProcessWindowMessages(); if (m_bQuit) return Quit; ezClock::UpdateAllGlobalClocks(); const auto tUpdateInterval = ezTime::Seconds(1.0 / 60.0); const auto tNow = ezTime::Now(); bool bInputUpdated = false; while(tNow - m_LastUpdate > tUpdateInterval) { bInputUpdated = true; UpdateInput(tUpdateInterval); Update(tUpdateInterval); m_LastUpdate += tUpdateInterval; } // Make sure we don't miss any input events. if (!bInputUpdated) { ezInputManager::PollHardware(); } RenderFrame(); m_pWindow->PresentFrame(); ezTaskSystem::FinishFrameTasks(); ezTelemetry::PerFrameUpdate(); return Continue; }
7389953a7755412cc604014821ba81c9090b8ec9
58fa075d43d718bfffed89deda9af9ec01a31e34
/libldpc.h
27643db074b84cc74bf1ae0c528bb8245940271c
[]
no_license
pspuser/qldpc
9af0fd1c8b8708e0a1b463704cc25f0ee2f90a89
e3d548725520330e4fdb0de76f157e5a8dfe24d2
refs/heads/master
2021-09-14T13:40:02.669680
2017-11-09T16:28:33
2017-11-09T16:28:33
123,130,682
0
0
null
null
null
null
UTF-8
C++
false
false
1,936
h
libldpc.h
#ifndef LIBLDPC_H #define LIBLDPC_H #include "LDPC-4Qt/ldpc4qt.h" #include <fstream> #include <QByteArray> #include <vector> #include <QCoreApplication> #include <QtWidgets/QApplication> namespace LibLDPC { //!!! Размер ключа должен быть постоянным и быть равен 1000 (одной тысяче) //!!! QBER не должен превышать 0.11 static std::vector<LDPCCode> memory; static std::vector<double> speeds = {0.80, 0.70, 0.65, 0.63, 0.55, 0.53, 0.52, 0.47, 0.45, 0.35, 0.30}; static const uint constSize = 1024; void init(int seed); /* * @brief Возвращает LDPC-код для исправления ошибок на приёмной стороне * * @param vkey Отправляемое сообщение * @param _qber Доля ошибочных бит * @param seed Зерно для ПСП. Должен быть одинаковым для энкодера и декодера * * @return LDPC-код */ std::vector<bool> Encoder( std::vector<bool> &vkey, const double _qber, int seed); /* * @brief Возвращает сообщение, избавленное от ошибок * * @param vkey Сообщение с ошибочными битами * @param ldpcCode LDPC-код от энкодера * @param _qber Доля ошибочных бит * @param seed Зерно для ПСП. Должен быть одинаковым для энкодера и декодера * * @return LDPC-код */ std::vector<bool> Decoder( std::vector<bool> &vkey, std::vector<bool> &ldpcCode, const double _qber, int seed); //! Диапазоны QBER }; #endif // LIBLDPC_H
e0afae6ff4a008c1d33e1fbddfba3168a218ee43
b21894539d927e811f20f3ad93e54ce3f533f781
/main.cpp
3b3250aeb21205b8b79f43d2ae446d12b3213d3b
[ "MIT" ]
permissive
6rayWa1cher/codename-piratelands
93b156d81cca283800c0012ca6424a069809db4f
092850162879aa2fdfba8c78166311657c67bcf6
refs/heads/master
2022-11-17T11:12:27.066657
2020-06-28T11:10:11
2020-06-28T11:10:11
273,352,896
0
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
main.cpp
#include "mainwindow.h" #include <QApplication> #include <QInputDialog> int main(int argc, char *argv[]) { QApplication a(argc, argv); auto playerName = QInputDialog::getText(nullptr, "PirateLands", "Enter your name"); std::shared_ptr<Game> game = std::make_shared<Game>(playerName); ShopWindow s(nullptr, game); BattleWindow bw(nullptr, game); CopyrightWindow cw(nullptr); MapWindow mw(nullptr); MainWindow w(nullptr, &s, &mw, &cw, game); s.setFixedSize(s.size()); bw.setFixedSize(bw.size()); w.setFixedSize(w.size()); w.setWindowTitle("PirateLands"); w.show(); return a.exec(); }
63c63e74f22553dee039cdcbdbf027630c1a9d3c
5008099a73040154d32b77df70063076e2dc612d
/include/GameLevel.h
b7eec673ba8875b209442399d12e6c70a5169e77
[]
no_license
JorgeLasaosa/Pengo
bdce4f7f04f89203309725baebe3da59675b4c9f
9083448d0cd78c1f15e5a015f1ec30e45cc4af6e
refs/heads/master
2021-01-20T01:41:36.394710
2017-05-03T10:51:49
2017-05-03T10:51:49
81,827,738
0
0
null
null
null
null
UTF-8
C++
false
false
2,485
h
GameLevel.h
#ifndef GAMELEVEL_H #define GAMELEVEL_H #define GLEW_STATIC #include <GL/glew.h> #include <vector> #include <queue> #include <string> #include "GameObject.h" #include "Player.h" #include "SpriteRenderer.h" #include "Wallblock.h" #include "Iceblock.h" #include "Diamondblock.h" #include "Snobee.h" #include "SnobeeEgg.h" #include "FloatingText.h" #include "Camera.h" enum LevelState { LEVEL_START, LEVEL_SHOWING_EGGS, LEVEL_PLAY, LEVEL_KILL, LEVEL_LAST, LEVEL_WIN, LEVEL_LOSE, LEVEL_LOSE2, LEVEL_BONUS, LEVEL_TMP }; class Iceblock; // For compile class Snobee; // For compile class SnobeeEgg; // For compile class GameLevel { public: LevelState state; std::vector< std::vector<GameObject*> > field, fieldStart; std::vector< GameObject* > activeObjects; std::vector< Iceblock* > deadBlocks, eggBlocks; std::vector< Snobee* > enemies; std::vector< SnobeeEgg* > eggs; std::vector< FloatingText* > floatingTexts; std::queue< glm::vec2 > mazeNodesStart; std::vector<Wallblock> wallN; // Wall North std::vector<Wallblock> wallS; // Wall South std::vector<Wallblock> wallE; // Wall East std::vector<Wallblock> wallW; // Wall West Player* pengo; Camera* camera; GLint deadEnemies, liveEnemies; GLint showEggsCount; GLint numEggs; GLfloat SNOBEE_SPEED; GLint remainEggs; GLint maxEnemies; Texture creaturesTexture; Texture eggsTexture; GLint bonusOffset; GameLevel(Camera* camera); void update(); // Loads level from file void load(const std::string& filePath); bool generate(); // Render level void draw(SpriteRenderer& renderer); void draw(Cube3DRenderer& cube3DRenderer); void drawGenerating(SpriteRenderer& renderer); void drawGenerating(Cube3DRenderer& cube3DRenderer); bool checkCollision(glm::vec2 pos) const; bool checkWalls(glm::vec2 pos) const; bool checkEggAndDiamondBlocks(glm::vec2 pos) const; GameObject* getObjFromPosition(glm::vec2 pos) const; void moveBlocks(GLfloat interpolation); void moveEnemies(GLfloat interpolation); void destroyBlocks(GLfloat interpolation); void clearFromTop(SpriteRenderer& renderer, GLfloat to); void clearFromTop(Cube3DRenderer& renderer, GLfloat to); void respawnPengo(); glm::vec2 nearestAvailablePosition(GLint row, GLint col) const; void respawnEnemiesAtCorners(); void respawnBlocks(); void clear(); virtual ~GameLevel(); private: glm::vec2 genActualNode; }; #endif // GAMELEVEL_H
7856e04954c1f6ff324c910ab806b0b89f4ad123
9dc7f37e290c03d27172ef211fac548d08ec83c6
/Devices/igtlioStatusDevice.cxx
7e54781c40960bac9914bcda75071d8f5d35ba4e
[ "Apache-2.0" ]
permissive
Sunderlandkyl/OpenIGTLinkIO
cd8414ae08add54372e0c6e0facba5984ca3ec48
4b792865f07e0dbc812c328176d74c94a5e5983c
refs/heads/master
2022-11-01T01:09:22.149398
2018-01-12T04:03:04
2018-01-24T03:08:33
120,339,747
0
0
null
2018-02-05T17:45:29
2018-02-05T17:45:28
null
UTF-8
C++
false
false
3,723
cxx
igtlioStatusDevice.cxx
#include "igtlioStatusDevice.h" #include <vtkObjectFactory.h> namespace igtlio { //--------------------------------------------------------------------------- DevicePointer StatusDeviceCreator::Create(std::string device_name) { StatusDevicePointer retval = StatusDevicePointer::New(); retval->SetDeviceName(device_name); return retval; } //--------------------------------------------------------------------------- std::string StatusDeviceCreator::GetDeviceType() const { return StatusConverter::GetIGTLTypeName(); } //--------------------------------------------------------------------------- vtkStandardNewMacro(StatusDeviceCreator); //--------------------------------------------------------------------------- vtkStandardNewMacro(StatusDevice); //--------------------------------------------------------------------------- StatusDevice::StatusDevice() { } //--------------------------------------------------------------------------- StatusDevice::~StatusDevice() { } //--------------------------------------------------------------------------- unsigned int StatusDevice::GetDeviceContentModifiedEvent() const { return StatusModifiedEvent; } //--------------------------------------------------------------------------- std::string StatusDevice::GetDeviceType() const { return StatusConverter::GetIGTLTypeName(); } //--------------------------------------------------------------------------- int StatusDevice::ReceiveIGTLMessage(igtl::MessageBase::Pointer buffer, bool checkCRC) { if (StatusConverter::fromIGTL(buffer, &HeaderData, &Content, checkCRC, &this->metaInfo)) { this->Modified(); this->InvokeEvent(StatusModifiedEvent, this); this->InvokeEvent(ReceiveEvent); return 1; } return 0; } //--------------------------------------------------------------------------- igtl::MessageBase::Pointer StatusDevice::GetIGTLMessage() { /* // cannot send a non-existent status (?) if (Content.errorname.empty()) { return 0; } */ if (!StatusConverter::toIGTL(HeaderData, Content, &this->OutMessage, &this->metaInfo)) { return 0; } return dynamic_pointer_cast<igtl::MessageBase>(this->OutMessage); } //--------------------------------------------------------------------------- igtl::MessageBase::Pointer StatusDevice::GetIGTLMessage(MESSAGE_PREFIX prefix) { /* if (prefix==MESSAGE_PREFIX_GET) { if (this->GetMessage.IsNull()) { this->GetMessage = igtl::GetStatusMessage::New(); } this->GetMessage->SetDeviceName(HeaderData.deviceName.c_str()); this->GetMessage->Pack(); return dynamic_pointer_cast<igtl::MessageBase>(this->GetMessage); } */ if (prefix==MESSAGE_PREFIX_NOT_DEFINED) { return this->GetIGTLMessage(); } return igtl::MessageBase::Pointer(); } //--------------------------------------------------------------------------- std::set<Device::MESSAGE_PREFIX> StatusDevice::GetSupportedMessagePrefixes() const { std::set<MESSAGE_PREFIX> retval; retval.insert(MESSAGE_PREFIX_NOT_DEFINED); return retval; } void StatusDevice::SetContent(StatusConverter::ContentData content) { Content = content; this->Modified(); this->InvokeEvent(StatusModifiedEvent, this); } StatusConverter::ContentData StatusDevice::GetContent() { return Content; } //--------------------------------------------------------------------------- void StatusDevice::PrintSelf(ostream& os, vtkIndent indent) { Device::PrintSelf(os, indent); os << indent << "ErrorCode:\t" << Content.code << "\n"; os << indent << "ErrorSubCode:\t" << Content.subcode << "\n"; os << indent << "ErrorName:\t" << Content.errorname << "\n"; os << indent << "StatusString:\t" << Content.statusstring << "\n"; } } //namespace igtlio
bb6d478fccb94f7f276dc5a3f92b2705092fd0b1
69c340aed4412535dd6e185ade0d3e2b6147418e
/Graphs/All_possible_paths_of_len_k_from_u_to_v.cpp
ac866afd3197415fb42859214f3c2ca4052c5d9f
[]
no_license
Meaha7/DSA-Marathon
656f1c1505adf24d2a3501a1f216e2fcb9aa3e32
9fb5c4d16a0192cb35f3da5c0a09b67ea2906dbd
refs/heads/main
2023-07-11T07:14:01.912316
2021-08-21T21:25:05
2021-08-21T21:25:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,520
cpp
All_possible_paths_of_len_k_from_u_to_v.cpp
#include <iostream> #include <string> #include <vector> #include <climits> #include <queue> #include <stack> #include <map> #include <set> using namespace std; //Dp solution int MinimumWalk(vector<vector<int>> &graph, int u, int v, int k) { // Code here int i, j, e, a; int V = graph.size(); int dp[V][V][k + 1]; for (e = 0; e <= k; e++) { for (i = 0; i < V; i++) { for (j = 0; j < V; j++) { dp[i][j][e] = 0; if (e == 0 && i == j) { dp[i][j][e] = 1; } else if (e == 1 && graph[i][j]) { dp[i][j][e] = 1; } else if (e > 1) { for (a = 0; a < V; a++) { if (graph[i][a]) { dp[i][j][e] += dp[a][j][e - 1]; } } } } } } return dp[u][v][k]; } //Recursive sol int Minwalk(vector<vector<int>>&graph, int u, int v, int k) { int V=graph.size(); if(k==0 && u==v) return 1; if(k==1 && graph[u][v]) return 1; int count=0; for(int i=0;i<V;i++) { if(graph[u][i]) count+=Minwalk(graph,i,v,k-1); } return count; } int main() { }
08e6b4e62a30646dbcb3ed05b04cdad76142743d
1bcc75d266ba8416563727ff19ead5976b2deb18
/Classes/widgets/Slider.cpp
9d787ad40c433f1b321f61fcf1155b66ae19cd27
[ "MIT" ]
permissive
Pisces000221/thats-unnatural
3aaab0517b0577310073b36c50e3fa09e52d4dde
b84575b19c86e7de878078198a40383f5e16d30d
refs/heads/master
2020-12-24T14:26:59.709765
2014-08-27T11:02:41
2014-08-27T11:02:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,633
cpp
Slider.cpp
#include "Slider.h" #include "cocos2d.h" using namespace cocos2d; Slider *Slider::create(float min, float max, float increment, callback_type callback) { Slider *ret = new Slider(); if (ret && ret->init(min, max, increment, callback)) return ret; else { CC_SAFE_DELETE(ret); ret = nullptr; return nullptr; } } bool Slider::init(float min, float max, float increment, callback_type callback) { if (!Node::init()) return false; _val = _minval = min; _maxval = max; _increment = increment; _callback = callback; // Calculate number format, currently only decimal precision supported int digits = 0; // Use increment as a temporary variable while (fabs((int)increment - increment) / _increment > 1e-5) { increment *= 10.; ++digits; } _num_format = new char[10]; sprintf(_num_format, "%%.%df", digits); _bar = Sprite::create("images/slider_bar.png"); _bar->setNormalizedPosition(Vec2(0.5, 0)); _bar->setColor(Color3B(255, 192, 64)); _bar->setOpacity(96); this->addChild(_bar); _ptbar = ProgressTimer::create(Sprite::create("images/slider_bar.png")); _ptbar->getSprite()->setColor(Color3B(255, 192, 64)); _ptbar->setNormalizedPosition(Vec2(0.5, 0)); _ptbar->setType(ProgressTimer::Type::BAR); _ptbar->setBarChangeRate(Vec2(1, 0)); _ptbar->setMidpoint(Vec2::ANCHOR_MIDDLE_LEFT); this->addChild(_ptbar); _thumb = Sprite::create("images/gpicker_thumb.png"); _thumb->setPositionY(_contentSize.height * 0.5); _thumb->setScale(1.618034); this->addChild(_thumb); _label = LABEL("", 24, "Light"); _label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP); _label->setNormalizedPosition(Vec2(0.5, 0)); _label->setScale(0.5); // Prevent over-antialiasing _thumb->addChild(_label); // Enable touching auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(Slider::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(Slider::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(Slider::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); this->setContentSize(Size(_bar->getContentSize().width, _thumb->getContentSize().height + _label->getContentSize().height * 0.5)); refreshDisp(); return true; } void Slider::setContentSize(const Size &newSize) { float w = _bar->getContentSize().width; float h = _thumb->getContentSize().height * _thumb->getScaleY(); Node::setContentSize(Size(newSize.width, h)); _bar->setScaleX(newSize.width / w); _ptbar->setScaleX(newSize.width / w); _validTouchRect.origin = Vec2(0, -_thumb->getContentSize().height); _validTouchRect.size = Size(newSize.width, h); refreshDisp(); } void Slider::setValue(float val) { _val = val; ENSURE_IN_RANGE(_val, _minval, _maxval); refreshDisp(); if (_callback) _callback(_val); } bool Slider::onTouchBegan(Touch *touch, Event *event) { if (!_validTouchRect.containsPoint(convertTouchToNodeSpace(touch))) return false; this->onTouchMoved(touch, event); return true; } void Slider::onTouchMoved(Touch *touch, Event *event) { float x = this->convertTouchToNodeSpace(touch).x; this->setValueByRate(x / _contentSize.width); } void Slider::onTouchEnded(Touch *touch, Event *event) { } void Slider::refreshDisp() { float r = (_val - _minval) / (_maxval - _minval); _thumb->setPositionX(r * _contentSize.width); _ptbar->setPercentage(r * 100.f); char s[5]; sprintf(s, _num_format, _val); _label->setString(s); }
3ea9ccf4a28c2a53dd73692b8dce54547700d124
e67259f518e61f2b15dda1eb767f012a5f3a6958
/src/storage/table/chunk_info.cpp
91c0040b5992497f84baa11022a129e248751383
[ "MIT" ]
permissive
AdrianRiedl/duckdb
e0151d883d9ef2fa1b84296c57e9d5d11210e9e3
60c06c55973947c37fcf8feb357da802e39da3f1
refs/heads/master
2020-11-26T13:14:07.776404
2020-01-31T11:44:23
2020-01-31T11:44:23
229,081,391
2
0
MIT
2019-12-19T15:17:41
2019-12-19T15:17:40
null
UTF-8
C++
false
false
3,048
cpp
chunk_info.cpp
#include "duckdb/storage/table/chunk_info.hpp" #include "duckdb/transaction/transaction.hpp" using namespace duckdb; using namespace std; static bool UseVersion(Transaction &transaction, transaction_t id) { return id < transaction.start_time || id == transaction.transaction_id; } //===--------------------------------------------------------------------===// // Delete info //===--------------------------------------------------------------------===// ChunkDeleteInfo::ChunkDeleteInfo(VersionManager &manager, index_t start_row, ChunkInfoType type) : ChunkInfo(manager, start_row, type) { for (index_t i = 0; i < STANDARD_VECTOR_SIZE; i++) { deleted[i] = NOT_DELETED_ID; } } ChunkDeleteInfo::ChunkDeleteInfo(ChunkDeleteInfo &info, ChunkInfoType type) : ChunkInfo(info.manager, info.start, type) { for (index_t i = 0; i < STANDARD_VECTOR_SIZE; i++) { deleted[i] = info.deleted[i]; } } index_t ChunkDeleteInfo::GetSelVector(Transaction &transaction, sel_t sel_vector[], index_t max_count) { index_t count = 0; for (index_t i = 0; i < max_count; i++) { if (!UseVersion(transaction, deleted[i])) { sel_vector[count++] = i; } } return count; } bool ChunkDeleteInfo::Fetch(Transaction &transaction, row_t row) { return !UseVersion(transaction, deleted[row]); } void ChunkDeleteInfo::Delete(Transaction &transaction, row_t rows[], index_t count) { // first check the chunk for conflicts for (index_t i = 0; i < count; i++) { if (deleted[rows[i]] != NOT_DELETED_ID) { // tuple was already deleted by another transaction throw TransactionException("Conflict on tuple deletion!"); } } // after verifying that there are no conflicts we mark the tuples as deleted for (index_t i = 0; i < count; i++) { deleted[rows[i]] = transaction.transaction_id; } } void ChunkDeleteInfo::CommitDelete(transaction_t commit_id, row_t rows[], index_t count) { for (index_t i = 0; i < count; i++) { deleted[rows[i]] = commit_id; } } //===--------------------------------------------------------------------===// // Insert info //===--------------------------------------------------------------------===// ChunkInsertInfo::ChunkInsertInfo(VersionManager &manager, index_t start_row) : ChunkDeleteInfo(manager, start_row, ChunkInfoType::INSERT_INFO) { for (index_t i = 0; i < STANDARD_VECTOR_SIZE; i++) { inserted[i] = NOT_DELETED_ID; } } ChunkInsertInfo::ChunkInsertInfo(ChunkDeleteInfo &info) : ChunkDeleteInfo(info, ChunkInfoType::INSERT_INFO) { for (index_t i = 0; i < STANDARD_VECTOR_SIZE; i++) { inserted[i] = NOT_DELETED_ID; } } index_t ChunkInsertInfo::GetSelVector(Transaction &transaction, sel_t sel_vector[], index_t max_count) { index_t count = 0; for (index_t i = 0; i < max_count; i++) { if (UseVersion(transaction, inserted[i]) && !UseVersion(transaction, deleted[i])) { sel_vector[count++] = i; } } return count; } bool ChunkInsertInfo::Fetch(Transaction &transaction, row_t row) { return UseVersion(transaction, inserted[row]) && !UseVersion(transaction, deleted[row]); }
e007b8b52371463812e28fd17d02d2d5458af730
9d854d6314a444d3e1c63730104ba7357916ba8d
/c++_course_version/1/2_prim.cpp
1384ee6ed2fe5d02d3d8a09ab5c1c6e6d8f954b3
[]
no_license
MikeShah/C-SoftwareEngineering
b0c0289e0a2969207e10d221dd5b281f9758b9ce
63ba44f1b8b039534aea7dbadb5401fb7b3c011e
refs/heads/master
2023-05-02T16:25:36.769839
2023-04-13T21:37:31
2023-04-13T21:37:31
233,117,843
14
12
null
2023-02-02T01:08:41
2020-01-10T19:38:05
C++
UTF-8
C++
false
false
680
cpp
2_prim.cpp
// clang++ -std=c++11 2_prim.cpp -o prim #include <iostream> // Declare variable ahead of use // This variable is outside scope of any // function, so it is also 'global' // (i.e. available anywhere) const float PI = 3.1415; // ('const' means PI will not change) // Define a primitive char char status; int main(){ // Use '<<' operator to output multiple values std::cout << "PI is: " << PI << '\n'; // Best practice(read: almost always) // define value of variable before use. status = 'A'; // Note, '\n' in single quotes because it is // an escape sequence represented in one char. std::cout << "status: " << status << '\n'; return 0; }
3d0242801a2f4224acc90c0fc1eebabb0d9a5f2d
730aa55f95f63b5c457093b805ed55c2f6d703db
/src/scena.cpp
9621b3579324930c67aecc2daa4567ca01bc4d24
[ "Unlicense" ]
permissive
KPO-2020-2021/zad5_1-michalpiaskowski15
7bb39d14119cfc0d07bb6f6109bd3cb1fdf5cbab
4424dd047f9bfedb83d952a1439e58f38622732b
refs/heads/master
2023-06-07T02:18:38.970682
2021-06-27T20:10:06
2021-06-27T20:10:06
371,340,987
0
0
null
null
null
null
UTF-8
C++
false
false
10,586
cpp
scena.cpp
#include "scena.h" #include "przeszkoda1.h" #include "graniastoslup.hh" scena::scena(){ this->promien_drona = 6.4; this->rozmiar_przeszkody = 6; this->index_drona = 0; matrix3d orient = matrix3d(); vector3d pozycja_drona1 = vector3d(20, 20, 1); vector3d pozycja_drona2 = vector3d(100, 20, 1); std::shared_ptr<Droniarz> dronLewy = std::make_shared<Droniarz>("../datasets/korpus1.dat","../datasets/rotor10.dat", "../datasets/rotor11.dat", "../datasets/rotor12.dat", "../datasets/rotor13.dat", pozycja_drona1,orient); std::shared_ptr<Droniarz> dronPrawy = std::make_shared<Droniarz>("../datasets/korpus2.dat","../datasets/rotor20.dat", "../datasets/rotor21.dat", "../datasets/rotor22.dat", "../datasets/rotor23.dat", pozycja_drona2,orient); this->wszystkie_drony.push_back(dronLewy); this->wszystkie_drony.push_back(dronPrawy); vector3d pozycja1 = vector3d(50, 20, 1); vector3d pozycja2 = vector3d(30, 30, 1); vector3d pozycja3 = vector3d(40, 40, 1); vector3d pozycja4 = vector3d(50, 50, 1); vector3d skala1 = vector3d(1,1,1); vector3d pozycja5 = vector3d(78, 86, 1); this->wszystkie_przeszkody.push_back(dronLewy); this->wszystkie_przeszkody.push_back(dronPrawy); this->wszystkie_przeszkody.push_back(std::make_shared<Przeszkoda1>(pozycja1,"../datasets/przeszkoda1.dat", "../datasets/przeszkoda1_rys.dat", skala1)); this->wszystkie_przeszkody.push_back(std::make_shared<Przeszkoda2>(pozycja2,"../datasets/przeszkoda2.dat", "../datasets/przeszkoda2_rys.dat", skala1)); this->wszystkie_przeszkody.push_back(std::make_shared<Przeszkoda3>(pozycja3,"../datasets/przeszkoda3.dat", "../datasets/przeszkoda3_rys.dat", skala1)); this->wszystkie_przeszkody.push_back(std::make_shared<Przeszkoda2>(pozycja4,"../datasets/przeszkoda2.dat", "../datasets/przeszkoda4_rys.dat", skala1)); this->wszystkie_przeszkody.push_back(std::make_shared<Przeszkoda3>(pozycja5,"../datasets/przeszkoda3.dat", "../datasets/przeszkoda5_rys.dat", skala1)); for(int j = 0; j < 2; ++j){ this->wszystkie_drony[j]->szukanie_pozycji(); gnuplot.DodajNazwePliku(this->wszystkie_drony[j]->Wez_korpus().Zapis_wierzcholki().c_str()) .ZmienSposobRys(PzG::SR_Ciagly) .ZmienSzerokosc(2) .ZmienKolor(1); for(int i = 0; i<4; ++i){ gnuplot.DodajNazwePliku(this->wszystkie_drony[j]->Wez_rotor(i).Zapis_wierzcholki().c_str()) .ZmienSposobRys(PzG::SR_Ciagly) .ZmienSzerokosc(2) .ZmienKolor(2); } } for(int i = 2; i < this->wszystkie_przeszkody.size(); ++i){ gnuplot.DodajNazwePliku(this->wszystkie_przeszkody[i]->Zapis_wierzcholki().c_str()) .ZmienSposobRys(PzG::SR_Ciagly) .ZmienSzerokosc(2) .ZmienKolor(3); } std::ofstream x; x.open("../datasets/linia_lotu.dat"); x.close(); gnuplot.DodajNazwePliku("../datasets/linia_lotu.dat") .ZmienSposobRys(PzG::SR_Ciagly) .ZmienSzerokosc(2) .ZmienKolor(4); x.open("../datasets/tlo.dat"); x.close(); gnuplot.DodajNazwePliku("../datasets/tlo.dat") .ZmienSposobRys(PzG::SR_Ciagly) .ZmienSzerokosc(1) .ZmienKolor(5); gnuplot.ZmienTrybRys(PzG::TR_3D); gnuplot.UstawZakresX((0), 200); gnuplot.UstawZakresY((0), 200); gnuplot.UstawZakresZ((-10), 40); } /** * @brief Rysowanie sceny * */ void scena::rysowanie_sceny(){ std::ofstream x; for(int i = 2; i < this->wszystkie_przeszkody.size(); ++i) { this->wszystkie_przeszkody[i]->szukanie_pozycji(); x.open(this->wszystkie_przeszkody[i]->Zapis_wierzcholki()); x << *(wszystkie_przeszkody[i]); x.close(); } for(int j = 0; j < 2; ++j){ Cuboid tmp; Graniastoslup tmpGr; x.open(this->wszystkie_drony[j]->Wez_korpus().Zapis_wierzcholki()); tmp = this->wszystkie_drony[j]->Wez_korpus(); x << tmp; x.close(); for(int i = 0; i<4;++i){ x.open(this->wszystkie_drony[j]->Wez_rotor(i).Zapis_wierzcholki()); tmpGr = this->wszystkie_drony[j]->Wez_rotor(i); x << tmpGr; x.close(); } } x.open("../datasets/tlo.dat"); for(int i = 0; i <= 200; i+=10){ for(int j = 0; j <= 200; j += 10){ x << j << " " << i+10 << " 0\n"; x << j << " " << i << " 0\n"; if(j < 200){ x << "#\n\n"; } } x << 0 << " " << i << " 0\n#\n\n"; } x.close(); gnuplot.Inicjalizuj(); gnuplot.Rysuj(); } /** * @brief Animacja lotu drona * * @param dlugosc * @param kat */ void scena::animcja_lotu(double dlugosc, double kat){ vector3d wektor_lotu = vector3d(dlugosc, 0 ,0); matrix3d kierunek = matrix3d(kat, 'z'); wektor_lotu = kierunek * wektor_lotu; wszystkie_drony[this->index_drona]->obrot(kierunek); rysowanie_sceny(); vector3d wektor_jednostkowy; wektor_jednostkowy = wektor_lotu / wektor_lotu.dlugosc(); std::ofstream x; while(sprawdz_trase(wektor_lotu)){ zapisz_linie_lotu(wektor_lotu, 20); wektor_lotu = wektor_lotu + wektor_jednostkowy; usleep(100); rysowanie_sceny(); } zapisz_linie_lotu(wektor_lotu, 20); lot_w_gore(20); vector3d wektor_animacji = wektor_jednostkowy; matrix3d macierz_animacji = matrix3d(15, 'z'); matrix3d macierz_maly_kat = matrix3d(15,'z'); while(wektor_animacji.dlugosc() < wektor_lotu.dlugosc()){ wszystkie_drony[this->index_drona]->translacja(wektor_jednostkowy); wektor_animacji = wektor_animacji + wektor_jednostkowy; usleep(50000); wszystkie_drony[this->index_drona]->szukanie_pozycji(); rysowanie_sceny(); for(int k = 0; k < 10; ++k) { this->wszystkie_drony[this->index_drona]->obrot_rotorow(macierz_animacji); macierz_animacji = macierz_maly_kat * macierz_animacji; rysowanie_sceny(); usleep(1000); } } lot_w_gore(-20); x.open("../datasets/linia_lotu.dat"); x.close(); } /** * @brief Indeksowanie drona * * @param index */ void scena::ustaw_index(int index){ this->index_drona = index; } void scena::lot_w_gore(double wysokosc){ vector3d wektor_lotu = vector3d(0,0,wysokosc); vector3d wektor_jednostkowy; wektor_jednostkowy = wektor_lotu / wektor_lotu.dlugosc(); vector3d wektor_animacji = wektor_jednostkowy;\ matrix3d macierz_animacji = matrix3d(15, 'z'); matrix3d macierz_maly_kat = matrix3d(15,'z'); while(wektor_animacji.dlugosc() < wektor_lotu.dlugosc()){ wszystkie_drony[this->index_drona]->translacja(wektor_jednostkowy); wektor_animacji = wektor_animacji + wektor_jednostkowy; usleep(50000); wszystkie_drony[this->index_drona]->szukanie_pozycji(); rysowanie_sceny(); /*ruch rotora*/ for(int k = 0; k < 10; ++k) { this->wszystkie_drony[this->index_drona]->obrot_rotorow(macierz_animacji); macierz_animacji = macierz_maly_kat * macierz_animacji; rysowanie_sceny(); usleep(500); } } } /** * @brief Zapis linii lotu * * @param wektor_lotu * @param wysokosc */ void scena::zapisz_linie_lotu(vector3d &wektor_lotu, double wysokosc){ vector3d vec1; vector3d vec2; std::ofstream x; x.open("../datasets/linia_lotu.dat"); vec1 = this->wszystkie_drony[this->index_drona]->Wez_korpus().Wez_srodek(); x << vec1 << std::endl; vec2 = vector3d(0,0,wysokosc); vec2 = vec2 + vec1; x << vec2 << std::endl; vec2 = vec2 + wektor_lotu; x << vec2 <<std::endl; vec1 = vector3d(0,0,wysokosc); vec2 = vec2 - vec1; x << vec2 << std::endl; x.close(); } /** * @brief Dodawanie przeszkody * * @param _x * @param _y * @param typ * @param nazwa_przeszkody */ void scena::dodaj_przeszkode(double _x, double _y, char typ, std::string nazwa_przeszkody){ vector3d pozycja = vector3d(_x,_y,1); vector3d skala = vector3d(1,1,1); nazwa_przeszkody = std::string("../datasets/") + nazwa_przeszkody + std::string(".dat"); switch (typ) { case '1': this->wszystkie_przeszkody.push_back(std::make_shared<Przeszkoda1>(pozycja ,"../datasets/przeszkoda1.dat", nazwa_przeszkody.c_str(), skala)); break; case '2': this->wszystkie_przeszkody.push_back(std::make_shared<Przeszkoda2>(pozycja ,"../datasets/przeszkoda2.dat", nazwa_przeszkody.c_str(), skala)); break; case '3': this->wszystkie_przeszkody.push_back(std::make_shared<Przeszkoda3>(pozycja ,"../datasets/przeszkoda3.dat", nazwa_przeszkody.c_str(), skala)); break;; default: break; } std::ofstream x; x.open(nazwa_przeszkody); x.close(); gnuplot.DodajNazwePliku(this->wszystkie_przeszkody.back()->Zapis_wierzcholki().c_str()) .ZmienSposobRys(PzG::SR_Ciagly) .ZmienSzerokosc(1) .ZmienKolor(1); this->wszystkie_przeszkody.back()->szukanie_pozycji(); rysowanie_sceny(); } /** * @brief Usuwanie przeszkody * * @param index */ void scena::usun_przeszkode(int index){ std::ofstream x; switch (index) { case 0: throw std::exception(); break; case 1: throw std::exception(); break; default: x.open(this->wszystkie_przeszkody[index]->Zapis_wierzcholki()); x.close(); break; } this->wszystkie_przeszkody.erase(this->wszystkie_przeszkody.begin() + index); } /** * @brief Sprawdzanie trasy * * @param trasa * @return true * @return false */ bool scena::sprawdz_trase(vector3d &trasa){ vector3d nowa_pozycja_drona = this->wszystkie_drony[this->index_drona]->Wez_srodek(); nowa_pozycja_drona = nowa_pozycja_drona + trasa; for(int i = 0; i < this->wszystkie_przeszkody.size(); ++i){ if((abs(nowa_pozycja_drona[0] - this->wszystkie_przeszkody[i]->Wez_srodek()[0]) < this->promien_drona + this->rozmiar_przeszkody)&& (abs(nowa_pozycja_drona[1] - this->wszystkie_przeszkody[i]->Wez_srodek()[0]) < this->promien_drona + this->rozmiar_przeszkody)){ return true; } } return false; }
8bc7810299a6685f0367fd993e157f02184a8501
6ddba6f24428e5639e4079daae7507deb763aab6
/getImage.h
d21b8a4e7b2f5c496a086e62de44684a0c3d33b4
[]
no_license
malreddysid/sudoku
dfe9a30e202ebcb67de02dee51a2fd659b6febe9
d0a9feb4f8249c391a1af222d9768d1b5281a8a3
refs/heads/master
2021-01-20T18:57:48.525799
2016-07-22T18:25:46
2016-07-22T18:25:46
63,436,409
2
0
null
null
null
null
UTF-8
C++
false
false
393
h
getImage.h
#include <stdio.h> #include <vector> #include <stdlib.h> #include <opencv2/opencv.hpp> #include <opencv/cv.hpp> #include <opencv/highgui.h> using namespace std; using namespace cv; const int NUMRECT_DIM = 20; const int NUMRECT_PIX = NUMRECT_DIM * NUMRECT_DIM; // images for number overlay const int OVERLAY_ROWS = 30; const int OVERLAY_COLS = 26; void getImage(char *image, int **puzzle);
246213b19dcb2462055b2cbeb1b3739233d51162
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/new_hunk_4390.cpp
089ab9de2cfd6bce69d87f0e2599a83b0f19668b
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
new_hunk_4390.cpp
graph_show_commit(opt->graph); if (!opt->graph) put_revision_mark(opt, commit); fputs(find_unique_abbrev(commit->object.sha1, abbrev_commit), stdout); if (opt->print_parents) show_parents(commit, abbrev_commit);
ca1eaead8975082b7dd910b926f0a02b25aa8224
9cd1657460a405cd3f356e73c70d2d6e95616bc9
/algolab2018-master/week5/punch/punch2.cc
93d4d04620d96a2bf92ce6c74ed839f6bb3698c8
[]
no_license
Alchemille/Algolab
42663a5b9cf5e1d72d62828da7ef6143b5df063f
abd6efecf1dd0b7a762db07c82efc660525d259e
refs/heads/master
2022-04-06T23:11:21.885451
2020-02-03T22:34:27
2020-02-03T22:34:27
216,910,855
0
0
null
null
null
null
UTF-8
C++
false
false
1,587
cc
punch2.cc
#include <bits/stdc++.h> void testcase(){ int n, k; std::cin >> n >> k; std::vector<int> prices(n), volumes(n); for(int i=0; i<n; i++) std::cin >> prices[i] >> volumes[i]; std::vector<std::vector<int>> mem_table(k+1, std::vector<int>(n, 0)); std::vector<std::vector<int>> na(k+1, std::vector<int>(n, 0)); // set the base cases of the table for(int i=0; i<k+1; i++){ mem_table[i][0] = ceil((double)i / volumes[0]) * prices[0]; na[i][0] = 1; } for(int i=1; i<k+1; i++){ for(int j=1; j<n; j++){ // special case: force to use the jth alcohol int price_with = 0; int best_price = 0; int n_with = 0, n_without = 0; int best_drinks = 0; if(i <= volumes[j]){ price_with = mem_table[i][j] = prices[j]; n_with = 1; }else{ price_with = prices[j] + mem_table[i-volumes[j]][j]; n_with = na[i-volumes[j]][j]; if(price_with == prices[j] + mem_table[i-volumes[j]][j-1]){ n_with = std::max(n_with, 1+na[i-volumes[j]][j-1]); } } int price_without = mem_table[i][j-1]; n_without = na[i][j-1]; if(price_with < price_without){ best_price = price_with; best_drinks = n_with; }else if(price_with == price_without){ best_price = price_with; best_drinks = std::max(n_with, n_without); }else{ best_price = price_without; best_drinks = n_without; } mem_table[i][j] = best_price; na[i][j] = best_drinks; } } std::cout << mem_table[k][n-1] << " " << na[k][n-1] << "\n"; } int main(){ std::ios_base::sync_with_stdio(false); int T; std::cin >> T; while(T--) testcase(); return 0; }
dd0667a157a310d47ad4709d502eabcde7c63f6a
14bf8412b344fca2611eddcb5a8240b1166d5687
/main/main.cpp
bd886cdb369b57169c693eb0f2b670a645eea434
[ "MIT" ]
permissive
am1ko/nes
57a5edfc15b68a23f3fb86f6aa3f7ce9847db334
4c1addaa6331733ccde90a3d9a0eed74968e859e
refs/heads/master
2018-09-23T06:44:04.717027
2018-06-28T18:08:43
2018-06-28T18:08:43
104,556,373
0
0
null
null
null
null
UTF-8
C++
false
false
7,225
cpp
main.cpp
#include <array> #include <cassert> #include <iostream> #include <iomanip> #include <boost/format.hpp> #include "ram.h" #include "rom.h" #include "ines_parser_ifstream.h" #include "io_registers.h" #include "bus.h" #include "cpu.h" #include "ppu.h" #include "emu.h" #include "bus_ppu.h" #include "renderer.h" #include "SDL2/SDL.h" #undef main // deal with #define main SDL_main from within SDL.h static unsigned ppu_cycles; // ---------------------------------------------------------------------------------------------- // constexpr std::array<std::array<uint8_t, 3>, 64> rgb_palette = {{ {{ 84, 84, 84}}, {{ 0, 30, 116}}, {{ 8, 16, 144}}, {{ 48, 0, 136}}, {{ 68, 0, 100}}, {{ 92, 0, 48}}, {{ 84, 4, 0}}, {{ 60, 24, 0}}, {{ 32, 42, 0}}, {{ 8, 58, 0}}, {{ 0, 64, 0}}, {{ 0, 60, 0}}, {{ 0, 50, 60}}, {{ 0, 0, 0}}, {{ 0, 0, 0}}, {{ 0, 0, 0}}, {{152, 150, 152}}, {{ 8, 76, 196}}, {{ 48, 50, 236}}, {{ 92, 30, 228}}, {{136, 20, 176}}, {{160, 20, 100}}, {{152, 34, 32}}, {{120, 60, 0}}, {{ 84, 90, 0}}, {{ 40, 114, 0}}, {{ 8, 124, 0}}, {{ 0, 118, 40}}, {{ 0, 102, 120}}, {{ 0, 0, 0}}, {{ 0, 0, 0}}, {{ 0, 0, 0}}, {{236, 238, 236}}, {{ 76, 154, 236}}, {{120, 124, 236}}, {{176, 98, 236}}, {{228, 84, 236}}, {{236, 88, 180}}, {{236, 106, 100}}, {{212, 136, 32}}, {{160, 170, 0}}, {{116, 196, 0}}, {{ 76, 208, 32}}, {{ 56, 204, 108}}, {{ 56, 180, 204}}, {{ 60, 60, 60}}, {{ 0, 0, 0}}, {{ 0, 0, 0}}, {{236, 238, 236}}, {{168, 204, 236}}, {{188, 188, 236}}, {{212, 178, 236}}, {{236, 174, 236}}, {{236, 174, 212}}, {{236, 180, 176}}, {{228, 196, 144}}, {{204, 210, 120}}, {{180, 222, 120}}, {{168, 226, 144}}, {{152, 226, 180}}, {{160, 214, 228}}, {{160, 162, 160}}, {{ 0, 0, 0}}, {{ 0, 0, 0}} }}; // ---------------------------------------------------------------------------------------------- // struct NES_SDL_Renderer : public Renderer { SDL_Surface * sdl_surface; SDL_Window * sdl_window; NES_SDL_Renderer(SDL_Window * window) : sdl_window(window) { sdl_surface = SDL_GetWindowSurface(window); } // ------------------------------------------------------------------------------------------ // void prepare() { SDL_Rect rect; rect.x = rect.y = 0; rect.w = 256; rect.h = 240; SDL_FillRect(sdl_surface, &rect, 0xFF000000U); } // ------------------------------------------------------------------------------------------ // void draw_pixel(uint16_t x, uint16_t y, uint8_t color) { ((uint32_t*)sdl_surface->pixels)[(y*256 + x)] = rgb_palette[color][0] << 16 | rgb_palette[color][1] << 8 | rgb_palette[color][2]; } // ------------------------------------------------------------------------------------------ // void flush() { SDL_UpdateWindowSurface(sdl_window); } }; // ---------------------------------------------------------------------------------------------- // class StdOutLogger : public ICpuLogger { public: void log(uint8_t const * instr, uint8_t bytes, uint16_t instr_addr, uint8_t cycles, struct CpuContext const * const context); }; // ---------------------------------------------------------------------------------------------- // void StdOutLogger::log(uint8_t const * instr, uint8_t bytes, uint16_t instr_addr, uint8_t cycles, struct CpuContext const * const context) { std::cout << boost::format("%04X ") % instr_addr; for (int i = 0; i < 3; i++) { if (bytes > i) { std::cout << boost::format("%02X ") % static_cast<int>(instr[i]); } else { std::cout << " "; } } // TODO(amiko): disassembly std::cout << boost::format("%-20s") % ""; std::cout << boost::format("A:%02X X:%02X Y:%02X P:%02X SP:%02X CYC:%3u \n") % static_cast<int>(context->sregs[A]) % static_cast<int>(context->sregs[X]) % static_cast<int>(context->sregs[Y]) % static_cast<int>(context->P) % static_cast<int>(context->SP) % (ppu_cycles); } static constexpr std::size_t CPU_RAM_SIZE = (2*1024); static constexpr std::size_t PPU_RAM_SIZE = (2*1024); static constexpr std::size_t OAM_SIZE = (256); static constexpr std::size_t PAL_RAM_SIZE = 32; static std::array<uint8_t, CPU_RAM_SIZE> cpu_ram_storage; static std::array<uint8_t, PPU_RAM_SIZE> ppu_ram_storage; static std::array<uint8_t, PAL_RAM_SIZE> pal_ram_storage; static std::array<uint8_t, CHR_ROM_SIZE> chr_rom_storage; static std::array<uint8_t, PRG_ROM_SIZE> prg_rom_storage_lower; static std::array<uint8_t, PRG_ROM_SIZE> prg_rom_storage_upper; static std::array<uint8_t, OAM_SIZE> oam_storage; // ---------------------------------------------------------------------------------------------- // int main(int argc, char **argv) { SDL_Init(SDL_INIT_VIDEO); SDL_Window * window = SDL_CreateWindow("YANES", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 256, 240, 0); // ------------------------------------------------------------------------------------------ // assert(argc == 2); std::string file = std::string(argv[1]); StdOutLogger logger; ROM <PRG_ROM_SIZE> prg_rom_lower(prg_rom_storage_lower); ROM <PRG_ROM_SIZE> prg_rom_upper(prg_rom_storage_upper); ROM <CHR_ROM_SIZE> chr_rom(chr_rom_storage); RAM <CPU_RAM_SIZE> cpu_ram(cpu_ram_storage); RAM <PPU_RAM_SIZE> ppu_ram(ppu_ram_storage); RAM <PAL_RAM_SIZE> pal_ram(pal_ram_storage); RAM <OAM_SIZE> oam(oam_storage); { INES_parser_ifstream ines_parser(file); assert(ines_parser.num_prg_rom_banks < 3); assert(ines_parser.num_chr_rom_banks == 1); ines_parser.write_chr_rom(0U, chr_rom_storage); ines_parser.write_prg_rom(0U, prg_rom_storage_lower); if (ines_parser.num_prg_rom_banks == 2) { ines_parser.write_prg_rom(1U, prg_rom_storage_upper); } else { ines_parser.write_prg_rom(0U, prg_rom_storage_upper); } } NES_SDL_Renderer renderer(window); IO_Registers io_registers; BusPpu ppu_bus(ppu_ram, pal_ram, chr_rom); Ppu ppu(ppu_bus, oam, renderer); Bus bus(cpu_ram, prg_rom_lower, prg_rom_upper, ppu, io_registers); Cpu cpu(bus); Emu emu(cpu, ppu); // cpu.set_logger(&logger); emu.reset(); // ------------------------------------------------------------------------------------------ // bool quit = false; while (!quit) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = true; break; } } unsigned ret; while(1) { ret = emu.tick(); unsigned ppu_cycles_old = ppu_cycles; ppu_cycles = (ppu_cycles + ret*3U) % 341U; if (ppu_cycles < ppu_cycles_old) break;; } if (ret == 0) { std::cout << "Unknown instruction" << std::endl; break; } } SDL_DestroyWindow(window); SDL_Quit(); return 0; }
6c1fbaa2c8d78a9180e71312937c319af747724e
e7538e19b16768c34f0c7321a6fb969cbadd22a5
/include/Screens/LevelScreen.h
c351c4ce411281a6fefc4d25c0a64154987e379f
[]
no_license
MORTAL2000/Cendric2
725d1b94da8a61898378b633571bac787c3c7392
8b5d6528e65c69eefa0539b44d450039c3142534
refs/heads/master
2021-01-21T23:45:42.444644
2016-03-25T20:41:15
2016-03-25T20:41:15
54,257,324
0
0
null
2016-03-19T09:12:32
2016-03-19T09:12:32
null
UTF-8
C++
false
false
2,514
h
LevelScreen.h
#pragma once #include "global.h" #include "Level/Level.h" #include "Level/LevelMainCharacter.h" #include "WorldScreen.h" #include "ResourceManager.h" #include "Level/LevelMainCharacterLoader.h" #include "Level/LevelInterface.h" #include "GUI/Button.h" #include "GUI/YesOrNoForm.h" #include "GUI/ProgressLog.h" class LevelScreen : public WorldScreen { public: LevelScreen(const std::string& levelID, CharacterCore* core); // called by the loading screen void load(); void execUpdate(const sf::Time& frameTime) override; void render(sf::RenderTarget& renderTarget) override; void execOnEnter(const Screen* previousScreen) override; void execOnExit(const Screen* nextScreen) override; void addSpellBuffToInterface(const sf::IntRect& textureLocation, const sf::Time& duration, Spell* spell, const AttributeData& attr); void addFoodBuffToInterface(const sf::IntRect& textureLocation, const sf::Time& duration, const std::string& itemID, const AttributeData& attr); void addDotBuffToInterface(const sf::IntRect& textureLocation, const sf::Time& duration, const DamageOverTimeData& data); void removeTypedBuffs(SpellID id); // called by the loading screen. the dynamic tiles & light in level void loadForRenderTexture(); // the level screen doesn't return the original core here, but a mere copy. CharacterCore* getCharacterCore() const override; // the level screen does not use the original core, but runs on a copy. // to update the original core, call this method. (used by the checkpoints and when leaving the world) void writeToCore(); bool exitWorld() override; LevelMainCharacter* getMainCharacter() const override; const Level* getWorld() const override; private: Level m_currentLevel; sf::Music m_backgroundMusic; LevelMainCharacter* m_mainChar = nullptr; std::string m_levelID; bool m_isGameOver = false; BitmapText* m_overlayText = nullptr; sf::Sprite* m_overlaySprite = nullptr; YesOrNoForm* m_yesOrNoForm = nullptr; Button* m_retryButton = nullptr; Button* m_backToMenuButton = nullptr; void handleGameOver(const sf::Time& frameTime); // pretty little agents to give to our yes or no form and buttons void onNo(); void onYesToCheckpoint(); void onYesToMenu(); void onBackToCheckpoint(); void onBackToMenu(); void onRetry(); // the level screen runs on a copy of the character core that only gets written back to the original core // if a checkpoint is reached or the level is finished. CharacterCore* m_characterCoreCopy = nullptr; void cleanUp(); };
32b42d53384d005d5092a7182f1b5f4e27282056
c3ba02d86f982ef237876c487f64002246a05eb7
/src/qchem/libqchem.cpp
32f1558b5f3e5fc5db5648e268e7b43a56121ff6
[]
no_license
scottmcguire/libra-code
69fc5f2a9bc865378c92af4ab0fe984017a5697c
5621ce1d5c569593714b2dbd854fc0ddcc4f44ad
refs/heads/master
2020-07-06T05:08:43.023198
2016-11-08T13:42:22
2016-11-08T13:42:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,458
cpp
libqchem.cpp
/********************************************************************************* * Copyright (C) 2015 Alexey V. Akimov * * This file is distributed under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 2 of * the License, or (at your option) any later version. * See the file LICENSE in the root directory of this distribution * or <http://www.gnu.org/licenses/>. * *********************************************************************************/ /** \file libqchem.cpp \brief The file implements Python export function */ #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include "libqchem.h" using namespace boost::python; /// libqchem namespace namespace libqchem{ using namespace libmolint; using namespace libqobjects; using namespace libbasis; void export_Qchem_objects(){ /** \brief Exporter of libqchem classes and functions */ export_molint_objects(); export_qobjects_objects(); export_basis_objects(); }// export_Qchem_objects() #ifdef CYGWIN BOOST_PYTHON_MODULE(cygqchem){ #else BOOST_PYTHON_MODULE(libqchem){ #endif // Register converters: // See here: https://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/ //to_python_converter<std::vector<DATA>, VecToList<DATA> >(); export_Qchem_objects(); } }// libqchem
f07f6b40daa79be9dc456be215c358b8a404b7cc
a2c29e0df5af75554e2f86c5c023d48b0d0a773c
/0013.罗马数字转成整数.cpp
07109a540348a78bc844bcf74e73343889064791
[]
no_license
havoc-sheep/LeetCode
8e82e302ae4cef271da71ea0151a323e54f19132
d8f3f74a8a2a87a2e5ac2efc6d2a6d61efdebd29
refs/heads/master
2020-05-30T13:26:19.125484
2019-06-03T16:02:30
2019-06-03T16:02:30
189,761,072
0
0
null
null
null
null
UTF-8
C++
false
false
1,613
cpp
0013.罗马数字转成整数.cpp
class Solution { public: int romanToInt(string s) { int size = s.size(); int ans = 0; for(int i = 0; i < size; i++){ //1,4,9 if(s[i] == 'I'){ if(s[i+1] == 'V' || s[i+1] == 'X') ans -= 1; else ans += 1; } //5 if(s[i] == 'V') ans += 5; //10,40,90 if(s[i] == 'X'){ if(s[i+1] == 'L' || s[i+1] == 'C') ans -= 10; else ans += 10; } //50 if(s[i] == 'L') ans += 50; if(s[i] == 'C'){ if(s[i+1] == 'D' || s[i+1] == 'M') ans -= 100; else ans += 100; } if(s[i] == 'D') ans += 500; if(s[i] == 'M') ans += 1000; } return ans; } /* //巨慢 int result = 0; map<char, int> roman_num_map; roman_num_map['I'] = 1; roman_num_map['V'] = 5; roman_num_map['X'] = 10; roman_num_map['L'] = 50; roman_num_map['C'] = 100; roman_num_map['D'] = 500; roman_num_map['M'] = 1000; int size = s.size(); for(int i = 0; i < size; ++i) { //小的数字位于大的数字左边 if(roman_num_map[s[i]] < roman_num_map[s[i + 1]]) { result -= roman_num_map[s[i]]; } else { result += roman_num_map[s[i]]; } } return result; }*/ };
0acb7b47331ea5e7dc876a5403c58b63688805af
303b48eb9354338542e0a4ca68df1978dd8d038b
/include/fox/FXQuat.h
a91e6c376cbf520071a0021710e22c37192bb3b5
[ "BSD-3-Clause" ]
permissive
ldematte/beppe
fa98a212bbe4a27c5d63defaf386898a48d72deb
53369e0635d37d2dc58aa0b6317e664b3cf67547
refs/heads/master
2020-06-04T00:05:39.688233
2013-01-06T16:37:03
2013-01-06T16:37:03
7,469,184
1
0
null
null
null
null
UTF-8
C++
false
false
3,236
h
FXQuat.h
/******************************************************************************** * * * Q u a t e r n i o n F u n c t i o n s * * * ********************************************************************************* * Copyright (C) 1994,2002 by Jeroen van der Zijp. All Rights Reserved. * ********************************************************************************* * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * ********************************************************************************* * $Id: FXQuat.h,v 1.11 2002/01/18 22:55:03 jeroen Exp $ * ********************************************************************************/ #ifndef FXQUAT_H #define FXQUAT_H /// Quaternion (single-precision version) class FXAPI FXQuat : public FXHVec { public: /// Constructors FXQuat(){} /// Construct from axis and angle FXQuat(const FXVec& axis,FXfloat phi=0.0); /// Construct from euler angles yaw (z), pitch (y), and roll (x) FXQuat(FXfloat roll,FXfloat pitch,FXfloat yaw); /// Construct from components FXQuat(FXfloat x,FXfloat y,FXfloat z,FXfloat w):FXHVec(x,y,z,w){} /// Adjust quaternion length FXQuat& adjust(); /// Set quaternion from yaw (z), pitch (y), and roll (x) void setRollPitchYaw(FXfloat roll,FXfloat pitch,FXfloat yaw); /// Obtain yaw, pitch, and roll void getRollPitchYaw(FXfloat& roll,FXfloat& pitch,FXfloat& yaw); /// Exponentiate quaternion friend FXAPI FXQuat exp(const FXQuat& q); /// Take logarithm of quaternion friend FXAPI FXQuat log(const FXQuat& q); /// Invert quaternion friend FXAPI FXQuat invert(const FXQuat& q); /// Conjugate quaternion friend FXAPI FXQuat conj(const FXQuat& q); /// Multiply quaternions friend FXAPI FXQuat operator*(const FXQuat& p,const FXQuat& q); /// Construct quaternion from arc a->b on unit sphere friend FXAPI FXQuat arc(const FXVec& a,const FXVec& b); /// Spherical lerp friend FXAPI FXQuat lerp(const FXQuat& u,const FXQuat& v,FXfloat f); }; #endif
1d4f764ea64788e4512fb1bc23ef0ffd3aaf88e6
a5da02227cbbc30effaf43d52bdca26223daf98e
/Codeforces/462/C.cpp
ba87ef6272f538e0423385db23449f5b489b6306
[ "MIT" ]
permissive
zzh8829/CompetitiveProgramming
853edabdfc728504abaa27333bd4900a7f97c8c9
36f36b10269b4648ca8be0b08c2c49e96abede25
refs/heads/master
2021-01-01T15:41:08.984386
2018-03-25T17:32:39
2018-03-25T17:32:39
35,587,680
1
0
null
null
null
null
UTF-8
C++
false
false
605
cpp
C.cpp
#include <algorithm> #include <iostream> #include <fstream> #include <cstdlib> #include <cstring> #include <cstdio> #include <string> #include <vector> #include <cmath> #include <queue> #include <map> #include <set> using namespace std; typedef long long LL; LL tot; LL cur; int n; LL num[300001]; /* 1 3 5 6 1 | 3 5 6 3 | 5 6 5 | 6 */ int main() { cin >> n; for(int i=0;i!=n;i++) { cin >> num[i]; cur += num[i]; } sort(num,num+n); tot += cur; for(int i=0;i!=n-1;i++) { tot += cur; cur -= num[i]; } cout << tot << endl; return 0; }
554f6f40fe809f1485adfa35422d8ab8da43e0c8
83b010956550bceb6f2bd3ea3717729994da6c3a
/EsSystem/EEsystemAppConfig.cpp
df46c3d3dad617fbd1e24b40a927817c53be0cac
[ "MIT" ]
permissive
bvchirkov/OpenMovingHumanFlow
ec32bc50246f778877d24d24320b7597be17e12e
5ebb0db03d0cf75902eee19a70d407ca346bd9d5
refs/heads/master
2023-03-06T03:47:27.017292
2021-02-10T08:03:33
2021-02-10T08:03:33
322,227,167
0
0
null
null
null
null
UTF-8
C++
false
false
540
cpp
EEsystemAppConfig.cpp
#include "EEsystemAppConfig.hpp" GP_IMPL_REFLECTABLE(EEsystemAppConfig, "d3ed9a2e-d681-4721-b54b-92a8983d9a4b"_sv, GpReflectInheritanceState::HERITABLE, 1); EEsystemAppConfig::EEsystemAppConfig (void) { } EEsystemAppConfig::~EEsystemAppConfig (void) { } void EEsystemAppConfig::SRegisterProps(GpReflectRegPropsCtx &aCtx) { GP_WARNING_PUSH() GP_WARNING_DISABLE(invalid-offsetof) GP_WARNING_POP() } void EEsystemAppConfig::SRegisterMeta (GpReflectRegMetaCtx& /*aCtx*/) { }
ad0ad9853f44de91e3f60d83784a5ea164ed9f5a
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/10_3825_66.cpp
2230af59ae5172bb1154a3272c03704cac3f75a7
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
434
cpp
10_3825_66.cpp
#include <stdio.h> #include <math.h> int main() { int p,i,n,k,T; freopen("1.in","r",stdin); freopen("1.out","w",stdout); scanf("%d",&T); for(i=1;i<=T;i++) { scanf("%d%d",&n,&k); p = (int)pow(2.0,(double)n); if(k==p-1 || (k-p+1)%p==0) { printf("Case #%d: ON\n",i); } else printf("Case #%d: OFF\n",i); } return 0; }
043b9ec63769ea9611ad2fbe6e0eaecc436dca47
48102b2556a4e17997416770451a4fefe2b7100d
/src/decoder.hpp
1378279d9c1c6f0ce2bcc2ad9414067d297ffdbe
[ "Apache-2.0" ]
permissive
ignatenkobrain/libprocess
685354f8d97cb0f4736b99b2c608155352fe9625
d283d260937c8e7fc3a5fb4ffdbdef9f21688a50
refs/heads/master
2021-01-18T05:46:08.883178
2013-10-01T20:54:58
2013-10-01T20:54:58
11,611,009
1
1
null
null
null
null
UTF-8
C++
false
false
11,593
hpp
decoder.hpp
#ifndef __DECODER_HPP__ #define __DECODER_HPP__ #include <http_parser.h> #include <deque> #include <string> #include <vector> #include <libprocess/http.hpp> #include <libprocess/socket.hpp> #include <stout/foreach.hpp> #include <stout/gzip.hpp> #include <stout/try.hpp> // TODO(bmahler): Upgrade our http_parser to the latest version. namespace process { // TODO: Make DataDecoder abstract and make RequestDecoder a concrete subclass. class DataDecoder { public: DataDecoder(const Socket& _s) : s(_s), failure(false), request(NULL) { settings.on_message_begin = &DataDecoder::on_message_begin; settings.on_header_field = &DataDecoder::on_header_field; settings.on_header_value = &DataDecoder::on_header_value; settings.on_url = &DataDecoder::on_url; settings.on_body = &DataDecoder::on_body; settings.on_headers_complete = &DataDecoder::on_headers_complete; settings.on_message_complete = &DataDecoder::on_message_complete; #if !(HTTP_PARSER_VERSION_MAJOR >=2) settings.on_path = &DataDecoder::on_path; settings.on_fragment = &DataDecoder::on_fragment; settings.on_query_string = &DataDecoder::on_query_string; #endif http_parser_init(&parser, HTTP_REQUEST); parser.data = this; } std::deque<http::Request*> decode(const char* data, size_t length) { size_t parsed = http_parser_execute(&parser, &settings, data, length); if (parsed != length) { failure = true; } if (!requests.empty()) { std::deque<http::Request*> result = requests; requests.clear(); return result; } return std::deque<http::Request*>(); } bool failed() const { return failure; } Socket socket() const { return s; } private: static int on_message_begin(http_parser* p) { DataDecoder* decoder = (DataDecoder*) p->data; assert(!decoder->failure); decoder->header = HEADER_FIELD; decoder->field.clear(); decoder->value.clear(); decoder->query.clear(); assert(decoder->request == NULL); decoder->request = new http::Request(); decoder->request->headers.clear(); decoder->request->method.clear(); decoder->request->path.clear(); decoder->request->url.clear(); decoder->request->fragment.clear(); decoder->request->query.clear(); decoder->request->body.clear(); return 0; } static int on_headers_complete(http_parser* p) { DataDecoder* decoder = (DataDecoder*) p->data; // Add final header. decoder->request->headers[decoder->field] = decoder->value; decoder->field.clear(); decoder->value.clear(); decoder->request->method = http_method_str((http_method) decoder->parser.method); decoder->request->keepAlive = http_should_keep_alive(&decoder->parser); return 0; } static int on_message_complete(http_parser* p) { DataDecoder* decoder = (DataDecoder*) p->data; // std::cout << "http::Request:" << std::endl; // std::cout << " method: " << decoder->request->method << std::endl; // std::cout << " path: " << decoder->request->path << std::endl; // Parse the query key/values. Try<std::string> decoded = http::decode(decoder->query); if (decoded.isError()) { return 1; } decoder->request->query = http::query::parse(decoded.get()); Option<std::string> encoding = decoder->request->headers.get("Content-Encoding"); if (encoding.isSome() && encoding.get() == "gzip") { Try<std::string> decompressed = gzip::decompress(decoder->request->body); if (decompressed.isError()) { return 1; } decoder->request->body = decompressed.get(); decoder->request->headers["Content-Length"] = decoder->request->body.length(); } decoder->requests.push_back(decoder->request); decoder->request = NULL; return 0; } static int on_header_field(http_parser* p, const char* data, size_t length) { DataDecoder* decoder = (DataDecoder*) p->data; assert(decoder->request != NULL); if (decoder->header != HEADER_FIELD) { decoder->request->headers[decoder->field] = decoder->value; decoder->field.clear(); decoder->value.clear(); } decoder->field.append(data, length); decoder->header = HEADER_FIELD; return 0; } static int on_header_value(http_parser* p, const char* data, size_t length) { DataDecoder* decoder = (DataDecoder*) p->data; assert(decoder->request != NULL); decoder->value.append(data, length); decoder->header = HEADER_VALUE; return 0; } static int on_url(http_parser* p, const char* data, size_t length) { DataDecoder* decoder = (DataDecoder*) p->data; assert(decoder->request != NULL); decoder->request->url.append(data, length); int ret = 0; #if (HTTP_PARSER_VERSION_MAJOR >=2) // reworked parsing for version 2.0 &> http_parser_url tUrlData; ret = http_parser_parse_url(data, length, 0, &tUrlData); if (tUrlData.field_set & (1<<UF_PATH)) decoder->request->path.append(data+tUrlData.field_data[UF_PATH].off, tUrlData.field_data[UF_PATH].len); if (tUrlData.field_set & (1<<UF_FRAGMENT)) decoder->request->fragment.append(data+tUrlData.field_data[UF_FRAGMENT].off, tUrlData.field_data[UF_FRAGMENT].len); if (tUrlData.field_set & (1<<UF_QUERY)) decoder->query.append(data+tUrlData.field_data[UF_QUERY].off, tUrlData.field_data[UF_QUERY].len); #endif return ret; } #if !(HTTP_PARSER_VERSION_MAJOR >=2) static int on_path(http_parser* p, const char* data, size_t length) { DataDecoder* decoder = (DataDecoder*) p->data; assert(decoder->request != NULL); decoder->request->path.append(data, length); return 0; } static int on_query_string(http_parser* p, const char* data, size_t length) { DataDecoder* decoder = (DataDecoder*) p->data; assert(decoder->request != NULL); decoder->query.append(data, length); return 0; } static int on_fragment(http_parser* p, const char* data, size_t length) { DataDecoder* decoder = (DataDecoder*) p->data; assert(decoder->request != NULL); decoder->request->fragment.append(data, length); return 0; } #endif static int on_body(http_parser* p, const char* data, size_t length) { DataDecoder* decoder = (DataDecoder*) p->data; assert(decoder->request != NULL); decoder->request->body.append(data, length); return 0; } const Socket s; // The socket this decoder is associated with. bool failure; http_parser parser; http_parser_settings settings; enum { HEADER_FIELD, HEADER_VALUE } header; std::string field; std::string value; std::string query; http::Request* request; std::deque<http::Request*> requests; }; class ResponseDecoder { public: ResponseDecoder() : failure(false), header(HEADER_FIELD), response(NULL) { settings.on_message_begin = &ResponseDecoder::on_message_begin; settings.on_header_field = &ResponseDecoder::on_header_field; settings.on_header_value = &ResponseDecoder::on_header_value; settings.on_url = &ResponseDecoder::on_url; settings.on_body = &ResponseDecoder::on_body; settings.on_headers_complete = &ResponseDecoder::on_headers_complete; settings.on_message_complete = &ResponseDecoder::on_message_complete; #if !(HTTP_PARSER_VERSION_MAJOR >=2) settings.on_path = &ResponseDecoder::on_path; settings.on_fragment = &ResponseDecoder::on_fragment; settings.on_query_string = &ResponseDecoder::on_query_string; #endif http_parser_init(&parser, HTTP_RESPONSE); parser.data = this; } std::deque<http::Response*> decode(const char* data, size_t length) { size_t parsed = http_parser_execute(&parser, &settings, data, length); if (parsed != length) { failure = true; } if (!responses.empty()) { std::deque<http::Response*> result = responses; responses.clear(); return result; } return std::deque<http::Response*>(); } bool failed() const { return failure; } private: static int on_message_begin(http_parser* p) { ResponseDecoder* decoder = (ResponseDecoder*) p->data; assert(!decoder->failure); decoder->header = HEADER_FIELD; decoder->field.clear(); decoder->value.clear(); assert(decoder->response == NULL); decoder->response = new http::Response(); decoder->response->status.clear(); decoder->response->headers.clear(); decoder->response->type = http::Response::BODY; decoder->response->body.clear(); decoder->response->path.clear(); return 0; } static int on_headers_complete(http_parser* p) { ResponseDecoder* decoder = (ResponseDecoder*) p->data; // Add final header. decoder->response->headers[decoder->field] = decoder->value; decoder->field.clear(); decoder->value.clear(); return 0; } static int on_message_complete(http_parser* p) { ResponseDecoder* decoder = (ResponseDecoder*) p->data; // Get the response status string. if (http::statuses.contains(decoder->parser.status_code)) { decoder->response->status = http::statuses[decoder->parser.status_code]; } else { decoder->failure = true; return 1; } // We can only provide the gzip encoding. Option<std::string> encoding = decoder->response->headers.get("Content-Encoding"); if (encoding.isSome() && encoding.get() == "gzip") { Try<std::string> decompressed = gzip::decompress(decoder->response->body); if (decompressed.isError()) { decoder->failure = true; return 1; } decoder->response->body = decompressed.get(); decoder->response->headers["Content-Length"] = decoder->response->body.length(); } decoder->responses.push_back(decoder->response); decoder->response = NULL; return 0; } static int on_header_field(http_parser* p, const char* data, size_t length) { ResponseDecoder* decoder = (ResponseDecoder*) p->data; assert(decoder->response != NULL); if (decoder->header != HEADER_FIELD) { decoder->response->headers[decoder->field] = decoder->value; decoder->field.clear(); decoder->value.clear(); } decoder->field.append(data, length); decoder->header = HEADER_FIELD; return 0; } static int on_header_value(http_parser* p, const char* data, size_t length) { ResponseDecoder* decoder = (ResponseDecoder*) p->data; assert(decoder->response != NULL); decoder->value.append(data, length); decoder->header = HEADER_VALUE; return 0; } static int on_path(http_parser* p, const char* data, size_t length) { return 0; } static int on_url(http_parser* p, const char* data, size_t length) { return 0; } static int on_query_string(http_parser* p, const char* data, size_t length) { return 0; } static int on_fragment(http_parser* p, const char* data, size_t length) { return 0; } static int on_body(http_parser* p, const char* data, size_t length) { ResponseDecoder* decoder = (ResponseDecoder*) p->data; assert(decoder->response != NULL); decoder->response->body.append(data, length); return 0; } bool failure; http_parser parser; http_parser_settings settings; enum { HEADER_FIELD, HEADER_VALUE } header; std::string field; std::string value; http::Response* response; std::deque<http::Response*> responses; }; } // namespace process { #endif // __DECODER_HPP__
79d47f8d5d84770f85ad8472e56fc05931ec5295
b8ce08a0032f467a2d14d3ee3105c1a6418e1f0c
/src/python/PyImath/PyImathColor.h
767b9b1ea35bd7026eb8e4c0d72eed9d0c344992
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
AcademySoftwareFoundation/Imath
a78c4ba015c0a465c1e35291094a78f59688a8a9
4d4e01c8c9fb9b9dbbefa2e135b21778c9cd331e
refs/heads/main
2023-08-31T05:09:54.756260
2023-08-13T23:40:57
2023-08-13T23:40:57
271,841,243
300
96
BSD-3-Clause
2023-09-09T04:51:00
2020-06-12T16:18:26
C++
UTF-8
C++
false
false
7,499
h
PyImathColor.h
// // SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenEXR Project. // // clang-format off #ifndef _PyImathColor3_h_ #define _PyImathColor3_h_ #include <Python.h> #define BOOST_BIND_GLOBAL_PLACEHOLDERS #include <boost/python.hpp> #include <ImathColor.h> #include "PyImath.h" namespace PyImath { template <class T> boost::python::class_<IMATH_NAMESPACE::Color4<T> > register_Color4(); template <class T> boost::python::class_<PyImath::FixedArray2D<IMATH_NAMESPACE::Color4<T> > > register_Color4Array2D(); template <class T> boost::python::class_<PyImath::FixedArray<IMATH_NAMESPACE::Color4<T> > > register_Color4Array(); template <class T> boost::python::class_<IMATH_NAMESPACE::Color3<T>, boost::python::bases<IMATH_NAMESPACE::Vec3<T> > > register_Color3(); template <class T> boost::python::class_<PyImath::FixedArray<IMATH_NAMESPACE::Color3<T> > > register_Color3Array(); typedef FixedArray2D<IMATH_NAMESPACE::Color4f> Color4fArray; typedef FixedArray2D<IMATH_NAMESPACE::Color4c> Color4cArray; typedef FixedArray<IMATH_NAMESPACE::Color4f> C4fArray; typedef FixedArray<IMATH_NAMESPACE::Color4c> C4cArray; typedef FixedArray<IMATH_NAMESPACE::Color3f> C3fArray; typedef FixedArray<IMATH_NAMESPACE::Color3c> C3cArray; // // Other code in the Zeno code base assumes the existance of a class with the // same name as the Imath class, and with static functions wrap() and // convert() to produce a PyImath object from an Imath object and vice-versa, // respectively. The class Boost generates from the Imath class does not // have these properties, so we define a companion class here. // The template argument, T, is the element type for the color in C++ (e.g., char, // float). The other argument, U, is how this type is represented in Python // (e.g., int, float). template <class T, class U> class C3 { public: static PyObject * wrap (const IMATH_NAMESPACE::Color3<T> &c); static int convert (PyObject *p, IMATH_NAMESPACE::Color3<T> *v); }; template <class T, class U> class C4 { public: static PyObject * wrap (const IMATH_NAMESPACE::Color4<T> &c); static int convert (PyObject *p, IMATH_NAMESPACE::Color4<T> *v); }; template <class T, class U> PyObject * C3<T, U>::wrap (const IMATH_NAMESPACE::Color3<T> &c) { typename boost::python::return_by_value::apply < IMATH_NAMESPACE::Color3<T> >::type converter; PyObject *p = converter (c); return p; } template <class T, class U> PyObject * C4<T, U>::wrap (const IMATH_NAMESPACE::Color4<T> &c) { typename boost::python::return_by_value::apply < IMATH_NAMESPACE::Color4<T> >::type converter; PyObject *p = converter (c); return p; } template <class T, class U> int C3<T, U>::convert (PyObject *p, IMATH_NAMESPACE::Color3<T> *v) { boost::python::extract <IMATH_NAMESPACE::C3c> extractorC3c (p); if (extractorC3c.check()) { IMATH_NAMESPACE::C3c c3c = extractorC3c(); v->setValue (U(c3c[0]), U(c3c[1]), U(c3c[2])); return 1; } boost::python::extract <IMATH_NAMESPACE::C3f> extractorC3f (p); if (extractorC3f.check()) { IMATH_NAMESPACE::C3f c3f = extractorC3f(); v->setValue (U(c3f[0]), U(c3f[1]), U(c3f[2])); return 1; } boost::python::extract <boost::python::tuple> extractorTuple (p); if (extractorTuple.check()) { boost::python::tuple t = extractorTuple(); if (t.attr ("__len__") () == 3) { double a = boost::python::extract <double> (t[0]); double b = boost::python::extract <double> (t[1]); double c = boost::python::extract <double> (t[2]); v->setValue (U(a), U(b), U(c)); return 1; } } boost::python::extract <boost::python::list> extractorList (p); if (extractorList.check()) { boost::python::list l = extractorList(); if (l.attr ("__len__") () == 3) { boost::python::extract <double> extractor0 (l[0]); boost::python::extract <double> extractor1 (l[1]); boost::python::extract <double> extractor2 (l[2]); if (extractor0.check() && extractor1.check() && extractor2.check()) { v->setValue (U(extractor0()), U(extractor1()), U(extractor2())); return 1; } } } boost::python::extract <IMATH_NAMESPACE::V3i> extractorV3i (p); if (extractorV3i.check()) { IMATH_NAMESPACE::V3i v3i = extractorV3i(); v->setValue (U(v3i[0]), U(v3i[1]), U(v3i[2])); return 1; } boost::python::extract <IMATH_NAMESPACE::V3f> extractorV3f (p); if (extractorV3f.check()) { IMATH_NAMESPACE::V3f v3f = extractorV3f(); v->setValue (U(v3f[0]), U(v3f[1]), U(v3f[2])); return 1; } boost::python::extract <IMATH_NAMESPACE::V3d> extractorV3d (p); if (extractorV3d.check()) { IMATH_NAMESPACE::V3d v3d = extractorV3d(); v->setValue (U(v3d[0]), U(v3d[1]), U(v3d[2])); return 1; } return 0; } template <class T, class U> int C4<T, U>::convert (PyObject *p, IMATH_NAMESPACE::Color4<T> *v) { boost::python::extract <IMATH_NAMESPACE::C4c> extractorC4c (p); if (extractorC4c.check()) { IMATH_NAMESPACE::C4c c4c = extractorC4c(); v->setValue (U(c4c[0]), U(c4c[1]), U(c4c[2]), U(c4c[3])); return 1; } boost::python::extract <IMATH_NAMESPACE::C4f> extractorC4f (p); if (extractorC4f.check()) { IMATH_NAMESPACE::C4f c4f = extractorC4f(); v->setValue (U(c4f[0]), U(c4f[1]), U(c4f[2]), U(c4f[3])); return 1; } boost::python::extract <boost::python::tuple> extractorTuple (p); if (extractorTuple.check()) { boost::python::tuple t = extractorTuple(); if (t.attr ("__len__") () == 4) { // As with V3<T>, we extract the tuple elements as doubles and // cast them to Ts in setValue(), to avoid any odd cases where // extracting them as Ts from the start would fail. double a = boost::python::extract <double> (t[0]); double b = boost::python::extract <double> (t[1]); double c = boost::python::extract <double> (t[2]); double d = boost::python::extract <double> (t[3]); v->setValue (U(a), U(b), U(c), U(d)); return 1; } } boost::python::extract <boost::python::list> extractorList (p); if (extractorList.check()) { boost::python::list l = extractorList(); if (l.attr ("__len__") () == 4) { boost::python::extract <double> extractor0 (l[0]); boost::python::extract <double> extractor1 (l[1]); boost::python::extract <double> extractor2 (l[2]); boost::python::extract <double> extractor3 (l[3]); if (extractor0.check() && extractor1.check() && extractor2.check() && extractor3.check()) { v->setValue (U(extractor0()), U(extractor1()), U(extractor2()), U(extractor3())); return 1; } } } return 0; } typedef C3<float, float> Color3f; typedef C3<unsigned char, int> Color3c; typedef Color3f C3f; typedef Color3c C3c; typedef C4<float, float> Color4f; typedef C4<unsigned char, int> Color4c; typedef Color4f C4f; typedef Color4c C4c; } #endif
12fcfd0ca41b542db51ee9a8d3a84602160761b5
37810fcdbb7c21d18d2b480535f4e067b99d0e7c
/app/main.cpp
3284af44a602e128bf0ada20a3ab2f2ff3cf6ab6
[]
no_license
mtupikov42/Computor
7a18712884c22a1f04689a8287190b421066cf8a
27c28dd4555c0cf7c06851f4546a5ad567717452
refs/heads/master
2020-07-03T02:56:36.143803
2020-05-13T15:43:16
2020-05-13T15:43:16
201,762,910
0
0
null
null
null
null
UTF-8
C++
false
false
2,554
cpp
main.cpp
#include <QSettings> #include <QDir> #include <QQuickWindow> #include <QGuiApplication> #include <QDirIterator> #include <QFontDatabase> #include <QLoggingCategory> #include <app_config.h> #include <StandardPaths.h> #include "EBST.h" #include "ExpressionException.h" #include "Core/UIManager.h" #include "Core/Logger.h" #include "Utils/MetadataInitializer.h" #include "qmlplugins/AssetsProvider.h" #include "Models/ExpressionModel.h" namespace L { Q_LOGGING_CATEGORY(init, "app.main.init", QtInfoMsg); } // end namespace L void setupApplicationInfo() { QGuiApplication::setOrganizationName(app_cfg::company_name); QGuiApplication::setApplicationDisplayName(app_cfg::application_name); QGuiApplication::setApplicationName(app_cfg::application_name); QGuiApplication::setApplicationVersion(app_cfg::version_string); } void setupAppStorages() { const auto setupDir = [](QStandardPaths::StandardLocation path, QString appendedPath = {}) { auto wpath = StandardPaths::writableLocation(path); if (!appendedPath.isEmpty()) { wpath.append(QDir::separator()) .append(appendedPath); } QDir dir(QDir::toNativeSeparators(wpath)); if (!dir.exists()) { dir.mkpath(dir.absolutePath()); } }; setupDir(QStandardPaths::AppDataLocation); setupDir(QStandardPaths::GenericDataLocation, Logger::logsDirName()); } void setupSettings() { QSettings::setDefaultFormat(QSettings::IniFormat); const auto settingsLocation = StandardPaths::writableLocation(QStandardPaths::AppDataLocation); QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settingsLocation); } void setupApplicationFonts() { QDirIterator it(":/fonts", { "*.otf", "*.ttf" }, QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); const auto fontId = QFontDatabase::addApplicationFont(it.filePath()); if (fontId < 0) { qCCritical(L::init) << "Unable to load font" << it.fileName(); } } } void setupGraphics() { #ifdef Q_OS_WIN QGuiApplication::setAttribute(Qt::AA_UseOpenGLES); #endif } int main(int argc, char** argv) { setupApplicationInfo(); setupAppStorages(); Logger logger; MetadataInitializer::registerAllMeta(); setupGraphics(); setupSettings(); auto appInstance = QGuiApplication(argc, argv); appInstance.setWindowIcon(QIcon(AssetsProvider::appIcon())); qCInfo(L::init) << QGuiApplication::applicationName() << QGuiApplication::organizationName() << QGuiApplication::applicationVersion(); setupApplicationFonts(); UIManager uiManager; uiManager.initEngine(); return appInstance.exec(); }
a7536ea0fdd09a3125c507ba5d219b646680d730
ce7011ef94e4cf393f249a54e2b7d7d39d70b577
/FunctionGraph/FunctionGraph_itog2.cpp
e65337ff2420ed0607be10bb50c5aff9727db873
[]
no_license
alanpa2020/KPK
f2762cf1ba478f46016d8af4951cc3c502eaf49b
84fff21133b21225a5fdab20b68828f3ee9ef550
refs/heads/master
2021-02-01T11:03:04.924212
2020-03-05T07:26:44
2020-03-05T07:26:44
243,521,276
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,756
cpp
FunctionGraph_itog2.cpp
#include "TXLib.h" const int Scale = 50; //прототипы void DrawGraphic(double (*func) (double x, double a, double b, double c), double a, double b, double c,COLORREF color); void DrawDecartSystem (); void Live_graphic(); double Sqr_abc (double x, double a, double b, double c); double SinX_abc (double x, double a, double b, double c); int main() { txCreateWindow (800, 600); txSetFillColor ( RGB(0, 50, 0) ); txClear(); DrawDecartSystem (); Live_graphic(); } // описание типа (не к месту) typedef unsigned long long suoerlong_t; void DrawGraphic(double (*func) (double x, double a, double b, double c), double a, double b, double c, COLORREF color ) { double x = -10; double x_old = -10, y_old = (*func) (x, a, b, c); txSetColor (color); while (x<= +10) { double y = (*func) (x, a, b, c); // можно так:double y = func (x); //txCircle (800/2 + x*Scale, 300 - y*Scale, 2); txLine (800/2 + x_old*Scale, 300 - y_old*Scale, 800/2 + x*Scale, 300 - y*Scale); x_old = x; y_old = y; x += 0.01; } } void DrawDecartSystem () { int kolX = 800 / Scale / 2; int koly = 600 / Scale / 2; txSetColor (RGB(0, 100, 0)); for (int i = 0; i<kolX; i++){ txLine (400 - i*Scale, 0, 400 - i*Scale, 600); txLine (400 + i*Scale, 0, 400 + i*Scale, 600); } for (int i = 0; i<koly; i++){ txLine (0, 300 - i*Scale, 800, 300 - i*Scale); txLine (0, 300 + i*Scale, 800, 300 + i*Scale); } txSetColor (RGB(255, 255, 255)); txLine (400, 0, 400, 600); txLine (400, 0, 405, 15); txLine (400, 0, 400-5, 15); txLine (800-15, 305, 800, 300); txLine (800-15, 300-5, 800, 300); txLine (0, 300, 800, 300); } double Sqr_abc (double x, double a, double b, double c) {return a*x*x+b*x+c;} double SinX_abc (double x, double a, double b, double c) {return a*sin (b*x+c);} void Live_graphic(){ txBegin(); int t = 0; while (true){ DrawDecartSystem (); DrawGraphic (&Sqr_abc, t%100 *0.1 - 5, 0, t%10-5, RGB (rand() % 155+100, rand() % 155+100, rand() % 155+100)); DrawGraphic (&Sqr_abc, t%100 *0.1 - 5, 0, 0, RGB (rand() % 155+100, rand() % 155+100, rand() % 155+100)); DrawGraphic (&SinX_abc, 1, 1, 0.1*t, RGB (rand() % 155+100, rand() % 155+100, rand() % 155+100)); DrawGraphic (&SinX_abc, t%50*0.1 - 2.5, 1, 1, RGB (rand() % 155+100, rand() % 155+100, rand() % 155+100)); t += 1; txSleep(75); txClear(); } return ; }
54ae086990072ab23e87def34d8bfea1aa94876c
c8e40fc06049b74d74d22cb05459d4d22dec59f8
/cpp_and_gramatics/3/main.cpp
32ac2cc340299f01b87b9c7f3c926bc72545ce5e
[]
no_license
DoubleDi/cmc-msu-tasks
d33af4209013294f2cb28fa596b4550637e30ccd
97c490283fa1fc40ce3abed9ace1cfedf8ffa671
refs/heads/master
2021-01-20T19:05:21.910671
2018-09-06T13:23:17
2018-09-06T13:23:17
61,066,958
0
0
null
null
null
null
UTF-8
C++
false
false
749
cpp
main.cpp
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> using namespace std; class Sum { double sm; public: Sum() { sm = 0; } void operator()(double n) { sm += n; } double get() { return sm; } }; int main() { vector<double> v; double tmp; while (cin >> tmp) { v.push_back(tmp); } int cnt; cnt = (int) (v.size() / 10); v.erase(v.begin(), v.begin() + cnt); v.erase(v.end() - cnt, v.end()); sort(v.begin(), v.end()); cnt = (int) (v.size() / 10); v.erase(v.begin(), v.begin() + cnt); v.erase(v.end() - cnt, v.end()); Sum s = for_each(v.begin(), v.end(), Sum()); cout << fixed << setprecision(10) << s.get() / v.size() << endl; return 0; }
ab9117975c0b3a2e8539480e10d5978be3325e95
d013cc33cd7067159d223c1eca2304f4040bc26a
/glutVS/src/Vector3.h
cd7224d76341af9369482b03a17b54e2a0453ae0
[]
no_license
rw10/cgavr
c90aa4d6e541be89dc3773283220960e9423847f
e8cc3f070765267ff148ebb0ae311283054706d4
refs/heads/master
2020-04-01T04:27:52.309186
2019-01-23T16:52:58
2019-01-23T16:52:58
152,864,765
1
0
null
null
null
null
UTF-8
C++
false
false
1,559
h
Vector3.h
#pragma once #include <GL/glut.h> class Vector3 { public: Vector3(); Vector3(double x, double y, double z); ~Vector3(); double x; double y; double z; GLfloat gl_x() const { return (GLfloat)x; } GLfloat gl_y() const { return (GLfloat)y; } GLfloat gl_z() const { return (GLfloat)z; } // compare operator bool operator< (const Vector3& other) const; bool operator!= (const Vector3& other) const; // overloaded operators Vector3 operator+ (const Vector3& other) const; Vector3 operator- (const Vector3& other) const; Vector3 operator*(const Vector3& other) const; // cross product Vector3 operator* (const double& multiplier) const; // multiplication with scalar static double dotProduct(const Vector3& u, const Vector3& v); static double calcAngleInXY(Vector3 u, Vector3 v); // not needed (yet) //static double calcAngleInXZ(Vector3 u, Vector3 v); //static double calcAngleInYZ(Vector3 u, Vector3 v); double getLength() const; double getLengthXY() const; void normalize(double targetLength = 1); static double deg2rad(double degrees); static double rad2deg(double radians); static Vector3 getRichtungsVector(const Vector3& begin, const Vector3& end); void rotateAroundX(double degrees); void rotateAroundY(double degrees); void rotateAroundZ(double degrees); double distance(const Vector3& other) const; static double distance(const Vector3& start, const Vector3& end) { start.distance(end); } // TODO: // normalize, multiplication, addition, rotation, angle calculation, intersection, ... };
069c43b839632d83bfa8e0ac2a9770292215df83
f386a4d9dea36518fb20a3d353c3548c1dc085d8
/Simulate3D/Simulate3D.cpp
ca3fdabe65ca48b1468e25ed1c9be8f0d8d0722f
[ "BSD-2-Clause" ]
permissive
fbergmann/3DSimulate
a63d7fce06b485927bfd27e0e122a0c5e861d6ef
12215ce4d29d75c1a86317100a35d7cad222540d
refs/heads/master
2021-01-20T12:49:41.653058
2017-05-07T08:48:13
2017-05-07T08:48:13
90,414,662
2
0
null
null
null
null
UTF-8
C++
false
false
47,231
cpp
Simulate3D.cpp
#include "Simulate3D.h" #include "PickEventHandler.h" #include "RotateHandler.h" #include "UpdateGeodeCallback.h" #include "Simulate3DArgumentParser.h" #include "Configuration.h" #include "Util.h" #include "SBWSimulatorData.h" #include "TimeSeriesData.h" #include "NOMData.h" #include <sstream> #include <fstream> #include <stdio.h> // SBW modules #include "BROKER_BROKER.h" #include "DrawNetwork_network.h" #include "SBMLLayoutModule_reader.h" #include "edu_caltech_NOMClipboard_NOM.h" #include <osg/Vec2> #include <osg/Node> #include <osg/Geode> #include <osg/Group> #include <osg/Light> #include <osg/LightSource> #include <osg/ref_ptr> #include <osg/Geometry> #include <osg/Material> #include <osg/StateSet> #include <osg/Texture2D> #include <osg/LineWidth> #include <osg/NodeVisitor> #include <osg/LineSegment> #include <osg/NodeCallback> #include <osg/AnimationPath> #include <osg/ShapeDrawable> #include <osg/MatrixTransform> #include <osg/PositionAttitudeTransform> #include <osg/StateAttribute> #include <osg/StateSet> #include <osgGA/GUIEventAdapter> #include <osgUtil/Optimizer> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgDB/ReaderWriter> #include <osgViewer/Viewer> #include <osgViewer/ViewerBase> using namespace std; using namespace simulate; using namespace BROKER1; using namespace DrawNetwork; using namespace SBMLLayoutModule; using namespace edu_caltech_NOMClipboard; #ifdef WIN32 unsigned int getNumberOfScreens() { unsigned int nNumDisplays = 0; DISPLAY_DEVICE oDisplayDevice; DISPLAY_DEVICE oMonitor; DWORD nDevices = 0; DWORD nMonitors = 0; ZeroMemory (&oDisplayDevice, sizeof(oDisplayDevice)); oDisplayDevice.cb = sizeof(oDisplayDevice); while (EnumDisplayDevices(0, nDevices, &oDisplayDevice, 0)) { // don't count mirroring devices if (!(oDisplayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) ) { // don't count disabled devices if (oDisplayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) { ZeroMemory (&oMonitor, sizeof(oMonitor)); nMonitors = 0; oMonitor.cb = sizeof(oMonitor); while (EnumDisplayDevices(oDisplayDevice.DeviceName, nMonitors, &oMonitor, 0)) { if (oMonitor.StateFlags & DISPLAY_DEVICE_ACTIVE ) { // only count active displays nNumDisplays ++; break; } nMonitors ++; } } } nDevices++; } // fall back ... somehow detection of horizontal / vertical span does not quite work // also it is reasonable to assume that a user has at least one display ... if (nNumDisplays == 0) nNumDisplays = 1; return nNumDisplays ; } #endif Simulate3D::Simulate3D (Simulate3DArgumentParser& oArguments) { _bRenderReactions = oArguments.renderReactions(); if ( oArguments.hasConfigFile() ) { initFromConfig(oArguments.getConfigFile()); } else { _bWhite = oArguments.useWhite(); _sTexture = oArguments.getTextureFile(); _sFileName = oArguments.getModelFile(); _sCSVFile = oArguments.getDataFile(); initCommon(); initModel(); } } Simulate3D::Simulate3D(string sConfigFile) { initFromConfig(sConfigFile); } /** * Constructor ... initializes the scene * * \param sFileName SBML model file * \param sTexture Texture file (optional) * \param sCSVFile CSV Data file (optional) * * \return new Simulate3D object */ Simulate3D::Simulate3D(string sFileName, string sTexture, string sCSVFile) { _bWhite = false; _sTexture = sTexture; _sFileName = sFileName; _sCSVFile = sCSVFile; initCommon(); initModel(); } void Simulate3D::initFromConfig(std::string sConfigFile) { initCommon(); Configuration oConfig(sConfigFile); _bWhite = false; _sTexture = oConfig.getTextureFile(); _sTextureFilename = oConfig.getTextureFile(); _sFileName = oConfig.getSBMLFile(); if (_sTexture == "") throw new SBWApplicationException("Texture could not be created, verify your config file"); if (_sFileName == "") cerr << endl << "Warning: could not read SBML file ..." << endl; readFile(); TimeSeriesData *oData = new TimeSeriesData(); _sCSVFile = oConfig.getTimeSeriesFile(); if (_sCSVFile == "") { cerr << endl << "Warning: could not read time series file ..." << endl; } else { oData->readDataFile(_sCSVFile); oData->syncSpecies(); } _dimensions = oConfig.getDimensions(); _species = oConfig.getSpecies(); _oSpeciesMap.clear(); for (unsigned int i = 0; i < _species.size(); i++) { _oSpeciesMap[_species[i].SpeciesName] = i; } _oData = oData; DataProviders.push_back(oData); switchDataProvider(0,false); } void Simulate3D::initCommon() { _oInfoText = new osgText::Text; _oCurrentText = new osgText::Text; _oUpdateText = new osgText::Text; _oControlGroup = new osg::Group; _oHelpGroup = new osg::Group; _nInfoDelay = SIMULATE3D_DELAY * 3 ; #ifdef WIN32 _sTempDir = getenv("TEMP"); #else _sTempDir = "/tmp/"; #endif osgDB::Registry::instance()->getDataFilePathList().push_back(_sTempDir ); osgDB::Registry::instance()->getDataFilePathList().push_back( Util::getPath( Simulate3D::_sPath )); #ifdef WIN32 osgDB::Registry::instance()->getDataFilePathList().push_back("c:\\"); #endif } Simulate3D::~Simulate3D() { try { try { stop(); } catch(...) { } for (unsigned int i = DataProviders.size() ; i > 0 ; i--) { DataProvider *oTemp = DataProviders.back(); DataProviders.pop_back(); free(oTemp); } for (unsigned int i = _species.size() ; i > 0; i--) { _species.pop_back(); } for (unsigned int i = _reactions.size() ; i > 0; i--) { _reactions.pop_back(); } } catch(...) { } } /** * Causes all columns to be re-adjusted */ void Simulate3D::setDirty() { for (unsigned int i = 0; i < _species.size(); i++) { _species[i].Dirty = true; } } /** * Requests new data points from the current DataProvider. If these values differ from the previous values * the corresponding colums will be readjusted. */ void Simulate3D::updateSpecies() { _oData->getSpeciesConcentrations(); } /** * Reads in the SBML file ... * \param sFileName the SBML filename */ void Simulate3D::readFile() { // read model string buffer; ifstream oFile(_sFileName.c_str()); if (!oFile.is_open()) throw new SBWApplicationException("error reading file", "an error occured while trying to read: '" + _sFileName + "'"); try{ while (!oFile.eof()) { getline(oFile, buffer); _sSBML+=buffer; } oFile.close(); } catch (...) { throw new SBWApplicationException("error reading file", "an error occured while trying to read: '" + _sFileName + "'"); } // validate the SBML and promote local to global parameters try { _sSBML = NOM::getParamPromotedSBML(_sSBML); } catch(...) { } } /** * Initializes the available DataProviders */ void Simulate3D::initDataProviders() { try { if (!_sCSVFile.empty()) { TimeSeriesData *oTS = new TimeSeriesData (_sSBML); oTS->readDataFile(_sCSVFile); Simulate3D::DataProviders.push_back(oTS); } else { Simulate3D::DataProviders.push_back(new NOMData (_sSBML)); } DataProviders[0]->init(); } catch(...) { } try { Simulate3D::DataProviders.push_back(new SBWSimulatorData(_sSBML)); DataProviders[1]->init(); } catch(...) { } try { Simulate3D::DataProviders.push_back(new NOMData(_sSBML)); DataProviders[2]->init(); } catch(...) { } if (!_sCSVFile.empty()) _oData = DataProviders[0]; else _oData = DataProviders[2]; //switchDataProvider(2,false); } void Simulate3D::initTexture() { if (_sTexture == "") { // load into simulator and layout tool reader::loadSBML(_sSBML); if (!reader::hasLayout()) { cerr << "Model contains neither JD nor SBML Layout Extension Annotations. Try to generate layout." << endl; /// ok ... in this case take ana's tool and try and create a layout for it ... // turn viewer invisible reader::setVisible(false); network::doAnalysis(_sSBML); _sSBML = network::getSBML(); reader::loadSBML(_sSBML); if (!reader::hasLayout()) { //cerr << "Couldn't generate a layout for the model."<< endl; //exit(-1); throw new SBWApplicationException("Couldn't generate a layout for the model."); } } // get dimensions of the layout _dimensions = reader::getDimensions(); try { unsigned char* array; int length = 0; double dScale = MY_MIN((double)(TextureSize / _dimensions[0]), (double)(TextureSize / _dimensions[1])); reader::getImage(dScale,length,array); _sTextureFilename = _sTempDir + SBWOS::DirectorySeparator() + "texture.jpg"; // writing the texture FILE *texture = fopen( _sTextureFilename.c_str(),"wb+"); fwrite(array, sizeof(unsigned char) , length-1, texture); fflush(texture); fclose(texture); free(array); } catch(...) { //HACK: will fail on OSX ... so let's forget about it for now ... } } else { _sTextureFilename = _sTexture; // get dimensions of the layout _dimensions = reader::getDimensions(); } } void Simulate3D::initSpecies() { // read boundary and floating species from simulator // we have to match the id's for later use readSpecies(); _oSpeciesMap.clear(); // read all positions for species for (int i = 0; i < reader::getNumberOfSpeciesGlyphs(); i++) { DataBlockReader oSpeciesReader = reader::getSpeciesGlyph(i); SpeciesCoordinates oSpecies; oSpeciesReader >> oSpecies.SpeciesName; oSpeciesReader >> oSpecies.SpeciesName; oSpeciesReader >> oSpecies.Position; oSpeciesReader >> oSpecies.Dimension; oSpecies.Color = reader::getSpeciesGlyphColor(i); if (IsFloating(oSpecies.SpeciesName)) { oSpecies.IsBoundary = false; oSpecies.Index = getFloatingIndex(oSpecies.SpeciesName); oSpecies.Concentration = _oData->getSpeciesConcentration(oSpecies.Index, false); } else { oSpecies.IsBoundary = true; oSpecies.Index = getBoundaryIndex(oSpecies.SpeciesName); oSpecies.Concentration = _oData->getSpeciesConcentration(oSpecies.Index, true); } oSpecies.BaseConcentration = oSpecies.Concentration; oSpecies.Dirty = true; _species.push_back(oSpecies); _oSpeciesMap[oSpecies.SpeciesName] = i; } if (!_sCSVFile.empty()) switchDataProvider(0,false); else switchDataProvider(1,false); } /** * Initializes the model, generates a texture and sets up the species objects needed. * * \param sFileName the SBML file */ void Simulate3D::initModel() { try { reader::setVisible(false); //read raw SBML readFile(); // initialize DataProviders initDataProviders(); // init base texture initTexture(); // init species initSpecies(); } catch(SBWException *e) { cerr << e->getMessage() << endl << endl << e->getDetailedMessage() << endl; } catch(...) { } } bool Simulate3D::IsFloating(string &sName) { return getFloatingIndex(sName) != -1; } int Simulate3D::getFloatingIndex(string &sName) { for (unsigned int i=0; i < _oFloatingSpecies.size(); i++) { if (_oFloatingSpecies[i] == sName) return i; } return -1; } int Simulate3D::getBoundaryIndex(string &sName) { for (unsigned int i=0; i < _oBoundarySpecies.size(); i++) { if (_oBoundarySpecies[i] == sName) return i; } return -1; } void Simulate3D::readSpecies() { _oFloatingSpecies = _oData->getFloatingSpeciesNames(); _oBoundarySpecies = _oData->getBoundarySpeciesNames(); } osg::ref_ptr<osg::Node> Simulate3D::createModelPlane(osg::BoundingBox bb,const std::string filename) { osg::ref_ptr<osg::Group> group = new osg::Group; // left hand side of bounding box. osg::Vec3 top_left(bb.xMin(),bb.yMax(),bb.zMin()); osg::Vec3 bottom_left(bb.xMin(),bb.yMin(),bb.zMin()); osg::Vec3 bottom_right(bb.xMax(),bb.yMin(),bb.zMin()); osg::Vec3 top_right(bb.xMax(),bb.yMax(),bb.zMin()); osg::Vec3 center((bb.xMin()+bb.xMax())*0.5f,(bb.yMin()+bb.yMax())*0.5f,bb.zMin()); float height = bb.yMax()-bb.yMin(); // create the geometry for the wall. osg::ref_ptr<osg::Geometry> geom = new osg::Geometry; osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(4); (*vertices)[0] = top_left; (*vertices)[1] = bottom_left; (*vertices)[2] = bottom_right; (*vertices)[3] = top_right; geom->setVertexArray(vertices.get()); osg::ref_ptr<osg::Vec2Array> texcoords = new osg::Vec2Array(4); (*texcoords)[0].set(0.0f,1.0f); (*texcoords)[1].set(0.0f,0.0f); (*texcoords)[2].set(1.0f,0.0f); (*texcoords)[3].set(1.0f,1.0f); geom->setTexCoordArray(0,texcoords.get()); osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array(1); (*normals)[0].set(0.0f,0.0f,1.0f); geom->setNormalArray(normals.get()); geom->setNormalBinding(osg::Geometry::BIND_OVERALL); osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(1); (*colors)[0].set(1.0f,1.0f,1.0f,1.0f); geom->setColorArray(colors.get()); geom->setColorBinding(osg::Geometry::BIND_OVERALL); geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4)); osg::ref_ptr<osg::Geode> geom_geode = new osg::Geode; geom_geode->addDrawable(geom.get()); group->addChild(geom_geode.get()); // set up the texture state. osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setResizeNonPowerOfTwoHint(true); texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR_MIPMAP_NEAREST); texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR_MIPMAP_NEAREST); texture->setDataVariance(osg::Object::DYNAMIC); // protect from being optimized away as static state. texture->setImage(osgDB::readImageFile(filename)); texture->setMaxAnisotropy(16.0f); osg::StateSet* stateset = geom->getOrCreateStateSet(); stateset->setTextureAttributeAndModes(0,texture.get(),osg::StateAttribute::ON); return group.get(); } osg::ref_ptr<osg::Group> Simulate3D::createColumns() { osg::ref_ptr<osg::Group> model = new osg::Group; for ( unsigned int i = 0; i < _species.size(); i++) { SpeciesCoordinates oCoord = _species[i]; osg::ref_ptr<osg::Box> oBox = new osg::Box( osg::Vec3( oCoord.Position[0]+(oCoord.Dimension[0]/2.0f), -1.0F*oCoord.Position[1]-(oCoord.Dimension[1]/2.0f), 0.5f /*oCoord.Concentration*Simulate3D::ScaleFactor + SIMULATE3D_SPACER*/), oCoord.Dimension[0], oCoord.Dimension[1], 1.0f /*oCoord.Concentration*Simulate3D::ScaleFactor + SIMULATE3D_SPACER*/); osg::ref_ptr<osg::Geode> geodeCube = new osg::Geode(); geodeCube->setName( oCoord.SpeciesName ); osg::ref_ptr<osg::ShapeDrawable> oShape = new osg::ShapeDrawable(oBox.get()); oShape->setColor( osg::Vec4( osg::Vec3( oCoord.Color[1], oCoord.Color[2], oCoord.Color[3] ), oCoord.Color[0]*0.5f ) ); geodeCube->addDrawable(oShape.get()); geodeCube->setUpdateCallback(new SpeciesCallback()); osg::ref_ptr<osg::MatrixTransform> matrixTransform = new osg::MatrixTransform(); matrixTransform->setName( oCoord.SpeciesName ); matrixTransform->addChild(geodeCube.get()); model->addChild(matrixTransform.get()); } osg::ref_ptr<osg::StateSet> stateset = model->getOrCreateStateSet(); stateset->setMode((osg::StateAttribute::GLMode)GL_LIGHTING,osg::StateAttribute::ON); stateset->setMode((osg::StateAttribute::GLMode)GL_BLEND,osg::StateAttribute::ON); //stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); //stateset->setRenderingHint(osg::StateSet::RenderingHint::TRANSPARENT_BIN); model->setStateSet(stateset.get()); return model; } osg::ref_ptr<osg::Group> Simulate3D::createReactions() { osg::ref_ptr<osg::Group> reactions = new osg::Group; try { if (_sSBML.empty()) return reactions; reader::loadSBML(_sSBML); if (!reader::hasLayout()) return reactions; _oReactionCurves.clear(); _reactions.clear(); _oAnimationCallbacks.clear(); vector<double> oReactionRates = sim::getReactionRates(); vector<double> oRatesOfChange = sim::getRatesOfChange(); vector<string> oRectionNames; DataBlockReader oReader = sim::getReactionNames(); while (oReader.getNextType() != SystemsBiologyWorkbench::TerminateType) { string sName; oReader >> sName; oRectionNames.push_back(sName); } int nReactions = reader::getNumberOfReactionGlyphs(); _oReactionMap.clear(); for (int i = 0; i < nReactions; i++) { string sId; string sReference; int nSpeciesReferences; DataBlockReader oReader = reader::getReactionGlyph(i); oReader >> sId >> sReference >> nSpeciesReferences; vector<double> oInfo = reader::getReactionGlyphRenderInfoGL(i); ReactionInfo oReactionInfo; oReactionInfo.ID = sReference; oReactionInfo.Color = oInfo; oReactionInfo.LineWidth = oInfo[0]; for (unsigned int l = 0; l < oRectionNames.size(); l++) { if (oRectionNames[l] == oReactionInfo.ID) { oReactionInfo.Index = l; oReactionInfo.Rate = oReactionRates[l]; //oReactionInfo.RateOfChange = oRatesOfChange[l]; oReactionInfo.Dirty = true; } } _reactions.push_back(oReactionInfo); _oReactionMap[oReactionInfo.ID] = i; osg::ref_ptr < osg::Geode > oGeode = new osg::Geode(); osg::ref_ptr < osg::StateSet > stateset = new osg::StateSet(); osg::ref_ptr < osg::LineWidth > lineWidth = new osg::LineWidth(); lineWidth->setWidth(oInfo[0]); stateset->setAttributeAndModes(lineWidth.get(), osg::StateAttribute::ON); stateset->setMode((osg::StateAttribute::GLMode)GL_LINE_SMOOTH,osg::StateAttribute::ON); stateset->setMode((osg::StateAttribute::GLMode)GL_DEPTH_TEST,osg::StateAttribute::OFF); stateset->setMode((osg::StateAttribute::GLMode)GL_LIGHTING,osg::StateAttribute::OFF); oGeode->setStateSet( stateset.get() ); oGeode->setName( sReference ); oGeode->setUpdateCallback( new SpeciesCallback() ); vector<DataBlockReader> oCurve = reader::getReactionCurve(i); _oReactionCurves.clear(); for (unsigned int j = 0; j < oCurve.size(); j ++) { string sType; vector<double> oStart; vector<double> oEnd; vector<double> oBase1; vector<double> oBase2; oCurve[j] >> sType; if (sType == "LineSegment") { oCurve[j] >> oStart >> oEnd; oGeode->addDrawable( drawLine( oStart,oEnd,oInfo ).get() ); } else { oCurve[j] >> oStart >> oEnd >> oBase1 >> oBase2; oGeode->addDrawable( drawLine( oStart,oEnd,oBase1,oBase2,oInfo ).get() ); } } for (int k = 0; k < nSpeciesReferences; k ++) { string sRole; DataBlockReader oSpeciesReference = reader::getSpeciesReference(i, k); oSpeciesReference >> sRole >> sRole >> sRole >> sRole; if (sRole != "product" && sRole != "substrate" && sRole != "sidesubstrate" && sRole != "sideproduct") continue; vector<DataBlockReader> oSpeciesCurve = reader::getSpeciesReferenceCurve(i, k); for (unsigned int j = 0; j < oSpeciesCurve.size(); j ++) { string sType; vector<double> oStart; vector<double> oEnd; vector<double> oBase1; vector<double> oBase2; oSpeciesCurve[j] >> sType; if (sType == "LineSegment") { oSpeciesCurve[j] >> oStart >> oEnd; oGeode->addDrawable( drawLine( oStart,oEnd,oInfo ).get() ); } else { oSpeciesCurve[j] >> oStart >> oEnd >> oBase1 >> oBase2; oGeode->addDrawable( drawLine( oStart,oEnd,oBase1,oBase2,oInfo ).get() ); } } } // by now all the neccessary data about the reactionCurves is in the buffer, so we now need // to extract them from the buffer, form appropriate animationpaths and objects with position- // attitudeTransforms ... vector < osg::ref_ptr < osg::AnimationPathCallback > > oAnimCallbacks; for (unsigned int k = 0; k < _oReactionCurves.size(); k++) { osg::ref_ptr < osg::Vec3Array > oVertices = _oReactionCurves[k]; // first construct the animation path osg::ref_ptr < osg::AnimationPath > animationPath = new osg::AnimationPath; animationPath -> setLoopMode (osg::AnimationPath::LOOP); double time = 0.0; double time_delta = 1.0/(double)oVertices->size(); for (unsigned int j = 0; j < oVertices->size(); j++) { animationPath->insert( time, osg::AnimationPath::ControlPoint(oVertices->at(j))); time += time_delta; } // next generate an object, giving it a position attitude transform that should move it around { // first create a sphere osg::ref_ptr<osg::Sphere> oSphere = new osg::Sphere(osg::Vec3(), MY_MAX( oInfo[0]*1.5f, 0.75) ); osg::ref_ptr<osg::Geode> geodeSphere = new osg::Geode(); geodeSphere->setName( sReference ); osg::ref_ptr<osg::ShapeDrawable> oShape = new osg::ShapeDrawable(oSphere.get()); oShape->setColor( osg::Vec4( osg::Vec3(0.5, 0.5, 0.5),0.5)); osg::ref_ptr<osg::Material> mat = new osg::Material(); mat->setColorMode ( osg::Material::EMISSION ); mat->setAmbient ( osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1) ); mat->setSpecular ( osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1) ); mat->setEmission ( osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1) ); mat->setShininess ( osg::Material::FRONT_AND_BACK, 64.0f ); geodeSphere->getOrCreateStateSet()->setAttributeAndModes(mat.get(),osg::StateAttribute::ON); geodeSphere->addDrawable(oShape.get()); //// how about adding a light at the position of the sphere, might look ok. //osg::ref_ptr< osg::Light > oLight = new osg::Light; ////oLight->setLightNum(i); ////oLight->setPosition(osg::Vec3(), 1.0f); ////oLight->setAmbient(osg::Vec4(0.0f,0.0f,1.0f,1.0f)); //oLight->setDiffuse(osg::Vec4(0.0f,0.0f,1.0f,1.0f)); //oLight->setConstantAttenuation(1.0f/_dimensions[0]/2); //oLight->setLinearAttenuation(2.0f/_dimensions[0]); //oLight->setQuadraticAttenuation(2.0f/osg::square(_dimensions[0])); //osg::ref_ptr< osg::LightSource > oLightSource = new osg::LightSource; //oLightSource->setLight(oLight.get()); //oLightSource->setLocalStateSetModes(osg::StateAttribute::ON); // next create a transform node for sphere osg::ref_ptr<osg::MatrixTransform> matrixTransform = new osg::MatrixTransform(); matrixTransform->setName( sReference ); //matrixTransform->addChild(oLightSource.get()); matrixTransform->addChild(geodeSphere.get()); // finally make our marker move where it should :) osg::ref_ptr < osg::PositionAttitudeTransform > xForm = new osg::PositionAttitudeTransform; osg::ref_ptr < osg::AnimationPathCallback > oCallback = new osg::AnimationPathCallback(animationPath.get(), 0.0, 1.0); oAnimCallbacks.push_back( oCallback ); xForm->setUpdateCallback ( oCallback.get() ); xForm->addChild(matrixTransform.get()); reactions->addChild( xForm.get() ); } } _oAnimationCallbacks.push_back ( oAnimCallbacks ); // finally add the reactionShape reactions->addChild(oGeode.get()); } } catch(SBWException *e) { cerr << "Couldn't generate Lines for reactions. Is SBW installed and working properly?" << endl << "Error message: " << e->getMessage() << endl << "Detailed Error message: " << e->getDetailedMessage() << endl << endl; } try { // read the global parameters next: DataBlockReader oReader = sim::getAllGlobalParameterTupleList(); _parameters.clear(); while (oReader.getNextType() != SystemsBiologyWorkbench::TerminateType) { ParameterInfo oInfo; DataBlockReader oTemp; oReader >> oTemp; oTemp >> oInfo.ID; oTemp >> oInfo.Value; _parameters.push_back(oInfo); } } catch(...) { } return reactions; } osg::Vec2 Simulate3D::getNormal (std::vector<double> oStart, std::vector<double> oEnd) { osg::Vec2 p1 (oStart[0], oStart[1]); osg::Vec2 p2 (oEnd[0], oEnd[1]); osg::Vec2 result = p1 - p2; bool bTemp = abs(result.x()) > abs(result.y()); osg::Vec2 dTemp ( (bTemp ? -result.x():result.x()), (bTemp? result.y():-result.y())); result = dTemp; result.normalize(); return result; } osg::ref_ptr< osg::Geometry > Simulate3D::drawLine( std::vector<double> oStart, std::vector<double> oEnd, std::vector<double> oBase1, std::vector<double> oBase2, std::vector<double> oColor ) { osg::ref_ptr< osg::Geometry > result = new osg::Geometry(); // set up vertices osg::ref_ptr< osg::Vec3Array > vertices = new osg::Vec3Array(); osg::ref_ptr< osg::Vec3Array > reverseBuffer = new osg::Vec3Array(); osg::ref_ptr< osg::Vec3Array > forwardBuffer = new osg::Vec3Array(); osg::ref_ptr< osg::Vec3Array > curveVertices = new osg::Vec3Array(); double m_dTension = 0.0; double P[4][2] = { {oStart[0],-oStart[1]}, {oBase1[0],-oBase1[1]}, {oBase2[0],-oBase2[1]}, {oEnd [0],-oEnd [1]} }; double StartPoint[2] = {oStart[0],-oStart[1]}; double EndPoint[2] = { oEnd[0],- oEnd[1]}; double vv[2]; double tangent1, tangent2, t; double dRange = MY_MAX(0.5 * oColor[0],0.5); osg::Vec2 oOffset = getNormal(oStart, oEnd); oOffset.set(Util::sign(oOffset.x())*dRange, Util::sign(oOffset.y())*dRange); for(t=0; t<=1; t+=0.001) { for(int i=0; i<2; i++) { tangent1 = ( 3 * (1 - m_dTension)*(P[1][i] - P[0][i]) ); tangent2 = ( 3 * (1 - m_dTension)*(P[3][i] - P[2][i]) ); vv[i] = ((2*t*t*t)-(3*t*t)+1)*StartPoint[i] + ((-2*t*t*t)+(3*t*t))*EndPoint[i] + ((t*t*t)-(2*t*t)+t)*tangent1 + ((t*t*t)-(t*t))*tangent2; } curveVertices->push_back( osg::Vec3(vv[0],vv[1],0.001) ); forwardBuffer->push_back( osg::Vec3(vv[0]+oOffset.x(),vv[1]-oOffset.y(),0.001) ); reverseBuffer->push_back( osg::Vec3(vv[0]-oOffset.x(),vv[1]+oOffset.y(),0.001) ); } while (forwardBuffer->size() >= 2) { vertices->push_back( forwardBuffer->back() ); forwardBuffer->pop_back(); osg::Vec3 dTemp = forwardBuffer->back(); vertices->push_back( dTemp ); vertices->push_back( reverseBuffer->back() ); vertices->push_back( reverseBuffer->back() ); reverseBuffer->pop_back(); vertices->push_back( reverseBuffer->back() ); vertices->push_back( dTemp ); } _oReactionCurves.push_back(curveVertices); result->setVertexArray( vertices.get() ); // set up colours osg::ref_ptr< osg::Vec4Array > oColorArray = new osg::Vec4Array(); oColorArray->push_back( osg::Vec4(oColor[1], oColor[2], oColor[3], oColor[4]) ); result->setColorArray ( oColorArray.get() ); result->setColorBinding ( osg::Geometry::BIND_OVERALL ); // set up the primitive set to draw lines //osg::ref_ptr < osg::DrawArrays > oArrays = new osg::DrawArrays( GL_LINE_STRIP, 0, vertices->size() ); osg::ref_ptr < osg::DrawArrays > oArrays = new osg::DrawArrays( GL_TRIANGLE_STRIP, 0, vertices->size() ); result->addPrimitiveSet ( oArrays.get() ); return result.get(); } osg::ref_ptr< osg::Geometry > Simulate3D::drawLine(std::vector<double> oStart, std::vector<double> oEnd, std::vector<double> oColor) { osg::ref_ptr< osg::Geometry > result = new osg::Geometry(); // set up vertices double dRange = MY_MAX(0.5 * oColor[0],0.5); osg::Vec2 oOffset = getNormal(oStart, oEnd); oOffset.set(Util::sign(oOffset.x())*dRange, Util::sign(oOffset.y())*dRange); osg::ref_ptr< osg::Vec3Array > vertices = new osg::Vec3Array( ); vertices -> push_back( osg::Vec3(oStart[0]+oOffset.x(),-oStart[1]-oOffset.y(),0.001f) ); vertices -> push_back( osg::Vec3(oEnd[0]+oOffset.x(),-oEnd[1]-oOffset.y(),0.001f) ); vertices -> push_back( osg::Vec3(oEnd[0]-oOffset.x(),-oEnd[1]+oOffset.y(),0.001f) ); vertices -> push_back( osg::Vec3(oStart[0]-oOffset.x(),-oStart[1]+oOffset.y(),0.001f) ); result->setVertexArray( vertices.get() ); // set up colours osg::ref_ptr< osg::Vec4Array > oColorArray = new osg::Vec4Array(); oColorArray->push_back( osg::Vec4(oColor[1],oColor[2],oColor[3],oColor[4]) ); result->setColorArray ( oColorArray.get() ); result->setColorBinding ( osg::Geometry::BIND_OVERALL ); osg::ref_ptr < osg::DrawArrays > oArrays = new osg::DrawArrays(GL_POLYGON,0,vertices->size()); // set up the primitive set to draw lines result->addPrimitiveSet ( oArrays.get() ); // generate points for animation path osg::ref_ptr< osg::Vec3Array > curveVertices = new osg::Vec3Array( ); curveVertices -> push_back( osg::Vec3(oStart[0],-oStart[1],0.001f) ); curveVertices -> push_back( osg::Vec3(oEnd[0],-oEnd[1],0.001f) ); _oReactionCurves.push_back(curveVertices); return result.get(); } osg::ref_ptr<osg::Node> Simulate3D::createModel() { if (_dimensions.size() < 2) throw new SBWApplicationException("Fatal Error", "The dimensions of the model are still unknown in createModel."); osg::ref_ptr<osg::Group> root = new osg::Group; // turn off lighting root->getOrCreateStateSet()->setMode((osg::StateAttribute::GLMode)GL_LIGHTING,osg::StateAttribute::OFF); osg::ref_ptr<osg::Material> mat = new osg::Material(); mat->setColorMode ( osg::Material::DIFFUSE ); mat->setAmbient ( osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1) ); mat->setSpecular ( osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1) ); mat->setShininess ( osg::Material::FRONT_AND_BACK, 64.0f ); root->getOrCreateStateSet()->setAttributeAndModes(mat.get(),osg::StateAttribute::ON); osg::BoundingBox bb(0.0f,-1.0f*_dimensions[1],0.0f,_dimensions[0],0.0f,0.0f); // add the model background root->addChild(createModelPlane(bb,_sTextureFilename.c_str()).get()); // add the bars representing species concentrations _oColumns = createColumns().get(); root->addChild(_oColumns.get()); // add reactions ... if (_bRenderReactions) { _oReactions = createReactions().get(); if (_oReactions->getNumChildren() > 0) root->addChild(_oReactions.get()); } // add HUD root->addChild(createHUD(_oUpdateText.get()).get()); root->addChild(createInfo(_oInfoText.get()).get()); try { _oLogoGroup = createHelp( osg::BoundingBox(0.0f,0.0f,0.0f, 1280.0f,1024.0f,0.0f), string("Simulate3DLogo.png")).get(); } catch (...) { /// } _oLogoGroup->setNodeMask(0); root->addChild(_oLogoGroup.get()); createControls(root.get()); try { _oHelpGroup = createHelp( osg::BoundingBox(0.0f,0.0f,0.0f, 1280.0f,1024.0f,0.0f), string("help_screen.png")).get(); } catch (...) { /// } _oHelpGroup->setNodeMask(0); root->addChild(_oHelpGroup.get()); return root.get(); } void Simulate3D::createControls(osg::Group* oControl) { float dWidth = 305.0f/2.5; float dHeight = 203.0f/2.5; _oControlGroup->setName(""); _oControlGroup->addChild(createHelp( osg::BoundingBox(0.0f,0.0f,0.0f, 1280.0f,dHeight/2.0,0.0f), string("white.png"),"").get()); if (CreateControls) { _oControlGroup->addChild(createHelp( osg::BoundingBox(0.0f,0.0f,0.0f, dWidth/2.0,dHeight/2.0,0.0f), string("cmdFastBack.png"),"fastBack").get()); _oControlGroup->addChild(createHelp( osg::BoundingBox(dWidth/2.0,0.0f,0.0f, dWidth,dHeight/2,0.0f), string("cmdBack.png"),"back").get()); _oControlGroup->addChild(createHelp( osg::BoundingBox(dWidth,0.0f,0.0f, dWidth*1.5,dHeight/2,0.0f), string("cmdPlay.png"),"play").get()); _oControlGroup->addChild(createHelp( osg::BoundingBox(dWidth*1.5,0.0f,0.0f, dWidth*2,dHeight/2,0.0f), string("cmdPause.png"),"pause").get()); _oControlGroup->addChild(createHelp( osg::BoundingBox(dWidth*2,0.0f,0.0f, dWidth*2.5,dHeight/2,0.0f), string("cmdNext.png"),"next").get()); _oControlGroup->addChild(createHelp( osg::BoundingBox(dWidth*2.5,0.0f,0.0f, dWidth*3,dHeight/2,0.0f), string("cmdFastNext.png"),"fastNext").get()); _oControlGroup->addChild(createHelp( osg::BoundingBox(dWidth*3,0.0f,0.0f, dWidth*3.5,dHeight/2,0.0f), string("cmdStop.png"),"stop").get()); } _oControlGroup->addChild(createCurrent(_oCurrentText.get()).get()); oControl->addChild(_oControlGroup.get()); } osg::ref_ptr<osg::Node> Simulate3D::createHelp(osg::BoundingBox bb,const std::string filename, string sName) { // create the hud. derived from osgHud.cpp // adds a set of quads, each in a separate Geode - which can be picked individually // eg to be used as a menuing/help system! // Can pick texts too! osg::ref_ptr<osg::MatrixTransform> modelview_abs = new osg::MatrixTransform; modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF); modelview_abs->setMatrix(osg::Matrix::identity()); //modelview_abs->setName(sName); // // create the geometry for the wall. osg::ref_ptr<osg::Geometry> geom = new osg::Geometry; //geom->setName(sName); osg::ref_ptr<osg::Projection> projection = new osg::Projection; //projection->setName(sName); projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); projection->addChild(modelview_abs.get()); osg::ref_ptr<osg::Group> group = new osg::Group; //group->setName(sName); // left hand side of bounding box. osg::Vec3 top_left(bb.xMin(),bb.yMax(),bb.zMin()); osg::Vec3 bottom_left(bb.xMin(),bb.yMin(),bb.zMin()); osg::Vec3 bottom_right(bb.xMax(),bb.yMin(),bb.zMin()); osg::Vec3 top_right(bb.xMax(),bb.yMax(),bb.zMin()); osg::Vec3 center((bb.xMin()+bb.xMax())*0.5f,(bb.yMin()+bb.yMax())*0.5f,bb.zMin()); float height = bb.yMax()-bb.yMin(); osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(4); (*vertices)[0] = top_left; (*vertices)[1] = bottom_left; (*vertices)[2] = bottom_right; (*vertices)[3] = top_right; geom->setVertexArray(vertices.get()); osg::ref_ptr<osg::Vec2Array> texcoords = new osg::Vec2Array(4); (*texcoords)[0].set(0.0f,1.0f); (*texcoords)[1].set(0.0f,0.0f); (*texcoords)[2].set(1.0f,0.0f); (*texcoords)[3].set(1.0f,1.0f); geom->setTexCoordArray(0,texcoords.get()); osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array(1); (*normals)[0].set(0.0f,0.0f,1.0f); geom->setNormalArray(normals.get()); geom->setNormalBinding(osg::Geometry::BIND_OVERALL); osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(1); (*colors)[0].set(1.0f,1.0f,1.0f,1.0f); geom->setColorArray(colors.get()); geom->setColorBinding(osg::Geometry::BIND_OVERALL); geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4)); //geom->setName(sName); osg::ref_ptr<osg::Geode> geom_geode = new osg::Geode; geom_geode->addDrawable(geom.get()); geom_geode->setName(sName); group->addChild(geom_geode.get()); //group->setName(sName); // set up the texture state. osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setResizeNonPowerOfTwoHint(true); //texture->setName(sName); texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR_MIPMAP_NEAREST); texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR_MIPMAP_NEAREST); texture->setDataVariance(osg::Object::DYNAMIC); // protect from being optimized away as static state. //texture->setImage(_oImage.get()); texture->setImage(osgDB::readImageFile(filename)); //texture->setMaxAnisotropy(16.0f); osg::StateSet* stateset = geom->getOrCreateStateSet(); stateset->setTextureAttributeAndModes(0,texture.get(),osg::StateAttribute::ON); stateset->setMode((osg::StateAttribute::GLMode)GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode((osg::StateAttribute::GLMode)GL_DEPTH_TEST,osg::StateAttribute::OFF); modelview_abs->addChild(group.get()); return projection.get(); } // end create HUD osg::ref_ptr<osg::Node> Simulate3D::createHUD(osgText::Text* updateText) { // create the hud. derived from osgHud.cpp // adds a set of quads, each in a separate Geode - which can be picked individually // eg to be used as a menuing/help system! // Can pick texts too! osg::ref_ptr<osg::MatrixTransform> modelview_abs = new osg::MatrixTransform; modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF); modelview_abs->setMatrix(osg::Matrix::identity()); osg::ref_ptr<osg::Projection> projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); projection->addChild(modelview_abs.get()); std::string timesFont("fonts/courbd.ttf"); // turn lighting off for the text and disable depth test to ensure its always ontop. osg::Vec3 position(0.0f,1000.0f,0.0f); osg::Vec3 delta(0.0f,-120.0f,0.0f); { // this displays what has been selected osg::ref_ptr<osg::Geode> geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode((osg::StateAttribute::GLMode)GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode((osg::StateAttribute::GLMode)GL_DEPTH_TEST,osg::StateAttribute::OFF); geode->setName("update"); geode->addDrawable( updateText ); geode->setUpdateCallback(new SpeciesCallback()); modelview_abs->addChild(geode.get()); updateText->setCharacterSize(30.0f); updateText->setFont(timesFont); updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f)); updateText->setText(""); updateText->setPosition(position); updateText->setName("update"); position += delta; } if (CreateControls) { osg::ref_ptr<osg::Geode> geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode((osg::StateAttribute::GLMode)GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode((osg::StateAttribute::GLMode)GL_DEPTH_TEST,osg::StateAttribute::OFF); geode->setName("HELP Text"); osg::ref_ptr<osgText::Text> text= new osgText::Text(); geode->addDrawable( text.get() ); modelview_abs->addChild(geode.get()); text->setCharacterSize(20.0f); text->setFont(timesFont); if (!_bWhite) text->setColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); else text->setColor(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); text->setText("<H> - Help\n<ESC> - Quit"); text->setPosition(osg::Vec3(1100.0f,1004.0f,0.0f)); } return projection.get(); } // end create HUDf osg::ref_ptr<osg::Node> Simulate3D::createCurrent(osgText::Text* currentText) { osg::ref_ptr<osg::MatrixTransform> modelview_abs = new osg::MatrixTransform; modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF); modelview_abs->setMatrix(osg::Matrix::identity()); osg::ref_ptr<osg::Projection> projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); projection->addChild(modelview_abs.get()); std::string timesFont("fonts/lcd.ttf"); // turn lighting off for the text and disable depth test to ensure its always ontop. osg::Vec3 position(1200.0f,10.0f,0.0f); osg::Vec3 delta(0.0f,10.0f,0.0f); { // this displays what has been selected osg::ref_ptr<osg::Geode> geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode((osg::StateAttribute::GLMode)GL_LIGHTING,(osg::StateAttribute::GLModeValue)osg::StateAttribute::OFF); stateset->setMode((osg::StateAttribute::GLMode)GL_DEPTH_TEST,(osg::StateAttribute::GLModeValue)osg::StateAttribute::OFF); geode->setName("current"); geode->addDrawable( currentText ); geode->setUpdateCallback(new SpeciesCallback()); modelview_abs->addChild(geode.get()); currentText->setCharacterSize(30.0f); currentText->setFont(timesFont); currentText->setAlignment(osgText::Text::RIGHT_BOTTOM); currentText->setColor(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); currentText->setText("Time"); currentText->setPosition(position); currentText->setName("current"); position += delta; } return projection.get(); } osg::ref_ptr<osg::Node> Simulate3D::createInfo(osgText::Text* infoText) { // create the hud. derived from osgHud.cpp // adds a set of quads, each in a separate Geode - which can be picked individually // eg to be used as a menuing/help system! // Can pick texts too! osg::ref_ptr<osg::MatrixTransform> modelview_abs = new osg::MatrixTransform; modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF); modelview_abs->setMatrix(osg::Matrix::identity()); osg::ref_ptr<osg::Projection> projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); projection->addChild(modelview_abs.get()); std::string timesFont("fonts/courbd.ttf"); // turn lighting off for the text and disable depth test to ensure its always ontop. osg::Vec3 position(0.0f,60.0f,0.0f); osg::Vec3 delta(0.0f,60.0f,0.0f); { // this displays what has been selected osg::ref_ptr<osg::Geode> geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); geode->setName("info"); geode->addDrawable( infoText ); geode->setUpdateCallback(new SpeciesCallback()); modelview_abs->addChild(geode.get()); infoText->setCharacterSize(30.0f); infoText->setFont(timesFont); infoText->setColor(osg::Vec4(1.0f,0.0f,0.0f,1.0f)); infoText->setText(""); infoText->setPosition(position); infoText->setName("info"); position += delta; } return projection.get(); } // end create HUD void Simulate3D::startProducer(osg::ArgumentParser arguments) { startProducer(arguments, false); } void Simulate3D::clearLists() { stop(); _oBoundarySpecies.clear(); _oFloatingSpecies.clear(); _species.clear(); DataProviders.clear(); if (_oColumns != NULL) _oColumns->removeChildren(0,_oColumns->getNumChildren()); if (_oReactions != NULL) _oReactions->removeChildren(0,_oReactions->getNumChildren()); _oData = NULL; _rootnode = new osg::MatrixTransform(); CanSimulate=false; //unlink(_sTextureFilename.c_str()); _sTextureFilename = ""; _sTexture = ""; _sSBML = ""; _sCSVFile = ""; _sFileName = ""; } void Simulate3D::startProducer(osg::ArgumentParser arguments, bool bWhite) { try { _bWhite = bWhite; // initialize the viewer. osgViewer::Viewer viewer(arguments); //#if defined (DEBUG) || defined (_DEBUG) // viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); //#else // // set up the value with sensible default event handlers. // viewer.setUpViewer( // osgProducer::Viewer::TRACKBALL_MANIPULATOR| // osgProducer::Viewer::DRIVE_MANIPULATOR | // osgProducer::Viewer::FLIGHT_MANIPULATOR | // osgProducer::Viewer::TERRAIN_MANIPULATOR | // osgProducer::Viewer::HEAD_LIGHT_SOURCE | // osgProducer::Viewer::ESCAPE_SETS_DONE // ); //#endif // if (bWhite) // viewer.setClearColor(osg::Vec4(osg::Vec3(1.0f,1.0f,1.0f),0.0f)); // else // viewer.setClearColor(osg::Vec4(osg::Vec3(0.0f,0.0f,0.0f),0.0f)); // // viewer osgDB::ReaderWriter::Options* options = new osgDB::ReaderWriter::Options; options->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_IMAGES); osgDB::Registry::instance()->setOptions(options); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); PickHandler *handler = new PickHandler(&viewer); viewer.addEventHandler(handler); // viewer.getEventHandlerList().push_front(handler); // if (MultiScreen) // { // Producer::RenderSurface* oSurface = viewer.getCamera(0)->getRenderSurface(); // // unsigned int nWidth; // unsigned int nHeight; // oSurface->getScreenSize( nWidth, nHeight ); // unsigned int nNumDisplay; //#ifdef WIN32 // nNumDisplay = getNumberOfScreens(); //#else // nNumDisplay = oSurface->getNumberOfScreens(); //#endif // // oSurface->setCustomFullScreenRectangle(0,0 // , nWidth*nNumDisplay, nHeight); // } // load the nodes from the commandline arguments. osg::ref_ptr<osg::Node> model = createModel(); if (!model) { return; } srand( (unsigned)time( NULL ) ); // tilt the scene so the default eye position is looking down on the model. _rootnode = new osg::MatrixTransform; _rootnode -> setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f)); _rootnode -> addChild(model.get()); // run optimization over the scene graph //osgUtil::Optimizer optimzer; //optimzer.optimize(rootnode.get()); if (ScreenSaverMode) { RotateCallback::bb = osg::BoundingBox(0.0f,-1.0f*_dimensions[1],0.0f,_dimensions[0],0.0f,0.0f); // set up a transform to rotate the model osg::Matrix oTemp; oTemp.makeTranslate(-RotateCallback::bb.center()); osg::ref_ptr<osg::MatrixTransform> xform = new osg::MatrixTransform(oTemp); RotateCallback::rotate_cb = new RotateCallback; xform->setUpdateCallback(RotateCallback::rotate_cb); xform->addChild(_rootnode.get()); // set the scene to render viewer.setSceneData(xform.get()); } else { viewer.setSceneData(_rootnode.get()); } // create the windows and run the threads. viewer.realize(); //Simulate3D::setText( "Frank Bergmann" ); Simulate3D::setInfo( "Simulate 3D version 2.0" ); startThread(); viewer.setThreadingModel(osgViewer::ViewerBase::SingleThreaded); viewer.run(); SleepFactor = 0; stop(); } catch (...) { } } bool Simulate3D::switchDataProvider(int nProvider, bool bStopThread ) { DataProvider *oTemp = NULL; bool bError = false; try { if ((int)DataProviders.size() > nProvider) { oTemp = DataProviders[nProvider]; } else { oTemp = _oData; } oTemp->reset(); } catch(...) { bError = true; } if (!bError) { if (bStopThread) Simulate3D::stop(); Simulate3D::TimeStart = 0.0; Simulate3D::SleepFactor = 4; Simulate3D::_oData = oTemp; Simulate3D::_oData->syncSpecies(); CanSimulate = _oData->canSimulate(); if (bStopThread) Simulate3D::startThread(); if (_oData->getName() == "TimeSeriesData") { _oControlGroup->setNodeMask(1); } else { _oControlGroup->setNodeMask(0); } } return bError; } bool Simulate3D::CanSimulate = true; bool Simulate3D::_bCurrentSet = false; bool Simulate3D::CreateControls = true; bool Simulate3D::ScreenSaverMode = false; bool Simulate3D::MultiScreen = false; bool Simulate3D::_bBufferSet = false; bool Simulate3D::_bInfoSet = false; bool Simulate3D::_bRenderReactions = false; int Simulate3D::SleepFactor = 50; int Simulate3D::_nInfoDelay = 0; double Simulate3D::TextureSize = 1024.0; double Simulate3D::ScaleFactor = 30.0; double Simulate3D::TimeStart = 0.0; double Simulate3D::TimeStep = 0.05; double Simulate3D::MaxRate = 1.0; string Simulate3D::_sSBML = ""; string Simulate3D::_sBuffer = ""; string Simulate3D::_sPath = ""; string Simulate3D::_sInfo = ""; string Simulate3D::_sTempDir = ""; string Simulate3D::_sCurrent = ""; DataProvider *Simulate3D::_oData = NULL; SimulationThread Simulate3D::_oTread; osg::ref_ptr<osgText::Text> Simulate3D::_oInfoText = NULL; osg::ref_ptr<osgText::Text> Simulate3D::_oCurrentText = NULL; osg::ref_ptr<osgText::Text> Simulate3D::_oUpdateText = NULL; osg::ref_ptr<osg::Node> Simulate3D::_oHelpGroup = NULL; osg::ref_ptr<osg::Node> Simulate3D::_oLogoGroup = NULL; osg::ref_ptr<osg::Group> Simulate3D::_oControlGroup = NULL; osg::ref_ptr<osg::Group> Simulate3D::_oColumns = NULL; osg::ref_ptr<osg::Group> Simulate3D::_oReactions = NULL; vector<double> Simulate3D::_dimensions; vector<SpeciesCoordinates> Simulate3D::_species; vector<DataProvider*> Simulate3D::DataProviders; vector<ReactionInfo> Simulate3D::_reactions; vector<ParameterInfo> Simulate3D::_parameters; vector < osg::ref_ptr< osg::Vec3Array > > Simulate3D::_oReactionCurves; vector < vector < osg::ref_ptr < osg::AnimationPathCallback > > > Simulate3D::_oAnimationCallbacks; hash_map< string, int > Simulate3D::_oSpeciesMap; hash_map< string, int > Simulate3D::_oReactionMap;
a3574945fe8f6214c06298b74f029143cd77ed96
e376a236d0e07848357a7189e1aa8449e1e6c828
/src/panes/DrawablePane.cpp
2c3b4e2abe25c0f506b5a2a13a4ee19bf643d07c
[]
no_license
vencho/arkanoid
2f6032c46d46ef7672de990aac288a683faa1dff
5ba8c5e5dff193f941b9b7c22e0ffc77cf28397e
refs/heads/master
2021-01-23T20:01:11.397989
2019-06-02T23:03:36
2019-06-02T23:03:36
102,844,911
0
1
null
2019-06-02T23:03:38
2017-09-08T09:34:42
C++
UTF-8
C++
false
false
465
cpp
DrawablePane.cpp
#include<panes/DrawablePane.h> DrawablePane::DrawablePane() : FloatingRectangle(0, 0) { } void DrawablePane::reset() { } void DrawablePane::draw(SDL_Surface *target, int baseX, int baseY) { setClip(target, baseX, baseY); drawYourself(target, baseX, baseY); } void DrawablePane::setClip(SDL_Surface *target, int baseX, int baseY) { SDL_Rect clip; clip.x = baseX; clip.y = baseY; clip.w = width; clip.h = height; SDL_SetClipRect(target, &clip); }
87e70a09f034fffc691189116a8a7994f5486adf
caa560f573580080b8f372043dd80442382a6c32
/project_state/PerspectiveTransform.cpp
891c95ef1b4435b34458e58d5fbd4360eb67db2b
[]
no_license
shainaloria/ph-plate-recognition
80b2304c7de02c3cd36423a0f27b6f02f588e156
8781c11f6b0e38fafd9972637a0afa891721f05b
refs/heads/master
2021-02-27T04:40:10.034810
2020-03-07T07:45:49
2020-03-07T07:45:49
245,579,823
0
1
null
null
null
null
UTF-8
C++
false
false
15,279
cpp
PerspectiveTransform.cpp
//--------------------------------------------------------------------------- // // Name: PerspectiveTransform.cpp // Author: John Benedict Du // Created: 14/02/2018 2:07:33 PM // Description: // //--------------------------------------------------------------------------- #include <vector> #include <fstream> #include <iostream> #include "PerspectiveTransform.h" /* * The Perspective Transform Object contains the values of the matrix * that would be used to transform coordinates of the given pixels. * The matrix is given as follows: * | a11 a12 a13 | * | a21 a22 a33 | * | a31 a32 a33 | */ PerspectiveTransform::PerspectiveTransform( double a11Given, double a21Given, double a31Given, double a12Given, double a22Given, double a32Given, double a13Given, double a23Given, double a33Given) { a11 = a11Given; a12 = a12Given; a13 = a13Given; a21 = a21Given; a22 = a22Given; a23 = a23Given; a31 = a31Given; a32 = a32Given; a33 = a33Given; } /* * Source: George Wolberg-Digital Image Warping-IEEE (1990) pp 52-56 * * This function computes for the matrix values of the PerspectiveTransform * object. The inputs are the 4 points of the corners of the desired * quadrilateral where (x0, y0), (x1, y1), (x2, y2) and (x3, y3) are the * top-left, top-right, bottom-right and bottom-left corners respectively. * * Original four corners Result * (0, 0) (newX0, newY0) * (1, 0) (newX1, newY1) * (1, 1) (newX2, newY2) * (0, 1) (newX3, newY3) * * According to our source the general reperesentation Perespective Transform is * | a11 a12 a13 | * [x', y', w'] = [x, y, w]| a21 a22 a23 | * | a31 a32 a33 | * * Since the images that we were using are 2 dimensional, only x and y are * variables while w would be 1 by default. Thus the values of the newX and * the newY could be computed as follows. * newX = x'/w' * newY = y'/w' * * For this function, the given would be 4 points or 8 values. Thus, the * 9th coefficeint, a33, of the matrix could be normalized to 1 so that * a minimum of 8 degrees of freedom could be acheived for the algorithm * without making it too complex. * * Leting a33 = 1 and w = 1 and solving to x' and y': * newX = (a11 * x + a21 * y + a31)/(a13 * x + a23 * y) * newY = (a12 * x + a22 * y + a32)/(a13 * x + a23 * y) * * Simplifing where i = 0, 1, 2, 3: * newXi = a11 * xi + a21 * yi + a31 - a13 * xi * newXi - a23 * yi * newXi * newYi = a12 * xi + a22 * yi + a32 - a13 * xi * newYi - a23 * yi * newYi * * Expanding where i = 0, 1, 2, 3: * newXi = a11 * (xi) + a21 * (yi) + a31 * (1) * + a12 * (0) + a22 * (0) + a32 * (0) * + a13 * (- xi * newXi) + a23 * (- yi * newXi) + a33 * (0) * newYi = a11 * (0) + a21 * (0) + a31 * (0) * + a12 * (xi) + a22 * (yi) + a32 * (1) * + a13 * (- xi * newYi) + a23 * (- yi * newYi) + a33 * (0) * * This would result in having 8 equations with 16 unknown values namely the * coordinates of the 4 points newX0, newY0, newX1, newY1, newX2, newY2, newX3 * and newY3 and the matrix values a11, a21, a31, a12, a22, a32, a13 and a23. * All 8 equations could be represented into the following matrix equation. * |x0 y0 1 0 0 0 -x0*newX0 -y0*newX0||a11| = |newX0| * |x1 y1 1 0 0 0 -x1*newX1 -y1*newX1||a21| = |newX1| * |x2 y2 1 0 0 0 -x2*newX2 -y2*newX2||a31| = |newX2| * |x3 y3 1 0 0 0 -x3*newX3 -y3*newX3||a12| = |newX3| * |0 0 0 x0 y0 1 -x0*newY0 -y0*newY0||a22| = |newY0| * |0 0 0 x1 y1 1 -x1*newY1 -y1*newY1||a32| = |newY1| * |0 0 0 x2 y2 1 -x2*newY2 -y2*newY2||a13| = |newY2| * |0 0 0 x3 y3 1 -x3*newY3 -y3*newY3||a23| = |newY3| * * Since the image would originally start as a * square, the following values can be used. * (x0, y0) = (0, 0) * (x1, y1) = (1, 0) * (x2, y2) = (1, 1) * (x3, y3) = (0, 1) * * Plugging in the values into the matrix: * |0 0 1 0 0 0 0 0 ||a11| = |newX0| * |1 0 1 0 0 0 -newX1 0 ||a21| = |newX1| * |1 1 1 0 0 0 -newX2 -newX2||a31| = |newX2| * |0 1 1 0 0 0 0 -newX3||a12| = |newX3| * |0 0 0 0 0 1 0 0 ||a22| = |newY0| * |0 0 0 1 0 1 -newY1 0 ||a32| = |newY1| * |0 0 0 1 1 1 -newY2 -newY2||a13| = |newY2| * |0 0 0 0 1 1 0 -newY3||a23| = |newY3| * * This result into the following equations: * a31 = newX0 * a11 + a31 - a13*newX1= newX1 * a11 + a21 + a31 - a13*newX2 - a23*newX2 = newX2 * a21 + a31 - a23*newX3 = newX3 * a32 = newY0 * a12 + a32 - a13*newY1 = newY1 * a12 + a22 + a32 - a13*newY2 - a23*newY2 = newY2 * a22 + a32 - a23*newY3 = newY3 * * With the power of calculators, solving for the * matrix values in terms of the 4 coordinates: * a11 = newX1 - newX0 + a13*newX1 * a21 = newX3 - newX0 + a23*newX3 * a31 = newX0 * a12 = newY1 - newY0 + a13*newY1 * a22 = newY3 - newY0 + a23*newY3 * a32 = newY0 * a13 = ((newX0 - newX1 + newX2 - newX3)*(newY3 - newY2) * - (newY0 - newY1 + newY2 - newY3)*(newX3 - newX2)) * /((newX1 - newX2)*(newY3 - newY2) * - (newY1 - newY2)*(newX3 - newX2)) * a23 = ((newY0 - newY1 + newY2 - newY3)*(newX1 - newX2) * - (newX0 - newX1 + newX2 - newX3)*(newY1 - newY2)) * /((newX1 - newX2)*(newY3 - newY2) * - (newY1 - newY2)*(newX3 - newX2)) */ PerspectiveTransform PerspectiveTransform::squareToQuadrilateral( double newX0, double newY0, double newX1, double newY1, double newX2, double newY2, double newX3, double newY3) { double dx3 = newX0 - newX1 + newX2 - newX3; double dy3 = newY0 - newY1 + newY2 - newY3; /* * If dx3 and dy3 results in a 0, the algorithm could * be simplified to make the computation faster. */ if(dx3 == 0.0 && dy3 == 0.0) { a11 = newX1 - newX0; a21 = newX3 - newX0; a31 = newX0; a12 = newY1 - newY0; a22 = newY3 - newY0; a32 = newY0; a13 = 0.0; a23 = 0.0; a33 = 1.0; } /* * The code as follows implements the equations * as obtained in the description ablove. */ else { double dx1 = newX1 - newX2; double dx2 = newX3 - newX2; double dy1 = newY1 - newY2; double dy2 = newY3 - newY2; double denominator = dx1 * dy2 - dx2 * dy1; a13 = (dx3 * dy2 - dx2 * dy3) / denominator; a23 = (dx1 * dy3 - dx3 * dy1) / denominator; a11 = newX1 - newX0 + a13 * newX1; a21 = newX3 - newX0 + a23 * newX3; a31 = newX0; a12 = newY1 - newY0 + a13 * newY1; a22 = newY3 - newY0 + a23 * newY3; a32 = newY0; a33 = 1.0; } /* * The results of the matrix values are then returned. */ PerspectiveTransform result( a11, a21, a31, a12, a22, a32, a13, a23, 1.0 ); //Use this code to check if the matrix is generated correctly /* std::ofstream myfile ("result.txt"); if (myfile.is_open()) { myfile << a11 <<" " << a21 << " " << a31 << "\n"; myfile << a12 <<" " << a22 << " " << a32 << "\n"; myfile << a13 <<" " << a23 << " " << a33 << "\n"; myfile.close(); } else std::cout << "Unable to open file"; */ return result; } /* * This function transforms the points of a given pixel array using the * PerspectiveTransform object's matrix values. The returned object is a * new pixel array containing the transformed image. */ int** PerspectiveTransform::transformPoints(int** givenPixelArray, int givenWidth, int givenHeight) { /* * Creates a new pixel array with the same * width and height of the given pixel array. */ int** imgPixelArray = new int*[givenHeight]; for(int dynamicIndex = 0; dynamicIndex < givenHeight; ++dynamicIndex) { imgPixelArray[dynamicIndex] = new int[givenWidth]; } /* * The new pixel array's default form is a blank white image. */ for (int heightIndex=0; heightIndex<givenHeight; ++heightIndex) { for (int widthIndex=0; widthIndex<givenWidth; ++widthIndex) { imgPixelArray[heightIndex][widthIndex] = 1; } } /* * Each pixel in the given pixel array is * then transformed using the matrix values. */ for (int heightIndex=0; heightIndex<givenHeight; ++heightIndex) { for (int widthIndex=0; widthIndex<givenWidth; ++widthIndex) { /* * Given that the general reperesentation Perespective Transform * | a11 a12 a13 | * [x', y', w'] = [x, y, w]| a21 a22 a23 | * | a31 a32 a33 | * where w = 1 for 2 dimensional coordinates * * Solving the matrix gives the following formulas for x' and y' * newX = x'/w' = (a11 * x + a21 * y + a31)/(a13 * x + a23 * y + a33) * newY = y'/w' = (a12 * x + a22 * y + a32)/(a13 * x + a23 * y + a33) * where newX and newY are the new coordinates of the pixel. */ double x = widthIndex; double y = heightIndex; double denominator = a13 * x + a23 * y + a33; double doubleNewX = ((a11 * x + a21 * y + a31) / denominator); double doubleNewY = ((a12 * x + a22 * y + a32) / denominator); /* * Since the pixel array does not have any decimal coordinates, * the new coordinate is converted into an integer. */ int newX = doubleNewX; int newY = doubleNewY; /* * Sometimes when the image is streched too much the image goes out * of bounds of the avaliable size of the image. Thus, new coordinates * that are out of bounds would be ignored. */ int value = givenPixelArray[heightIndex][widthIndex]; if(newX < givenWidth && newY < givenHeight && newX > 0 && newY > 0) { /* * The pixel value of the given pixel array is then * stored in the new pixel array at its new coordinates. */ imgPixelArray[newY][newX] = value; } } } //Use this code to check if the matrix is generated correctly /* std::ofstream myfile ("matrix.txt"); if (myfile.is_open()) { myfile << a11 <<" " << a21 << " " << a31 << "\n"; myfile << a12 <<" " << a22 << " " << a32 << "\n"; myfile << a13 <<" " << a23 << " " << a33 << "\n"; for (int heightIndex=0; heightIndex<givenHeight; ++heightIndex) { for (int widthIndex=0; widthIndex<givenWidth; ++widthIndex) { myfile << imgPixelArray[heightIndex][widthIndex] << " "; } myfile << "\n"; } myfile.close(); } else std::cout << "Unable to open file"; */ return imgPixelArray; } /* * This function returns a custom PerspectiveTransform object which adapts * to the many limitations of the finder pattern's results and the * squareToQuadrilateral function. The inputs are the three points from the * finder pattern algorithm with the 4th point being estimated based on the * three points. */ PerspectiveTransform PerspectiveTransform::reverseWarp( double x0, double y0, double x1, double y1, double x3, double y3) { /* * It has been observed that the squareToQuadrilateral function had the * limitation of only accepting rhombuses and parallelograms. Fortunately, * only 3 points are given from the finder pattern which allows the 4th point * could be generated by taking the differences of the 3 coordinates and * thus, allowing the 4 points to create a parallogram. */ x0 *= 1.0; x1 *= 1.0; x3 *= 1.0; double x2 = (x3 + (x1 - x0))*1.0; y0 *= 1.0; y1 *= 1.0; y3 *= 1.0; double y2 = (y3 + (y1 - y0))*1.0; double scaleY = 0; double scaleX = 0; /* * One thing to note was that the given points most likely won't be in a form * of a square. This makes using the squareToQuadrilateral function won't * work because what we want would be to make the Quadrilateral into a square * instead of the other way around. Thus, in order for it to work, instead of * plugging the given 4 points in, we create the reverse of the shape formed * by the given 4 points and plugin the points of the reversed shape instead. */ double x0p = 0; double x1p = 0; double x2p = 0; double x3p = 0; double y0p = 0; double y1p = 0; double y2p = 0; double y3p = 0; if(y2 > y3) { y0p = y0 + (y2 - y3); y1p = y0; y2p = y2 - (y1 - y0); y3p = y2; scaleY = y3p - y1p; } else { y0p = y1; y1p = y1 + (y3 - y2); y2p = y3; y3p = y3 - (y0 - y1); scaleY = y2p - y0p; } if(x1 > x2) { x0p = x3; x1p = x1 - (x0 - x3); x2p = x1; x3p = x3 + (x1 - x2); scaleX = x1 - x3; } else { x0p = x0 + (x2 - x1); x1p = x2; x2p = x2 - (x3 - x0); x3p = x0; scaleX = x2 - x0; } /* * Another limitation of the squareToQuadrilateral would be that it assumes * that the image is a 1x1 square image. Since the 4 points would most likely * for a quadrilateral bigger than a 1x1 square, the point would then have to * be scaled such that the matrix could be generated properly. The scale was * computed based on the length from corner to corner of the points. */ x0p /= scaleX; x1p /= scaleX; x2p /= scaleX; x3p /= scaleX; y0p /= scaleY; y1p /= scaleY; y2p /= scaleY; y3p /= scaleY; //Use this code to check if the coordinates were generated correctly /* std::ofstream myfile ("center.txt"); if (myfile.is_open()) { myfile << x0p << "\t" << y0p << "\n"; myfile << x1p << "\t" << y1p << "\n"; myfile << x2p << "\t" << y2p << "\n"; myfile << x3p << "\t" << y3p << "\n"; myfile.close(); } else std::cout << "Unable to open file"; */ /* * The results of the matrix values are then returned. */ PerspectiveTransform result = squareToQuadrilateral( x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p ); return result; }
20836ea83650b5412b76e418b5fcf599ccc5776d
d46b808a40fd16ce501cd83287f8129934da74ad
/48.cpp
13e39c0e836cd858aa796cd72340fc7639c21bf9
[]
no_license
Luisa158/NuevoLenguaje
418813b5b3cbb463d1b853706486a5d73217fe42
c4c02006c8cdcf93986115594302352bf1e9204b
refs/heads/master
2020-05-24T18:28:21.155719
2019-05-19T04:14:39
2019-05-19T04:14:39
187,411,351
0
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
48.cpp
#include <iostream> using namespace std; int main() { string palabra; string pinvertida=""; cout<<"Escribe una palabra:"<<std::endl; cin>>palabra; for (int i = palabra.size(); i >=0 ; i--) pinvertida += palabra[i]; cout<<"La palabra ingresada es: "<<palabra<<std::endl; cout<<"La palabra invertida es:"<<pinvertida<<std::endl; return 0; }
d847a73d48dd7785df8e6dd8a79a657c925e427e
b42335bbd64ad987a883f3a3bf1a76aa5d154d2e
/pcl/sem.hpp
30d12605e2a91a87b77d3ef7c3b4add8e63abac5
[ "MIT" ]
permissive
johnp41/Compiler-Uni
2af3e806ad965ea9b81e23642f6b1acdad3ab508
4f653180d4f3f98316b15e566e57443041ef6faa
refs/heads/master
2020-04-30T01:26:08.596689
2019-10-15T09:17:47
2019-10-15T09:17:47
176,528,712
0
0
null
null
null
null
UTF-8
C++
false
false
613
hpp
sem.hpp
#ifndef _semh #define _semh extern "C"{ #include "symbol.h" #include "error.h" } #include "my-ast.hpp" #include "stack" extern stack<SymbolEntry* > func_stack ; extern SymbolEntry* dummy ; void sem_rvalue(Rval* r); void sem_if(Stmt* s); void sem_expr(Expr* e); void sem_call(Call* call); void sem_lvalue(Lval* p); void sem_stmt (Stmt* s); void sem_formal(Formal* p,SymbolEntry* f); void sem_formals(list<Formal *> *p , SymbolEntry* f); void sem_header(Header* p , Body* body); void sem_prog(Program* p); void sem_body(Body* p); void sem_local(Local* p); void sem_block(Block* p); void add_lib_func(); #endif