hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fbcba0d70dfedecba3aee499c267b17ca5e5cdeb
860
cpp
C++
new folder/codejamrobot.cpp
bprithiraj/DSA-CPsolvedproblemscode
4b3765e4afb26016fade1f1e526b36934583c668
[ "Apache-2.0" ]
null
null
null
new folder/codejamrobot.cpp
bprithiraj/DSA-CPsolvedproblemscode
4b3765e4afb26016fade1f1e526b36934583c668
[ "Apache-2.0" ]
null
null
null
new folder/codejamrobot.cpp
bprithiraj/DSA-CPsolvedproblemscode
4b3765e4afb26016fade1f1e526b36934583c668
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<string> #include<algorithm> #include<set> void test_case() { int n; cin>>n; vector<string>they(n); for(int i=0;i<n;i++) { cin>>they(i); string moves; for(int pos=0;true;pos++) { set<int>chars; for(string s:they) { chars.insert[s[pos%s.length()]]; } If((int)chars.size()==3) { cout<<"IMPOSSIBLE\n"; return; } if(chars.count('R')&&chars.count('S')) moves+="R"; else if(chars.count('R')&&chars.count('P')) moves+="P"; else if(chars.count('P')&&chars.count('S')) moves+="S"; else if(chars.count('S')) moves+="R"; else if(chars.count('R')) moves+="P"; else if(chars.count('P')) moves+="S"; } } } int main() { int t; cin>>t; for(int i;i<=t;i++) { cout<<"Case #"<<i<<": "; test_case(); } }
15.087719
48
0.502326
bprithiraj
fbcbeea84548acb6c85d54a57d05ee4bc8128e92
575
cpp
C++
Programming/lab05/cpp/5lab.cpp
3xlerman/labsbonch
5255bb62e3cd8d707e38d7ffc0e7ef99f764773b
[ "MIT" ]
3
2020-04-27T11:49:34.000Z
2020-04-30T10:27:58.000Z
Programming/lab05/cpp/5lab.cpp
3xlerman/labsbonch
5255bb62e3cd8d707e38d7ffc0e7ef99f764773b
[ "MIT" ]
null
null
null
Programming/lab05/cpp/5lab.cpp
3xlerman/labsbonch
5255bb62e3cd8d707e38d7ffc0e7ef99f764773b
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; int main() { float x, y, znamSum, chislSum, i, j, k, n, m; cout << "n= "; cin >> n; cout << "m= "; cin >> m; cout << "x= "; cin >> x; y = 0; znamSum = 0; chislSum = 0; for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { chislSum = chislSum + pow(i+j,2); } for(k=1;k<=m;k++) { znamSum = znamSum + k + 1; } y = y + ((2*x + chislSum) / (x + i * znamSum)); } cout << "y= " << y; return 0; }
17.96875
55
0.382609
3xlerman
fbd2e44c4666b106c60546cbb6f714bd914933a8
5,765
cc
C++
tensorflow/core/kernels/xsmm_conv2d.cc
bhbai/tensorflow
d4b5c606fc9fbd1a20b5b113b4bc831f31d889a3
[ "Apache-2.0" ]
65
2016-09-26T01:30:40.000Z
2021-08-11T17:00:41.000Z
tensorflow/core/kernels/xsmm_conv2d.cc
bhbai/tensorflow
d4b5c606fc9fbd1a20b5b113b4bc831f31d889a3
[ "Apache-2.0" ]
5
2017-02-21T08:37:52.000Z
2017-03-29T05:46:05.000Z
tensorflow/core/kernels/xsmm_conv2d.cc
bhbai/tensorflow
d4b5c606fc9fbd1a20b5b113b4bc831f31d889a3
[ "Apache-2.0" ]
10
2017-02-08T21:39:27.000Z
2018-10-04T17:34:54.000Z
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Make this file empty (or nearly empty) so that it can be compiled even when // libxsmm is not available. #ifndef TENSORFLOW_USE_LIBXSMM void dummy_xsmm_conv2d_ensure_file_is_not_empty(void); #else #define USE_EIGEN_TENSOR #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/xsmm_conv2d.h" #include <stdlib.h> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/blocking_counter.h" #include "tensorflow/core/lib/core/threadpool.h" #include "libxsmm/include/libxsmm_cpuid.h" namespace tensorflow { // Xsmm*Conv2D are wrappers for libxsmm direct convolutions. typedef Eigen::ThreadPoolDevice CPUDevice; namespace functor { static void chk_libxsmm_err(libxsmm_dnn_err_t status, string msg) { if (status != LIBXSMM_DNN_SUCCESS) { VLOG(0) << msg << " failed: " << libxsmm_dnn_get_error(status); } } template <typename InputPtr, typename FilterPtr, typename OutputPtr> static bool CallLibxsmmConvGeneric(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, libxsmm_dnn_conv_kind kind, InputPtr input, FilterPtr filter, OutputPtr output) { libxsmm_dnn_err_t status; libxsmm_dnn_conv_handle* libxsmm_handle; libxsmm_handle = libxsmm_dnn_create_conv_handle_check(desc, &status); chk_libxsmm_err(status, "Create handle"); status = libxsmm_dnn_get_codegen_success(libxsmm_handle, kind); if (status == LIBXSMM_DNN_WARN_FALLBACK) { chk_libxsmm_err(libxsmm_dnn_destroy_conv_handle(libxsmm_handle), "Destroy handle"); return false; // Use non-libxsmm code } // libxsmm_dnn_get_codegen_success can return real errors as well chk_libxsmm_err(status, "Check codegen status"); libxsmm_dnn_buffer* libxsmm_input; libxsmm_dnn_buffer* libxsmm_output; libxsmm_dnn_filter* libxsmm_filter; libxsmm_input = libxsmm_dnn_link_input_buffer_check( libxsmm_handle, input, LIBXSMM_DNN_CONV_FORMAT_NHWC_PTR, &status); chk_libxsmm_err(status, "Link input buffer"); libxsmm_output = libxsmm_dnn_link_output_buffer_check( libxsmm_handle, output, LIBXSMM_DNN_CONV_FORMAT_NHWC_PTR, &status); chk_libxsmm_err(status, "Link output buffer"); libxsmm_filter = libxsmm_dnn_link_filter_check( libxsmm_handle, filter, LIBXSMM_DNN_CONV_FORMAT_RSCK_PTR, &status); chk_libxsmm_err(status, "Link filter"); chk_libxsmm_err(libxsmm_dnn_zero_buffer(libxsmm_output), "Zero output"); chk_libxsmm_err(libxsmm_dnn_bind_input_buffer(libxsmm_handle, libxsmm_input), "Bind input"); chk_libxsmm_err( libxsmm_dnn_bind_output_buffer(libxsmm_handle, libxsmm_output), "Bind output"); chk_libxsmm_err(libxsmm_dnn_bind_filter(libxsmm_handle, libxsmm_filter), "Bind filter"); if (kind == LIBXSMM_DNN_CONV_KIND_BWD) { libxsmm_dnn_transpose_filter(libxsmm_handle); } // TODO(maciejd) We would prefer raw threads instead of threadpool. auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads()); int num_threads = worker_threads.num_threads; BlockingCounter counter(num_threads); for (int i = 0; i < num_threads; ++i) { worker_threads.workers->Schedule([=, &counter]() { chk_libxsmm_err(libxsmm_dnn_convolve_st(libxsmm_handle, kind, 0, i), "Worker"); counter.DecrementCount(); }); } counter.Wait(); chk_libxsmm_err(libxsmm_dnn_destroy_buffer(libxsmm_input), "Destroy input"); chk_libxsmm_err(libxsmm_dnn_destroy_buffer(libxsmm_output), "Destroy output"); chk_libxsmm_err(libxsmm_dnn_destroy_filter(libxsmm_filter), "Destroy filter"); chk_libxsmm_err(libxsmm_dnn_destroy_conv_handle(libxsmm_handle), "Destroy handle"); return true; // Succeeded } template <typename T> struct XsmmFwdConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, const T* input, const T* filter, T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_FWD, input, filter, output); } }; template <typename T> struct XsmmBkwInputConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, T* input, const T* filter, const T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_BWD, input, filter, output); } }; template <typename T> struct XsmmBkwFilterConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, const T* input, T* filter, const T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_UPD, input, filter, output); } }; } // namespace functor template struct functor::XsmmFwdConv2D<CPUDevice, float>; template struct functor::XsmmBkwInputConv2D<CPUDevice, float>; template struct functor::XsmmBkwFilterConv2D<CPUDevice, float>; } // namespace tensorflow #endif // TENSORFLOW_USE_LIBXSMM
36.955128
80
0.721075
bhbai
fbd4217c109fdd479f197bfe296eceb994c22065
807
cpp
C++
src/0027_remove_element.cpp
hariharanragothaman/cpprevise-leetcode
736d497961f5493a82c3f9355abbc2daa8219643
[ "Apache-2.0" ]
1
2021-04-21T07:59:30.000Z
2021-04-21T07:59:30.000Z
src/0027_remove_element.cpp
hariharanragothaman/cpprevise-leetcode
736d497961f5493a82c3f9355abbc2daa8219643
[ "Apache-2.0" ]
null
null
null
src/0027_remove_element.cpp
hariharanragothaman/cpprevise-leetcode
736d497961f5493a82c3f9355abbc2daa8219643
[ "Apache-2.0" ]
null
null
null
/* Remove element from an array -in place and return the length of the resultant array */ #include "headers.h" class Solution { public: int removeElement(vector<int>& nums, int val) { int index = 0; for(int i=0; i < nums.size(); i++) { if(nums[i] != val) { nums[index] = nums[i]; index++; } } return index; } }; int removeElement(vector<int>& nums, int val) { nums.erase(remove(nums.begin(), nums.end(), val), nums.end()); return nums.size(); } int main() { vector<int> nums = {3, 2, 2, 3}; int val = 3; Solution s1; int result = removeElement(nums, val); cout << "The result is " << result << endl; return 0; }
21.236842
90
0.490706
hariharanragothaman
fbd70fabe038cad1bb9011d0583a1304357e402c
1,797
cpp
C++
src/net/data/message.cpp
wensiso/Ayvu
1f147b2e468b221a8f98db40de07cd95261ba123
[ "Apache-2.0" ]
null
null
null
src/net/data/message.cpp
wensiso/Ayvu
1f147b2e468b221a8f98db40de07cd95261ba123
[ "Apache-2.0" ]
null
null
null
src/net/data/message.cpp
wensiso/Ayvu
1f147b2e468b221a8f98db40de07cd95261ba123
[ "Apache-2.0" ]
null
null
null
/* * Message.cpp * * Created on: 07/11/2013 * Author: Wendell */ #include <message.h> namespace ayvu { Message::Message() { m_header.timestamp = 0; m_header.sequence = 0; m_data = new QByteArray(); m_receive_timestamp = 0; } Message::Message(QByteArray& data, qint64 seq) { m_header.timestamp = QDateTime::currentMSecsSinceEpoch(); m_header.sequence = seq; m_data = new QByteArray(data); m_receive_timestamp = 0; } void Message::createFromReceivedDatagram(QByteArray *datagram) { m_receive_timestamp = QDateTime::currentMSecsSinceEpoch(); int headerSize = 2*sizeof(qint64); QByteArray myDatagram = *datagram; QByteArray header = myDatagram.left(headerSize); char* char_ts = header.left(sizeof(qint64)).data(); memcpy(&m_header.timestamp, char_ts, sizeof(qint64)); char *char_seq = header.right(sizeof(qint64)).data(); memcpy(&m_header.sequence, char_seq, sizeof(qint64)); myDatagram.remove(0, headerSize); m_data = new QByteArray(myDatagram); } QByteArray Message::createDatagram() { QByteArray message; char char_ts[sizeof(qint64)]; memcpy(char_ts, &m_header.timestamp, sizeof(qint64)); message.append(char_ts, sizeof(qint64)); char char_seq[sizeof(qint64)]; memcpy(char_seq, &m_header.sequence, sizeof(qint64)); message.append(char_seq, sizeof(qint64)); message.append(*m_data); return message; } //Getters and Setters QByteArray* Message::getData() const { return m_data; } void Message::setData(QByteArray* data) { m_data = data; } void Message::setHeader(Message::Header header) { m_header = header; } qint64 Message::getSequence() const { return m_header.sequence; } void Message::setSequence(const qint64& sequence) { m_header.sequence = sequence; } qint64 Message::getTimeStamp() const { return m_header.timestamp; } }
20.191011
64
0.732332
wensiso
fbd8dbf4028bb72dd478f0fccbde51c35ec9d1f2
1,514
cpp
C++
src/tests/core/Test_RootBounds.cpp
smtrat/carl-windows
22b3a7677477cdbed9adc7619479ce82a0304666
[ "MIT" ]
29
2015-05-19T12:17:16.000Z
2021-03-05T17:53:00.000Z
src/tests/core/Test_RootBounds.cpp
smtrat/carl-windows
22b3a7677477cdbed9adc7619479ce82a0304666
[ "MIT" ]
36
2016-10-26T12:47:11.000Z
2021-03-03T15:19:38.000Z
src/tests/core/Test_RootBounds.cpp
smtrat/carl-windows
22b3a7677477cdbed9adc7619479ce82a0304666
[ "MIT" ]
16
2015-05-27T07:35:19.000Z
2021-03-05T17:53:08.000Z
#include <gtest/gtest.h> #include <carl/core/VariablePool.h> #include <carl/core/UnivariatePolynomial.h> #include <carl/core/polynomialfunctions/Chebyshev.h> #include <carl/core/polynomialfunctions/RootBounds.h> #include "../Common.h" using UPoly = carl::UnivariatePolynomial<Rational>; template<typename T> class RootBoundTest: public testing::Test {}; TYPED_TEST_CASE(RootBoundTest, RationalTypes); // TODO should use NumberTypes TYPED_TEST(RootBoundTest, CauchyBound) { carl::Variable x = carl::freshRealVariable("x"); carl::UnivariatePolynomial<TypeParam> p(x, {12, 4, 9, 5, 0, 3}); TypeParam bound = carl::cauchyBound(p); EXPECT_EQ(bound, TypeParam(5)); } TYPED_TEST(RootBoundTest, HirstMacey) { carl::Variable x = carl::freshRealVariable("x"); carl::UnivariatePolynomial<TypeParam> p(x, {12, 4, 9, 5, 0, 3}); TypeParam bound = carl::hirstMaceyBound(p); EXPECT_EQ(bound, TypeParam(10)); } TYPED_TEST(RootBoundTest, Lagrange) { carl::Variable x = carl::freshRealVariable("x"); carl::UnivariatePolynomial<TypeParam> p(x, {12, 4, 9, 5, 0, 3}); TypeParam bound = carl::lagrangeBound(p); EXPECT_TRUE(bound <= TypeParam(6)); } TYPED_TEST(RootBoundTest, Chebyshev) { carl::Variable x = carl::freshRealVariable("x"); carl::Chebyshev<TypeParam> chebyshev(x); auto p = chebyshev(50); EXPECT_EQ(TypeParam("9371571/4096"), carl::cauchyBound(p)); EXPECT_EQ(TypeParam("6882064642385021251/562949953421312"), carl::hirstMaceyBound(p)); EXPECT_TRUE(TypeParam("10") >= carl::lagrangeBound(p)); }
31.541667
87
0.73712
smtrat
fbdde82423c30520ae968617046e0f4e3a07cb62
780
cpp
C++
LeetCode/Spiral Matrix II/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
LeetCode/Spiral Matrix II/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
null
null
null
LeetCode/Spiral Matrix II/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> arr(n, vector<int>(n)); int dir = 0, rowStart = 0, rowEnd = n - 1, colStart = 0, colEnd = n - 1, num = 1; while (rowStart <= rowEnd && colStart <= colEnd) { if (dir == 0) { for (int j = colStart; j <= colEnd; ++j) { arr[rowStart][j] = num++; } rowStart++; } else if (dir == 1) { for (int i = rowStart; i <= rowEnd; ++i) { arr[i][colEnd] = num++; } colEnd--; } else if (dir == 2) { for (int j = colEnd; j >= colStart; --j) { arr[rowEnd][j] = num++; } rowEnd--; } else { for (int i = rowEnd; i >= rowStart; --i) { arr[i][colStart] = num++; } colStart++; } dir = (dir + 1) % 4; } return arr; } };
24.375
83
0.489744
Code-With-Aagam
fbdf08b5f3aab6c5e235e6de30d35263abf182bc
338
cpp
C++
chapter12/exercise12_26.cpp
zerenlu/primer_Cpp
4882e244ef90c9f69e344171468b8cfc8308b2c4
[ "MIT" ]
null
null
null
chapter12/exercise12_26.cpp
zerenlu/primer_Cpp
4882e244ef90c9f69e344171468b8cfc8308b2c4
[ "MIT" ]
null
null
null
chapter12/exercise12_26.cpp
zerenlu/primer_Cpp
4882e244ef90c9f69e344171468b8cfc8308b2c4
[ "MIT" ]
null
null
null
#include<string> #include<memory> #include<iostream> int main() { int n(2); std::allocator<std::string> s_m; auto const p = s_m.allocate(n); std::string s; auto q = p; while (std::cin >> s && q != p + n) { s_m.construct(q++, s); } const size_t size = q - p; while (q != p) { s_m.destroy(--q); } s_m.deallocate(p, n); }
14.083333
38
0.573964
zerenlu
fbe18bc3c0038a05b001fc500b7381ffffa086cc
4,022
cpp
C++
ext/emsdk_portable/clang/tag-e1.34.1/src/unittests/Bitcode/NaClAbbrevErrorTests.cpp
slightperturbation/Cobalt
7b398d155d28f7ddf4068a6c25c8aa6aaae486d4
[ "Apache-2.0" ]
null
null
null
ext/emsdk_portable/clang/tag-e1.34.1/src/unittests/Bitcode/NaClAbbrevErrorTests.cpp
slightperturbation/Cobalt
7b398d155d28f7ddf4068a6c25c8aa6aaae486d4
[ "Apache-2.0" ]
null
null
null
ext/emsdk_portable/clang/tag-e1.34.1/src/unittests/Bitcode/NaClAbbrevErrorTests.cpp
slightperturbation/Cobalt
7b398d155d28f7ddf4068a6c25c8aa6aaae486d4
[ "Apache-2.0" ]
null
null
null
//===- llvm/unittest/Bitcode/NaClAbbrevErrorTests.cpp ---------------------===// // Tests parser for PNaCl bitcode instructions. // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Tests errors on bad abbreviation index. #include "llvm/ADT/STLExtras.h" #include "llvm/Bitcode/NaCl/NaClBitcodeMunge.h" #include "llvm/Bitcode/NaCl/NaClBitcodeParser.h" #include "llvm/Bitcode/NaCl/NaClLLVMBitCodes.h" #include "gtest/gtest.h" using namespace llvm; namespace { static const uint64_t Terminator = 0x5768798008978675LL; /// Test if we handle badly defined abbreviation indices. TEST(MyDeathNaClAbbrevErrorTests, BadAbbreviationIndex) { const uint64_t BitcodeRecords[] = { 1, naclbitc::BLK_CODE_ENTER, naclbitc::MODULE_BLOCK_ID, 2, Terminator, 1, naclbitc::BLK_CODE_ENTER, naclbitc::TYPE_BLOCK_ID_NEW, 3, Terminator, 3, naclbitc::TYPE_CODE_NUMENTRY, 2, Terminator, 3, naclbitc::TYPE_CODE_VOID, Terminator, 3, naclbitc::TYPE_CODE_FUNCTION, 0, 0, Terminator, 0, naclbitc::BLK_CODE_EXIT, Terminator, 3, naclbitc::MODULE_CODE_FUNCTION, 1, 0, 0, 0, Terminator, 1, naclbitc::BLK_CODE_ENTER, naclbitc::FUNCTION_BLOCK_ID, 2, Terminator, 3, naclbitc::FUNC_CODE_DECLAREBLOCKS, 1, Terminator, 3, naclbitc::FUNC_CODE_INST_RET, Terminator, 0, naclbitc::BLK_CODE_EXIT, Terminator, 0, naclbitc::BLK_CODE_EXIT, Terminator }; const uint64_t ReplaceIndex = 3; // Index for TYPE_CODE_VOID; // Show that we can parse this code. NaClObjDumpMunger DumpMunger(BitcodeRecords, array_lengthof(BitcodeRecords), Terminator); EXPECT_TRUE(DumpMunger.runTest("BadAbbreviationIndex assembly")); EXPECT_EQ( " 0:0|<65532, 80, 69, 88, 69, 1, 0,|Magic Number: 'PEXE' (80, 69, " "88, 69)\n" " | 8, 0, 17, 0, 4, 0, 2, 0, 0, |PNaCl Version: 2\n" " | 0> |\n" " 16:0|1: <65535, 8, 2> |module { // BlockID = 8\n" " 24:0| 1: <65535, 17, 3> | types { // BlockID = 17\n" " 32:0| 3: <1, 2> | count 2;\n" " 34:5| 3: <2> | @t0 = void;\n" " 36:4| 3: <21, 0, 0> | @t1 = void ();\n" " 39:7| 0: <65534> | }\n" " 44:0| 3: <8, 1, 0, 0, 0> | define external void @f0();\n" " 48:6| 1: <65535, 12, 2> | function void @f0() { \n" " | | // BlockID " "= 12\n" " 56:0| 3: <1, 1> | blocks 1;\n" " | | %b0:\n" " 58:4| 3: <10> | ret void;\n" " 60:2| 0: <65534> | }\n" " 64:0|0: <65534> |}\n" "", DumpMunger.getTestResults()); // Shows what happens when we change the abbreviation index to an // illegal value. const uint64_t AbbrevIndex4[] = { ReplaceIndex, NaClBitcodeMunger::Replace, 4, naclbitc::TYPE_CODE_VOID, Terminator, }; DumpMunger.setRunAsDeathTest(true); EXPECT_DEATH( DumpMunger.runTest("Bad abbreviation index 4", AbbrevIndex4, array_lengthof(AbbrevIndex4)), ".*Fatal\\(35\\:0\\)\\: Invalid abbreviation \\# 4 defined for record.*"); // Test that bitcode reader reports problem correctly. NaClParseBitcodeMunger Munger(BitcodeRecords, array_lengthof(BitcodeRecords), Terminator); EXPECT_DEATH( Munger.runTest("Bad abbreviation index", AbbrevIndex4, array_lengthof(AbbrevIndex4), true), ".*Fatal\\(35\\:0\\)\\: Invalid abbreviation \\# 4 defined for record.*"); } } // end of anonymous namespace.
42.787234
80
0.55271
slightperturbation
fbe42dad361b377f505f35e3da99634ae9c29d9c
19,518
cpp
C++
Core/SoarKernel/src/soar_representation/agent.cpp
emamanto/Soar
72d2bc095068dd87ac78dad4f48938f6edc0353a
[ "BSD-2-Clause" ]
2
2019-11-21T14:40:00.000Z
2020-10-25T15:44:53.000Z
Core/SoarKernel/src/soar_representation/agent.cpp
emamanto/Soar
72d2bc095068dd87ac78dad4f48938f6edc0353a
[ "BSD-2-Clause" ]
null
null
null
Core/SoarKernel/src/soar_representation/agent.cpp
emamanto/Soar
72d2bc095068dd87ac78dad4f48938f6edc0353a
[ "BSD-2-Clause" ]
2
2019-12-23T05:06:28.000Z
2020-01-16T12:57:55.000Z
/************************************************************************* * PLEASE SEE THE FILE "license.txt" (INCLUDED WITH THIS SOFTWARE PACKAGE) * FOR LICENSE AND COPYRIGHT INFORMATION. *************************************************************************/ /************************************************************************* * * file: agent.cpp * * ======================================================================= * Initialization for the agent structure. Also the cleanup routine * when an agent is destroyed. These routines are usually replaced * by the same-named routines in the Tcl interface file soarAgent.c * The versions in this file are used only when not linking in Tcl. * HOWEVER, this code should be maintained, and the agent structure * must be kept up to date. * ======================================================================= */ #include "agent.h" #include "action_record.h" #include "callback.h" #include "cmd_settings.h" #include "condition_record.h" #include "decide.h" #include "decider.h" #include "decision_manipulation.h" #include "ebc.h" #include "ebc_identity.h" #include "ebc_repair.h" #include "episodic_memory.h" #include "explanation_memory.h" #include "exploration.h" #include "instantiation.h" #include "instantiation_record.h" #include "io_link.h" #include "lexer.h" #include "mem.h" #include "memory_manager.h" #include "output_manager.h" #include "parser.h" #include "print.h" #include "preference.h" #include "production.h" #include "production_record.h" #include "instantiation.h" #include "reinforcement_learning.h" #include "rete.h" #include "rhs.h" #include "rhs_functions.h" #include "run_soar.h" #include "semantic_memory.h" #include "smem_settings.h" #include "smem_stats.h" #include "smem_structs.h" #include "soar_instance.h" #include "soar_module.h" #include "stats.h" #include "symbol.h" #include "trace.h" #include "working_memory_activation.h" #include "working_memory.h" #include "xml.h" #include "visualize.h" #ifndef NO_SVS #include "svs_interface.h" #endif #include <stdlib.h> #include <map> /* =================================================================== Initialization Function =================================================================== */ void init_soar_agent(agent* thisAgent) { thisAgent->rhs_functions = NIL; /* --- initialize everything --- */ init_production_utilities(thisAgent); init_built_in_rhs_functions(thisAgent); init_rete(thisAgent); init_instantiation_pool(thisAgent); init_decider(thisAgent); init_soar_io(thisAgent); init_tracing(thisAgent); select_init(thisAgent); predict_init(thisAgent); thisAgent->memoryManager->init_memory_pool(MP_chunk_cond, sizeof(chunk_cond), "chunk_condition"); thisAgent->memoryManager->init_memory_pool(MP_constraints, sizeof(constraint_struct), "constraints"); thisAgent->memoryManager->init_memory_pool(MP_sym_triple, sizeof(symbol_triple), "symbol_triple"); thisAgent->memoryManager->init_memory_pool(MP_identity_mapping, sizeof(identity_mapping), "id_mapping"); thisAgent->memoryManager->init_memory_pool(MP_chunk_element, sizeof(chunk_element), "chunk_element"); thisAgent->memoryManager->init_memory_pool(MP_identity_sets, sizeof(Identity), "identities"); thisAgent->memoryManager->init_memory_pool(MP_action_record, sizeof(action_record), "action_record"); thisAgent->memoryManager->init_memory_pool(MP_condition_record, sizeof(condition_record), "cond_record"); thisAgent->memoryManager->init_memory_pool(MP_instantiation_record, sizeof(instantiation_record), "inst_record"); thisAgent->memoryManager->init_memory_pool(MP_chunk_record, sizeof(chunk_record), "chunk_record"); thisAgent->memoryManager->init_memory_pool(MP_production_record, sizeof(production_record), "prod_record"); thisAgent->memoryManager->init_memory_pool(MP_repair_path, sizeof(Repair_Path), "repair_paths"); thisAgent->memoryManager->init_memory_pool(MP_gds, sizeof(goal_dependency_set), "gds"); thisAgent->memoryManager->init_memory_pool(MP_rl_info, sizeof(rl_data), "rl_id_data"); thisAgent->memoryManager->init_memory_pool(MP_rl_et, sizeof(rl_et_map), "rl_et"); thisAgent->memoryManager->init_memory_pool(MP_rl_rule, sizeof(production_list), "rl_rules"); thisAgent->memoryManager->init_memory_pool(MP_wma_decay_element, sizeof(wma_decay_element), "wma_decay"); thisAgent->memoryManager->init_memory_pool(MP_wma_decay_set, sizeof(wma_decay_set), "wma_decay_set"); thisAgent->memoryManager->init_memory_pool(MP_wma_wme_oset, sizeof(wme_set), "wma_oset"); thisAgent->memoryManager->init_memory_pool(MP_wma_slot_refs, sizeof(wma_sym_reference_map), "wma_slot_ref"); thisAgent->memoryManager->init_memory_pool(MP_smem_wmes, sizeof(preference_list), "smem_wmes"); thisAgent->memoryManager->init_memory_pool(MP_smem_info, sizeof(smem_data), "smem_id_data"); thisAgent->memoryManager->init_memory_pool(MP_epmem_wmes, sizeof(preference_list), "epmem_wmes"); thisAgent->memoryManager->init_memory_pool(MP_epmem_info, sizeof(epmem_data), "epmem_id_data"); thisAgent->memoryManager->init_memory_pool(MP_epmem_literal, sizeof(epmem_literal), "epmem_literals"); thisAgent->memoryManager->init_memory_pool(MP_epmem_pedge, sizeof(epmem_pedge), "epmem_pedges"); thisAgent->memoryManager->init_memory_pool(MP_epmem_uedge, sizeof(epmem_uedge), "epmem_uedges"); thisAgent->memoryManager->init_memory_pool(MP_epmem_interval, sizeof(epmem_interval), "epmem_intervals"); thisAgent->EpMem->epmem_params->exclusions->set_value("epmem"); thisAgent->EpMem->epmem_params->exclusions->set_value("smem"); /* --- add default object trace formats --- */ add_trace_format(thisAgent, false, FOR_ANYTHING_TF, NIL, "%id %ifdef[(%v[name])]"); add_trace_format(thisAgent, false, FOR_STATES_TF, NIL, "%id %ifdef[(%v[attribute] %v[impasse])]"); { Symbol* evaluate_object_sym; evaluate_object_sym = thisAgent->symbolManager->make_str_constant("evaluate-object"); add_trace_format(thisAgent, false, FOR_OPERATORS_TF, evaluate_object_sym, "%id (evaluate-object %o[object])"); thisAgent->symbolManager->symbol_remove_ref(&evaluate_object_sym); } /* --- add default stack trace formats --- */ add_trace_format(thisAgent, true, FOR_STATES_TF, NIL, "%right[6,%dc]: %rsd[ ]==>S: %cs"); add_trace_format(thisAgent, true, FOR_OPERATORS_TF, NIL, "%right[6,%dc]: %rsd[ ] O: %co"); reset_statistics(thisAgent); #ifndef NO_SVS thisAgent->svs = make_svs(thisAgent); #endif /* RDF: For gSKI */ init_agent_memory(thisAgent); /* END */ } agent* create_soar_agent(char* agent_name) /* loop index */ { char cur_path[MAXPATHLEN]; agent* thisAgent = new agent(); thisAgent->name = savestring(agent_name); thisAgent->output_settings = new AgentOutput_Info(); thisAgent->newly_created_instantiations = NULL; thisAgent->current_tc_number = 0; thisAgent->all_wmes_in_rete = NIL; thisAgent->alpha_mem_id_counter = 0; thisAgent->beta_node_id_counter = 0; thisAgent->bottom_goal = NIL; thisAgent->changed_slots = NIL; thisAgent->context_slots_with_changed_accept_prefs = NIL; thisAgent->current_phase = INPUT_PHASE; thisAgent->applyPhase = false; thisAgent->current_wme_timetag = 1; thisAgent->disconnected_ids = NIL; thisAgent->existing_output_links = NIL; thisAgent->output_link_changed = false; thisAgent->go_number = 1; thisAgent->go_type = GO_DECISION; thisAgent->init_count = 0; thisAgent->highest_goal_whose_context_changed = NIL; thisAgent->ids_with_unknown_level = NIL; thisAgent->input_period = 0; thisAgent->input_cycle_flag = true; thisAgent->link_update_mode = UPDATE_LINKS_NORMALLY; thisAgent->mcs_counter = 1; thisAgent->ms_assertions = NIL; thisAgent->ms_retractions = NIL; thisAgent->num_existing_wmes = 0; thisAgent->num_wmes_in_rete = 0; thisAgent->prev_top_state = NIL; thisAgent->production_being_fired = NIL; thisAgent->productions_being_traced = NIL; thisAgent->promoted_ids = NIL; thisAgent->reason_for_stopping = "Startup"; thisAgent->slots_for_possible_removal = NIL; thisAgent->stop_soar = true; thisAgent->system_halted = false; thisAgent->token_additions = 0; thisAgent->top_goal = NIL; thisAgent->top_state = NIL; thisAgent->wmes_to_add = NIL; thisAgent->wmes_to_remove = NIL; thisAgent->wme_filter_list = NIL; thisAgent->multi_attributes = NIL; thisAgent->did_PE = false; thisAgent->FIRING_TYPE = IE_PRODS; thisAgent->ms_o_assertions = NIL; thisAgent->ms_i_assertions = NIL; thisAgent->postponed_assertions = NIL; thisAgent->active_goal = NIL; thisAgent->active_level = 0; thisAgent->previous_active_level = 0; thisAgent->nil_goal_retractions = NIL; /* Initializing rete stuff */ for (int i = 0; i < 256; i++) { thisAgent->actual[i] = 0; thisAgent->if_no_merging[i] = 0; thisAgent->if_no_sharing[i] = 0; } reset_max_stats(thisAgent); if (!getcwd(cur_path, MAXPATHLEN)) { char* error = strerror(errno); thisAgent->outputManager->printa_sf(thisAgent, "Unable to set current directory while initializing agent: %s\n", error); } for (int productionTypeCounter = 0; productionTypeCounter < NUM_PRODUCTION_TYPES; productionTypeCounter++) { thisAgent->all_productions_of_type[productionTypeCounter] = NIL; thisAgent->num_productions_of_type[productionTypeCounter] = 0; } thisAgent->numeric_indifferent_mode = NUMERIC_INDIFFERENT_MODE_SUM; thisAgent->rhs_functions = NIL; // Allocate data for XML generation xml_create(thisAgent); soar_init_callbacks(thisAgent); // thisAgent->memoryManager = &Memory_Manager::Get_MPM(); init_memory_utilities(thisAgent); // // This was moved here so that system parameters could // be set before the agent was initialized. init_trace_settings(thisAgent); /* Initializing all the timer structures. Must be initialized after sysparams */ thisAgent->timers_enabled = true; #ifndef NO_TIMING_STUFF thisAgent->timers_cpu.set_enabled(&(thisAgent->timers_enabled)); thisAgent->timers_kernel.set_enabled(&(thisAgent->timers_enabled)); thisAgent->timers_phase.set_enabled(&(thisAgent->timers_enabled)); #ifdef DETAILED_TIMING_STATS thisAgent->timers_gds.set_enabled(&(thisAgent->timers_enabled)); #endif reset_timers(thisAgent); #endif // dynamic counters thisAgent->dyn_counters = new std::unordered_map< std::string, uint64_t >(); thisAgent->outputManager = &Output_Manager::Get_OM(); thisAgent->command_params = new cli_command_params(thisAgent); thisAgent->EpMem = new EpMem_Manager(thisAgent); thisAgent->SMem = new SMem_Manager(thisAgent); thisAgent->symbolManager = new Symbol_Manager(thisAgent); thisAgent->explanationBasedChunker = new Explanation_Based_Chunker(thisAgent); thisAgent->explanationMemory = new Explanation_Memory(thisAgent); thisAgent->visualizationManager = new GraphViz_Visualizer(thisAgent); thisAgent->RL = new RL_Manager(thisAgent); thisAgent->WM = new WM_Manager(thisAgent); thisAgent->Decider = new SoarDecider(thisAgent); /* Something used for one of Alex's unit tests. Should remove. */ thisAgent->lastCue = NULL; // statistics initialization thisAgent->dc_stat_tracking = false; thisAgent->stats_db = new soar_module::sqlite_database(); thisAgent->substate_break_level = 0; return thisAgent; } /* =============================== =============================== */ void destroy_soar_agent(agent* delete_agent) { delete delete_agent->visualizationManager; delete delete_agent->explanationBasedChunker; delete_agent->explanationBasedChunker = NULL; delete_agent->visualizationManager = NULL; #ifndef NO_SVS delete delete_agent->svs; delete_agent->svs = NULL; #endif delete_agent->RL->clean_up_for_agent_deletion(); delete_agent->WM->clean_up_for_agent_deletion(); delete_agent->EpMem->clean_up_for_agent_deletion(); delete_agent->SMem->clean_up_for_agent_deletion(); delete_agent->Decider->clean_up_for_agent_deletion(); delete delete_agent->command_params; delete_agent->command_params = NULL; stats_close(delete_agent); delete delete_agent->stats_db; delete_agent->stats_db = NULL; remove_built_in_rhs_functions(delete_agent); getSoarInstance()->Delete_Agent(delete_agent->name); free(delete_agent->name); multi_attribute* lastmattr = 0; for (multi_attribute* curmattr = delete_agent->multi_attributes; curmattr != 0; curmattr = curmattr->next) { delete_agent->symbolManager->symbol_remove_ref(&(curmattr->symbol)); delete_agent->memoryManager->free_memory(lastmattr, MISCELLANEOUS_MEM_USAGE); lastmattr = curmattr; } delete_agent->memoryManager->free_memory(lastmattr, MISCELLANEOUS_MEM_USAGE); excise_all_productions(delete_agent, false); /* We can't clean up the explanation manager until after production excision */ delete delete_agent->explanationMemory; delete_agent->explanationMemory = NULL; delete_agent->symbolManager->release_predefined_symbols(); delete_agent->symbolManager->release_common_variables_and_numbers(); delete_agent->memoryManager->free_with_pool(MP_rete_node, delete_agent->dummy_top_node); delete_agent->memoryManager->free_with_pool(MP_token, delete_agent->dummy_top_token); soar_remove_all_monitorable_callbacks(delete_agent); delete_agent->memoryManager->free_memory(delete_agent->left_ht, HASH_TABLE_MEM_USAGE); delete_agent->memoryManager->free_memory(delete_agent->right_ht, HASH_TABLE_MEM_USAGE); delete_agent->memoryManager->free_memory(delete_agent->rhs_variable_bindings, MISCELLANEOUS_MEM_USAGE); /* Releasing trace formats (needs to happen before tracing hashtables are released) */ remove_trace_format(delete_agent, false, FOR_ANYTHING_TF, NIL); remove_trace_format(delete_agent, false, FOR_STATES_TF, NIL); Symbol* evaluate_object_sym = delete_agent->symbolManager->find_str_constant("evaluate-object"); remove_trace_format(delete_agent, false, FOR_OPERATORS_TF, evaluate_object_sym); remove_trace_format(delete_agent, true, FOR_STATES_TF, NIL); remove_trace_format(delete_agent, true, FOR_OPERATORS_TF, NIL); delete delete_agent->output_settings; delete_agent->output_settings = NULL; /* Releasing hashtables allocated in init_tracing */ for (int i = 0; i < 3; i++) { free_hash_table(delete_agent, delete_agent->object_tr_ht[i]); free_hash_table(delete_agent, delete_agent->stack_tr_ht[i]); } /* Releasing memory allocated in init_rete */ for (int i = 0; i < 16; i++) { free_hash_table(delete_agent, delete_agent->alpha_hash_tables[i]); } /* Release module managers */ delete delete_agent->WM; delete delete_agent->Decider; delete delete_agent->RL; delete delete_agent->EpMem; delete delete_agent->SMem; delete delete_agent->symbolManager; delete delete_agent->dyn_counters; /* Release data used by XML generation */ xml_destroy(delete_agent); /* Release agent data structure */ delete delete_agent; } void reinitialize_agent(agent* thisAgent) { /* Clean up explanation-based chunking, episodic and semantic memory data structures */ epmem_reinit(thisAgent); thisAgent->SMem->reinit(); thisAgent->explanationBasedChunker->reinit(); /* Turn off WM activation and RL forgetting temporarily while clearing the goal stack */ bool wma_was_enabled = wma_enabled(thisAgent); thisAgent->WM->wma_params->activation->set_value(off); rl_param_container::apoptosis_choices rl_apoptosis = thisAgent->RL->rl_params->apoptosis->get_value(); thisAgent->RL->rl_params->apoptosis->set_value(rl_param_container::apoptosis_none); /* Remove all states and report to input/output functions */ clear_goal_stack(thisAgent); /* Re-enable WM activation and RL forgetting */ if (wma_was_enabled) thisAgent->WM->wma_params->activation->set_value(on); thisAgent->RL->rl_params->apoptosis->set_value(rl_apoptosis); /* Clear stats for WM, EpMem, SMem and RL */ thisAgent->RL->rl_stats->reset(); thisAgent->WM->wma_stats->reset(); thisAgent->EpMem->epmem_stats->reset(); thisAgent->SMem->reset_stats(); thisAgent->dyn_counters->clear(); /* Signal that everything should be retracted and allow all i-instantiations to retract */ thisAgent->active_level = 0; thisAgent->FIRING_TYPE = IE_PRODS; do_preference_phase(thisAgent); /* It's now safe to clear out explanation memory */ thisAgent->explanationMemory->re_init(); /* Reset Soar identifier hash table and counters for WMEs, SMem and Soar IDs. * Note: reset_hash_table() is where refcount leaks in identifiers are detected. */ reset_wme_timetags(thisAgent); thisAgent->symbolManager->reset_hash_table(MP_identifier); thisAgent->symbolManager->reset_id_counters(); if (thisAgent->SMem->connected()) thisAgent->SMem->reset_id_counters(); /* Reset basic Soar counters and pending XML trace/commands */ reset_statistics(thisAgent); xml_reset(thisAgent); } cli_command_params::cli_command_params(agent* thisAgent) { decide_params = new decide_param_container(thisAgent); load_params = new load_param_container(thisAgent); production_params = new production_param_container(thisAgent); save_params = new save_param_container(thisAgent); wm_params = new wm_param_container(thisAgent); } cli_command_params::~cli_command_params() { delete decide_params; delete load_params; delete production_params; delete save_params; delete wm_params; }
41.351695
128
0.664207
emamanto
fbe4588c43b0b9c5602afd51fa2216a02f4046dc
5,858
cpp
C++
TriangleSplitter/TriangleSplitterFixedLeafSize.cpp
jrouwe/RayCastTest
6f16eef819bd13f7f7bf063b076dab7091b1886a
[ "MIT" ]
7
2020-05-26T15:23:25.000Z
2022-02-25T19:36:25.000Z
TriangleSplitter/TriangleSplitterFixedLeafSize.cpp
jrouwe/RayCastTest
6f16eef819bd13f7f7bf063b076dab7091b1886a
[ "MIT" ]
null
null
null
TriangleSplitter/TriangleSplitterFixedLeafSize.cpp
jrouwe/RayCastTest
6f16eef819bd13f7f7bf063b076dab7091b1886a
[ "MIT" ]
2
2022-03-02T16:30:50.000Z
2022-03-06T14:45:33.000Z
#include <pch.h> // IWYU pragma: keep #include <TriangleSplitter/TriangleSplitterFixedLeafSize.h> #include <TriangleGrouper/TriangleGrouperClosestCentroid.h> TriangleSplitterFixedLeafSize::TriangleSplitterFixedLeafSize(const VertexList &inVertices, const IndexedTriangleList &inTriangles, uint inLeafSize, uint inMinNumBins, uint inMaxNumBins, uint inNumTrianglesPerBin) : TriangleSplitter(inVertices, inTriangles), mLeafSize(inLeafSize), mMinNumBins(inMinNumBins), mMaxNumBins(inMaxNumBins), mNumTrianglesPerBin(inNumTrianglesPerBin) { // Group the triangles TriangleGrouperClosestCentroid grouper; grouper.Group(inVertices, inTriangles, mLeafSize, mSortedTriangleIdx); // Pad triangles so that we have a multiple of mLeafSize const uint num_triangles = (uint)inTriangles.size(); const uint num_groups = (num_triangles + mLeafSize - 1) / mLeafSize; const uint last_triangle_idx = mSortedTriangleIdx.back(); for (uint t = num_triangles, t_end = num_groups * mLeafSize; t < t_end; ++t) mSortedTriangleIdx.push_back(last_triangle_idx); } Vec3 TriangleSplitterFixedLeafSize::GetCentroidForGroup(uint inFirstTriangleInGroup) { assert(inFirstTriangleInGroup % mLeafSize == 0); AABox box; for (uint g = 0; g < mLeafSize; ++g) box.Encapsulate(mVertices, GetTriangle(inFirstTriangleInGroup + g)); return box.GetCenter(); } bool TriangleSplitterFixedLeafSize::Split(const Range &inTriangles, Range &outLeft, Range &outRight, uint &outDimension, float &outSplit) { // Cannot split anything smaller than leaf size assert(inTriangles.Count() > mLeafSize); assert(inTriangles.Count() % mLeafSize == 0); // Calculate bounds for this range AABox centroid_bounds; for (uint t = inTriangles.mBegin; t < inTriangles.mEnd; t += mLeafSize) centroid_bounds.Encapsulate(GetCentroidForGroup(t)); float best_cp = FLT_MAX; uint best_dim = 0xffffffff; float best_split = 0; // Bin in all dimensions uint num_bins = Clamp(inTriangles.Count() / mNumTrianglesPerBin, mMinNumBins, mMaxNumBins); vector<Bin> bins(num_bins); for (uint dim = 0; dim < 3; ++dim) { float bounds_min = centroid_bounds.mMin[dim]; float bounds_size = centroid_bounds.mMax[dim] - bounds_min; // Skip axis if too small if (bounds_size < 1.0e-5f) continue; // Initialize bins for (uint b = 0; b < num_bins; ++b) { Bin &bin = bins[b]; bin.mBounds.SetEmpty(); bin.mMinCentroid = bounds_min + bounds_size * (b + 1) / num_bins; bin.mNumTriangles = 0; } // Bin all triangles for (uint t = inTriangles.mBegin; t < inTriangles.mEnd; t += mLeafSize) { // Calculate average centroid for group float centroid_pos = GetCentroidForGroup(t)[dim]; // Select bin uint bin_no = min(uint((centroid_pos - bounds_min) / bounds_size * num_bins), num_bins - 1); Bin &bin = bins[bin_no]; // Put all triangles of group in same bin for (uint g = 0; g < mLeafSize; ++g) bin.mBounds.Encapsulate(mVertices, GetTriangle(t + g)); bin.mMinCentroid = min(bin.mMinCentroid, centroid_pos); bin.mNumTriangles += mLeafSize; } // Calculate totals left to right AABox prev_bounds; int prev_triangles = 0; for (uint b = 0; b < num_bins; ++b) { Bin &bin = bins[b]; bin.mBoundsAccumulatedLeft = prev_bounds; // Don't include this node as we'll take a split on the left side of the bin bin.mNumTrianglesAccumulatedLeft = prev_triangles; prev_bounds.Encapsulate(bin.mBounds); prev_triangles += bin.mNumTriangles; } // Calculate totals right to left prev_bounds.SetEmpty(); prev_triangles = 0; for (int b = num_bins - 1; b >= 0; --b) { Bin &bin = bins[b]; prev_bounds.Encapsulate(bin.mBounds); prev_triangles += bin.mNumTriangles; bin.mBoundsAccumulatedRight = prev_bounds; bin.mNumTrianglesAccumulatedRight = prev_triangles; } // Get best splitting plane for (uint b = 1; b < num_bins; ++b) // Start at 1 since selecting bin 0 would result in everything ending up on the right side { // Calculate surface area heuristic and see if it is better than the current best Bin &bin = bins[b]; float cp = bin.mBoundsAccumulatedLeft.GetSurfaceArea() * bin.mNumTrianglesAccumulatedLeft + bin.mBoundsAccumulatedRight.GetSurfaceArea() * bin.mNumTrianglesAccumulatedRight; if (cp < best_cp) { best_cp = cp; best_dim = dim; best_split = bin.mMinCentroid; } } } // No split found? if (best_dim == 0xffffffff) return false; // Store best split outDimension = best_dim; outSplit = best_split; // Divide triangles uint start = inTriangles.mBegin, end = inTriangles.mEnd; while (start < end) { // Search for first element that is on the right hand side of the split plane while (start < end && GetCentroidForGroup(start)[best_dim] < best_split) start += mLeafSize; // Search for the first element that is on the left hand side of the split plane while (start < end && GetCentroidForGroup(end - mLeafSize)[best_dim] >= best_split) end -= mLeafSize; if (start < end) { // Swap the two elements for (uint g = 0; g < mLeafSize; ++g) swap(mSortedTriangleIdx[start + g], mSortedTriangleIdx[end - mLeafSize + g]); start += mLeafSize; end -= mLeafSize; } } assert(start == end); // No suitable split found, doing random split in half if (start == inTriangles.mBegin || start == inTriangles.mEnd) start = inTriangles.mBegin + (inTriangles.Count() / mLeafSize + 1) / 2 * mLeafSize; outLeft = Range(inTriangles.mBegin, start); outRight = Range(start, inTriangles.mEnd); assert(outLeft.mEnd > outLeft.mBegin && outRight.mEnd > outRight.mBegin); assert(outLeft.Count() % mLeafSize == 0 && outRight.Count() % mLeafSize == 0); return true; }
35.077844
215
0.698191
jrouwe
fbe66069d17680ad18613bde5d34f79314bf1d19
672
cpp
C++
0169. Majority Element.cpp
luispc111/Leetcode_problems
6f3bc5fb89cb4b9e6e2940b551341489580bd3a0
[ "MIT" ]
null
null
null
0169. Majority Element.cpp
luispc111/Leetcode_problems
6f3bc5fb89cb4b9e6e2940b551341489580bd3a0
[ "MIT" ]
null
null
null
0169. Majority Element.cpp
luispc111/Leetcode_problems
6f3bc5fb89cb4b9e6e2940b551341489580bd3a0
[ "MIT" ]
null
null
null
#include <map> class Solution { public: int majorityElement(vector<int>& nums) { map<int,int> elementos; for (int i = 0; i < nums.size(); i++){ // No está en mi map if(elementos.find(nums[i]) == elementos.end()){ elementos.insert({nums[i], 1}); } // Si está en mi map else{ elementos[nums[i]] += 1; } // Verificar if (elementos[nums[i]] > nums.size()/2){ return nums[i]; } } return 0; } };
24
60
0.366071
luispc111
fbe901569596f1d14929c1dcaab88bc996a2e339
19,471
cpp
C++
components/stella/tia.cpp
mslinklater/retrotools
962d7ed5cfea09f901919cef4ec1b240a0396e0c
[ "BSD-2-Clause" ]
7
2019-11-18T23:11:23.000Z
2022-02-01T14:12:17.000Z
components/stella/tia.cpp
mslinklater/retrotools
962d7ed5cfea09f901919cef4ec1b240a0396e0c
[ "BSD-2-Clause" ]
70
2019-11-06T22:10:52.000Z
2022-02-19T09:49:03.000Z
components/stella/tia.cpp
mslinklater/retrotools
962d7ed5cfea09f901919cef4ec1b240a0396e0c
[ "BSD-2-Clause" ]
1
2020-01-03T13:28:34.000Z
2020-01-03T13:28:34.000Z
#include <assert.h> #include "common.h" #include "tia.h" #include "../commands.h" #include "command.h" #define HALT_ON_UNIMPLEMENTED 0 Tia::Tia() : rasterX(0) , rasterY(0) , frameNum(0) , rasterCount(0) , rasterCountLatched(0) , region(ERegion::NTSC) , bHaltOnTick(false) , bHaltOnHBlank(false) , bHaltOnVBlank(false) , ticksSinceBoot(0) { CommandCenter::Instance()->Subscribe(Commands::kHaltCommand, this); for(int i=0 ; i<kNumReadRegisters ; i++) { readRegisters[i] = 0; bReadBreakpoints[i] = false; } for(int i=0 ; i<kNumWriteRegisters ; i++) { writeRegisters[i] = 0; bWriteBreakpoints[i] = false; } for(int y=0 ; y<kOutputVerticalResolution ; y++) { for(int x=0 ; x<kOutputHorizontalResolution ; x++) { pixels[(y*kOutputHorizontalResolution) + x] = y & 7; } } // Playfield bits for(int i=0 ; i<kNumPlayfieldBits ; i++) { playfieldBits[i] = false; } // sprite bits for(int i=0 ; i<kNumSpriteBits ; i++) { sprite0Bits[i] = false; sprite1Bits[i] = false; } bShowPF = true; bShowP0 = true; bShowP1 = true; } Tia::~Tia() { } void Tia::Tick() { // do tick // Begin actual render logic pixels[rasterX + (rasterY*228)] = GetCOLUBK(); if(rasterX >= 68) { int playfieldIndex = (rasterX-68)/4; if(bShowPF && playfieldBits[playfieldIndex]) { pixels[rasterX + (rasterY*228)] = GetCOLUPF(); } if(bShowP0 && sprite0Bits[rasterX-68]) { pixels[rasterX + (rasterY*228)] = GetCOLUP0(); } if(bShowP1 && sprite1Bits[rasterX-68]) { pixels[rasterX + (rasterY*228)] = GetCOLUP1(); } } // End actual render logic cpuActive[rasterX + (rasterY*228)] = !bCpuWaitingForHsync; // now move rasterX++; if(rasterX >= 228) { // hblank vblankActive[rasterY] = GetVBLANK() != 0; rasterX = 0; rasterY++; // stop overruns if(rasterY >= kOutputVerticalResolution) { rasterY = kOutputVerticalResolution; } rasterCount++; if(bHaltOnHBlank) { Commands::Halt(true, Commands::HaltCommand::kHalt, "TIA HBlank"); bHaltOnHBlank = false; } bCpuWaitingForHsync = false; // end hblank } ticksSinceBoot++; if(bHaltOnTick) { Commands::Halt(true, Commands::HaltCommand::kHalt, "TIA Tick"); bHaltOnTick = false; } } const uint8_t* Tia::GetPalette() { switch(region) { case NTSC: return &paletteNTSC[0]; case PAL: return &palettePAL[0]; default: // SECAM return &paletteSECAM[0]; } } void Tia::RebuildPlayfieldBits() { uint8_t PF0 = GetPF0(); uint8_t PF1 = GetPF1(); uint8_t PF2 = GetPF2(); playfieldBits[0] = PF0 & 0x10; playfieldBits[1] = PF0 & 0x20; playfieldBits[2] = PF0 & 0x40; playfieldBits[3] = PF0 & 0x80; playfieldBits[4] = PF1 & 0x80; playfieldBits[5] = PF1 & 0x40; playfieldBits[6] = PF1 & 0x20; playfieldBits[7] = PF1 & 0x10; playfieldBits[8] = PF1 & 0x08; playfieldBits[9] = PF1 & 0x04; playfieldBits[10] = PF1 & 0x02; playfieldBits[11] = PF1 & 0x01; playfieldBits[12] = PF2 & 0x01; playfieldBits[13] = PF2 & 0x02; playfieldBits[14] = PF2 & 0x04; playfieldBits[15] = PF2 & 0x08; playfieldBits[16] = PF2 & 0x10; playfieldBits[17] = PF2 & 0x20; playfieldBits[18] = PF2 & 0x40; playfieldBits[19] = PF2 & 0x80; if(writeRegisters[kCTRLPF] & 0x01) { // mirror for(int i=0 ; i<20 ; i++) { playfieldBits[39-i] = playfieldBits[i]; } } else { // duplicate for(int i=0 ; i<20 ; i++) { playfieldBits[i+20] = playfieldBits[i]; } } } void Tia::RebuildSprite0Bits() { uint8_t numCopies = 0; uint8_t scale = 0; uint8_t gap = 0; uint8_t nusiz = GetNUSIZ0() & 0x07; switch(nusiz) { case 0: numCopies=1; scale=1; break; case 1: numCopies=2; scale=1; gap=1; break; case 2: numCopies=2; scale=1; gap=3; break; case 3: numCopies=3; scale=1; gap=1; break; case 4: numCopies=2; scale=1; gap=7; break; case 5: numCopies=1; scale=2; break; case 6: numCopies=3; scale=1; gap=3; break; case 7: numCopies=1; scale=4; break; } // clear for(int i=0 ; i<kHBlankClocks ; i++) { sprite0Bits[i] = false; } uint8_t val = GetGRP0(); int offset = 0; for(int iCopy = 0 ; iCopy<numCopies ; iCopy++) { // sprite for(int bit=7 ; bit >= 0 ; bit--) { for(int rep=0 ; rep<scale ; rep++) { int i = resP0Pos+offset; if(i < kNumSpriteBits) { sprite0Bits[i] = val & (0x01 << bit); } offset++; } } // gap for(int iGap=0 ; iGap<gap ; iGap++) { for(int bit=7 ; bit >= 0 ; bit--) { int i = resP0Pos+offset; if(i < kNumSpriteBits) { sprite0Bits[i] = false; } offset++; } } } } void Tia::RebuildSprite1Bits() { uint8_t numCopies = 0; uint8_t scale = 0; uint8_t gap = 0; uint8_t nusiz = GetNUSIZ1() & 0x07; switch(nusiz) { case 0: numCopies=1; scale=1; break; case 1: numCopies=2; scale=1; gap=1; break; case 2: numCopies=2; scale=1; gap=3; break; case 3: numCopies=3; scale=1; gap=1; break; case 4: numCopies=2; scale=1; gap=7; break; case 5: numCopies=1; scale=2; break; case 6: numCopies=3; scale=1; gap=3; break; case 7: numCopies=1; scale=4; break; } // clear for(int i=0 ; i<kHBlankClocks ; i++) { sprite1Bits[i] = false; } uint8_t val = GetGRP1(); int offset = 0; for(int iCopy = 0 ; iCopy<numCopies ; iCopy++) { // sprite for(int bit=7 ; bit >= 0 ; bit--) { for(int rep=0 ; rep<scale ; rep++) { uint8_t i = resP1Pos+offset; if(i < kNumSpriteBits) { sprite1Bits[i] = val & (0x01 << bit); } offset++; } } // gap for(int iGap=0 ; iGap<gap ; iGap++) { for(int bit=7 ; bit >= 0 ; bit--) { uint8_t i = resP1Pos+offset; if(i < kNumSpriteBits) { sprite1Bits[resP1Pos+offset] = false; } offset++; } } } } uint8_t Tia::Read(uint8_t address) { uint8_t ret = 0; switch(address) { case kCXM0P: ret = GetCXM0P(); break; case kCXM1P: ret = GetCXM1P(); break; case kCXP0FB: ret = GetCXP0FB(); break; case kCXP1FB: ret = GetCXP1FB(); break; case kCXM0FB: ret = GetCXM0FB(); break; case kCXM1FB: ret = GetCXM1FB(); break; case kCXBLPF: ret = GetCXBLPF(); break; case kCXPPMM: ret = GetCXPPMM(); break; case kINPT0: ret = GetINPT0(); break; case kINPT1: ret = GetINPT1(); break; case kINPT2: ret = GetINPT2(); break; case kINPT3: ret = GetINPT3(); break; case kINPT4: ret = GetINPT4(); break; case kINPT5: ret = GetINPT5(); break; default: // LOGERRORF("TIA::Unknown read addr 0x%02x", address); break; } if((address < kNumReadRegisters) && (bReadBreakpoints[address])) { Commands::Halt(true, Commands::HaltCommand::kHalt, "TIA read"); } return ret; } void Tia::Write(uint8_t address, uint8_t value) { switch(address) { case kVSYNC: SetVSYNC(value); break; case kVBLANK: SetVBLANK(value); break; case kWSYNC: SetWSYNC(value); break; case kRSYNC: SetRSYNC(value); break; case kNUSIZ0: SetNUSIZ0(value); break; case kNUSIZ1: SetNUSIZ1(value); break; case kCOLUP0: SetCOLUP0(value); break; case kCOLUP1: SetCOLUP1(value); break; case kCOLUPF: SetCOLUPF(value); break; case kCOLUBK: SetCOLUBK(value); break; case kCTRLPF: SetCTRLPF(value); break; case kREFP0: SetREFP0(value); break; case kREFP1: SetREFP1(value); break; case kPF0: SetPF0(value); break; case kPF1: SetPF1(value); break; case kPF2: SetPF2(value); break; case kRESP0: SetRESP0(value); break; case kRESP1: SetRESP1(value); break; case kRESM0: SetRESM0(value); break; case kRESM1: SetRESM1(value); break; case kRESBL: SetRESBL(value); break; case kAUDC0: SetAUDC0(value); break; case kAUDC1: SetAUDC1(value); break; case kAUDF0: SetAUDF0(value); break; case kAUDF1: SetAUDF1(value); break; case kAUDV0: SetAUDV0(value); break; case kAUDV1: SetAUDV1(value); break; case kGRP0: SetGRP0(value); break; case kGRP1: SetGRP1(value); break; case kENAM0: SetENAM0(value); break; case kENAM1: SetENAM1(value); break; case kENABL: SetENABL(value); break; case kHMP0: SetHMP0(value); break; case kHMP1: SetHMP1(value); break; case kHMM0: SetHMM0(value); break; case kHMBL: SetHMBL(value); break; case kVDELP0: SetVDELP0(value); break; case kVDELP1: SetVDELP1(value); break; case kVDELBL: SetVDELBL(value); break; case kRESMP0: SetRESMP0(value); break; case kRESMP1: SetRESMP1(value); break; case kHMOVE: SetHMOVE(value); break; case kHMCLR: SetHMCLR(value); break; case kCXCLR: SetCXCLR(value); break; default: break; } if((address < kNumWriteRegisters) && (bWriteBreakpoints[address])) { Commands::Halt(true, Commands::HaltCommand::kHalt, "TIA write"); } } bool Tia::HandleCommand(const std::shared_ptr<CommandBase> command) { #if 0 if(command.name == Commands::kHaltCommand) { if((command.payload == "false") && (command.payload2 == Commands::kHaltCommandTickTia)) { bHaltOnTick = true; } if((command.payload == "false") && (command.payload2 == Commands::kHaltCommandHBlank)) { bHaltOnHBlank = true; } if((command.payload == "false") && (command.payload2 == Commands::kHaltCommandVBlank)) { bHaltOnVBlank = true; } } #endif return false; } uint8_t Tia::GetCXM0P() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXM0P unimplemented"); #endif return readRegisters[kCXM0P]; } uint8_t Tia::GetCXM1P() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXM1P unimplemented"); #endif return readRegisters[kCXM1P]; } uint8_t Tia::GetCXP0FB() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXP0FB unimplemented"); #endif return readRegisters[kCXP0FB]; } uint8_t Tia::GetCXP1FB() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXP1FB unimplemented"); #endif return readRegisters[kCXP1FB]; } uint8_t Tia::GetCXM0FB() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXM0FB unimplemented"); #endif return readRegisters[kCXM0FB]; } uint8_t Tia::GetCXM1FB() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXM1FB unimplemented"); #endif return readRegisters[kCXM1FB]; } uint8_t Tia::GetCXBLPF() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXBLPF unimplemented"); #endif return readRegisters[kCXBLPF]; } uint8_t Tia::GetCXPPMM() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXPPMM unimplemented"); #endif return readRegisters[kCXPPMM]; } uint8_t Tia::GetINPT0() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::INPT0 unimplemented"); #endif return readRegisters[kINPT0]; } uint8_t Tia::GetINPT1() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::INPT1 unimplemented"); #endif return readRegisters[kINPT1]; } uint8_t Tia::GetINPT2() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::INPT2 unimplemented"); #endif return readRegisters[kINPT2]; } uint8_t Tia::GetINPT3() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::INPT3 unimplemented"); #endif return readRegisters[kINPT3]; } uint8_t Tia::GetINPT4() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::INPT4 unimplemented"); #endif return readRegisters[kINPT4]; } uint8_t Tia::GetINPT5() { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::INPT5 unimplemented"); #endif return readRegisters[kINPT5]; } uint8_t Tia::HOffsetToRealOffset(uint8_t offset) { if(offset < 8) { return offset + 8; } else { return offset - 8; } } void Tia::SetVSYNC(uint8_t val) { writeRegisters[kVSYNC] = val; if(val & 0x02) { Commands::VSync(); rasterY = 0; frameNum++; if(bHaltOnVBlank) { Commands::Halt(true, Commands::HaltCommand::kHalt, "TIA VSync"); bHaltOnVBlank = false; } } } void Tia::SetVBLANK(uint8_t val) { if(val != 0) { rasterCountLatched = rasterCount; rasterCount = 0; } writeRegisters[kVBLANK] = val; } void Tia::SetWSYNC(uint8_t val) { writeRegisters[kWSYNC] = 0x01; bCpuWaitingForHsync = true; } void Tia::SetRSYNC(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::RSYNC unimplemented"); #endif writeRegisters[kRSYNC] = val; } void Tia::SetNUSIZ0(uint8_t val) { writeRegisters[kNUSIZ0] = val; } void Tia::SetNUSIZ1(uint8_t val) { writeRegisters[kNUSIZ1] = val; } void Tia::SetCOLUP0(uint8_t val) { writeRegisters[kCOLUP0] = (val >> 1) & 0x7f; } void Tia::SetCOLUP1(uint8_t val) { writeRegisters[kCOLUP1] = (val >> 1) & 0x7f; } void Tia::SetCOLUPF(uint8_t val) { writeRegisters[kCOLUPF] = (val >> 1) & 0x7f; } void Tia::SetCOLUBK(uint8_t val) { writeRegisters[kCOLUBK] = (val >> 1) & 0x7f; } void Tia::SetCTRLPF(uint8_t val) { writeRegisters[kCTRLPF] = val; RebuildPlayfieldBits(); } void Tia::SetREFP0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::REFP0 unimplemented"); #endif writeRegisters[kREFP0] = val; } void Tia::SetREFP1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::REFP1 unimplemented"); #endif writeRegisters[kREFP1] = val; } void Tia::SetPF0(uint8_t val) { writeRegisters[kPF0] = val; RebuildPlayfieldBits(); } void Tia::SetPF1(uint8_t val) { writeRegisters[kPF1] = val; RebuildPlayfieldBits(); } void Tia::SetPF2(uint8_t val) { writeRegisters[kPF2] = val; RebuildPlayfieldBits(); } void Tia::SetRESP0(uint8_t val) { resP0Pos = rasterX - kHBlankClocks; resP0Pos += HOffsetToRealOffset(GetHMP0()); resP0Pos += 4; writeRegisters[kRESP0] = resP0Pos; RebuildSprite0Bits(); } void Tia::SetRESP1(uint8_t val) { resP1Pos = rasterX - kHBlankClocks; resP1Pos += HOffsetToRealOffset(GetHMP1()); resP1Pos += 4; writeRegisters[kRESP1] = resP1Pos; RebuildSprite1Bits(); } void Tia::SetRESM0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::RESM0 unimplemented"); #endif // resM0Pos = rasterX - kHBlankClocks; writeRegisters[kRESM0] = resM0Pos; } void Tia::SetRESM1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::RESM1 unimplemented"); #endif // resM1Pos = rasterX - kHBlankClocks; writeRegisters[kRESM1] = resM1Pos; } void Tia::SetRESBL(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::RESBL unimplemented"); #endif // resBLPos = rasterX - kHBlankClocks; writeRegisters[kRESBL] = resBLPos; } void Tia::SetAUDC0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::AUDC0 unimplemented"); #endif writeRegisters[kAUDC0] = val; } void Tia::SetAUDC1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::AUDC1 unimplemented"); #endif writeRegisters[kAUDC1] = val; } void Tia::SetAUDF0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::AUDF0 unimplemented"); #endif writeRegisters[kAUDF0] = val; } void Tia::SetAUDF1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::AUDF1 unimplemented"); #endif writeRegisters[kAUDF1] = val; } void Tia::SetAUDV0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::AUDV0 unimplemented"); #endif writeRegisters[kAUDV0] = val; } void Tia::SetAUDV1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::AUDV1 unimplemented"); #endif writeRegisters[kAUDV1] = val; } void Tia::SetGRP0(uint8_t val) { writeRegisters[kGRP0] = val; RebuildSprite0Bits(); } void Tia::SetGRP1(uint8_t val) { writeRegisters[kGRP1] = val; RebuildSprite1Bits(); } void Tia::SetENAM0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::ENAM0 unimplemented"); #endif writeRegisters[kENAM0] = val; } void Tia::SetENAM1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::ENAM1 unimplemented"); #endif writeRegisters[kENAM1] = val; } void Tia::SetENABL(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::ENABL unimplemented"); #endif writeRegisters[kENABL] = val; } void Tia::SetHMP0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::HMP0 unimplemented"); #endif writeRegisters[kHMP0] = val; } void Tia::SetHMP1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::HMP1 unimplemented"); #endif writeRegisters[kHMP1] = val; } void Tia::SetHMM0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::HMM0 unimplemented"); #endif writeRegisters[kHMM0] = val; } void Tia::SetHMM1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::HMM1 unimplemented"); #endif writeRegisters[kHMM1] = val; } void Tia::SetHMBL(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::HMBL unimplemented"); #endif writeRegisters[kHMBL] = val; } void Tia::SetVDELP0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::VDELP0 unimplemented"); #endif writeRegisters[kVDELP0] = val; } void Tia::SetVDELP1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::VDELP1 unimplemented"); #endif writeRegisters[kVDELP1] = val; } void Tia::SetVDELBL(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::VDELBL unimplemented"); #endif writeRegisters[kVDELBL] = val; } void Tia::SetRESMP0(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::RESMP0 unimplemented"); #endif writeRegisters[kRESMP0] = val; } void Tia::SetRESMP1(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::RESMP1 unimplemented"); #endif writeRegisters[kRESMP1] = val; } void Tia::SetHMOVE(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::HMOVE unimplemented"); #endif writeRegisters[kHMOVE] = val; } void Tia::SetHMCLR(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::HMCLR unimplemented"); #endif writeRegisters[kHMCLR] = val; } void Tia::SetCXCLR(uint8_t val) { #if HALT_ON_UNIMPLEMENTED Commands::Halt(true, "", "TIA::CXCLR unimplemented"); #endif writeRegisters[kCXCLR] = val; }
20.780149
89
0.617328
mslinklater
fbe95ed9c8f000ca556e89e544bddb85570b529b
560
cpp
C++
lab_03/libs/driver/src/objects/camera/camera.cpp
migregal/bmstu_iu7_oop
a17b2b5b5eaa175ae3ad4fa5a217b2664d4aa331
[ "MIT" ]
5
2021-05-24T20:03:38.000Z
2021-06-22T23:32:52.000Z
lab_03/libs/driver/src/objects/camera/camera.cpp
migregal/bmstu_iu7_oop
a17b2b5b5eaa175ae3ad4fa5a217b2664d4aa331
[ "MIT" ]
null
null
null
lab_03/libs/driver/src/objects/camera/camera.cpp
migregal/bmstu_iu7_oop
a17b2b5b5eaa175ae3ad4fa5a217b2664d4aa331
[ "MIT" ]
1
2021-06-17T19:32:26.000Z
2021-06-17T19:32:26.000Z
#include <objects/camera/camera.h> void Camera::move_x(const double &shift) { current_pos.set_x(current_pos.get_x() + shift); } void Camera::move_y(const double &shift) { current_pos.set_y(current_pos.get_y() + shift); } void Camera::move_z(const double &shift) { current_pos.set_z(current_pos.get_z() + shift); } void Camera::reform(const Point &new_pos, const Point &scale, const Point &turn) { move_x(new_pos.get_x()); move_y(new_pos.get_y()); } void Camera::accept(std::shared_ptr<Visitor> _visitor) { _visitor->visit(*this); }
25.454545
82
0.701786
migregal
fbeb2091c94ff64d61805860d3d5c87b6b3fa5b0
5,164
hpp
C++
src/treegen.hpp
ReallySnazzy/Xhaust
d53cef987ecec9456ec3b002639035e69500298a
[ "MIT" ]
1
2021-11-13T01:23:06.000Z
2021-11-13T01:23:06.000Z
src/treegen.hpp
ReallySnazzy/Xhaust
d53cef987ecec9456ec3b002639035e69500298a
[ "MIT" ]
null
null
null
src/treegen.hpp
ReallySnazzy/Xhaust
d53cef987ecec9456ec3b002639035e69500298a
[ "MIT" ]
null
null
null
#ifndef Treegen_hpp #define Treegen_hpp #include "lexer.hpp" #include <vector> #include <string> #include <iostream> #define TN_UNDEFINED -1 #define TN_FUNC_CALL 0 #define TN_GROUP 1 #define TN_VALUE 2 #define TN_OPERATOR 3 #define TN_BLOCK 4 #define TN_IF 5 #define TN_EXHAUST 6 #pragma region Nodes class TreeNode { public: int type = TN_UNDEFINED; TreeNode() = default; virtual ~TreeNode() = default; virtual void print(int level) const = 0; }; class FunctionCallNode : public TreeNode { public: const std::string functionName; const std::vector<TreeNode *> functionArguments; FunctionCallNode(std::string functionName, std::vector<TreeNode *> args) : functionName(functionName), functionArguments(args) { type = TN_FUNC_CALL; } virtual ~FunctionCallNode() { for (TreeNode *tn : functionArguments) if (tn != nullptr) delete tn; } virtual void print(int level) const { for (int i = 0; i < level; i++) std::cout << " "; std::cout << "FunctionCall : " << functionName << std::endl; for (TreeNode *node : functionArguments) node->print(level + 1); } }; class GroupNode : public TreeNode { public: const TreeNode *expression = nullptr; GroupNode(TreeNode *expr) : expression(expr) { type = TN_GROUP; } virtual ~GroupNode() { if (expression != nullptr) delete expression; expression = nullptr; } virtual void print(int level) const { for (int i = 0; i < level; i++) std::cout << " "; std::cout << "Group" << std::endl; expression->print(level + 1); } }; class ValueNode : public TreeNode { public: const std::string value; const bool isConstant; ValueNode(std::string value, bool isConstant) : value(value), isConstant(isConstant) { type = TN_VALUE; } virtual ~ValueNode() = default; virtual void print(int level) const { for (int i = 0; i < level; i++) std::cout << " "; std::cout << "Value : " << value << std::endl; } }; class BlockNode : public TreeNode { public: const std::vector<TreeNode *> body; BlockNode(std::vector<TreeNode *> body) : body(body) { type = TN_BLOCK; } ~BlockNode() { for (TreeNode *elem : body) delete elem; } virtual void print(int level) const { for (int i = 0; i < level; i++) std::cout << " "; std::cout << "Block" << std::endl; for (TreeNode *elem : body) elem->print(level + 1); } }; class ExhaustNode : public TreeNode { public: const TreeNode *condition; const TreeNode *body; const bool usesVariable; ExhaustNode(TreeNode *condition, TreeNode *body, bool usesVariable) : condition(condition), body(body), usesVariable(usesVariable) { type = TN_EXHAUST; } ~ExhaustNode() { delete condition; delete body; } virtual void print(int level) const { for (int i = 0; i < level; i++) { std::cout << " "; } std::cout << "Exhaust" << std::endl; condition->print(level + 1); body->print(level + 1); } }; class IfNode : public TreeNode { public: const TreeNode *condition; const TreeNode *body; IfNode(TreeNode *condition, TreeNode *body) : condition(condition), body(body) { type = TN_IF; } virtual ~IfNode() { delete condition; delete body; } virtual void print(int level) const { for (int i = 0; i < level; i++) std::cout << " "; std::cout << "If" << std::endl; condition->print(level + 1); body->print(level + 1); } }; class OperatorNode : public TreeNode { public: const std::string op; const TreeNode *lhs = nullptr, *rhs = nullptr; public: OperatorNode(std::string op, TreeNode *lhs, TreeNode *rhs) : op(op), lhs(lhs), rhs(rhs) { type = TN_OPERATOR; } virtual ~OperatorNode() { if (lhs != nullptr) delete lhs; if (rhs != nullptr) delete rhs; } virtual void print(int level) const { for (int i = 0; i < level; i++) std::cout << " "; std::cout << "Operator : " << op << std::endl; lhs->print(level + 1); rhs->print(level + 1); } }; #pragma endregion #pragma region TreeGenerator class TreeGenerator { public: std::vector<Token> tokens; int marker = 0; TreeNode *runningLHS = nullptr; TreeGenerator(std::vector<Token>); static TreeGenerator *fromString(std::string source); BlockNode *parseBlock(); ExhaustNode *parseExhaust(); IfNode *parseIf(); FunctionCallNode *parseFunctionCall(); GroupNode *parseGroup(); TreeNode *parseFactor(); OperatorNode *parseBinaryOperation(); TreeNode *parseExpression(); TreeNode *parseConditional(); TreeNode *parseStatement(); std::vector<TreeNode *> buildTree(); }; #pragma endregion #endif
22.258621
134
0.577072
ReallySnazzy
fbedf45fc81550fc7986b9bd4618030034ba67ab
3,279
cpp
C++
redemption/tests/mod/internal/test_login_mod.cpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/tests/mod/internal/test_login_mod.cpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/tests/mod/internal/test_login_mod.cpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Product name: redemption, a FLOSS RDP proxy Copyright (C) Wallix 2013 Author(s): Christophe Grosjean, Meng Tan */ #include "test_only/test_framework/redemption_unit_tests.hpp" #include "configs/config.hpp" #include "core/RDP/capabilities/window.hpp" #include "RAIL/client_execute.hpp" #include "mod/internal/login_mod.hpp" #include "gdi/graphic_api.hpp" #include "keyboard/keymap.hpp" #include "keyboard/keylayouts.hpp" #include "test_only/front/fake_front.hpp" #include "test_only/core/font.hpp" #include "core/events.hpp" RED_AUTO_TEST_CASE(TestLoginMod) { ScreenInfo screen_info{800, 600, BitsPerPixel{24}}; FakeFront front(screen_info); WindowListCaps window_list_caps; EventContainer events; ClientExecute client_execute(events.get_time_base(), front.gd(), front, window_list_caps, false); Inifile ini; Theme theme; Keymap keymap(*find_layout_by_id(KeyLayout::KbdId(0x040C))); RED_CHECK_NE(ini.get<cfg::globals::auth_user>(), "user"); RED_CHECK_NE(ini.get<cfg::context::password>(), "pass"); LoginMod d(ini, events, "user", "pass", front.gd(), front, screen_info.width, screen_info.height, Rect(0, 0, 799, 599), client_execute, global_font(), theme); d.init(); keymap.event(Keymap::KbdFlags(), Keymap::Scancode(0x1c)); // enter d.rdp_input_scancode(Keymap::KbdFlags(), Keymap::Scancode(0x1c), 0, keymap); RED_CHECK_EQUAL(ini.get<cfg::globals::auth_user>(), "user"); RED_CHECK_EQUAL(ini.get<cfg::context::password>(), "pass"); } RED_AUTO_TEST_CASE(TestLoginMod2) { ScreenInfo screen_info{2048, 1536, BitsPerPixel{24}}; FakeFront front(screen_info); WindowListCaps window_list_caps; EventManager event_manager; auto& events = event_manager.get_events(); ClientExecute client_execute(events.get_time_base(), front.gd(), front, window_list_caps, false); Inifile ini; Theme theme; ini.set<cfg::globals::authentication_timeout>(std::chrono::seconds(1)); LoginMod d(ini, events, "user", "pass", front.gd(), front, screen_info.width, screen_info.height, Rect(1024, 768, 1023, 767), client_execute, global_font(), theme); d.init(); using namespace std::literals::chrono_literals; event_manager.execute_events([](int){return false;}, false); RED_CHECK_EQUAL(BACK_EVENT_NONE, d.get_mod_signal()); event_manager.get_writable_time_base().monotonic_time = MonotonicTimePoint{2s + 1us}; event_manager.execute_events([](int){return false;}, false); RED_CHECK_EQUAL(BACK_EVENT_STOP, d.get_mod_signal()); }
36.842697
101
0.727356
DianaAssistant
fbf053ec7d876df54b5204a299e6fd3d8d4612fb
2,491
cpp
C++
tests/test_broker_shell.cpp
ETCLabs/RDMnetBroker
c71ebec3e187b2a560f37ff37ffe9b442f609f83
[ "Apache-2.0" ]
null
null
null
tests/test_broker_shell.cpp
ETCLabs/RDMnetBroker
c71ebec3e187b2a560f37ff37ffe9b442f609f83
[ "Apache-2.0" ]
2
2019-09-13T13:39:56.000Z
2019-10-29T22:21:45.000Z
tests/test_broker_shell.cpp
ETCLabs/RDMnetBroker
c71ebec3e187b2a560f37ff37ffe9b442f609f83
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2019 ETC Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************** * This file is a part of RDMnetBroker. For more information, go to: * https://github.com/ETCLabs/RDMnetBroker *****************************************************************************/ #include "broker_shell.h" #include "gmock/gmock.h" #include "broker_os_interface.h" using testing::_; using testing::ByMove; using testing::Return; class MockBrokerOsInterface : public BrokerOsInterface { public: MOCK_METHOD(std::string, GetLogFilePath, (), (const override)); MOCK_METHOD(bool, OpenLogFile, (), (override)); MOCK_METHOD((std::pair<std::string, std::ifstream>), GetConfFile, (rdmnet::BrokerLog & log), (override)); MOCK_METHOD(void, GetLogTime, (EtcPalLogTimeParams & time), (override)); MOCK_METHOD(void, OutputLogMsg, (const std::string& msg), (override)); }; class TestBrokerShell : public testing::Test { protected: TestBrokerShell() { ON_CALL(os_interface_, OpenLogFile()).WillByDefault(Return(true)); // ON_CALL(os_interface_, GetConfFile(_)).WillByDefault(Return(true)); } testing::NiceMock<MockBrokerOsInterface> os_interface_; BrokerShell shell_{os_interface_}; }; // TODO - if these tests don't work as expected, we might start a real broker and enter an infinite // loop. This will be caught by the CTest timeout but it's not ideal. RDMNET-137 has been created // to track making the broker mockable to avoid this situation. TEST_F(TestBrokerShell, DoesNotStartIfOpenLogFileFails) { EXPECT_CALL(os_interface_, OpenLogFile()).WillOnce(Return(false)); EXPECT_FALSE(shell_.Run()); } TEST_F(TestBrokerShell, DoesNotStartIfGetConfFileFails) { EXPECT_CALL(os_interface_, GetConfFile(_)).WillOnce(Return(ByMove(std::make_pair("fake_path", std::ifstream{})))); EXPECT_FALSE(shell_.Run()); }
37.179104
116
0.676837
ETCLabs
fbf2c66e90cf093c588233d6da46a9ba674c7471
4,629
cpp
C++
thirdparty/webm/src/libmkv/EbmlWriter.cpp
WowaBBS/CrashRpt
edcec3751df1e0d4e92a71560ff5b91b0abafd1e
[ "BSD-3-Clause" ]
37
2017-06-01T23:38:05.000Z
2020-11-06T02:29:47.000Z
thirdparty/webm/src/libmkv/EbmlWriter.cpp
WowaBBS/CrashRpt
edcec3751df1e0d4e92a71560ff5b91b0abafd1e
[ "BSD-3-Clause" ]
11
2017-07-26T01:22:37.000Z
2021-01-08T07:27:02.000Z
thirdparty/webm/src/libmkv/EbmlWriter.cpp
WowaBBS/CrashRpt
edcec3751df1e0d4e92a71560ff5b91b0abafd1e
[ "BSD-3-Clause" ]
20
2018-01-07T00:13:08.000Z
2021-01-08T07:54:03.000Z
// Copyright (c) 2010 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "EbmlWriter.h" #include <stdlib.h> #include <wchar.h> #include <string.h> #include <limits.h> #if defined(_MSC_VER) #define LITERALU64(n) n #else #define LITERALU64(n) n##LLU #endif void Ebml_WriteLen(EbmlGlobal *glob, long long val) { //TODO check and make sure we are not > than 0x0100000000000000LLU unsigned char size = 8; //size in bytes to output unsigned long long minVal = LITERALU64(0x00000000000000ff); //mask to compare for byte size for (size = 1; size < 8; size ++) { if (val < minVal) break; minVal = (minVal << 7); } val |= (LITERALU64(0x000000000000080) << ((size - 1) * 7)); Ebml_Serialize(glob, (void *) &val, sizeof(val), size); } void Ebml_WriteString(EbmlGlobal *glob, const char *str) { const size_t size_ = strlen(str); const unsigned long long size = size_; Ebml_WriteLen(glob, size); //TODO: it's not clear from the spec whether the nul terminator //should be serialized too. For now we omit the null terminator. Ebml_Write(glob, str, size); } void Ebml_WriteUTF8(EbmlGlobal *glob, const wchar_t *wstr) { const size_t strlen = wcslen(wstr); //TODO: it's not clear from the spec whether the nul terminator //should be serialized too. For now we include it. const unsigned long long size = strlen; Ebml_WriteLen(glob, size); Ebml_Write(glob, wstr, size); } void Ebml_WriteID(EbmlGlobal *glob, unsigned long class_id) { int len; if (class_id >= 0x01000000) len = 4; else if (class_id >= 0x00010000) len = 3; else if (class_id >= 0x00000100) len = 2; else len = 1; Ebml_Serialize(glob, (void *)&class_id, sizeof(class_id), len); } void Ebml_SerializeUnsigned64(EbmlGlobal *glob, unsigned long class_id, uint64_t ui) { unsigned char sizeSerialized = 8 | 0x80; Ebml_WriteID(glob, class_id); Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1); Ebml_Serialize(glob, &ui, sizeof(ui), 8); } void Ebml_SerializeUnsigned(EbmlGlobal *glob, unsigned long class_id, unsigned long ui) { unsigned char size = 8; //size in bytes to output unsigned char sizeSerialized = 0; unsigned long minVal; Ebml_WriteID(glob, class_id); minVal = 0x7fLU; //mask to compare for byte size for (size = 1; size < 4; size ++) { if (ui < minVal) { break; } minVal <<= 7; } sizeSerialized = 0x80 | size; Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1); Ebml_Serialize(glob, &ui, sizeof(ui), size); } //TODO: perhaps this is a poor name for this id serializer helper function void Ebml_SerializeBinary(EbmlGlobal *glob, unsigned long class_id, unsigned long bin) { int size; for (size=4; size > 1; size--) { if (bin & 0x000000ff << ((size-1) * 8)) break; } Ebml_WriteID(glob, class_id); Ebml_WriteLen(glob, size); Ebml_WriteID(glob, bin); } void Ebml_SerializeFloat(EbmlGlobal *glob, unsigned long class_id, double d) { unsigned char len = 0x88; Ebml_WriteID(glob, class_id); Ebml_Serialize(glob, &len, sizeof(len), 1); Ebml_Serialize(glob, &d, sizeof(d), 8); } void Ebml_WriteSigned16(EbmlGlobal *glob, short val) { signed long out = ((val & 0x003FFFFF) | 0x00200000) << 8; Ebml_Serialize(glob, &out, sizeof(out), 3); } void Ebml_SerializeString(EbmlGlobal *glob, unsigned long class_id, const char *s) { Ebml_WriteID(glob, class_id); Ebml_WriteString(glob, s); } void Ebml_SerializeUTF8(EbmlGlobal *glob, unsigned long class_id, wchar_t *s) { Ebml_WriteID(glob, class_id); Ebml_WriteUTF8(glob, s); } void Ebml_SerializeData(EbmlGlobal *glob, unsigned long class_id, unsigned char *data, unsigned long data_length) { Ebml_WriteID(glob, class_id); Ebml_WriteLen(glob, data_length); Ebml_Write(glob, data, data_length); } void Ebml_WriteVoid(EbmlGlobal *glob, unsigned long vSize) { unsigned char tmp = 0; unsigned long i = 0; Ebml_WriteID(glob, 0xEC); Ebml_WriteLen(glob, vSize); for (i = 0; i < vSize; i++) { Ebml_Write(glob, &tmp, 1); } } //TODO Serialize Date
26.912791
113
0.667531
WowaBBS
fbf529aef311fabf5aee4dd95a35beab0236324e
539
cpp
C++
Source/StdLib/Terminal.cpp
FoxCutter/BootDebug
d40afa3a19d8a840788cbdb091cc121b01b36f7f
[ "BSD-2-Clause" ]
null
null
null
Source/StdLib/Terminal.cpp
FoxCutter/BootDebug
d40afa3a19d8a840788cbdb091cc121b01b36f7f
[ "BSD-2-Clause" ]
1
2020-02-15T03:11:11.000Z
2020-02-15T03:11:11.000Z
Source/StdLib/Terminal.cpp
FoxCutter/BootDebug
d40afa3a19d8a840788cbdb091cc121b01b36f7f
[ "BSD-2-Clause" ]
null
null
null
#include "Terminal.h" #include <windows.h> #pragma comment(linker, "/defaultlib:kernel32.lib") // This file should have the majority of OS dependent code in it. // //int Write(const char *szData, int cbLength) //{ // DWORD cbWritten; // // WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), szData, cbLength, &cbWritten, nullptr); // // return cbWritten; //} // //int Read(char *Buffer, int cbLength) //{ // DWORD ReadCount; // // ReadFile(GetStdHandle(STD_INPUT_HANDLE), Buffer, cbLength, & ReadCount, nullptr); // // return ReadCount; //}
22.458333
85
0.695733
FoxCutter
fbf8d1b83d1c52c5353e1aa8d20299bef818b135
2,922
cpp
C++
examples/stm32f4_discovery/colour_tcs3414/main.cpp
roboterclubaachen/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
161
2015-01-13T15:52:06.000Z
2020-02-13T01:26:04.000Z
examples/stm32f4_discovery/colour_tcs3414/main.cpp
salkinium/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
281
2015-01-06T12:46:40.000Z
2019-01-06T13:06:57.000Z
examples/stm32f4_discovery/colour_tcs3414/main.cpp
salkinium/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
51
2015-03-03T19:56:12.000Z
2020-03-22T02:13:36.000Z
#include <xpcc/architecture/platform.hpp> #include <xpcc/processing.hpp> #include <xpcc/processing/protothread.hpp> #include <xpcc/driver/color/tcs3414.hpp> #include <xpcc/io/iostream.hpp> #include <xpcc/architecture/interface/gpio.hpp> xpcc::IODeviceWrapper< Usart2, xpcc::IOBuffer::BlockIfFull > device; xpcc::IOStream stream(device); /** * Example to demonstrate a XPCC driver for colour sensor TCS3414 * * This example uses I2cMaster2 of STM32F407 * * SDA PB11 * SCL PB10 * * GND and +3V3 are connected to the colour sensor. * */ // typedef I2cMaster1 MyI2cMaster; typedef I2cMaster2 MyI2cMaster; // typedef xpcc::SoftwareI2cMaster<GpioB10, GpioB11> MyI2cMaster; class ThreadOne : public xpcc::pt::Protothread { public: ThreadOne() : colorSensor() { } bool update() { PT_BEGIN(); stream << "Ping the device from ThreadOne" << xpcc::endl; // ping the device until it responds while (true) { // we wait until the task started if (PT_CALL(colorSensor.ping())) { break; } // otherwise, try again in 100ms this->timeout.restart(100); PT_WAIT_UNTIL(this->timeout.isExpired()); } stream << "Device responded" << xpcc::endl; while (true) { if (PT_CALL(colorSensor.initialize())) { break; } // otherwise, try again in 100ms this->timeout.restart(100); PT_WAIT_UNTIL(this->timeout.isExpired()); } stream << "Device initialized" << xpcc::endl; while (true) { if (PT_CALL(colorSensor.configure( xpcc::tcs3414::Gain::X16, xpcc::tcs3414::Prescaler::DEFAULT, xpcc::tcs3414::IntegrationMode::INTERNAL, static_cast<uint8_t>(xpcc::tcs3414::NominalIntegrationTime::MSEC_100)))){ break; } // otherwise, try again in 100ms this->timeout.restart(100); PT_WAIT_UNTIL(this->timeout.isExpired()); } stream << "Device configured" << xpcc::endl; while (true) { if (PT_CALL(colorSensor.refreshAllColors())) { auto colors = colorSensor.getOldColors(); stream.printf("RGB: %5d %5d %5d", colors.red, colors.green, colors.blue); xpcc::color::HsvT<xpcc::tcs3414::UnderlyingType> hsv; colors.toHsv(&hsv); stream.printf(" %5d\n", hsv.hue); } this->timeout.restart(500); PT_WAIT_UNTIL(this->timeout.isExpired()); } PT_END(); } private: xpcc::ShortTimeout timeout; xpcc::Tcs3414<MyI2cMaster> colorSensor; }; ThreadOne one; // ---------------------------------------------------------------------------- int main() { Board::initialize(); GpioOutputA2::connect(Usart2::Tx); Usart2::initialize<Board::systemClock, xpcc::Uart::B115200>(10); GpioB11::connect(I2cMaster2::Sda); GpioB10::connect(I2cMaster2::Scl); MyI2cMaster::initialize<Board::systemClock, 100000>(); stream << "\n\nWelcome to TCS3414 demo!\n\n"; xpcc::ShortPeriodicTimer tmr(500); while (1) { one.update(); if (tmr.execute()) { Board::LedOrange::toggle(); } } return 0; }
21.173913
79
0.658453
roboterclubaachen
fbfd2db8645cb6cff30f8935edf5cb2a0baa4ec2
2,509
hpp
C++
old/include/mp/adjacency_list/edges_ending_at.hpp
SuperV1234/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
475
2016-05-03T13:34:30.000Z
2021-11-26T07:02:47.000Z
old/include/mp/adjacency_list/edges_ending_at.hpp
vittorioromeo/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
28
2016-08-30T06:37:40.000Z
2017-11-24T11:14:07.000Z
old/include/mp/adjacency_list/edges_ending_at.hpp
vittorioromeo/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
60
2016-05-11T22:16:15.000Z
2021-08-02T20:42:35.000Z
// Copyright (c) 2015-2016 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 // http://vittorioromeo.info | vittorio.romeo@outlook.com #pragma once #include <ecst/config.hpp> #include <ecst/mp/edge.hpp> #include <ecst/mp/adjacency_list/ndp.hpp> #include <ecst/mp/adjacency_list/edges.hpp> ECST_MP_ADJACENCY_LIST_NAMESPACE { namespace impl { template <typename TNDPList, typename TNode> constexpr auto find_ndp_with_goal_from_ndl_list(TNDPList ndpl, TNode n) { return list::find_if(ndpl, [=](auto ndp) { return same_type_decay(ndp_goal(ndp), n); }); } template <typename TALKVP, typename TNode> constexpr auto al_kvp_has_goal(TALKVP al_kvp, TNode n) { return bool_v<!decltype(is_null( find_ndp_with_goal_from_ndl_list(map::value(al_kvp), n))){}>; } template <typename TAList, typename TNode> constexpr auto edges_ending_at_impl(TAList al, TNode n) { return list::fold_l(list::empty_v, [=](auto acc, auto x_kvp) { // Find `n` in the list of goals of `x_kvp`. auto ndp = find_ndp_with_goal_from_ndl_list(map::value(x_kvp), n); return static_if(is_null(ndp)) .then([=](auto) { return acc; }) .else_([=](auto x_ndp) { return list::append( acc, to_edge(map::key(x_kvp), x_ndp)); })(ndp); }, impl::unwrap(al)); } } /// @brief Returns a list of edges ending at `n`. /// @details Does not currently support multiple edges with same start/goal /// nodes (TODO). template <typename TAList, typename TNode> constexpr auto edges_ending_at(TAList al, TNode n) { return decltype(impl::edges_ending_at_impl(al, n)){}; } /// @brief Returns the count of edges ending at `n`. template <typename TAList, typename TNode> constexpr auto count_edges_ending_at(TAList al, TNode n) { return list::size(edges_ending_at(al, n)); } } ECST_MP_ADJACENCY_LIST_NAMESPACE_END
33.453333
79
0.540454
SuperV1234
2201bd472dcbde16e135723d4ff2b377b1f726ff
28,647
cpp
C++
iSeg/ImageViewerWidget.cpp
ITISFoundation/osparc-iseg
6f38924120b3a3e7a0292914d2c17f24c735309b
[ "MIT" ]
32
2018-03-26T12:39:19.000Z
2022-03-22T20:54:22.000Z
iSeg/ImageViewerWidget.cpp
dyollb/osparc-iseg
6f38924120b3a3e7a0292914d2c17f24c735309b
[ "MIT" ]
10
2018-04-03T15:54:22.000Z
2022-02-01T14:32:36.000Z
iSeg/ImageViewerWidget.cpp
dyollb/osparc-iseg
6f38924120b3a3e7a0292914d2c17f24c735309b
[ "MIT" ]
11
2018-03-08T13:11:28.000Z
2021-02-01T10:43:39.000Z
/* * Copyright (c) 2021 The Foundation for Research on Information Technologies in Society (IT'IS). * * This file is part of iSEG * (see https://github.com/ITISFoundation/osparc-iseg). * * This software is released under the MIT License. * https://opensource.org/licenses/MIT */ #include "Precompiled.h" #include "ImageViewerWidget.h" #include "SlicesHandler.h" #include "TissueInfos.h" #include "bmp_read_1.h" #include "Interface/QtConnect.h" #include "Core/ColorLookupTable.h" #include "Data/ExtractBoundary.h" #include "Data/Point.h" #include <QAction> #include <QApplication> #include <QCloseEvent> #include <QColor> #include <QContextMenuEvent> #include <QEvent> #include <QImage> #include <QInputDialog> #include <QLineEdit> #include <QMenu> #include <QMouseEvent> #include <QPaintEvent> #include <QPainter> #include <QPen> #include <QWheelEvent> #include <algorithm> #include <cassert> #include <cmath> #include <sstream> #include <string> namespace iseg { ImageViewerWidget::ImageViewerWidget(QWidget* parent, Qt::WindowFlags wFlags) : QWidget(parent, wFlags) //,showvp(false) { m_Brightness = m_Scaleoffset = 0.0f; m_Contrast = m_Scalefactor = 1.0f; m_Mode = 1; m_Zoom = 1.0; m_Pixelsize.high = m_Pixelsize.low = 1.0f; m_Workborderlimit = true; m_ActualColor.setRgb(255, 255, 255); m_OutlineColor.setRgb(255, 255, 255); m_Crosshairxpos = 0; m_Crosshairypos = 0; m_Marks = nullptr; m_Overlayalpha = 0.0f; m_Selecttissue = new QAction("Select Tissue", this); m_Addtoselection = new QAction("Select Tissue", this); m_Viewtissue = new QAction("View Tissue Surface", this); m_Viewtarget = new QAction("View Target Surface", this); m_Nexttargetslice = new QAction("Next Target Slice", this); m_Addmark = new QAction("&Add Mark", this); m_Addlabel = new QAction("Add &Label", this); m_Removemark = new QAction("&Remove Mark", this); m_Clearmarks = new QAction("&Clear Marks", this); m_Addtissue = new QAction("Add &Tissue", this); m_Addtissueconnected = new QAction("Add Tissue &Conn", this); m_Addtissue3D = new QAction("Add Tissue 3&D", this); m_Subtissue = new QAction("&Subtract Tissue", this); m_Addtissuelarger = new QAction("Add Tissue &Larger", this); QObject_connect(m_Addmark, SIGNAL(activated()), this, SLOT(AddMark())); QObject_connect(m_Addlabel, SIGNAL(activated()), this, SLOT(AddLabel())); QObject_connect(m_Clearmarks, SIGNAL(activated()), this, SLOT(ClearMarks())); QObject_connect(m_Removemark, SIGNAL(activated()), this, SLOT(RemoveMark())); QObject_connect(m_Addtissue, SIGNAL(activated()), this, SLOT(AddTissue())); QObject_connect(m_Addtissueconnected, SIGNAL(activated()), this, SLOT(AddTissueConnected())); QObject_connect(m_Subtissue, SIGNAL(activated()), this, SLOT(SubTissue())); QObject_connect(m_Addtissue3D, SIGNAL(activated()), this, SLOT(AddTissue3D())); QObject_connect(m_Addtissuelarger, SIGNAL(activated()), this, SLOT(AddTissuelarger())); QObject_connect(m_Selecttissue, SIGNAL(activated()), this, SLOT(SelectTissue())); QObject_connect(m_Addtoselection, SIGNAL(activated()), this, SLOT(AddToSelectedTissues())); QObject_connect(m_Viewtissue, SIGNAL(activated()), this, SLOT(ViewTissueSurface())); QObject_connect(m_Viewtarget, SIGNAL(activated()), this, SLOT(ViewTargetSurface())); QObject_connect(m_Nexttargetslice, SIGNAL(activated()), this, SLOT(NextTargetSlice())); } ImageViewerWidget::~ImageViewerWidget() { delete m_Addmark; delete m_Addlabel; delete m_Removemark; delete m_Clearmarks; delete m_Addtissue; delete m_Addtissueconnected; delete m_Addtissue3D; delete m_Subtissue; delete m_Addtissuelarger; delete m_Selecttissue; delete m_Addtoselection; } void ImageViewerWidget::ModeChanged(unsigned char newmode, bool updatescale) { if (newmode != 0 && m_Mode != newmode) { m_Mode = newmode; if (updatescale) { UpdateScaleoffsetfactor(); } } } void ImageViewerWidget::GetScaleoffsetfactor(float& offset1, float& factor1) const { offset1 = m_Scaleoffset; factor1 = m_Scalefactor; } void ImageViewerWidget::SetZoom(double z) { if (z != m_Zoom) { //QPoint oldCenter = visibleRegion().boundingRect().center(); QPoint old_center = rect().center(); QPoint new_center; if (m_MousePosZoom.x() == 0 && m_MousePosZoom.y() == 0) { new_center = z * old_center / m_Zoom; } else { new_center = m_Zoom * (old_center + z * m_MousePosZoom / m_Zoom - m_MousePosZoom) / z; } m_Zoom = z; int const w = static_cast<int>(m_Width) * m_Zoom * m_Pixelsize.high; int const h = static_cast<int>(m_Height) * m_Zoom * m_Pixelsize.low; setFixedSize(w, h); if (m_MousePosZoom.x() != 0 && m_MousePosZoom.y() != 0) { emit SetcenterSign(new_center.x(), new_center.y()); } } } void ImageViewerWidget::PixelsizeChanged(Pair pixelsize1) { if (pixelsize1.high != m_Pixelsize.high || pixelsize1.low != m_Pixelsize.low) { m_Pixelsize = pixelsize1; setFixedSize((int)m_Width * m_Zoom * m_Pixelsize.high, (int)m_Height * m_Zoom * m_Pixelsize.low); repaint(); } } void ImageViewerWidget::paintEvent(QPaintEvent* e) { m_Marks = m_Handler3D->GetActivebmphandler()->ReturnMarks(); if (m_Image.size() != QSize(0, 0)) // is an image loaded? { { QPainter painter(this); painter.setClipRect(e->rect()); painter.scale(m_Zoom * m_Pixelsize.high, m_Zoom * m_Pixelsize.low); painter.drawImage(0, 0, m_ImageDecorated); painter.setPen(QPen(m_ActualColor)); if (m_Marks != nullptr) { unsigned char r, g, b; for (auto& m : *m_Marks) { std::tie(r, g, b) = TissueInfos::GetTissueColorMapped(m.mark); QColor qc1(r, g, b); painter.setPen(QPen(qc1)); painter.drawLine(int(m.p.px) - 2, int(m_Height - m.p.py) - 3, int(m.p.px) + 2, int(m_Height - m.p.py) + 1); painter.drawLine(int(m.p.px) - 2, int(m_Height - m.p.py) + 1, int(m.p.px) + 2, int(m_Height - m.p.py) - 3); if (!m.name.empty()) { painter.drawText(int(m.p.px) + 3, int(m_Height - m.p.py) + 1, QString(m.name.c_str())); } } } } { QPainter painter1(this); float dx = m_Zoom * m_Pixelsize.high; float dy = m_Zoom * m_Pixelsize.low; for (auto& p : m_Vpdyn) { painter1.fillRect(int(dx * p.px), int(dy * (m_Height - p.py - 1)), int(dx + 0.999f), int(dy + 0.999f), m_ActualColor); } } } } void ImageViewerWidget::BmpChanged() { update(); } void ImageViewerWidget::SlicenrChanged() { m_Activeslice = m_Handler3D->ActiveSlice(); BmphandChanged(m_Handler3D->GetActivebmphandler()); } void ImageViewerWidget::BmphandChanged(Bmphandler* bmph) { m_Bmphand = bmph; if (m_Bmporwork) m_Bmpbits = bmph->ReturnBmpfield(); else m_Bmpbits = bmph->ReturnWorkfield(); m_Tissue = bmph->ReturnTissuefield(m_Handler3D->ActiveTissuelayer()); m_Marks = bmph->ReturnMarks(); ModeChanged(bmph->ReturnMode(m_Bmporwork), false); UpdateScaleoffsetfactor(); ReloadBits(); if (m_Workborder) { if (m_Bmporwork) { WorkborderChanged(); } } else { repaint(); } } void ImageViewerWidget::OverlayChanged() { ReloadBits(); repaint(); } void ImageViewerWidget::OverlayChanged(QRect rect) { ReloadBits(); repaint((int)(rect.left() * m_Zoom * m_Pixelsize.high), (int)((m_Height - 1 - rect.bottom()) * m_Zoom * m_Pixelsize.low), (int)ceil(rect.width() * m_Zoom * m_Pixelsize.high), (int)ceil(rect.height() * m_Zoom * m_Pixelsize.low)); } void ImageViewerWidget::update() { QRect rect; rect.setLeft(0); rect.setTop(0); rect.setRight(m_Width - 1); rect.setBottom(m_Height - 1); update(rect); } void ImageViewerWidget::update(QRect rect) { m_Bmphand = m_Handler3D->GetActivebmphandler(); m_Overlaybits = m_Handler3D->ReturnOverlay(); ModeChanged(m_Bmphand->ReturnMode(m_Bmporwork), false); UpdateScaleoffsetfactor(); if (m_Bmporwork) m_Bmpbits = m_Bmphand->ReturnBmpfield(); else m_Bmpbits = m_Bmphand->ReturnWorkfield(); m_Tissue = m_Bmphand->ReturnTissuefield(m_Handler3D->ActiveTissuelayer()); m_Marks = m_Bmphand->ReturnMarks(); if (m_Bmphand->ReturnWidth() != m_Width || m_Bmphand->ReturnHeight() != m_Height) { m_Vp.clear(); m_VpOld.clear(); m_Vp1.clear(); m_Vp1Old.clear(); m_Vpdyn.clear(); m_VpdynOld.clear(); m_Vm.clear(); m_VmOld.clear(); m_Width = m_Bmphand->ReturnWidth(); m_Height = m_Bmphand->ReturnHeight(); m_Image.create(int(m_Width), int(m_Height), 32); m_ImageDecorated.create(int(m_Width), int(m_Height), 32); setFixedSize((int)m_Width * m_Zoom * m_Pixelsize.high, (int)m_Height * m_Zoom * m_Pixelsize.low); if (m_Bmporwork && m_Workborder) { ReloadBits(); WorkborderChanged(); return; } } ReloadBits(); repaint((int)(rect.left() * m_Zoom * m_Pixelsize.high), (int)((m_Height - 1 - rect.bottom()) * m_Zoom * m_Pixelsize.low), (int)ceil(rect.width() * m_Zoom * m_Pixelsize.high), (int)ceil(rect.height() * m_Zoom * m_Pixelsize.low)); } void ImageViewerWidget::Init(SlicesHandler* hand3D, bool bmporwork1) { m_Handler3D = hand3D; m_Activeslice = m_Handler3D->ActiveSlice(); m_Bmphand = m_Handler3D->GetActivebmphandler(); m_Overlaybits = m_Handler3D->ReturnOverlay(); m_Bmporwork = bmporwork1; if (m_Bmporwork) m_Bmpbits = m_Bmphand->ReturnBmpfield(); else m_Bmpbits = m_Bmphand->ReturnWorkfield(); m_Tissue = m_Bmphand->ReturnTissuefield(hand3D->ActiveTissuelayer()); m_Width = m_Bmphand->ReturnWidth(); m_Height = m_Bmphand->ReturnHeight(); m_Marks = m_Bmphand->ReturnMarks(); m_Image.create(int(m_Width), int(m_Height), 32); m_ImageDecorated.create(int(m_Width), int(m_Height), 32); setFixedSize((int)m_Width * m_Zoom * m_Pixelsize.high, (int)m_Height * m_Zoom * m_Pixelsize.low); setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); ModeChanged(m_Bmphand->ReturnMode(m_Bmporwork), false); UpdateRange(); UpdateScaleoffsetfactor(); ReloadBits(); if (m_Workborder) { if (m_Bmporwork) WorkborderChanged(); else repaint(); } show(); } void ImageViewerWidget::UpdateRange() { // Recompute ranges for all slices if (m_Bmporwork) { m_Handler3D->ComputeBmprangeMode1(&m_RangeMode1); } else { m_Handler3D->ComputeRangeMode1(&m_RangeMode1); } } void ImageViewerWidget::UpdateRange(unsigned short slicenr) { // Recompute range only for single slice if (m_Bmporwork) { m_Handler3D->ComputeBmprangeMode1(slicenr, &m_RangeMode1); } else { m_Handler3D->ComputeRangeMode1(slicenr, &m_RangeMode1); } } void ImageViewerWidget::ReloadBits() { auto color_lut = m_Handler3D->GetColorLookupTable(); float* bmpbits1 = *m_Bmpbits; tissues_size_t* tissue1 = *m_Tissue; unsigned pos = 0; int f; unsigned char r, g, b; for (int y = m_Height - 1; y >= 0; y--) { for (int x = 0; x < m_Width; x++) { if (m_Picturevisible) { if (color_lut && m_Bmporwork) { // \todo not sure if we should allow to 'scale & offset & clamp' when a color lut is available //f = max(0.0f, min(255.0f, scaleoffset + scalefactor * (bmpbits1)[pos])); color_lut->GetColor((bmpbits1)[pos], r, g, b); } else { r = g = b = (int)std::max(0.0f, std::min(255.0f, m_Scaleoffset + m_Scalefactor * (bmpbits1)[pos])); } // overlay only visible if picture is visible if (m_Overlayvisible) { f = std::max(0.0f, std::min(255.0f, m_Scaleoffset + m_Scalefactor * (m_Overlaybits)[pos])); r = (1.0f - m_Overlayalpha) * r + m_Overlayalpha * f; g = (1.0f - m_Overlayalpha) * g + m_Overlayalpha * f; b = (1.0f - m_Overlayalpha) * b + m_Overlayalpha * f; } } else { r = g = b = 0; } if (m_Tissuevisible && tissue1[pos] != 0) { // blend with tissue color auto rgbo = TissueInfos::GetTissueColor(tissue1[pos]); float alpha = 0.5f; r = static_cast<unsigned char>(r + alpha * (255.0f * rgbo[0] - r)); g = static_cast<unsigned char>(g + alpha * (255.0f * rgbo[1] - g)); b = static_cast<unsigned char>(b + alpha * (255.0f * rgbo[2] - b)); m_Image.setPixel(x, y, qRgb(r, g, b)); } else // no tissue { m_Image.setPixel(x, y, qRgb(r, g, b)); } pos++; } } // copy to decorated image m_ImageDecorated = m_Image; // now decorate QRgb color_used = m_ActualColor.rgb(); QRgb color_dim = (m_ActualColor.light(30)).rgb(); if (m_Workborder && m_Bmporwork && ((!m_Workborderlimit) || (unsigned)m_Vp.size() < unsigned(m_Width) * m_Height / 5)) { for (auto& p : m_Vp) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), color_dim); } } for (auto& p : m_Vp1) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), color_used); } for (auto& m : m_Vm) { std::tie(r, g, b) = TissueInfos::GetTissueColorMapped(m.mark); m_ImageDecorated.setPixel(int(m.p.px), int(m_Height - m.p.py - 1), qRgb(r, g, b)); } if (m_Crosshairxvisible) { for (int x = 0; x < m_Width; x++) { m_ImageDecorated.setPixel(x, m_Height - 1 - m_Crosshairxpos, qRgb(0, 255, 0)); m_Image.setPixel(x, m_Height - 1 - m_Crosshairxpos, qRgb(0, 255, 0)); } } if (m_Crosshairyvisible) { for (int y = 0; y < m_Height; y++) { m_ImageDecorated.setPixel(m_Crosshairypos, y, qRgb(0, 255, 0)); m_Image.setPixel(m_Crosshairypos, y, qRgb(0, 255, 0)); } } } void ImageViewerWidget::TissueChanged() { ReloadBits(); repaint(); } void ImageViewerWidget::TissueChanged(QRect rect) { ReloadBits(); repaint((int)(rect.left() * m_Zoom * m_Pixelsize.high), (int)((m_Height - 1 - rect.bottom()) * m_Zoom * m_Pixelsize.low), (int)ceil(rect.width() * m_Zoom * m_Pixelsize.high), (int)ceil(rect.height() * m_Zoom * m_Pixelsize.low)); } void ImageViewerWidget::MarkChanged() { m_Marks = m_Bmphand->ReturnMarks(); repaint(); } bool ImageViewerWidget::ToggleTissuevisible() { m_Tissuevisible = !m_Tissuevisible; update(); return m_Tissuevisible; } bool ImageViewerWidget::TogglePicturevisible() { m_Picturevisible = !m_Picturevisible; update(); return m_Picturevisible; } bool ImageViewerWidget::ToggleMarkvisible() { m_Markvisible = !m_Markvisible; repaint(); return m_Markvisible; } bool ImageViewerWidget::ToggleOverlayvisible() { m_Overlayvisible = !m_Overlayvisible; update(); return m_Overlayvisible; } void ImageViewerWidget::SetTissuevisible(bool on) { m_Tissuevisible = on; update(); } void ImageViewerWidget::SetPicturevisible(bool on) { m_Picturevisible = on; update(); } void ImageViewerWidget::SetMarkvisible(bool on) { m_Markvisible = on; repaint(); } void ImageViewerWidget::SetOverlayvisible(bool on) { m_Overlayvisible = on; update(); } void ImageViewerWidget::SetOverlayalpha(float alpha) { m_Overlayalpha = alpha; update(); } void ImageViewerWidget::AddMark() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit AddmarkSign(p); } void ImageViewerWidget::AddLabel() { bool ok; QString new_text = QInputDialog::getText("Label", "Enter a name for the label:", QLineEdit::Normal, "", &ok, this); if (ok) { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit AddlabelSign(p, new_text.toStdString()); } } void ImageViewerWidget::ClearMarks() { emit ClearmarksSign(); } void ImageViewerWidget::RemoveMark() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit RemovemarkSign(p); } void ImageViewerWidget::AddTissue() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit AddtissueSign(p); } void ImageViewerWidget::AddTissueConnected() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit AddtissueconnectedSign(p); } void ImageViewerWidget::AddTissue3D() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit Addtissue3DSign(p); } void ImageViewerWidget::SubTissue() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit SubtissueSign(p); } void ImageViewerWidget::AddTissuelarger() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit AddtissuelargerSign(p); } void ImageViewerWidget::SelectTissue() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit SelecttissueSign(p, true); } void ImageViewerWidget::ViewTissueSurface() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit ViewtissueSign(p); } void ImageViewerWidget::ViewTargetSurface() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit ViewtargetSign(p); } void ImageViewerWidget::NextTargetSlice() { auto target_slices = m_Handler3D->TargetSlices(); size_t slice_size = m_Handler3D->Width() * m_Handler3D->Height(); // find next slice int slice = -1; auto non_zero = [](float v) { return v != 0.f; }; for (int s = m_Handler3D->ActiveSlice() + 1; s < m_Handler3D->NumSlices(); ++s) { auto data = target_slices.at(s); if (std::any_of(data, data + slice_size, non_zero)) { slice = s; break; } } if (slice == -1) { for (int s = 0; s <= m_Handler3D->ActiveSlice(); ++s) { auto data = target_slices.at(s); if (std::any_of(data, data + slice_size, non_zero)) { slice = s; break; } } } if (slice < 0) { QMessageBox::information(this, "iSeg", "The target contains no foreground pixels"); } else { m_Handler3D->SetActiveSlice(slice, true); } } void ImageViewerWidget::AddToSelectedTissues() { Point p; p.px = (unsigned short)m_Eventx; p.py = (unsigned short)m_Eventy; emit SelecttissueSign(p, false); } void ImageViewerWidget::ZoomIn() { SetZoom(2 * m_Zoom); } void ImageViewerWidget::ZoomOut() { SetZoom(0.5 * m_Zoom); } void ImageViewerWidget::Unzoom() { SetZoom(1.0); } double ImageViewerWidget::ReturnZoom() const { return m_Zoom; } void ImageViewerWidget::contextMenuEvent(QContextMenuEvent* event) { m_Eventx = (int)std::max(std::min(m_Width - 1.0, (event->x() / (m_Zoom * m_Pixelsize.high))), 0.0); m_Eventy = (int)std::max(std::min(m_Height - 1.0, m_Height - 1 - (event->y() / (m_Zoom * m_Pixelsize.low))), 0.0); QMenu context_menu(this); // tissue selection if (event->modifiers() == Qt::ControlModifier) { context_menu.addAction(m_Addtoselection); } else { context_menu.addAction(m_Selecttissue); } // surface view if (m_Bmporwork) { context_menu.addAction(m_Viewtissue); } else { context_menu.addAction(m_Viewtarget); context_menu.addAction(m_Nexttargetslice); // add to tissue context_menu.addSeparator(); context_menu.addAction(m_Addtissue); context_menu.addAction(m_Subtissue); context_menu.addAction(m_Addtissue3D); context_menu.addAction(m_Addtissueconnected); context_menu.addAction(m_Addtissuelarger); } // marks context_menu.addSeparator(); context_menu.addAction(m_Addmark); context_menu.addAction(m_Addlabel); context_menu.addAction(m_Removemark); context_menu.addAction(m_Clearmarks); context_menu.exec(event->globalPos()); } void ImageViewerWidget::SetBrightnesscontrast(float bright, float contr, bool paint) { m_Brightness = bright; m_Contrast = contr; UpdateScaleoffsetfactor(); if (paint) { ReloadBits(); repaint(); } } void ImageViewerWidget::UpdateScaleoffsetfactor() { Bmphandler* bmphand = m_Handler3D->GetActivebmphandler(); if (m_Bmporwork && m_Handler3D->GetColorLookupTable()) { // Disable scaling/offset for color mapped images, since it would break the lookup table m_Scalefactor = 1.0f; m_Scaleoffset = 0.0f; } else if (bmphand->ReturnMode(m_Bmporwork) == eScaleMode::kFixedRange) { // Mode 2 assumes the range [0, 255] m_Scalefactor = m_Contrast; m_Scaleoffset = (127.5f - 255 * m_Scalefactor) * (1.0f - m_Brightness) + 127.5f * m_Brightness; } else if (bmphand->ReturnMode(m_Bmporwork) == eScaleMode::kArbitraryRange) { // Mode 1 assumes an arbitrary range --> scale to range [0, 255] auto r = m_RangeMode1; if (r.high == r.low) { r.high = r.low + 1.f; } m_Scalefactor = 255.0f * m_Contrast / (r.high - r.low); m_Scaleoffset = (127.5f - r.high * m_Scalefactor) * (1.0f - m_Brightness) + (127.5f - r.low * m_Scalefactor) * m_Brightness; } emit ScaleoffsetfactorChanged(m_Scaleoffset, m_Scalefactor, m_Bmporwork); } void ImageViewerWidget::mousePressEvent(QMouseEvent* e) { Point p; // p.px=(unsigned short)(e->x()/(zoom*pixelsize.high)); // p.py=(unsigned short)height-1-(e->y()/(zoom*pixelsize.low)); p.px = (unsigned short)std::max(std::min(m_Width - 1.0, (e->x() / (m_Zoom * m_Pixelsize.high))), 0.0); p.py = (unsigned short)std::max(std::min(m_Height - 1.0, m_Height - ((e->y() + 1) / (m_Zoom * m_Pixelsize.low))), 0.0); if (e->button() == Qt::LeftButton) { emit MousepressedSign(p); } else if (e->button() == Qt::MidButton) { emit MousepressedmidSign(p); } } void ImageViewerWidget::mouseReleaseEvent(QMouseEvent* e) { if (e->button() == Qt::LeftButton) { Point p; p.px = (unsigned short)std::max(std::min(m_Width - 1.0, (e->x() / (m_Zoom * m_Pixelsize.high))), 0.0); p.py = (unsigned short)std::max(std::min(m_Height - 1.0, m_Height - ((e->y() + 1) / (m_Zoom * m_Pixelsize.low))), 0.0); emit MousereleasedSign(p); } } void ImageViewerWidget::mouseDoubleClickEvent(QMouseEvent* e) { Point p; p.px = (unsigned short)std::max(std::min(m_Width - 1.0, (e->x() / (m_Zoom * m_Pixelsize.high))), 0.0); p.py = (unsigned short)std::max(std::min(m_Height - 1.0, m_Height - ((e->y() + 1) / (m_Zoom * m_Pixelsize.low))), 0.0); if (e->button() == Qt::LeftButton) { emit MousedoubleclickSign(p); } else if (e->button() == Qt::MidButton) { emit MousedoubleclickmidSign(p); } } void ImageViewerWidget::mouseMoveEvent(QMouseEvent* e) { Point p; p.px = (unsigned short)std::max(std::min(m_Width - 1.0, (e->x() / (m_Zoom * m_Pixelsize.high))), 0.0); p.py = (unsigned short)std::max(std::min(m_Height - 1.0, m_Height - ((e->y() + 1) / (m_Zoom * m_Pixelsize.low))), 0.0); emit MousemovedSign(p); } void ImageViewerWidget::wheelEvent(QWheelEvent* e) { int delta = e->delta(); if (e->state() & Qt::ControlModifier) { m_MousePosZoom = e->pos(); emit MousePosZoomSign(m_MousePosZoom); emit WheelrotatedctrlSign(delta); } else { e->ignore(); } } void ImageViewerWidget::RecomputeWorkborder() { m_Bmphand = m_Handler3D->GetActivebmphandler(); m_Vp = extract_boundary(m_Bmphand->ReturnWork(), m_Width, m_Height, Point()); } void ImageViewerWidget::WorkborderChanged() { if (m_Workborder) { RecomputeWorkborder(); VpChanged(); } } void ImageViewerWidget::WorkborderChanged(QRect rect) { if (m_Workborder) { RecomputeWorkborder(); VpChanged(rect); } } void ImageViewerWidget::VpToImageDecorator() { if ((!m_Workborderlimit) || ((unsigned)m_VpOld.size() < unsigned(m_Width) * m_Height / 5)) { for (auto& p : m_VpOld) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), m_Image.pixel(int(p.px), int(m_Height - p.py - 1))); } } QRgb color_used = m_OutlineColor.rgb(); QRgb color_dim = (m_OutlineColor.light(30)).rgb(); if ((!m_Workborderlimit) || ((unsigned)m_Vp.size() < unsigned(m_Width) * m_Height / 5)) { for (auto& p : m_Vp) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), color_dim); } } for (auto& p : m_Vp1Old) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), m_Image.pixel(int(p.px), int(m_Height - p.py - 1))); } for (auto& p : m_Vp1) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), color_used); } for (auto& m : m_VmOld) { m_ImageDecorated.setPixel(int(m.p.px), int(m_Height - m.p.py - 1), m_Image.pixel(int(m.p.px), int(m_Height - m.p.py - 1))); } unsigned char r, g, b; for (auto& m : m_Vm) { std::tie(r, g, b) = TissueInfos::GetTissueColorMapped(m.mark); m_ImageDecorated.setPixel(int(m.p.px), int(m_Height - m.p.py - 1), qRgb(r, g, b)); } } void ImageViewerWidget::VpChanged() { VpToImageDecorator(); repaint(); m_VpOld = m_Vp; m_Vp1Old = m_Vp1; m_VmOld = m_Vm; } void ImageViewerWidget::VpChanged(QRect rect) { VpToImageDecorator(); if (rect.left() > 0) rect.setLeft(rect.left() - 1); if (rect.top() > 0) rect.setTop(rect.top() - 1); if (rect.right() + 1 < m_Width) rect.setRight(rect.right() + 1); if (rect.bottom() + 1 < m_Height) rect.setBottom(rect.bottom() + 1); repaint((int)(rect.left() * m_Zoom * m_Pixelsize.high), (int)((m_Height - 1 - rect.bottom()) * m_Zoom * m_Pixelsize.low), (int)ceil(rect.width() * m_Zoom * m_Pixelsize.high), (int)ceil(rect.height() * m_Zoom * m_Pixelsize.low)); m_VpOld = m_Vp; m_Vp1Old = m_Vp1; m_VmOld = m_Vm; } void ImageViewerWidget::Vp1dynChanged() { if ((!m_Workborderlimit) || ((unsigned)m_VpOld.size() < unsigned(m_Width) * m_Height / 5)) { for (auto& p : m_VpOld) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), m_Image.pixel(int(p.px), int(m_Height - p.py - 1))); } } QRgb color_used = m_ActualColor.rgb(); QRgb color_dim = (m_ActualColor.light(30)).rgb(); QRgb color_highlight = (m_ActualColor.lighter(60)).rgb(); if ((!m_Workborderlimit) || ((unsigned)m_Vp.size() < unsigned(m_Width) * m_Height / 5)) { for (auto& p : m_Vp) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), color_dim); } } for (auto& p : m_Vp1Old) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), m_Image.pixel(int(p.px), int(m_Height - p.py - 1))); } for (auto& p : m_Vp1) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), color_used); } for (auto& p : m_LimitPoints) { m_ImageDecorated.setPixel(int(p.px), int(m_Height - p.py - 1), color_highlight); } for (auto& m : m_VmOld) { m_ImageDecorated.setPixel(int(m.p.px), int(m_Height - m.p.py - 1), m_Image.pixel(int(m.p.px), int(m_Height - m.p.py - 1))); } unsigned char r, g, b; for (auto& m : m_Vm) { std::tie(r, g, b) = TissueInfos::GetTissueColorMapped(m.mark); m_ImageDecorated.setPixel(int(m.p.px), int(m_Height - m.p.py - 1), qRgb(r, g, b)); } repaint(); m_VpdynOld = m_Vpdyn; m_VpOld = m_Vp; m_Vp1Old = m_Vp1; m_VmOld = m_Vm; } void ImageViewerWidget::VpdynChanged() { repaint(); } void ImageViewerWidget::SetWorkbordervisible(bool on) { if (on) { if (m_Bmporwork && !m_Workborder) { m_Workborder = true; WorkborderChanged(); } } else { if (m_Workborder && m_Bmporwork) { m_Vp.clear(); m_Workborder = false; ReloadBits(); repaint(); } } } void ImageViewerWidget::SetOutlineColor(const QColor& c) { if (m_OutlineColor != c) { m_OutlineColor = c; // this will trigger a repaint with the new color VpChanged(); } } bool ImageViewerWidget::ToggleWorkbordervisible() { if (m_Workborder) { if (m_Bmporwork) { m_Vp.clear(); m_Workborder = false; ReloadBits(); repaint(); } } else { if (m_Bmporwork) { m_Workborder = true; WorkborderChanged(); } } return m_Workborder; } bool ImageViewerWidget::ReturnWorkbordervisible() const { return m_Workborder; } void ImageViewerWidget::SetVp1(std::vector<Point>* vp1_arg) { m_Vp1.clear(); m_Vp1.insert(m_Vp1.begin(), vp1_arg->begin(), vp1_arg->end()); VpChanged(); } void ImageViewerWidget::SetVm(std::vector<Mark>* vm_arg) { m_Vm.clear(); m_Vm.insert(m_Vm.begin(), vm_arg->begin(), vm_arg->end()); VpChanged(); } void ImageViewerWidget::SetVpdyn(std::vector<Point>* vpdyn_arg) { m_Vpdyn.clear(); m_Vpdyn.insert(m_Vpdyn.begin(), vpdyn_arg->begin(), vpdyn_arg->end()); VpdynChanged(); } void ImageViewerWidget::SetVp1Dyn(std::vector<Point>* vp1_arg, std::vector<Point>* vpdyn_arg, bool also_points) { m_Vp1.clear(); m_Vp1.insert(m_Vp1.begin(), vp1_arg->begin(), vp1_arg->end()); m_Vpdyn.clear(); m_Vpdyn.insert(m_Vpdyn.begin(), vpdyn_arg->begin(), vpdyn_arg->end()); m_LimitPoints.clear(); if (also_points && m_Vp1.size() > 1) { m_LimitPoints.push_back(m_Vp1.front()); m_LimitPoints.push_back(m_Vp1.back()); } Vp1dynChanged(); } void ImageViewerWidget::ColorChanged(int tissue) { unsigned char r, g, b; std::tie(r, g, b) = TissueInfos::GetTissueColorMapped(tissue + 1); m_ActualColor.setRgb(r, g, b); VpChanged(); } void ImageViewerWidget::CrosshairxChanged(int i) { if (i < m_Height) { m_Crosshairxpos = i; if (m_Crosshairxvisible) { ReloadBits(); repaint(); } } } void ImageViewerWidget::CrosshairyChanged(int i) { if (i < m_Width) { m_Crosshairypos = i; if (m_Crosshairyvisible) { ReloadBits(); repaint(); } } } void ImageViewerWidget::SetCrosshairxvisible(bool on) { if (m_Crosshairxvisible != on) { m_Crosshairxvisible = on; ReloadBits(); repaint(); } } void ImageViewerWidget::SetCrosshairyvisible(bool on) { if (m_Crosshairyvisible != on) { m_Crosshairyvisible = on; ReloadBits(); repaint(); } } } // namespace iseg
24.484615
229
0.685098
ITISFoundation
220559445ed7807d051c504e414514a5eb367d1c
12,273
cpp
C++
Trees/BST With Infinite Input Number/BST_2.cpp
aayush-1/Data-Structures
eceb6360feef6e684a430113db7c0663e64aecfa
[ "MIT" ]
null
null
null
Trees/BST With Infinite Input Number/BST_2.cpp
aayush-1/Data-Structures
eceb6360feef6e684a430113db7c0663e64aecfa
[ "MIT" ]
null
null
null
Trees/BST With Infinite Input Number/BST_2.cpp
aayush-1/Data-Structures
eceb6360feef6e684a430113db7c0663e64aecfa
[ "MIT" ]
null
null
null
#include <stdio.h> #include<stdlib.h> int check(); void freee(); int l1; int l2; struct BST { struct node *pointer; struct BST *left; struct BST *right; struct BST *parent; }*root=NULL; struct node { int a; struct node *next; }*head=NULL,*head1=NULL; //inserting the no. in the linked list void insertdigit(int val) { struct node *newnode; newnode=(struct node*)malloc(sizeof(struct node)); newnode->a=val; newnode->next=NULL; if(head==NULL) { head=newnode; } else { struct node *temp=head; while(temp->next!=NULL) { temp=temp->next; } temp->next=newnode; } } //sanitize the input int check() { struct node *temp1,*temp=head; while(temp!=NULL ) { if(temp->a == 0) { temp1=temp; temp=temp->next; free(temp1); } else { break; } } head=temp; if(head==NULL) { struct node *newnode; newnode=(struct node*)malloc(sizeof(struct node)); newnode->a=0; newnode->next=NULL; head=newnode; } } int compare(struct node *A,struct node *B) { l1=0; struct node *tempa=A; while(tempa!=NULL) { l1++; tempa=tempa->next; } l2=0; struct node *tempb=B; while(tempb!=NULL) { l2++; tempb=tempb->next; } if(l1>l2) { return 1; } if(l2>l1) { return 0; } if(l2==l1) { struct node *temp1=A; struct node *temp2=B; while(temp1!=NULL) { if(temp1->a > temp2->a) { return 1; } else if(temp1->a < temp2->a) { return 0; } else{ temp1=temp1->next; temp2=temp2->next; } } return 2; } } //delete the whole bst with numbers stored as linked list in it void deletebst(struct BST *root) { struct BST *temp=root; if(temp!=NULL) { deletebst(temp->left); deletebst(temp->right); freee(temp->pointer); temp->pointer=NULL; free(temp); } root=NULL; } //insert the linked list of numbers entered in the binary search tree void insertbst() { struct BST *newnode; newnode=(struct BST*)malloc(sizeof(struct BST)); newnode->pointer=head; int a; if(root==NULL) { root=newnode; root->right=NULL; root->left=NULL; root->parent=NULL; } else { struct BST *par,*temp=root; while(temp!=NULL) { par=temp; if(compare(newnode->pointer,temp->pointer)==0)//newnode->data < temp->data { temp=temp->left; a=1; } else if(compare(newnode->pointer,temp->pointer)==1) { temp=temp->right; a=2; } else if(compare(newnode->pointer,temp->pointer)==2) { return; } } temp=newnode; temp->left=NULL; temp->right=NULL; if(a==1) { par->left=temp; } if(a==2) { par->right=temp; } temp->parent=par; } } int z; //display the binary search tree void display(struct BST *root)//preorder traversal { if(root != NULL){ z=0; struct node *temp = root->pointer; while(temp!=NULL) { printf("%d",temp->a); temp=temp->next; z=1; } if(z==1) { printf(" "); } display(root->left); display(root->right); } } //delete the number enter while checking the position of that no. in bst void freee(struct node *A) { struct node *temp=A; struct node *temp2; while(temp!=NULL) { temp2=temp->next; free(temp); temp=temp2; } A= NULL; } //insert the position of the number entered in the bst void insert1(int val) { struct node *newnode; newnode=(struct node*)malloc(sizeof(struct node)); newnode->a=val; newnode->next=NULL; if(head1==NULL) { head1=newnode; } else { struct node *temp=head1; while(temp->next!=NULL) { temp=temp->next; } temp->next=newnode; } } //displays the position of no. entered in bst void display1(struct node *A) { if(A == NULL) { printf("\n"); } else { struct node *temp = A; while(temp->next != NULL) { printf("%d",temp->a); temp = temp->next; } printf("%d\n",temp->a); } } //free the linked list containing the position of the no. asked to be searched in the linked list void free1() { struct node *temp=head1; struct node *temp2; while(temp!=NULL) { temp2=temp->next; free(temp); temp=temp2; } head1 = NULL; } //search the no. in the linked list void search() { struct BST *temp=root; while(temp!=NULL) { if(compare(head,temp->pointer)==0) { temp=temp->left; insert1(0); } else if(compare(head,temp->pointer)==1) { temp=temp->right; insert1(1); } else if(compare(head,temp->pointer)==2) { display1(head1); return; } } printf("-1\n"); } //find the successor of a no. present or not present in the binary search tree struct node *succ(struct node *A) { if(root!=NULL) { int a; struct BST *temp=root; struct BST *temp2; while(temp!=NULL) { if(compare(A,temp->pointer)==2) { break; } else if(compare(A,temp->pointer)==0) { temp2=temp; temp=temp->left; a=0; } else if(compare(A,temp->pointer)==1) { temp2=temp; temp=temp->right; a=1; } } if(temp!=NULL) { if(temp->right!=NULL) { struct BST *y; y=temp->right; while(y->left!=NULL) { y=y->left; } return y->pointer; } else { struct BST *y; y=temp->parent; while(compare(y->pointer,temp->pointer)==0) { if(y->parent!=NULL) { y=y->parent; } else{ return NULL; } } return y->pointer; } } else{ if(a==0) { return temp2->pointer; } else if(a==1) { return succ(temp2->pointer); } } } else{ return NULL; } } //deleting by replacing with successor when node has 2 children void delete1(struct node *A) {int a=2; struct node *succesor; if(root!=NULL) { struct BST *temp=root; while(temp!=NULL) { if(compare(A,temp->pointer)==2) { break; } else if(compare(A,temp->pointer)==0) { temp=temp->left; a=0; } else if(compare(A,temp->pointer)==1) { temp=temp->right; a=1; } } if(temp==NULL) { return ; } if(temp->left==NULL && temp->right==NULL) { struct BST *par; par=temp->parent; if(par==NULL) { root=NULL; } if(a==0) { par->left=NULL; } else if(a==1) { par->right=NULL; } } else if(temp->left!=NULL && temp->right!=NULL) { succesor=succ(A); delete1(succesor); temp->pointer=succesor; } else { struct BST *par=temp->parent; if(temp->left!=NULL && par!=NULL) { if(a==0) { par->left=temp->left; temp->left->parent=par; } else if(a==1){ par->right=temp->left; temp->left->parent=par; } } else if(temp->right!=NULL && par!=NULL) { if(a==0) { par->left=temp->right; temp->right->parent=par; } else if(a==1){ par->right=temp->right; temp->right->parent=par; } } else if(par==NULL) { struct BST *temp2=root; if(temp->left==NULL) { root=temp->right; root->parent=NULL; } else if(temp->right==NULL) { root=temp->left; root->parent=NULL; } free(temp2); } } } else{ printf("no element present"); } } int main(){ int digit; while((digit=fgetc(stdin))!=EOF){ if(digit=='N'){ int x=0; while((digit=fgetc(stdin))!=EOF){ if(digit=='\n'){ //display(root); check(); insertbst(); head=NULL; break; } else if(digit==' '){ if(x==0) { deletebst(root); root=NULL; //free all BST x=1; } else if(x==1) { //compare and insert linked list in BST simultaneously check(); insertbst(); head=NULL; //put head = NULL } } else{ //insert digits in linked list insertdigit(digit-48); //check too } } } else if(digit=='S'){ int y=0; while((digit=fgetc(stdin))!=EOF){ if(digit=='\n'){ check(); search(); freee(head); head=NULL; free1(); //compare with bst and print ans //free linked list of digits break; } else if(digit==' '){ y=1; } else{ //insert digits in linked list insertdigit(digit-48); //check too } } } else if(digit=='P'){ //put a \n in the end in display of bst. while((digit=fgetc(stdin))!=EOF){ if(digit=='\n'){ display(root); printf("\n"); break; } } } else if(digit=='+'){ int y=0; while((digit=fgetc(stdin))!=EOF){ if(digit=='\n'){ check(); insertbst(); head=NULL; //compare with bst and print ans //free linked list of digits break; } else if(digit==' '){ y=1; } else{ //insert digits in linked list insertdigit(digit-48); //check too } } } else if(digit=='-'){ int y=0; while((digit=fgetc(stdin))!=EOF){ if(digit=='\n'){ check(); delete1(head); freee(head); head=NULL; //compare with bst and print ans //free linked list of digits break; } else if(digit==' '){ y=1; } else{ //insert digits in linked list insertdigit(digit-48); //check too } } } else if(digit=='>'){ int y=0; while((digit=fgetc(stdin))!=EOF){ if(digit=='\n'){ check(); struct node *temp; temp=succ(head); if(temp==NULL) { printf("-1"); } while(temp!=NULL) { printf("%d",temp->a); temp=temp->next; } printf("\n"); free(temp); freee(head); head=NULL; //compare with bst and print ans //free linked list of digits break; } else if(digit==' '){ y=1; } else{ //insert digits in linked list insertdigit(digit-48); //check too } } } } //delete bst again deletebst(root); root=NULL; return(0); }
16.630081
98
0.436405
aayush-1
220ba7ab5b29865df7623acbcc807ef0faf5fec6
174
cpp
C++
tournaments/prefixSums/prefixSums.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
5
2020-02-06T09:51:22.000Z
2021-03-19T00:18:44.000Z
tournaments/prefixSums/prefixSums.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
null
null
null
tournaments/prefixSums/prefixSums.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
3
2019-09-27T13:06:21.000Z
2021-04-20T23:13:17.000Z
std::vector<int> prefixSums(std::vector<int> a) { std::vector<int> b(1, a[0]); for (int i = 1; i < a.size(); i++) { b.push_back(b[i - 1] + a[i]); } return b; }
17.4
49
0.505747
gurfinkel
220ca8e6c2e30a1581f67272c2fcdaca28d2917b
8,881
cpp
C++
clang/lib/CConv/Utils.cpp
Bhaskers-Blu-Org2/checkedc-clang
84347be1c8213a1415ca6aa48b4e1a0cf072ad9a
[ "BSD-Source-Code" ]
null
null
null
clang/lib/CConv/Utils.cpp
Bhaskers-Blu-Org2/checkedc-clang
84347be1c8213a1415ca6aa48b4e1a0cf072ad9a
[ "BSD-Source-Code" ]
null
null
null
clang/lib/CConv/Utils.cpp
Bhaskers-Blu-Org2/checkedc-clang
84347be1c8213a1415ca6aa48b4e1a0cf072ad9a
[ "BSD-Source-Code" ]
1
2020-07-30T11:23:41.000Z
2020-07-30T11:23:41.000Z
//=--Utils.cpp----------------------------------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // Implementation of Utils methods. //===----------------------------------------------------------------------===// #include "llvm/Support/Path.h" #include "clang/CConv/Utils.h" #include "clang/CConv/CCGlobalOptions.h" #include "clang/CConv/ConstraintVariables.h" using namespace llvm; using namespace clang; const clang::Type *getNextTy(const clang::Type *Ty) { if (Ty->isPointerType()) { // TODO: how to keep the qualifiers around, and what qualifiers do // we want to keep? QualType qtmp = Ty->getLocallyUnqualifiedSingleStepDesugaredType(); return qtmp.getTypePtr()->getPointeeType().getTypePtr(); } else return Ty; } ConstraintVariable *getHighest(std::set<ConstraintVariable *> Vs, ProgramInfo &Info) { if (Vs.size() == 0) return nullptr; ConstraintVariable *V = nullptr; for (auto &P : Vs) { if (V) { if (V->isLt(*P, Info)) V = P; } else { V = P; } } return V; } // Walk the list of declarations and find a declaration that is NOT // a definition and does NOT have a body. FunctionDecl *getDeclaration(FunctionDecl *FD) { // optimization if (!FD->isThisDeclarationADefinition()) { return FD; } for (const auto &D : FD->redecls()) if (FunctionDecl *tFD = dyn_cast<FunctionDecl>(D)) if (!tFD->isThisDeclarationADefinition()) return tFD; return nullptr; } // Walk the list of declarations and find a declaration accompanied by // a definition and a function body. FunctionDecl *getDefinition(FunctionDecl *FD) { // optimization if (FD->isThisDeclarationADefinition() && FD->hasBody()) { return FD; } for (const auto &D : FD->redecls()) if (FunctionDecl *tFD = dyn_cast<FunctionDecl>(D)) if (tFD->isThisDeclarationADefinition() && tFD->hasBody()) return tFD; return nullptr; } SourceLocation getFunctionDeclarationEnd(FunctionDecl *FD, SourceManager &S) { const FunctionDecl *oFD = nullptr; if (FD->hasBody(oFD) && oFD == FD) { // Replace everything up to the beginning of the body. const Stmt *Body = FD->getBody(oFD); int Offset = 0; const char *Buf = S.getCharacterData(Body->getSourceRange().getBegin()); while (*Buf != ')') { Buf--; Offset--; } return Body->getSourceRange().getBegin().getLocWithOffset(Offset); } else { return FD->getSourceRange().getEnd(); } } clang::CheckedPointerKind getCheckedPointerKind(InteropTypeExpr *ItypeExpr) { TypeSourceInfo *InteropTypeInfo = ItypeExpr->getTypeInfoAsWritten(); const clang::Type *InnerType = InteropTypeInfo->getType().getTypePtr(); if (InnerType->isCheckedPointerNtArrayType()) { return CheckedPointerKind::NtArray; } if (InnerType->isCheckedPointerArrayType()) { return CheckedPointerKind::Array; } if (InnerType->isCheckedPointerType()) { return CheckedPointerKind::Ptr; } return CheckedPointerKind::Unchecked; } // Check if function body exists for the // provided declaration. bool hasFunctionBody(clang::Decl *D) { // If this a parameter? if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D)) { if (DeclContext *DC = PD->getParentFunctionOrMethod()) { FunctionDecl *FD = dyn_cast<FunctionDecl>(DC); if (getDefinition(FD) != nullptr) { return true; } } return false; } // Else this should be within body and // the function body should exist. return true; } static std::string storageClassToString(StorageClass SC) { switch (SC) { case StorageClass::SC_Static: return "static "; case StorageClass::SC_Extern: return "extern "; case StorageClass::SC_Register: return "register "; // For all other cases, we do not care. default: return ""; } } // This method gets the storage qualifier for the // provided declaration i.e., static, extern, etc. std::string getStorageQualifierString(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { return storageClassToString(FD->getStorageClass()); } if (VarDecl *VD = dyn_cast<VarDecl>(D)) { return storageClassToString(VD->getStorageClass()); } return ""; } bool isNULLExpression(clang::Expr *E, ASTContext &C) { // This checks if the expression is NULL. Specifically, (void*)0 if (CStyleCastExpr *CS = dyn_cast<CStyleCastExpr>(E)) { Expr *SE = CS->getSubExpr(); return SE->isIntegerConstantExpr(C) && SE->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNotNull); } return false; } bool getAbsoluteFilePath(std::string FileName, std::string &AbsoluteFp) { // Get absolute path of the provided file // returns true if successful else false. SmallString<255> abs_path(FileName); llvm::sys::fs::make_absolute(BaseDir,abs_path); AbsoluteFp = abs_path.str(); return true; } bool functionHasVarArgs(clang::FunctionDecl *FD) { if (FD && FD->getFunctionType()->isFunctionProtoType()) { const FunctionProtoType *srcType = dyn_cast<FunctionProtoType>(FD->getFunctionType()); return srcType->isVariadic(); } return false; } bool isFunctionAllocator(std::string FuncName) { return llvm::StringSwitch<bool>(FuncName) .Cases("malloc", "calloc", "realloc", true) .Default(false); } float getTimeSpentInSeconds(clock_t StartTime) { return float(clock() - StartTime)/CLOCKS_PER_SEC; } bool isPointerType(clang::VarDecl *VD) { return VD->getType().getTypePtr()->isPointerType(); } bool isStructOrUnionType(clang::VarDecl *VD) { return VD->getType().getTypePtr()->isStructureType() || VD->getType().getTypePtr()->isUnionType(); } std::string tyToStr(const clang::Type *T) { QualType QT(T, 0); return QT.getAsString(); } Expr *removeAuxillaryCasts(Expr *E) { bool NeedStrip = true; while (NeedStrip) { NeedStrip = false; E = E->IgnoreParenImpCasts(); if (CStyleCastExpr *C = dyn_cast<CStyleCastExpr>(E)) { E = C->getSubExpr(); NeedStrip = true; } } return E; } bool isTypeHasVoid(clang::QualType QT) { const clang::Type *CurrType = QT.getTypePtrOrNull(); if (CurrType != nullptr) { if (CurrType->isVoidType()) return true; const clang::Type *InnerType = getNextTy(CurrType); while (InnerType != CurrType) { CurrType = InnerType; InnerType = getNextTy(InnerType); } return InnerType->isVoidType(); } return false; } bool isVarArgType(const std::string &TypeName) { return TypeName == "struct __va_list_tag *" || TypeName == "va_list" || TypeName == "struct __va_list_tag"; } bool hasVoidType(clang::ValueDecl *D) { return isTypeHasVoid(D->getType()); } bool canWrite(const std::string &FilePath) { // Was this file explicitly provided on the command line? if (FilePaths.count(FilePath) > 0) return true; // Get the absolute path of the file and check that // the file path starts with the base directory. std::string fileAbsPath = FilePath; getAbsoluteFilePath(FilePath, fileAbsPath); return fileAbsPath.rfind(BaseDir, 0) == 0; } #define MAX_VAR_LEN 35 static int lcsMemoization(std::string Str1, std::string Str2, int Str1Len, int Str2Len, int Mem[][MAX_VAR_LEN]) { // base case if (Str1Len == 0 || Str2Len == 0) return 0; // if the same state has already been // computed if (Mem[Str1Len - 1][Str2Len - 1] != -1) return Mem[Str1Len - 1][Str2Len - 1]; // if equal, then we store the value of the // function call if (Str1[Str1Len - 1] == Str2[Str2Len - 1]) { // store it in arr to avoid further repetitive // work in future function calls Mem[Str1Len - 1][Str2Len - 1] = 1 + lcsMemoization(Str1, Str2, Str1Len - 1, Str2Len - 1, Mem); return Mem[Str1Len - 1][Str2Len - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls Mem[Str1Len - 1][Str2Len - 1] = std::max(lcsMemoization(Str1, Str2, Str1Len, Str2Len - 1, Mem), lcsMemoization(Str1, Str2, Str1Len - 1, Str2Len, Mem)); return Mem[Str1Len - 1][Str2Len - 1]; } } unsigned longestCommonSubsequence(const char *Str1, const char *Str2, unsigned Str1Len, unsigned Str2Len) { int Mem[MAX_VAR_LEN][MAX_VAR_LEN]; // assign -1 to all positions memset(Mem, -1, sizeof(Mem)); // We expect the variable assert(Str1Len < MAX_VAR_LEN && Str2Len < MAX_VAR_LEN && "Insufficient memory"); return lcsMemoization(Str1, Str2, Str1Len, Str2Len, Mem); }
28.7411
80
0.649476
Bhaskers-Blu-Org2
220ed398776056607e332d8ab909a587aa28d4aa
397
cpp
C++
chapter6/constexpr.cpp
kingmax/cpp
b0c3abcfc77094421d906695a4ac167463a43b92
[ "Apache-2.0" ]
null
null
null
chapter6/constexpr.cpp
kingmax/cpp
b0c3abcfc77094421d906695a4ac167463a43b92
[ "Apache-2.0" ]
null
null
null
chapter6/constexpr.cpp
kingmax/cpp
b0c3abcfc77094421d906695a4ac167463a43b92
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; constexpr int new_sz() { return 42; } constexpr size_t scale(size_t cnt) { return new_sz() * cnt; } int main() { constexpr int foo = new_sz(); cout << foo << endl; const size_t sc = scale(10); cout << sc << endl; int arr[scale(2)]; //ok cout << arr << endl; int x = 2; //int arr2[x]; //error //int arr3[scale(x)]; //error return 0; }
13.233333
34
0.602015
kingmax
220f3bd9e47693b930fc311f5b37e95944d5bf04
1,075
cpp
C++
bwi_tasks_pnp/pnp/src/test/mainTest.cpp
pato/bwi_experimental
0cc71672580a886e4c405bbc6ea8305624a28572
[ "BSD-3-Clause" ]
null
null
null
bwi_tasks_pnp/pnp/src/test/mainTest.cpp
pato/bwi_experimental
0cc71672580a886e4c405bbc6ea8305624a28572
[ "BSD-3-Clause" ]
null
null
null
bwi_tasks_pnp/pnp/src/test/mainTest.cpp
pato/bwi_experimental
0cc71672580a886e4c405bbc6ea8305624a28572
[ "BSD-3-Clause" ]
null
null
null
#include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> #include <cppunit/TextTestProgressListener.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cstdlib> int main() { // Create the event manager and test controller CppUnit::TestResult controller; // Add a listener that collects test result CppUnit::TestResultCollector result; controller.addListener( &result ); // Add a listener that print dots as test run. CppUnit::TextTestProgressListener progress; controller.addListener( &progress ); // Add the top suite to the test runner CppUnit::TestRunner runner; runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() ); srand(1); runner.run( controller ); // Print test in a compiler compatible format. CppUnit::CompilerOutputter outputter( &result, std::cerr ); outputter.write(); return result.wasSuccessful() ? 0 : 1; }
26.219512
77
0.727442
pato
2210d550b5823cf707704f68528a654f5f24517d
3,000
cpp
C++
trainings/2015-09-30-Multi-University-2015-6/A.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-09-30-Multi-University-2015-6/A.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-09-30-Multi-University-2015-6/A.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <iostream> using namespace std; const int N = 111111; int n; int a[N], b[N]; pair<int, int> ans[N]; void recover() { for (int i = 0; i < n; i++) { a[i] = b[i]; } } int check() { for (int i = 0; i < n; i++) { if (a[i] != a[(i + 1) % n]) { return 0; } } return 1; } void solve() { scanf("%d", &n); long long sum = 0; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); sum += a[i]; } for (int i = 0; i < n; i++) { b[i] = a[i]; } if (sum % n != 0) { puts("NO"); return; } long long average = sum / n; int tot = 1; if (check()) { puts("YES"); puts("0"); return; } if (a[n - 1] > 0) { a[0]++; a[n - 1]--; tot = 1; ans[1] = make_pair(n - 1, 0); for (int i = 0; i < n - 1; i++) { if (a[i] < average) { a[i]++; a[i + 1]--; ans[++tot] = make_pair(i + 1, i); } else { if (a[i] > average) { a[i]--; a[i + 1]++; ans[++tot] = make_pair(i, i + 1); } } } if (check()) { puts("YES"); printf("%d\n", tot); for (int i = 1; i <= tot; i++) { printf("%d %d\n", ans[i].first + 1, ans[i].second + 1); } return; } } recover(); if (a[0] > 0) { a[0]--; a[n - 1]++; tot = 1; ans[1] = make_pair(0, n - 1); for (int i = 0; i < n - 1; i++) { if (a[i] < average) { a[i]++; a[i + 1]--; ans[++tot] = make_pair(i + 1, i); } else { if (a[i] > average) { a[i]--; a[i + 1]++; ans[++tot] = make_pair(i, i + 1); } } } if (check()) { puts("YES"); printf("%d\n", tot); for (int i = 1; i <= tot; i++) { printf("%d %d\n", ans[i].first + 1, ans[i].second + 1); } return; } } recover(); tot = 0; for (int i = 0; i < n - 1; i++) { if (a[i] < average) { a[i]++; a[i + 1]--; ans[++tot] = make_pair(i + 1, i); } else { if (a[i] > average) { a[i]--; a[i + 1]++; ans[++tot] = make_pair(i, i + 1); } } } if (check()) { puts("YES"); printf("%d\n", tot); for (int i = 1; i <= tot; i++) { printf("%d %d\n", ans[i].first + 1, ans[i].second + 1); } return; } puts("NO"); } int main() { int tests; scanf("%d", &tests); for (int i = 1; i <= tests; i++) { solve(); } return 0; }
20.979021
71
0.296
HcPlu
81fb379858f03c11b943b95bf3fafec52dfbe31b
1,713
cpp
C++
JEBMath/JEBMath/Geometry/ProfileIterator.cpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
1
2019-12-25T05:30:20.000Z
2019-12-25T05:30:20.000Z
JEBMath/JEBMath/Geometry/ProfileIterator.cpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
null
null
null
JEBMath/JEBMath/Geometry/ProfileIterator.cpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
null
null
null
#include "ProfileIterator.hpp" #include <limits> #include "../Math/Constants.hpp" #include "LineString.hpp" #include "Profile.hpp" namespace JEBMath { using namespace std; ProfileIterator::ProfileIterator(const Profile* prof, size_t* index) : m_Profile(prof), m_Index(index), m_UndefinedHeight(numeric_limits<double>::max()) { } bool ProfileIterator::isValid() const { return *m_Index != m_Profile->size(); } void ProfileIterator::next() { if (*m_Index != m_Profile->size()) ++(*m_Index); } size_t ProfileIterator::getIndex() const { return *m_Index; } void ProfileIterator::setIndex(size_t index) { *m_Index = std::min(index, m_Profile->size()); } const Profile* ProfileIterator::getProfile() const { return m_Profile; } double ProfileIterator::getUndefinedHeight() const { return m_UndefinedHeight; } void ProfileIterator::setUndefinedHeight(double undefinedHeight) { m_UndefinedHeight = undefinedHeight; } Vector<double, 2> ProfileIterator::getPoint() const { return (*m_Profile)[*m_Index]; } Vector<double, 2> ProfileIterator::getPointAtX(double x) const { return vector2(x, getYAtX(x)); } double ProfileIterator::getX() const { using JEBMath::getX; return getX(getPoint()); } double ProfileIterator::getY() const { using JEBMath::getY; return getY(getPoint()); } double ProfileIterator::getYAtX(double x) const { using JEBMath::isValid; double y = interpolateY(*m_Profile, x); if (!isValid(y)) return m_UndefinedHeight; else return y; } LineSegment<double, 2> ProfileIterator::getSegment() const { using JEBMath::getSegment; return getSegment(*m_Profile, *m_Index - 1); } }
18.223404
68
0.695271
jebreimo
81fed4602d315e10f484fcae51c46aca25b90d7f
138
cpp
C++
Game/Client/WXEngine/FakeObject/TDFakeObjSystem.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXEngine/FakeObject/TDFakeObjSystem.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXEngine/FakeObject/TDFakeObjSystem.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "StdAfx.h" #include "TDFakeObjSystem.h" #include "TDException.h" WX_IMPLEMENT_DYNAMIC_VIRTUAL(tFakeObjSystem, GETCLASS(tNode));
23
62
0.804348
hackerlank
c3022a032e10cb683c19380b266c818434e51d6b
328
cpp
C++
modify_exit.cpp
jhonatheberson/circuit-simulator
fcb57c108c9138ba29af40918ea9ef2d67905f65
[ "MIT" ]
null
null
null
modify_exit.cpp
jhonatheberson/circuit-simulator
fcb57c108c9138ba29af40918ea9ef2d67905f65
[ "MIT" ]
null
null
null
modify_exit.cpp
jhonatheberson/circuit-simulator
fcb57c108c9138ba29af40918ea9ef2d67905f65
[ "MIT" ]
null
null
null
#include "modify_exit.h" #include "ui_modify_exit.h" modify_exit::modify_exit(QWidget *parent) : QDialog(parent), ui(new Ui::modify_exit) { ui->setupUi(this); } modify_exit::~modify_exit() { delete ui; } void modify_exit::on_id_exit_valueChanged(int arg1) { } void modify_exit::on_buttonBox_accepted() { }
13.12
51
0.704268
jhonatheberson
c3028c8a8e420981d1ff2bfda46e1f5d0c2aa5cc
2,619
cpp
C++
src/Module.cpp
lupuchard/eb
a51641e28fdfe4c1bf34234de07a2a78e0cf62c8
[ "MIT" ]
1
2015-12-28T22:30:17.000Z
2015-12-28T22:30:17.000Z
src/Module.cpp
lupuchard/eb
a51641e28fdfe4c1bf34234de07a2a78e0cf62c8
[ "MIT" ]
null
null
null
src/Module.cpp
lupuchard/eb
a51641e28fdfe4c1bf34234de07a2a78e0cf62c8
[ "MIT" ]
null
null
null
#include "ast/Module.h" bool Module::declare(Function& func) { if (func.pub) pub_functions.push_back(&func); auto key = std::make_pair(func.token.str(), func.param_names.size()); auto iter = functions.find(key); if (iter == functions.end()) { std::vector<Function*> vec; vec.push_back(&func); functions[key] = vec; } else { for (Function* f : iter->second) { if (f->param_types == func.param_types) { return true; } } func.index = (int)iter->second.size(); iter->second.push_back(&func); } return false; } const std::vector<Function*>& Module::get_functions(int num_params, const std::string& name) const { auto key = std::make_pair(name, num_params); auto iter = functions.find(key); if (iter == functions.end()) { static std::vector<Function*> empty; return empty; } return iter->second; } const std::vector<Function*>& Module::get_pub_functions() const { return pub_functions; } bool Module::declare(Global& global) { if (globals.count(global.token.str())) return true; if (global.pub) pub_globals.push_back(&global); globals[global.token.str()] = &global; return false; } Global* Module::get_global(const std::string& name) { auto iter = globals.find(name); if (iter == globals.end()) return nullptr; return iter->second; } const std::vector<Global*>& Module::get_pub_globals() const { return pub_globals; } bool Module::declare(Struct& strukt) { if (structs.count(strukt.token.str())) return true; if (strukt.pub) pub_structs.push_back(&strukt); structs[strukt.token.str()] = &strukt; return false; } Struct* Module::get_struct(const std::string& name) { auto iter = structs.find(name); if (iter == structs.end()) return nullptr; return iter->second; } const std::vector<Struct*>& Module::get_pub_structs() const { return pub_structs; } Module* Module::create_submodule(const std::string& name) { submodules.push_back(std::unique_ptr<Module>(new Module())); std::vector<std::string> vec(1, name); bool success = imports.add(vec, *submodules.back()); if (!success) return nullptr; return &*submodules.back(); } void Module::push_back(std::unique_ptr<Item> item) { return items.push_back(std::move(item)); } size_t Module::size() const { return items.size(); } Item& Module::operator[](size_t index) { return *items[index]; } const Item& Module::operator[](size_t index) const { return *items[index]; } bool Module::add_import(const std::vector<std::string>& module_name, Module& module) { return imports.add(module_name, module); } Module* Module::search(const std::vector<std::string>& module_name) { return imports.search(module_name); }
28.16129
100
0.701795
lupuchard
c304ebadb77294ee646c163929df9e7475b88f80
7,047
cpp
C++
src/mir/passes/threaded.cpp
neheb/meson-plus-plus
8f075012e7a12613883fa335b07c4143f5423111
[ "Apache-2.0" ]
null
null
null
src/mir/passes/threaded.cpp
neheb/meson-plus-plus
8f075012e7a12613883fa335b07c4143f5423111
[ "Apache-2.0" ]
null
null
null
src/mir/passes/threaded.cpp
neheb/meson-plus-plus
8f075012e7a12613883fa335b07c4143f5423111
[ "Apache-2.0" ]
null
null
null
// SPDX-license-identifier: Apache-2.0 // Copyright © 2022 Dylan Baker #include <algorithm> #include <array> #include <future> #include <iostream> #include <mutex> #include "argument_extractors.hpp" #include "exceptions.hpp" #include "log.hpp" #include "passes.hpp" #include "private.hpp" namespace MIR::Passes { namespace fs = std::filesystem; namespace { /** * Do the actual program finding * * This looks for the first program with a given name and sets the * * TODO: handle host vs build */ void find_program(const std::vector<std::string> & names, std::mutex & lock, State::Persistant & pstate, std::set<std::string> & programs) { const std::string path{std::getenv("PATH")}; for (const std::string & name : names) { std::string::size_type last{0}, next{0}; // Only schedule one finder for this program { std::lock_guard l{lock}; if (programs.count(name)) { continue; } programs.emplace(name); } // TODO: the path separator may not be `:` while ((next = path.find(":", last)) != std::string::npos) { fs::path substr = path.substr(last, next - last); last = next + 1; fs::path trial = substr / name; if (fs::exists(trial)) { std::lock_guard l{lock}; auto & map = pstate.programs.build(); for (const auto & name : names) { if (map.count(name) == 0) { map[name] = trial; } } std::cout << "Found program \"" << name << "\" " << Util::Log::green("YES") << " (" << trial << ")" << std::endl; return; } } std::lock_guard l{lock}; std::cout << "Found program \"" << names[0] << "\": " << Util::Log::red("NO") << std::endl; } } enum class Type { PROGRAM, }; using FindJob = std::tuple<Type, std::vector<std::string>>; using FindList = std::vector<FindJob>; bool search_find_program(const Object & obj, State::Persistant & pstate, FindList & jobs) { if (!std::holds_alternative<std::shared_ptr<FunctionCall>>(obj)) { return false; } const auto & f = std::get<std::shared_ptr<FunctionCall>>(obj); if (f->holder.has_value() || f->name != "find_program") { return false; } else if (!all_args_reduced(f->pos_args, f->kw_args)) { return false; } auto names = extract_variadic_arguments<std::shared_ptr<String>>(f->pos_args.begin(), f->pos_args.end()); std::vector<std::string> ret{names.size()}; std::transform(names.begin(), names.end(), ret.begin(), [](const std::shared_ptr<String> & s) { return s->value; }); jobs.emplace_back(std::make_tuple(Type::PROGRAM, ret)); return true; } void worker(FindList & jobs, std::mutex & state_lock, std::mutex & job_lock, State::Persistant & pstate, std::set<std::string> & programs) { while (true) { Type job; std::vector<std::string> names; { std::lock_guard l{job_lock}; if (jobs.empty()) { return; } std::tie(job, names) = jobs.back(); jobs.pop_back(); } switch (job) { case Type::PROGRAM: find_program(names, state_lock, pstate, programs); } } } /** * Search calls that we want to handle in a thread * * this includes: * - find_program() * - dependency() * - compiler.* (that run the compiler) * - subproject()? We would need a hueristic to make sure we don't start * subprojects we don't need, plus some logger changes. */ void search_for_threaded_impl(FindList & jobs, State::Persistant & pstate) { // TODO: should we use promises to get a result back from this? std::mutex state_lock{}, job_lock{}; std::set<std::string> programs{}; // TODO: Don't hardocde this std::array<std::thread, 8> threads{}; for (uint i = 0; i < threads.size(); ++i) { threads[i] = std::thread(&worker, std::ref(jobs), std::ref(state_lock), std::ref(job_lock), std::ref(pstate), std::ref(programs)); } for (auto & t : threads) { t.join(); } } std::optional<Object> replace_find_program(const Object & obj, State::Persistant & state) { if (!std::holds_alternative<std::shared_ptr<FunctionCall>>(obj)) { return std::nullopt; } const auto & f = std::get<std::shared_ptr<FunctionCall>>(obj); if (f->holder.has_value() || f->name != "find_program") { return std::nullopt; } else if (!all_args_reduced(f->pos_args, f->kw_args)) { return std::nullopt; } // We know this is safe since we've already processed this call before (hopefully) // We only need the first name, as all of the names should be in the mapping auto name = extract_positional_argument<std::shared_ptr<String>>(f->pos_args[0]).value()->value; fs::path exe; try { exe = state.programs.build().at(name); } catch (std::out_of_range &) { exe = ""; } bool required = extract_keyword_argument<std::shared_ptr<Boolean>>(f->kw_args, "required") .value_or(std::make_shared<Boolean>(true)) ->value; if (required && exe == "") { throw Util::Exceptions::MesonException("Could not find required program \"" + name + "\""); } return std::make_shared<Program>(name, Machines::Machine::BUILD, exe, f->var); } } // namespace bool threaded_lowering(BasicBlock * block, State::Persistant & pstate) { bool progress = false; FindList jobs{}; // TODO: three step process here: // 1. call the block walker to gather find_program, dependency, etc // 2. create the threads and send them to work on filling out those futures // 3. call the block walker again to fill in those values progress |= block_walker(block, { [&](BasicBlock * b) { return function_walker(b, [&](const Object & obj) { return search_find_program(obj, pstate, jobs); }); }, }); if (progress) { search_for_threaded_impl(jobs, pstate); progress |= block_walker(block, { [&](BasicBlock * b) { return function_walker(b, [&](const Object & obj) { return replace_find_program(obj, pstate); }); }, }); } return progress; } } // namespace MIR::Passes
33.557143
100
0.532709
neheb
c30b9af7f1b9ac41897db90405989e002c9e0e3b
3,294
cpp
C++
src/points/cylindrical.cpp
jonancm/viennagrid-python
a56f23ab65cf82b2f06ff546d45c056bb9d326b2
[ "MIT" ]
null
null
null
src/points/cylindrical.cpp
jonancm/viennagrid-python
a56f23ab65cf82b2f06ff546d45c056bb9d326b2
[ "MIT" ]
1
2015-05-13T08:28:52.000Z
2015-05-13T08:28:52.000Z
src/points/cylindrical.cpp
jonancm/viennagrid-python
a56f23ab65cf82b2f06ff546d45c056bb9d326b2
[ "MIT" ]
null
null
null
/* * Copyright (c) 2013 Jonan Cruz-Martin * * Distributed under the terms of the MIT license, see the accompanying * file COPYING or http://opensource.org/licenses/MIT. */ #include "cylindrical.hpp" #include "cartesian.hpp" #include "spherical.hpp" PointCylindrical3D::PointCylindrical3D() { point = new PointCylindrical_t(0, 0, 0); id = -1; } PointCylindrical3D::PointCylindrical3D(double x, double y, double z) { point = new PointCylindrical_t(x, y, z); id = -1; } PointCylindrical3D::PointCylindrical3D(PointCylindrical_t *initial_point, unsigned int initial_id) { point = initial_point; id = initial_id; } PointCylindrical3D::PointCylindrical3D(PointCylindrical_t &initial_point, unsigned int initial_id) { point = new PointCylindrical_t(initial_point); id = initial_id; } size_t PointCylindrical3D::get_dimension() { return 3; } const char * PointCylindrical3D::get_coord_system() { return "cylindrical"; } PointCylindrical_t & PointCylindrical3D::get_point() { return *point; } unsigned int PointCylindrical3D::get_id() { return id; } void PointCylindrical3D::set_id(unsigned int new_id) { id = new_id; } double PointCylindrical3D::get_coord(unsigned int index) { return point->at(index); } void PointCylindrical3D::set_coord(unsigned int index, double new_value) { point->at(index) = new_value; } list PointCylindrical3D::get_coord_list() { list coord_list; coord_list.append<double>(point->at(0)); coord_list.append<double>(point->at(1)); coord_list.append<double>(point->at(2)); return coord_list; } PointCylindrical3D & PointCylindrical3D::operator=(const PointCylindrical3D &other) { *(this->point) = *(other.point); return *this; } PointCylindrical3D PointCylindrical3D::operator+(const PointCylindrical3D &other) { PointCylindrical_t result = *(this->point) + *(other.point); return PointCylindrical3D(result.at(0), result.at(1), result.at(2)); } PointCylindrical3D PointCylindrical3D::operator-(const PointCylindrical3D &other) { PointCylindrical_t result = *(this->point) - *(other.point); return PointCylindrical3D(result.at(0), result.at(1), result.at(2)); } PointCylindrical3D PointCylindrical3D::operator*(const double factor) { PointCylindrical_t result = *(this->point) * factor; return PointCylindrical3D(result.at(0), result.at(1), result.at(2)); } PointCylindrical3D PointCylindrical3D::operator/(const double factor) { PointCylindrical_t result = *(this->point) / factor; return PointCylindrical3D(result.at(0), result.at(1), result.at(2)); } PointCylindrical3D PointCylindrical3D::operator-() { PointCylindrical_t result = -(*point); return PointCylindrical3D(result.at(0), result.at(1), result.at(2)); } PointCartesian3D PointCylindrical3D::to_cartesian() { PointCartesian3D_t new_point = get_point(); return PointCartesian3D(new_point.at(0), new_point.at(1), new_point.at(2)); } PointSpherical3D PointCylindrical3D::to_spherical() { PointSpherical_t new_point = get_point(); return PointSpherical3D(new_point.at(0), new_point.at(1), new_point.at(2)); } double PointCylindrical3D::norm_1() { return viennagrid::norm_1(get_point()); } double PointCylindrical3D::norm_2() { return viennagrid::norm_2(get_point()); } double PointCylindrical3D::norm_inf() { return viennagrid::norm_inf(get_point()); }
23.197183
98
0.754706
jonancm
c3138edb556d284ec262422a547c336c0182fbb0
819
cpp
C++
skim/src/main.cpp
mclauchlinc/analysis_twopi_clas6
620e8f032e225ba90d228563c702f5c9ac2a6f75
[ "MIT" ]
null
null
null
skim/src/main.cpp
mclauchlinc/analysis_twopi_clas6
620e8f032e225ba90d228563c702f5c9ac2a6f75
[ "MIT" ]
null
null
null
skim/src/main.cpp
mclauchlinc/analysis_twopi_clas6
620e8f032e225ba90d228563c702f5c9ac2a6f75
[ "MIT" ]
null
null
null
#include "TChain.h" #include "TStopwatch.h" #include "skim.hpp" using namespace std; int main(int argc, char **argv) { std::string infile; std::string outfile; if (argc == 2) { infile = argv[1]; outfile = infile.substr(0, infile.size() - 5) + "_skim.root"; } else if (argc == 3) { infile = argv[1]; outfile = argv[2]; } else { std::cerr << BOLDRED << "Error: \n"; std::cerr << BOLDWHITE << "\tNeed input file and output file\n"; std::cerr << BOLDBLUE << "Usage:\n\t"; std::cerr << RESET << argv[0] << " /path/to/unskimmed.root\n"; std::cerr << BOLDBLUE << "or:\n\t"; std::cerr << RESET << argv[0] << " /path/to/unskimmed.root /path/to/skimmed.root\n"; std::cerr << std::endl; return 1; } Skim *s = new Skim(infile, outfile); s->Basic(); return 0; }
25.59375
88
0.570208
mclauchlinc
c314a2aab2ca429cd5919a4b1f2a8e1a80d4a55c
11,470
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/text/CTextUtils.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/text/CTextUtils.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/text/CTextUtils.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "elastos/droid/text/TextUtils.h" #include "elastos/droid/text/CTextUtils.h" namespace Elastos { namespace Droid { namespace Text { CAR_INTERFACE_IMPL(CTextUtils, Singleton, ITextUtils) CAR_SINGLETON_IMPL(CTextUtils) ECode CTextUtils::GetChars( /* [in] */ ICharSequence* s, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ ArrayOf<Char32>* dest, /* [in] */ Int32 destoff) { return TextUtils::GetChars(s, start, end, dest, destoff); } ECode CTextUtils::IndexOf( /* [in] */ ICharSequence* s, /* [in] */ Char32 ch, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IndexOf(s, ch); return NOERROR; } ECode CTextUtils::IndexOf( /* [in] */ ICharSequence* s, /* [in] */ Char32 ch, /* [in] */ Int32 start, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IndexOf(s, ch, start); return NOERROR; } ECode CTextUtils::IndexOf( /* [in] */ ICharSequence* s, /* [in] */ Char32 ch, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IndexOf(s, ch, start, end); return NOERROR; } ECode CTextUtils::LastIndexOf( /* [in] */ ICharSequence* s, /* [in] */ Char32 ch, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::LastIndexOf(s, ch); return NOERROR; } ECode CTextUtils::LastIndexOf( /* [in] */ ICharSequence* s, /* [in] */ Char32 ch, /* [in] */ Int32 start, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::LastIndexOf(s, ch, start); return NOERROR; } ECode CTextUtils::LastIndexOf( /* [in] */ ICharSequence* s, /* [in] */ Char32 ch, /* [in] */ Int32 start, /* [in] */ Int32 last, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::LastIndexOf(s, ch, start, last); return NOERROR; } ECode CTextUtils::IndexOf( /* [in] */ ICharSequence* s, /* [in] */ ICharSequence* needle, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IndexOf(s, needle); return NOERROR; } ECode CTextUtils::IndexOf( /* [in] */ ICharSequence* s, /* [in] */ ICharSequence* needle, /* [in] */ Int32 start, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IndexOf(s, needle, start); return NOERROR; } ECode CTextUtils::IndexOf( /* [in] */ ICharSequence* s, /* [in] */ ICharSequence* needle, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IndexOf(s, needle, start, end); return NOERROR; } ECode CTextUtils::RegionMatches( /* [in] */ ICharSequence* one, /* [in] */ Int32 toffset, /* [in] */ ICharSequence* two, /* [in] */ Int32 ooffset, /* [in] */ Int32 len, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::RegionMatches(one, toffset, two, ooffset, len); return NOERROR; } ECode CTextUtils::Substring( /* [in] */ ICharSequence* source, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out] */ String* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::Substring(source, start, end); return NOERROR; } ECode CTextUtils::Join( /* [in] */ ICharSequence* delimiter, /* [in] */ ArrayOf<IInterface*>* tokens, /* [out] */ String* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::Join(delimiter, tokens); return NOERROR; } ECode CTextUtils::Join( /* [in] */ ICharSequence* delimiter, /* [in] */ IIterable* tokens, /* [out] */ String* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::Join(delimiter, tokens); return NOERROR; } ECode CTextUtils::Split( /* [in] */ const String& text, /* [in] */ const String& expression, /* [out, callee] */ ArrayOf<String>** strs) { VALIDATE_NOT_NULL(strs) AutoPtr<ArrayOf<String> > array = TextUtils::Split(text, expression); *strs = array; REFCOUNT_ADD(*strs) return NOERROR; } ECode CTextUtils::Split( /* [in] */ const String& text, /* [in] */ IPattern* pattern, /* [out, callee] */ ArrayOf<String>** strs) { VALIDATE_NOT_NULL(strs) AutoPtr<ArrayOf<String> > array = TextUtils::Split(text, pattern); *strs = array; REFCOUNT_ADD(*strs) return NOERROR; } ECode CTextUtils::StringOrSpannedString( /* [in] */ ICharSequence* source, /* [out] */ ICharSequence** result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> csq = TextUtils::StringOrSpannedString(source); *result = csq; REFCOUNT_ADD(*result) return NOERROR; } ECode CTextUtils::IsEmpty( /* [in] */ ICharSequence* str, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IsEmpty(str); return NOERROR; } ECode CTextUtils::IsEmpty( /* [in] */ const String& str, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IsEmpty(str); return NOERROR; } ECode CTextUtils::GetTrimmedLength( /* [in] */ ICharSequence* s, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::GetTrimmedLength(s); return NOERROR; } ECode CTextUtils::Equals( /* [in] */ ICharSequence* a, /* [in] */ ICharSequence* b, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::Equals(a, b); return NOERROR; } ECode CTextUtils::Equals( /* [in] */ const String& a, /* [in] */ const String& b, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::Equals(a, b); return NOERROR; } ECode CTextUtils::GetReverse( /* [in] */ ICharSequence* source, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out] */ ICharSequence** result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> csq = TextUtils::GetReverse(source, start, end); *result = csq; REFCOUNT_ADD(*result) return NOERROR; } ECode CTextUtils::WriteToParcel( /* [in] */ ICharSequence* cs, /* [in] */ IParcel* p) { return TextUtils::WriteToParcel(cs, p); } ECode CTextUtils::Replace( /* [in] */ ICharSequence* temp, /* [in] */ ArrayOf<String>* sources, /* [in] */ ArrayOf<ICharSequence*>* destinations, /* [out] */ ICharSequence** result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> csq = TextUtils::Replace(temp, sources, destinations); *result = csq; REFCOUNT_ADD(*result) return NOERROR; } ECode CTextUtils::ExpandTemplate( /* [in] */ ICharSequence* temp, /* [in] */ ArrayOf<ICharSequence*>* values, /* [out] */ ICharSequence** result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> csq = TextUtils::ExpandTemplate(temp, values); *result = csq; REFCOUNT_ADD(*result) return NOERROR; } ECode CTextUtils::GetOffsetBefore( /* [in] */ ICharSequence* text, /* [in] */ Int32 offset, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::GetOffsetBefore(text, offset); return NOERROR; } ECode CTextUtils::GetOffsetAfter( /* [in] */ ICharSequence* text, /* [in] */ Int32 offset, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::GetOffsetAfter(text, offset); return NOERROR; } ECode CTextUtils::CopySpansFrom( /* [in] */ ISpanned* source, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ const InterfaceID& kind, /* [in] */ ISpannable* dest, /* [in] */ Int32 destoff) { return TextUtils::CopySpansFrom(source, start, end, kind, dest, destoff); } ECode CTextUtils::Ellipsize( /* [in] */ ICharSequence* text, /* [in] */ ITextPaint* p, /* [in] */ Float avail, /* [in] */ TextUtilsTruncateAt where, /* [out] */ ICharSequence** result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> csq = TextUtils::Ellipsize(text, p, avail, where); *result = csq; REFCOUNT_ADD(*result) return NOERROR; } ECode CTextUtils::Ellipsize( /* [in] */ ICharSequence* text, /* [in] */ ITextPaint* paint, /* [in] */ Float avail, /* [in] */ TextUtilsTruncateAt where, /* [in] */ Boolean preserveLength, /* [in] */ ITextUtilsEllipsizeCallback* callback, /* [out] */ ICharSequence** result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> csq = TextUtils::Ellipsize(text, paint, avail, where, preserveLength, callback); *result = csq; REFCOUNT_ADD(*result) return NOERROR; } ECode CTextUtils::CommaEllipsize( /* [in] */ ICharSequence* text, /* [in] */ ITextPaint* p, /* [in] */ Float avail, /* [in] */ const String& oneMore, /* [in] */ const String& more, /* [out] */ ICharSequence** result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> csq = TextUtils::CommaEllipsize(text, p, avail, oneMore, more); *result = csq; REFCOUNT_ADD(*result) return NOERROR; } ECode CTextUtils::HtmlEncode( /* [in] */ const String& s, /* [out] */ String* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::HtmlEncode(s); return NOERROR; } ECode CTextUtils::Concat( /* [in] */ ArrayOf<ICharSequence*>* text, /* [out] */ ICharSequence** result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> csq = TextUtils::Concat(text); *result = csq; REFCOUNT_ADD(*result) return NOERROR; } ECode CTextUtils::IsGraphic( /* [in] */ ICharSequence* str, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IsGraphic(str); return NOERROR; } ECode CTextUtils::IsGraphic( /* [in] */ Char32 c, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IsGraphic(c); return NOERROR; } ECode CTextUtils::IsDigitsOnly( /* [in] */ ICharSequence* str, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::IsDigitsOnly(str); return NOERROR; } ECode CTextUtils::GetCapsMode( /* [in] */ ICharSequence* cs, /* [in] */ Int32 off, /* [in] */ Int32 reqModes, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::GetCapsMode(cs, off, reqModes); return NOERROR; } ECode CTextUtils::GetLayoutDirectionFromLocale( /* [in] */ ILocale* locale, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = TextUtils::GetLayoutDirectionFromLocale(locale); return NOERROR; } } // namespace Text } // namepsace Droid } // namespace Elastos
25.153509
107
0.611857
jingcao80
c322d7ba8400761ae530e7eb4c37f65b10cd2eba
7,185
cpp
C++
fboss/agent/hw/sai/switch/SaiPortManager.cpp
soumithx/fboss
84e921dcef19174c4c61d93e04736d80ba0b2b1c
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/sai/switch/SaiPortManager.cpp
soumithx/fboss
84e921dcef19174c4c61d93e04736d80ba0b2b1c
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/sai/switch/SaiPortManager.cpp
soumithx/fboss
84e921dcef19174c4c61d93e04736d80ba0b2b1c
[ "BSD-3-Clause" ]
null
null
null
/* * 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/hw/sai/switch/SaiPortManager.h" #include "fboss/agent/FbossError.h" #include "fboss/agent/hw/sai/store/SaiStore.h" #include "fboss/agent/hw/sai/switch/SaiBridgeManager.h" #include "fboss/agent/hw/sai/switch/SaiManagerTable.h" #include "fboss/agent/hw/sai/switch/SaiQueueManager.h" #include "fboss/agent/hw/sai/switch/SaiSwitchManager.h" #include "fboss/agent/platforms/sai/SaiPlatform.h" #include <folly/logging/xlog.h> namespace facebook { namespace fboss { SaiPortManager::SaiPortManager( SaiManagerTable* managerTable, SaiPlatform* platform) : managerTable_(managerTable), platform_(platform) {} PortSaiId SaiPortManager::addPort(const std::shared_ptr<Port>& swPort) { SaiPortHandle* portHandle = getPortHandle(swPort->getID()); if (portHandle) { throw FbossError( "Attempted to add port which already exists: ", swPort->getID(), " SAI id: ", portHandle->port->adapterKey()); } SaiPortTraits::CreateAttributes attributes = attributesFromSwPort(swPort); SaiPortTraits::AdapterHostKey portKey{GET_ATTR(Port, HwLaneList, attributes)}; auto handle = std::make_unique<SaiPortHandle>(); auto& portStore = SaiStore::getInstance()->get<SaiPortTraits>(); auto saiPort = portStore.setObject(portKey, attributes); handle->port = saiPort; handle->bridgePort = managerTable_->bridgeManager().addBridgePort(saiPort->adapterKey()); handle->queues = managerTable_->queueManager().createQueues( saiPort->adapterKey(), swPort->getPortQueues()); handles_.emplace(swPort->getID(), std::move(handle)); portSaiIds_.emplace(saiPort->adapterKey(), swPort->getID()); return saiPort->adapterKey(); } void SaiPortManager::removePort(PortID swId) { auto itr = handles_.find(swId); if (itr == handles_.end()) { throw FbossError("Attempted to remove non-existent port: ", swId); } portSaiIds_.erase(itr->second->port->adapterKey()); handles_.erase(itr); } void SaiPortManager::changePort(const std::shared_ptr<Port>& swPort) { SaiPortHandle* existingPort = getPortHandle(swPort->getID()); if (!existingPort) { throw FbossError("Attempted to change non-existent port "); } SaiPortTraits::CreateAttributes attributes = attributesFromSwPort(swPort); SaiPortTraits::AdapterHostKey portKey{GET_ATTR(Port, HwLaneList, attributes)}; auto& portStore = SaiStore::getInstance()->get<SaiPortTraits>(); portStore.setObject(portKey, attributes); existingPort->queues = managerTable_->queueManager().createQueues( existingPort->port->adapterKey(), swPort->getPortQueues()); } SaiPortTraits::CreateAttributes SaiPortManager::attributesFromSwPort( const std::shared_ptr<Port>& swPort) const { bool adminState; switch (swPort->getAdminState()) { case cfg::PortState::DISABLED: adminState = false; break; case cfg::PortState::ENABLED: adminState = true; break; default: adminState = false; XLOG(INFO) << "Invalid port admin state!"; break; } uint32_t speed; switch (swPort->getSpeed()) { case cfg::PortSpeed::TWENTYFIVEG: speed = static_cast<uint32_t>(swPort->getSpeed()); break; case cfg::PortSpeed::HUNDREDG: speed = static_cast<uint32_t>(swPort->getSpeed()); break; default: speed = 0; XLOG(INFO) << "Invalid port speed!"; } auto platformPort = platform_->getPort(swPort->getID()); auto hwLaneList = platformPort->getHwPortLanes(swPort->getSpeed()); auto fecMode = SAI_PORT_FEC_MODE_NONE; if (!platformPort->shouldDisableFEC() && swPort->getFEC() == cfg::PortFEC::ON) { auto fec = platformPort->getFecMode(swPort->getSpeed()); if (fec == phy::FecMode::CL91 || fec == phy::FecMode::CL74) { fecMode = SAI_PORT_FEC_MODE_FC; } else if (fec == phy::FecMode::RS528 || fec == phy::FecMode::RS544) { fecMode = SAI_PORT_FEC_MODE_RS; } } auto pause = swPort->getPause(); auto globalFlowControlMode = SAI_PORT_FLOW_CONTROL_MODE_DISABLE; if (pause.tx && pause.rx) { globalFlowControlMode = SAI_PORT_FLOW_CONTROL_MODE_BOTH_ENABLE; } else if (pause.tx) { globalFlowControlMode = SAI_PORT_FLOW_CONTROL_MODE_TX_ONLY; } else if (pause.rx) { globalFlowControlMode = SAI_PORT_FLOW_CONTROL_MODE_RX_ONLY; } auto internalLoopbackMode = SAI_PORT_INTERNAL_LOOPBACK_MODE_NONE; switch (swPort->getLoopbackMode()) { case cfg::PortLoopbackMode::NONE: internalLoopbackMode = SAI_PORT_INTERNAL_LOOPBACK_MODE_NONE; break; case cfg::PortLoopbackMode::PHY: internalLoopbackMode = SAI_PORT_INTERNAL_LOOPBACK_MODE_PHY; break; case cfg::PortLoopbackMode::MAC: internalLoopbackMode = SAI_PORT_INTERNAL_LOOPBACK_MODE_MAC; break; } auto mediaType = SAI_PORT_MEDIA_TYPE_UNKNOWN; switch (platformPort->getTransmitterTech()) { case TransmitterTechnology::COPPER: mediaType = SAI_PORT_MEDIA_TYPE_COPPER; break; case TransmitterTechnology::OPTICAL: mediaType = SAI_PORT_MEDIA_TYPE_FIBER; break; default: mediaType = SAI_PORT_MEDIA_TYPE_UNKNOWN; } uint16_t vlanId = swPort->getIngressVlan(); return SaiPortTraits::CreateAttributes{hwLaneList, speed, adminState, fecMode, internalLoopbackMode, mediaType, globalFlowControlMode, vlanId}; } // private const getter for use by const and non-const getters SaiPortHandle* SaiPortManager::getPortHandleImpl(PortID swId) const { auto itr = handles_.find(swId); if (itr == handles_.end()) { return nullptr; } if (!itr->second.get()) { XLOG(FATAL) << "Invalid null SaiPortHandle for " << swId; } return itr->second.get(); } const SaiPortHandle* SaiPortManager::getPortHandle(PortID swId) const { return getPortHandleImpl(swId); } SaiPortHandle* SaiPortManager::getPortHandle(PortID swId) { return getPortHandleImpl(swId); } PortID SaiPortManager::getPortID(sai_object_id_t saiId) const { auto itr = portSaiIds_.find(saiId); if (itr == portSaiIds_.end()) { return PortID(0); } return itr->second; } void SaiPortManager::processPortDelta(const StateDelta& stateDelta) { auto delta = stateDelta.getPortsDelta(); auto processChanged = [this](const auto& /* oldPort */, const auto& newPort) { changePort(newPort); }; auto processAdded = [this](const auto& newPort) { addPort(newPort); }; auto processRemoved = [this](const auto& oldPort) { removePort(oldPort->getID()); }; DeltaFunctions::forEachChanged( delta, processChanged, processAdded, processRemoved); } } // namespace fboss } // namespace facebook
34.37799
80
0.687404
soumithx
c323a29d81c9d2cdbb36b2f3fffd58f0108f2b32
3,836
cpp
C++
demo/Vitis-AI-Library/samples/dpu_task/psmnet/dpu_sfm.cpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
1
2022-02-17T22:13:23.000Z
2022-02-17T22:13:23.000Z
demo/Vitis-AI-Library/samples/dpu_task/psmnet/dpu_sfm.cpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
null
null
null
demo/Vitis-AI-Library/samples/dpu_task/psmnet/dpu_sfm.cpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "./dpu_sfm.hpp" #include <glog/logging.h> #include <stdio.h> #include <chrono> #include <ctime> #include <fstream> #include <iostream> #include <string> #include <vitis/ai/env_config.hpp> #include <vitis/ai/weak.hpp> DEF_ENV_PARAM(DEBUG_SFM_X8, "0"); using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::high_resolution_clock; using namespace std; using int8 = uint8_t; using int32 = uint32_t; extern int xrtSyncBOAIENB(xrtDeviceHandle handle, xrtBufferHandle bohdl, const char* gmioName, enum xclBOSyncDirection dir, size_t size, size_t offset); extern int xrtGMIOWait(xrtDeviceHandle handle, const char* gmioName); static constexpr int NUM_OF_CORE = 8; static constexpr int CHANNEL = 192; static constexpr int WIDTH = 960; static constexpr int HEIGHT = 576; static constexpr int SFM_INPUT_SIZE = (WIDTH * HEIGHT * CHANNEL / NUM_OF_CORE); static constexpr auto SFM_INPUT_BYTE = (SFM_INPUT_SIZE * sizeof(int8)); static constexpr auto SFM_OUTPUT_BYTE = (SFM_INPUT_SIZE / CHANNEL * sizeof(float)); DpuSfm::DpuSfm(const char* xclbin, vitis::ai::library::OutputTensor& input) { auto batch = input.batch; graph_ = vitis::ai::WeakStore<std::string, vai_graph>::create( "graph_sfm", std::string(xclbin), std::string("graph_sfm")); inBO_ = vitis::ai::ImportedXrtBo::create(graph_->h_->dhdl, input); outBO_ = xrtBOAlloc(graph_->h_->dhdl, SFM_OUTPUT_BYTE * NUM_OF_CORE * batch, 0, 0); out_ = ((float*)xrtBOMap(outBO_)); int32 control_params[6] = {0}; control_params[0] = 1; control_params[1] = 192; control_params[2] = 1; control_params[3] = 1; control_params[4] = 0; control_params[5] = 0; for (auto c = 0; c < NUM_OF_CORE; ++c) { xrtGraphUpdateRTP( graph_->g_, (std::string("graph_sfm.superkernel[") + std::to_string(c) + "].in[1]") .c_str(), (char*)control_params, 6 * sizeof(int32)); } // xrtGraphRun(graph_->g_, 0); } DpuSfm::~DpuSfm() { // xrtGraphClose(g_sfm_); inBO_.clear(); xrtBOFree(outBO_); // h_ = nullptr; } void DpuSfm::run_with() { static std::shared_ptr<std::mutex> mtx = vitis::ai::WeakStore<std::string, std::mutex>::create("aie-resize"); std::lock_guard<std::mutex> lock(*mtx); auto batch = inBO_.size(); // LOG(INFO) << "input = " << *input; for (auto b = 0u; b < batch; ++b) { for (auto c = 0; c < NUM_OF_CORE; ++c) { xrtSyncBOAIENB(graph_->h_->dhdl, inBO_[b].real->bo, (std::string("gmio_sfm_a") + std::to_string(c)).c_str(), XCL_BO_SYNC_BO_GMIO_TO_AIE, SFM_INPUT_BYTE, inBO_[b].offset + SFM_INPUT_BYTE * c); } auto batch_offset = b * SFM_OUTPUT_BYTE * NUM_OF_CORE; for (auto c = 0; c < NUM_OF_CORE; ++c) { xrtSyncBOAIENB(graph_->h_->dhdl, outBO_, (std::string("gmio_sfm_c") + std::to_string(c)).c_str(), XCL_BO_SYNC_BO_AIE_TO_GMIO, SFM_OUTPUT_BYTE, batch_offset + SFM_OUTPUT_BYTE * c); } for (auto c = 0; c < NUM_OF_CORE; ++c) { xrtGMIOWait(graph_->h_->dhdl, (std::string("gmio_sfm_c") + std::to_string(c)).c_str()); } } }
34.558559
80
0.650938
hito0512
c3246940ac405fa28d57578f142c787dcd0bdb16
202
hpp
C++
vendor/cucumber-cpp/include/cucumber-cpp/defs.hpp
AndreasAugustin/Gherkin-Demos-cpp
79a4be81ee1fffce56ac503760a48a2b77d6d03f
[ "MIT" ]
1
2016-07-21T10:10:33.000Z
2016-07-21T10:10:33.000Z
vendor/cucumber-cpp/include/cucumber-cpp/defs.hpp
AndreasAugustin/Gherkin-Demos-cpp
79a4be81ee1fffce56ac503760a48a2b77d6d03f
[ "MIT" ]
null
null
null
vendor/cucumber-cpp/include/cucumber-cpp/defs.hpp
AndreasAugustin/Gherkin-Demos-cpp
79a4be81ee1fffce56ac503760a48a2b77d6d03f
[ "MIT" ]
null
null
null
#include "internal/step/StepManager.hpp" #include "internal/hook/HookRegistrar.hpp" #include "internal/ContextManager.hpp" #include "internal/Macros.hpp" #include "internal/drivers/DriverSelector.hpp"
28.857143
46
0.806931
AndreasAugustin
c32546e593916763e60177de71f7945a9d34dd1c
5,456
hxx
C++
include/z5/dataset_factory.hxx
isuruf/z5
2283297d25672d8cf1dc7ca9d809136dbe6b048c
[ "MIT" ]
null
null
null
include/z5/dataset_factory.hxx
isuruf/z5
2283297d25672d8cf1dc7ca9d809136dbe6b048c
[ "MIT" ]
null
null
null
include/z5/dataset_factory.hxx
isuruf/z5
2283297d25672d8cf1dc7ca9d809136dbe6b048c
[ "MIT" ]
null
null
null
#pragma once #include "z5/dataset.hxx" #include "z5/metadata.hxx" #include "z5/handle/handle.hxx" namespace fs = boost::filesystem; namespace z5 { // factory function to open an existing zarr-array inline std::unique_ptr<Dataset> openDataset(const std::string & path, const FileMode::modes mode=FileMode::a) { // read the data type from the metadata handle::Dataset h(path, mode); auto dtype = readDatatype(h); // make the ptr to the DatasetTyped of appropriate dtype std::unique_ptr<Dataset> ptr; switch(dtype) { case types::int8: ptr.reset(new DatasetTyped<int8_t>(h)); break; case types::int16: ptr.reset(new DatasetTyped<int16_t>(h)); break; case types::int32: ptr.reset(new DatasetTyped<int32_t>(h)); break; case types::int64: ptr.reset(new DatasetTyped<int64_t>(h)); break; case types::uint8: ptr.reset(new DatasetTyped<uint8_t>(h)); break; case types::uint16: ptr.reset(new DatasetTyped<uint16_t>(h)); break; case types::uint32: ptr.reset(new DatasetTyped<uint32_t>(h)); break; case types::uint64: ptr.reset(new DatasetTyped<uint64_t>(h)); break; case types::float32: ptr.reset(new DatasetTyped<float>(h)); break; case types::float64: ptr.reset(new DatasetTyped<double>(h)); break; } return ptr; } inline std::unique_ptr<Dataset> openDataset( const handle::Group & group, const std::string & key ) { auto path = group.path(); path /= key; return openDataset(path.string(), group.mode().mode()); } inline std::unique_ptr<Dataset> createDataset( const std::string & path, const std::string & dtype, const types::ShapeType & shape, const types::ShapeType & chunkShape, const bool createAsZarr, const std::string & compressor="raw", const types::CompressionOptions & compressionOptions=types::CompressionOptions(), const double fillValue=0, const FileMode::modes mode=FileMode::a ) { // get the internal data type types::Datatype internalDtype; try { internalDtype = types::Datatypes::n5ToDtype().at(dtype); } catch(const std::out_of_range & e) { throw std::runtime_error("z5py.createDataset: Invalid dtype for dataset"); } // get the compressor types::Compressor internalCompressor; try { internalCompressor = types::Compressors::stringToCompressor().at(compressor); } catch(const std::out_of_range & e) { throw std::runtime_error("z5py.createDataset: Invalid compressor for dataset"); } // add the default compression options if necessary // we need to make a compy of the compression options, because // they are const auto internalCompressionOptions = compressionOptions; types::defaultCompressionOptions(internalCompressor, internalCompressionOptions, createAsZarr); // make metadata DatasetMetadata metadata( internalDtype, shape, chunkShape, createAsZarr, internalCompressor, internalCompressionOptions, fillValue); // make array handle handle::Dataset h(path, mode); // make the ptr to the DatasetTyped of appropriate dtype std::unique_ptr<Dataset> ptr; switch(internalDtype) { case types::int8: ptr.reset(new DatasetTyped<int8_t>(h, metadata)); break; case types::int16: ptr.reset(new DatasetTyped<int16_t>(h, metadata)); break; case types::int32: ptr.reset(new DatasetTyped<int32_t>(h, metadata)); break; case types::int64: ptr.reset(new DatasetTyped<int64_t>(h, metadata)); break; case types::uint8: ptr.reset(new DatasetTyped<uint8_t>(h, metadata)); break; case types::uint16: ptr.reset(new DatasetTyped<uint16_t>(h, metadata)); break; case types::uint32: ptr.reset(new DatasetTyped<uint32_t>(h, metadata)); break; case types::uint64: ptr.reset(new DatasetTyped<uint64_t>(h, metadata)); break; case types::float32: ptr.reset(new DatasetTyped<float>(h, metadata)); break; case types::float64: ptr.reset(new DatasetTyped<double>(h, metadata)); break; } return ptr; } inline std::unique_ptr<Dataset> createDataset( const handle::Group & group, const std::string & key, const std::string & dtype, const types::ShapeType & shape, const types::ShapeType & chunkShape, const bool createAsZarr, const std::string & compressor="raw", const types::CompressionOptions & compressionOptions=types::CompressionOptions(), const double fillValue=0 ) { auto path = group.path(); path /= key; return createDataset(path.string(), dtype, shape, chunkShape, createAsZarr, compressor, compressionOptions, fillValue, group.mode().mode()); } }
37.369863
115
0.592192
isuruf
c3256d968fa26eb4fb05971b039a5aabeb564c46
39,157
cpp
C++
gen/windows/kin/eigen/src/Jp_toe_joint_right.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
26
2018-07-20T15:20:19.000Z
2022-03-14T07:12:12.000Z
gen/windows/kin/eigen/src/Jp_toe_joint_right.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
2
2019-04-19T22:57:00.000Z
2022-01-11T12:46:20.000Z
gen/windows/kin/eigen/src/Jp_toe_joint_right.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
10
2018-07-29T08:05:14.000Z
2022-02-03T08:48:11.000Z
/* * Automatically Generated from Mathematica. * Thu 23 May 2019 13:10:07 GMT-04:00 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "Jp_toe_joint_right.h" #ifdef _MSC_VER #define INLINE __forceinline /* use __forceinline (VC++ specific) */ #else #define INLINE static inline /* use standard inline */ #endif /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ INLINE double Power(double x, double y) { return pow(x, y); } INLINE double Sqrt(double x) { return sqrt(x); } INLINE double Abs(double x) { return fabs(x); } INLINE double Exp(double x) { return exp(x); } INLINE double Log(double x) { return log(x); } INLINE double Sin(double x) { return sin(x); } INLINE double Cos(double x) { return cos(x); } INLINE double Tan(double x) { return tan(x); } INLINE double Csc(double x) { return 1.0/sin(x); } INLINE double Sec(double x) { return 1.0/cos(x); } INLINE double ArcSin(double x) { return asin(x); } INLINE double ArcCos(double x) { return acos(x); } /* update ArcTan function to use atan2 instead. */ INLINE double ArcTan(double x, double y) { return atan2(y,x); } INLINE double Sinh(double x) { return sinh(x); } INLINE double Cosh(double x) { return cosh(x); } INLINE double Tanh(double x) { return tanh(x); } #define E 2.71828182845904523536029 #define Pi 3.14159265358979323846264 #define Degree 0.01745329251994329576924 /* * Sub functions */ static void output1(Eigen::Matrix<double,3,20> &p_output1, const Eigen::Matrix<double,20,1> &var1) { double t471; double t689; double t609; double t653; double t808; double t215; double t236; double t243; double t411; double t572; double t656; double t809; double t825; double t914; double t1101; double t1105; double t1142; double t60; double t1255; double t1259; double t1298; double t1314; double t1375; double t1378; double t1590; double t1632; double t1635; double t1647; double t1893; double t1926; double t1929; double t1937; double t1939; double t1946; double t2060; double t2124; double t2254; double t2264; double t2440; double t2457; double t2494; double t2502; double t2530; double t2538; double t2553; double t2579; double t2584; double t2587; double t2663; double t2668; double t2672; double t2700; double t2713; double t2714; double t2727; double t2773; double t2793; double t2795; double t2935; double t2939; double t2965; double t3013; double t3049; double t3053; double t3113; double t3269; double t3322; double t3362; double t3466; double t3501; double t3512; double t266; double t445; double t447; double t580; double t597; double t926; double t960; double t1054; double t1086; double t1202; double t1209; double t1217; double t3708; double t3740; double t3761; double t3767; double t3855; double t3870; double t1450; double t1594; double t1597; double t3888; double t3902; double t3911; double t1876; double t1877; double t1891; double t2003; double t2065; double t2075; double t3945; double t3958; double t3970; double t4097; double t4113; double t4125; double t2379; double t2382; double t2395; double t2550; double t2570; double t2571; double t4159; double t4220; double t4239; double t4260; double t4267; double t4272; double t2623; double t2625; double t2632; double t2725; double t2746; double t2771; double t4314; double t4315; double t4329; double t4405; double t4434; double t4472; double t2817; double t2824; double t2917; double t3065; double t3192; double t3245; double t4539; double t4560; double t4564; double t4591; double t4600; double t4618; double t3410; double t3419; double t3463; double t4657; double t4682; double t4725; double t4733; double t4743; double t4750; double t4938; double t4948; double t4959; double t4980; double t4986; double t4993; double t5063; double t5116; double t5121; double t5186; double t5198; double t5203; double t5245; double t5260; double t5270; double t5314; double t5320; double t5355; double t5382; double t5384; double t5392; double t5451; double t5490; double t5558; double t5575; double t5615; double t5655; double t5729; double t5740; double t5837; double t5877; double t5913; double t5923; double t6006; double t6047; double t6064; double t6075; double t6080; double t6086; double t6150; double t6157; double t6181; double t6208; double t6235; double t6243; double t6273; double t6287; double t6298; double t6306; double t6320; double t6334; double t6347; double t6358; double t6383; double t6388; double t6392; double t6394; double t6427; double t6461; double t6514; double t6531; double t6533; double t6555; double t6565; double t6570; double t6571; double t6840; double t6842; double t6857; double t6881; double t6886; double t6897; double t6978; double t7013; double t7026; double t7041; double t7046; double t7050; double t7072; double t7084; double t7097; double t7103; double t7121; double t7166; double t7205; double t7206; double t7210; double t7227; double t7233; double t7234; double t7242; double t7283; double t7311; double t7335; double t7352; double t7359; double t7372; double t7379; double t7398; double t7679; double t7680; double t7704; double t7773; double t7774; double t7726; double t7731; double t7742; double t7841; double t7847; double t7865; double t7880; double t7882; double t7888; double t7908; double t7911; double t7921; double t7956; double t7965; double t7971; double t7995; double t8004; double t8005; double t8041; double t8045; double t8049; double t8058; double t8064; double t8072; double t8087; double t8110; double t8114; double t8171; double t8173; double t8174; double t8264; double t8268; double t8278; double t8224; double t8229; double t8300; double t8303; double t8321; double t8339; double t8350; double t8363; double t8380; double t8381; double t8391; double t8409; double t8415; double t8428; double t8448; double t8452; double t8463; double t8473; double t8474; double t8475; double t8481; double t8486; double t8495; double t8504; double t8516; double t8520; double t8682; double t8707; double t8719; double t8636; double t8652; double t8663; double t8743; double t8744; double t8749; double t8767; double t8770; double t8776; double t8780; double t8790; double t8806; double t8808; double t8829; double t8849; double t8875; double t8879; double t8895; double t8920; double t8923; double t8928; double t8938; double t8943; double t8954; double t8958; double t8965; double t8975; double t9085; double t9087; double t9155; double t9168; double t9170; double t9210; double t9211; double t9217; double t9227; double t9235; double t9236; double t9251; double t9254; double t9267; double t9278; double t9290; double t9298; double t9306; double t9308; double t9315; double t9330; double t9350; double t9357; double t9369; double t9370; double t9378; double t9468; double t9475; double t9481; double t9493; double t9495; double t9485; double t9489; double t9529; double t9573; double t9575; double t9591; double t9604; double t9629; double t9655; double t9663; double t9679; double t9698; double t9718; double t9736; double t9752; double t9756; double t9759; double t9767; double t9768; double t9777; double t9790; double t9802; double t9805; double t9815; double t9824; double t9828; double t8677; double t8731; double t8737; double t8742; double t8764; double t8779; double t8807; double t8861; double t8905; double t8937; double t8956; double t8989; double t8990; double t9010; double t9013; double t9018; double t9021; double t9033; double t9039; double t9042; double t4003; double t4019; double t4023; double t10065; double t10074; double t10077; double t10099; double t10106; double t10117; double t10126; double t10147; double t10148; double t10151; double t10156; double t10163; double t10167; double t10171; double t10179; double t10196; double t10205; double t10220; double t9927; double t9931; double t9940; double t9964; double t9967; double t10298; double t10306; double t10307; double t10315; double t10323; double t10327; double t10362; double t10369; double t10370; double t10380; double t10383; double t10393; double t10395; double t10396; double t10404; double t10417; double t10429; double t10431; double t10449; double t10453; double t10455; double t10462; double t10467; double t10469; double t10510; double t10517; double t10519; double t10531; double t10533; double t10537; double t10557; double t10561; double t10562; double t10564; double t10566; double t10568; double t10576; double t10577; double t10578; double t10584; double t10586; double t10589; double t10596; double t10597; double t10601; double t10610; double t10614; double t10615; double t10666; double t10667; double t10671; double t10674; double t10675; double t10679; double t10681; double t10683; double t10692; double t10693; double t10695; double t10710; double t10711; double t10717; double t10720; double t10723; double t10724; double t10728; double t10732; double t10736; double t10648; double t10652; double t10657; double t10658; double t10662; double t10759; double t10760; double t10762; double t10766; double t10768; double t10771; double t10776; double t10777; double t10778; double t10783; double t10784; double t10793; double t10796; double t10800; double t10802; double t10806; double t10807; double t10809; double t10812; double t10815; double t10817; double t10825; double t10826; double t10829; double t10833; double t10835; double t10838; double t10861; double t10862; double t10863; double t10866; double t10870; double t10871; double t10878; double t10881; double t10884; double t10888; double t10889; double t10890; double t10895; double t10901; double t10902; double t10906; double t10907; double t10908; double t10910; double t10911; double t10914; double t10917; double t10918; double t10924; double t10934; double t10935; double t10938; double t10974; double t10975; double t10977; double t10978; double t10979; double t10981; double t10982; double t10986; double t10988; double t10991; double t10993; double t10996; double t10997; double t10960; double t10962; double t10963; double t10966; double t10967; double t11012; double t11013; double t11014; double t11018; double t11021; double t11023; double t11024; double t11027; double t11028; double t11029; double t11031; double t11032; double t11033; double t11035; double t11036; double t11037; double t11039; double t11041; double t11042; double t11060; double t11062; double t11063; double t11066; double t11068; double t11070; double t11071; double t11074; double t11076; double t11077; double t11082; double t11083; double t11085; double t11087; double t11089; double t11090; double t11093; double t11094; double t11096; double t11122; double t11123; double t11127; double t11128; double t11131; double t11132; double t11133; double t11109; double t11110; double t11113; double t11115; double t11116; double t11151; double t11152; double t11153; double t11156; double t11157; double t11159; double t11162; double t11165; double t11166; double t11168; double t11172; double t11173; double t11174; double t11188; double t11189; double t11192; double t11194; double t11196; double t11200; double t11201; double t11203; double t11204; double t11205; double t11207; double t11208; double t11209; double t11237; double t11238; double t4840; double t11225; double t11228; double t11229; double t11231; double t11232; double t11249; double t11250; double t11252; double t11256; double t11257; double t11259; double t11261; double t11279; double t11280; double t11281; double t11286; double t11287; double t11292; double t11293; double t11240; double t4861; double t4865; double t11310; double t11311; double t11313; double t11314; double t11315; double t11264; double t11325; double t11326; double t11327; double t11271; double t11296; double t11338; double t11339; double t11340; double t11304; t471 = Sin(var1[3]); t689 = Cos(var1[3]); t609 = Cos(var1[5]); t653 = Sin(var1[4]); t808 = Sin(var1[5]); t215 = Cos(var1[14]); t236 = -1.*t215; t243 = 1. + t236; t411 = Sin(var1[14]); t572 = Sin(var1[13]); t656 = -1.*t609*t471*t653; t809 = t689*t808; t825 = t656 + t809; t914 = Cos(var1[13]); t1101 = -1.*t689*t609; t1105 = -1.*t471*t653*t808; t1142 = t1101 + t1105; t60 = Cos(var1[4]); t1255 = t572*t825; t1259 = t914*t1142; t1298 = t1255 + t1259; t1314 = Cos(var1[15]); t1375 = -1.*t1314; t1378 = 1. + t1375; t1590 = Sin(var1[15]); t1632 = t914*t825; t1635 = -1.*t572*t1142; t1647 = t1632 + t1635; t1893 = -1.*t215*t60*t471; t1926 = t411*t1298; t1929 = t1893 + t1926; t1937 = Cos(var1[16]); t1939 = -1.*t1937; t1946 = 1. + t1939; t2060 = Sin(var1[16]); t2124 = t1590*t1647; t2254 = t1314*t1929; t2264 = t2124 + t2254; t2440 = t1314*t1647; t2457 = -1.*t1590*t1929; t2494 = t2440 + t2457; t2502 = Cos(var1[17]); t2530 = -1.*t2502; t2538 = 1. + t2530; t2553 = Sin(var1[17]); t2579 = -1.*t2060*t2264; t2584 = t1937*t2494; t2587 = t2579 + t2584; t2663 = t1937*t2264; t2668 = t2060*t2494; t2672 = t2663 + t2668; t2700 = Cos(var1[18]); t2713 = -1.*t2700; t2714 = 1. + t2713; t2727 = Sin(var1[18]); t2773 = t2553*t2587; t2793 = t2502*t2672; t2795 = t2773 + t2793; t2935 = t2502*t2587; t2939 = -1.*t2553*t2672; t2965 = t2935 + t2939; t3013 = Cos(var1[19]); t3049 = -1.*t3013; t3053 = 1. + t3049; t3113 = Sin(var1[19]); t3269 = -1.*t2727*t2795; t3322 = t2700*t2965; t3362 = t3269 + t3322; t3466 = t2700*t2795; t3501 = t2727*t2965; t3512 = t3466 + t3501; t266 = -0.049*t243; t445 = -0.135*t411; t447 = 0. + t266 + t445; t580 = 0.135*t572; t597 = 0. + t580; t926 = -1.*t914; t960 = 1. + t926; t1054 = -0.135*t960; t1086 = 0. + t1054; t1202 = -0.135*t243; t1209 = 0.049*t411; t1217 = 0. + t1202 + t1209; t3708 = t689*t609*t653; t3740 = t471*t808; t3761 = t3708 + t3740; t3767 = -1.*t609*t471; t3855 = t689*t653*t808; t3870 = t3767 + t3855; t1450 = -0.09*t1378; t1594 = 0.049*t1590; t1597 = 0. + t1450 + t1594; t3888 = t572*t3761; t3902 = t914*t3870; t3911 = t3888 + t3902; t1876 = -0.049*t1378; t1877 = -0.09*t1590; t1891 = 0. + t1876 + t1877; t2003 = -0.049*t1946; t2065 = -0.21*t2060; t2075 = 0. + t2003 + t2065; t3945 = t914*t3761; t3958 = -1.*t572*t3870; t3970 = t3945 + t3958; t4097 = t215*t689*t60; t4113 = t411*t3911; t4125 = t4097 + t4113; t2379 = -0.21*t1946; t2382 = 0.049*t2060; t2395 = 0. + t2379 + t2382; t2550 = -0.2707*t2538; t2570 = 0.0016*t2553; t2571 = 0. + t2550 + t2570; t4159 = t1590*t3970; t4220 = t1314*t4125; t4239 = t4159 + t4220; t4260 = t1314*t3970; t4267 = -1.*t1590*t4125; t4272 = t4260 + t4267; t2623 = -0.0016*t2538; t2625 = -0.2707*t2553; t2632 = 0. + t2623 + t2625; t2725 = 0.0184*t2714; t2746 = -0.7055*t2727; t2771 = 0. + t2725 + t2746; t4314 = -1.*t2060*t4239; t4315 = t1937*t4272; t4329 = t4314 + t4315; t4405 = t1937*t4239; t4434 = t2060*t4272; t4472 = t4405 + t4434; t2817 = -0.7055*t2714; t2824 = -0.0184*t2727; t2917 = 0. + t2817 + t2824; t3065 = -1.1135*t3053; t3192 = 0.0216*t3113; t3245 = 0. + t3065 + t3192; t4539 = t2553*t4329; t4560 = t2502*t4472; t4564 = t4539 + t4560; t4591 = t2502*t4329; t4600 = -1.*t2553*t4472; t4618 = t4591 + t4600; t3410 = -0.0216*t3053; t3419 = -1.1135*t3113; t3463 = 0. + t3410 + t3419; t4657 = -1.*t2727*t4564; t4682 = t2700*t4618; t4725 = t4657 + t4682; t4733 = t2700*t4564; t4743 = t2727*t4618; t4750 = t4733 + t4743; t4938 = t689*t60*t609*t572; t4948 = t914*t689*t60*t808; t4959 = t4938 + t4948; t4980 = t914*t689*t60*t609; t4986 = -1.*t689*t60*t572*t808; t4993 = t4980 + t4986; t5063 = -1.*t215*t689*t653; t5116 = t411*t4959; t5121 = t5063 + t5116; t5186 = t1590*t4993; t5198 = t1314*t5121; t5203 = t5186 + t5198; t5245 = t1314*t4993; t5260 = -1.*t1590*t5121; t5270 = t5245 + t5260; t5314 = -1.*t2060*t5203; t5320 = t1937*t5270; t5355 = t5314 + t5320; t5382 = t1937*t5203; t5384 = t2060*t5270; t5392 = t5382 + t5384; t5451 = t2553*t5355; t5490 = t2502*t5392; t5558 = t5451 + t5490; t5575 = t2502*t5355; t5615 = -1.*t2553*t5392; t5655 = t5575 + t5615; t5729 = -1.*t2727*t5558; t5740 = t2700*t5655; t5837 = t5729 + t5740; t5877 = t2700*t5558; t5913 = t2727*t5655; t5923 = t5877 + t5913; t6006 = t60*t609*t572*t471; t6047 = t914*t60*t471*t808; t6064 = t6006 + t6047; t6075 = t914*t60*t609*t471; t6080 = -1.*t60*t572*t471*t808; t6086 = t6075 + t6080; t6150 = -1.*t215*t471*t653; t6157 = t411*t6064; t6181 = t6150 + t6157; t6208 = t1590*t6086; t6235 = t1314*t6181; t6243 = t6208 + t6235; t6273 = t1314*t6086; t6287 = -1.*t1590*t6181; t6298 = t6273 + t6287; t6306 = -1.*t2060*t6243; t6320 = t1937*t6298; t6334 = t6306 + t6320; t6347 = t1937*t6243; t6358 = t2060*t6298; t6383 = t6347 + t6358; t6388 = t2553*t6334; t6392 = t2502*t6383; t6394 = t6388 + t6392; t6427 = t2502*t6334; t6461 = -1.*t2553*t6383; t6514 = t6427 + t6461; t6531 = -1.*t2727*t6394; t6533 = t2700*t6514; t6555 = t6531 + t6533; t6565 = t2700*t6394; t6570 = t2727*t6514; t6571 = t6565 + t6570; t6840 = -1.*t609*t572*t653; t6842 = -1.*t914*t653*t808; t6857 = t6840 + t6842; t6881 = -1.*t914*t609*t653; t6886 = t572*t653*t808; t6897 = t6881 + t6886; t6978 = -1.*t215*t60; t7013 = t411*t6857; t7026 = t6978 + t7013; t7041 = t1590*t6897; t7046 = t1314*t7026; t7050 = t7041 + t7046; t7072 = t1314*t6897; t7084 = -1.*t1590*t7026; t7097 = t7072 + t7084; t7103 = -1.*t2060*t7050; t7121 = t1937*t7097; t7166 = t7103 + t7121; t7205 = t1937*t7050; t7206 = t2060*t7097; t7210 = t7205 + t7206; t7227 = t2553*t7166; t7233 = t2502*t7210; t7234 = t7227 + t7233; t7242 = t2502*t7166; t7283 = -1.*t2553*t7210; t7311 = t7242 + t7283; t7335 = -1.*t2727*t7234; t7352 = t2700*t7311; t7359 = t7335 + t7352; t7372 = t2700*t7234; t7379 = t2727*t7311; t7398 = t7372 + t7379; t7679 = t609*t471; t7680 = -1.*t689*t653*t808; t7704 = t7679 + t7680; t7773 = t572*t7704; t7774 = t3945 + t7773; t7726 = -1.*t572*t3761; t7731 = t914*t7704; t7742 = t7726 + t7731; t7841 = t1590*t7742; t7847 = t1314*t411*t7774; t7865 = t7841 + t7847; t7880 = t1314*t7742; t7882 = -1.*t411*t1590*t7774; t7888 = t7880 + t7882; t7908 = -1.*t2060*t7865; t7911 = t1937*t7888; t7921 = t7908 + t7911; t7956 = t1937*t7865; t7965 = t2060*t7888; t7971 = t7956 + t7965; t7995 = t2553*t7921; t8004 = t2502*t7971; t8005 = t7995 + t8004; t8041 = t2502*t7921; t8045 = -1.*t2553*t7971; t8049 = t8041 + t8045; t8058 = -1.*t2727*t8005; t8064 = t2700*t8049; t8072 = t8058 + t8064; t8087 = t2700*t8005; t8110 = t2727*t8049; t8114 = t8087 + t8110; t8171 = t609*t471*t653; t8173 = -1.*t689*t808; t8174 = t8171 + t8173; t8264 = t914*t8174; t8268 = t572*t1142; t8278 = t8264 + t8268; t8224 = -1.*t572*t8174; t8229 = t8224 + t1259; t8300 = t1590*t8229; t8303 = t1314*t411*t8278; t8321 = t8300 + t8303; t8339 = t1314*t8229; t8350 = -1.*t411*t1590*t8278; t8363 = t8339 + t8350; t8380 = -1.*t2060*t8321; t8381 = t1937*t8363; t8391 = t8380 + t8381; t8409 = t1937*t8321; t8415 = t2060*t8363; t8428 = t8409 + t8415; t8448 = t2553*t8391; t8452 = t2502*t8428; t8463 = t8448 + t8452; t8473 = t2502*t8391; t8474 = -1.*t2553*t8428; t8475 = t8473 + t8474; t8481 = -1.*t2727*t8463; t8486 = t2700*t8475; t8495 = t8481 + t8486; t8504 = t2700*t8463; t8516 = t2727*t8475; t8520 = t8504 + t8516; t8682 = t914*t60*t609; t8707 = -1.*t60*t572*t808; t8719 = t8682 + t8707; t8636 = -1.*t60*t609*t572; t8652 = -1.*t914*t60*t808; t8663 = t8636 + t8652; t8743 = t1590*t8663; t8744 = t1314*t411*t8719; t8749 = t8743 + t8744; t8767 = t1314*t8663; t8770 = -1.*t411*t1590*t8719; t8776 = t8767 + t8770; t8780 = -1.*t2060*t8749; t8790 = t1937*t8776; t8806 = t8780 + t8790; t8808 = t1937*t8749; t8829 = t2060*t8776; t8849 = t8808 + t8829; t8875 = t2553*t8806; t8879 = t2502*t8849; t8895 = t8875 + t8879; t8920 = t2502*t8806; t8923 = -1.*t2553*t8849; t8928 = t8920 + t8923; t8938 = -1.*t2727*t8895; t8943 = t2700*t8928; t8954 = t8938 + t8943; t8958 = t2700*t8895; t8965 = t2727*t8928; t8975 = t8958 + t8965; t9085 = -1.*t914*t3870; t9087 = t7726 + t9085; t9155 = t1590*t9087; t9168 = t1314*t411*t3970; t9170 = t9155 + t9168; t9210 = t1314*t9087; t9211 = -1.*t411*t1590*t3970; t9217 = t9210 + t9211; t9227 = -1.*t2060*t9170; t9235 = t1937*t9217; t9236 = t9227 + t9235; t9251 = t1937*t9170; t9254 = t2060*t9217; t9267 = t9251 + t9254; t9278 = t2553*t9236; t9290 = t2502*t9267; t9298 = t9278 + t9290; t9306 = t2502*t9236; t9308 = -1.*t2553*t9267; t9315 = t9306 + t9308; t9330 = -1.*t2727*t9298; t9350 = t2700*t9315; t9357 = t9330 + t9350; t9369 = t2700*t9298; t9370 = t2727*t9315; t9378 = t9369 + t9370; t9468 = t689*t609; t9475 = t471*t653*t808; t9481 = t9468 + t9475; t9493 = -1.*t572*t9481; t9495 = t8264 + t9493; t9485 = -1.*t914*t9481; t9489 = t8224 + t9485; t9529 = t1590*t9489; t9573 = t1314*t411*t9495; t9575 = t9529 + t9573; t9591 = t1314*t9489; t9604 = -1.*t411*t1590*t9495; t9629 = t9591 + t9604; t9655 = -1.*t2060*t9575; t9663 = t1937*t9629; t9679 = t9655 + t9663; t9698 = t1937*t9575; t9718 = t2060*t9629; t9736 = t9698 + t9718; t9752 = t2553*t9679; t9756 = t2502*t9736; t9759 = t9752 + t9756; t9767 = t2502*t9679; t9768 = -1.*t2553*t9736; t9777 = t9767 + t9768; t9790 = -1.*t2727*t9759; t9802 = t2700*t9777; t9805 = t9790 + t9802; t9815 = t2700*t9759; t9824 = t2727*t9777; t9828 = t9815 + t9824; t8677 = t1597*t8663; t8731 = -0.1305*t215*t8719; t8737 = t1217*t8719; t8742 = t411*t1891*t8719; t8764 = t2075*t8749; t8779 = t2395*t8776; t8807 = t2571*t8806; t8861 = t2632*t8849; t8905 = t2771*t8895; t8937 = t2917*t8928; t8956 = t3245*t8954; t8989 = t3463*t8975; t8990 = t3113*t8954; t9010 = t3013*t8975; t9013 = t8990 + t9010; t9018 = -0.0216*t9013; t9021 = t3013*t8954; t9033 = -1.*t3113*t8975; t9039 = t9021 + t9033; t9042 = -1.1135*t9039; t4003 = -1.*t689*t60*t411; t4019 = t215*t3911; t4023 = t4003 + t4019; t10065 = -1.*t1937*t1590*t4023; t10074 = -1.*t1314*t2060*t4023; t10077 = t10065 + t10074; t10099 = t1314*t1937*t4023; t10106 = -1.*t1590*t2060*t4023; t10117 = t10099 + t10106; t10126 = t2553*t10077; t10147 = t2502*t10117; t10148 = t10126 + t10147; t10151 = t2502*t10077; t10156 = -1.*t2553*t10117; t10163 = t10151 + t10156; t10167 = -1.*t2727*t10148; t10171 = t2700*t10163; t10179 = t10167 + t10171; t10196 = t2700*t10148; t10205 = t2727*t10163; t10220 = t10196 + t10205; t9927 = -0.135*t215; t9931 = -0.049*t411; t9940 = t9927 + t9931; t9964 = 0.049*t215; t9967 = t9964 + t445; t10298 = t572*t8174; t10306 = t914*t9481; t10307 = t10298 + t10306; t10315 = -1.*t60*t411*t471; t10323 = t215*t10307; t10327 = t10315 + t10323; t10362 = -1.*t1937*t1590*t10327; t10369 = -1.*t1314*t2060*t10327; t10370 = t10362 + t10369; t10380 = t1314*t1937*t10327; t10383 = -1.*t1590*t2060*t10327; t10393 = t10380 + t10383; t10395 = t2553*t10370; t10396 = t2502*t10393; t10404 = t10395 + t10396; t10417 = t2502*t10370; t10429 = -1.*t2553*t10393; t10431 = t10417 + t10429; t10449 = -1.*t2727*t10404; t10453 = t2700*t10431; t10455 = t10449 + t10453; t10462 = t2700*t10404; t10467 = t2727*t10431; t10469 = t10462 + t10467; t10510 = t60*t609*t572; t10517 = t914*t60*t808; t10519 = t10510 + t10517; t10531 = t411*t653; t10533 = t215*t10519; t10537 = t10531 + t10533; t10557 = -1.*t1937*t1590*t10537; t10561 = -1.*t1314*t2060*t10537; t10562 = t10557 + t10561; t10564 = t1314*t1937*t10537; t10566 = -1.*t1590*t2060*t10537; t10568 = t10564 + t10566; t10576 = t2553*t10562; t10577 = t2502*t10568; t10578 = t10576 + t10577; t10584 = t2502*t10562; t10586 = -1.*t2553*t10568; t10589 = t10584 + t10586; t10596 = -1.*t2727*t10578; t10597 = t2700*t10589; t10601 = t10596 + t10597; t10610 = t2700*t10578; t10614 = t2727*t10589; t10615 = t10610 + t10614; t10666 = -1.*t1590*t3970; t10667 = -1.*t1314*t4125; t10671 = t10666 + t10667; t10674 = t2060*t10671; t10675 = t10674 + t4315; t10679 = t1937*t10671; t10681 = -1.*t2060*t4272; t10683 = t10679 + t10681; t10692 = -1.*t2553*t10675; t10693 = t2502*t10683; t10695 = t10692 + t10693; t10710 = t2502*t10675; t10711 = t2553*t10683; t10717 = t10710 + t10711; t10720 = t2727*t10695; t10723 = t2700*t10717; t10724 = t10720 + t10723; t10728 = t2700*t10695; t10732 = -1.*t2727*t10717; t10736 = t10728 + t10732; t10648 = 0.049*t1314; t10652 = t10648 + t1877; t10657 = -0.09*t1314; t10658 = -0.049*t1590; t10662 = t10657 + t10658; t10759 = t215*t60*t471; t10760 = t411*t10307; t10762 = t10759 + t10760; t10766 = -1.*t1590*t9495; t10768 = -1.*t1314*t10762; t10771 = t10766 + t10768; t10776 = t1314*t9495; t10777 = -1.*t1590*t10762; t10778 = t10776 + t10777; t10783 = t2060*t10771; t10784 = t1937*t10778; t10793 = t10783 + t10784; t10796 = t1937*t10771; t10800 = -1.*t2060*t10778; t10802 = t10796 + t10800; t10806 = -1.*t2553*t10793; t10807 = t2502*t10802; t10809 = t10806 + t10807; t10812 = t2502*t10793; t10815 = t2553*t10802; t10817 = t10812 + t10815; t10825 = t2727*t10809; t10826 = t2700*t10817; t10829 = t10825 + t10826; t10833 = t2700*t10809; t10835 = -1.*t2727*t10817; t10838 = t10833 + t10835; t10861 = -1.*t215*t653; t10862 = t411*t10519; t10863 = t10861 + t10862; t10866 = -1.*t1590*t8719; t10870 = -1.*t1314*t10863; t10871 = t10866 + t10870; t10878 = t1314*t8719; t10881 = -1.*t1590*t10863; t10884 = t10878 + t10881; t10888 = t2060*t10871; t10889 = t1937*t10884; t10890 = t10888 + t10889; t10895 = t1937*t10871; t10901 = -1.*t2060*t10884; t10902 = t10895 + t10901; t10906 = -1.*t2553*t10890; t10907 = t2502*t10902; t10908 = t10906 + t10907; t10910 = t2502*t10890; t10911 = t2553*t10902; t10914 = t10910 + t10911; t10917 = t2727*t10908; t10918 = t2700*t10914; t10924 = t10917 + t10918; t10934 = t2700*t10908; t10935 = -1.*t2727*t10914; t10938 = t10934 + t10935; t10974 = -1.*t1937*t4239; t10975 = t10974 + t10681; t10977 = -1.*t2553*t4329; t10978 = t2502*t10975; t10979 = t10977 + t10978; t10981 = t2553*t10975; t10982 = t4591 + t10981; t10986 = t2727*t10979; t10988 = t2700*t10982; t10991 = t10986 + t10988; t10993 = t2700*t10979; t10996 = -1.*t2727*t10982; t10997 = t10993 + t10996; t10960 = -0.21*t1937; t10962 = -0.049*t2060; t10963 = t10960 + t10962; t10966 = 0.049*t1937; t10967 = t10966 + t2065; t11012 = t1590*t9495; t11013 = t1314*t10762; t11014 = t11012 + t11013; t11018 = -1.*t2060*t11014; t11021 = t11018 + t10784; t11023 = -1.*t1937*t11014; t11024 = t11023 + t10800; t11027 = -1.*t2553*t11021; t11028 = t2502*t11024; t11029 = t11027 + t11028; t11031 = t2502*t11021; t11032 = t2553*t11024; t11033 = t11031 + t11032; t11035 = t2727*t11029; t11036 = t2700*t11033; t11037 = t11035 + t11036; t11039 = t2700*t11029; t11041 = -1.*t2727*t11033; t11042 = t11039 + t11041; t11060 = t1590*t8719; t11062 = t1314*t10863; t11063 = t11060 + t11062; t11066 = -1.*t2060*t11063; t11068 = t11066 + t10889; t11070 = -1.*t1937*t11063; t11071 = t11070 + t10901; t11074 = -1.*t2553*t11068; t11076 = t2502*t11071; t11077 = t11074 + t11076; t11082 = t2502*t11068; t11083 = t2553*t11071; t11085 = t11082 + t11083; t11087 = t2727*t11077; t11089 = t2700*t11085; t11090 = t11087 + t11089; t11093 = t2700*t11077; t11094 = -1.*t2727*t11085; t11096 = t11093 + t11094; t11122 = -1.*t2502*t4472; t11123 = t10977 + t11122; t11127 = t2727*t11123; t11128 = t11127 + t4682; t11131 = t2700*t11123; t11132 = -1.*t2727*t4618; t11133 = t11131 + t11132; t11109 = 0.0016*t2502; t11110 = t11109 + t2625; t11113 = -0.2707*t2502; t11115 = -0.0016*t2553; t11116 = t11113 + t11115; t11151 = t1937*t11014; t11152 = t2060*t10778; t11153 = t11151 + t11152; t11156 = -1.*t2502*t11153; t11157 = t11027 + t11156; t11159 = -1.*t2553*t11153; t11162 = t11031 + t11159; t11165 = t2727*t11157; t11166 = t2700*t11162; t11168 = t11165 + t11166; t11172 = t2700*t11157; t11173 = -1.*t2727*t11162; t11174 = t11172 + t11173; t11188 = t1937*t11063; t11189 = t2060*t10884; t11192 = t11188 + t11189; t11194 = -1.*t2502*t11192; t11196 = t11074 + t11194; t11200 = -1.*t2553*t11192; t11201 = t11082 + t11200; t11203 = t2727*t11196; t11204 = t2700*t11201; t11205 = t11203 + t11204; t11207 = t2700*t11196; t11208 = -1.*t2727*t11201; t11209 = t11207 + t11208; t11237 = -1.*t2700*t4564; t11238 = t11237 + t11132; t4840 = t3013*t4725; t11225 = -0.7055*t2700; t11228 = 0.0184*t2727; t11229 = t11225 + t11228; t11231 = -0.0184*t2700; t11232 = t11231 + t2746; t11249 = t2553*t11021; t11250 = t2502*t11153; t11252 = t11249 + t11250; t11256 = -1.*t2727*t11252; t11257 = t11256 + t11166; t11259 = -1.*t2700*t11252; t11261 = t11259 + t11173; t11279 = t2553*t11068; t11280 = t2502*t11192; t11281 = t11279 + t11280; t11286 = -1.*t2727*t11281; t11287 = t11286 + t11204; t11292 = -1.*t2700*t11281; t11293 = t11292 + t11208; t11240 = -1.*t3113*t4725; t4861 = -1.*t3113*t4750; t4865 = t4840 + t4861; t11310 = 0.0216*t3013; t11311 = t11310 + t3419; t11313 = -1.1135*t3013; t11314 = -0.0216*t3113; t11315 = t11313 + t11314; t11264 = -1.*t3113*t11257; t11325 = t2700*t11252; t11326 = t2727*t11162; t11327 = t11325 + t11326; t11271 = t3013*t11257; t11296 = -1.*t3113*t11287; t11338 = t2700*t11281; t11339 = t2727*t11201; t11340 = t11338 + t11339; t11304 = t3013*t11287; p_output1(0)=1.; p_output1(1)=0; p_output1(2)=0; p_output1(3)=0; p_output1(4)=1.; p_output1(5)=0; p_output1(6)=0; p_output1(7)=0; p_output1(8)=1.; p_output1(9)=t1086*t1142 + t1217*t1298 + t1597*t1647 + t1891*t1929 + t2075*t2264 + t2395*t2494 + t2571*t2587 + t2632*t2672 + t2771*t2795 + t2917*t2965 + t3245*t3362 + t3463*t3512 - 0.0216*(t3113*t3362 + t3013*t3512) - 1.1135*(t3013*t3362 - 1.*t3113*t3512) - 1.*t447*t471*t60 - 0.1305*(t1298*t215 + t411*t471*t60) + t597*t825; p_output1(10)=t1086*t3870 + t1217*t3911 + t1597*t3970 - 0.1305*t4023 + t1891*t4125 + t2075*t4239 + t2395*t4272 + t2571*t4329 + t2632*t4472 + t2771*t4564 + t2917*t4618 + t3245*t4725 + t3463*t4750 - 0.0216*(t3113*t4725 + t3013*t4750) - 1.1135*t4865 + t3761*t597 + t447*t60*t689; p_output1(11)=0; p_output1(12)=t1217*t4959 + t1597*t4993 + t1891*t5121 + t2075*t5203 + t2395*t5270 + t2571*t5355 + t2632*t5392 + t2771*t5558 + t2917*t5655 + t3245*t5837 + t3463*t5923 - 0.0216*(t3113*t5837 + t3013*t5923) - 1.1135*(t3013*t5837 - 1.*t3113*t5923) + t597*t60*t609*t689 - 1.*t447*t653*t689 - 0.1305*(t215*t4959 + t411*t653*t689) + t1086*t60*t689*t808; p_output1(13)=t1217*t6064 + t1597*t6086 + t471*t597*t60*t609 + t1891*t6181 + t2075*t6243 + t2395*t6298 + t2571*t6334 + t2632*t6383 + t2771*t6394 + t2917*t6514 - 1.*t447*t471*t653 - 0.1305*(t215*t6064 + t411*t471*t653) + t3245*t6555 + t3463*t6571 - 0.0216*(t3113*t6555 + t3013*t6571) - 1.1135*(t3013*t6555 - 1.*t3113*t6571) + t1086*t471*t60*t808; p_output1(14)=-1.*t447*t60 - 1.*t597*t609*t653 + t1217*t6857 - 0.1305*(t411*t60 + t215*t6857) + t1597*t6897 + t1891*t7026 + t2075*t7050 + t2395*t7097 + t2571*t7166 + t2632*t7210 + t2771*t7234 + t2917*t7311 + t3245*t7359 + t3463*t7398 - 0.0216*(t3113*t7359 + t3013*t7398) - 1.1135*(t3013*t7359 - 1.*t3113*t7398) - 1.*t1086*t653*t808; p_output1(15)=t1086*t3761 + t597*t7704 + t1597*t7742 + t1217*t7774 - 0.1305*t215*t7774 + t1891*t411*t7774 + t2075*t7865 + t2395*t7888 + t2571*t7921 + t2632*t7971 + t2771*t8005 + t2917*t8049 + t3245*t8072 + t3463*t8114 - 0.0216*(t3113*t8072 + t3013*t8114) - 1.1135*(t3013*t8072 - 1.*t3113*t8114); p_output1(16)=t1142*t597 + t1086*t8174 + t1597*t8229 + t1217*t8278 - 0.1305*t215*t8278 + t1891*t411*t8278 + t2075*t8321 + t2395*t8363 + t2571*t8391 + t2632*t8428 + t2771*t8463 + t2917*t8475 + t3245*t8495 + t3463*t8520 - 0.0216*(t3113*t8495 + t3013*t8520) - 1.1135*(t3013*t8495 - 1.*t3113*t8520); p_output1(17)=t1086*t60*t609 - 1.*t597*t60*t808 + t8677 + t8731 + t8737 + t8742 + t8764 + t8779 + t8807 + t8861 + t8905 + t8937 + t8956 + t8989 + t9018 + t9042; p_output1(18)=0; p_output1(19)=0; p_output1(20)=0; p_output1(21)=0; p_output1(22)=0; p_output1(23)=0; p_output1(24)=0; p_output1(25)=0; p_output1(26)=0; p_output1(27)=0; p_output1(28)=0; p_output1(29)=0; p_output1(30)=0; p_output1(31)=0; p_output1(32)=0; p_output1(33)=0; p_output1(34)=0; p_output1(35)=0; p_output1(36)=0; p_output1(37)=0; p_output1(38)=0; p_output1(39)=t1217*t3970 - 0.1305*t215*t3970 + t1891*t3970*t411 - 0.135*t3870*t572 + t1597*t9087 + 0.135*t3761*t914 + t2075*t9170 + t2395*t9217 + t2571*t9236 + t2632*t9267 + t2771*t9298 + t2917*t9315 + t3245*t9357 + t3463*t9378 - 0.0216*(t3113*t9357 + t3013*t9378) - 1.1135*(t3013*t9357 - 1.*t3113*t9378); p_output1(40)=0.135*t8174*t914 - 0.135*t572*t9481 + t1597*t9489 + t1217*t9495 - 0.1305*t215*t9495 + t1891*t411*t9495 + t2075*t9575 + t2395*t9629 + t2571*t9679 + t2632*t9736 + t2771*t9759 + t2917*t9777 + t3245*t9805 + t3463*t9828 - 0.0216*(t3113*t9805 + t3013*t9828) - 1.1135*(t3013*t9805 - 1.*t3113*t9828); p_output1(41)=-0.135*t572*t60*t808 + t8677 + t8731 + t8737 + t8742 + t8764 + t8779 + t8807 + t8861 + t8905 + t8937 + t8956 + t8989 + t9018 + t9042 + 0.135*t60*t609*t914; p_output1(42)=t10077*t2571 + t10117*t2632 + t10148*t2771 + t10163*t2917 - 0.0216*(t10220*t3013 + t10179*t3113) - 1.1135*(t10179*t3013 - 1.*t10220*t3113) + t10179*t3245 + t10220*t3463 + t1891*t4023 + t1314*t2075*t4023 - 1.*t1590*t2395*t4023 - 0.1305*(-1.*t3911*t411 - 1.*t215*t60*t689) + t60*t689*t9940 + t3911*t9967; p_output1(43)=t10327*t1891 + t10327*t1314*t2075 - 1.*t10327*t1590*t2395 + t10370*t2571 + t10393*t2632 + t10404*t2771 + t10431*t2917 - 0.0216*(t10469*t3013 + t10455*t3113) - 1.1135*(t10455*t3013 - 1.*t10469*t3113) + t10455*t3245 + t10469*t3463 - 0.1305*(t1893 - 1.*t10307*t411) + t471*t60*t9940 + t10307*t9967; p_output1(44)=t10537*t1891 + t10537*t1314*t2075 - 1.*t10537*t1590*t2395 + t10562*t2571 + t10568*t2632 + t10578*t2771 + t10589*t2917 - 0.0216*(t10615*t3013 + t10601*t3113) - 1.1135*(t10601*t3013 - 1.*t10615*t3113) + t10601*t3245 + t10615*t3463 - 0.1305*(-1.*t10519*t411 + t215*t653) - 1.*t653*t9940 + t10519*t9967; p_output1(45)=t10671*t2395 + t10683*t2571 + t10675*t2632 + t10717*t2771 + t10695*t2917 - 1.1135*(t10736*t3013 - 1.*t10724*t3113) - 0.0216*(t10724*t3013 + t10736*t3113) + t10736*t3245 + t10724*t3463 + t10652*t3970 + t10662*t4125 + t2075*t4272; p_output1(46)=t10662*t10762 + t10778*t2075 + t10771*t2395 + t10802*t2571 + t10793*t2632 + t10817*t2771 + t10809*t2917 - 1.1135*(t10838*t3013 - 1.*t10829*t3113) - 0.0216*(t10829*t3013 + t10838*t3113) + t10838*t3245 + t10829*t3463 + t10652*t9495; p_output1(47)=t10662*t10863 + t10884*t2075 + t10871*t2395 + t10902*t2571 + t10890*t2632 + t10914*t2771 + t10908*t2917 - 1.1135*(t10938*t3013 - 1.*t10924*t3113) - 0.0216*(t10924*t3013 + t10938*t3113) + t10938*t3245 + t10924*t3463 + t10652*t8719; p_output1(48)=t10975*t2571 + t10982*t2771 + t10979*t2917 - 1.1135*(t10997*t3013 - 1.*t10991*t3113) - 0.0216*(t10991*t3013 + t10997*t3113) + t10997*t3245 + t10991*t3463 + t10963*t4239 + t10967*t4272 + t2632*t4329; p_output1(49)=t10778*t10967 + t10963*t11014 + t11024*t2571 + t11021*t2632 + t11033*t2771 + t11029*t2917 - 1.1135*(t11042*t3013 - 1.*t11037*t3113) - 0.0216*(t11037*t3013 + t11042*t3113) + t11042*t3245 + t11037*t3463; p_output1(50)=t10884*t10967 + t10963*t11063 + t11071*t2571 + t11068*t2632 + t11085*t2771 + t11077*t2917 - 1.1135*(t11096*t3013 - 1.*t11090*t3113) - 0.0216*(t11090*t3013 + t11096*t3113) + t11096*t3245 + t11090*t3463; p_output1(51)=t11123*t2917 - 1.1135*(t11133*t3013 - 1.*t11128*t3113) - 0.0216*(t11128*t3013 + t11133*t3113) + t11133*t3245 + t11128*t3463 + t11110*t4329 + t11116*t4472 + t2771*t4618; p_output1(52)=t11021*t11110 + t11116*t11153 + t11162*t2771 + t11157*t2917 - 1.1135*(t11174*t3013 - 1.*t11168*t3113) - 0.0216*(t11168*t3013 + t11174*t3113) + t11174*t3245 + t11168*t3463; p_output1(53)=t11068*t11110 + t11116*t11192 + t11201*t2771 + t11196*t2917 - 1.1135*(t11209*t3013 - 1.*t11205*t3113) - 0.0216*(t11205*t3013 + t11209*t3113) + t11209*t3245 + t11205*t3463; p_output1(54)=-1.1135*(t11240 + t11238*t3013) + t11238*t3245 + t11229*t4564 + t11232*t4618 + t3463*t4725 - 0.0216*(t11238*t3113 + t4840); p_output1(55)=t11162*t11232 + t11229*t11252 - 1.1135*(t11264 + t11261*t3013) - 0.0216*(t11271 + t11261*t3113) + t11261*t3245 + t11257*t3463; p_output1(56)=t11201*t11232 + t11229*t11281 - 1.1135*(t11296 + t11293*t3013) - 0.0216*(t11304 + t11293*t3113) + t11293*t3245 + t11287*t3463; p_output1(57)=t11311*t4725 + t11315*t4750 - 1.1135*(t11240 - 1.*t3013*t4750) - 0.0216*t4865; p_output1(58)=t11257*t11311 + t11315*t11327 - 1.1135*(t11264 - 1.*t11327*t3013) - 0.0216*(t11271 - 1.*t11327*t3113); p_output1(59)=t11287*t11311 + t11315*t11340 - 1.1135*(t11296 - 1.*t11340*t3013) - 0.0216*(t11304 - 1.*t11340*t3113); } Eigen::Matrix<double,3,20> Jp_toe_joint_right(const Eigen::Matrix<double,20,1> &var1) //void Jp_toe_joint_right(Eigen::Matrix<double,3,20> &p_output1, const Eigen::Matrix<double,20,1> &var1) { /* Call Subroutines */ Eigen::Matrix<double,3,20> p_output1; output1(p_output1, var1); return p_output1; }
25.230026
347
0.661082
UMich-BipedLab
c327ed9f1e99830746560356017923f4bbf4014b
4,996
cpp
C++
lib/output_file.test.cpp
milasudril/wad64
c656710513013041e8efc29505d328abbbf5e843
[ "MIT" ]
null
null
null
lib/output_file.test.cpp
milasudril/wad64
c656710513013041e8efc29505d328abbbf5e843
[ "MIT" ]
2
2021-02-02T19:40:39.000Z
2021-02-21T10:25:02.000Z
lib/output_file.test.cpp
milasudril/wad64
c656710513013041e8efc29505d328abbbf5e843
[ "MIT" ]
null
null
null
//@ { //@ "targets":[{"name":"output_file.test","type":"application", "autorun":1}] //@ } #include "./output_file.hpp" #include "./membuffer.hpp" #include "./file_structs.hpp" #include <cassert> #include <algorithm> #include <random> #include <cstring> namespace { Wad64::MemBuffer generateData() { Wad64::WadInfo header{}; header.identification = Wad64::MagicNumber; header.numlumps = 4; header.infotablesofs = sizeof(header); Wad64::MemBuffer buffer; write(buffer, std::span{reinterpret_cast<std::byte const*>(&header), sizeof(header)}, 0); assert(std::size(buffer.data) == sizeof(header)); std::array<Wad64::FileLump, 4> lumps{}; std::array<std::string, 4> names{"Bar", "Bulle", "Foo", "Kaka"}; std::array<int, 4> start_ofs{0, 1, 3, 6}; std::array<int, 4> sizes{1, 2, 3, 12}; constexpr auto startoffset = sizeof(header) + sizeof(lumps); for(int k = 0; k < 4; ++k) { lumps[k].filepos = startoffset + start_ofs[k]; lumps[k].size = sizes[k]; std::ranges::copy(names[k], std::data(lumps[k].name)); } std::minstd_rand rng; std::ranges::shuffle(lumps, rng); write(buffer, std::span{reinterpret_cast<std::byte const*>(&lumps), sizeof(lumps)}, header.infotablesofs); char const* hello = "Hello, World"; write(buffer, std::span{reinterpret_cast<std::byte const*>(hello), 12}, 6 + startoffset); return buffer; } } namespace Testcases { void wad64OutputFileCreationAllowedFileDoesNotExist() //010 { auto data = generateData(); Wad64::Archive archive{std::ref(data)}; Wad64::OutputFile output{archive, "New file", Wad64::FileCreationMode::AllowCreation()}; assert(archive.stat("New file").has_value()); } void wad64OutputFileCreationNotAllowedFileExists() //101 { auto data = generateData(); Wad64::Archive archive{std::ref(data)}; auto const& dir = archive.ls(); Wad64::OutputFile output{ archive, "Kaka", Wad64::FileCreationMode::AllowOverwriteWithTruncation()}; assert(std::size(archive.ls()) == std::size(dir)); } void wad64OutputFileCreationNotAllowedFileDoesNotExist() //100 { auto data = generateData(); Wad64::Archive archive{std::ref(data)}; try { Wad64::OutputFile output{ archive, "New file", Wad64::FileCreationMode::AllowOverwriteWithTruncation()}; abort(); } catch(...) { } } void wad64OutputFileCreationAllowedOverwriteDisallowedFileExists() //011 { auto data = generateData(); Wad64::Archive archive{std::ref(data)}; try { Wad64::OutputFile output{archive, "Kaka", Wad64::FileCreationMode::AllowCreation()}; abort(); } catch(...) { } } void wad64OutputFileCreationAllowedOverwriteAllowedFileExists() // 111 { auto data = generateData(); Wad64::Archive archive{std::ref(data)}; auto const& dir = archive.ls(); Wad64::OutputFile output{ archive, "Kaka", Wad64::FileCreationMode::AllowCreation().allowOverwriteWithTruncation()}; assert(std::size(archive.ls()) == std::size(dir)); } void wad64OutputFileCreationAllowedOverwriteAllowedFileDoesNotExist() // 110 { auto data = generateData(); Wad64::Archive archive{std::ref(data)}; auto const dir = archive.ls(); Wad64::OutputFile output{ archive, "New file", Wad64::FileCreationMode::AllowCreation().allowOverwriteWithTruncation()}; assert(std::size(archive.ls()) == std::size(dir) + 1); assert(archive.stat("New file").has_value()); } void wad64OoutputFileWrite() { auto data = generateData(); auto const data_old = data.data; { Wad64::Archive archive{std::ref(data)}; { Wad64::OutputFile output{ archive, "New file", Wad64::FileCreationMode::AllowCreation()}; assert(output.size() == 0); assert(output.tell() == 0); constexpr std::string_view text_a{"This is a test"}; auto const n_written = output.write(std::as_bytes(std::span{text_a})); assert(n_written == std::size(text_a)); assert(output.size() == static_cast<int64_t>(std::size(text_a))); assert(output.tell() == output.size()); output.seek(-4, Wad64::SeekMode::Cur); assert(output.tell() == output.size() - 4); constexpr std::string_view text_b{"foobar"}; output.write(std::as_bytes(std::span{text_b})); assert(output.size() == static_cast<int64_t>(std::size(text_a)) - 4 + 6); assert(data_old == data.data); } assert(data.data != data_old); auto item = archive.stat("New file"); assert(item->end - item->begin == strlen("This is a foobar")); } } } int main() { Testcases::wad64OutputFileCreationAllowedFileDoesNotExist(); Testcases::wad64OutputFileCreationNotAllowedFileExists(); Testcases::wad64OutputFileCreationNotAllowedFileDoesNotExist(); Testcases::wad64OutputFileCreationAllowedOverwriteDisallowedFileExists(); Testcases::wad64OutputFileCreationAllowedOverwriteAllowedFileExists(); Testcases::wad64OutputFileCreationAllowedOverwriteAllowedFileDoesNotExist(); Testcases::wad64OoutputFileWrite(); return 0; }
29.216374
91
0.681946
milasudril
c328172ec3c8b90d2784ecdac41a75333a788ec6
1,089
cpp
C++
src/FalconEngine/Graphics/Renderer/Platform/OpenGL/OGLTexture1d.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
null
null
null
src/FalconEngine/Graphics/Renderer/Platform/OpenGL/OGLTexture1d.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
null
null
null
src/FalconEngine/Graphics/Renderer/Platform/OpenGL/OGLTexture1d.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
1
2021-08-25T07:39:02.000Z
2021-08-25T07:39:02.000Z
#include <FalconEngine/Graphics/Renderer/Platform/OpenGL/OGLTexture1d.h> #include <cstring> #include <FalconEngine/Graphics/Renderer/Platform/OpenGL/OGLUtility.h> namespace FalconEngine { /************************************************************************/ /* Constructors and Destructor */ /************************************************************************/ PlatformTexture1d::PlatformTexture1d(const Texture1d *texture) : PlatformTexture(texture) { // Bind newly created texture GLuint textureBindingPrevious = BindTexture(mTexturePtr->mType, mTextureObj); { glTexStorage1D(GL_TEXTURE_1D, 1, mFormatInternal, mDimension[0]); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, mBufferObj); { glTexSubImage1D(GL_TEXTURE_1D, 0, 0, mDimension[0], mFormat, mType, nullptr); } glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } // Restore previous texture binding BindTexture(mTexturePtr->mType, textureBindingPrevious); } PlatformTexture1d::~PlatformTexture1d() { } }
26.560976
89
0.599633
LiuYiZhou95
c328781e3a11445abc2486f53567e3898e09e2e8
1,152
cpp
C++
src/Graphics/Renderer.cpp
Tojrsen/Callie
42f4a573c468b5b99c1ab440583d5b5930a0cff2
[ "Apache-2.0" ]
null
null
null
src/Graphics/Renderer.cpp
Tojrsen/Callie
42f4a573c468b5b99c1ab440583d5b5930a0cff2
[ "Apache-2.0" ]
null
null
null
src/Graphics/Renderer.cpp
Tojrsen/Callie
42f4a573c468b5b99c1ab440583d5b5930a0cff2
[ "Apache-2.0" ]
null
null
null
#include <clpch.h> #include <GL/glew.h> #include <Graphics/Renderer.h> namespace cl{ int Renderer::Init(){ GLenum err = glewInit(); if (GLEW_OK != err){ CL_CORE_ASSERT("Unable to initialize GLEW!", glewGetErrorString(err)); return -1; } GLCall(glEnable(GL_DEPTH_TEST)); return 0; } void Renderer::SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height){ GLCall(glViewport(x, y, width, height)); } void Renderer::OnWindowResize(const unsigned int width, const unsigned int height){ GLCall(glViewport(0, 0, width, height)); } void Renderer::SetClearColor(const glm::vec4& color){ GLCall(glClearColor(color.r, color.g, color.b, color.a)); } void Renderer::Clear(){ GLCall(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); } void Renderer::Draw(unsigned int count, bool isWireframe=false){ if (!isWireframe){ GLCall(glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, 0)); } else{ GLCall(glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, 0)); } } }
28.097561
88
0.626736
Tojrsen
c3289e018da5b6e29b46a65809c7ac1017ae32df
1,367
cpp
C++
.vscode/cquery_cached_index/c@@users@jeste@vex u@towertakeover@stackbot/src@libstack@drive.cpp
kettering-vex-u/TowerTakeover
a6c5445faa0a0c99c66f16a7104f6ba7b38ea250
[ "MIT" ]
null
null
null
.vscode/cquery_cached_index/c@@users@jeste@vex u@towertakeover@stackbot/src@libstack@drive.cpp
kettering-vex-u/TowerTakeover
a6c5445faa0a0c99c66f16a7104f6ba7b38ea250
[ "MIT" ]
null
null
null
.vscode/cquery_cached_index/c@@users@jeste@vex u@towertakeover@stackbot/src@libstack@drive.cpp
kettering-vex-u/TowerTakeover
a6c5445faa0a0c99c66f16a7104f6ba7b38ea250
[ "MIT" ]
null
null
null
#include "main.h" using namespace okapi; std::shared_ptr<okapi::ChassisControllerIntegrated> controller; std::unique_ptr<okapi::Motor> dl1, dl2, dl3; std::unique_ptr<okapi::Motor> dr1, dr2, dr3; namespace drive { void init() { // creating a ChassisControl object using the MotorGroups defined above, // setting the gearset to red (36:1, 100rpm), // setting the wheel diameter to 3.5in, // and setting the drivetrain width to 24in controller = ChassisControllerFactory::createPtr( {DRIVE_LEFT_1, DRIVE_LEFT_2, DRIVE_LEFT_3}, {-DRIVE_RIGHT_1, -DRIVE_RIGHT_2, -DRIVE_RIGHT_3}, AbstractMotor::gearset::red, {3.5_in, 24_in} ); dl1 = std::make_unique<okapi::Motor>(DRIVE_LEFT_1); dl2 = std::make_unique<okapi::Motor>(DRIVE_LEFT_2); dl3 = std::make_unique<okapi::Motor>(DRIVE_LEFT_3); dr1 = std::make_unique<okapi::Motor>(DRIVE_RIGHT_1); dr2 = std::make_unique<okapi::Motor>(DRIVE_RIGHT_2); dr3 = std::make_unique<okapi::Motor>(DRIVE_RIGHT_3); } // arcade drive control: // left joystick controls throttle, // right joystick controls rotation void arcadeDrive(double throttle, double rotation) { controller->arcade(throttle, rotation); } // tank drive control: // left joystick controls left side, // right joystick controls right side void tankDrive(double left, double right) { controller->tank(left, right); } }
30.377778
74
0.727871
kettering-vex-u
c336ad5ddfea4ebd9a85a629cdf94c9c4a61e99b
421
hpp
C++
src/settingspage.hpp
Chepik/SpaceInvaders1
8547cfaaa33d7ccddd8c58391d92dd97864d9e5f
[ "MIT" ]
null
null
null
src/settingspage.hpp
Chepik/SpaceInvaders1
8547cfaaa33d7ccddd8c58391d92dd97864d9e5f
[ "MIT" ]
null
null
null
src/settingspage.hpp
Chepik/SpaceInvaders1
8547cfaaa33d7ccddd8c58391d92dd97864d9e5f
[ "MIT" ]
null
null
null
#pragma once #include <QWidget> #include <string> namespace Ui { class SettingsPage; } class SettingsPage : public QWidget { Q_OBJECT public: explicit SettingsPage(QWidget *parent = 0); ~SettingsPage(); private slots: void on_menuButton_clicked(); /// /// It stores setting data into a file. /// void on_saveButton_clicked(); signals: void moveToMenuPage(); private: Ui::SettingsPage *ui; };
12.757576
45
0.695962
Chepik
c337a0816a0f36567cbccc2405a833339cfd7830
11,150
cpp
C++
Enclave/src/enclave_forward.cpp
yy738686337/sgx_project_v2
20a8db8a2aecac0aead50e00d3f8515c46b9af9a
[ "Apache-2.0" ]
null
null
null
Enclave/src/enclave_forward.cpp
yy738686337/sgx_project_v2
20a8db8a2aecac0aead50e00d3f8515c46b9af9a
[ "Apache-2.0" ]
null
null
null
Enclave/src/enclave_forward.cpp
yy738686337/sgx_project_v2
20a8db8a2aecac0aead50e00d3f8515c46b9af9a
[ "Apache-2.0" ]
null
null
null
#include "enclave.h" extern "C" { #include "ecall_batchnorm_layer.h" } #include "types.h" // void ecall_gemm(int TA, int TB, int M, int N, int K, float ALPHA, // float *A, int lda, // float *B, int ldb, // float BETA, // float *C, int ldc, int a_size, int b_size, int c_size) { // crypt_aux((unsigned char*)pass, pass_len, (unsigned char*)B, 4, b_size); // //rc4_crypt("lizheng", 7, C, c_size); // gemm(TA, TB, M, N, K, ALPHA, A, lda, B, ldb, BETA, C, ldc); // crypt_aux((unsigned char*)pass, pass_len, (unsigned char*)C, 4, c_size); // } void ecall_avgpool_forward(int batch, int c, int fig_size, float *input, int input_len, float *output, int output_len) { crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float), input_len); int b, k, i; for (b = 0; b < batch; ++b) { for (k = 0; k < c; ++k) { int out_index = k + b * c; output[out_index] = 0; for (i = 0; i < fig_size; ++i) { int in_index = i + fig_size * (k + b * c); output[out_index] += input[in_index]; } output[out_index] /= fig_size; } } crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)output, sizeof(float), output_len); } void ecall_forward_connected_layer(int TA, int TB, int batch, int outputs, int inputs, int batch_normalize, int train, float *rolling_mean, float *rolling_variance, float *scales, float *x, float *x_norm, float *input, int lda, float *weights, int ldb, float *output, int ldc, long a_size, long b_size, long c_size, float *biases, float *mean, float *variance, ACTIVATION a) { int M = batch; int K = inputs; int N = outputs; crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * inputs, batch); #ifdef DNNL dnnl_transfer_layer_data data; data.batch = batch; data.input = input; data.ic = inputs; data.oc = outputs; data.output = output; data.biases = biases; data.weights = weights; run_dnnl_function(dnnl_connected_forward, &data); #else gemm(0, 1, M, N, K, 1, input, K, weights, K, 1, output, N); add_bias(output, biases, batch, outputs, 1); #endif if (batch_normalize) { forward_batchnorm_layer(CONNECTED, train, outputs, batch, outputs, 1, 1, output, input, mean, rolling_mean, variance, rolling_variance, x, x_norm, scales); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)x, sizeof(float) * N, batch); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)x_norm, sizeof(float) * N, batch); } // add_bias(output, biases, batch, outputs, 1); activate_array(output, c_size, a); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)output, sizeof(float) * N, batch); } void ecall_forward_maxpool_layer(int pad, int raw_h, int raw_w, int out_h, int out_w, int c, int batch, int size, int stride, float *input, int input_len, float *output, int out_len, int *indices) { crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * raw_h * raw_w * c, batch); int b, i, j, k, m, n; // 初始偏移设定为四周补0长度的负值 int w_offset = -pad; int h_offset = -pad; // 获取当前层的输出尺寸 int h = out_h; int w = out_w; // 获取当前层输入图像的通道数,为什么是输入通道数?不应该为输出通道数吗?实际二者没有区别,对于最大池化层来说,输入有多少通道,输出就有多少通道! // 遍历batch中每一张输入图片,计算得到与每一张输入图片具有相同通道数的输出图 for (b = 0; b < batch; ++b) { // 对于每张输入图片,将得到通道数一样的输出图,以输出图为基准,按输出图通道,行,列依次遍历 // (这对应图像在output的存储方式,每张图片按行铺排成一大行,然后图片与图片之间再并成一行)。 // 以输出图为基准进行遍历,最终循环的总次数刚好覆盖池化核在输入图片不同位置进行池化操作。 for (k = 0; k < c; ++k) { for (i = 0; i < h; ++i) { for (j = 0; j < w; ++j) { // out_index为输出图中的索引:out_index = b * c * w * h + k * w * h + h * w + w,展开写可能更为清晰些 int out_index = j + w * (i + h * (k + c * b)); float max = -FLT_MAX; // FLT_MAX为c语言中float.h定义的对大浮点数,此处初始化最大元素值为最小浮点数 int max_i = -1; // 最大元素值的索引初始化为-1 // 下面两个循环回到了输入图片,计算得到的cur_h以及cur_w都是在当前层所有输入元素的索引,内外循环的目的是找寻输入图像中, // 以(h_offset + i*l.stride, w_offset + j*l.stride)为左上起点,尺寸为l.size池化区域中的最大元素值max及其在所有输入元素中的索引max_i for (n = 0; n < size; ++n) { for (m = 0; m < size; ++m) { // cur_h,cur_w是在所有输入图像中第k通道中的cur_h行与cur_w列,index是在所有输入图像元素中的总索引。 // 为什么这里少一层对输入通道数的遍历循环呢?因为对于最大池化层来说输入与输出通道数是一样的,并在上面的通道数循环了! int cur_h = h_offset + i * stride + n; int cur_w = w_offset + j * stride + m; int index = raw_w * (cur_h + raw_h * (k + b * c)) + cur_w; // 边界检查:正常情况下,是不会越界的,但是如果有补0操作,就会越界了,这里的处理方式是直接让这些元素值为-FLT_MAX // (注意虽然称之为补0操作,但实际不是补0),总之,这些补的元素永远不会充当最大元素值。 int valid = (cur_h >= 0 && cur_h < raw_h && cur_w >= 0 && cur_w < raw_w); float val = (valid != 0) ? input[index] : -FLT_MAX; // 记录这个池化区域中的最大的元素值及其在所有输入元素中的总索引 max_i = (val > max) ? index : max_i; max = (val > max) ? val : max; } } // 由此得到最大池化层每一个输出元素值及其在所有输入元素中的总索引。 // 为什么需要记录每个输出元素值对应在输入元素中的总索引呢?因为在下面的反向过程中需要用到,在计算当前最大池化层上一层网络的敏感度时, // 需要该索引明确当前层的每个元素究竟是取上一层输出(也即上前层输入)的哪一个元素的值,具体见下面backward_maxpool_layer()函数的注释。 output[out_index] = max; indices[out_index] = max_i; } } } } crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)output, sizeof(float) * out_h * out_w * c, batch); } void ecall_forward_convolutional_layer(int batch, int ic, int h, int w, int size, int stride, int pad, int n_filters, int out_h, int out_w, float *weights, int weight_len, float *input, int in_len, float *output, int out_len, float *biases, int bias_len, int batch_normalize, int train, int outputs, float *rolling_mean, float *rolling_variance, float *scales, float *x, float *x_norm, float *mean, float *variance, ACTIVATION activation) { int i; int m = n_filters; // 该层卷积核个数 int k = size * size * ic; // 该层每个卷积核的参数元素个数 int n = out_h * out_w; // 该层每个特征图的尺寸(元素个数) int fig_size = h * ic * w; crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * fig_size, batch); #ifdef DNNL dnnl_transfer_layer_data data = {}; data.batch = batch; data.h = h; data.w = w; data.ic = ic; data.oc = m; data.out_h = out_h; data.out_w = out_w; data.pad = pad; data.stride = stride; data.size = size; data.input = input; data.weights = weights; data.biases = biases; data.output = output; run_dnnl_function(dnnl_conv_forward, &data); #else float *a = weights; // 所有卷积核(也即权重),元素个数为l.n*l.c*l.size*l.size,按行存储,共有l*n行,l.c*l.size*l.size列 float *b = (float *)calloc(out_h * out_w * size * size * ic, sizeof(float)); float *c = output; // 存储一张输入图片(多通道)所有的输出特征图(输入图片是多通道的,输出图片也是多通道的,有多少个卷积核就有多少个通道,每个卷积核得到一张特征图即为一个通道) for (i = 0; i < batch; ++i) { im2col_cpu(input, ic, h, w, size, stride, pad, b); gemm(0, 0, m, n, k, 1, a, k, b, n, 1, c, n); c += n * m; input += ic * h * w; } if (batch_normalize) { forward_batchnorm_layer(CONNECTED, train, outputs, batch, m, out_h, out_w, output, input, mean, rolling_mean, variance, rolling_variance, x, x_norm, scales); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)x, sizeof(float) * outputs, batch); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)x_norm, sizeof(float) * outputs, batch); } add_bias(output, biases, batch, n_filters, out_h * out_w); #endif activate_array(output, m * n * batch, activation); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)output, sizeof(float) * n * m, batch); } void ecall_forward_cost_layer(COST_TYPE cost_type, int batch, int in_len, float *input, size_t input_size, float *truth, float *delta, float *output, float *cost) { crypt_aux((uint8_t *)pass, pass_len, (uint8_t *)input, sizeof(float) * in_len, batch); crypt_aux((uint8_t *)pass, pass_len, (uint8_t *)truth, sizeof(float) * 1, batch); if (cost_type == SMOOTH) { smooth_l1_cpu(input_size, input, truth, delta, output); } else if (cost_type == L1) { l1_cpu(input_size, input, truth, delta, output); } else if (cost_type == CE) { ce_forward(batch, in_len, input, truth, delta, output); } else { l2_cpu(input_size, input, truth, delta, output); } cost[0] = sum_array(output, input_size); } void ecall_forward_dropout_layer(int train, size_t batch, size_t inputs, float probability, float scale, size_t, float *rand, float *input) { crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * inputs, batch); int i; // 如果当前网络不是处于训练阶段而处于测试阶段,则直接返回(使用inverted dropout带来的方便) if (!train) return; // 遍历dropout层的每一个输入元素(包含整个batch的),按照指定的概率l.probability置为0或者按l.scale缩放 for (i = 0; i < batch * inputs; ++i) { // 产生一个0~1之间均匀分布的随机数 float r = rand_uniform(0, 1); // 每个输入元素都对应一个随机数,保存在l.rand中 rand[i] = r; // 如果r小于l.probability(l.probability是舍弃概率),则舍弃该输入元素,注意,舍弃并不是删除, // 而是将其值置为0,所以输入元素个数总数没变(因故输出元素个数l.outputs等于l.inputs) if (r < probability) input[i] = 0; // 否则保留该输入元素,并乘以比例因子 else input[i] *= scale; } crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * inputs, batch); }
39.964158
139
0.530314
yy738686337
c33aa15e40f13b90ecbc39f24e23d934fd8e17db
1,817
cpp
C++
Source code/Game/Source files/Graphics/Texture.cpp
Ansoulom/cat-rush
e99b18d7bf7b72f0e4918f0cc24a190dd55747e6
[ "MIT" ]
null
null
null
Source code/Game/Source files/Graphics/Texture.cpp
Ansoulom/cat-rush
e99b18d7bf7b72f0e4918f0cc24a190dd55747e6
[ "MIT" ]
null
null
null
Source code/Game/Source files/Graphics/Texture.cpp
Ansoulom/cat-rush
e99b18d7bf7b72f0e4918f0cc24a190dd55747e6
[ "MIT" ]
null
null
null
#include "Texture.h" #include "Game_core.h" #include <SDL_image.h> #include <SDL_ttf.h> #include "Colors.h" namespace Game { namespace Graphics { Texture::Texture(Renderer& renderer, const std::filesystem::path& file_path) : Texture{ std::unique_ptr<SDL_Surface, Sdl_deleter>{IMG_Load(file_path.string().c_str()), Sdl_deleter{}}, renderer } { } Texture::Texture(Renderer& renderer, const std::string& text, Color text_color, const Text::Font& font) : Texture{ std::unique_ptr<SDL_Surface, Sdl_deleter>{ TTF_RenderText_Blended( &Wrappers::Sdl_wrapper::get_font(font), text.c_str(), Wrappers::Sdl_wrapper::get_color(text_color)), Sdl_deleter{} }, renderer } { } Texture::Texture(Texture&& other) noexcept : texture_{move(other.texture_)}, width_{other.width_}, height_{other.height_} { } Texture& Texture::operator=(Texture&& other) noexcept { texture_ = move(other.texture_); width_ = other.width_; height_ = other.height_; return *this; } Texture::Texture(std::unique_ptr<SDL_Surface, Sdl_deleter> surface, Renderer& renderer) : texture_{}, width_{0}, height_{0} { if(!surface) { throw std::runtime_error{std::string{"Could not create surface: "} + SDL_GetError()}; } texture_ = std::unique_ptr<SDL_Texture, Sdl_deleter>{ SDL_CreateTextureFromSurface(renderer.sdl_renderer_.get(), surface.get()), Sdl_deleter{} }; if(!texture_) { throw std::runtime_error{std::string{"Could not create texture from surface: "} + SDL_GetError()}; } SDL_SetTextureBlendMode(texture_.get(), SDL_BLENDMODE_BLEND); width_ = surface->w; height_ = surface->h; } int Texture::width() const { return width_; } int Texture::height() const { return height_; } } }
23
105
0.672537
Ansoulom
c33da97875df8f8a499fb3c743b29be6118380bc
2,950
cpp
C++
lib/Error.cpp
OMAS-IIIF/cserve
8932ed36fa6f1935b3db97ed556f876e2e459c4b
[ "MIT" ]
1
2021-06-24T06:10:07.000Z
2021-06-24T06:10:07.000Z
lib/Error.cpp
OMAS-IIIF/cserve
8932ed36fa6f1935b3db97ed556f876e2e459c4b
[ "MIT" ]
null
null
null
lib/Error.cpp
OMAS-IIIF/cserve
8932ed36fa6f1935b3db97ed556f876e2e459c4b
[ "MIT" ]
null
null
null
/* * Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer, * Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton. * This file is part of Sipi. * Sipi is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * Sipi 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. * Additional permission under GNU AGPL version 3 section 7: * If you modify this Program, or any covered work, by linking or combining * it with Kakadu (or a modified version of that library) or Adobe ICC Color * Profiles (or a modified version of that library) or both, containing parts * covered by the terms of the Kakadu Software Licence or Adobe Software Licence, * or both, the licensors of this Program grant you additional permission * to convey the resulting work. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public * License along with Sipi. If not, see <http://www.gnu.org/licenses/>. */ #include <cstring> // std::strerror #include <sstream> // std::ostringstream #include "Error.h" namespace cserve { Error::Error(const char *file_p, const int line_p, const char *msg, int errno_p) : runtime_error( std::string(msg) + "\nFile: " + std::string(file_p) + std::string(" Line: ") + std::to_string(line_p)), line(line_p), file(file_p), message(msg), sysErrno(errno_p) { } //============================================================================ Error::Error(const char *file_p, const int line_p, const std::string &msg, int errno_p) : runtime_error( std::string(msg) + "\nFile: " + std::string(file_p) + std::string(" Line: ") + std::to_string(line_p)), line(line_p), file(file_p), message(msg), sysErrno(errno_p) { } //============================================================================ std::string Error::to_string(void) const { std::ostringstream err_stream; err_stream << "Error at [" << file << ": " << line << "]"; if (sysErrno != 0) err_stream << " (system error: " << std::strerror(sysErrno) << ")"; err_stream << ": " << message; return err_stream.str(); } //============================================================================ std::ostream &operator<<(std::ostream &out_stream, const Error &rhs) { std::string errStr = rhs.to_string(); out_stream << errStr; return out_stream; } //============================================================================ }
42.753623
108
0.581695
OMAS-IIIF
c3400e35727d8d10b38cbfff47efe2051869ec33
22,148
cpp
C++
Engine/source/platformX86UNIX.alt/x86UNIXWindow.client.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
46
2015-01-05T17:34:43.000Z
2022-01-04T04:03:09.000Z
Engine/source/platformX86UNIX.alt/x86UNIXWindow.client.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
10
2015-01-20T23:14:46.000Z
2019-04-05T22:04:15.000Z
Engine/source/platformX86UNIX.alt/x86UNIXWindow.client.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
9
2015-08-08T18:46:06.000Z
2021-02-01T13:53:20.000Z
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "windowManager/x11/x11WindowMgr.h" #include "console/console.h" #include "core/stream/fileStream.h" //#include "game/resource.h" //#include "game/version.h" #include "math/mRandom.h" #include "platformX86UNIX/platformX86UNIX.h" #include "platformX86UNIX/x86UNIXStdConsole.h" #include "platform/input/event.h" //#include "platform/gameInterface.h" #include "platform/platform.h" //#include "platform/platformAL.h" #include "platform/platformInput.h" //#include "platform/platformVideo.h" #include "platform/profiler.h" //#include "platformX86UNIX/platformGL.h" //#include "platformX86UNIX/x86UNIXOGLVideo.h" #include "platformX86UNIX/x86UNIXState.h" #ifndef TORQUE_DEDICATED #include "platformX86UNIX/x86UNIXMessageBox.h" #include "platformX86UNIX/x86UNIXInputManager.h" #endif #include <errno.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> // fork, execvp, chdir #include <time.h> // nanosleep #ifndef TORQUE_DEDICATED #include <X11/Xlib.h> #include <X11/Xos.h> #include <SDL/SDL.h> #include <SDL/SDL_syswm.h> #include <SDL/SDL_version.h> #endif static x86UNIXPlatformState _x86UNIXState_Obj; x86UNIXPlatformState *x86UNIXState = &_x86UNIXState_Obj; bool DisplayPtrManager::sgDisplayLocked = false; LockFunc_t DisplayPtrManager::sgLockFunc = NULL; LockFunc_t DisplayPtrManager::sgUnlockFunc = NULL; static U32 lastTimeTick; static MRandomLCG sgPlatRandom; #ifndef TORQUE_DEDICATED extern void InstallRedBookDevices(); extern void PollRedbookDevices(); extern bool InitOpenGL(); // This is called when some X client sends // a selection event (e.g. SelectionRequest) // to the window extern void NotifySelectionEvent(XEvent& event); #endif //------------------------------------------------------------------------------ static S32 ParseCommandLine(S32 argc, const char **argv, Vector<char*>& newCommandLine) { x86UNIXState->setExePathName(argv[0]); bool foundDedicated = false; for ( int i=0; i < argc; i++ ) { // look for platform specific args if (dStrcmp(argv[i], "-version") == 0) { dPrintf("%s (built on %s)\n", getVersionString(), getCompileTimeString()); dPrintf("gcc: %s\n", __VERSION__); return 1; } if (dStrcmp(argv[i], "-cdaudio") == 0) { x86UNIXState->setCDAudioEnabled(true); continue; } if (dStrcmp(argv[i], "-dedicated") == 0) { foundDedicated = true; // no continue because dedicated is also handled by script } if (dStrcmp(argv[i], "-dsleep") == 0) { x86UNIXState->setDSleep(true); continue; } if (dStrcmp(argv[i], "-nohomedir") == 0) { x86UNIXState->setUseRedirect(false); continue; } if (dStrcmp(argv[i], "-chdir") == 0) { if ( ++i >= argc ) { dPrintf("Follow -chdir option with the desired working directory.\n"); return 1; } if (chdir(argv[i]) == -1) { dPrintf("Unable to chdir to %s: %s\n", argv[i], strerror(errno)); return 1; } continue; } // copy the arg into newCommandLine int argLen = dStrlen(argv[i]) + 1; char* argBuf = new char[argLen]; // this memory is deleted in main() dStrncpy(argBuf, argv[i], argLen); newCommandLine.push_back(argBuf); } x86UNIXState->setDedicated(foundDedicated); #if defined(TORQUE_DEDICATED) && !defined(TORQUE_ENGINE) if (!foundDedicated) { dPrintf("This is a dedicated server build. You must supply the -dedicated command line parameter.\n"); return 1; } #endif return 0; } int XLocalErrorHandler(Display* display, XErrorEvent* error) { char errorBuffer[4096]; XGetErrorText(display, error->error_code, errorBuffer, sizeof(errorBuffer)); Con::printf(errorBuffer); AssertFatal(0, "X Error"); } void InitWindowingSystem() { #ifndef TORQUE_DEDICATED if( !x86UNIXState->isXWindowsRunning() ) { Display* dpy = XOpenDisplay(NULL); AssertFatal(dpy, "Failed to connect to X Server"); if (dpy != NULL) { x86UNIXState->setXWindowsRunning(true); x86UNIXState->setDisplayPointer(dpy); XSetErrorHandler(XLocalErrorHandler); } } #endif } //------------------------------------------------------------------------------ static void InitWindow(const Point2I &initialSize, const char *name) { x86UNIXState->setWindowSize(initialSize); x86UNIXState->setWindowName(name); } #ifndef TORQUE_DEDICATED /* //------------------------------------------------------------------------------ bool InitSDL() { if (SDL_Init(SDL_INIT_VIDEO) != 0) return false; atexit(SDL_Quit); SDL_SysWMinfo sysinfo; SDL_VERSION(&sysinfo.version); if (SDL_GetWMInfo(&sysinfo) == 0) return false; x86UNIXState->setDisplayPointer(sysinfo.info.x11.display); DisplayPtrManager::setDisplayLockFunction(sysinfo.info.x11.lock_func); DisplayPtrManager::setDisplayUnlockFunction(sysinfo.info.x11.unlock_func); DisplayPtrManager xdisplay; Display* display = xdisplay.getDisplayPointer(); x86UNIXState->setScreenNumber( DefaultScreen( display ) ); x86UNIXState->setScreenPointer( DefaultScreenOfDisplay( display ) ); x86UNIXState->setDesktopSize( (S32) DisplayWidth( display, x86UNIXState->getScreenNumber()), (S32) DisplayHeight( display, x86UNIXState->getScreenNumber()) ); x86UNIXState->setDesktopBpp( (S32) DefaultDepth( display, x86UNIXState->getScreenNumber())); // indicate that we want sys WM messages SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE); return true; } */ //------------------------------------------------------------------------------ static void ProcessSYSWMEvent(const SDL_Event& event) { XEvent& xevent = event.syswm.msg->event.xevent; //Con::printf("xevent : %d", xevent.type); switch (xevent.type) { case SelectionRequest: // somebody wants our clipboard NotifySelectionEvent(xevent); break; } } //------------------------------------------------------------------------------ static void SetAppState() { U8 state = SDL_GetAppState(); // if we're not active but we have appactive and inputfocus, set window // active and reactivate input if ((!x86UNIXState->windowActive() || !Input::isActive()) && state & SDL_APPACTIVE && state & SDL_APPINPUTFOCUS) { x86UNIXState->setWindowActive(true); Input::deactivate(); Input::activate(); } // if we are active, but we don't have appactive or input focus, // deactivate input (if window not locked) and clear windowActive else if (x86UNIXState->windowActive() && !(state & SDL_APPACTIVE && state & SDL_APPINPUTFOCUS)) { if (x86UNIXState->windowLocked()) Input::deactivate(); x86UNIXState->setWindowActive(false); } } //------------------------------------------------------------------------------ static S32 NumEventsPending() { static const int MaxEvents = 255; static SDL_Event events[MaxEvents]; SDL_PumpEvents(); return SDL_PeepEvents(events, MaxEvents, SDL_PEEKEVENT, SDL_ALLEVENTS); } //------------------------------------------------------------------------------ static void PrintSDLEventQueue() { static const int MaxEvents = 255; static SDL_Event events[MaxEvents]; SDL_PumpEvents(); S32 numEvents = SDL_PeepEvents( events, MaxEvents, SDL_PEEKEVENT, SDL_ALLEVENTS); if (numEvents <= 0) { dPrintf("SDL Event Queue is empty\n"); return; } dPrintf("SDL Event Queue:\n"); for (int i = 0; i < numEvents; ++i) { const char *eventType; switch (events[i].type) { case SDL_NOEVENT: eventType = "SDL_NOEVENT"; break; case SDL_ACTIVEEVENT: eventType = "SDL_ACTIVEEVENT"; break; case SDL_KEYDOWN: eventType = "SDL_KEYDOWN"; break; case SDL_KEYUP: eventType = "SDL_KEYUP"; break; case SDL_MOUSEMOTION: eventType = "SDL_MOUSEMOTION"; break; case SDL_MOUSEBUTTONDOWN: eventType = "SDL_MOUSEBUTTONDOWN"; break; case SDL_MOUSEBUTTONUP: eventType = "SDL_MOUSEBUTTONUP"; break; case SDL_JOYAXISMOTION: eventType = "SDL_JOYAXISMOTION"; break; case SDL_JOYBALLMOTION: eventType = "SDL_JOYBALLMOTION"; break; case SDL_JOYHATMOTION: eventType = "SDL_JOYHATMOTION"; break; case SDL_JOYBUTTONDOWN: eventType = "SDL_JOYBUTTONDOWN"; break; case SDL_JOYBUTTONUP: eventType = "SDL_JOYBUTTONUP"; break; case SDL_QUIT: eventType = "SDL_QUIT"; break; case SDL_SYSWMEVENT: eventType = "SDL_SYSWMEVENT"; break; case SDL_VIDEORESIZE: eventType = "SDL_VIDEORESIZE"; break; case SDL_VIDEOEXPOSE: eventType = "SDL_VIDEOEXPOSE"; break; /* Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */ case SDL_USEREVENT: eventType = "SDL_USEREVENT"; break; default: eventType = "UNKNOWN!"; break; } dPrintf("Event %d: %s\n", i, eventType); } } //------------------------------------------------------------------------------ static bool ProcessMessages() { static const int MaxEvents = 255; static const U32 Mask = SDL_QUITMASK | SDL_VIDEORESIZEMASK | SDL_VIDEOEXPOSEMASK | SDL_ACTIVEEVENTMASK | SDL_SYSWMEVENTMASK | SDL_EVENTMASK(SDL_USEREVENT); static SDL_Event events[MaxEvents]; SDL_PumpEvents(); S32 numEvents = SDL_PeepEvents(events, MaxEvents, SDL_GETEVENT, Mask); if (numEvents == 0) return true; for (int i = 0; i < numEvents; ++i) { SDL_Event& event = events[i]; switch (event.type) { case SDL_QUIT: return false; break; case SDL_VIDEORESIZE: case SDL_VIDEOEXPOSE: //Game->refreshWindow(); break; case SDL_USEREVENT: if (event.user.code == TORQUE_SETVIDEOMODE) { SetAppState(); // SDL will send a motion event to restore the mouse position // on the new window. Ignore that if the window is locked. if (x86UNIXState->windowLocked()) { SDL_Event tempEvent; SDL_PeepEvents(&tempEvent, 1, SDL_GETEVENT, SDL_MOUSEMOTIONMASK); } } break; case SDL_ACTIVEEVENT: SetAppState(); break; case SDL_SYSWMEVENT: ProcessSYSWMEvent(event); break; } } return true; } //------------------------------------------------------------------------------ // send a destroy window event to the window. assumes // window is created. void SendQuitEvent() { SDL_Event quitevent; quitevent.type = SDL_QUIT; SDL_PushEvent(&quitevent); } #endif // TORQUE_DEDICATED //------------------------------------------------------------------------------ static inline void Sleep(int secs, int nanoSecs) { timespec sleeptime; sleeptime.tv_sec = secs; sleeptime.tv_nsec = nanoSecs; nanosleep(&sleeptime, NULL); } #ifndef TORQUE_DEDICATED struct AlertWinState { bool fullScreen; bool cursorHidden; bool inputGrabbed; }; //------------------------------------------------------------------------------ void DisplayErrorAlert(const char* errMsg, bool showSDLError) { char fullErrMsg[2048]; dStrncpy(fullErrMsg, errMsg, sizeof(fullErrMsg)); if (showSDLError) { char* sdlerror = SDL_GetError(); if (sdlerror != NULL && dStrlen(sdlerror) > 0) { dStrcat(fullErrMsg, " (Error: "); dStrcat(fullErrMsg, sdlerror); dStrcat(fullErrMsg, ")"); } } Platform::AlertOK("Error", fullErrMsg); } //------------------------------------------------------------------------------ static inline void AlertDisableVideo(AlertWinState& state) { /* RKO-TODO: Possibly re-implement this functionality? state.fullScreen = Video::isFullScreen(); state.cursorHidden = (SDL_ShowCursor(SDL_QUERY) == SDL_DISABLE); state.inputGrabbed = (SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON); if (state.fullScreen) SDL_WM_ToggleFullScreen(SDL_GetVideoSurface()); if (state.cursorHidden) SDL_ShowCursor(SDL_ENABLE); if (state.inputGrabbed) SDL_WM_GrabInput(SDL_GRAB_OFF); */ } //------------------------------------------------------------------------------ static inline void AlertEnableVideo(AlertWinState& state) { /* RKO-TODO: Possibly re-implement this functionality? if (state.fullScreen) SDL_WM_ToggleFullScreen(SDL_GetVideoSurface()); if (state.cursorHidden) SDL_ShowCursor(SDL_DISABLE); if (state.inputGrabbed) SDL_WM_GrabInput(SDL_GRAB_ON); */ } #endif // TORQUE_DEDICATED //------------------------------------------------------------------------------ void Platform::AlertOK(const char *windowTitle, const char *message) { #ifndef TORQUE_DEDICATED if (x86UNIXState->isXWindowsRunning()) { AlertWinState state; AlertDisableVideo(state); DisplayPtrManager xdisplay; XMessageBox mBox(xdisplay.getDisplayPointer()); mBox.alertOK(windowTitle, message); AlertEnableVideo(state); } else #endif { if (Con::isActive() && StdConsole::isEnabled()) Con::printf("Alert: %s %s", windowTitle, message); else dPrintf("Alert: %s %s\n", windowTitle, message); } } //------------------------------------------------------------------------------ bool Platform::AlertOKCancel(const char *windowTitle, const char *message) { #ifndef TORQUE_DEDICATED if (x86UNIXState->isXWindowsRunning()) { AlertWinState state; AlertDisableVideo(state); DisplayPtrManager xdisplay; XMessageBox mBox(xdisplay.getDisplayPointer()); bool val = mBox.alertOKCancel(windowTitle, message) == XMessageBox::OK; AlertEnableVideo(state); return val; } else #endif { if (Con::isActive() && StdConsole::isEnabled()) Con::printf("Alert: %s %s", windowTitle, message); else dPrintf("Alert: %s %s\n", windowTitle, message); return false; } } //------------------------------------------------------------------------------ bool Platform::AlertRetry(const char *windowTitle, const char *message) { #ifndef TORQUE_DEDICATED if (x86UNIXState->isXWindowsRunning()) { AlertWinState state; AlertDisableVideo(state); DisplayPtrManager xdisplay; XMessageBox mBox(xdisplay.getDisplayPointer()); bool val = mBox.alertRetryCancel(windowTitle, message) == XMessageBox::Retry; AlertEnableVideo(state); return val; } else #endif { if (Con::isActive() && StdConsole::isEnabled()) Con::printf("Alert: %s %s", windowTitle, message); else dPrintf("Alert: %s %s\n", windowTitle, message); return false; } } //------------------------------------------------------------------------------ Platform::ALERT_ASSERT_RESULT Platform::AlertAssert(const char *windowTitle, const char *message) { #ifndef TORQUE_DEDICATED if (x86UNIXState->isXWindowsRunning()) { AlertWinState state; AlertDisableVideo(state); DisplayPtrManager xdisplay; XMessageBox mBox(xdisplay.getDisplayPointer()); int val = mBox.alertAssert(windowTitle, message); ALERT_ASSERT_RESULT result = ALERT_ASSERT_IGNORE; switch( val ) { case XMessageBox::OK: result = ALERT_ASSERT_EXIT; break; default: case XMessageBox::Cancel: result = ALERT_ASSERT_IGNORE; break; case XMessageBox::Retry: result = ALERT_ASSERT_DEBUG; break; case XMessageBox::IgnoreAll: result = ALERT_ASSERT_IGNORE_ALL; break; } AlertEnableVideo(state); return result; } else #endif { if (Con::isActive() && StdConsole::isEnabled()) Con::printf("AlertAssert: %s %s", windowTitle, message); else dPrintf("AlertAssert: %s %s\n", windowTitle, message); return ALERT_ASSERT_DEBUG; } } //------------------------------------------------------------------------------ bool Platform::excludeOtherInstances(const char *mutexName) { AssertFatal(0, "Not Implemented"); return false; } //------------------------------------------------------------------------------ void Platform::process() { PROFILE_START(XUX_PlatformProcess); stdConsole->process(); if (x86UNIXState->windowCreated()) { #ifndef TORQUE_DEDICATED // process window events PROFILE_START(XUX_ProcessMessages); bool quit = !ProcessMessages(); PROFILE_END(); if(quit) { // generate a quit event Platform::postQuitMessage(0); } // process input events PROFILE_START(XUX_InputProcess); Input::process(); PROFILE_END(); // poll redbook state PROFILE_START(XUX_PollRedbookDevices); PollRedbookDevices(); PROFILE_END(); // if we're not the foreground window, sleep for 1 ms if (!x86UNIXState->windowActive()) Sleep(0, getBackgroundSleepTime() * 1000000); #endif } else { // no window // sleep for 1 ms // JMQ: since linux's minimum sleep latency seems to be 20ms, this can // increase player pings by 10-20ms in the dedicated server. So // you have to use -dsleep to enable it. the server sleeps anyway when // there are no players connected. // JMQ: recent kernels (such as RH 8.0 2.4.18) reduce the latency // to 2-4 ms on average. /*if (!Game->isJournalReading() && (x86UNIXState->getDSleep() || Con::getIntVariable("Server::PlayerCount") - Con::getIntVariable("Server::BotCount") <= 0)) { PROFILE_START(XUX_Sleep); Sleep(0, getBackgroundSleepTime() * 1000000); PROFILE_END(); }*/ } #ifndef TORQUE_DEDICATED #if 0 // JMQ: disabled this because it may fire mistakenly in some configurations. // sdl's default event handling scheme should be enough. // crude check to make sure that we're not loading up events. the sdl // event queue should never have more than (say) 25 events in it at this // point const int MaxEvents = 25; if (NumEventsPending() > MaxEvents) { PrintSDLEventQueue(); AssertFatal(false, "The SDL event queue has too many events!"); } #endif #endif PROFILE_END(); } //------------------------------------------------------------------------------ // Web browser function: //------------------------------------------------------------------------------ bool Platform::openWebBrowser( const char* webAddress ) { if (!webAddress || dStrlen(webAddress)==0) return false; // look for a browser preference variable // JMQTODO: be nice to implement some UI to customize this const char* webBrowser = Con::getVariable("Pref::Unix::WebBrowser"); if (dStrlen(webBrowser) == 0) webBrowser = NULL; pid_t pid = fork(); if (pid == -1) { Con::printf("WARNING: Platform::openWebBrowser failed to fork"); return false; } else if (pid != 0) { // parent //if (Video::isFullScreen()) // Video::toggleFullScreen(); return true; } else if (pid == 0) { // child // try to exec konqueror, then netscape char* argv[3]; argv[0] = const_cast<char*>(""); argv[1] = const_cast<char*>(webAddress); argv[2] = 0; int ok = -1; // if execvp returns, it means it couldn't execute the program if (webBrowser != NULL) ok = execvp(webBrowser, argv); ok = execvp("konqueror", argv); ok = execvp("mozilla", argv); ok = execvp("netscape", argv); // use dPrintf instead of Con here since we're now in another process, dPrintf("WARNING: Platform::openWebBrowser: couldn't launch a web browser\n"); _exit(-1); return false; } else { Con::printf("WARNING: Platform::openWebBrowser: forking problem"); return false; } } //------------------------------------------------------------------------------ // Login password routines: //------------------------------------------------------------------------------ const char* Platform::getLoginPassword() { Con::printf("WARNING: Platform::getLoginPassword() is unimplemented"); return ""; } //------------------------------------------------------------------------------ bool Platform::setLoginPassword( const char* password ) { Con::printf("WARNING: Platform::setLoginPassword is unimplemented"); return false; } //------------------------------------------------------------------------------ // Silly Korean registry key checker: //------------------------------------------------------------------------------ ConsoleFunction( isKoreanBuild, bool, 1, 1, "isKoreanBuild()" ) { Con::printf("WARNING: isKoreanBuild() is unimplemented"); return false; } bool Platform::displaySplashWindow(String path) { X11WindowManager* mgr = (X11WindowManager*)PlatformWindowManager::get(); return mgr->displaySplashWindow(); } void Platform::closeSplashWindow() { X11WindowManager* mgr = (X11WindowManager*)PlatformWindowManager::get(); return mgr->closeSplashWindow(); } void Platform::openFolder(const char* path ) { AssertFatal(0, "Not Implemented"); } void Platform::openFile(const char* path ) { AssertFatal(0, "Not Implemented"); }
29.530667
109
0.580865
fr1tz
c3485c0509f609322570a4459e6b8a047bc377b8
791
cpp
C++
OOP-cpp/assignment3/TrianglePattern.cpp
mtjin/University_and_AndroidProjects
c0ac3394043fd10730e68b391866d55c3be2c23b
[ "MIT" ]
1
2021-04-13T12:06:51.000Z
2021-04-13T12:06:51.000Z
OOP-cpp/assignment3/TrianglePattern.cpp
mtjin/University
c0ac3394043fd10730e68b391866d55c3be2c23b
[ "MIT" ]
2
2022-01-21T23:46:50.000Z
2022-01-21T23:48:45.000Z
OOP-cpp/assignment3/TrianglePattern.cpp
mtjin/university
c0ac3394043fd10730e68b391866d55c3be2c23b
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "TrianglePattern.h" using namespace std; TrianglePattern::TrianglePattern():ShapePattern(){ this->height = 0; } TrianglePattern::TrianglePattern(int x){ set_height(x); } void TrianglePattern::set_height(int x){ this->height = x; } int TrianglePattern::patternHelper(int h){ cout<<"The Right Triangle Pattern:(height = "<<this->height<<" )"<<endl; int tmp = h; for(int i= h; i>0; i--){ for(int j=tmp; j>0; j--){ cout<<ShapePattern::get_pattern(); } tmp--; cout<<endl; } return 0; } void TrianglePattern::printPattern(){ if(height>=0){ patternHelper(height); } else{ cout<<"Invaild Size!"<<endl; } cout<<endl; }
19.775
76
0.579014
mtjin
c34cd3a6f09c34be5a627b7d7a66f5c422434241
3,044
hpp
C++
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/frame/frame_init.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
10
2021-03-29T13:52:06.000Z
2022-03-10T02:24:25.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/frame/frame_init.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
1
2019-07-19T02:40:32.000Z
2019-07-19T02:40:32.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/frame/frame_init.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
7
2018-07-11T10:37:02.000Z
2019-08-03T10:34:08.000Z
// OpenVPN -- An application to securely tunnel IP networks // over a single port, with support for SSL/TLS-based // session authentication and key exchange, // packet encryption, packet authentication, and // packet compression. // // Copyright (C) 2012-2017 OpenVPN Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License Version 3 // as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program in the COPYING file. // If not, see <http://www.gnu.org/licenses/>. // Method to generate a Frame object for typical OpenVPN usage #ifndef OPENVPN_FRAME_FRAME_INIT_H #define OPENVPN_FRAME_FRAME_INIT_H #include <algorithm> #include <openvpn/frame/frame.hpp> namespace openvpn { inline Frame::Ptr frame_init(const bool align_adjust_3_1, const size_t tun_mtu, const size_t control_channel_payload, const bool verbose) { const size_t payload = std::max(tun_mtu + 512, size_t(2048)); const size_t headroom = 512; const size_t tailroom = 512; const size_t align_block = 16; const unsigned int buffer_flags = 0; Frame::Ptr frame(new Frame(Frame::Context(headroom, payload, tailroom, 0, align_block, buffer_flags))); if (align_adjust_3_1) { (*frame)[Frame::READ_LINK_TCP] = Frame::Context(headroom, payload, tailroom, 3, align_block, buffer_flags); (*frame)[Frame::READ_LINK_UDP] = Frame::Context(headroom, payload, tailroom, 1, align_block, buffer_flags); } (*frame)[Frame::READ_BIO_MEMQ_STREAM] = Frame::Context(headroom, std::min(control_channel_payload, payload), tailroom, 0, align_block, buffer_flags); (*frame)[Frame::WRITE_SSL_CLEARTEXT] = Frame::Context(headroom, payload, tailroom, 0, align_block, BufferAllocated::GROW); frame->standardize_capacity(~0); if (verbose) OPENVPN_LOG("Frame=" << headroom << '/' << payload << '/' << tailroom << " mssfix-ctrl=" << (*frame)[Frame::READ_BIO_MEMQ_STREAM].payload()); return frame; } inline Frame::Context frame_init_context_simple(const size_t payload) { const size_t headroom = 512; const size_t tailroom = 512; const size_t align_block = 16; const unsigned int buffer_flags = 0; return Frame::Context(headroom, payload, tailroom, 0, align_block, buffer_flags); } inline Frame::Ptr frame_init_simple(const size_t payload) { Frame::Ptr frame = new Frame(frame_init_context_simple(payload)); frame->standardize_capacity(~0); return frame; } } // namespace openvpn #endif // OPENVPN_FRAME_FRAME_INIT_H
37.580247
126
0.698095
TiagoPedroByterev
c34da09c457f0410e4e1f69bc1d89e138ac8d3ea
264
cpp
C++
cpp/DataStructures/vector.cpp
joro2404/Programming_problems
e0a6f5cbaed013ffde9ecaf3f6d266c582191e41
[ "MIT" ]
null
null
null
cpp/DataStructures/vector.cpp
joro2404/Programming_problems
e0a6f5cbaed013ffde9ecaf3f6d266c582191e41
[ "MIT" ]
null
null
null
cpp/DataStructures/vector.cpp
joro2404/Programming_problems
e0a6f5cbaed013ffde9ecaf3f6d266c582191e41
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v; for(int i=0;i<10;i++){ v.push_back(i); } cout << "Size: " << v.size() << endl; v.pop_back(); cout << "Size: " << v.size() << endl; }
15.529412
41
0.484848
joro2404
c34db1d2b727bafb6be96b212497109fe9458ee2
280
cpp
C++
CodeForces/CF742-D2-A.cpp
amraboelkher/CompetitiveProgramming
624ca5c3e5044eae2800d14b3dbb961c85494b85
[ "MIT" ]
2
2017-12-06T01:17:21.000Z
2018-05-02T04:49:44.000Z
CodeForces/CF742-D2-A.cpp
amraboelkher/CompetitiveProgramming
624ca5c3e5044eae2800d14b3dbb961c85494b85
[ "MIT" ]
null
null
null
CodeForces/CF742-D2-A.cpp
amraboelkher/CompetitiveProgramming
624ca5c3e5044eae2800d14b3dbb961c85494b85
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int get(int a , int b){ if(b == 0) return 1; if(b == 1)return a % 10; int x = get(a , b / 2) % 10; x = x * x % 10; if(b & 1) x = (x * a) % 10; return x; } int main(){ int n ; cin >> n; cout << get(1378 , n) << endl; }
13.333333
32
0.482143
amraboelkher
c34db30362a630e8d7a86dd70a27d8ab9b457446
2,331
cpp
C++
src/raytrace/scene.cpp
JohanSmet/rtiow
7ca1d0e52e96c7701b55bacebecf7ae9cdec773a
[ "BSD-3-Clause" ]
null
null
null
src/raytrace/scene.cpp
JohanSmet/rtiow
7ca1d0e52e96c7701b55bacebecf7ae9cdec773a
[ "BSD-3-Clause" ]
null
null
null
src/raytrace/scene.cpp
JohanSmet/rtiow
7ca1d0e52e96c7701b55bacebecf7ae9cdec773a
[ "BSD-3-Clause" ]
null
null
null
// raytrace/scene.cpp - Johan Smet - BSD-3-Clause (see LICENSE) #include "scene.h" namespace rtiow { Material &Scene::material_create_default() { auto &mat = m_materials.emplace_back(); mat.m_albedo = {0.0f, 0.0f, 0.0f}; mat.m_specular_chance = 0.0f; mat.m_specular_color = {0.0f, 0.0f, 0.0f}; mat.m_specular_roughness = 0.0f; mat.m_index_of_refraction = 1.0f; mat.m_refraction_chance = 0.0f; mat.m_refraction_color = {0.0f, 0.0f, 0.0f}; mat.m_refraction_roughness = 0.0f; return mat; } material_id_t Scene::material_create( const color_t &albedo, float specular_chance, const color_t &specular_color, float specular_roughness, float index_of_refraction, float refraction_chance, const color_t &refraction_color, float refraction_roughness) { auto &mat = material_create_default(); mat.m_albedo = albedo; mat.m_specular_chance = specular_chance; mat.m_specular_color = specular_color; mat.m_specular_roughness = specular_roughness; mat.m_index_of_refraction = index_of_refraction; mat.m_refraction_chance = refraction_chance; mat.m_refraction_color = refraction_color; mat.m_refraction_roughness = refraction_roughness; return m_materials.size() - 1; } material_id_t Scene::material_create_diffuse(const color_t &albedo) { auto &mat = material_create_default(); mat.m_albedo = albedo; return m_materials.size() - 1; } material_id_t Scene::material_create_specular( const color_t &albedo, float specular_chance, const color_t &specular_color, float specular_roughness) { auto &mat = material_create_default(); mat.m_albedo = albedo; mat.m_specular_chance = specular_chance; mat.m_specular_color = specular_color; mat.m_specular_roughness = specular_roughness; return m_materials.size() - 1; } void Scene::setup_camera(float aspect_ratio, float vertical_fov, point_t look_from, point_t look_at, vector_t v_up, float aperture, float focus_distance) { m_camera = Camera(aspect_ratio, vertical_fov, look_from, look_at, v_up, aperture, focus_distance); } void Scene::sphere_add(const point_t &center, float radius, material_id_t material) { m_spheres.add_sphere(center, radius, material); } bool Scene::hit_detection(const Ray &ray, HitRecord &hit) const { // there are only spheres right now return m_spheres.hit(ray, 0.001f, hit); } } // namespace rtiow
31.931507
99
0.766624
JohanSmet
c34ddf1360c2c90d3cf99e21714e472e916d7ba0
41,447
cpp
C++
Simulation/ODESimulator.cpp
bbgw/Klampt
3c022da372c81646ec9f7492fad499740431d38b
[ "BSD-3-Clause" ]
null
null
null
Simulation/ODESimulator.cpp
bbgw/Klampt
3c022da372c81646ec9f7492fad499740431d38b
[ "BSD-3-Clause" ]
null
null
null
Simulation/ODESimulator.cpp
bbgw/Klampt
3c022da372c81646ec9f7492fad499740431d38b
[ "BSD-3-Clause" ]
null
null
null
#include "ODESimulator.h" #include "ODECommon.h" #include "ODECustomGeometry.h" #include "Settings.h" #include <list> #include <fstream> //#include "Geometry/Clusterize.h" #include <geometry/ConvexHull2D.h> #include <statistics/KMeans.h> #include <statistics/HierarchicalClustering.h> #include <utils/EquivalenceMap.h> #include <utils/permutation.h> #include <ode/ode.h> #include <Timer.h> #ifndef WIN32 #include <unistd.h> #endif //WIN32 #define TEST_READ_WRITE_STATE 0 #define DO_TIMING 0 const static size_t gMaxKMeansSize = 5000; const static size_t gMaxHClusterSize = 2000; static size_t gPreclusterContacts = 0; static double gClusterTime = 0; static double gContactDetectTime = 0; template <class T> bool TestReadWriteState(T& obj,const char* name="") { File fwrite,fwritenew; fwrite.OpenData(); if(!obj.WriteState(fwrite)) { fprintf(stderr,"WriteState %s failed\n",name); return false; } //HACK for File internal buffer length bug returning buffer capacity rather //than size //int n = fwrite.Length(); int n1 = fwrite.Position(); fwrite.Seek(0,FILESEEKSTART); if(!obj.ReadState(fwrite)) { fprintf(stderr,"ReadState %s failed\n",name); return false; } fwritenew.OpenData(); if(!obj.WriteState(fwritenew)) { fprintf(stderr,"Second WriteState %s failed\n",name); return false; } //HACK for File internal buffer length bug returning buffer capacity rather //than size //int n2 = fwritenew.Length(); int n2 = fwritenew.Position(); char* d1 = (char*)fwrite.GetDataBuffer(); char* d2 = (char*)fwritenew.GetDataBuffer(); if(n1 != n2) { fprintf(stderr,"WriteState %s wrote different numbers of bytes: %d -> %d\n",name,n1,n2); return false; } for(int i=0;i<n1;i++) { if(d1[i] != d2[i]) { fprintf(stderr,"WriteState %s wrote different byte at position %d/%d: 0x%x vs 0x%x\n",name,i,n1,(int)d1[i],(int)d2[i]); return false; } } return true; } //contact merging -- these are now handled by the contact clustering procedure const static bool kMergeContacts = false; const static Real kContactPosMergeTolerance = 3e-3; const static Real kContactOriMergeTolerance = 1e-1; ODESimulatorSettings::ODESimulatorSettings() { gravity[0] = gravity[1] = 0; gravity[2] = -9.8; defaultEnvPadding = gDefaultEnvPadding; defaultEnvSurface.kFriction = 0.3; defaultEnvSurface.kRestitution = 0.1; defaultEnvSurface.kStiffness = 80000; defaultEnvSurface.kDamping = 20000; //defaultEnvSurface.kStiffness = Inf; //defaultEnvSurface.kDamping = Inf; boundaryLayerCollisions = gBoundaryLayerCollisionsEnabled; rigidObjectCollisions = gRigidObjectCollisionsEnabled; robotSelfCollisions = gRobotSelfCollisionsEnabled; robotRobotCollisions = gRobotRobotCollisionsEnabled; maxContacts = 20; clusterNormalScale = 0.1; errorReductionParameter = 0.95; dampedLeastSquaresParameter = 1e-6; } inline Real ERPFromSpring(Real timestep,Real kP,Real kD) { return timestep*kP/(timestep*kP+kD); } inline Real CFMFromSpring(Real timestep,Real kP,Real kD) { return 1.0/(timestep*kP+kD); } struct ODEObject { bool gODEInitialized; ODEObject () : gODEInitialized(false) {} void Init() { if(!gODEInitialized) { #ifdef dDOUBLE if(dCheckConfiguration("ODE_double_precision")!=1) { FatalError("ODE is compiled with single precision but Klamp't is compiled with double, either reconfigure ODE with --enable-double-precision or recompile Klamp't with dDOUBLE"); } #else if(dCheckConfiguration("ODE_single_precision")!=1) { FatalError("ODE is compiled with double precision but Klamp't is compiled with single, either reconfigure ODE without --enable-double-precision or recompile Klamp't with dSINGLE"); } #endif printf("Initializing ODE...\n"); dInitODE(); InitODECustomGeometry(); gODEInitialized = true; } } ~ODEObject() { if(gODEInitialized) { printf("Closing ODE...\n"); dCloseODE(); } } }; ODEObject g_ODE_object; //stuff for contact detection callbacks struct ODEContactResult { dGeomID o1,o2; vector<dContactGeom> contacts; vector<dJointFeedback> feedback; }; const static int max_contacts = 1000; static dContactGeom gContactTemp[max_contacts]; static list<ODEContactResult> gContacts; ODESimulator::ODESimulator() { timestep = 0; g_ODE_object.Init(); worldID = dWorldCreate(); contactGroupID = dJointGroupCreate(0); //envSpaceID = dHashSpaceCreate(0); //dHashSpaceSetLevels(envSpaceID,-2,1); envSpaceID = dSimpleSpaceCreate(0); dWorldSetERP(worldID,settings.errorReductionParameter); dWorldSetCFM(worldID,settings.dampedLeastSquaresParameter); dWorldSetGravity(worldID,settings.gravity[0],settings.gravity[1],settings.gravity[2]); } void ODESimulator::SetGravity(const Vector3& g) { g.get(settings.gravity); dWorldSetGravity(worldID,g.x,g.y,g.z); } void ODESimulator::SetERP(double erp) { settings.errorReductionParameter = erp; dWorldSetERP(worldID,erp); } void ODESimulator::SetCFM(double cfm) { settings.dampedLeastSquaresParameter = cfm; dWorldSetCFM(worldID,cfm); } ODESimulator::~ODESimulator() { dJointGroupDestroy(contactGroupID); for(size_t i=0;i<envGeoms.size();i++) delete envGeoms[i]; for(size_t i=0;i<robots.size();i++) delete robots[i]; dSpaceDestroy(envSpaceID); dWorldDestroy(worldID); } void ODESimulator::AddEnvironment(Environment& env) { envs.push_back(&env); envGeoms.resize(envGeoms.size()+1); envGeoms.back() = new ODEGeometry; envGeoms.back()->Create(&env.geometry,envSpaceID,Vector3(Zero),settings.boundaryLayerCollisions); envGeoms.back()->surf() = settings.defaultEnvSurface; envGeoms.back()->SetPadding(settings.defaultEnvPadding); if(!env.kFriction.empty()) envGeoms.back()->surf().kFriction = env.kFriction[0]; //the index of the environment is encoded as -1-index dGeomSetData(envGeoms.back()->geom(),(void*)(-(int)envs.size())); dGeomSetCategoryBits(envGeoms.back()->geom(),0x1); dGeomSetCollideBits(envGeoms.back()->geom(),0xffffffff ^ 0x1); } void ODESimulator::AddRobot(Robot& robot) { robots.push_back(new ODERobot(robot)); //For some reason, self collisions don't work with hash spaces robots.back()->Create(worldID,settings.boundaryLayerCollisions); //robotStances.resize(robots.size()); for(size_t i=0;i<robot.links.size();i++) if(robots.back()->triMesh(i) && robots.back()->geom(i)) { if(robots.back()->robot.parents[i] == -1) { //treat as part of the terrain dGeomSetCategoryBits(robots.back()->geom(i),0x1); dGeomSetCollideBits(robots.back()->geom(i),0xffffffff ^ 0x1); } else { dGeomSetCategoryBits(robots.back()->geom(i),0x4); dGeomSetCollideBits(robots.back()->geom(i),0xffffffff); } } } void ODESimulator::AddObject(RigidObject& object) { objects.push_back(new ODERigidObject(object)); objects.back()->Create(worldID,envSpaceID,settings.boundaryLayerCollisions); dGeomSetData(objects.back()->geom(),(void*)(objects.size()-1)); dGeomSetCategoryBits(objects.back()->geom(),0x2); dGeomSetCollideBits(objects.back()->geom(),0xffffffff); } void ODESimulator::Step(Real dt) { Assert(timestep == 0); #if DO_TIMING Timer timer; double collisionTime,stepTime,updateTime; gContactDetectTime = gClusterTime = 0; gPreclusterContacts = 0; #endif // DO_TIMING gContacts.clear(); timestep=dt; DetectCollisions(); //printf(" %d contacts detected\n",gContacts.size()); #if DO_TIMING collisionTime = timer.ElapsedTime(); timer.Reset(); #endif // DO_TIMING StepDynamics(dt); #if DO_TIMING stepTime = timer.ElapsedTime(); timer.Reset(); #endif // DO_TIMING for(map<pair<ODEObjectID,ODEObjectID>,ODEContactList>::iterator i=contactList.begin();i!=contactList.end();i++) { ODEContactList& cl=i->second; cl.forces.clear(); for(size_t j=0;j<cl.feedbackIndices.size();j++) { int k=cl.feedbackIndices[j]; Assert(k >= 0 && k < (int)gContacts.size()); list<ODEContactResult>::iterator cres=gContacts.begin(); advance(cres,k); Vector3 temp; for(size_t i=0;i<cres->feedback.size();i++) { CopyVector(temp,cres->feedback[i].f1); cl.forces.push_back(temp); /* if(!cl.points.back().isValidForce(-temp)) { printf("ODESimulator: Warning, solved contact force %d %d is invalid\n",k,i); cout<<" Force: "<<-temp<<", normal "<<cl.points.back().n<<" kFriction "<<cl.points.back().kFriction<<endl; } */ } } if(!cl.feedbackIndices.empty()) Assert(cl.points.size() == cl.forces.size()); } timestep = 0; #if DO_TIMING updateTime = timer.ElapsedTime(); #endif //DO_TIMING #if DO_TIMING ofstream out("odesimulator_timing.csv",ios::app); if(out.tellp()==0) { cout<<"Saving to odesimulator_timing.csv"<<endl; out<<"total,#preclusterContacts,#contacts,collision detection,contact detect,clustering,dynamics step,misc update"<<endl; } size_t nc = 0; for(list<ODEContactResult>::iterator i=gContacts.begin();i!=gContacts.end();i++) nc += i->contacts.size(); out<<collisionTime+stepTime+updateTime<<","<<gPreclusterContacts<<","<<nc<<","<<collisionTime<<","<<gContactDetectTime<<","<<gClusterTime<<","<<stepTime<<","<<updateTime<<endl; #endif //KH: commented this out so GetContacts() would work for ContactSensor simulation. Be careful about loading state //gContacts.clear(); } struct EqualPlane { //position tolerance and angle tolerance, in radians EqualPlane(double xtol,double atol) : ptol(xtol),catol(Cos(atol)) {} //assumes normalized normals bool operator () (const dContactGeom& a,const dContactGeom& b) { Vector3 an,bn; CopyVector(an,a.normal); CopyVector(bn,b.normal); Real ndot = an.dot(bn); if(ndot > catol) { Vector3 ax,bx; CopyVector(ax,a.pos); CopyVector(bx,b.pos); return FuzzyEquals(ax.dot(an),bx.dot(an),ptol) && FuzzyEquals(ax.dot(bn),bx.dot(bn),ptol); } return false; } double ptol,catol; }; struct EqualPoint { //position tolerance and angle tolerance, in radians EqualPoint(double xtol) : ptol(xtol) {} //assumes normalized normals bool operator () (const dContactGeom& a,const dContactGeom& b) { Vector3 ax,bx; CopyVector(ax,a.pos); CopyVector(bx,b.pos); return ax.distanceSquared(bx) < Sqr(ptol); } double ptol; }; /** Two ways of merging frictionless contacts without resorting to 6D * wrench space * 1) interior points in 2D convex hull, with the projection defined * by the contact normal * 2) interior points in convex cone at a single contact point (TODO) * * If contacts have friction, the convex hull method only works when the * points are on the same plane. */ void CHContactsPlane(vector<dContactGeom>& contacts) { if(contacts.empty()) return; if(contacts.size() <= 2) return; Vector3 c(Zero),n(Zero); for(size_t i=0;i<contacts.size();i++) { Vector3 cx,nx; CopyVector(cx,contacts[i].pos); CopyVector(nx,contacts[i].normal); c += cx; n += nx; } c /= contacts.size(); n.inplaceNormalize(); //get the deepest contact size_t deepest = 0; for(size_t i=1;i<contacts.size();i++) if(contacts[i].depth > contacts[deepest].depth) deepest=i; //make a plane Vector3 x,y; n.getOrthogonalBasis(x,y); //Real nofs = n.dot(c); Real xofs = x.dot(c); Real yofs = y.dot(c); vector<Vector2> pt2d(contacts.size()); for(size_t i=0;i<contacts.size();i++) { Vector3 cx; CopyVector(cx,contacts[i].pos); pt2d[i].x = x.dot(cx)-xofs; pt2d[i].y = y.dot(cx)-yofs; } //get the convex hull vector<Vector2> ch(contacts.size()); vector<int> mapping(contacts.size()); int num=Geometry::ConvexHull2D_Chain_Unsorted(&pt2d[0],contacts.size(),&ch[0],&mapping[0]); vector<dContactGeom> temp(num); bool addDeepest = true; for(int i=0;i<num;i++) { Assert(mapping[i] < (int)contacts.size()); temp[i] = contacts[mapping[i]]; if(mapping[i] == (int)deepest) addDeepest = false; } if(addDeepest) temp.push_back(contacts[deepest]); swap(temp,contacts); } void interpolate(const dContactGeom& a,const dContactGeom& b,Real u,dContactGeom& x) { for(int i=0;i<3;i++) { x.pos[i] = (1-u)*a.pos[i]+u*b.pos[i]; } Vector3 an,bn; CopyVector(an,a.normal); CopyVector(bn,b.normal); Vector3 n = (1-u)*an+u*bn; n.inplaceNormalize(); CopyVector(x.normal,n); x.depth = Max(a.depth,b.depth); x.g1 = a.g1; x.g2 = a.g2; Assert(x.g1 == b.g1); Assert(x.g2 == b.g2); } void ClusterContactsMerge(vector<dContactGeom>& contacts,int maxClusters,Real clusterNormalScale) { if((int)contacts.size() <= maxClusters) return; vector<Vector> pts(contacts.size()); for(size_t i=0;i<pts.size();i++) { pts[i].resize(7); pts[i][0] = contacts[i].pos[0]; pts[i][1] = contacts[i].pos[1]; pts[i][2] = contacts[i].pos[2]; pts[i][3] = contacts[i].normal[0]*clusterNormalScale; pts[i][4] = contacts[i].normal[1]*clusterNormalScale; pts[i][5] = contacts[i].normal[2]*clusterNormalScale; pts[i][6] = contacts[i].depth; } //Timer timer; Statistics::HierarchicalClustering clust; clust.Build(pts,maxClusters,Statistics::HierarchicalClustering::AverageLinkage); //cout<<"Clustering time: "<<timer.ElapsedTime()<<endl; /* cout<<"Points"<<endl; for(size_t i=0;i<pts.size();i++) cout<<pts[i]<<endl; */ //read out the clusters contacts.resize(maxClusters); for(int i=0;i<maxClusters;i++) { const vector<int>& inds = clust.Cluster(i); /* cout<<"Cluster "<<i<<": "; for(size_t j=0;j<inds.size();j++) cout<<inds[j]<<", "; cout<<endl; */ Vector mean(7,Zero); for(size_t j=0;j<inds.size();j++) mean += pts[inds[j]]; mean /= inds.size(); contacts[i].pos[0] = mean[0]; contacts[i].pos[1] = mean[1]; contacts[i].pos[2] = mean[2]; contacts[i].normal[0] = mean[3]/clusterNormalScale; contacts[i].normal[1] = mean[4]/clusterNormalScale; contacts[i].normal[2] = mean[5]/clusterNormalScale; Real len = Vector3(contacts[i].normal[0],contacts[i].normal[1],contacts[i].normal[2]).length(); if(FuzzyZero(len) || !IsFinite(len)) { printf("ODESimulator: Warning, clustered normal became zero/infinite\n"); int found = inds[0]; contacts[i].pos[0] = pts[found][0]; contacts[i].pos[1] = pts[found][1]; contacts[i].pos[2] = pts[found][2]; contacts[i].normal[0] = pts[found][3]; contacts[i].normal[1] = pts[found][4]; contacts[i].normal[2] = pts[found][5]; Real len = Vector3(contacts[i].normal[0],contacts[i].normal[1],contacts[i].normal[2]).length(); contacts[i].normal[0] /= len; contacts[i].normal[1] /= len; contacts[i].normal[2] /= len; contacts[i].depth = pts[found][6]; continue; } contacts[i].normal[0] /= len; contacts[i].normal[1] /= len; contacts[i].normal[2] /= len; contacts[i].depth = mean[6]; } } void ClusterContactsKMeans(vector<dContactGeom>& contacts,int maxClusters,Real clusterNormalScale) { if((int)contacts.size() <= maxClusters) return; vector<Vector> pts(contacts.size()); for(size_t i=0;i<pts.size();i++) { pts[i].resize(7); pts[i][0] = contacts[i].pos[0]; pts[i][1] = contacts[i].pos[1]; pts[i][2] = contacts[i].pos[2]; pts[i][3] = contacts[i].normal[0]*clusterNormalScale; pts[i][4] = contacts[i].normal[1]*clusterNormalScale; pts[i][5] = contacts[i].normal[2]*clusterNormalScale; pts[i][6] = contacts[i].depth; } Statistics::KMeans kmeans(pts,maxClusters); //randomized //kmeans.RandomInitialCenters(); //deterministic for(size_t i=0;i<kmeans.centers.size();i++) kmeans.centers[i] = kmeans.data[(i*pts.size())/kmeans.centers.size()]; int iters=20; kmeans.Iterate(iters); contacts.resize(kmeans.centers.size()); vector<int> degenerate; for(size_t i=0;i<contacts.size();i++) { contacts[i].pos[0] = kmeans.centers[i][0]; contacts[i].pos[1] = kmeans.centers[i][1]; contacts[i].pos[2] = kmeans.centers[i][2]; contacts[i].normal[0] = kmeans.centers[i][3]/clusterNormalScale; contacts[i].normal[1] = kmeans.centers[i][4]/clusterNormalScale; contacts[i].normal[2] = kmeans.centers[i][5]/clusterNormalScale; Real len = Vector3(contacts[i].normal[0],contacts[i].normal[1],contacts[i].normal[2]).length(); if(FuzzyZero(len) || !IsFinite(len)) { printf("ODESimulator: Warning, clustered normal became zero/infinite\n"); //pick any in the cluster int found = -1; for(size_t k=0;k<kmeans.labels.size();k++) { if(kmeans.labels[k] == (int)i) { found = (int)k; break; } } if(found < 0) { //strange -- degenerate cluster? degenerate.push_back(i); continue; } contacts[i].pos[0] = pts[found][0]; contacts[i].pos[1] = pts[found][1]; contacts[i].pos[2] = pts[found][2]; contacts[i].normal[0] = pts[found][3]; contacts[i].normal[1] = pts[found][4]; contacts[i].normal[2] = pts[found][5]; Real len = Vector3(contacts[i].normal[0],contacts[i].normal[1],contacts[i].normal[2]).length(); contacts[i].normal[0] /= len; contacts[i].normal[1] /= len; contacts[i].normal[2] /= len; contacts[i].depth = pts[found][6]; continue; } contacts[i].normal[0] /= len; contacts[i].normal[1] /= len; contacts[i].normal[2] /= len; //cout<<"Clustered contact "<<contacts[i].pos[0]<<" "<<contacts[i].pos[1]<<" "<<contacts[i].pos[2]<<endl; //cout<<"Clustered normal "<<contacts[i].normal[0]<<" "<<contacts[i].normal[1]<<" "<<contacts[i].normal[2]<<endl; contacts[i].depth = kmeans.centers[i][6]; } reverse(degenerate.begin(),degenerate.end()); for(size_t i=0;i<degenerate.size();i++) { contacts.erase(contacts.begin()+degenerate[i]); } } bool depthGreater(const dContactGeom& a,const dContactGeom& b) { return a.depth > b.depth; } void ClusterContacts(vector<dContactGeom>& contacts,int maxClusters,Real clusterNormalScale) { gPreclusterContacts += contacts.size(); //for really big contact sets, do a subsampling if(contacts.size()*maxClusters > gMaxKMeansSize && contacts.size()*contacts.size() > gMaxHClusterSize) { int minsize = Max((int)gMaxKMeansSize/maxClusters,(int)Sqrt(Real(gMaxHClusterSize))); printf("ClusterContacts: subsampling %d to %d contacts\n",(int)contacts.size(),minsize); vector<dContactGeom> subcontacts(minsize); //random subsample /* vector<int> subsample(contacts.size()); RandomPermutation(subsample); subsample.resize(minsize); for(size_t i=0;i<subsample.size();i++) subcontacts[i] = contacts[subsample[i]]; */ //deterministic subsample for(int i=0;i<minsize;i++) { subcontacts[i] = contacts[(i*minsize)/contacts.size()]; } swap(subcontacts,contacts); } size_t hclusterSize = contacts.size()*contacts.size(); size_t kmeansSize = contacts.size()*maxClusters; //if(hclusterSize < gMaxHClusterSize) //ClusterContactsMerge(contacts,maxClusters,clusterNormalScale); //else ClusterContactsKMeans(contacts,maxClusters,clusterNormalScale); /* //TEST: contact depth sorting if(contacts.size() > maxClusters) { sort(contacts.begin(),contacts.end(),depthGreater); contacts.resize(maxClusters); } */ } void MergeContacts(vector<dContactGeom>& contacts,double posTolerance,double oriTolerance) { EqualPlane eq(posTolerance,oriTolerance); vector<vector<int> > sets; EquivalenceMap(contacts,sets,eq); vector<dContactGeom> res; vector<dContactGeom> temp; for(size_t i=0;i<sets.size();i++) { if(sets[i].empty()) continue; temp.resize(sets[i].size()); for(size_t j=0;j<sets[i].size();j++) temp[j] = contacts[sets[i][j]]; CHContactsPlane(temp); //printf("CH Reduced from %d to %d\n",sets[i].size(),temp.size()); //EqualPoint eq(posTolerance); //Clusterize(temp,eq); res.insert(res.end(),temp.begin(),temp.end()); } swap(contacts,res); } void collisionCallback(void *data, dGeomID o1, dGeomID o2) { Assert(!dGeomIsSpace(o1) && !dGeomIsSpace(o2)); dBodyID b1 = dGeomGetBody(o1); dBodyID b2 = dGeomGetBody(o2); // take care of disabled bodies if( b1 && !b2 && !dBodyIsEnabled(b1) ) return; // b1 is disabled and collides with no-body if( b2 && !b1 && !dBodyIsEnabled(b2) ) return; // b2 is disabled and collides with no-body if( b1 && b2 && !dBodyIsEnabled(b1) && !dBodyIsEnabled(b2) ) return; // both b1 and b2 are disabled int num = dCollide (o1,o2,max_contacts,gContactTemp,sizeof(dContactGeom)); vector<dContactGeom> vcontact(num); int numOk = 0; for(int i=0;i<num;i++) { if(gContactTemp[i].g1 == o2 && gContactTemp[i].g2 == o1) { printf("Swapping contact\n"); std::swap(gContactTemp[i].g1,gContactTemp[i].g2); for(int k=0;k<3;k++) gContactTemp[i].normal[k]*=-1.0; std::swap(gContactTemp[i].side1,gContactTemp[i].side2); } Assert(gContactTemp[i].g1 == o1); Assert(gContactTemp[i].g2 == o2); vcontact[numOk] = gContactTemp[i]; const dReal* n=vcontact[numOk].normal; if(Sqr(n[0])+Sqr(n[1])+Sqr(n[2]) < 0.9 || Sqr(n[0])+Sqr(n[1])+Sqr(n[2]) > 1.2) { //GIMPACT will report this //printf("Warning, degenerate contact with normal %f %f %f\n",vcontact[numOk].normal[0],vcontact[numOk].normal[1],vcontact[numOk].normal[2]); continue; } numOk++; } vcontact.resize(numOk); if(vcontact.size() > 0) { gContacts.push_back(ODEContactResult()); gContacts.back().o1 = o1; gContacts.back().o2 = o2; swap(gContacts.back().contacts,vcontact); } } void selfCollisionCallback(void *data, dGeomID o1, dGeomID o2) { ODERobot* robot = reinterpret_cast<ODERobot*>(data); Assert(!dGeomIsSpace(o1) && !dGeomIsSpace(o2)); intptr_t link1 = (intptr_t)dGeomGetData(o1); intptr_t link2 = (intptr_t)dGeomGetData(o2); Assert(link1 >= 0 && (int)link1 < (int)robot->robot.links.size()); Assert(link2 >= 0 && (int)link2 < (int)robot->robot.links.size()); if(robot->robot.selfCollisions(link1,link2)==NULL) { return; } int num = dCollide (o1,o2,max_contacts,gContactTemp,sizeof(dContactGeom)); vector<dContactGeom> vcontact(num); int numOk = 0; for(int i=0;i<num;i++) { if(gContactTemp[i].g1 == o2 && gContactTemp[i].g2 == o1) { printf("Swapping contact\n"); std::swap(gContactTemp[i].g1,gContactTemp[i].g2); for(int k=0;k<3;k++) gContactTemp[i].normal[k]*=-1.0; std::swap(gContactTemp[i].side1,gContactTemp[i].side2); } Assert(gContactTemp[i].g1 == o1); Assert(gContactTemp[i].g2 == o2); vcontact[numOk] = gContactTemp[i]; const dReal* n=vcontact[numOk].normal; if(Sqr(n[0])+Sqr(n[1])+Sqr(n[2]) < 0.9 || Sqr(n[0])+Sqr(n[1])+Sqr(n[2]) > 1.2) { printf("Warning, degenerate contact with normal %f %f %f\n",vcontact[numOk].normal[0],vcontact[numOk].normal[1],vcontact[numOk].normal[2]); //continue; } numOk++; } //TEMP: printing self collisions //if(numOk > 0) printf("%d self collision contacts between links %d and %d\n",numOk,(int)link1,(int)link2); vcontact.resize(numOk); if(kMergeContacts && numOk > 0) { MergeContacts(vcontact,kContactPosMergeTolerance,kContactOriMergeTolerance); } if(vcontact.size() > 0) { if(numOk != (int)vcontact.size()) //// The int type is not guaranteed to be big enough, use intptr_t //cout<<numOk<<" contacts between env "<<(int)dGeomGetData(o2)<<" and body "<<(int)dGeomGetData(o1)<<" (clustered to "<<vcontact.size()<<")"<<endl; cout<<numOk<<" contacts between link "<<(intptr_t)dGeomGetData(o2)<<" and link "<<(intptr_t)dGeomGetData(o1)<<" (clustered to "<<vcontact.size()<<")"<<endl; gContacts.push_back(ODEContactResult()); gContacts.back().o1 = o1; gContacts.back().o2 = o2; swap(gContacts.back().contacts,vcontact); } } void ProcessContacts(list<ODEContactResult>::iterator start,list<ODEContactResult>::iterator end,const ODESimulatorSettings& settings,bool aggregateCount=true) { if(kMergeContacts) { for(list<ODEContactResult>::iterator j=start;j!=end;j++) MergeContacts(j->contacts,kContactPosMergeTolerance,kContactOriMergeTolerance); } static bool warnedContacts = false; if(aggregateCount) { int numContacts = 0; for(list<ODEContactResult>::iterator j=start;j!=end;j++) numContacts += (int)j->contacts.size(); if(numContacts > settings.maxContacts) { //printf("Warning: %d robot-env contacts > maximum %d, may crash\n",numContacts,settings.maxContacts); if(settings.maxContacts > 50) { if(!warnedContacts) { printf("Max contacts > 50, may crash. Press enter to continue...\n"); getchar(); } warnedContacts = true; } Real scale = Real(settings.maxContacts)/numContacts; for(list<ODEContactResult>::iterator j=start;j!=end;j++) { int n=(int)Ceil(Real(j->contacts.size())*scale); //printf("Clustering %d->%d\n",j->contacts.size(),n); ClusterContacts(j->contacts,n,settings.clusterNormalScale); } } } else { for(list<ODEContactResult>::iterator j=start;j!=end;j++) { if(settings.maxContacts > 50) { if(!warnedContacts) { printf("Max contacts > 50, may crash. Press enter to continue...\n"); getchar(); } warnedContacts = true; } for(list<ODEContactResult>::iterator j=start;j!=end;j++) { ClusterContacts(j->contacts,settings.maxContacts,settings.clusterNormalScale); } } } } void ODESimulator::ClearCollisions() { dJointGroupEmpty(contactGroupID); contactList.clear(); } void ODESimulator::GetSurfaceParameters(const ODEObjectID& a,const ODEObjectID& b,dSurfaceParameters& surface) const { //TODO: base the friction on the properties of the contact point //completely rigid contact surface.mode = dContactApprox1; //surface.mode = 0; surface.bounce = 0; surface.bounce_vel = 0; //printf("GetSurfaceParameters a = %d,%d, b = %d,%d\n",a.type,a.index,b.type,b.index); ODEGeometry *ma,*mb; if(a.type == 0) { Assert(a.index < (int)envs.size()); ma = envGeoms[a.index]; } else if(a.type == 1) ma = robots[a.index]->triMesh(a.bodyIndex); else if(a.type == 2) ma = objects[a.index]->triMesh(); else Abort(); if(b.type == 0) { Assert(b.index < (int)envs.size()); mb=envGeoms[b.index]; } else if(b.type == 1) mb=robots[b.index]->triMesh(b.bodyIndex); else if(b.type == 2) mb=objects[b.index]->triMesh(); else Abort(); const ODESurfaceProperties &propa=ma->surf(),&propb=mb->surf(); if(!IsInf(propa.kStiffness) || !IsInf(propb.kStiffness)) { surface.mode |= (dContactSoftERP | dContactSoftCFM); Real kStiffness = 1.0/(1.0/propa.kStiffness+1.0/propb.kStiffness); Real kDamping = 1.0/(1.0/propa.kDamping+1.0/propb.kDamping); surface.soft_erp = ERPFromSpring(timestep,kStiffness,kDamping); surface.soft_cfm = CFMFromSpring(timestep,kStiffness,kDamping); //printf("Joint stiffness %g, damping %g\n",kStiffness,kDamping); //printf("ERP = %g, CFM = %g\n",surface.soft_erp,surface.soft_cfm); } surface.mu = 2.0/(1.0/propa.kFriction+1.0/propb.kFriction); //correction to account for pyramid shaped friction cone surface.mu *= 0.707; surface.bounce = 0.5*(propa.kRestitution+propb.kRestitution); surface.bounce_vel = 1e-2; if(surface.bounce != 0) surface.mode |= dContactBounce; } void ODESimulator::SetupContactResponse(const ODEObjectID& a,const ODEObjectID& b,int feedbackIndex,ODEContactResult& c) { dContact contact; GetSurfaceParameters(a,b,contact.surface); dBodyID b1 = dGeomGetBody(c.o1); dBodyID b2 = dGeomGetBody(c.o2); c.feedback.resize(c.contacts.size()); for(size_t k=0;k<c.contacts.size();k++) { //add contact joint to joint group contact.geom = c.contacts[k]; Assert(contact.geom.g1 == c.o1 || contact.geom.g1 == c.o2); Assert(contact.geom.g2 == c.o1 || contact.geom.g2 == c.o2); Assert(contact.geom.depth >= 0); Assert(contact.geom.g1 == c.o1); dJointID joint = dJointCreateContact(worldID,contactGroupID,&contact); dJointSetFeedback(joint,&c.feedback[k]); //if(b2==0) //dJointAttach(joint,b2,b1); //else dJointAttach(joint,b1,b2); } //if contact feedback is enabled, do it! pair<ODEObjectID,ODEObjectID> cindex; bool reverse = false; if(b < a) { cindex.first = b; cindex.second = a; reverse = true; } else { cindex.first = a; cindex.second = b; } ODEContactList* cl=NULL; if(contactList.count(cindex) != 0) { cl=&contactList[cindex]; } else { //check if there's a generic robot feedback list bool checkRobot=false; if(cindex.first.type == 1 && cindex.first.bodyIndex != -1) { cindex.first.bodyIndex=-1; checkRobot=true; } if(cindex.second.type == 1 && cindex.second.bodyIndex != -1) { cindex.second.bodyIndex=-1; checkRobot=true; } if(checkRobot) { if(contactList.count(cindex) != 0) cl=&contactList[cindex]; } } if(cl) { size_t start=cl->points.size(); cl->points.resize(start+c.contacts.size()); for(size_t k=0;k<c.contacts.size();k++) { Assert(k+start < cl->points.size()); CopyVector(cl->points[k+start].x,c.contacts[k].pos); CopyVector(cl->points[k+start].n,c.contacts[k].normal); cl->points[k+start].kFriction = contact.surface.mu; if(reverse) cl->points[k+start].n.inplaceNegative(); } Assert(feedbackIndex >= 0 && feedbackIndex < (int)gContacts.size()); cl->feedbackIndices.push_back(feedbackIndex); } } void ODESimulator::DetectCollisions() { #if DO_TIMING Timer timer; #endif //DO_TIMING dJointGroupEmpty(contactGroupID); //clear feedback structure for(map<pair<ODEObjectID,ODEObjectID>,ODEContactList>::iterator i=contactList.begin();i!=contactList.end();i++) { i->second.points.clear(); i->second.forces.clear(); i->second.feedbackIndices.clear(); } gContacts.clear(); pair<ODEObjectID,ODEObjectID> cindex; int jcount=0; if(settings.rigidObjectCollisions) { //call the collision routine between objects and the world dSpaceCollide(envSpaceID,(void*)this,collisionCallback); #if DO_TIMING gContactDetectTime += timer.ElapsedTime(); timer.Reset(); #endif //DO_TIMING ProcessContacts(gContacts.begin(),gContacts.end(),settings,false); #if DO_TIMING gClusterTime += timer.ElapsedTime(); timer.Reset(); #endif //DO_TIMING for(list<ODEContactResult>::iterator j=gContacts.begin();j!=gContacts.end();j++,jcount++) { //// int is not necessarily big enough, use intptr_t //int o1 = (int)dGeomGetData(j->o1); //int o2 = (int)dGeomGetData(j->o2); intptr_t o1 = (intptr_t)dGeomGetData(j->o1); intptr_t o2 = (intptr_t)dGeomGetData(j->o2); if(o1 < 0) { //it's an environment cindex.first = ODEObjectID(0,(-o1-1)); } else { cindex.first = ODEObjectID(2,o1); } if(o2 < 0) { //it's an environment cindex.second = ODEObjectID(0,(-o2-1)); } else { cindex.second = ODEObjectID(2,o2); } if(o1 < 0 && o2 < 0) { fprintf(stderr,"Warning, detecting terrain-terrain collisions?\n"); } else { j->feedback.resize(j->contacts.size()); SetupContactResponse(cindex.first,cindex.second,jcount,*j); } } } //do robot-environment collisions for(size_t i=0;i<robots.size();i++) { cindex.first = ODEObjectID(1,i); #if DO_TIMING timer.Reset(); #endif //DO_TIMING //call the collision routine between the robot and the world bool gContactsEmpty = gContacts.empty(); list<ODEContactResult>::iterator gContactStart; if(!gContactsEmpty) gContactStart = --gContacts.end(); dSpaceCollide2((dxGeom *)robots[i]->space(),(dxGeom *)envSpaceID,(void*)this,collisionCallback); if(!gContactsEmpty) ++gContactStart; else gContactStart = gContacts.begin(); #if DO_TIMING gContactDetectTime += timer.ElapsedTime(); timer.Reset(); #endif //DO_TIMING ProcessContacts(gContactStart,gContacts.end(),settings); #if DO_TIMING gClusterTime += timer.ElapsedTime(); timer.Reset(); #endif //DO_TIMING //setup the contact "joints" and contactLists for(list<ODEContactResult>::iterator j=gContactStart;j!=gContacts.end();j++,jcount++) { bool isBodyo1 = false, isBodyo2 = false; for(size_t k=0;k<robots[i]->robot.links.size();k++) { if(robots[i]->triMesh(k) && j->o1 == robots[i]->geom(k)) isBodyo1=true; if(robots[i]->triMesh(k) && j->o2 == robots[i]->geom(k)) isBodyo2=true; } intptr_t body,obj; if(isBodyo2) { printf("Warning, ODE collision result lists bodies in reverse order\n"); Assert(!isBodyo1); body = (intptr_t)dGeomGetData(j->o2); obj = (intptr_t)dGeomGetData(j->o1); } else { Assert(!isBodyo2); Assert(isBodyo1); body = (intptr_t)dGeomGetData(j->o1); obj = (intptr_t)dGeomGetData(j->o2); } //printf("Collision between body %d and obj %d\n",body,obj); Assert(body >= 0 && body < (int)robots[i]->robot.links.size()); Assert(obj >= -(int)envs.size() && obj < (int)objects.size()); if(robots[i]->robot.parents[body] == -1 && obj < 0) { //fixed links fprintf(stderr,"Warning, colliding a fixed link and the terrain\n"); continue; } cindex.first.bodyIndex = body; if(obj < 0) { //it's an environment cindex.second = ODEObjectID(0,(-obj-1)); } else { cindex.second = ODEObjectID(2,obj); } SetupContactResponse(cindex.first,cindex.second,jcount,*j); } if(settings.robotSelfCollisions) { robots[i]->EnableSelfCollisions(true); #if DO_TIMING timer.Reset(); #endif cindex.second = ODEObjectID(1,i); gContactsEmpty = gContacts.empty(); if(!gContactsEmpty) gContactStart = --gContacts.end(); //call the self collision routine for the robot dSpaceCollide(robots[i]->space(),(void*)robots[i],selfCollisionCallback); if(!gContactsEmpty) ++gContactStart; else gContactStart = gContacts.begin(); #if DO_TIMING gContactDetectTime += timer.ElapsedTime(); timer.Reset(); #endif //DO_TIMING ProcessContacts(gContactStart,gContacts.end(),settings); #if DO_TIMING gClusterTime += timer.ElapsedTime(); timer.Reset(); #endif //DO_TIMING //setup the contact "joints" and contactLists for(list<ODEContactResult>::iterator j=gContactStart;j!=gContacts.end();j++,jcount++) { intptr_t body1 = (intptr_t)dGeomGetData(j->o1); intptr_t body2 = (intptr_t)dGeomGetData(j->o2); //printf("Collision between body %d and body %d\n",body1,body2); Assert(body1 >= 0 && body1 < (int)robots[i]->robot.links.size()); Assert(body2 >= 0 && body2 < (int)robots[i]->robot.links.size()); cindex.first.bodyIndex = body1; cindex.second.bodyIndex = body2; SetupContactResponse(cindex.first,cindex.second,jcount,*j); } } if(settings.robotRobotCollisions) { for(size_t k=i+1;k<robots.size();k++) { cindex.second = ODEObjectID(1,k); #if DO_TIMING timer.Reset(); #endif //DO_TIMING gContactsEmpty = gContacts.empty(); if(!gContactsEmpty) gContactStart = --gContacts.end(); dSpaceCollide2((dxGeom *)robots[i]->space(),(dxGeom *)robots[k]->space(),(void*)this,collisionCallback); if(!gContactsEmpty) ++gContactStart; else gContactStart = gContacts.begin(); #if DO_TIMING gContactDetectTime += timer.ElapsedTime(); timer.Reset(); #endif //DO_TIMING ProcessContacts(gContactStart,gContacts.end(),settings); #if DO_TIMING gClusterTime += timer.ElapsedTime(); timer.Reset(); #endif //DO_TIMING //setup the contact "joints" and contactLists for(list<ODEContactResult>::iterator j=gContactStart;j!=gContacts.end();j++,jcount++) { intptr_t body1 = (intptr_t)dGeomGetData(j->o1); intptr_t body2 = (intptr_t)dGeomGetData(j->o2); //printf("Collision between robot %d and robot %d\n",i,k); Assert(body1 >= 0 && body1 < (int)robots[i]->robot.links.size()); Assert(body2 >= 0 && body2 < (int)robots[k]->robot.links.size()); cindex.first.bodyIndex = body1; cindex.second.bodyIndex = body2; SetupContactResponse(cindex.first,cindex.second,jcount,*j); } } } } } void ODESimulator::EnableContactFeedback(const ODEObjectID& a,const ODEObjectID& b) { pair<ODEObjectID,ODEObjectID> index; if(a < b) { index.first=a; index.second=b; } else { index.first=b; index.second=a; } contactList[index] = ODEContactList(); } ODEContactList* ODESimulator::GetContactFeedback(const ODEObjectID& a,const ODEObjectID& b) { pair<ODEObjectID,ODEObjectID> index; if(a < b) { index.first=a; index.second=b; } else { index.first=b; index.second=a; } if(contactList.count(index) != 0) { return &contactList[index]; } return NULL; } bool HasContact(dBodyID a) { if(a == 0) return false; int n = dBodyGetNumJoints (a); for(int i=0;i<n;i++) { dJointID j=dBodyGetJoint (a,i); if(dJointGetType(j)==dJointTypeContact) return true; } return false; } ///Will produce bogus o1 and o2 vectors void GetContacts(dBodyID a,vector<ODEContactList>& contacts) { if(a == 0) return; contacts.resize(0); for(list<ODEContactResult>::iterator i=gContacts.begin();i!=gContacts.end();i++) { if(a == dGeomGetBody(i->o1) || a == dGeomGetBody(i->o2)) { dBodyID b = dGeomGetBody(i->o2); bool reverse = false; if(b == a) { b = dGeomGetBody(i->o1); reverse = true; } contacts.resize(contacts.size()+1); contacts.back().points.resize(i->contacts.size()); contacts.back().forces.resize(i->feedback.size()); for(size_t j=0;j<i->feedback.size();j++) { CopyVector(contacts.back().forces[j],i->feedback[j].f1); CopyVector(contacts.back().points[j].x,i->contacts[j].pos); CopyVector(contacts.back().points[j].n,i->contacts[j].normal); //contacts.back().points[j].kFriction = i->contacts[j].surface.mu; contacts.back().points[j].kFriction = 0; if(reverse) { contacts.back().forces[j].inplaceNegative(); contacts.back().points[j].n.inplaceNegative(); } } } } } bool HasContact(dBodyID a,dBodyID b) { if(a == 0 && b == 0) return false; //two environments if(a == 0) Swap(a,b); int n = dBodyGetNumJoints (a); for(int i=0;i<n;i++) { dJointID j=dBodyGetJoint (a,i); if(dJointGetType(j)==dJointTypeContact) { dBodyID j0=dJointGetBody(j,0); dBodyID j1=dJointGetBody(j,1); if(j0 == b || j1 == b) return true; } } return false; } bool ODESimulator::InContact(const ODEObjectID& a) const { if(a.type == 0) { //environment //must loop through all objects to see what is in contact with the //environment for(size_t i=0;i<objects.size();i++) { if(HasContact(objects[i]->body(),0)) return true; } for(size_t i=0;i<robots.size();i++) { for(size_t j=0;j<robots[i]->robot.links.size();j++) { if(HasContact(robots[i]->body(j),0)) return true; } } return false; } else if(a.type == 2) {//object return HasContact(objects[a.index]->body()); } else { if(a.bodyIndex >= 0) return HasContact(robots[a.index]->body(a.bodyIndex)); else { //any robot link for(size_t i=0;i<robots[a.index]->robot.links.size();i++) if(HasContact(robots[a.index]->body(i))) return true; return false; } } return false; } bool ODESimulator::InContact(const ODEObjectID& a,const ODEObjectID& b) const { vector<dBodyID> bodya, bodyb; if(a.type == 0) { bodya.push_back(0); } else if(a.type == 2) { bodya.push_back(objects[a.index]->body()); } else { if(a.bodyIndex >= 0) bodya.push_back(robots[a.index]->body(a.bodyIndex)); else { for(size_t i=0;i<robots[a.index]->robot.links.size();i++) if(robots[a.index]->body(i)) bodya.push_back(robots[a.index]->body(i)); } } if(b.type == 0) { bodyb.push_back(0); } else if(b.type == 2) { bodyb.push_back(objects[b.index]->body()); } else { if(b.bodyIndex >= 0) bodyb.push_back(robots[b.index]->body(b.bodyIndex)); else { for(size_t i=0;i<robots[b.index]->robot.links.size();i++) if(robots[b.index]->body(i)) bodyb.push_back(robots[b.index]->body(i)); } } for(size_t i=0;i<bodya.size();i++) for(size_t j=0;j<bodyb.size();j++) if(HasContact(bodya[i],bodyb[j])) return true; return false; } void ODESimulator::StepDynamics(Real dt) { dWorldStep(worldID,dt); //dWorldQuickStep(worldID,dt); } bool ODESimulator::ReadState(File& f) { #if TEST_READ_WRITE_STATE for(size_t i=0;i<robots.size();i++) TestReadWriteState(*robots[i],"ODERobot"); for(size_t i=0;i<objects.size();i++) TestReadWriteState(*objects[i],"ODEObject"); #endif for(size_t i=0;i<robots.size();i++) { if(!robots[i]->ReadState(f)) { fprintf(stderr,"ODESimulator::ReadState(): failed to read robot %d\n",i); return false; } } for(size_t i=0;i<objects.size();i++) { if(!objects[i]->ReadState(f)) { fprintf(stderr,"ODESimulator::ReadState(): failed to read object %d\n",i); return false; } } contactList.clear(); return true; } bool ODESimulator::WriteState(File& f) const { for(size_t i=0;i<robots.size();i++) if(!robots[i]->WriteState(f)) return false; for(size_t i=0;i<objects.size();i++) if(!objects[i]->WriteState(f)) return false; return true; }
30.953697
181
0.661544
bbgw
c34ef8b4ed2fe5fbc87c817a7025e7eff1622ad7
1,284
cpp
C++
webrtc_note/mediaserver/10_addr_pointer/03_dynamic_cast/dynamic_cast.cpp
miaopei/ffmpeg-webrtc
1a0b59530f4d008a368376be041549db40e066eb
[ "MIT" ]
12
2019-06-06T15:34:19.000Z
2022-01-14T07:41:55.000Z
webrtc_note/mediaserver/10_addr_pointer/03_dynamic_cast/dynamic_cast.cpp
xuesongzh/ffmpeg-webrtc
a00e7e08226039c8ff6a105e0083f207043e2b2b
[ "MIT" ]
2
2019-08-17T16:52:44.000Z
2020-07-05T15:06:12.000Z
webrtc_note/mediaserver/10_addr_pointer/03_dynamic_cast/dynamic_cast.cpp
miaopei/ffmpeg-webrtc
1a0b59530f4d008a368376be041549db40e066eb
[ "MIT" ]
8
2019-06-13T12:25:02.000Z
2022-01-09T13:23:55.000Z
#include <iostream> class Base { public: Base(int a, int b){ this->a = a; this->b = b; } public: virtual void print(){ std::cout << "member: a=" << a << ", b=" << b << std::endl; } public: int a; int b; }; class Derived1: public Base { public: Derived1(int a, int b, int o):Base(a, b){ c = o; } public: virtual void print(){ std::cout << "member: a=" << a << ", b=" << b << ", c=" << c << std::endl; } public: int c; }; class Derived2: public Base { public: Derived2(int a, int b, int o):Base(a, b){ d = o; } public: virtual void print() { std::cout << "member: a=" << a << ", b=" << b << ", d=" << d << std::endl; } public: int d; }; int main(int argc, char* argv[]) { Base *b = new Base(1, 2); b = dynamic_cast<Base*>(new Derived1(3, 4, 5)); b->print(); b = static_cast<Base*>(new Derived2(6, 7, 8)); b->print(); }
21.4
56
0.352804
miaopei
c3515e4b503c723adf43bff2a1b1200b4e0bc9a3
13,700
cpp
C++
swg_generated/cpp/qt5cpp/client/SWGDepositApi.cpp
Reclusive-Trader/upbit-client
ca1fb02c9d4e22f6d726baf30a455a235ce0324a
[ "MIT" ]
46
2021-01-07T14:53:26.000Z
2022-03-25T10:11:16.000Z
swg_generated/cpp/qt5cpp/client/SWGDepositApi.cpp
Reclusive-Trader/upbit-client
ca1fb02c9d4e22f6d726baf30a455a235ce0324a
[ "MIT" ]
4
2021-02-20T05:21:29.000Z
2022-03-01T12:53:02.000Z
swg_generated/cpp/qt5cpp/client/SWGDepositApi.cpp
Reclusive-Trader/upbit-client
ca1fb02c9d4e22f6d726baf30a455a235ce0324a
[ "MIT" ]
59
2021-01-07T11:58:10.000Z
2022-02-15T06:11:33.000Z
/** * Upbit Open API * ## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [open-api@upbit.com] * * OpenAPI spec version: 1.0.0 * Contact: ujhin942@gmail.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "SWGDepositApi.h" #include "SWGHelpers.h" #include "SWGModelFactory.h" #include "SWGQObjectWrapper.h" #include <QJsonArray> #include <QJsonDocument> namespace Swagger { SWGDepositApi::SWGDepositApi() {} SWGDepositApi::~SWGDepositApi() {} SWGDepositApi::SWGDepositApi(QString host, QString basePath) { this->host = host; this->basePath = basePath; } void SWGDepositApi::deposit_coinAddress(QString* currency) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/deposits/coin_address"); if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("currency")) .append("=") .append(QUrl::toPercentEncoding(stringValue(currency))); SWGHttpRequestWorker *worker = new SWGHttpRequestWorker(); SWGHttpRequestInput input(fullPath, "GET"); foreach(QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); } connect(worker, &SWGHttpRequestWorker::on_execution_finished, this, &SWGDepositApi::deposit_coinAddressCallback); worker->execute(&input); } void SWGDepositApi::deposit_coinAddressCallback(SWGHttpRequestWorker * worker) { QString msg; QString error_str = worker->error_str; QNetworkReply::NetworkError error_type = worker->error_type; if (worker->error_type == QNetworkReply::NoError) { msg = QString("Success! %1 bytes").arg(worker->response.length()); } else { msg = "Error: " + worker->error_str; } QString json(worker->response); SWGDepositCompleteResponse* output = static_cast<SWGDepositCompleteResponse*>(create(json, QString("SWGDepositCompleteResponse"))); auto wrapper = new SWGQObjectWrapper<SWGDepositCompleteResponse*> (output); wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { emit deposit_coinAddressSignal(output); } else { emit deposit_coinAddressSignalE(output, error_type, error_str); emit deposit_coinAddressSignalEFull(worker, error_type, error_str); } } void SWGDepositApi::deposit_coinAddresses() { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/deposits/coin_addresses"); SWGHttpRequestWorker *worker = new SWGHttpRequestWorker(); SWGHttpRequestInput input(fullPath, "GET"); foreach(QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); } connect(worker, &SWGHttpRequestWorker::on_execution_finished, this, &SWGDepositApi::deposit_coinAddressesCallback); worker->execute(&input); } void SWGDepositApi::deposit_coinAddressesCallback(SWGHttpRequestWorker * worker) { QString msg; QString error_str = worker->error_str; QNetworkReply::NetworkError error_type = worker->error_type; if (worker->error_type == QNetworkReply::NoError) { msg = QString("Success! %1 bytes").arg(worker->response.length()); } else { msg = "Error: " + worker->error_str; } QString json(worker->response); SWGObject* output = static_cast<SWGObject*>(create(json, QString("SWGObject"))); auto wrapper = new SWGQObjectWrapper<SWGObject*> (output); wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { emit deposit_coinAddressesSignal(output); } else { emit deposit_coinAddressesSignalE(output, error_type, error_str); emit deposit_coinAddressesSignalEFull(worker, error_type, error_str); } } void SWGDepositApi::deposit_generateCoinAddress(QString* currency) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/deposits/generate_coin_address"); SWGHttpRequestWorker *worker = new SWGHttpRequestWorker(); SWGHttpRequestInput input(fullPath, "POST"); if (currency != nullptr) { input.add_var("currency", *currency); } foreach(QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); } connect(worker, &SWGHttpRequestWorker::on_execution_finished, this, &SWGDepositApi::deposit_generateCoinAddressCallback); worker->execute(&input); } void SWGDepositApi::deposit_generateCoinAddressCallback(SWGHttpRequestWorker * worker) { QString msg; QString error_str = worker->error_str; QNetworkReply::NetworkError error_type = worker->error_type; if (worker->error_type == QNetworkReply::NoError) { msg = QString("Success! %1 bytes").arg(worker->response.length()); } else { msg = "Error: " + worker->error_str; } QString json(worker->response); SWGDepositCompleteResponse* output = static_cast<SWGDepositCompleteResponse*>(create(json, QString("SWGDepositCompleteResponse"))); auto wrapper = new SWGQObjectWrapper<SWGDepositCompleteResponse*> (output); wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { emit deposit_generateCoinAddressSignal(output); } else { emit deposit_generateCoinAddressSignalE(output, error_type, error_str); emit deposit_generateCoinAddressSignalEFull(worker, error_type, error_str); } } void SWGDepositApi::deposit_info(QString* uuid, QString* txid, QString* currency) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/deposit"); if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("uuid")) .append("=") .append(QUrl::toPercentEncoding(stringValue(uuid))); if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("txid")) .append("=") .append(QUrl::toPercentEncoding(stringValue(txid))); if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("currency")) .append("=") .append(QUrl::toPercentEncoding(stringValue(currency))); SWGHttpRequestWorker *worker = new SWGHttpRequestWorker(); SWGHttpRequestInput input(fullPath, "GET"); foreach(QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); } connect(worker, &SWGHttpRequestWorker::on_execution_finished, this, &SWGDepositApi::deposit_infoCallback); worker->execute(&input); } void SWGDepositApi::deposit_infoCallback(SWGHttpRequestWorker * worker) { QString msg; QString error_str = worker->error_str; QNetworkReply::NetworkError error_type = worker->error_type; if (worker->error_type == QNetworkReply::NoError) { msg = QString("Success! %1 bytes").arg(worker->response.length()); } else { msg = "Error: " + worker->error_str; } QString json(worker->response); SWGDeposit* output = static_cast<SWGDeposit*>(create(json, QString("SWGDeposit"))); auto wrapper = new SWGQObjectWrapper<SWGDeposit*> (output); wrapper->deleteLater(); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { emit deposit_infoSignal(output); } else { emit deposit_infoSignalE(output, error_type, error_str); emit deposit_infoSignalEFull(worker, error_type, error_str); } } void SWGDepositApi::deposit_infoAll(QString* currency, QString* state, QList<QString*>* uuids, QList<QString*>* txids, SWGNumber* limit, SWGNumber* page, QString* order_by) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/deposits"); if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("currency")) .append("=") .append(QUrl::toPercentEncoding(stringValue(currency))); if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("state")) .append("=") .append(QUrl::toPercentEncoding(stringValue(state))); if (uuids->size() > 0) { if (QString("multi").indexOf("multi") == 0) { foreach(QString* t, *uuids) { if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append("uuids=").append(stringValue(t)); } } else if (QString("multi").indexOf("ssv") == 0) { if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append("uuids="); qint32 count = 0; foreach(QString* t, *uuids) { if (count > 0) { fullPath.append(" "); } fullPath.append(stringValue(t)); } } else if (QString("multi").indexOf("tsv") == 0) { if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append("uuids="); qint32 count = 0; foreach(QString* t, *uuids) { if (count > 0) { fullPath.append("\t"); } fullPath.append(stringValue(t)); } } } if (txids->size() > 0) { if (QString("multi").indexOf("multi") == 0) { foreach(QString* t, *txids) { if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append("txids=").append(stringValue(t)); } } else if (QString("multi").indexOf("ssv") == 0) { if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append("txids="); qint32 count = 0; foreach(QString* t, *txids) { if (count > 0) { fullPath.append(" "); } fullPath.append(stringValue(t)); } } else if (QString("multi").indexOf("tsv") == 0) { if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append("txids="); qint32 count = 0; foreach(QString* t, *txids) { if (count > 0) { fullPath.append("\t"); } fullPath.append(stringValue(t)); } } } if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("limit")) .append("=") .append(QUrl::toPercentEncoding(stringValue(limit))); if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("page")) .append("=") .append(QUrl::toPercentEncoding(stringValue(page))); if (fullPath.indexOf("?") > 0) fullPath.append("&"); else fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("order_by")) .append("=") .append(QUrl::toPercentEncoding(stringValue(order_by))); SWGHttpRequestWorker *worker = new SWGHttpRequestWorker(); SWGHttpRequestInput input(fullPath, "GET"); foreach(QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); } connect(worker, &SWGHttpRequestWorker::on_execution_finished, this, &SWGDepositApi::deposit_infoAllCallback); worker->execute(&input); } void SWGDepositApi::deposit_infoAllCallback(SWGHttpRequestWorker * worker) { QString msg; QString error_str = worker->error_str; QNetworkReply::NetworkError error_type = worker->error_type; if (worker->error_type == QNetworkReply::NoError) { msg = QString("Success! %1 bytes").arg(worker->response.length()); } else { msg = "Error: " + worker->error_str; } QList<SWGDeposit*>* output = new QList<SWGDeposit*>(); QString json(worker->response); QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonArray jsonArray = doc.array(); auto wrapper = new SWGQObjectWrapper<QList<SWGDeposit*>*> (output); wrapper->deleteLater(); foreach(QJsonValue obj, jsonArray) { SWGDeposit* o = new SWGDeposit(); QJsonObject jv = obj.toObject(); QJsonObject * ptr = (QJsonObject*)&jv; o->fromJsonObject(*ptr); auto objwrapper = new SWGQObjectWrapper<SWGDeposit*> (o); objwrapper->deleteLater(); output->append(o); } worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { emit deposit_infoAllSignal(output); } else { emit deposit_infoAllSignalE(output, error_type, error_str); emit deposit_infoAllSignalEFull(worker, error_type, error_str); } } }
29.148936
174
0.63146
Reclusive-Trader
c3531b198c7bb2f9265dae8567fa54f4391b28e7
2,296
cpp
C++
DEM/Game/src/AI/Memory/MemSystem.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
15
2019-05-07T11:26:13.000Z
2022-01-12T18:26:45.000Z
DEM/Game/src/AI/Memory/MemSystem.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
16
2021-10-04T17:15:31.000Z
2022-03-20T09:34:29.000Z
DEM/Game/src/AI/Memory/MemSystem.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
2
2019-04-28T23:27:48.000Z
2019-05-07T11:26:18.000Z
#include "MemSystem.h" #include <AI/PropActorBrain.h> namespace AI { void CMemSystem::Update() { float Now = 0.f;//(float)GameSrv->GetTime(); CArray<CSensor*> ValidationSensors; // Here we validate facts that reside in memory but weren't updated by the last // sensor activity session. Facts will be accepted or rejected by sensors where // it is possible. Some sort of prediction can be applied to remaining facts. for (UPTR i = 0; i < Facts.GetListCount(); ++i) { //!!!can avoid second dictionary lookup, index will always be i! //???!!!cache sensor lists?! CArray<PSensor>::CIterator It = pActor->GetSensors().Begin(); for (; It != pActor->GetSensors().End(); ++It) if ((*It)->ValidatesFactType(*Facts.GetKeyAt(i))) ValidationSensors.Add((*It)); for (CMemFactNode ItCurr = Facts.GetHeadAt(i); ItCurr; /* empty */) { CMemFact* pFact = ItCurr->Get(); if (pFact->LastUpdateTime < Now) { UPTR Result = Running; CArray<CSensor*>::CIterator It = ValidationSensors.Begin(); for (; It != ValidationSensors.End(); ++It) { // Since we validate only facts not updated this frame, we definitely know here, // that sensor didn't sense stimulus that produced this fact Result = (*It)->ValidateFact(pActor, *pFact); if (Result != Running) break; } if (Result != Failure) pFact->Confidence -= (Now - pFact->LastUpdateTime) * pFact->ForgettingFactor; if (Result == Failure || pFact->Confidence <= 0.f) { CMemFactNode ItRemove = ItCurr; ++ItCurr; Facts.Remove(ItRemove); continue; } // update facts here (can predict positions etc) pFact->LastUpdateTime = Now; } ++ItCurr; } ValidationSensors.Clear(); //???sort by confidence? may be only some fact types } } //--------------------------------------------------------------------- CMemFact* CMemSystem::FindFact(const CMemFact& Pattern, Data::CFlags FieldMask) { CMemFactNode ItCurr = Facts.GetHead(Pattern.GetKey()); while (ItCurr) { // Can lookup pointer to virtual function Match() once since facts are grouped by the class if ((*ItCurr)->Match(Pattern, FieldMask)) return *ItCurr; ++ItCurr; } return nullptr; } //--------------------------------------------------------------------- }
26.697674
93
0.619338
niello
c354055e941357c284944c6b60ed479af608b87c
34,574
cpp
C++
src/QtPhonemes/Phonemes/nSpeechTune.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nSpeechTune.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nSpeechTune.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
#include <qtphonemes.h> #define SYL_RISE 1 #define SYL_EMPHASIS 2 #define SYL_END_CLAUSE 4 #define PITCHfall 0 #define PITCHrise 2 #define PITCHfrise 4 // and 3 must be for the variant preceded by 'r' #define PITCHfrise2 6 // and 5 must be the 'r' variant #define PITCHrisefall 8 #define N_TONE_HEAD_TABLE 13 #define N_TONE_NUCLEUS_TABLE 13 #define SECONDARY 3 #define PRIMARY 4 #define PRIMARY_STRESSED 6 #define PRIMARY_LAST 7 #define T_EMPH 1 #define OPTION_EMPHASIZE_ALLCAPS 0x100 #define OPTION_EMPHASIZE_PENULTIMATE 0x200 typedef struct { char name [12] ; unsigned char flags [ 4] ; signed char head_extend [ 8] ; unsigned char prehead_start ; unsigned char prehead_end ; unsigned char stressed_env ; unsigned char stressed_drop ; unsigned char secondary_drop ; unsigned char unstressed_shape ; unsigned char onset ; unsigned char head_start ; unsigned char head_end ; unsigned char head_last ; unsigned char head_max_steps ; unsigned char n_head_extend ; signed char unstr_start [ 3] ; // for: onset, head, last signed char unstr_end [ 3] ; unsigned char nucleus0_env ; // pitch envelope, tonic syllable is at end, no tail unsigned char nucleus0_max ; unsigned char nucleus0_min ; unsigned char nucleus1_env ; // when followed by a tail unsigned char nucleus1_max ; unsigned char nucleus1_min ; unsigned char tail_start ; unsigned char tail_end ; unsigned char split_nucleus_env ; unsigned char split_nucleus_max ; unsigned char split_nucleus_min ; unsigned char split_tail_start ; unsigned char split_tail_end ; unsigned char split_tune ; unsigned char spare [ 8] ; int spare2 ; // the struct length should be a multiple of 4 bytes } TUNE ; typedef struct { unsigned char pre_start ; unsigned char pre_end ; unsigned char body_start ; unsigned char body_end ; int * body_drops ; unsigned char body_max_steps ; char body_lower_u ; unsigned char n_overflow ; signed char * overflow ; } TONE_HEAD ; typedef struct { unsigned char pitch_env0 ; /* pitch envelope, tonic syllable at end */ unsigned char tonic_max0 ; unsigned char tonic_min0 ; unsigned char pitch_env1 ; /* followed by unstressed */ unsigned char tonic_max1 ; unsigned char tonic_min1 ; short * backwards ; unsigned char tail_start ; unsigned char tail_end ; unsigned char flags ; } TONE_NUCLEUS ; /* indexed by stress */ static int min_drop[] = { 6, 7, 9, 9,20,20,20,25} ; // pitch change during the main part of the clause static int drops_0[8] = { 9, 9,16,16,16,23,55,32} ; // overflow table values are 64ths of the body pitch range (between body_start and body_end) static signed char oflow [] = { 0, 40, 24, 8, 0} ; static signed char oflow_emf [] = {10, 52, 32, 20, 10} ; static signed char oflow_less[] = { 6, 38, 24, 14, 4} ; static TONE_HEAD tone_head_table[N_TONE_HEAD_TABLE] = { { 46, 57, 78, 50, drops_0, 3, 7, 5, oflow } , // 0 statement { 46, 57, 78, 46, drops_0, 3, 7, 5, oflow } , // 1 comma { 46, 57, 78, 46, drops_0, 3, 7, 5, oflow } , // 2 question { 46, 57, 90, 50, drops_0, 3, 9, 5, oflow_emf } , // 3 exclamation { 46, 57, 78, 50, drops_0, 3, 7, 5, oflow } , // 4 statement, emphatic { 46, 57, 74, 55, drops_0, 4, 7, 5, oflow_less} , // 5 statement, less intonation { 46, 57, 74, 55, drops_0, 4, 7, 5, oflow_less} , // 6 comma, less intonation { 46, 57, 74, 55, drops_0, 4, 7, 5, oflow_less} , // 7 comma, less intonation, less rise { 46, 57, 78, 50, drops_0, 3, 7, 5, oflow } , // 8 pitch raises at end of sentence { 46, 57, 78, 46, drops_0, 3, 7, 5, oflow } , // 9 comma { 46, 57, 78, 50, drops_0, 3, 7, 5, oflow } , // 10 question { 34, 41, 41, 32, drops_0, 3, 7, 5, oflow_less} , // 11 test { 46, 57, 55, 50, drops_0, 3, 7, 5, oflow_less} // 12 test }; static TONE_NUCLEUS tone_nucleus_table[N_TONE_NUCLEUS_TABLE] = { {PITCHfall, 64, 8, PITCHfall, 70,18, NULL, 24, 12, 0}, // 0 statement {PITCHfrise, 80,18, PITCHfrise2, 78,22, NULL, 34, 52, 0}, // 1 comma {PITCHfrise, 88,22, PITCHfrise2, 82,22, NULL, 34, 64, 0}, // 2 question {PITCHfall, 92, 8, PITCHfall, 92,80, NULL, 76, 8, T_EMPH}, // 3 exclamation {PITCHfall, 86, 4, PITCHfall, 94,66, NULL, 34, 10, 0}, // 4 statement, emphatic {PITCHfall, 62,10, PITCHfall, 62,20, NULL, 28, 16, 0}, // 5 statement, less intonation {PITCHfrise, 68,18, PITCHfrise2, 68,22, NULL, 30, 44, 0}, // 6 comma, less intonation {PITCHfrise2, 64,16, PITCHfall, 66,32, NULL, 32, 18, 0}, // 7 comma, less intonation, less rise {PITCHrise, 68,46, PITCHfall, 42,32, NULL, 46, 58, 0}, // 8 pitch raises at end of sentence {PITCHfrise, 78,24, PITCHfrise2, 72,22, NULL, 42, 52, 0}, // 9 comma {PITCHfrise, 88,34, PITCHfall, 64,32, NULL, 46, 82, 0}, // 10 question {PITCHfall, 56,12, PITCHfall, 56,20, NULL, 24, 12, 0}, // 11 test {PITCHfall, 70,18, PITCHfall, 70,24, NULL, 32, 20, 0}, // 12 test }; //////////////////////////////////////////////////////////////////////// int PitchSegment ( N::Syllables & syllables , int start , int end , TONE_HEAD * th , TONE_NUCLEUS * tn , int MinStress , int Continuing ) /* Calculate pitches until next RESET or tonic syllable, or end. Increment pitch if stress is >= min_stress. Used for tonic segment */ { int stress ; int pitch = 0 ; int increment = 0 ; int n_primary = 0 ; int n_steps = 0 ; int initial ; int overflow = 0 ; int n_overflow ; int pitch_range ; int pitch_range_abs ; int * drops = th->body_drops ; signed char * overflow_tab ; static signed char continue_tab[5] = {-26, 32, 20, 8, 0} ; /////////////////////////////////////////////////////////////////////// pitch_range = (th->body_end - th->body_start) << 8 ; pitch_range_abs = abs(pitch_range) ; /////////////////////////////////////////////////////////////////////// if ( Continuing ) { initial = 0 ; overflow = 0 ; n_overflow = 5 ; overflow_tab = continue_tab ; increment = pitch_range / ( th->body_max_steps -1 ) ; } else { n_overflow = th->n_overflow ; overflow_tab = th->overflow ; initial = 1 ; } ; /////////////////////////////////////////////////////////////////////// while ( start < end ) { stress = syllables[start]->Stress ; if ( initial || (stress >= MinStress)) { // a primary stress if ( ( initial ) || ( stress == 5 ) ) { initial = 0 ; overflow = 0 ; n_steps = n_primary = syllables.Increments(start,end,MinStress) ; if ( n_steps > th->body_max_steps ) { n_steps = th->body_max_steps ; } ; if ( n_steps > 1 ) increment = pitch_range / (n_steps -1) ; else increment = 0 ; pitch = th->body_start << 8 ; } else { if ( n_steps > 0 ) pitch += increment ; else { pitch = (th->body_end << 8) + (pitch_range_abs * overflow_tab[overflow++]) /64 ; if ( overflow >= n_overflow ) { overflow = 0 ; overflow_tab = th->overflow ; } ; } ; } ; n_steps -- ; n_primary -- ; if ( ( tn->backwards ) && ( n_primary < 2 ) ) { pitch = tn->backwards[n_primary] << 8 ; } ; } ; ///////////////////////////////////////////////////////////////////// if ( stress >= PRIMARY ) { syllables[start]->Stress = PRIMARY_STRESSED ; syllables[start]->setPitch((pitch >> 8),drops[stress]) ; } else if ( stress >= SECONDARY ) { syllables[start]->setPitch((pitch >> 8),drops[stress]); } else { /* unstressed, drop pitch if preceded by PRIMARY */ if ( (syllables[start-1]->Stress & 0x3f) >= SECONDARY) { syllables[start]->setPitch ( (pitch >> 8) - th->body_lower_u , drops[stress] ) ; } else { syllables[start]->setPitch((pitch >> 8),drops[stress]) ; } ; } ; start++ ; } ; return start ; } //////////////////////////////////////////////////////////////////////// N::SpeechTune:: SpeechTune (void) : prehead_start (0 ) , prehead_end (0 ) , stressed_env (0 ) , stressed_drop (0 ) , secondary_drop (0 ) , unstressed_shape (0 ) , onset (0 ) , head_start (0 ) , head_end (0 ) , head_last (0 ) , head_max_steps (0 ) , n_head_extend (0 ) , nucleus0_env (0 ) , nucleus0_max (0 ) , nucleus0_min (0 ) , nucleus1_env (0 ) , nucleus1_max (0 ) , nucleus1_min (0 ) , tail_start (0 ) , tail_end (0 ) , split_nucleus_env (0 ) , split_nucleus_max (0 ) , split_nucleus_min (0 ) , split_tail_start (0 ) , split_tail_end (0 ) , split_tune (0 ) , spare2 (0 ) { memset(name ,0,sizeof(char)*12) ; memset(flags ,0,sizeof(char)* 4) ; memset(head_extend,0,sizeof(char)* 8) ; memset(unstr_start,0,sizeof(char)* 3) ; memset(unstr_end ,0,sizeof(char)* 3) ; memset(spare ,0,sizeof(char)* 8) ; } N::SpeechTune:: SpeechTune(const SpeechTune & tune) { assign ( tune ) ; } N::SpeechTune::~SpeechTune(void) { } N::SpeechTune & N::SpeechTune::operator = (const SpeechTune & tune) { return assign(tune) ; } N::SpeechTune & N::SpeechTune::assign(const SpeechTune & tune) { nMemberCopy ( tune , prehead_start ) ; nMemberCopy ( tune , prehead_end ) ; nMemberCopy ( tune , stressed_env ) ; nMemberCopy ( tune , stressed_drop ) ; nMemberCopy ( tune , secondary_drop ) ; nMemberCopy ( tune , unstressed_shape ) ; nMemberCopy ( tune , onset ) ; nMemberCopy ( tune , head_start ) ; nMemberCopy ( tune , head_end ) ; nMemberCopy ( tune , head_last ) ; nMemberCopy ( tune , head_max_steps ) ; nMemberCopy ( tune , n_head_extend ) ; nMemberCopy ( tune , nucleus0_env ) ; nMemberCopy ( tune , nucleus0_max ) ; nMemberCopy ( tune , nucleus0_min ) ; nMemberCopy ( tune , nucleus1_env ) ; nMemberCopy ( tune , nucleus1_max ) ; nMemberCopy ( tune , nucleus1_min ) ; nMemberCopy ( tune , tail_start ) ; nMemberCopy ( tune , tail_end ) ; nMemberCopy ( tune , split_nucleus_env ) ; nMemberCopy ( tune , split_nucleus_max ) ; nMemberCopy ( tune , split_nucleus_min ) ; nMemberCopy ( tune , split_tail_start ) ; nMemberCopy ( tune , split_tail_end ) ; nMemberCopy ( tune , split_tune ) ; nMemberCopy ( tune , spare2 ) ; ::memcpy(name ,tune.name ,sizeof(char)*12) ; ::memcpy(flags ,tune.flags ,sizeof(char)* 4) ; ::memcpy(head_extend,tune.head_extend,sizeof(char)* 8) ; ::memcpy(unstr_start,tune.unstr_start,sizeof(char)* 3) ; ::memcpy(unstr_end ,tune.unstr_end ,sizeof(char)* 3) ; ::memcpy(spare ,tune.spare ,sizeof(char)* 8) ; return ME ; } int N::SpeechTune::packetSize(void) { return sizeof(TUNE) ; } void N::SpeechTune::set(int index,QByteArray & data) { TUNE * tune = NULL ; char * d = (char *)data.data() ; tune = (TUNE *) ( d + index ) ; #define MemberCopy(o,m) m = o->m MemberCopy ( tune , prehead_start ) ; MemberCopy ( tune , prehead_end ) ; MemberCopy ( tune , stressed_env ) ; MemberCopy ( tune , stressed_drop ) ; MemberCopy ( tune , secondary_drop ) ; MemberCopy ( tune , unstressed_shape ) ; MemberCopy ( tune , onset ) ; MemberCopy ( tune , head_start ) ; MemberCopy ( tune , head_end ) ; MemberCopy ( tune , head_last ) ; MemberCopy ( tune , head_max_steps ) ; MemberCopy ( tune , n_head_extend ) ; MemberCopy ( tune , nucleus0_env ) ; MemberCopy ( tune , nucleus0_max ) ; MemberCopy ( tune , nucleus0_min ) ; MemberCopy ( tune , nucleus1_env ) ; MemberCopy ( tune , nucleus1_max ) ; MemberCopy ( tune , nucleus1_min ) ; MemberCopy ( tune , tail_start ) ; MemberCopy ( tune , tail_end ) ; MemberCopy ( tune , split_nucleus_env ) ; MemberCopy ( tune , split_nucleus_max ) ; MemberCopy ( tune , split_nucleus_min ) ; MemberCopy ( tune , split_tail_start ) ; MemberCopy ( tune , split_tail_end ) ; MemberCopy ( tune , split_tune ) ; MemberCopy ( tune , spare2 ) ; #undef MemberCopy ::memcpy(name ,tune->name ,sizeof(char)*12) ; ::memcpy(flags ,tune->flags ,sizeof(char)* 4) ; ::memcpy(head_extend,tune->head_extend,sizeof(char)* 8) ; ::memcpy(unstr_start,tune->unstr_start,sizeof(char)* 3) ; ::memcpy(unstr_end ,tune->unstr_end ,sizeof(char)* 3) ; ::memcpy(spare ,tune->spare ,sizeof(char)* 8) ; } int N::SpeechTune::Packet(QByteArray & data) { TUNE tune ; char * d = (char *)&tune ; #define MemberCopy(o,m) o.m = m MemberCopy ( tune , prehead_start ) ; MemberCopy ( tune , prehead_end ) ; MemberCopy ( tune , stressed_env ) ; MemberCopy ( tune , stressed_drop ) ; MemberCopy ( tune , secondary_drop ) ; MemberCopy ( tune , unstressed_shape ) ; MemberCopy ( tune , onset ) ; MemberCopy ( tune , head_start ) ; MemberCopy ( tune , head_end ) ; MemberCopy ( tune , head_last ) ; MemberCopy ( tune , head_max_steps ) ; MemberCopy ( tune , n_head_extend ) ; MemberCopy ( tune , nucleus0_env ) ; MemberCopy ( tune , nucleus0_max ) ; MemberCopy ( tune , nucleus0_min ) ; MemberCopy ( tune , nucleus1_env ) ; MemberCopy ( tune , nucleus1_max ) ; MemberCopy ( tune , nucleus1_min ) ; MemberCopy ( tune , tail_start ) ; MemberCopy ( tune , tail_end ) ; MemberCopy ( tune , split_nucleus_env ) ; MemberCopy ( tune , split_nucleus_max ) ; MemberCopy ( tune , split_nucleus_min ) ; MemberCopy ( tune , split_tail_start ) ; MemberCopy ( tune , split_tail_end ) ; MemberCopy ( tune , split_tune ) ; MemberCopy ( tune , spare2 ) ; #undef MemberCopy ::memcpy(tune.name ,name ,sizeof(char)*12) ; ::memcpy(tune.flags ,flags ,sizeof(char)* 4) ; ::memcpy(tune.head_extend,head_extend,sizeof(char)* 8) ; ::memcpy(tune.unstr_start,unstr_start,sizeof(char)* 3) ; ::memcpy(tune.unstr_end ,unstr_end ,sizeof(char)* 3) ; ::memcpy(tune.spare ,spare ,sizeof(char)* 8) ; data.append((const char *)d,sizeof(TUNE)) ; return sizeof(TUNE) ; } int N::SpeechTune::setHeadIntonation ( Syllables & syllables , int start , int end ) { int stress ; int ix ; int pitch = 0 ; int increment = 0 ; int n_steps = 0 ; int stage = 0 ; // onset, head, last int initial = 1 ; int overflow_ix = 0 ; int pitch_range = ( head_end - head_start ) << 8 ; int pitch_range_abs = ::abs ( pitch_range ) ; int * drops = drops_0 ; // this should be controled by tune->head_drops int n_unstressed = 0 ; int unstressed_ix = 0 ; int unstressed_inc ; int used_onset = 0 ; int head_final = end ; int secondary = 2 ; // 2 //////////////////////////////////////////////////////////////////////// if ( onset == 255 ) stage = 1 ; // no onset specified if ( head_last != 255 ) { // find the last primary stress in the body for ( ix = end - 1 ; ix >= start ; ix-- ) { if ( syllables[ix]->Stress >= 4 ) { head_final = ix ; break ; } ; } ; } ; //////////////////////////////////////////////////////////////////////// while ( start < end ) { stress = syllables[start]->Stress ; if ( initial || ( stress >= 4 ) ) { // a primary stress if ( ( initial ) || ( stress == 5 ) ) { initial = 0 ; overflow_ix = 0 ; if ( onset == 255 ) { n_steps = syllables.Increments(start,head_final,4) ; pitch = head_start << 8 ; } else { // a pitch has been specified for the onset syllable, don't include it in the pitch incrementing n_steps = syllables.Increments(start+1,head_final,4) ; pitch = onset << 8 ; used_onset = 1 ; } ; if ( n_steps > head_max_steps) n_steps = head_max_steps ; if ( n_steps > 1 ) { increment = pitch_range / ( n_steps - 1 ) ; } else increment = 0 ; } else if ( start == head_final ) { // a pitch has been specified for the last primary stress before the nucleus pitch = head_last << 8 ; stage = 2 ; } else { if ( used_onset ) { stage = 1 ; used_onset = 0 ; pitch = head_start << 8 ; n_steps++ ; } else if ( n_steps > 0 ) pitch += increment ; else { pitch = (head_end << 8) + (pitch_range_abs * head_extend[overflow_ix++]) / 64 ; if ( overflow_ix >= n_head_extend ) overflow_ix = 0 ; } ; } ; n_steps-- ; } ; if ( stress >= PRIMARY ) { n_unstressed = syllables.Unstressed(start+1,end,secondary) ; unstressed_ix = 0 ; syllables[start]->Stress = PRIMARY_STRESSED ; syllables[start]->Envelope = stressed_env ; syllables[start]->setPitch ( ( pitch >> 8 ) , stressed_drop ) ; } else if ( stress >= secondary ) { n_unstressed = syllables.Unstressed(start,end,secondary) ; unstressed_ix = 0 ; syllables[start]->setPitch( (pitch >> 8) , drops[stress] ) ; } else { if(n_unstressed > 1) { unstressed_inc = ( unstr_end[stage] - unstr_start[stage]) / ( n_unstressed - 1 ) ; } else unstressed_inc = 0 ; syllables[start]->setPitch ( (pitch >> 8) + unstr_start[stage] + (unstressed_inc * unstressed_ix) , drops[stress] ) ; unstressed_ix++ ; } ; start++ ; } ; return start ; } int N::SpeechTune::Pitches(Syllables & syllables,int start,int end,int toneflags) // Calculate pitch values for the vowels in this tone group { int ix = start ; int prev = syllables.Previous ; int drop ; /* vowels before the first primary stress */ syllables.setPitchGradient(ix,ix+prev,prehead_start,prehead_end) ; ix += prev ; /* body of tonic segment */ if ( toneflags & OPTION_EMPHASIZE_PENULTIMATE ) { syllables.TonePosition = syllables.TonePosition2 ; // put tone on the penultimate stressed word } ; ix = setHeadIntonation(syllables,ix,syllables.TonePosition) ; if (syllables.NoTonic) return 0 ; if (syllables.Tail == 0) { syllables.PitchEnvelope = nucleus0_env ; drop = nucleus0_max - nucleus0_min ; syllables[ix++]->setPitch(nucleus0_min,drop) ; } else { syllables.PitchEnvelope = nucleus1_env ; drop = nucleus1_max - nucleus1_min ; syllables[ix++]->setPitch(nucleus1_min,drop) ; } ; syllables[syllables.TonePosition]->Envelope = syllables.PitchEnvelope ; if (syllables[syllables.TonePosition]->Stress == PRIMARY) { syllables[syllables.TonePosition]->Stress = PRIMARY_STRESSED ; } ; /* tail, after the tonic syllable */ syllables.setPitchGradient(ix,end,tail_start,tail_end) ; return syllables.PitchEnvelope ; } int N::SpeechTune::Pitches(Syllables & syllables,int start,int end,int control,int index,int toneflags) { int ix ; TONE_HEAD * th ; TONE_NUCLEUS * tn ; int drop ; int continuing = 0 ; ////////////////////////////////////////////////////////////////////// if ( control == 0 ) return Pitches (syllables,start,end,toneflags) ; if ( start > 0 ) continuing = 1 ; th = &tone_head_table [ index ] ; tn = &tone_nucleus_table [ index ] ; ix = start ; /* vowels before the first primary stress */ syllables.setPitchGradient(ix ,ix+syllables.Previous , th->pre_start,th->pre_end ) ; ix += syllables.Previous ; /* body of tonic segment */ if ( toneflags & OPTION_EMPHASIZE_PENULTIMATE ) { // put tone on the penultimate stressed word syllables.TonePosition = syllables.TonePosition2 ; } ; ix = PitchSegment ( syllables , ix , syllables.TonePosition , th , tn , PRIMARY , continuing ) ; if (syllables.NoTonic) return 0 ; /* tonic syllable */ if ( tn->flags & T_EMPH ) { syllables[ix]->Flags |= SYL_EMPHASIS ; } ; if ( syllables.Tail == 0 ) { syllables.PitchEnvelope = tn->pitch_env0 ; drop = tn->tonic_max0 - tn->tonic_min0 ; syllables[ix]->setPitch(tn->tonic_min0,drop) ; ix++ ; } else { syllables.PitchEnvelope = tn->pitch_env1 ; drop = tn->tonic_max1 - tn->tonic_min1 ; syllables[ix]->setPitch(tn->tonic_min1,drop) ; ix++ ; } ; ////////////////////////////////////////////////////////////////////// syllables[syllables.TonePosition]->Envelope = syllables.PitchEnvelope ; if (syllables[syllables.TonePosition]->Stress == PRIMARY) { syllables[syllables.TonePosition]->Stress = PRIMARY_STRESSED ; } ; /* tail, after the tonic syllable */ syllables.setPitchGradient(ix,end,tn->tail_start,tn->tail_end) ; return syllables.PitchEnvelope ; } void N::SpeechTune::report(void) { printf("Name = %s\n",name) ; #define R(item) printf(#item " = %d\n",item) R ( prehead_start ) ; R ( prehead_end ) ; R ( stressed_env ) ; R ( stressed_drop ) ; R ( secondary_drop ) ; R ( unstressed_shape ) ; R ( onset ) ; R ( head_start ) ; R ( head_end ) ; R ( head_last ) ; R ( head_max_steps ) ; R ( n_head_extend ) ; R ( nucleus0_env ) ; R ( nucleus0_max ) ; R ( nucleus0_min ) ; R ( nucleus1_env ) ; R ( nucleus1_max ) ; R ( nucleus1_min ) ; R ( tail_start ) ; R ( tail_end ) ; R ( split_nucleus_env ) ; R ( split_nucleus_max ) ; R ( split_nucleus_min ) ; R ( split_tail_start ) ; R ( split_tail_end ) ; R ( split_tune ) ; R ( spare2 ) ; #undef R #define R(item,total) \ printf(#item " = ") ; \ for (int i=0;i<total;i++) { \ printf("[%d]",item[i]) ; \ } ; \ printf("\n") R(flags ,4) ; R(head_extend,8) ; R(unstr_start,3) ; R(unstr_end ,3) ; R(spare ,8) ; #undef R }
53.853583
122
0.37398
Vladimir-Lin
c357b32535eb58b0741bde301a38f6e29ed2125f
405
hpp
C++
include/Nen/Component/CircleComponent.hpp
Astomih/NenEngine
669fcbaa7a26cbdeb764315d8c9c17370075611e
[ "MIT" ]
2
2021-03-16T15:59:41.000Z
2021-12-01T12:30:30.000Z
include/Nen/Component/CircleComponent.hpp
Astomih/NenEngine
669fcbaa7a26cbdeb764315d8c9c17370075611e
[ "MIT" ]
1
2021-09-05T05:08:48.000Z
2021-09-05T05:08:48.000Z
include/Nen/Component/CircleComponent.hpp
Astomih/NenEngine
669fcbaa7a26cbdeb764315d8c9c17370075611e
[ "MIT" ]
null
null
null
#pragma once #include "Component.hpp" namespace nen { class circle_component : public base_component { public: circle_component(class base_actor &owner); void SetRadius(float radius) noexcept { mRadius = radius; } vector3 GetRadius() const; const vector3 &GetCenter() const; bool Intersect(const circle_component &a, const circle_component &b); private: float mRadius; }; } // namespace nen
23.823529
71
0.750617
Astomih
c35a7d175749453b2ba1a1d63890b00162cd038e
628
hpp
C++
src/gameworld/gameworld/scene/speciallogic/personspecial/specialfbguide.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/gameworld/gameworld/scene/speciallogic/personspecial/specialfbguide.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/gameworld/gameworld/scene/speciallogic/personspecial/specialfbguide.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#ifndef __SPECIAL_FB_GUIDE_H__ #define __SPECIAL_FB_GUIDE_H__ #include "scene/speciallogic/speciallogic.hpp" #include "other/fb/fbguideconfig.hpp" #include "protocal/msgfb.h" class SpecialFbGuide: public SpecialLogic { public: SpecialFbGuide(Scene *scene); virtual ~SpecialFbGuide(); virtual void OnRoleLeaveScene(Role *role, bool is_logout); void OnFinish(Role *role, int monster_x, int monster_y, int monster_id); void OnCreateGather(Role *role, int gather_x, int gather_y, int gather_id, int gather_time); void SetObjPos(Role * role, Protocol::CSFunOpenSetObjToPos *cmd); protected: bool m_is_finish; }; #endif
25.12
93
0.786624
mage-game
c35e73449277aad3de3b3112624f0b1b0d26a4ae
13,811
cc
C++
lite/kernels/opencl/conv2d_1x1_compute_test.cc
ishine/paddle-mobile
04565a67d4acce39ceccf4131e364762f75a2b87
[ "Apache-2.0" ]
null
null
null
lite/kernels/opencl/conv2d_1x1_compute_test.cc
ishine/paddle-mobile
04565a67d4acce39ceccf4131e364762f75a2b87
[ "Apache-2.0" ]
null
null
null
lite/kernels/opencl/conv2d_1x1_compute_test.cc
ishine/paddle-mobile
04565a67d4acce39ceccf4131e364762f75a2b87
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <random> #include "lite/backends/opencl/cl_image_converter.h" #include "lite/backends/opencl/target_wrapper.h" #include "lite/core/op_registry.h" #include "lite/core/tensor.h" namespace paddle { namespace lite { template <typename Dtype1, typename Dtype2> static void conv_basic(const Dtype1* din, Dtype2* dout, int num, int chout, int hout, int wout, int chin, int hin, int win, const Dtype1* weights, const Dtype2* bias, int group, int kernel_w, int kernel_h, int stride_w, int stride_h, int dila_w, int dila_h, int pad_w, int pad_h, bool flag_bias, bool flag_relu) { Dtype2 beta = 0; auto src_data = din; auto dst_data_ref = dout; auto weights_data = weights; auto with_bias = flag_bias; auto bias_data = bias; int in_num = num; int out_channels = chout; int out_h = hout; int out_w = wout; int in_channel = chin; int in_h = hin; int in_w = win; int out_c_group = out_channels / group; int in_c_group = in_channel / group; for (int n = 0; n < in_num; ++n) { for (int g = 0; g < group; ++g) { for (int oc = 0; oc < out_c_group; ++oc) { for (int oh = 0; oh < out_h; ++oh) { for (int ow = 0; ow < out_w; ++ow) { int out_idx = n * group * out_c_group * out_h * out_w + g * out_c_group * out_h * out_w + oc * out_h * out_w + oh * out_w + ow; Dtype2 bias_d = with_bias ? (bias_data[g * out_c_group + oc]) : (Dtype2)0; dst_data_ref[out_idx] = bias_d; // + dst_data_ref[out_idx] * beta; for (int ic = 0; ic < in_c_group; ++ic) { for (int kh = 0; kh < kernel_h; ++kh) { for (int kw = 0; kw < kernel_w; ++kw) { int iw = ow * stride_w - pad_w + kw * (dila_w); int ih = oh * stride_h - pad_h + kh * (dila_h); if (iw < 0 || iw >= in_w) continue; if (ih < 0 || ih >= in_h) continue; int iidx = n * in_channel * in_h * in_w + g * in_c_group * in_h * in_w + ic * in_h * in_w + ih * in_w + iw; int widx = g * out_c_group * in_c_group * kernel_h * kernel_w + oc * in_c_group * kernel_h * kernel_w + ic * kernel_h * kernel_w + kh * kernel_w + kw; dst_data_ref[out_idx] += src_data[iidx] * weights_data[widx]; } } } if (flag_relu) { dst_data_ref[out_idx] = dst_data_ref[out_idx] > (Dtype2)0 ? dst_data_ref[out_idx] : (Dtype2)0; } } } } } } } TEST(conv2d_1x1, compute) { // conv infos const int ksize = 1; const int stride = 1; const int pad = 0; const int group = 1; const int dilation = 0; // int loop_cnt = 0; const bool bias_flag = true; const bool relu_flag = true; const int batch_size = 8; const int oc = 64; const int ih = 28; const int iw = 28; const int ic = 63; const int oh = ih; const int ow = iw; LOG(INFO) << "to get kernel ..."; auto kernels = KernelRegistry::Global().Create("conv2d_1x1", TARGET(kOpenCL), PRECISION(kFloat), DATALAYOUT(kImageDefault)); ASSERT_FALSE(kernels.empty()); auto kernel = std::move(kernels.front()); LOG(INFO) << "created conv2d_1x1 kernel"; LOG(INFO) << "prepare kernel ------"; lite::Tensor input, filter, bias, output; operators::ConvParam param; param.x = &input; param.filter = &filter; param.output = &output; if (bias_flag) { param.bias = &bias; } param.fuse_relu = relu_flag; std::vector<int> paddings = {pad, pad, pad, pad}; std::vector<int> dilations = {dilation, dilation}; param.paddings = std::make_shared<std::vector<int>>(paddings); param.dilations = std::make_shared<std::vector<int>>(dilations); param.strides = std::vector<int>{stride, stride}; std::unique_ptr<KernelContext> context(new KernelContext); context->As<OpenCLContext>().InitOnce(); std::unique_ptr<KernelContext> conv_1x1_context(new KernelContext); context->As<OpenCLContext>().CopySharedTo( &(conv_1x1_context->As<OpenCLContext>())); kernel->SetContext(std::move(conv_1x1_context)); const DDim& input_dim = lite::DDim{std::vector<int64_t>({batch_size, ic, ih, iw})}; const DDim& filter_dim = lite::DDim{std::vector<int64_t>({oc, ic, ksize, ksize})}; const DDim& out_dim = lite::DDim{std::vector<int64_t>({batch_size, oc, ih, iw})}; // element wise bias const DDim& bias_dim = lite::DDim{std::vector<int64_t>({oc})}; param.x->Resize(input_dim); param.filter->Resize(filter_dim); param.output->Resize(out_dim); if (bias_flag) { param.bias->Resize(bias_dim); } kernel->SetParam(param); size_t input_image_width = iw * ((ic + 3) / 4); size_t input_image_height = ih * batch_size; size_t out_image_width = ow * ((oc + 3) / 4); size_t out_image_height = oh * batch_size; size_t bias_image_width = ow * ((oc + 3) / 4); size_t bias_image_height = oh * batch_size; size_t filter_image_width = ksize * ((oc + 3) / 4); size_t filter_image_height = ic * ksize; auto* input_data = input.mutable_data<float, cl::Image2D>(input_image_width, input_image_height); auto* filter_data = filter.mutable_data<float, cl::Image2D>( filter_image_width, filter_image_height); bias.mutable_data<float, cl::Image2D>(bias_image_width, bias_image_height); auto* bias_data = bias.mutable_data<float, cl::Image2D>(bias_image_width, bias_image_height); const size_t cl_image2d_row_pitch{0}; const size_t cl_image2d_slice_pitch{0}; LOG(INFO) << "map input ..."; auto* mapped_input = static_cast<float*>(TargetWrapperCL::MapImage(input_data, input_image_width, input_image_height, cl_image2d_row_pitch, cl_image2d_slice_pitch)); LOG(INFO) << "map filter ..."; auto* mapped_filter = static_cast<float*>(TargetWrapperCL::MapImage(filter_data, filter_image_width, filter_image_height, cl_image2d_row_pitch, cl_image2d_slice_pitch)); std::default_random_engine engine; std::uniform_real_distribution<float> gen(-5, 5); std::vector<float> input_v(batch_size * ic * ih * iw); std::vector<float> filter_v(oc * ic * ksize * ksize); std::vector<float> output_v(batch_size * oc * ih * iw); std::vector<float> bias_v(oc); float* input_v_data = &input_v[0]; float* filter_v_data = &filter_v[0]; float* output_v_data = &output_v[0]; float* bias_v_data = &bias_v[0]; LOG(INFO) << "gen input and filter ..."; for (auto& i : input_v) { i = gen(engine); } for (auto& f : filter_v) { f = gen(engine); } LOG(INFO) << "after gen input and filter ..."; LOG(INFO) << "input_v.size(): " << input_v.size(); LOG(INFO) << "filter_v.size(): " << filter_v.size(); LOG(INFO) << "output_v.size(): " << output_v.size(); LOG(INFO) << "bias_v.size(): " << bias_v.size(); LOG(INFO) << "input_dim.production(): " << input_dim.production(); LOG(INFO) << "filter_dim.production(): " << filter_dim.production(); LOG(INFO) << "out_dim.production(): " << out_dim.production(); LOG(INFO) << "bias_dim.production(): " << bias_dim.production(); LOG(INFO) << "4 * input_image_height * input_image_width: " << 4 * input_image_height * input_image_width; LOG(INFO) << "4 * filter_image_width * filter_image_height: " << 4 * filter_image_width * filter_image_height; CHECK(input_dim.production() == input_v.size()); CHECK_LE(input_dim.production(), 4 * input_image_height * input_image_width); CHECK(filter_dim.production() == filter_v.size()); CHECK_LE(filter_dim.production(), 4 * filter_image_width * filter_image_height); paddle::lite::CLImageConverterDefault default_convertor; LOG(INFO) << "set mapped input ..."; default_convertor.NCHWToImage(input_v_data, mapped_input, input_dim); LOG(INFO) << "set mapped filter ..."; paddle::lite::CLImageConverterNWBlock nw_convertor; nw_convertor.NCHWToImage(filter_v_data, mapped_filter, filter_dim); LOG(INFO) << "resize output ..."; output.Resize(out_dim); // cpu conv basic calc lite::Tensor out_ref; out_ref.Resize(out_dim); float* mapped_bias = nullptr; if (bias_flag) { mapped_bias = static_cast<float*>(TargetWrapperCL::MapImage(bias_data, bias_image_width, bias_image_height, cl_image2d_row_pitch, cl_image2d_slice_pitch)); for (int i = 0; i < bias_dim.production(); ++i) { bias_v[i] = static_cast<int>(gen(engine)); } CLImageConverterFolder folder_convertor; folder_convertor.NCHWToImage(bias_v_data, mapped_bias, bias_dim); } LOG(INFO) << "prepare kernel ready"; LOG(INFO) << "kernel launch ..."; kernel->Launch(); LOG(INFO) << "mutable output ..."; auto* output_data = output.mutable_data<float, cl::Image2D>(out_image_width, out_image_height); auto* wait_list = context->As<OpenCLContext>().cl_wait_list(); auto* out_ptr = param.output->data<float, cl::Image2D>(); auto it = wait_list->find(out_ptr); if (it != wait_list->end()) { VLOG(4) << "--- Find the sync event for the target cl tensor. ---"; auto& event = *(it->second); event.wait(); } else { LOG(FATAL) << "Could not find the sync event for the target cl tensor."; } auto* mapped_output = static_cast<float*>(TargetWrapperCL::MapImage(output_data, out_image_width, out_image_height, cl_image2d_row_pitch, cl_image2d_slice_pitch)); LOG(INFO) << "mutable_data out_ref_data: "; // run cpu ref auto* out_ref_data = out_ref.mutable_data<float>(TARGET(kARM)); LOG(INFO) << " conv_basic beigin ..... "; conv_basic<float, float>(input_v_data, out_ref_data, batch_size, oc, oh, ow, ic, ih, iw, filter_v_data, bias_v_data, // mapped_bias, group, ksize, ksize, stride, stride, dilation, dilation, pad, pad, bias_flag, relu_flag); LOG(INFO) << " conv_basic end ..... "; LOG(INFO) << " out_dim: " << out_dim; const DDim& out_image_dims = lite::DDim{ std::vector<int64_t>({static_cast<int64_t>(out_image_width), static_cast<int64_t>(out_image_height)})}; default_convertor.ImageToNCHW( mapped_output, output_v_data, out_image_dims, out_dim); for (int i = 0; i < out_dim.production(); i++) { EXPECT_NEAR(output_v_data[i], out_ref_data[i], 1e-3); if (abs(output_v_data[i] - out_ref_data[i]) > 1e-3) { LOG(FATAL) << "error idx:" << i; } } TargetWrapperCL::Unmap(output_data, mapped_output); TargetWrapperCL::Unmap(filter_data, mapped_filter); TargetWrapperCL::Unmap(input_data, mapped_input); if (bias_flag) { if (mapped_bias) { TargetWrapperCL::Unmap(bias_data, mapped_bias); } } } } // namespace lite } // namespace paddle USE_LITE_KERNEL(conv2d_1x1, kOpenCL, kFloat, kImageDefault, image2d);
36.440633
80
0.539932
ishine
c35fcbba7224c1026c2211ce692fcda966eac0dc
4,066
cpp
C++
src/3rdparty/khtml/src/svg/graphics/qt/SVGResourceClipperQt.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
src/3rdparty/khtml/src/svg/graphics/qt/SVGResourceClipperQt.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
src/3rdparty/khtml/src/svg/graphics/qt/SVGResourceClipperQt.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2004, 2005, 2006 Nikolas Zimmermann <wildfox@kde.org> 2004, 2005, 2006 Rob Buis <buis@kde.org> 2005 Apple Computer, Inc. This file is part of the KDE project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License aint with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "wtf/Platform.h" #if ENABLE(SVG) #include "SVGResourceClipper.h" /*#include "GraphicsContext.h"*/ #include <QPainter> #include <QPainterPath> #include "FloatRect.h" namespace WebCore { void SVGResourceClipper::applyClip(/*GraphicsContext* context*/QPainter *painter, const FloatRect &boundingBox) const { if (m_clipData.clipData().size() < 1) { return; } /*context->beginPath();*/ QPainterPath newPath; WindRule clipRule = m_clipData.clipData()[0].windRule; unsigned int clipDataCount = m_clipData.clipData().size(); for (unsigned int x = 0; x < clipDataCount; x++) { ClipData clipData = m_clipData.clipData()[x]; QPainterPath path = *(clipData.path.platformPath()); if (path.isEmpty()) { continue; } if (!newPath.isEmpty()) { newPath.closeSubpath(); } // Respect clipping units... QMatrix transform; if (clipData.bboxUnits) { transform.translate(boundingBox.x(), boundingBox.y()); transform.scale(boundingBox.width(), boundingBox.height()); } // TODO: support heterogenous clip rules! //clipRule = (clipData.windRule() == RULE_EVENODD ? Qt::OddEvenFill : Qt::WindingFill); for (int i = 0; i < path.elementCount(); ++i) { const QPainterPath::Element &cur = path.elementAt(i); switch (cur.type) { case QPainterPath::MoveToElement: newPath.moveTo(QPointF(cur.x, cur.y) * transform); break; case QPainterPath::LineToElement: newPath.lineTo(QPointF(cur.x, cur.y) * transform); break; case QPainterPath::CurveToElement: { const QPainterPath::Element &c1 = path.elementAt(i + 1); const QPainterPath::Element &c2 = path.elementAt(i + 2); Q_ASSERT(c1.type == QPainterPath::CurveToDataElement); Q_ASSERT(c2.type == QPainterPath::CurveToDataElement); newPath.cubicTo(QPointF(cur.x, cur.y) * transform, QPointF(c1.x, c1.y) * transform, QPointF(c2.x, c2.y) * transform); i += 2; break; } case QPainterPath::CurveToDataElement: Q_ASSERT(false); break; } } } if (m_clipData.clipData().size()) { // FIXME! // We don't currently allow for heterogenous clip rules. // we would have to detect such, draw to a mask, and then clip // to that mask // if (!CGContextIsPathEmpty(cgContext)) { if (clipRule == RULE_EVENODD) { newPath.setFillRule(Qt::OddEvenFill); } else { newPath.setFillRule(Qt::WindingFill); } // } } /*QPainter* painter(context ? context->platformContext() : 0); Q_ASSERT(painter);*/ painter->setClipPath(newPath); } } // namespace WebCore #endif
31.276923
117
0.597147
afarcat
c363de7be63ea5a8b59ec8d1d468458348f1d8ba
506
hpp
C++
Core/src/Readers/nexus.hpp
vais-ral/CCPi-Reconstruction
6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd
[ "Apache-2.0" ]
1
2018-11-09T11:58:32.000Z
2018-11-09T11:58:32.000Z
Core/src/Readers/nexus.hpp
vais-ral/CCPi-Reconstruction
6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd
[ "Apache-2.0" ]
8
2018-05-22T12:58:27.000Z
2020-10-15T14:54:04.000Z
Core/src/Readers/nexus.hpp
vais-ral/CCPi-Reconstruction
6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd
[ "Apache-2.0" ]
1
2019-01-11T12:04:53.000Z
2019-01-11T12:04:53.000Z
#ifndef CCPI_RECON_NEXUS #define CCPI_RECON_NEXUS namespace CCPi { bool read_NeXus(pixel_data &pixels, pixel_2d &i_dark, pixel_2d &f_dark, pixel_2d &i_bright, pixel_2d &f_bright, int &nh_pixels, int &nv_pixels, std::vector<real> &angles, int &nangles, real &hsize, real &vsize, const std::string filename, const bool all_angles, const bool read_data, const int start_idx, const int block_size, const int v_shift); // Todo - write NeXus NXtomoproc? } #endif // CCPI_RECON_NEXUS
28.111111
73
0.735178
vais-ral
c364effde5518012cc87a4ae2f0bbc33fa3e385f
32,762
cpp
C++
applications/plugins/LeapMotion/src/LeapMotionDriver.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/LeapMotion/src/LeapMotionDriver.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/LeapMotion/src/LeapMotionDriver.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "LeapMotionDriver.h" #ifdef SOFA_HAVE_BOOST #include <boost/thread/thread.hpp> #endif #include <SofaBaseVisual/VisualTransform.h> #include <sofa/core/objectmodel/KeypressedEvent.h> #include <sofa/core/objectmodel/MouseEvent.h> namespace sofa { namespace component { namespace controller { #define SCROLL_DIRECTION_THRESHOLD 0.5 #define SWIPE_MIN_VELOCITY 500 #define SWIPE_MAX_VELOCITY 6000 #define PINCH_DISTANCE_THRESHOLD 40 // a pinch will be detected if the distance between two fingers is smaller than this thresold #define PINCH_DOTPRODUCT_THRESHOLD 0.8 int32_t fingersIdsArray[5] = {-1,-1,-1,-1,-1}; LeapMotionDriver::LeapMotionDriver() : scale(initData(&scale, 1.0, "scale","Default scale applied to the Leap Motion Coordinates. ")) , translation(initData(&translation, Vec3d(0,0,0), "translation","Position of the tool/hand in the Leap Motion reference frame")) , rotation(initData(&rotation, sofa::defaulttype::Vector3(), "rotation", "Rotation of the DOFs of the hand")) , handPalmCoordinate(initData(&handPalmCoordinate, "handPalmCoordinate","Coordinate of the hand detected by the Leap Motion")) , sphereCenter(initData(&sphereCenter, "sphereCenter","Center of the sphere of the hand detected by the Leap Motion")) , sphereRadius(initData(&sphereRadius, "sphereRadius","Radius of the sphere of the hand detected by the Leap Motion")) , fingersCoordinates(initData(&fingersCoordinates, sofa::helper::vector<Rigid3dTypes::Coord>(1,Rigid3dTypes::Coord(sofa::defaulttype::Vector3(0,0,0),Quat(0,0,0,1))), "fingersCoordinates","Coordinate of the fingers detected by the Leap Motion")) , gestureType(initData(&gestureType, int(-1) ,"gestureType","Type of the current gesture detected by the Leap Motion")) , gesturePosition(initData(&gesturePosition, "gesturePosition","Position of the current gesture detected by the Leap Motion")) , gestureDirection(initData(&gestureDirection, "gestureDirection","Direction of the current gesture detected by the Leap Motion")) , scrollDirection(initData (&scrollDirection, int(0), "scrollDirection", "Enter 0 if no scrolling (1 if scoll increases the value, 2 if scroll decreases it)")) , displayHand(initData (&displayHand, false, "displayHand", "display the hand detected by the Leap Motion")) { this->f_listening.setValue(true); slideDisplayDuration = sofa::helper::system::thread::CTime::getTime(); } LeapMotionDriver::~LeapMotionDriver() { // Remove the sample listener when done if (leapConnected) { getLeapController()->removeListener(myListener); } } void LeapMotionDriver::cleanup() { sout << "LeapMotionDriver::cleanup()" << sendl; } void LeapMotionDriver::init() { bool leapEnabled = true; leapConnected = false; if (leapEnabled) { std::cout << "[LeapMotion] Connecting"; for (unsigned int n=0; n<15 && !leapConnected; n++) { std::cout << "."; sofa::helper::system::thread::CTime::sleep(0.1); leapConnected = getLeapController()->isConnected(); } std::cout << "." << std::endl; } if (leapConnected) { leapConfig = getLeapController()->config(); leapConfig.setFloat("Gesture.ScreenTap.MinForwardVelocity",50); leapConfig.setFloat("Gesture.ScreenTap.HistorySeconds",0.1); leapConfig.setFloat("Gesture.ScreenTap.MinDistance",3.0); leapConfig.setFloat("Gesture.KeyTap.MinDownVelocity",10); leapConfig.setFloat("Gesture.KeyTap.HistorySeconds",0.1); leapConfig.setFloat("Gesture.KeyTap.MinDistance",5.0); leapConfig.setFloat("Gesture.Swipe.MinLength",120); leapConfig.setFloat("Gesture.Swipe.MinVelocity",SWIPE_MIN_VELOCITY); leapConfig.setFloat("Gesture.Circle.MinArc", 2*M_PI); leapConfig.setFloat("Gesture.Circle.MinRadius", 25.0); leapConfig.save(); getLeapController()->addListener(myListener); drawInteractionBox = false; } else if (leapEnabled) serr << "Device not detected" << sendl; //initialisation of the fingers coordinates array helper::WriteAccessor<Data<sofa::helper::vector<RigidCoord<3,double> > > > fingerCoords = fingersCoordinates; for (int i=0; i<14; i++) fingerCoords.push_back(fingerCoords[i]); scrollDirection.setValue(0); lastGestureType = TYPE_SWIPE; for (int i=0; i<TYPES_COUNT; i++) { lastGesturesFrameIds.push_back(std::make_pair(i,0)); } lastGestureFrameId = 0; } void LeapMotionDriver::bwdInit() { sout<<"LeapMotionDriver::bwdInit()"<<sendl; } void LeapMotionDriver::reset() { sout<<"LeapMotionDriver::reset()" << sendl; scrollDirection.setValue(0); this->reinit(); } void LeapMotionDriver::reinitVisual() {} void LeapMotionDriver::reinit() { this->bwdInit(); this->reinitVisual(); } Vec3d LeapMotionDriver::verticeOnRadius(Vec3d center, Vec3d vecOnCirclePlane, Vec3d orthoVecOnCirclePlane, double radius, double radAngle) { vecOnCirclePlane.normalize(); orthoVecOnCirclePlane.normalize(); return Vec3d(center + radius*(vecOnCirclePlane*cos(radAngle) + orthoVecOnCirclePlane*sin(radAngle))); } void LeapMotionDriver::computeFingerJoints(int i, helper::WriteAccessor<Data<sofa::helper::vector<RigidCoord<3,double> > > >* fingersCoordsArray ) { //palm normal Mat3x3d palmMatrix; handPalmCoordinate.getValue().writeRotationMatrix(palmMatrix); Vec3d palmDirection = -Vec3d(palmMatrix.col(0)); palmDirection.normalize(); Vec3d palmNormal = -Vec3d(palmMatrix.col(2)); palmNormal.normalize(); //\\Projections\\// Vec3d v = fingersCoordinates.getValue()[3*i].getCenter() - handPalmCoordinate.getValue().getCenter(); //fingerTip projection into vertical palm plane double dist = dot(v,palmDirection); //Vec3d v_proj_point = fingersCoordinates.getValue()[3*i].getCenter() - dist*palmDirection; //fingerTip projection into horizontal palm plane dist = dot(v,palmNormal); Vec3d h_proj_point = fingersCoordinates.getValue()[3*i].getCenter() - dist*palmNormal; //metacarpophalangeal joint Vec3d palmToTipProjectionDirection = handPalmCoordinate.getValue().getCenter() - h_proj_point; palmToTipProjectionDirection.normalize(); Quat McpQuat = Quat().createQuaterFromFrame(palmNormal, palmToTipProjectionDirection.cross(palmNormal),palmToTipProjectionDirection); Rigid3dTypes::Coord Mcp = Rigid3dTypes::Coord(handPalmCoordinate.getValue().getCenter() - palmToTipProjectionDirection.mulscalar(30*scale.getValue()), McpQuat); (*fingersCoordsArray)[3*i+1] = Mcp; //proximal interphalangial joint double pipAngleCorrection = (h_proj_point - fingersCoordinates.getValue()[3*i].getCenter()).norm()/scale.getValue()/100.0; if(dist > 0) {pipAngleCorrection = -2*pipAngleCorrection;} Vec3d pipPos = verticeOnRadius(Mcp.getCenter(),Vec3d(palmMatrix.col(2)),(handPalmCoordinate.getValue().getCenter()-Mcp.getCenter()),(Mcp.getCenter()-fingersCoordinates.getValue()[3*i].getCenter()).norm()/2.2 ,1.5*M_PI+pipAngleCorrection); (*fingersCoordsArray)[3*i+2] = Rigid3dTypes::Coord(pipPos, McpQuat); } void LeapMotionDriver::draw(const sofa::core::visual::VisualParams* vparams) { if (!vparams->displayFlags().getShowVisualModels()) return; if(displayHand.getValue()) { helper::gl::GlText text; //text.setText("SLICE"); //text.update(Vector3(myListener.getStabilizedPalmPosition().toFloatPointer()).mulscalar(scale.getValue())); //text.update(0.0005); text.draw(); if(leapConnected && drawInteractionBox ) { Vec3d interactionBoxParallelepipedVecs[5]; Vec3d leapInteractionBoxCenter = Vec3d(myListener.getInteractionBox().center().toFloatPointer()); double halfWidth = myListener.getInteractionBox().width()/2.0; double halfHeight = myListener.getInteractionBox().height()/2.0; double halfDepth = myListener.getInteractionBox().depth()/2.0; interactionBoxParallelepipedVecs[0] = Vec3d(leapInteractionBoxCenter.x()-halfWidth, leapInteractionBoxCenter.y() - halfHeight, leapInteractionBoxCenter.z() - halfDepth); interactionBoxParallelepipedVecs[1] = Vec3d(leapInteractionBoxCenter.x()-halfWidth, leapInteractionBoxCenter.y() - halfHeight, leapInteractionBoxCenter.z() + halfDepth); interactionBoxParallelepipedVecs[2] = Vec3d(leapInteractionBoxCenter.x()-halfWidth, leapInteractionBoxCenter.y() + halfHeight, leapInteractionBoxCenter.z() + halfDepth); interactionBoxParallelepipedVecs[3] = Vec3d(leapInteractionBoxCenter.x()-halfWidth, leapInteractionBoxCenter.y() + halfHeight, leapInteractionBoxCenter.z() - halfDepth); interactionBoxParallelepipedVecs[4] = Vec3d(2.0*halfWidth, 0.0, 0.0); Quat q = Quat().createQuaterFromEuler(rotation.getValue().mulscalar(M_PI / 180.0)); for(int i=0; i<5; i++) { interactionBoxParallelepipedVecs[i] = q.rotate(interactionBoxParallelepipedVecs[i].mulscalar(scale.getValue())); interactionBoxParallelepipedVecs[i] += translation.getValue(); } ///FIXME: draw // helper::gl::drawEmptyParallelepiped(interactionBoxParallelepipedVecs[0],interactionBoxParallelepipedVecs[1],interactionBoxParallelepipedVecs[2],interactionBoxParallelepipedVecs[3],interactionBoxParallelepipedVecs[4],1.25*scale.getValue()); } if (leapConnected) { float coordMatrix[16]; //draw palm as a torus handPalmCoordinate.getValue().writeOpenGlMatrix(coordMatrix); helper::gl::drawTorus( coordMatrix, 2.5*scale.getValue(), 28*scale.getValue(), 30, Vec3i(255,215,180) ); //helper::gl::drawTorus( coordMatrix, 2.5*scale.getValue(), 23*scale.getValue(), 30, Vec3i(255,215,180) ); //helper::gl::drawTorus( coordMatrix, 4*scale.getValue(), 16.5*scale.getValue(), 30, Vec3i(255,215,180) ); //helper::gl::drawTorus( coordMatrix, 4*scale.getValue(), 8.5*scale.getValue(), 30, Vec3i(255,215,180) ); //draw palm Normal as a cylinder //Mat3x3d palmMatrix; //handPalmCoordinate.getValue().writeRotationMatrix(palmMatrix); //Vec3d palmNormal = -Vec3d(palmMatrix.col(2)); //palmNormal.normalize(); //helper::gl::drawCylinder(handPalmCoordinate.getValue().getCenter(), handPalmCoordinate.getValue().getCenter() + palmNormal.mulscalar(3.0) ,0.25,8); for(int i=0; i<5; i++) { //draw fingerTip as a torus fingersCoordinates.getValue()[3*i].writeOpenGlMatrix(coordMatrix); helper::gl::drawTorus(coordMatrix,0.9*scale.getValue(),4.0*scale.getValue(),30, Vec3i(255-(i*55)%255, 255-((5-i)*75)%255, (i*60)%255)); //draw metacarpus as a cylinder helper::gl::drawCylinder(handPalmCoordinate.getValue().getCenter(),fingersCoordinates.getValue()[3*i+1].getCenter() ,2.25*scale.getValue(),8); //draw metacarpophalangeal joint as a torus fingersCoordinates.getValue()[3*i+1].writeOpenGlMatrix(coordMatrix); helper::gl::drawTorus(coordMatrix,scale.getValue(),5.0*scale.getValue(),30,Vec3i(255,215,180)); //draw proximal interphalangial joint helper::gl::drawCylinder(fingersCoordinates.getValue()[3*i+1].getCenter(),fingersCoordinates.getValue()[3*i+2].getCenter() ,2.25*scale.getValue(),8); helper::gl::drawCylinder(fingersCoordinates.getValue()[3*i+2].getCenter(), fingersCoordinates.getValue()[3*i].getCenter(),2.25*scale.getValue(),8); helper::gl::drawSphere(fingersCoordinates.getValue()[3*i+2].getCenter(),2.0*scale.getValue(),15,15); //draw leap sphere of the hand //helper::gl::drawSphere(sphereCenter.getValue(),0.1*sphereRadius.getValue()*scale.getValue(),15,15); } } } } void LeapMotionDriver::computeBBox(const core::ExecParams * params, bool /*onlyVisible=false*/ ) { const double max_real = std::numeric_limits<double>::max(); const double min_real = -std::numeric_limits<double>::max(); double maxBBox[3] = {min_real,min_real,min_real}; double minBBox[3] = {max_real,max_real,max_real}; for(int i=0; i<15; i++) { for( int c=0; c<3; c++) { minBBox[c] = (fingersCoordinates.getValue()[i][c] < minBBox[c]) ? fingersCoordinates.getValue()[i][c] : minBBox[c] ; maxBBox[c] = (fingersCoordinates.getValue()[i][c] > maxBBox[c]) ? fingersCoordinates.getValue()[i][c] : maxBBox[c] ; } } Mat3x3d matrix; handPalmCoordinate.getValue().writeRotationMatrix(matrix); Vec3d toFrontHandPalmDirection = Vec3d(matrix.col(0)); double palmDiag = toFrontHandPalmDirection.mulscalar(20.0*scale.getValue()).norm() * sqrt(2.0); for( int c=0; c<3; c++) { minBBox[c] = ((handPalmCoordinate.getValue()[c] - palmDiag) < minBBox[c]) ? (handPalmCoordinate.getValue()[c] - palmDiag) : minBBox[c] ; maxBBox[c] = ((handPalmCoordinate.getValue()[c] + palmDiag) > maxBBox[c]) ? (handPalmCoordinate.getValue()[c] + palmDiag) : maxBBox[c] ; } this->f_bbox.setValue(params,sofa::defaulttype::TBoundingBox<double>(minBBox,maxBBox)); } void LeapMotionDriver::applyRotation (Rigid3dTypes::Coord* rigidToRotate) { Quat q = Quat().createQuaterFromEuler(rotation.getValue().mulscalar(M_PI / 180.0)); (*rigidToRotate).getCenter() = q.rotate((*rigidToRotate).getCenter()); (*rigidToRotate).getOrientation() = q * (*rigidToRotate).getOrientation(); } void LeapMotionDriver::handleEvent(core::objectmodel::Event *event) { if (sofa::core::objectmodel::KeypressedEvent* ev = dynamic_cast<sofa::core::objectmodel::KeypressedEvent*>(event)) { if (ev->getKey() == 'I' || ev->getKey() == 'i') { drawInteractionBox = !drawInteractionBox; } /*Does it work ?*/ else if (ev->getKey() == 'Q' || ev->getKey() == 'q') { gestureType.setValue(TYPE_V_SIGN_AND_2ND_HAND); gesturePosition.setValue(Vec3d(currentFrame,0,0)); gestureDirection.setValue(Vec3d(0,0,0)); lastGestureType = TYPE_V_SIGN_AND_2ND_HAND; lastGestureFrameId = currentFrame; lastGesturesFrameIds.at(TYPE_V_SIGN_AND_2ND_HAND).second = currentFrame; } } if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event)) { //----- Get hand palm coordinates if (leapConnected ) { Vector3 handPalmPosition = Vector3(myListener.getStabilizedPalmPosition().toFloatPointer()); Quat handPalmRotation = myListener.getPalmRotation(); Rigid3dTypes::Coord tmpHandPalmCoord = Rigid3dTypes::Coord(scale.getValue()*handPalmPosition, handPalmRotation); applyRotation(&tmpHandPalmCoord); tmpHandPalmCoord.getCenter() += translation.getValue(); handPalmCoordinate.setValue(tmpHandPalmCoord); } //----- Get hand sphere if (leapConnected ) { Vector3 handSphereCenter = Vector3(myListener.getHandSphereCenter().toFloatPointer()); float handSphereRadius = myListener.getHandSphereRadius(); Quat q = Quat().createQuaterFromEuler(rotation.getValue().mulscalar(M_PI / 180.0)); Vec3d tmpHandSphereCenter = q.rotate(scale.getValue()*handSphereCenter); tmpHandSphereCenter += translation.getValue(); sphereCenter.setValue(tmpHandSphereCenter); sphereRadius.setValue(scale.getValue()*handSphereRadius); } //----- Get fingers coordinates int fingerCount = std::min(myListener.getFingers().count(),5); //----begin finger registration init int registeredFingersCount = 0; int nbFrame=0; for(int i=0; i<5; i++) { if(fingersIdsArray[i]!=-1) registeredFingersCount++; } int32_t newFingersIdsArray[5] = {-1,-1,-1,-1,-1}; tmpIds.clear(); //----end finger registration init helper::WriteAccessor<Data<helper::vector<RigidCoord<3,double> > > > fingerCoords = fingersCoordinates; for(int i=0; i<15; i++) { fingerCoords[i] = handPalmCoordinate.getValue(); } for(int i=0; i<fingerCount; i++) { nbFrame++; Vec3d xAxis = Vec3d(myListener.getFingers()[i].direction().toFloatPointer()); xAxis.normalize(); Vector3 yAxis; Vector3 zAxis(1.0, 0.0, 0.0); if ( fabs(dot(zAxis, xAxis)) > 0.7) zAxis = Vector3(0.0, 0.0, 1.0); yAxis = zAxis.cross(xAxis); yAxis.normalize(); zAxis = xAxis.cross(yAxis); zAxis.normalize(); Vec3d fingerPosition = Vec3d(myListener.getFingers()[i].stabilizedTipPosition().toFloatPointer()); Quat fingerOrientation = Quat().createQuaterFromFrame(yAxis, zAxis, xAxis); Rigid3dTypes::Coord tmpFingerCoord = Rigid3dTypes::Coord(scale.getValue()*fingerPosition, fingerOrientation); applyRotation(&tmpFingerCoord); tmpFingerCoord.getCenter() += translation.getValue(); fingerCoords[3*i] = tmpFingerCoord; computeFingerJoints(i, &fingerCoords); bool alreadyRegistered=false; int32_t fingerId; fingerId = myListener.getFingers()[i].id(); //----begin finger registration int fIdIter; for ( fIdIter = 0; fIdIter < 5; fIdIter++) { if(fingersIdsArray[fIdIter]==fingerId) { newFingersIdsArray[fIdIter] = fingerId; alreadyRegistered = true; } } fIdIter = 0; if(!alreadyRegistered) tmpIds.insert(tmpIds.end(),fingerId); }//foreach finger for(size_t j=0; j<tmpIds.size(); j++) { int fIdIter=0; while(fIdIter<5 && newFingersIdsArray[fIdIter]!=-1 ) { fIdIter++; } if(fIdIter<5) newFingersIdsArray[fIdIter] = tmpIds[j]; else std::cout << "ID insersion failed, array is full" << std::endl; } for (int k=0; k<5; k++) fingersIdsArray[k] = newFingersIdsArray[k]; //----end finger registration //-------------------------------- OUR Handle Gestures ---------------------------- // -------------------------- PINCH Gesture ---------------------------- Mat3x3d fingerMatrix; pinchGestureRecognized = false; double pinchDotproduct; Vec3d pinchPosition; for(int i=0; i<fingerCount; i++) { fingerCoords[3*i].getOrientation().toMatrix(fingerMatrix); Vec3d finger1Dir = Vec3d(fingerMatrix.col(0)); double distance; for(int fIter= (i+1); fIter<fingerCount; fIter++) { distance = (fingerCoords[3*i].getCenter()-fingerCoords[3*fIter].getCenter()).norm() / scale.getValue(); if(distance < PINCH_DISTANCE_THRESHOLD) { fingerCoords[3*fIter].getOrientation().toMatrix(fingerMatrix); Vec3d finger2Dir = Vec3d(fingerMatrix.col(0)); pinchDotproduct = dot(finger1Dir,finger2Dir); if(pinchDotproduct < PINCH_DOTPRODUCT_THRESHOLD) { if(!pinchGestureRecognized) { pinchPosition = fingerCoords[3*i].getCenter() + (fingerCoords[3*fIter].getCenter()-fingerCoords[3*i].getCenter()).divscalar(2.0); } pinchGestureRecognized = true; } } } } if(pinchGestureRecognized) { if(((currentFrame-lastGesturesFrameIds.at(TYPE_PINCH).second)/myListener.getCurrentFramesPerSecond())<5.0) { if(f_printLog.getValue()) std::cout << "Pinch rejected" << std::endl; } else { if(f_printLog.getValue()) std::cout << "PINCH gesture detected"<<std::endl; gestureType.setValue(TYPE_PINCH); gesturePosition.setValue(pinchPosition); gestureDirection.setValue(Vec3d(0,0,0)); lastGestureType = TYPE_PINCH; lastGestureFrameId = currentFrame; lastGesturesFrameIds.at(TYPE_PINCH).second = currentFrame; } } // -------------------------- TYPE_V_SIGN_ Gesture ---------------------------- static int lastFingerCount = 0, beginVSignFrame = 0, lastSecondHandFingerCount = 0, beginSecondHandFrame = 0; double distance; //V SIGN if(fingerCount == 2) { if(lastFingerCount!=2) { beginVSignFrame = currentFrame; } else { distance=sqrt(pow(((fingersCoordinates.getValue(0)[0][0])-(fingersCoordinates.getValue(0)[1][0])),2)+pow(((fingersCoordinates.getValue(0)[0][1])-(fingersCoordinates.getValue(0)[1][1])),2)+pow(((fingersCoordinates.getValue(0)[0][2])-(fingersCoordinates.getValue(0)[1][2])),2)); if((currentFrame-beginVSignFrame)/myListener.getFPS()>3.0 && distance<=160 && distance>=70) { VSignGestureRecognized = true; if(f_printLog.getValue()) std::cout << "V_SIGN gesture detected"<<std::endl; } } } else { VSignGestureRecognized = false; } lastFingerCount = fingerCount; //2ND HAND if(myListener.getSecondHand().isValid() && myListener.getSecondHandFingers().count()>=4) { if(lastSecondHandFingerCount<4) { beginSecondHandFrame = currentFrame; } else { if((currentFrame-beginSecondHandFrame)/myListener.getCurrentFramesPerSecond()>2.0) { secondHandRecognized = true; if(f_printLog.getValue()) std::cout << "Second hand detected"<<std::endl; } } } else { secondHandRecognized = false; } lastSecondHandFingerCount = myListener.getSecondHandFingers().count(); //------------------------------------------- GRASP_AND_RELEASE_GESTURE----------------------------------------------------- if (fingerCount==0 && lastFingerCount>=4 && myListener.getHand().palmPosition().isValid()) { GraspAndReleaseGestureRecognized=true; if (GraspAndReleaseGestureRecognized && ((currentFrame-lastGesturesFrameIds.at(GRASP_AND_RELEASE).second)/myListener.getFPS())>2.0) { if(f_printLog.getValue()) std::cout << "GRASP gesture detected"<<std::endl; gestureType.setValue(GRASP_AND_RELEASE); gesturePosition.setValue(handPalmCoordinate.getValue().getCenter()); gestureDirection.setValue(Vec3d(0,0,0)); } lastGestureType = GRASP_AND_RELEASE; lastGestureFrameId = currentFrame; lastGesturesFrameIds.at(GRASP_AND_RELEASE).second = currentFrame; } if (!myListener.getGestures().isEmpty()) { int nbGesturesInFrame = 0; for (int g = 0; g < myListener.getGestures().count(); ++g) { Gesture gesture = myListener.getGestures()[g]; if ( gesture.isValid() && gesture.state()==Gesture::STATE_STOP) { nbGesturesInFrame++; switch (gesture.type()) { // -------------------------- CIRCLE Gesture ---------------------------- case Gesture::TYPE_CIRCLE: { if(((currentFrame-lastGesturesFrameIds.at(TYPE_CIRCLE).second)/myListener.getCurrentFramesPerSecond())<2.0) { if(f_printLog.getValue()) std::cout << "CIRCLE REJECTED !" << std::endl; break; } CircleGesture circle = gesture; gestureType.setValue(TYPE_CIRCLE); gesturePosition.setValue(Vec3d(circle.center().toFloatPointer())); gestureDirection.setValue(Vec3d(0,0,0)); scrollDirection.setValue(0); if(f_printLog.getValue()) std::cout << "CIRCLE gesture detected"<<std::endl; lastGestureType = TYPE_CIRCLE; lastGesturesFrameIds.at(TYPE_CIRCLE).second = currentFrame; break; } // -------------------------- SWIPE Gesture ---------------------------- case Gesture::TYPE_SWIPE: { if(((currentFrame-lastGesturesFrameIds.at(TYPE_SWIPE).second)/myListener.getCurrentFramesPerSecond())<1.0 || ((currentFrame-lastGesturesFrameIds.at(TYPE_CIRCLE).second)/myListener.getCurrentFramesPerSecond())<1.0 ) { if(f_printLog.getValue()) std::cout << "SWIPE REJECTED !" << std::endl; break; } SwipeGesture swipe=gesture; if(swipe.speed() < SWIPE_MIN_VELOCITY) break; gestureType.setValue(TYPE_SWIPE); gesturePosition.setValue(Vec3d(swipe.position().toFloatPointer())); gestureDirection.setValue(Vec3d(swipe.direction().toFloatPointer())); if(f_printLog.getValue()) std::cout << "SWIPE gesture detected"<<std::endl; double leapScrollDirection = gestureDirection.getValue()[0]; leapScrollDirection /= gestureDirection.getValue().norm(); if (leapScrollDirection < -SCROLL_DIRECTION_THRESHOLD) { scrollDirection.setValue(1); } else if (leapScrollDirection > SCROLL_DIRECTION_THRESHOLD) { scrollDirection.setValue(2); } else { break; } lastGestureType = TYPE_SWIPE; lastGesturesFrameIds.at(TYPE_SWIPE).second = currentFrame; break; } // -------------------------- KEY_TAP Gesture ---------------------------- case Gesture::TYPE_KEY_TAP: { if(((currentFrame-lastGesturesFrameIds.at(TYPE_KEY_TAP).second)/myListener.getCurrentFramesPerSecond())<1.0) { if(f_printLog.getValue()) std::cout << "KEY TAP REJECTED !" << std::endl; break; } KeyTapGesture tap = gesture; gestureType.setValue(TYPE_KEY_TAP); gesturePosition.setValue(Vec3d(tap.position().toFloatPointer())); gestureDirection.setValue(Vec3d(tap.direction().toFloatPointer())); scrollDirection.setValue(0); if(f_printLog.getValue()) std::cout << "KEY_TAP gesture detected"<<std::endl; lastGestureType = TYPE_KEY_TAP; lastGesturesFrameIds.at(TYPE_KEY_TAP).second = currentFrame; break; } // -------------------------- SCREEN_TAP Gesture ---------------------------- case Gesture::TYPE_SCREEN_TAP: { if(((currentFrame-lastGesturesFrameIds.at(TYPE_SCREEN_TAP).second)/myListener.getCurrentFramesPerSecond())<1.0) { if(f_printLog.getValue()) std::cout << "SCREEN TAP REJECTED !" << std::endl; break; } ScreenTapGesture screentap = gesture; gestureType.setValue(TYPE_SCREEN_TAP); gesturePosition.setValue(Vec3d(screentap.position().toFloatPointer())); gestureDirection.setValue(Vec3d(screentap.direction().toFloatPointer())); scrollDirection.setValue(0); if(f_printLog.getValue()) std::cout << "SCREEN_TAP gesture detected"<<std::endl; lastGestureType = TYPE_SCREEN_TAP; lastGesturesFrameIds.at(TYPE_SCREEN_TAP).second = currentFrame; break; } // -------------------------- Unknown Gesture ---------------------------- default: break; } // switch lastGestureFrameId = currentFrame; } // isValid & stateSTOP } // for loop } } // AnimatedBeginEvent } int LeapMotionDriverClass = core::RegisterObject("LeapMotion device driver") .add< LeapMotionDriver >(); SOFA_DECL_CLASS(LeapMotionDriver) } // namespace controller } // namespace component } // namespace sofa
43.91689
292
0.563305
sofa-framework
c365a0cc958dc5ad3e5a502c3ac833300430ba49
760
cpp
C++
src/Event.cpp
zetef/calviewer
d08654051b5b6de214bf6cfc3b39afac2ab752c6
[ "MIT" ]
null
null
null
src/Event.cpp
zetef/calviewer
d08654051b5b6de214bf6cfc3b39afac2ab752c6
[ "MIT" ]
1
2019-04-21T22:31:24.000Z
2019-04-22T09:01:01.000Z
src/Event.cpp
zetef/kalendar
d08654051b5b6de214bf6cfc3b39afac2ab752c6
[ "MIT" ]
null
null
null
#include "../include/Event.h" //////////////////////////////// /// Public Member Functions //// //////////////////////////////// Event::Event() { init(); } void Event::init(){ m_exist = false; m_title = "No Event"; m_day = 1; m_month = 1; m_year = 1900; } void Event::set_title(std::string t_title) { m_title = t_title; } void Event::set_day(int t_day) { m_day = t_day; } int Event::get_day(){ return m_day; } void Event::set_month(int t_month) { m_month = t_month; } int Event::get_month(){ return m_month; } void Event::set_year(int t_year) { m_year = t_year; } int Event::get_year(){ return m_year; } // void Event::check() { // if(){ // set_title(); // } // } void Event::free(){ init(); } ////////////////////////////////
12.881356
44
0.534211
zetef
c36ccd5e99941446982a098dfc6f9b127eed8054
489
cpp
C++
subsequenceSum.cpp
vkku/cppWorkspace
1b07511eb30929139a3769cffc0be9e4683c8683
[ "MIT" ]
1
2016-10-20T17:08:02.000Z
2016-10-20T17:08:02.000Z
subsequenceSum.cpp
vkku/cppWorkspace
1b07511eb30929139a3769cffc0be9e4683c8683
[ "MIT" ]
null
null
null
subsequenceSum.cpp
vkku/cppWorkspace
1b07511eb30929139a3769cffc0be9e4683c8683
[ "MIT" ]
null
null
null
#include<iostream> int main() { int arr[50] = {1,2,3,4,5}; int sum = 0, currSum = 0, subIndex = 0;; int i = 0; cout<<"\nEnter Proposed Sum\n"; cin>>sum; currSum = 0; subIndex = 0; for(i = 0 ; i < 5 ; i++) { currSum += arr[i]; if(currSum > sum) currSum -= arr[subIndex++]; else if(currSum == sum) { cout<<"\nSubsequence is : "<<subIndex+1<<i+1; exit(0); } } return 0; }
20.375
57
0.439673
vkku
c37020276d614b12e9741e818c0c7873e18c1adf
809
cc
C++
ui/ozone/platform/drm/gpu/mock_scanout_buffer_generator.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
27
2016-04-27T01:02:03.000Z
2021-12-13T08:53:19.000Z
ui/ozone/platform/drm/gpu/mock_scanout_buffer_generator.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
2
2017-03-09T09:00:50.000Z
2017-09-21T15:48:20.000Z
ui/ozone/platform/drm/gpu/mock_scanout_buffer_generator.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
17
2016-04-27T02:06:39.000Z
2019-12-18T08:07:00.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/drm/gpu/mock_scanout_buffer_generator.h" #include "ui/ozone/platform/drm/common/drm_util.h" #include "ui/ozone/platform/drm/gpu/mock_scanout_buffer.h" namespace ui { MockScanoutBufferGenerator::MockScanoutBufferGenerator() {} MockScanoutBufferGenerator::~MockScanoutBufferGenerator() {} scoped_refptr<ScanoutBuffer> MockScanoutBufferGenerator::Create( const scoped_refptr<DrmDevice>& drm, gfx::BufferFormat format, const gfx::Size& size) { scoped_refptr<MockScanoutBuffer> buffer( new MockScanoutBuffer(size, GetFourCCFormatForFramebuffer(format))); return buffer; } } // namespace ui
29.962963
74
0.777503
Wzzzx
c378679b7958720abc9bed96bd19c616c7378980
141
cpp
C++
Algorithms/Bit Manipulation/Flip ith bit/flip.cpp
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
26
2019-07-17T11:05:43.000Z
2022-02-06T08:31:40.000Z
Algorithms/Bit Manipulation/Flip ith bit/flip.cpp
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
7
2019-07-16T19:52:25.000Z
2022-01-08T08:03:44.000Z
Algorithms/Bit Manipulation/Flip ith bit/flip.cpp
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
19
2020-01-14T02:44:28.000Z
2021-12-27T17:31:59.000Z
#include <bits/stdc++.h> using namespace std; int main(){ int n, i; cin >> n >> i; n = n ^ (1<<i); cout << n; return 0; }
15.666667
24
0.468085
Nidita
c379a50ee71309d9e765e9d9241fcac798ad588c
3,201
cpp
C++
src/Source Code/Mesh.cpp
MayKoder/Advanced-GL-Shader
3a73c5c112f9cc245b6353734eed572b96f95af2
[ "MIT" ]
null
null
null
src/Source Code/Mesh.cpp
MayKoder/Advanced-GL-Shader
3a73c5c112f9cc245b6353734eed572b96f95af2
[ "MIT" ]
null
null
null
src/Source Code/Mesh.cpp
MayKoder/Advanced-GL-Shader
3a73c5c112f9cc245b6353734eed572b96f95af2
[ "MIT" ]
null
null
null
#include "Mesh.h" #include <vector> void Mesh::init(Vertex* vertices, unsigned int numVertices, unsigned int* indices, unsigned int numIndices) { IndexedModel model; for (unsigned int i = 0; i < numVertices; i++) { model.positions.push_back(*vertices[i].GetPos()); model.texCoords.push_back(*vertices[i].GetTexCoord()); model.normals.push_back(*vertices[i].GetNormal()); } for (unsigned int i = 0; i < numIndices; i++) model.indices.push_back(indices[i]); initModel(model); } void Mesh::initModel(const IndexedModel& model) { drawCount = model.indices.size(); glGenVertexArrays(1, &vertexArrayObject); //generate a vertex array and store it in the VAO glBindVertexArray(vertexArrayObject); //bind the VAO (any operation that works on a VAO will work on our bound VAO - binding) glGenBuffers(4, vertexArrayBuffers); //generate our buffers based of our array of data/buffers - GLuint vertexArrayBuffers[NUM_BUFFERS]; glBindBuffer(GL_ARRAY_BUFFER, vertexArrayBuffers[POSITION_VERTEXBUFFER]); //tell opengl what type of data the buffer is (GL_ARRAY_BUFFER), and pass the data glBufferData(GL_ARRAY_BUFFER, model.positions.size() * sizeof(model.positions[0]), &model.positions[0], GL_STATIC_DRAW); //move the data to the GPU - type of data, size of data, starting address (pointer) of data, where do we store the data on the GPU (determined by type) glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, vertexArrayBuffers[TEXCOORD_VB]); //tell opengl what type of data the buffer is (GL_ARRAY_BUFFER), and pass the data glBufferData(GL_ARRAY_BUFFER, model.texCoords.size() * sizeof(model.texCoords[0]), &model.texCoords[0], GL_STATIC_DRAW); //move the data to the GPU - type of data, size of data, starting address (pointer) of data, where do we store the data on the GPU glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, vertexArrayBuffers[NORMAL_VB]); glBufferData(GL_ARRAY_BUFFER, sizeof(model.normals[0]) * model.normals.size(), &model.normals[0], GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexArrayBuffers[INDEX_VB]); //tell opengl what type of data the buffer is (GL_ARRAY_BUFFER), and pass the data glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.indices.size() * sizeof(model.indices[0]), &model.indices[0], GL_STATIC_DRAW); //move the data to the GPU - type of data, size of data, starting address (pointer) of data, where do we store the data on the GPU glBindVertexArray(0); // unbind our VAO } Mesh::Mesh() : vertexArrayObject(0) { drawCount = NULL; memset(vertexArrayBuffers, 0, sizeof(vertexArrayBuffers)); } void Mesh::loadModel(const std::string& filename) { IndexedModel model = OBJModel(filename).ToIndexedModel(); initModel(model); } Mesh::~Mesh() { glDeleteVertexArrays(1, &vertexArrayObject); // delete arrays } void Mesh::draw() { glBindVertexArray(vertexArrayObject); glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_INT, 0); //glDrawArrays(GL_TRIANGLES, 0, drawCount); glBindVertexArray(0); }
40.0125
273
0.759763
MayKoder
c37bee8a2868aaf01d2cbab804d52a1d98a34b1f
2,287
cpp
C++
src/main.cpp
horvatm/misaligned_roche_critical
8e302b468c8b23ce012407250292e5fdf806ef4f
[ "MIT" ]
null
null
null
src/main.cpp
horvatm/misaligned_roche_critical
8e302b468c8b23ce012407250292e5fdf806ef4f
[ "MIT" ]
null
null
null
src/main.cpp
horvatm/misaligned_roche_critical
8e302b468c8b23ce012407250292e5fdf806ef4f
[ "MIT" ]
null
null
null
/* Searching for critical points of the Kopal potential Omega of the misaligned binary star: Omega(x,y,z,params) = 1/r1 + q(1/r2 - x/delta^2) + 1/2 (1 + q) F^2 [(x cos theta' - z sin theta')^2 + y^2] r1 = sqrt(x^2 + y^2 + z^2) r2 = sqrt((x-delta)^2 + y^2 + z^2) The critical point r is defined as Nabla Omega(r) = 0; Note: * Sometimes we referee to theta as beta. Author: Martin Horvat, Jan 2018 */ #include <iostream> #include <cmath> #include <fstream> #include "main.h" int main(){ std::cout.precision(16); std::cout << std::scientific; std::ofstream fl("res1.dat"); fl.precision(16); fl << std::scientific; double X0 = -10000, // limits of the bounding box [X0,Y0] , [X1,Y1] Y0 = -10000, X1 = +10000, Y1 = +10000, Nx = 1000000, // maximal number of steps in X direction Ny = 1000000, // maximal number of steps in Y direction Nl = 50, // maximal number of recursions Nth = 400, // steps in theta, theta in [th_min, th_max] th, th_min = -M_PI/2, th_max = +M_PI/2, dth = (th_max - th_min)/(Nth-1), Nq = 50, // steps in q, q in [q_min, q_max] q, q_min = 0.1, q_max = 10, dq = (q_max - q_min)/(Nq-1), NF = 50, // steps in F, F in [F_min, F_max] F, F_min = 0.1, F_max = 10, dF = (F_max - F_min)/(NF-1), p[4], H[2][2]; for (int i = 0; i < Nq; ++i) { p[0] = q = q_min + dq*i; for (int j = 0; j < NF; ++j) { F = F_min + dF*j; p[1] = (1 + q)*F*F; for (int k = 0; k < Nth; ++k) { th = th_min + k*dth; sincos(th, p+2, p+3); Troots <double> roots; //scan_with_lines<double>(X0, Y0, X1, Y1, p, roots, Nx, Ny, Nl); scan_with_image<double>(X0, Y0, X1, Y1, p, roots, Nx, Ny, Nl); for (auto && x: roots) if (!(x[0] == 0 && x[1] == 0) && !(x[0] == 1 && x[1] == 0)) { Dfun(x.ptr(), H, p); fl << q << ' ' << F << ' ' << th << ' ' << x[0] << ' ' << x[1] << ' ' << extreme_type(H) << '\n'; } } fl.flush(); } } return 0; }
23.336735
109
0.452995
horvatm
c38c0e9be13ac82ae63c579b8cf3e460d36c0964
2,586
hxx
C++
main/autodoc/inc/ary/doc/d_parametrized.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/autodoc/inc/ary/doc/d_parametrized.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/autodoc/inc/ary/doc/d_parametrized.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef ARY_DOC_D_PARAMETER_HXX #define ARY_DOC_D_PARAMETER_HXX // USED SERVICES // BASE CLASSES #include <ary/doc/d_node.hxx> namespace ary { namespace doc { /** Documentation unit with Parameter. */ template <class T> class Parametrized : public Node { public: // LIFECYCLE explicit Parametrized( nodetype::id i_id, T i_Parameter ); virtual ~Parametrized(); // INQUIRY const HyperText & Doc() const; const T & Parameter() const; // ACCESS HyperText & Doc(); void Set_Parameter( const T & i_param ); private: // Interface csv::ConstProcessorClient: virtual void do_Accept( csv::ProcessorIfc & io_processor ) const; // DATA HyperText aDoc; T aParameter; }; // IMPLEMENTATION template <class T> Parametrized<T>::Parametrized( nodetype::id i_id, T i_Parameter ) : Node(i_id), aDoc(), aParameter(i_Parameter) { } template <class T> Parametrized<T>::~Parametrized() { } template <class T> const HyperText & Parametrized<T>::Doc() const { return aDoc; } template <class T> const T & Parametrized<T>::Parameter() const { return aParameter; } template <class T> HyperText & Parametrized<T>::Doc() { return aDoc; } template <class T> inline void Parametrized<T>::Set_Parameter(const T & i_param) { aParameter = i_param; } } // namespace doc } // namespace ary #endif
21.915254
69
0.592421
Grosskopf
c38d7ee76063afeabc14b5c694b77bf4614c7682
3,371
cpp
C++
src/gles_ext_texture_buffer.cpp
ARM-software/tracetooltests
492159e67c9e58b2a8ce553fd30417faf70cb1d6
[ "MIT" ]
null
null
null
src/gles_ext_texture_buffer.cpp
ARM-software/tracetooltests
492159e67c9e58b2a8ce553fd30417faf70cb1d6
[ "MIT" ]
null
null
null
src/gles_ext_texture_buffer.cpp
ARM-software/tracetooltests
492159e67c9e58b2a8ce553fd30417faf70cb1d6
[ "MIT" ]
null
null
null
#include "gles_common.h" static GLuint gvPositionHandle; PACKED(struct params { GLuint count; GLuint primCount; GLuint first; GLuint baseInstance; }); const char *vertex_shader_source[] = GLSL_VS( in vec4 vPosition; flat out int texcoord; void main() { gl_Position = vPosition; texcoord = int(floor(vPosition.y + 1.0f) * 2.0f + floor(vPosition.x + 1.0f)); } ); const char *fragment_shader_source[] = GLSL_FS( flat in int texcoord; out vec4 fragmentColor; uniform highp samplerBuffer s_texture; void main() { fragmentColor = texelFetch( s_texture, texcoord ); } ); static GLuint vs, fs, draw_program; static GLuint g_bufferId; static GLubyte pixels[4 * 4] = { 0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255 }; static int setupGraphics(TOOLSTEST *handle) { // setup space glViewport(0, 0, handle->width, handle->height); // setup draw program draw_program = glCreateProgram(); vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, vertex_shader_source, NULL); compile("vertex_shader_source", vs); fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, fragment_shader_source, NULL); compile("fragment_shader_source", fs); glAttachShader(draw_program, vs); glAttachShader(draw_program, fs); link_shader("draw_program", draw_program); glUseProgram(draw_program); glGenBuffers(1, &g_bufferId); glBindBuffer(GL_TEXTURE_BUFFER_EXT, g_bufferId); glBufferData(GL_TEXTURE_BUFFER_EXT, sizeof(pixels), pixels, GL_STATIC_READ); glTexBuffer(GL_TEXTURE_BUFFER_EXT, GL_RGBA8, g_bufferId); glActiveTexture(GL_TEXTURE0); glUniform1i(glGetUniformLocation(draw_program, "s_texture"), 0); GLint value; glGetIntegerv(GL_TEXTURE_BUFFER, &value); glGetIntegerv(GL_MAX_TEXTURE_BUFFER_SIZE, &value); glGetIntegerv(GL_TEXTURE_BINDING_BUFFER, &value); glGetIntegerv(GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT, &value); GLsizei length; GLint size; GLenum type; GLchar name[255]; glGetActiveUniform(draw_program, 0, 1, &length, &size, &type, name); glGetTexLevelParameteriv(GL_TEXTURE_BUFFER, 0, GL_TEXTURE_BUFFER_DATA_STORE_BINDING, &value); glGetTexLevelParameteriv(GL_TEXTURE_BUFFER, 0, GL_TEXTURE_BUFFER_OFFSET, &value); glGetTexLevelParameteriv(GL_TEXTURE_BUFFER, 0, GL_TEXTURE_BUFFER_SIZE, &value); gvPositionHandle = glGetAttribLocation(draw_program, "vPosition"); return 0; } static const int triangle_num = 4; static const GLfloat gTriangleVertices[triangle_num][9] = { { -0.5f, 0.875f, 0, -0.875f, 0.125f, 0, -0.125f, 0.125f, 0 }, { 0.5f, 0.875f, 0, 0.125f, 0.125f, 0, 0.875f, 0.125f, 0 }, { -0.5f, -0.125f, 0, -0.875f, -0.875f, 0, -0.125f, -0.875f, 0 }, { 0.5f, -0.125f, 0, 0.125f, -0.875f, 0, 0.875f, -0.875f, 0 } }; static void callback_draw(TOOLSTEST *handle) { glClearColor(0.0f, 0.5f, 0.5f, 1.0f); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); for (int i = 0; i < triangle_num; i++) { glUseProgram(draw_program); glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 0, gTriangleVertices[i]); glEnableVertexAttribArray(gvPositionHandle); glDrawArrays(GL_TRIANGLES, 0, 3); } assert_fb(handle); } static void test_cleanup(TOOLSTEST *handle) { glDeleteShader(vs); glDeleteShader(fs); glDeleteProgram(draw_program); } int main(int argc, char** argv) { return init(argc, argv, "ext_texture_buffer", callback_draw, setupGraphics, test_cleanup); }
25.537879
94
0.741323
ARM-software
c39615e0b35dee60bd22cf92c60d9aeeffaabf7c
839
cpp
C++
프로그래머스/동적계획법/정수삼각형.cpp
woorimlee/cpp_CTCI_6E_APSS
ff1d42e871ba853ac3de726df0c609885ba07573
[ "MIT" ]
2
2020-12-30T03:35:51.000Z
2021-02-28T20:39:09.000Z
프로그래머스/동적계획법/정수삼각형.cpp
woorimlee/cpp_CTCI_6E_APSS
ff1d42e871ba853ac3de726df0c609885ba07573
[ "MIT" ]
1
2020-12-08T08:48:40.000Z
2021-04-09T04:58:57.000Z
프로그래머스/동적계획법/정수삼각형.cpp
woorimlee/Algorithm-Repository
ff1d42e871ba853ac3de726df0c609885ba07573
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; int cache[501][501]; int search_path(vector<vector<int>>& tri, int y, int x) { if (y == tri.size()) return 0; int& ret = cache[y][x]; if (ret != -1) return ret; ret = 0; ret = max(ret, search_path(tri, y + 1, x) + tri[y][x]); ret = max(ret, search_path(tri, y + 1, x + 1) + tri[y][x]); return ret; } int solution(vector<vector<int>> triangle) { int answer = 0; fill(&cache[0][0], &cache[500][501], -1); answer = search_path(triangle, 0, 0); cout << answer; return answer; } int main() { //[[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]] vector<vector <int> > t = { {7}, {3, 8}, {8, 1, 0}, {2, 7, 4, 4}, {4, 5, 2, 6, 5} }; solution(t); return 0; }
23.305556
88
0.517282
woorimlee
c399ef0be757dcb299e5ae931955127fcb73ac51
2,190
cpp
C++
ez_socket/src/ez_qbuffer.cpp
chcbaram/ez_socket
9ce4db935e1ef85ea1fa6a3be7d5ce3efbb386ce
[ "MIT" ]
null
null
null
ez_socket/src/ez_qbuffer.cpp
chcbaram/ez_socket
9ce4db935e1ef85ea1fa6a3be7d5ce3efbb386ce
[ "MIT" ]
null
null
null
ez_socket/src/ez_qbuffer.cpp
chcbaram/ez_socket
9ce4db935e1ef85ea1fa6a3be7d5ce3efbb386ce
[ "MIT" ]
null
null
null
#include "ez_qbuffer.h" namespace ez { void qbufferInit(void) { } bool qbufferCreate(qbuffer_t *p_node, uint8_t *p_buf, uint32_t length) { bool ret = true; p_node->in = 0; p_node->out = 0; p_node->len = length; p_node->size = 1; p_node->p_buf = p_buf; return ret; } bool qbufferCreateBySize(qbuffer_t *p_node, uint8_t *p_buf, uint32_t size, uint32_t length) { bool ret = true; p_node->in = 0; p_node->out = 0; p_node->len = length; p_node->size = size; p_node->p_buf = p_buf; return ret; } bool qbufferWrite(qbuffer_t *p_node, uint8_t *p_data, uint32_t length) { bool ret = true; uint32_t next_in; for (uint32_t i=0; i<length; i++) { next_in = (p_node->in + 1) % p_node->len; if (next_in != p_node->out) { if (p_node->p_buf != nullptr && p_data != nullptr) { uint8_t *p_buf; p_buf = &p_node->p_buf[p_node->in*p_node->size]; for (uint32_t i=0; i<p_node->size; i++) { p_buf[i] = p_data[i]; } p_data += p_node->size; } p_node->in = next_in; } else { ret = false; break; } } return ret; } bool qbufferRead(qbuffer_t *p_node, uint8_t *p_data, uint32_t length) { bool ret = true; for (uint32_t i=0; i<length; i++) { if (p_node->p_buf != nullptr && p_data != nullptr) { uint8_t *p_buf; p_buf = &p_node->p_buf[p_node->out*p_node->size]; for (uint32_t i=0; i<p_node->size; i++) { p_data[i] = p_buf[i]; } p_data += p_node->size; } if (p_node->out != p_node->in) { p_node->out = (p_node->out + 1) % p_node->len; } else { ret = false; break; } } return ret; } uint8_t *qbufferPeekWrite(qbuffer_t *p_node) { return &p_node->p_buf[p_node->in*p_node->size]; } uint8_t *qbufferPeekRead(qbuffer_t *p_node) { return &p_node->p_buf[p_node->out*p_node->size]; } uint32_t qbufferAvailable(qbuffer_t *p_node) { uint32_t ret; ret = (p_node->len + p_node->in - p_node->out) % p_node->len; return ret; } void qbufferFlush(qbuffer_t *p_node) { p_node->in = 0; p_node->out = 0; } }
15.985401
91
0.574429
chcbaram
c39bc962319fc7d0a14bae5b71c8c610ccd84fcb
9,611
cpp
C++
graphics/meshlab/src/meshlabplugins/edit_align/align/OccupancyGrid.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/meshlab/src/meshlabplugins/edit_align/align/OccupancyGrid.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/meshlab/src/meshlabplugins/edit_align/align/OccupancyGrid.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #include <time.h> #include <list> #include <utility> #include <bitset> #include "OccupancyGrid.h" #include <vcg/complex/algorithms/clean.h> #include <wrap/io_trimesh/import.h> #include <wrap/ply/plystuff.h> using namespace std; using namespace vcg; // Nota che il bbox viene automaticamento inflatato dalla G.SetBBox(); bool OccupancyGrid::Init(int _mn, Box3d bb, int size) { mn=_mn; // the number of meshes (including all the unused ones; eg it is the range of the possible id) if(mn>MeshCounter::MaxVal()) return false; MeshCounter MC; MC.Clear(); G.Create(bb,size,MC); VM.clear(); VM.resize(mn); return true; } void OccupancyGrid::Add(const char *MeshName, Matrix44d &Tr, int id) { A2Mesh M; tri::io::Importer<A2Mesh>::Open(M,MeshName); tri::Clean<A2Mesh>::RemoveUnreferencedVertex(M); AddMesh(M,Tr,id); } void OccupancyGrid::AddMeshes(std::vector<string> &names, std::vector<Matrix44d> &trv, int size ) { unsigned int i; Box3d bb,totalbb; bb.SetNull(); totalbb.SetNull(); printf("OG::AddMesh:Scanning BBoxex\n"); for(i=0;i<names.size();++i) { ply::ScanBBox(names[i].c_str(),bb); totalbb.Add( trv[i], bb); } Init(names.size(),totalbb,size); for(i=0;i<names.size();++i) { printf("OG::AddMesh:Adding Mesh %i '%s'\n",i,names[i].c_str()); Add(names[i].c_str(),trv[i],i); } } void OccupancyGrid::Compute() { // Analisi della griglia // Si deve trovare l'insieme degli archi piu'plausibili // un arco ha "senso" in una cella se entrambe le mesh compaiono in quell'arco // Si considera tutti gli archi possibili e si conta in quante celle ha senso un arco VA.clear(); VA.resize(mn*mn,0); // scan the grid and update possible arc count for(int i=0;i<G.siz[0];++i) for(int j=0;j<G.siz[1];++j) for(int k=0;k<G.siz[2];++k) { vector<int > vv; G.Grid(i,j,k).Pack(vv); size_t meshInCell = vv.size(); for( size_t ii=0; ii< vv.size(); ++ii) { int meshId = vv[ii]; ++VM[meshId].area; // compute mesh area if(meshInCell>VM[meshId].unicityDistribution.size()) VM[meshId].unicityDistribution.resize(meshInCell); ++(VM[meshId].unicityDistribution[meshInCell-1]); } for(size_t ii=0;ii<vv.size();++ii) for(size_t jj=ii+1;jj<vv.size();++jj) ++VA[vv[ii]+vv[jj]*mn]; // count intersections of all mesh pairs } // Find all the arcs SVA.clear(); for(int i=0;i<mn-1;++i) if(VM[i].used) for(int j=i+1;j<mn;++j) if(VM[j].used && VA[i+j*mn]>0) SVA.push_back( OGArcInfo(i,j, VA[i+j*mn], VA[i+j*mn]/float( min(VM[i].area,VM[j].area)) )); // Compute Mesh Coverage for(size_t i=0;i<SVA.size();++i) { VM[SVA[i].s].coverage += SVA[i].area; VM[SVA[i].t].coverage += SVA[i].area; } sort(SVA.begin(),SVA.end()); reverse(SVA.begin(),SVA.end()); } void OccupancyGrid::ComputeTotalArea() { int ccnt=0; MaxCount=0; int sz=G.size(); for(int i=0;i<sz;++i) if(!G.grid[i].Empty()) { ccnt++; if(G.grid[i].Count()>MaxCount) MaxCount=G.grid[i].Count(); } TotalArea=ccnt; } /* Ordinare le RangeMap in base a quanto sono utili. Una RangeMap e' utile se copre parti non ancora viste Per ogni cella della og c'e' un bit che dice quali range map ci passano per ogni range map si conosce l'area (espressa in celle della og) Si considera un voxel visto se ci sono almeno <K> range map che lo coprono. Inizialmente si moltiplica *1,2, ..K l'area di tutte le rm Si parte dalla rm con area maggiore e si diminuisce di uno l'area di tutte le altre rm che tocca in voxel visti meno di due volte. */ void OccupancyGrid::ComputeUsefulMesh(FILE *elfp) { vector<int> UpdArea(mn); vector<int> UpdCovg(mn); Use.clear(); int i,j,m,mcnt=0; for(m=0;m<mn;++m) { if(VM[m].used && VM[m].area>0) { mcnt++; UpdCovg[m]=VM[m].coverage; UpdArea[m]=VM[m].area; } } int sz=G.size(); if(elfp) { fprintf(elfp,"\n\nComputing Usefulness of Meshes of %i(on %i) meshes\n Og with %i / %i fill ratio %i max mesh per cell\n\n",mcnt,mn,TotalArea,sz,MaxCount); fprintf(elfp,"\n"); } int CumArea=0; for(m=0;m<mn-1;++m) { int best = max_element(UpdArea.begin(),UpdArea.end())-UpdArea.begin(); //int best = max_element(UpdCovg.begin(),UpdCovg.end())-UpdCovg.begin(); CumArea+=UpdArea[best]; if(UpdCovg[best]<0) break; if(VM[best].area==0) continue; // se era una mesh fuori del working group si salta tutto. if(elfp) fprintf(elfp,"%3i %3i %7i (%7i) %7i %5.2f %7i(%7i)\n", m, best, UpdArea[best],VM[best].area, TotalArea-CumArea, 100.0-100*float(CumArea)/TotalArea, UpdCovg[best],VM[best].coverage); Use.push_back(OGUseInfo(best,UpdArea[best])); UpdArea[best]=-1; UpdCovg[best]=-1; for(i=0;i<sz;++i) { MeshCounter &mc=G.grid[i]; if(mc.IsSet(best)) { mc.UnSet(best); for(j=0;j<mn;++j) if(mc.IsSet(j)) { --UpdArea[j]; UpdCovg[j]-=mc.Count(); } mc.Clear(); } } } } void OccupancyGrid::Dump(FILE *fp) { fprintf(fp,"Occupancy Grid\n"); fprintf(fp,"grid of ~%i kcells: %d x %d x %d\n",G.size(),G.siz[0],G.siz[1],G.siz[2]); fprintf(fp,"grid voxel size of %f %f %f\n",G.voxel[0],G.voxel[1],G.voxel[2]); fprintf(fp,"Computed %lu arcs for %i meshes\n",SVA.size(),mn); for(size_t i=0;i<VM.size();++i) { if(VM[i].used) { fprintf(fp,"mesh %3lu area %6i covg %7i (%5.2f%%) Uniq:",i,VM[i].area,VM[i].coverage,float(VM[i].coverage)/float(VM[i].area)); for(size_t j=0;j<std::min(size_t(8),VM[i].unicityDistribution.size());++j) fprintf(fp," %3i ", VM[i].unicityDistribution[j]); fprintf(fp,"\n"); } else fprintf(fp,"mesh %3lu ---- UNUSED\n",i); } fprintf(fp,"Computed %lu Arcs :\n",SVA.size()); for(size_t i=0;i<SVA.size() && SVA[i].norm_area > .1; ++i) fprintf(fp,"%4i -> %4i Area:%5i NormArea:%5.3f\n",SVA[i].s,SVA[i].t,SVA[i].area,SVA[i].norm_area); fprintf(fp,"End OG Dump\n"); } // sceglie gli archi da fare che abbiano una sovrapposizione di almeno <normarea> // e restituisce la lista di nodi isolati; void OccupancyGrid::ChooseArcs(vector<pair<int,int> > &AV, vector<int> &BNV, vector<int> &adjcnt, float normarea) { AV.clear(); BNV.clear(); size_t i=0; adjcnt.clear(); adjcnt.resize(mn,0); while(SVA[i].norm_area>normarea && i<SVA.size()) { AV.push_back(make_pair( SVA[i].s, SVA[i].t) ); ++adjcnt[SVA[i].s]; ++adjcnt[SVA[i].t]; ++i; } // Second loop to add some more constraints we add also all the arc with area > normarea/3 // and that connects meshes poorly connected (e.g. with zero or one adjacent) normarea/=3.0; while(SVA[i].norm_area>normarea && i<SVA.size()) { if(adjcnt[SVA[i].s]<=1 || adjcnt[SVA[i].t]<=1 ) { AV.push_back(make_pair( SVA[i].s, SVA[i].t) ); ++adjcnt[SVA[i].s]; ++adjcnt[SVA[i].t]; } ++i; } for(i=0;i<mn;++i) if(VM[i].used && adjcnt[i]==0) BNV.push_back(i); } void OccupancyGrid::RemoveMesh(int id) { MeshCounter *GridEnd=G.grid+G.size(); MeshCounter *ig; for(ig=G.grid;ig!=GridEnd;++ig) ig->UnSet(id); }
33.604895
163
0.517012
hlzz
c3a838b1b9a20f49df4a644f22c3613dd2e42bcb
158
cpp
C++
testcase/while_loop.cpp
ryanorz/srun
00080749fc7c1bff9c2ebb506bbbda23a893bf7c
[ "Apache-2.0" ]
7
2017-01-17T07:21:24.000Z
2017-02-26T17:24:02.000Z
testcase/while_loop.cpp
ryanorz/srun
00080749fc7c1bff9c2ebb506bbbda23a893bf7c
[ "Apache-2.0" ]
null
null
null
testcase/while_loop.cpp
ryanorz/srun
00080749fc7c1bff9c2ebb506bbbda23a893bf7c
[ "Apache-2.0" ]
null
null
null
#include <unistd.h> #include <stdio.h> int main() { int n = 0; while (1) { sleep(1); printf("while_loop %d\n", ++n); fflush(stdout); } return 0; }
11.285714
33
0.563291
ryanorz
c3a879bcd96ce698d083614a165c4a03598c6b93
13,193
cpp
C++
python_bindings/custom_cpp_cost_functions.cpp
goromal/ceres_python_bindings
f014ca0d367c0fcd7a244a067398dac363428a54
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
python_bindings/custom_cpp_cost_functions.cpp
goromal/ceres_python_bindings
f014ca0d367c0fcd7a244a067398dac363428a54
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
python_bindings/custom_cpp_cost_functions.cpp
goromal/ceres_python_bindings
f014ca0d367c0fcd7a244a067398dac363428a54
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/eigen.h> #include <pybind11/stl.h> #include <ceres/ceres.h> #include <Eigen/Core> #include <Eigen/Geometry> #include <sophus/se3.hpp> namespace py = pybind11; // Example autodiff cost function from ceres tutorial struct ExampleFunctor { template<typename T> bool operator()(const T *const x, T *residual) const { residual[0] = T(10.0) - x[0]; return true; } static ceres::CostFunction *Create() { return new ceres::AutoDiffCostFunction<ExampleFunctor, 1, 1>(new ExampleFunctor); } }; // cSE3 conversion functions: to/from pointer/vector template<typename T> void cSE3convert(const T* data, Sophus::SE3<T>& X) { X = Sophus::SE3<T>(Eigen::Quaternion<T>(data+3), Eigen::Map<const Eigen::Matrix<T,3,1>>(data)); } template<typename T> void cSE3convert(const Eigen::Matrix<T,7,1> &Xvec, Sophus::SE3<T>& X) { X = Sophus::SE3<T>(Eigen::Quaternion<T>(Xvec.data()+3), Eigen::Map<const Eigen::Matrix<T,3,1>>(Xvec.data())); } template<typename T> void cSE3convert(const Sophus::SE3<T>& X, Eigen::Matrix<T,7,1> &Xvec) { Xvec.template block<3,1>(0,0) = Eigen::Matrix<T,3,1>(X.translation().data()); Xvec.template block<4,1>(3,0) = Eigen::Matrix<T,4,1>(X.so3().data()); } // AutoDiff cost function (factor) for the difference between a measured 3D // relative transform, Xij = (tij_, qij_), and the relative transform between two // estimated poses, Xi_hat and Xj_hat. Weighted by measurement covariance, Qij_. class cSE3Functor { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW // store measured relative pose and inverted covariance matrix cSE3Functor(Eigen::Matrix<double,7,1> &Xij_vec, Eigen::Matrix<double,6,6> &Qij) { Sophus::SE3<double> Xij; cSE3convert(Xij_vec, Xij); Xij_inv_ = Xij.inverse(); Qij_inv_ = Qij.inverse(); } // templated residual definition for both doubles and jets // basically a weighted implementation of boxminus using Eigen templated types template<typename T> bool operator()(const T* _Xi_hat, const T* _Xj_hat, T* _res) const { // assign memory to usable objects Sophus::SE3<T> Xi_hat, Xj_hat; cSE3convert(_Xi_hat, Xi_hat); cSE3convert(_Xj_hat, Xj_hat); Eigen::Map<Eigen::Matrix<T,6,1>> r(_res); // compute current estimated relative pose const Sophus::SE3<T> Xij_hat = Xi_hat.inverse() * Xj_hat; // compute residual via boxminus (i.e., the logarithmic map of the error pose) // weight with inverse covariance r = Qij_inv_.cast<T>() * (Xij_inv_.cast<T>() * Xij_hat).log(); return true; } // cost function generator--ONLY FOR PYTHON WRAPPER static ceres::CostFunction *Create(Eigen::Matrix<double,7,1> &Xij, Eigen::Matrix<double,6,6> &Qij) { return new ceres::AutoDiffCostFunction<cSE3Functor, 6, 7, 7>(new cSE3Functor(Xij, Qij)); } private: Sophus::SE3<double> Xij_inv_; Eigen::Matrix<double,6,6> Qij_inv_; }; // AutoDiff cost function (factor) for the difference between a range measurement // rij, and the relative range between two estimated poses, Xi_hat and Xj_hat. // Weighted by measurement variance, qij_. class RangeFunctor { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW // store measured range and inverted variance RangeFunctor(double &rij, double &qij) { rij_ = rij; qij_inv_ = 1.0 / qij; } // templated residual definition for both doubles and jets template<typename T> bool operator()(const T* _Xi_hat, const T* _Xj_hat, T* _res) const { // assign memory to usable objects Eigen::Matrix<T,3,1> ti_hat(_Xi_hat), tj_hat(_Xj_hat); // range measurement error, scaled by inverse variance *_res = static_cast<T>(qij_inv_) * (static_cast<T>(rij_) - (tj_hat - ti_hat).norm()); return true; } // cost function generator--ONLY FOR PYTHON WRAPPER static ceres::CostFunction *Create(double &rij, double &qij) { return new ceres::AutoDiffCostFunction<RangeFunctor, 1, 7, 7>(new RangeFunctor(rij, qij)); } private: double rij_; double qij_inv_; }; // AutoDiff cost function (factor) for the difference between an altitude // measurement hi, and the altitude of an estimated pose, Xi_hat. // Weighted by measurement variance, qij_. class AltFunctor { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW // store measured range and inverted variance AltFunctor(double &hi, double &qi) { hi_ = hi; qi_inv_ = 1.0 / qi; } // templated residual definition for both doubles and jets template<typename T> bool operator()(const T* _Xi_hat, T* _res) const { // assign memory to usable objects T hi_hat = *(_Xi_hat + 2); // altitude measurement error, scaled by inverse variance *_res = static_cast<T>(qi_inv_) * (static_cast<T>(hi_) - hi_hat); return true; } // cost function generator--ONLY FOR PYTHON WRAPPER static ceres::CostFunction *Create(double &hi, double &qi) { return new ceres::AutoDiffCostFunction<AltFunctor, 1, 7>(new AltFunctor(hi, qi)); } private: double hi_; double qi_inv_; }; // AutoDiff cost function (factor) for the difference between a measured 3D // relative transform, Xij_ = (tij_, qij_), and the relative transform between two // estimated poses, Xi_hat and Xj_hat. Weighted by measurement covariance, Qij_. class Transform3DFunctor { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW // store measured relative pose and covariance matrix Transform3DFunctor(Eigen::Matrix<double,7,1> &X, Eigen::Matrix<double,6,6> &Q) { tij_ = X.block<3,1>(0,0); qij_ = Eigen::Quaterniond(X.block<4,1>(3,0)); // residual weighted by inverse covariance Wij_ = Q.inverse(); } // templated residual definition for both doubles and jets // basically a weighted implementation of boxminus using Eigen templated types template<typename T> bool operator()(const T* Xi_hat, const T* Xj_hat, T* res) const { // assign memory to usable objects Eigen::Map<const Eigen::Matrix<T,3,1>> ti_hat(Xi_hat); Eigen::Quaternion<T> qi_hat(Xi_hat+3); Eigen::Map<const Eigen::Matrix<T,3,1>> tj_hat(Xj_hat); Eigen::Quaternion<T> qj_hat(Xj_hat+3); Eigen::Map<Eigen::Matrix<T,6,1>> r(res); // compute trivial vector subtraction component Eigen::Matrix<T,3,1> t_res = tij_ - (tj_hat - ti_hat); // compute quaternion difference component Eigen::Quaternion<T> qij_hat = qi_hat.inverse() * qj_hat; Eigen::Quaternion<T> q_err = qij_hat.inverse() * static_cast<Eigen::Quaternion<T>>(qij_); Eigen::Matrix<T,3,1> q_res; if (q_err.w() < static_cast<T>(0.0)) { q_err.coeffs() *= static_cast<T>(-1.0); } const Eigen::Matrix<T,3,1> qv(q_err.vec()); T sinha = qv.norm(); if (sinha > static_cast<T>(0.0)) { T angle = static_cast<T>(2.0) * atan2(sinha, q_err.w()); q_res = qv * (angle / sinha); } else { q_res = qv * (static_cast<T>(2.0) / q_err.w()); } // assign to residual and weight by covariance r.template block<3,1>(0,0) = t_res; r.template block<3,1>(3,0) = q_res; r = Wij_ * r; return true; } // cost function generator--ONLY FOR PYTHON WRAPPER static ceres::CostFunction *Create(Eigen::Matrix<double,7,1> &X, Eigen::Matrix<double,6,6> &Q) { return new ceres::AutoDiffCostFunction<Transform3DFunctor, 6, 7, 7>(new Transform3DFunctor(X, Q)); } private: Eigen::Matrix<double,3,1> tij_; Eigen::Quaternion<double> qij_; Eigen::Matrix<double,6,6> Wij_; }; // AutoDiff cost function (factor) for the difference between a measured quaternion, // q_, and an estimated quaternion, q_hat. class QuaterniondFunctor { public: // store internal measured quaternion QuaterniondFunctor(Eigen::Vector4d &x) { q_ = Eigen::Quaternion<double>(x.data()); q_inv_ = q_.inverse(); } // templated residual definition for both doubles and jets template<typename T> bool operator()(const T* _q_hat, T* res) const { Eigen::Quaternion<T> q_hat(_q_hat); Eigen::Map<Eigen::Matrix<T, 3, 1>> r(res); // implementation of boxminus using templated Eigen types // https://eigen.tuxfamily.org/bz/show_bug.cgi?id=1244 // q_err = q^{-1} * q_hat Eigen::Quaternion<T> q_err(static_cast<Eigen::Quaternion<T>>(q_inv_)*(q_hat)); // q_err -> theta vector if (q_err.w() < static_cast<T>(0.0)) { q_err.coeffs() *= static_cast<T>(-1.0); } const Eigen::Matrix<T,3,1> qv(q_err.vec()); T sinha = qv.norm(); if (sinha > static_cast<T>(0.0)) { T angle = static_cast<T>(2.0) * atan2(sinha, q_err.w()); r = qv * (angle / sinha); } else { r = qv * (static_cast<T>(2.0) / q_err.w()); } return true; } // cost function generator--ONLY FOR PYTHON WRAPPER static ceres::CostFunction *Create(Eigen::Vector4d &x) { return new ceres::AutoDiffCostFunction<QuaterniondFunctor, 3, 4>(new QuaterniondFunctor(x)); } private: Eigen::Quaternion<double> q_; Eigen::Quaternion<double> q_inv_; }; // AutoDiff local parameterization for the compact SE3 pose [t q] object. // The boxplus operator informs Ceres how the manifold evolves and also // allows for the calculation of derivatives. struct cSE3Plus { // boxplus operator for both doubles and jets template<typename T> bool operator()(const T* x, const T* delta, T* x_plus_delta) const { // capture argument memory Sophus::SE3<T> X; cSE3convert(x, X); Eigen::Map<const Eigen::Matrix<T, 6, 1>> dX(delta); Eigen::Map<Eigen::Matrix<T, 7, 1>> Yvec(x_plus_delta); // increment pose using the exponential map Sophus::SE3<T> Exp_dX = Sophus::SE3<T>::exp(dX); Sophus::SE3<T> Y = X * Exp_dX; // assign SE3 coefficients to compact vector Eigen::Matrix<T,7,1> YvecCoef; cSE3convert(Y, YvecCoef); Yvec = YvecCoef; return true; } // local parameterization generator--ONLY FOR PYTHON WRAPPER static ceres::LocalParameterization *Create() { return new ceres::AutoDiffLocalParameterization<cSE3Plus, 7, 6>(new cSE3Plus); } }; // AutoDiff local parameterization for the Transform3D object. The boxplus // operator informs Ceres how the manifold evolves and also allows for the // calculation of derivatives struct Transform3DPlus { // boxplus operator for both doubles and jets template<typename T> bool operator()(const T* x, const T* delta, T* x_plus_delta) const { // capture argument memory Eigen::Map<const Eigen::Matrix<T, 3, 1>> t(x); Eigen::Map<const Eigen::Matrix<T, 3, 1>> dt(delta); const Eigen::Quaternion<T> q(x+3); Eigen::Map<const Eigen::Matrix<T, 3, 1>> dq(delta+3); Eigen::Map<Eigen::Matrix<T, 7, 1>> Tplus(x_plus_delta); // compute trivial vector addition component Tplus.template block<3,1>(0,0) = t + dt; // compute quaternion oplus component Eigen::Quaternion<T> plusq; T th = dq.norm(); if (th > static_cast<T>(0.0)) { Eigen::Matrix<T, 3, 1> u = dq / th; T sth2 = sin(th / static_cast<T>(2.0)); plusq = Eigen::Quaternion<T>(cos(th / static_cast<T>(2.0)), u.x()*sth2, u.y()*sth2, u.z()*sth2); } else { Eigen::Matrix<T, 3, 1> r2 = dq / static_cast<T>(2.0); plusq = Eigen::Quaternion<T>(static_cast<T>(1.0), r2.x(), r2.y(), r2.z()).normalized(); } Eigen::Quaternion<T> qplusq = q * plusq; Tplus.template block<4,1>(3,0) = qplusq.coeffs(); return true; } // local parameterization generator--ONLY FOR PYTHON WRAPPER static ceres::LocalParameterization *Create() { return new ceres::AutoDiffLocalParameterization<Transform3DPlus, 7, 6>(new Transform3DPlus); } }; void add_custom_cost_functions(py::module &m) { // Use pybind11 code to wrap your own cost function which is defined in C++ // Transform3DLocalParameterization m.def("Transform3DLocalParameterization", &Transform3DPlus::Create); // cSE3LocalParameterization m.def("cSE3LocalParameterization", &cSE3Plus::Create); // cSE3Factor m.def("cSE3Factor", &cSE3Functor::Create); // RangeFactor m.def("RangeFactor", &RangeFunctor::Create); // AltFactor m.def("AltFactor", &AltFunctor::Create); // Transform3DFactor m.def("Transform3DFactor", &Transform3DFunctor::Create); // Here is an example m.def("CreateCustomExampleCostFunction", &ExampleFunctor::Create); // QuaterniondFunctor m.def("CreateQuaterniondADCostFunction", &QuaterniondFunctor::Create); }
32.415233
102
0.636398
goromal
c3ac79593d612a9c9e6ad4eb3e97686fe7dce256
17,552
hpp
C++
filter/cuckoo_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
33
2021-08-29T00:19:14.000Z
2022-03-30T02:40:36.000Z
filter/cuckoo_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
null
null
null
filter/cuckoo_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
3
2021-09-09T11:34:35.000Z
2022-01-12T11:10:05.000Z
/* ** Modified from https://github.com/efficient/cuckoofilter ** (1) simplify the design ** (2) add serialize/deserialize interfaces ** Thanks discussions with Minglang Dong */ #ifndef KUNLUN_CUCKOO_FILTER_HPP #define KUNLUN_CUCKOO_FILTER_HPP #include "../include/std.inc" #include "../utility/murmurhash3.hpp" #include "../utility/bit_operation.hpp" #include "../crypto/ec_point.hpp" #include "../utility/print.hpp" // selection of keyed hash for cuckoo filter #define FastHash LiteMurmurHash enum InsertToBucketStatus { SuccessAndNoKick = 0, FreshInsertFailure = 1, SuccessButKick = 2, }; struct VictimCache{ uint32_t bucket_index; uint32_t tag; uint32_t used; // false or true }; // Cuckoo filter interfaces: Insert, Delete, Contain. class CuckooFilter{ public: // Storage of items std::vector<uint8_t> bucket_table; // number of inserted elements size_t inserted_element_num; size_t max_kick_count = 500; // maximum number of cuckoo kicks before claiming failure size_t slot_num = 4; // the slot num of each bucket size_t tag_bit_size = 16; size_t bucket_byte_size; size_t bucket_num; VictimCache victim; CuckooFilter() {}; CuckooFilter(size_t projected_element_num, double desired_false_positive_probability){ max_kick_count = 500; slot_num = 4; tag_bit_size = 16; bucket_byte_size = slot_num * tag_bit_size / 8; // bucket_num must be always a power of two bucket_num = upperpower2(std::max<uint32_t>(1, projected_element_num /slot_num)); double load_factor = (double)projected_element_num / (bucket_num * slot_num); if (load_factor > 0.96) { bucket_num = bucket_num * 2; } bucket_table.resize(bucket_num * slot_num * tag_bit_size / 8); memset(bucket_table.data(), 0, bucket_table.size()); inserted_element_num = 0; victim.used = 0; } ~CuckooFilter() {} size_t ObjectSize() { // hash_num + random_seed + table_size + table_content return 6 * 8 + bucket_table.size() + 4 * 3; } // index_1 = LEFT(Hash(x)) mod bucket_num serve as the first choice inline uint32_t ComputeBucketIndex(uint32_t hash_value) { // since bucket_num = 2^n, the following is equivalent to hash_value mod 2^n return hash_value & (bucket_num - 1); // fetch left 32 bit } inline uint32_t ComputeTag(uint32_t hash_value) { uint32_t tag; // set tag as the leftmost "tag_bit_size" part tag = hash_value >> (32 - tag_bit_size); tag += (tag == 0); // ensure tag is not zero return tag; } inline uint32_t ComputeAnotherBucketIndex(const uint32_t bucket_index, const uint32_t tag) { // index_2 = (index_1 XOR tag) mod bucket_num return (bucket_index ^ (tag * 0x5bd1e995)) & (bucket_num - 1); //return (bucket_index ^ FastHash(&tag, 4)) & (bucket_num - 1); } // Insert an item to the filter. // To make this procedure efficient, we omit the repetetion check // so, we need to ensure the inserted element // We also omit extra check when victim is being used // simply presume in that case the filter will be very dense bool PlainInsert(const void* input, size_t LEN){ if (victim.used){ std::cerr << "there is not enough space" << std::endl; return false; } uint32_t hash_value = FastHash(input, LEN); uint32_t current_bucket_index = ComputeBucketIndex(hash_value); uint32_t current_tag = ComputeTag(hash_value); // std::cout << "bucket index = " << std::hex << current_bucket_index << std::endl; // std::cout << "tag = " << std::hex << current_tag << std::endl; uint32_t kickout_tag = 0; bool licence_to_kickout = false; size_t kick_count = 0; int insert_to_bucket_status; while (kick_count < max_kick_count) { insert_to_bucket_status = InsertTagToBucket(current_bucket_index, current_tag, licence_to_kickout, kickout_tag); switch(insert_to_bucket_status){ case SuccessAndNoKick: inserted_element_num++; return true; case FreshInsertFailure: licence_to_kickout = true; break; case SuccessButKick: kick_count++; current_tag = kickout_tag; break; } current_bucket_index = ComputeAnotherBucketIndex(current_bucket_index, current_tag); } // if there is still kickout tag after MaxKickCount times kick, save it to victim cache victim.bucket_index = current_bucket_index; victim.tag = current_tag; victim.used = 1; return true; } template <typename ElementType> // Note: T must be a C++ POD type. inline bool Insert(const ElementType& element) { return PlainInsert(&element, sizeof(ElementType)); } inline bool Insert(const std::string& str) { return PlainInsert(str.data(), str.size()); } // You can insert any custom-type data you like as below inline bool Insert(const ECPoint &A) { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); return PlainInsert(buffer, POINT_BYTE_LEN); } inline bool Insert(const std::vector<ECPoint> &vec_A) { bool insert_status = true; size_t num = vec_A.size(); unsigned char *buffer = new unsigned char[num*POINT_BYTE_LEN]; for(auto i = 0; i < num; i++){ EC_POINT_point2oct(group, vec_A[i].point_ptr, POINT_CONVERSION_COMPRESSED, buffer+i*POINT_BYTE_LEN, POINT_BYTE_LEN, nullptr); if(PlainInsert(buffer+i*POINT_BYTE_LEN, POINT_BYTE_LEN) == false){ insert_status = false; break; } } delete[] buffer; return insert_status; } template <typename InputIterator> inline bool Insert(const InputIterator begin, const InputIterator end) { bool insert_status = true; InputIterator itr = begin; while (end != itr){ if(Insert(*(itr++)) == false){ insert_status = false; break; } } return insert_status; } template <class T, class Allocator, template <class,class> class Container> inline bool Insert(Container<T, Allocator>& container) { bool insert_status = true; for(auto i = 0; i < container.size(); i++){ if(Insert(container[i]) == false){ insert_status = false; std::cout << "insert the " << i << "-th element fails" << std::endl; break; } } return insert_status; } // Report if the item is inserted, with false positive rate. bool PlainContain(const void* input, size_t LEN) { uint32_t hash_value = FastHash(input, LEN); uint32_t index1 = ComputeBucketIndex(hash_value); uint32_t tag = ComputeTag(hash_value); uint32_t index2 = ComputeAnotherBucketIndex(index1, tag); // check if find in buckets if (FindTagInBucket(index1, tag)) return true; if (FindTagInBucket(index2, tag)) return true; // check if in victim.cache if (victim.used && (tag == victim.tag) && (index1 == victim.bucket_index || index2 == victim.bucket_index)) return true; return false; } template <typename ElementType> inline bool Contain(const ElementType& element) { return PlainContain(&element, sizeof(ElementType)); } inline bool Contain(const std::string& str) { return PlainContain(str.data(), str.size()); } inline bool Contain(const ECPoint& A) { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); return PlainContain(buffer, POINT_BYTE_LEN); } bool TrySaveVictim(uint32_t bucket_index, uint32_t slot_index, uint32_t tag) { if (victim.used && (victim.bucket_index == bucket_index) && (victim.tag == tag)) { victim.used = 0; WriteTag(bucket_index, slot_index, tag); return true; } return false; } // Delete an key from the filter bool PlainDelete(const void* input, size_t LEN) { bool delete_status = false; uint32_t hash_value = FastHash(input, LEN); uint32_t index1 = ComputeBucketIndex(hash_value); uint32_t tag = ComputeTag(hash_value); uint32_t index2 = ComputeAnotherBucketIndex(index1, tag); uint32_t delete_slot_index; if (DeleteTagFromBucket(index1, tag, delete_slot_index)) { inserted_element_num--; delete_status = true; TrySaveVictim(index1, delete_slot_index, tag); } if (DeleteTagFromBucket(index2, tag, delete_slot_index)) { inserted_element_num--; delete_status = true; TrySaveVictim(index2, delete_slot_index, tag); } if (victim.used && tag == victim.tag && (index1 == victim.bucket_index || index2 == victim.bucket_index)) { victim.used = 0; delete_status = true; } return delete_status; } template <typename ElementType> inline bool Delete(const ElementType& element) { return PlainDelete(&element, sizeof(ElementType)); } inline bool Delete(const std::string& str) { return PlainDelete(str.data(), str.size()); } inline bool Delete(const ECPoint& A) { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); return PlainDelete(buffer, POINT_BYTE_LEN); } // read tag from i-th bucket j-th slot inline uint32_t ReadTag(const size_t bucket_index, const size_t slot_index) { const uint8_t* ptr = bucket_table.data() + bucket_index * bucket_byte_size; uint32_t tag; /* following code only works for little-endian */ switch(tag_bit_size){ case 8: tag = ptr[slot_index]; break; case 16: ptr += (slot_index << 1); tag = *((uint16_t*)ptr); break; case 32: tag = ((uint32_t*)ptr)[slot_index]; break; } return tag; } // write tag to pos(i,j) inline void WriteTag(const size_t bucket_index, const size_t slot_index, const uint32_t tag) { const uint8_t *ptr = bucket_table.data() + bucket_index * bucket_byte_size; /* following code only works for little-endian */ switch(tag_bit_size){ case 8: ((uint8_t *)ptr)[slot_index] = tag; break; case 16: ((uint16_t *)ptr)[slot_index] = tag; break; case 32: ((uint32_t *)ptr)[slot_index] = tag; break; } } inline bool FindTagInBucket(const size_t bucket_index, const uint32_t tag) { // caution: unaligned access & assuming little endian const uint8_t *ptr = bucket_table.data() + bucket_index * bucket_byte_size; uint64_t v; switch(tag_bit_size){ case 8: v = *(uint32_t*)ptr; return hasvalue8(v, tag); case 16: v = *(uint64_t*)ptr; return hasvalue16(v, tag); default: for (auto slot_index = 0; slot_index < slot_num; slot_index++) { if (ReadTag(bucket_index, slot_index) == tag) return true; } } return false; } inline bool DeleteTagFromBucket(const size_t bucket_index, const uint32_t tag, uint32_t &delete_slot_index) { for (auto slot_index = 0; slot_index < slot_num; slot_index++) { if (ReadTag(bucket_index, slot_index) == tag) { WriteTag(bucket_index, slot_index, 0); delete_slot_index = slot_index; return true; } } return false; } inline InsertToBucketStatus InsertTagToBucket(const size_t bucket_index, const uint32_t tag, const bool licence_to_kickout, uint32_t &kickout_tag) { for (auto slot_index = 0; slot_index < slot_num; slot_index++) { if (ReadTag(bucket_index, slot_index) == 0) { WriteTag(bucket_index, slot_index, tag); return SuccessAndNoKick; } } // licence_to_kickout = true indicates the element must be add to this bucket // licence_to_kickout = false indicates this is a new element, and can be add to the alternative bucket if (licence_to_kickout == true) { size_t r = rand() % slot_num; kickout_tag = ReadTag(bucket_index, r); WriteTag(bucket_index, r, tag); return SuccessButKick; } // here, we must have licence_to_kickout == false return FreshInsertFailure; } inline bool WriteObject(std::string file_name){ std::ofstream fout; fout.open(file_name, std::ios::binary); if(!fout){ std::cerr << file_name << " open error" << std::endl; return false; } fout.write(reinterpret_cast<char *>(&inserted_element_num), 8); fout.write(reinterpret_cast<char *>(&max_kick_count), 8); fout.write(reinterpret_cast<char *>(&slot_num), 8); fout.write(reinterpret_cast<char *>(&tag_bit_size), 8); fout.write(reinterpret_cast<char *>(&bucket_byte_size), 8); fout.write(reinterpret_cast<char *>(&bucket_num), 8); fout.write(reinterpret_cast<char *>(&victim.bucket_index), 4); fout.write(reinterpret_cast<char *>(&victim.tag), 4); fout.write(reinterpret_cast<char *>(&victim.used), 4); fout.write(reinterpret_cast<char *>(bucket_table.data()), bucket_table.size()); fout.close(); #ifdef DEBUG std::cout << "'" <<file_name << "' size = " << ObjectSize() << " bytes" << std::endl; #endif return true; } inline bool ReadObject(std::string file_name){ std::ifstream fin; fin.open(file_name, std::ios::binary); if(!fin){ std::cerr << file_name << " open error" << std::endl; return false; } fin.read(reinterpret_cast<char *>(&inserted_element_num), 8); fin.read(reinterpret_cast<char *>(&max_kick_count), 8); fin.read(reinterpret_cast<char *>(&slot_num), 8); fin.read(reinterpret_cast<char *>(&tag_bit_size), 8); fin.read(reinterpret_cast<char *>(&bucket_byte_size), 8); fin.read(reinterpret_cast<char *>(&bucket_num), 8); fin.read(reinterpret_cast<char *>(&victim.bucket_index), 4); fin.read(reinterpret_cast<char *>(&victim.tag), 4); fin.read(reinterpret_cast<char *>(&victim.used), 4); bucket_table.resize(bucket_byte_size * bucket_num, static_cast<uint8_t>(0x00)); fin.read(reinterpret_cast<char *>(bucket_table.data()), bucket_table.size()); return true; } inline bool WriteObject(char* buffer){ if(buffer == nullptr){ std::cerr << "allocate memory for cuckoo filter fails" << std::endl; return false; } memcpy(buffer, &inserted_element_num, 8); memcpy(buffer+8, &max_kick_count, 8); memcpy(buffer+16, &slot_num, 8); memcpy(buffer+24, &tag_bit_size, 8); memcpy(buffer+32, &bucket_byte_size, 8); memcpy(buffer+40, &bucket_num, 8); memcpy(buffer+48, &victim.bucket_index, 4); memcpy(buffer+52, &victim.tag, 4); memcpy(buffer+66, &victim.used, 4); memcpy(buffer+60, bucket_table.data(), bucket_table.size()); return true; } inline bool ReadObject(char* buffer){ if(buffer == nullptr){ std::cerr << "allocate memory for cuckoo filter fails" << std::endl; return false; } memcpy(&inserted_element_num, buffer, 8); memcpy(&max_kick_count, buffer+8, 8); memcpy(&slot_num, buffer+16, 8); memcpy(&tag_bit_size, buffer+24, 8); memcpy(&bucket_byte_size, buffer+32, 8); memcpy(&bucket_num, buffer+40, 8); memcpy(&victim.bucket_index, buffer+48, 4); memcpy(&victim.tag, buffer+52, 4); memcpy(&victim.used, buffer+56, 4); bucket_table.resize(bucket_byte_size * bucket_num, static_cast<uint8_t>(0x00)); memcpy(bucket_table.data(), buffer+60, bucket_table.size()); return true; } /* methods for providing stats */ void PrintInfo() { PrintSplitLine('-'); std::cout << "CuckooFilter Status:" << std::endl; std::cout << "inserted element num = " << inserted_element_num << std::endl; std::cout << "load factor = " << 1.0 * inserted_element_num / (bucket_num * slot_num) << std::endl; std::cout << "bucket num = " << bucket_num << std::endl; std::cout << "hashtable size = " << (bucket_table.size() >> 10) << " KB" << std::endl; std::cout << "bits per element = " << double(bucket_table.size()) * 8 / inserted_element_num << std::endl; PrintSplitLine('-'); } }; #endif
35.387097
129
0.610529
yuchen1024
ce7bce35ffd69fa0ae6be4e09b10178988592c19
10,214
cc
C++
iocore/net/quic/qlog/QLogEvent.cc
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
1,351
2015-01-03T08:25:40.000Z
2022-03-31T09:14:08.000Z
iocore/net/quic/qlog/QLogEvent.cc
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
7,009
2015-01-14T16:22:45.000Z
2022-03-31T17:18:04.000Z
iocore/net/quic/qlog/QLogEvent.cc
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
901
2015-01-11T19:21:08.000Z
2022-03-18T18:21:33.000Z
/** @file * * A brief file description * * @section license License * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "QLogEvent.h" namespace QLog { void check_and_set(YAML::Node &node, std::string key, std::string val) { if (val.length() > 0) { node[key] = val; } } void check_and_set(YAML::Node &node, std::string key, std::vector<std::string> val) { if (val.size() > 0) { node[key] = val; } } template <typename T> void check_and_set(YAML::Node &node, std::string key, T val) { if (val) { node[key] = val; } } namespace Connectivity { void ServerListening::encode(YAML::Node &node) { check_and_set(node, "ip_v4", _ip_v4); check_and_set(node, "ip_v6", _ip_v6); check_and_set(node, "port_v4", _port_v4); check_and_set(node, "port_v6", _port_v6); check_and_set(node, "stateless_reset_required", _port_v6); check_and_set(node, "quic_version", _quic_version); check_and_set(node, "alpn_values", _alpn_values); } void ConnectionStarted::encode(YAML::Node &node) { check_and_set(node, "quic_version", _quic_version); check_and_set(node, "ip_version", _ip_version); check_and_set(node, "src_ip", _src_ip); check_and_set(node, "dst_ip", _dst_ip); check_and_set(node, "protocol", _protocol); check_and_set(node, "src_port", _src_port); check_and_set(node, "dst_port", _dst_port); check_and_set(node, "src_cid", _src_cid); check_and_set(node, "dst_cid", _dst_cid); check_and_set(node, "alpn_values", _alpn_values); } void ConnectionIdUpdated::encode(YAML::Node &node) { check_and_set(node, "src_old", _src_old); check_and_set(node, "src_new", _src_new); check_and_set(node, "dst_old", _dst_old); check_and_set(node, "dst_new", _dst_new); } void SpinBitUpdated::encode(YAML::Node &node) { check_and_set(node, "state", _state); } void ConnectionStateUpdated::encode(YAML::Node &node) { check_and_set(node, "new", static_cast<int>(_new)); check_and_set(node, "old", static_cast<int>(_old)); check_and_set(node, "trigger", trigger_name(_trigger)); } } // namespace Connectivity namespace Security { void KeyEvent::encode(YAML::Node &node) { node["key_type"] = static_cast<int>(_key_type); node["new"] = _new; check_and_set(node, "generation", _generation); check_and_set(node, "old", _old); check_and_set(node, "trigger", trigger_name(_trigger)); } } // namespace Security namespace Transport { void ParametersSet::encode(YAML::Node &node) { node["owner"] = _owner ? "local" : "remote"; check_and_set(node, "resumption_allowed", _resumption_allowed); check_and_set(node, "early_data_enabled", _early_data_enabled); check_and_set(node, "alpn", _alpn); check_and_set(node, "version", _version); check_and_set(node, "tls_cipher", _tls_cipher); check_and_set(node, "original_connection_id", _original_connection_id); check_and_set(node, "stateless_reset_token", _stateless_reset_token); check_and_set(node, "disable_active_migration", _disable_active_migration); check_and_set(node, "max_idle_timeout", _max_idle_timeout); check_and_set(node, "max_udp_payload_size", _max_udp_payload_size); check_and_set(node, "ack_delay_exponent", _ack_delay_exponent); check_and_set(node, "max_ack_delay", _max_ack_delay); check_and_set(node, "active_connection_id_limit", _active_connection_id_limit); check_and_set(node, "initial_max_data", _initial_max_data); check_and_set(node, "initial_max_stream_data_bidi_local", _initial_max_stream_data_bidi_local); check_and_set(node, "initial_max_stream_data_bidi_remote", _initial_max_stream_data_bidi_remote); check_and_set(node, "initial_max_stream_data_uni", _initial_max_stream_data_uni); check_and_set(node, "initial_max_streams_bidi", _initial_max_streams_bidi); check_and_set(node, "initial_max_streams_uni", _initial_max_streams_uni); if (_preferred_address.ip.length() > 0) { YAML::Node sub; check_and_set(sub, _preferred_address.ipv4 ? "ip_v4" : "ip_v6", _preferred_address.ip); check_and_set(sub, _preferred_address.ipv4 ? "port_v4" : "port_v6", _preferred_address.port); check_and_set(sub, "connection_id", _preferred_address.connection_id); check_and_set(sub, "stateless_reset_token", _preferred_address.stateless_reset_token); node["preferred_address"] = sub; } } void PacketEvent::encode(YAML::Node &node) { node["packet_type"] = _packet_type; for (auto &&it : this->_frames) { YAML::Node sub; it->encode(sub); node["frames"].push_back(sub); } check_and_set(node, "is_coalesced", _is_coalesced); check_and_set(node, "stateless_reset_token", _stateless_reset_token); check_and_set(node, "supported_version", _supported_version); check_and_set(node, "raw_encrypted", _raw_encrypted); check_and_set(node, "raw_decrypted", _raw_decrypted); check_and_set(node, "supported_version", _supported_version); check_and_set(node, "supported_version", trigger_name(_trigger)); node["header"]["packet_number"] = _header.packet_number; node["header"]["packet_size"] = _header.packet_size; node["header"]["payload_length"] = _header.payload_length; node["header"]["version"] = _header.version; node["header"]["scil"] = _header.scil; node["header"]["dcil"] = _header.dcil; node["header"]["scid"] = _header.scid; node["header"]["dcid"] = _header.dcid; } void PacketDropped::encode(YAML::Node &node) { node["packet_type"] = _packet_type; check_and_set(node, "packet_size", _packet_size); check_and_set(node, "raw", _raw); check_and_set(node, "trigger", trigger_name(_trigger)); } void PacketBuffered::encode(YAML::Node &node) { node["packet_type"] = _packet_type; check_and_set(node, "trigger", trigger_name(_trigger)); check_and_set(node, "packet_number", trigger_name(_trigger)); } void DatagramsEvent::encode(YAML::Node &node) { check_and_set(node, "count", _count); check_and_set(node, "byte_length", _byte_length); } void DatagramsDropped::encode(YAML::Node &node) { check_and_set(node, "byte_length", _byte_length); } void StreamStateUpdated::encode(YAML::Node &node) { node["new"] = static_cast<int>(_new); node["stream_id"] = _stream_id; // FIXME // node["stream_type"] = bidi ? "bidirectional" : "unidirectional"; // node["stream_side"] = "sending"; } void FrameProcessed::encode(YAML::Node &node) { for (auto &&it : _frames) { YAML::Node sub; it->encode(sub); node["frames"].push_back(sub); } } } // namespace Transport namespace Recovery { void ParametersSet::encode(YAML::Node &node) { check_and_set(node, "reordering_threshold", _reordering_threshold); check_and_set(node, "time_threshold", _time_threshold); check_and_set(node, "timer_granularity", _timer_granularity); check_and_set(node, "initial_rtt", _initial_rtt); check_and_set(node, "max_datagram_size", _max_datagram_size); check_and_set(node, "initial_congestion_window", _initial_congestion_window); check_and_set(node, "minimum_congestion_window", _minimum_congestion_window); check_and_set(node, "loss_reduction_factor", _loss_reduction_factor); check_and_set(node, "persistent_congestion_threshold", _persistent_congestion_threshold); } void MetricsUpdated::encode(YAML::Node &node) { check_and_set(node, "min_rtt", _min_rtt); check_and_set(node, "smoothed_rtt", _smoothed_rtt); check_and_set(node, "latest_rtt", _latest_rtt); check_and_set(node, "rtt_variance", _rtt_variance); check_and_set(node, "max_ack_delay", _max_ack_delay); check_and_set(node, "pto_count", _pto_count); check_and_set(node, "congestion_window", _congestion_window); check_and_set(node, "bytes_in_flight", _bytes_in_flight); check_and_set(node, "ssthresh", _ssthresh); check_and_set(node, "packets_in_flight", _packets_in_flight); check_and_set(node, "in_recovery", _in_recovery); check_and_set(node, "pacing_rate", _pacing_rate); } void CongestionStateUpdated::encode(YAML::Node &node) { node["new"] = state_to_string(_new); check_and_set(node, "old", state_to_string(_old)); check_and_set(node, "old", trigger_name(_trigger)); } void LossTimerUpdated::encode(YAML::Node &node) { node["timer_type"] = _timer_type_ack ? "ack" : "pto"; check_and_set(node, "event_type", event_type_name(_event_type)); check_and_set(node, "packet_number_space", _packet_number_space); if (_event_type == EventType::set) { check_and_set(node, "delta", _delta); } } void PacketLost::encode(YAML::Node &node) { node["packet_number"] = _packet_number; node["packet_type"] = _packet_type; check_and_set(node, "trigger", trigger_name(_trigger)); YAML::Node sub; _header.encode(sub); node["header"] = sub; for (auto &&it : _frames) { YAML::Node sub; it->encode(sub); node["frames"].push_back(sub); } } void MarkedForRetransmit::encode(YAML::Node &node) { for (auto &&it : _frames) { YAML::Node sub; it->encode(sub); node["frames"].push_back(sub); } } } // namespace Recovery } // namespace QLog
32.119497
101
0.698551
cmcfarlen
ce82ed132259bd302bb4bbcde281dff59033a932
1,230
cpp
C++
URI Online Judge/1367 - Ajude!/uri-1367.cpp
MarcoRhayden/Uri-Online-Judge
92bed9fd0e5455686d54500f8e36588d6518f1b3
[ "MIT" ]
1
2019-03-29T11:52:44.000Z
2019-03-29T11:52:44.000Z
URI Online Judge/1367 - Ajude!/uri-1367.cpp
MarcoRhayden/Uri-Online-Judge
92bed9fd0e5455686d54500f8e36588d6518f1b3
[ "MIT" ]
null
null
null
URI Online Judge/1367 - Ajude!/uri-1367.cpp
MarcoRhayden/Uri-Online-Judge
92bed9fd0e5455686d54500f8e36588d6518f1b3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void resultData(vector<string> identifier, vector<int> timeSbm, vector<string> result, int sbm) { vector<string> crt, inctr; int s = 0; int p = 0; for (int i = 0; i < sbm; ++i) { if (result[i].compare("correct") == 0) { s++; p += timeSbm[i]; crt.push_back(identifier[i]); } else { inctr.push_back(identifier[i]); } } for (int j = 0; j < inctr.size(); ++j) { if (find(crt.begin(), crt.end(), inctr[j]) != crt.end()) { p += 20; } } cout << s << " " << p << endl; } int main(int argc, char *argv[]) { int sbm, t; string str; vector<string> identifier; vector<int> timeSbm; vector<string> result; while ( (cin >> sbm) && (sbm != 0) ) { identifier.clear(); timeSbm.clear(); result.clear(); for (int x = 0; x < sbm; ++x) { cin >> str; identifier.push_back(str); cin >> t; timeSbm.push_back(t); cin >> str; result.push_back(str); } resultData(identifier, timeSbm, result, sbm); } return(0); }
24.117647
66
0.469919
MarcoRhayden
ce8c32476acb9549516cb83a98e56b2d8c6c5980
1,522
hpp
C++
dev/Basic/long/database/dao/IndvidualVehicleOwnershipLogsumDao.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
dev/Basic/long/database/dao/IndvidualVehicleOwnershipLogsumDao.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
dev/Basic/long/database/dao/IndvidualVehicleOwnershipLogsumDao.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
/* * IndvidualVehicleOwnershipLogsumDao.hpp * * Created on: Jan 20, 2016 * Author: gishara */ #pragma once #include "database/dao/SqlAbstractDao.hpp" #include "database/entity/IndvidualVehicleOwnershipLogsum.hpp" namespace sim_mob { namespace long_term { /** * Data Access Object to get individual logsums from datasource. */ class IndvidualVehicleOwnershipLogsumDao : public db::SqlAbstractDao<IndvidualVehicleOwnershipLogsum> { public: IndvidualVehicleOwnershipLogsumDao(db::DB_Connection& connection); virtual ~IndvidualVehicleOwnershipLogsumDao(); private: /** * Fills the given outObj with all values contained on Row. * @param result row with data to fill the out object. * @param outObj to fill. */ void fromRow(db::Row& result, IndvidualVehicleOwnershipLogsum& outObj); /** * Fills the outParam with all values to insert or update on datasource. * @param data to get values. * @param outParams to put the data parameters. * @param update tells if operation is an Update or Insert. */ void toRow(IndvidualVehicleOwnershipLogsum& data, db::Parameters& outParams, bool update); public: std::vector<IndvidualVehicleOwnershipLogsum*> getIndvidualVehicleOwnershipLogsumsByHHId(const long long householdId); }; } }
31.061224
129
0.634034
gusugusu1018
ce8db457e5ca9dad75bc10a04f0ebe641ba2559b
364
hpp
C++
include/socks5/detail/throw_error.hpp
xSHAD0Wx/libsocks5
a578033579ab9b3139e62aa4bf8ee72344ff2a30
[ "BSD-3-Clause" ]
null
null
null
include/socks5/detail/throw_error.hpp
xSHAD0Wx/libsocks5
a578033579ab9b3139e62aa4bf8ee72344ff2a30
[ "BSD-3-Clause" ]
null
null
null
include/socks5/detail/throw_error.hpp
xSHAD0Wx/libsocks5
a578033579ab9b3139e62aa4bf8ee72344ff2a30
[ "BSD-3-Clause" ]
null
null
null
#ifndef LIBSOCKS5_DETAIL_THROW_ERROR_HPP #define LIBSOCKS5_DETAIL_THROW_ERROR_HPP #include <boost/system/error_code.hpp> #include <boost/system/system_error.hpp> namespace socks5::detail { inline void throw_error(const boost::system::error_code &ec) { if (ec) { throw boost::system::system_error {ec}; } } } // namespace socks5::detail #endif
20.222222
62
0.741758
xSHAD0Wx
ce91ae694d0a886127026a86bae29615f735482a
3,447
inl
C++
20191112/perm_gen/perm_gen_base.inl
Goreli/DKMCPPM
a12401f6df8e3c0281d2efec18dcf4e330712023
[ "MIT" ]
3
2019-11-12T01:55:33.000Z
2021-05-07T14:58:22.000Z
20191112/perm_gen/perm_gen_base.inl
Goreli/DKMCPPM
a12401f6df8e3c0281d2efec18dcf4e330712023
[ "MIT" ]
null
null
null
20191112/perm_gen/perm_gen_base.inl
Goreli/DKMCPPM
a12401f6df8e3c0281d2efec18dcf4e330712023
[ "MIT" ]
null
null
null
/* perm_gen_base.inl This header file defines the PermutationGeneratorBase template class. Copyright(c) 2019 David Krikheli Modification history: 14/Nov/2019 - David Krikheli created the module. */ #include <algorithm> namespace dk { template <class T> PermutationGeneratorBase<T>::PermutationGeneratorBase() : bExcludeDups_{ false }, bRandom_{ false } { try { auto iSeed = std::random_device{}(); _randNumGen.seed(iSeed); } catch (...) { auto iSeed = std::chrono::system_clock::now().time_since_epoch().count(); _randNumGen.seed(iSeed); } } template <class T> PermutationGeneratorBase<T>::~PermutationGeneratorBase() { } template <class T> void PermutationGeneratorBase<T>::generate(const std::vector<T>& symbolPool, bool bExcludeDups, size_t iRandPermAlgId) { permutation_.resize(symbolPool.size()); symbolPool_ = symbolPool; switch (iRandPermAlgId) { case 0: bExcludeDups_ = bExcludeDups; bRandom_ = false; generate_(0); break; case 1: bExcludeDups_ = bExcludeDups; bRandom_ = true; generate_(0); break; case 2: // bExcludeDups_ and bRandom_ have no effect on generate_R2_R3_(....). generate_R2_R3_(0); break; case 3: // bExcludeDups_ and bRandom_ have no effect on generate_R2_R3_(....). generate_R2_R3_(1); break; } } template <class T> void PermutationGeneratorBase<T>::generate_(size_t iPos) { size_t vocSize = symbolPool_.size(); std::uniform_int_distribution<size_t> dist(0, vocSize-1); size_t inx{ 0 }; for (size_t _inx_ = 0; _inx_ < symbolPool_.size(); _inx_++) { if(bRandom_) inx = dist(_randNumGen); else { inx = _inx_; if (bExcludeDups_) { auto it = symbolPool_.begin() + inx; auto findIt = std::find(symbolPool_.begin(), it, *it); if (findIt != it) continue; } } permutation_[iPos] = symbolPool_[inx]; // If the call stack has hit the bottom of recursion tree then // process the permutation and move on to the next recursion cycle. // Otherwise just keep drilling down. if (vocSize == 1) process_(permutation_); else { symbolPool_.erase(symbolPool_.begin() + inx); generate_(iPos + 1); symbolPool_.insert(symbolPool_.begin() + inx, permutation_[iPos]); // The following piece of code ran perfectly ok when compiled with clang++ // on the Ubuntu subsystem of Windows 10. It crashed when compiled with // VS 2019 on Windows 10. /* it = symbolPool_.erase(it); generate_nodups_(iPos + 1); symbolPool_.insert(it, permutation_[iPos]); */ } } } template <class T> void PermutationGeneratorBase<T>::generate_l(const std::vector<T>& symbolPool, bool bAscending) { permutation_ = symbolPool; if (bAscending) do process_(permutation_); while (std::next_permutation(permutation_.begin(), permutation_.end())); else do process_(permutation_); while (std::prev_permutation(permutation_.begin(), permutation_.end())); } template <class T> void PermutationGeneratorBase<T>::generate_R2_R3_(size_t iOffset) { size_t vocSize = symbolPool_.size(); permutation_ = symbolPool_; size_t j{ 0 }; while (true) { for (size_t i = 0; i < vocSize - 1; i++) { std::uniform_int_distribution<size_t> dist(i + iOffset, vocSize - 1); j = dist(_randNumGen); iter_swap(permutation_.begin() + i, permutation_.begin() + j); } process_(permutation_); } } }; // namespace dk
27.576
121
0.680012
Goreli
ce91e6b161b565ceae74631230feb116cb1681a1
3,515
cpp
C++
src/libsocket/event.cpp
publiqnet/belt.pp
837112652885284cd0f8245b1c9cf31dcfad17e1
[ "MIT" ]
4
2017-11-24T09:47:18.000Z
2019-02-18T14:43:05.000Z
src/libsocket/event.cpp
publiqnet/belt.pp
837112652885284cd0f8245b1c9cf31dcfad17e1
[ "MIT" ]
1
2018-04-11T12:42:25.000Z
2018-04-11T12:42:25.000Z
src/libsocket/event.cpp
publiqnet/belt.pp
837112652885284cd0f8245b1c9cf31dcfad17e1
[ "MIT" ]
2
2019-01-10T14:11:28.000Z
2021-05-31T11:14:46.000Z
#include "event.hpp" #include <mutex> #include <unordered_set> namespace beltpp_socket_impl { using namespace beltpp; using std::unordered_set; event_handler_ex::event_handler_ex() : m_impl() { } event_handler_ex::~event_handler_ex() = default; event_handler_ex::wait_result event_handler_ex::wait(std::unordered_set<event_item const*>& set_items) { set_items.clear(); m_impl.m_event_item_ids.clear(); for (auto& event_item_in_set : m_impl.m_event_items) { event_item_in_set->prepare_wait(); } if (m_impl.m_timer_helper.expired()) { m_impl.m_timer_helper.update(); return event_handler_ex::timer_out; } std::unordered_set<uint64_t> set_ids; { std::lock_guard<std::mutex> lock(m_impl.m_mutex); auto it = m_impl.sync_eh_ids.begin(); if (it != m_impl.sync_eh_ids.end()) { set_ids.insert(*it); m_impl.sync_eh_ids.erase(it); } } bool on_demand = false; if (set_ids.empty()) set_ids = m_impl.m_poll_master.wait(m_impl.m_timer_helper, on_demand); std::lock_guard<std::mutex> lock(m_impl.m_mutex); auto it = set_ids.begin(); while (it != set_ids.end()) { auto id = *it; bool found = false; for (auto const& ids_item : m_impl.m_ids) { if (ids_item.valid_index(id)) { auto& ref_item = ids_item[id]; event_item* pitem = ref_item.m_pitem; set_items.insert(pitem); found = true; auto& item = m_impl.m_event_item_ids[pitem]; item.insert(ref_item.m_item_id); break; } } if (false == found) it = set_ids.erase(it); else ++it; } bool on_timer = m_impl.m_timer_helper.expired(); bool on_event = (false == set_ids.empty()); if (on_timer) m_impl.m_timer_helper.update(); if (false == on_demand && false == on_timer && false == on_event) return event_handler_ex::nothing; if (on_demand && false == on_timer && false == on_event) return event_handler_ex::on_demand; if (false == on_demand && on_timer && false == on_event) return event_handler_ex::timer_out; if (false == on_demand && false == on_timer && on_event) return event_handler_ex::event; if (on_demand && on_timer && false == on_event) return event_handler_ex::on_demand_and_timer_out; if (on_demand && false == on_timer && on_event) return event_handler_ex::on_demand_and_event; if (false == on_demand && on_timer && on_event) return event_handler_ex::timer_out_and_event; /*if (on_demand && on_timer && on_event)*/ return event_handler_ex::on_demand_and_timer_out_and_event; } std::unordered_set<uint64_t> event_handler_ex::waited(event_item& ev_it) const { return m_impl.m_event_item_ids.at(&ev_it); } void event_handler_ex::wake() { m_impl.m_poll_master.wake(); } void event_handler_ex::set_timer(std::chrono::steady_clock::duration const& period) { m_impl.m_timer_helper.set(period); } void event_handler_ex::add(event_item& ev_it) { m_impl.m_event_items.insert(&ev_it); } void event_handler_ex::remove(event_item& ev_it) { m_impl.m_event_items.erase(&ev_it); } }// beltpp_socket_impl
23.75
102
0.609388
publiqnet
ce94f263e66f74d2c46fcfd0c7437d69dd1aef6b
1,709
cc
C++
src/map_object.cc
cipherboy/COMS-327
c21d653a86a9e83ed2b97b61539094bba9491770
[ "BSD-2-Clause" ]
null
null
null
src/map_object.cc
cipherboy/COMS-327
c21d653a86a9e83ed2b97b61539094bba9491770
[ "BSD-2-Clause" ]
null
null
null
src/map_object.cc
cipherboy/COMS-327
c21d653a86a9e83ed2b97b61539094bba9491770
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright 2016 Alexander Scheel * * Map objects implementation file **/ #include <stdlib.h> #include <stdio.h> #include "map.h" #include "object.h" #include "map_object.h" #include "utils.h" void map_objects_init(map_c* current) { current->object_count = 35 + (rand() % 15); current->objects = (object_t**) malloc(sizeof(object_t*) * 1); current->objects[0] = NULL; int added = 1; for (int i = 0; i < current->object_count; i++) { int factory = rand() % current->object_factory_count; object_t* object = current->object_factories[factory]->make_widget(); int room = rand() % current->room_count; int pos_x = current->rooms[room].pos_x + 1 + rand() % (current->rooms[room].width-2); int pos_y = current->rooms[room].pos_y + 1 + rand() % (current->rooms[room].height-2); object->pos_x = pos_x; object->pos_y = pos_y; if (current->objects_location[pos_y][pos_x] == NULL) { current->objects[added-1] = object; current->objects_location[pos_y][pos_x] = object; added += 1; current->objects = (object_t**) realloc(current->objects, sizeof(object_t*) * (added)); current->objects[added-1] = NULL; } else { if (!current->objects_location[pos_y][pos_x]->add_to_stack(object)) { printf("Error adding object to stack...\n"); } } } current->object_count = added; } void map_objects_deinit(map_c* current) { for (int i = 0; i < current->object_count; i++) { if (current->objects[i] != NULL) { delete current->objects[i]; } } free(current->objects); }
27.126984
99
0.583967
cipherboy
ce955d4bcc6bd15db19b0f8269338eda4c626d55
2,310
cpp
C++
src/iksdl/Renderer.cpp
InternationalKoder/iksdl
066a60b405bab5310a500132b0bd4d82c6476f24
[ "Zlib" ]
null
null
null
src/iksdl/Renderer.cpp
InternationalKoder/iksdl
066a60b405bab5310a500132b0bd4d82c6476f24
[ "Zlib" ]
null
null
null
src/iksdl/Renderer.cpp
InternationalKoder/iksdl
066a60b405bab5310a500132b0bd4d82c6476f24
[ "Zlib" ]
null
null
null
/* * IKSDL - C++ wrapper for SDL * Copyright (C) 2021 InternationalKoder * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * */ #include "iksdl/Renderer.hpp" #include "iksdl/SdlException.hpp" #include <SDL.h> #include <string> namespace iksdl { Renderer::Renderer(SDL_Window& window, const RendererOptions& options) : m_renderer(nullptr) { m_renderer = SDL_CreateRenderer(&window, -1, options.m_sdlFlags); if(m_renderer == nullptr) throw SdlException(std::string(CREATE_RENDERER_ERROR) + SDL_GetError()); } Renderer::Renderer(Renderer&& other) : m_renderer(std::exchange(other.m_renderer, nullptr)), m_viewport(std::move(other.m_viewport)) {} Renderer::~Renderer() { SDL_DestroyRenderer(m_renderer); } Renderer& Renderer::operator=(Renderer&& other) { if(this == &other) return *this; SDL_DestroyRenderer(m_renderer); m_renderer = std::exchange(other.m_renderer, nullptr); m_viewport = std::move(other.m_viewport); return *this; } void Renderer::clear(const Color& clearColor) const { SDL_SetRenderDrawColor(m_renderer, clearColor.getRed(), clearColor.getGreen(), clearColor.getBlue(), clearColor.getAlpha()); SDL_RenderClear(m_renderer); } void Renderer::setViewport(const Recti& viewport) { m_viewport = { .x = viewport.getX(), .y = viewport.getY(), .w = viewport.getWidth(), .h = viewport.getHeight() }; SDL_RenderSetViewport(m_renderer, &m_viewport); } }
30.8
82
0.709524
InternationalKoder
ce957028c1714864476a0912d2af3718adf7e764
1,203
cpp
C++
src/phase_cong/ipermute.cpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
1
2020-06-12T13:30:56.000Z
2020-06-12T13:30:56.000Z
src/phase_cong/ipermute.cpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
src/phase_cong/ipermute.cpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
// // Academic License - for use in teaching, academic research, and meeting // course requirements at degree granting institutions only. Not for // government, commercial, or other organizational use. // File: ipermute.cpp // // MATLAB Coder version : 3.0 // C/C++ source code generated on : 27-Jan-2016 06:44:05 // // Include Files #include "rt_nonfinite.h" #include "logGaborFilter.h" #include "phasecong.h" #include "ipermute.h" #include "logGaborFilter_emxutil.h" // Function Definitions // // Arguments : const emxArray_creal_T *b // emxArray_creal_T *a // Return Type : void // void ipermute(const emxArray_creal_T *b, emxArray_creal_T *a) { int i6; int loop_ub; int b_loop_ub; int i7; i6 = a->size[0] * a->size[1]; a->size[0] = b->size[1]; a->size[1] = b->size[0]; emxEnsureCapacity((emxArray__common *)a, i6, (int)sizeof(creal_T)); loop_ub = b->size[0]; for (i6 = 0; i6 < loop_ub; i6++) { b_loop_ub = b->size[1]; for (i7 = 0; i7 < b_loop_ub; i7++) { a->data[i7 + a->size[0] * i6] = b->data[i6 + b->size[0] * i7]; } } } // // File trailer for ipermute.cpp // // [EOF] //
24.55102
74
0.600998
waterben
ce95ef89b50c5889cf42c95d259cca39f19c101a
1,394
cpp
C++
platform-io/lib/zeromq/src/zeromq/ZeroMQWriter.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
2
2020-01-13T07:32:50.000Z
2020-03-03T14:32:25.000Z
platform-io/lib/zeromq/src/zeromq/ZeroMQWriter.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
16
2019-06-16T05:51:02.000Z
2020-02-03T01:59:23.000Z
platform-io/lib/zeromq/src/zeromq/ZeroMQWriter.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
1
2020-03-03T14:32:27.000Z
2020-03-03T14:32:27.000Z
// // Created by Ivan Kishchenko on 05.09.2021. // #include "ZeroMQWriter.h" #include "ZeroMQFlag.h" std::error_code ZeroMQWriter::writeData(const void *data, std::size_t size) { write((const char*)data, size); if (!(*this)) { return std::make_error_code(std::errc::message_size); } return {}; } std::error_code ZeroMQWriter::writeFlag(uint8_t flag) { return writeData(&flag, sizeof(uint8_t)); } std::error_code ZeroMQWriter::writeFlagAndSize(uint8_t flags, uint64_t size) { if (size > UINT8_MAX) { flags |= flag_long; } if (auto err = writeFlag(flags)) { return err; } if (size > UINT8_MAX) { if (auto err = writeSize((uint64_t) size)) { return err; } } else { if (auto err = writeSize((uint8_t) size)) { return err; } } return {}; } std::error_code ZeroMQWriter::writeSize(uint8_t size) { return writeData(&size, sizeof(uint8_t)); } std::error_code ZeroMQWriter::writeSize(uint32_t size) { size = ZeroMQUtils::swapEndian(size); return writeData(&size, sizeof(uint32_t)); } std::error_code ZeroMQWriter::writeSize(uint64_t size) { size = ZeroMQUtils::swapEndian(size); return writeData(&size, sizeof(uint64_t)); } std::error_code ZeroMQWriter::writeString(const std::string& str) { return writeData(str.data(), str.size()); }
23.627119
78
0.637016
darvik80
ce96d8634af00facb457d9d8755a1fd50f15cb05
2,575
cpp
C++
aws-cpp-sdk-awstransfer/source/model/WorkflowStep.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-awstransfer/source/model/WorkflowStep.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-awstransfer/source/model/WorkflowStep.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/awstransfer/model/WorkflowStep.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Transfer { namespace Model { WorkflowStep::WorkflowStep() : m_type(WorkflowStepType::NOT_SET), m_typeHasBeenSet(false), m_copyStepDetailsHasBeenSet(false), m_customStepDetailsHasBeenSet(false), m_deleteStepDetailsHasBeenSet(false), m_tagStepDetailsHasBeenSet(false) { } WorkflowStep::WorkflowStep(JsonView jsonValue) : m_type(WorkflowStepType::NOT_SET), m_typeHasBeenSet(false), m_copyStepDetailsHasBeenSet(false), m_customStepDetailsHasBeenSet(false), m_deleteStepDetailsHasBeenSet(false), m_tagStepDetailsHasBeenSet(false) { *this = jsonValue; } WorkflowStep& WorkflowStep::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Type")) { m_type = WorkflowStepTypeMapper::GetWorkflowStepTypeForName(jsonValue.GetString("Type")); m_typeHasBeenSet = true; } if(jsonValue.ValueExists("CopyStepDetails")) { m_copyStepDetails = jsonValue.GetObject("CopyStepDetails"); m_copyStepDetailsHasBeenSet = true; } if(jsonValue.ValueExists("CustomStepDetails")) { m_customStepDetails = jsonValue.GetObject("CustomStepDetails"); m_customStepDetailsHasBeenSet = true; } if(jsonValue.ValueExists("DeleteStepDetails")) { m_deleteStepDetails = jsonValue.GetObject("DeleteStepDetails"); m_deleteStepDetailsHasBeenSet = true; } if(jsonValue.ValueExists("TagStepDetails")) { m_tagStepDetails = jsonValue.GetObject("TagStepDetails"); m_tagStepDetailsHasBeenSet = true; } return *this; } JsonValue WorkflowStep::Jsonize() const { JsonValue payload; if(m_typeHasBeenSet) { payload.WithString("Type", WorkflowStepTypeMapper::GetNameForWorkflowStepType(m_type)); } if(m_copyStepDetailsHasBeenSet) { payload.WithObject("CopyStepDetails", m_copyStepDetails.Jsonize()); } if(m_customStepDetailsHasBeenSet) { payload.WithObject("CustomStepDetails", m_customStepDetails.Jsonize()); } if(m_deleteStepDetailsHasBeenSet) { payload.WithObject("DeleteStepDetails", m_deleteStepDetails.Jsonize()); } if(m_tagStepDetailsHasBeenSet) { payload.WithObject("TagStepDetails", m_tagStepDetails.Jsonize()); } return payload; } } // namespace Model } // namespace Transfer } // namespace Aws
21.280992
93
0.744078
perfectrecall
ce97384dc5744247b8b1dab531cfa7e46c727497
1,079
cc
C++
mime1836_sigmaic256_bg00/species_advance/advance_p_efield.cc
laofei177/vpic_reconnection_tutorial
7ba13578fe34615a118f3d98446ea94ad2b3d188
[ "MIT" ]
1
2021-03-31T11:44:29.000Z
2021-03-31T11:44:29.000Z
mime1836_sigmaic256_bg00/species_advance/advance_p_efield.cc
xiaocanli/vpic_reconnection_tutorial
05ff2372404717a548066f4a5fd8bbeb1407b30a
[ "MIT" ]
null
null
null
mime1836_sigmaic256_bg00/species_advance/advance_p_efield.cc
xiaocanli/vpic_reconnection_tutorial
05ff2372404717a548066f4a5fd8bbeb1407b30a
[ "MIT" ]
1
2021-03-31T11:48:43.000Z
2021-03-31T11:48:43.000Z
/* #define IN_spa */ #include "species_advance_efield.h" //----------------------------------------------------------------------------// // Top level function to select and call particle advance function using the // desired particle advance abstraction. Currently, the only abstraction // available is the pipeline abstraction. Particles advanced by this function // experience only part of electric field and have no feedback to the fields. // efield_type=0: without parallel electric field // efield_type=1: without the y-component of parallel electric field // efield_type=2: without electric field in regions where |E|>|B| //----------------------------------------------------------------------------// void advance_p_efield( species_t * RESTRICT sp, accumulator_array_t * RESTRICT aa, const interpolator_array_t * RESTRICT ia, const int efield_type ) { // Once more options are available, this should be conditionally executed // based on user choice. advance_p_efield_pipeline( sp, aa, ia, efield_type ); }
43.16
80
0.623726
laofei177
ce9965984c806989b9fa18c73cf2a5cdaf84e800
2,297
cpp
C++
demo/saxpy/scalar/saxpy_scalar.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
demo/saxpy/scalar/saxpy_scalar.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
demo/saxpy/scalar/saxpy_scalar.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2014 MetaScale SAS // // 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 //============================================================================== #include <boost/fusion/include/at.hpp> #include <vector> #include <nt2/sdk/bench/benchmark.hpp> #include <nt2/sdk/bench/metric/gflops.hpp> #include <nt2/sdk/bench/protocol/max_duration.hpp> #include <nt2/sdk/bench/setup/geometric.hpp> #include <nt2/sdk/bench/setup/constant.hpp> #include <nt2/sdk/bench/setup/combination.hpp> #include <nt2/sdk/bench/stats/median.hpp> using namespace nt2::bench; using namespace nt2; template<typename T> struct axpy_scalar { typedef void experiment_is_immutable; template<typename Setup> axpy_scalar(Setup const& s) : size_(boost::fusion::at_c<0>(s)) , alpha(boost::fusion::at_c<1>(s)) { X.resize(size_); Y.resize(size_); for(std::size_t i = 0; i<size_; ++i) X[i] = Y[i] = T(i); } void operator()() { for(std::size_t i = 0; i<size_; i++) Y[i] = Y[i] + alpha*(X[i]); } friend std::ostream& operator<<(std::ostream& os, axpy_scalar<T> const& p) { return os << "(" << p.size() << ")"; } std::size_t size() const { return size_; } double flops() const { return 2.*size_; } private: std::size_t size_; T alpha; std::vector<T> X, Y; }; NT2_REGISTER_BENCHMARK_TPL( axpy_scalar, NT2_SIMD_REAL_TYPES ) { std::size_t size_min = args("size_min", 16); std::size_t size_max = args("size_max", 4096); std::size_t size_step = args("size_step", 2); T alpha = args("alpha", 1.); run_during_with< axpy_scalar<T> > ( 1. , and_( geometric(size_min,size_max,size_step) , constant(alpha) ) , gflops<stats::median_>() ); }
31.902778
82
0.538964
psiha
ce9b78cefa498828e70c02d708f5b467e494b08e
902
cpp
C++
Advanced-Programming/Lab-2/main.cpp
hstr2785/CS
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
[ "MIT" ]
null
null
null
Advanced-Programming/Lab-2/main.cpp
hstr2785/CS
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
[ "MIT" ]
1
2020-09-25T17:04:57.000Z
2020-09-25T17:04:57.000Z
Advanced-Programming/Lab-2/main.cpp
hstr2785/CS
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
[ "MIT" ]
2
2020-10-01T05:01:38.000Z
2020-10-01T08:11:50.000Z
#include<iostream> #include<string.h> using namespace std; class elective { private: int code; int capacity; int reserved; public: elective(int code, int capacity, int reserved); void printStatus(); void add(int n); void reduce(int n); }; void elective::printStatus() { float percentage; percentage = (((this->reserved)*100)/(this->capacity)); cout<<"Elective "<<this->code<<": "<<this->reserved<<"/"<<this->capacity<<" ("<<percentage<<"%) seats allotted\n"; } elective::elective(int c, int ca, int r) { code = c; capacity = ca; reserved = r; } int main() { int reserved = 0, capacity = 0; cout << "Provide elective capacity: "; cin >> capacity; cout << "Provide number of reserved seats: "; cin >> reserved; elective booking(1, capacity, reserved); booking.printStatus(); return 0; }
20.976744
118
0.59867
hstr2785
ce9bc8e8548eae2f6a3c556434c93481db45e62e
15,716
cpp
C++
src/hash.cpp
eval-apply/digamma
fbab05bdcb7019ff005ee84ed8f737ff3d44b38e
[ "BSD-2-Clause" ]
null
null
null
src/hash.cpp
eval-apply/digamma
fbab05bdcb7019ff005ee84ed8f737ff3d44b38e
[ "BSD-2-Clause" ]
null
null
null
src/hash.cpp
eval-apply/digamma
fbab05bdcb7019ff005ee84ed8f737ff3d44b38e
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2004-2022 Yoshikatsu Fujita / LittleWing Company Limited. // See LICENSE file for terms and conditions of use. #include "core.h" #include "hash.h" #include "arith.h" #include "equiv.h" #include "utf8.h" #define EQUAL_HASH_DEPTH_LIMIT 100 uint32_t address_hash1(void* adrs, uint32_t bound) { return (((uintptr_t)adrs >> 3) * 2654435761U + ((uintptr_t)adrs & 7)) % bound; } uint32_t address_hash2(void* adrs, uint32_t bound) { uint32_t hash = (((uintptr_t)adrs >> 3) * 13845163U) % bound; return hash + (hash == 0); } uint32_t string_hash1(const char* str, uint32_t bound) { int hash = 107; while (*str) hash = hash * 32 - hash + (*str++); return hash % bound; } uint32_t string_hash2(const char* str, uint32_t bound) { int hash = 131; while (*str) hash = hash * 4 + hash + (*str++); hash = hash % bound; return hash + (hash == 0); } static uint32_t eqv_hash1(scm_obj_t obj, uint32_t bound) { if (CELLP(obj)) { if (FLONUMP(obj)) { scm_flonum_t flonum = (scm_flonum_t)obj; assert(sizeof(flonum->value) == 8); uint32_t* datum = (uint32_t*)(&flonum->value); return (datum[0] + datum[1] * 5) % bound; } if (BIGNUMP(obj)) { scm_bignum_t bignum = (scm_bignum_t)obj; int count = bn_get_count(bignum); uint32_t hash = bn_get_sign(bignum) + count * 5; if (sizeof(digit_t) == sizeof(uint32_t)) { for (int i = 0; i < count; i++) hash = hash * 5 + bignum->elts[i]; } else { for (int i = 0; i < count; i++) { hash = hash * 5 + (bignum->elts[i] & 0xffffffff) + ((uint64_t)bignum->elts[i] >> 32); } } return hash % bound; } if (RATIONALP(obj)) { scm_rational_t rational = (scm_rational_t)obj; uint32_t hash; hash = eqv_hash(rational->nume, INT32_MAX) * 5 - eqv_hash(rational->deno, INT32_MAX); return hash % bound; } if (COMPLEXP(obj)) { scm_complex_t complex = (scm_complex_t)obj; uint32_t hash; hash = eqv_hash(complex->real, INT32_MAX) * 5 + eqv_hash(complex->imag, INT32_MAX); return hash % bound; } } return address_hash1(obj, bound); } static uint32_t eqv_hash2(scm_obj_t obj, uint32_t bound) { if (CELLP(obj)) { if (FLONUMP(obj)) { scm_flonum_t flonum = (scm_flonum_t)obj; assert(sizeof(flonum->value) == 8); uint32_t* datum = (uint32_t*)(&flonum->value); uint32_t hash = (datum[0] + datum[1] * 3) % bound; return hash + (hash == 0); } if (BIGNUMP(obj)) { scm_bignum_t bignum = (scm_bignum_t)obj; int count = bn_get_count(bignum); uint32_t hash = bn_get_sign(bignum) + count * 3; if (sizeof(digit_t) == sizeof(uint32_t)) { for (int i = 0; i < count; i++) hash = hash * 3 + bignum->elts[i]; } else { for (int i = 0; i < count; i++) { hash = hash * 3 + (bignum->elts[i] & 0xffffffff) + ((uint64_t)bignum->elts[i] >> 32); } } hash = hash % bound; return hash + (hash == 0); } if (RATIONALP(obj)) { scm_rational_t rational = (scm_rational_t)obj; uint32_t hash = eqv_hash2(rational->nume, INT32_MAX) * 3 - eqv_hash2(rational->deno, INT32_MAX); hash = hash % bound; return hash + (hash == 0); } if (COMPLEXP(obj)) { scm_complex_t complex = (scm_complex_t)obj; uint32_t hash = eqv_hash2(complex->real, INT32_MAX) * 3 + eqv_hash2(complex->imag, INT32_MAX); hash = hash % bound; return hash + (hash == 0); } } return address_hash2(obj, bound); } static uint32_t obj_hash(scm_obj_t obj, int depth) { if (depth > EQUAL_HASH_DEPTH_LIMIT) return 1; if (CELLP(obj)) { if (PAIRP(obj)) { uint32_t hash1 = obj_hash(CAR(obj), depth + 1); uint32_t hash2 = obj_hash(CDR(obj), depth + 1); return (hash1 + hash2 * 64 - hash2); } if (VECTORP(obj)) { scm_vector_t vector = (scm_vector_t)obj; int n = vector->count; scm_obj_t* elts = vector->elts; uint32_t hash = 1; for (int i = 0; i < n; i++) { hash = hash * 32 - hash + obj_hash(elts[i], depth + 1); } return hash; } if (SYMBOLP(obj)) return symbol_hash((scm_symbol_t)obj, INT32_MAX); if (STRINGP(obj)) return string_hash((scm_string_t)obj, INT32_MAX); if (number_pred(obj)) return eqv_hash(obj, INT32_MAX); return HDR_TC(HDR(obj)); } return address_hash1(obj, INT32_MAX); } uint32_t eqv_hash(scm_obj_t obj, uint32_t bound) { return eqv_hash1(obj, bound); } uint32_t equal_hash(scm_obj_t obj, uint32_t bound) { return obj_hash(obj, 0) % bound; } uint32_t string_hash(scm_obj_t obj, uint32_t bound) { assert(STRINGP(obj)); scm_string_t string = (scm_string_t)obj; return string_hash1(string->name, bound); } uint32_t symbol_hash(scm_obj_t obj, uint32_t bound) { assert(SYMBOLP(obj)); scm_symbol_t symbol = (scm_symbol_t)obj; return string_hash2(symbol->name, bound); } bool eqv_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return eqv_pred(obj1, obj2); } bool equal_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return r5rs_equal_pred(obj1, obj2); } bool string_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return string_eq_pred(obj1, obj2); } int lookup_mutable_hashtable_size(int n) { static const int primes[] = {7, 13, 29, 59, 113, 223, 431, 821, 1567, 2999, 5701, 10837, 20593, 39133, 74353, 141277, 268439, 510047, 969097, 1841291, 3498457, 5247701, 7871573, 11807381, 17711087, 26566649, 39849977, 59774983, 89662483, 134493731, 201740597, 302610937, 453916423, 680874641, 1021311983, 1531968019, 2147483647}; for (int i = 0; i < array_sizeof(primes); i++) { if (primes[i] > n) return primes[i]; } fatal("%s:%u internal error: hashtable too big", __FILE__, __LINE__); } int lookup_immutable_hashtable_size(int n) { static const int primes[] = { 7, 11, 13, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 157, 191, 229, 277, 337, 409, 491, 593, 719, 863, 1039, 1249, 1499, 1801, 2161, 2593, 3119, 3761, 4513, 5417, 6521, 7829, 9397, 11279, 13537, 16249, 19501, 23417, 28109, 33739, 40487, 48589, 58309, 69991, 84011, 100823, 120997, 145207, 174257, 209123, 250949, 301141, 361373, 433651, 520381, 624467, 749383, 899263, 1079123, 1294957, 1553971, 1864769, 2237743, 2685301, 3222379, 3866857, 4640231, 5568287, 6681947, 8018347, 9622021, 11546449, 13855747, 16626941, 19952329, 23942797, 28731359, 34477637, 41373173, 49647809, 59577379, 71492873, 85791451, 102949741, 123539747, 148247713, 177897311, 213476789, 256172149, 307406587, 368887919, 442665511, 531198691, 637438433, 764926171, 917911471, 1101493807, 1321792573, 1586151131, 1903381357, 2147483647}; for (int i = 0; i < array_sizeof(primes); i++) { if (primes[i] > n) return primes[i]; } fatal("%s:%u internal error: hashtable too big", __FILE__, __LINE__); } static int put_eq_hashtable(scm_hashtable_t ht, scm_obj_t key, scm_obj_t value) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (tag == scm_hash_deleted) { ht_datum->live++; goto found; } if (tag == key) goto found; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = key; ht_datum->elts[index + nsize] = value; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } static scm_obj_t get_eq_hashtable(scm_hashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key) return ht_datum->elts[index + nsize]; if (tag == scm_hash_free) return scm_undef; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } static int remove_eq_hashtable(scm_hashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->elts[index + nsize] = scm_unspecified; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; } if (tag == scm_hash_free) return 0; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } scm_obj_t lookup_weakhashtable(scm_weakhashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) return scm_undef; if (entry != scm_hash_deleted) { assert(WEAKMAPPINGP(entry)); scm_weakmapping_t wmap = (scm_weakmapping_t)entry; if (wmap->key == scm_false) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; } else { if (wmap->key == key) return wmap; } } index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int remove_weakhashtable(scm_weakhashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) return 0; if (entry != scm_hash_deleted) { assert(WEAKMAPPINGP(entry)); scm_weakmapping_t wmap = (scm_weakmapping_t)entry; if (wmap->key == scm_false) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; } else if (wmap->key == key) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; } } index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int put_weakhashtable(scm_weakhashtable_t ht, scm_weakmapping_t wmap) { ht->lock.verify_locked(); scm_obj_t key = wmap->key; weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (entry == scm_hash_deleted) { ht_datum->live++; goto found; } assert(WEAKMAPPINGP(entry)); assert(((scm_weakmapping_t)entry)->key != key); // verify no duplicate entry index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = wmap; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_SPARSE_THRESHOLD(nsize)) return lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)); if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } static uint32_t simple_hash2(uint32_t hash, int nsize) { int dist = nsize >> 6; dist = (dist < 8) ? ((nsize > 8) ? 8 : 1) : dist; int hash2 = dist - (hash % dist); assert(hash2 && hash2 < nsize); return hash2; } int put_hashtable(scm_hashtable_t ht, scm_obj_t key, scm_obj_t value) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return put_eq_hashtable(ht, key, value); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (tag == scm_hash_deleted) { ht_datum->live++; goto found; } if (tag == key || (*ht->equiv)(tag, key)) goto found; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = key; ht_datum->elts[index + nsize] = value; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } scm_obj_t get_hashtable(scm_hashtable_t ht, scm_obj_t key) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return get_eq_hashtable(ht, key); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key || (*ht->equiv)(tag, key)) return ht_datum->elts[index + nsize]; if (tag == scm_hash_free) return scm_undef; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int remove_hashtable(scm_hashtable_t ht, scm_obj_t key) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return remove_eq_hashtable(ht, key); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key || (*ht->equiv)(tag, key)) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->elts[index + nsize] = scm_unspecified; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; } if (tag == scm_hash_free) return 0; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); }
36.548837
141
0.627704
eval-apply
ce9ec0fa4206d70d1f98f8b34ba621934189dc21
667
cpp
C++
boboleetcode/Play-Leetcode-master/0541-Reverse-String-II/cpp-0541/main.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2019-03-20T17:05:59.000Z
2019-10-15T07:56:45.000Z
boboleetcode/Play-Leetcode-master/0541-Reverse-String-II/cpp-0541/main.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
boboleetcode/Play-Leetcode-master/0541-Reverse-String-II/cpp-0541/main.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
/// Source : https://leetcode.com/problems/reverse-string-ii/description/ /// Author : liuyubobobo /// Time : 2018-06-04 #include <iostream> using namespace std; /// Simulation /// Time Complexity: O(n) /// Space Complexity: O(1) class Solution { public: string reverseStr(string s, int k) { for(int i = 0 ; i < s.size() ; i += 2 * k) reverse(s, i, i + k); return s; } private: void reverse(string& s, int i, int j){ j = min(j, (int)s.size()); j --; while(i < j) swap(s[i ++], s[j --]); } }; int main() { cout << Solution().reverseStr("abcdefg", 2) << endl; return 0; }
19.057143
73
0.526237
mcuallen
ce9f8023b431fcf053b7b590b0c8ea901848a5dd
30,969
cpp
C++
examples/test/main.cpp
pkholland/anon
c9fbe49e505eb4d100da58058e9f51508b06635d
[ "MIT" ]
1
2015-03-12T01:05:52.000Z
2015-03-12T01:05:52.000Z
examples/test/main.cpp
pkholland/anon
c9fbe49e505eb4d100da58058e9f51508b06635d
[ "MIT" ]
null
null
null
examples/test/main.cpp
pkholland/anon
c9fbe49e505eb4d100da58058e9f51508b06635d
[ "MIT" ]
null
null
null
/* Copyright (c) 2015 Anon authors, see AUTHORS file. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <thread> #include <arpa/inet.h> #include <netdb.h> #include "log.h" #include "udp_dispatch.h" #include "big_id_serial.h" #include "big_id_crypto.h" #include "fiber.h" #include "tcp_server.h" #include "tcp_client.h" #include "dns_cache.h" #include "lock_checker.h" #include "time_utils.h" #include "dns_lookup.h" #include "http_server.h" #include "tls_pipe.h" #include "epc_test.h" #include "mcdc.h" //#include "http2_handler.h" //#include "http2_test.h" class my_udp : public udp_dispatch { public: my_udp(int port) : udp_dispatch(port, false, true) { } virtual void recv_msg(const unsigned char *msg, ssize_t len, const struct sockaddr_storage *sockaddr, socklen_t sockaddr_len) { anon_log("received msg of: \"" << (char *)msg << "\""); //std::this_thread::sleep_for(std::chrono::milliseconds( 0 )); } }; extern "C" int main(int argc, char **argv) { anon_log("application start"); if (!init_big_id_crypto()) { anon_log_error("init_big_id_crypto failed"); return 1; } uint8_t big_id_data[32] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; big_id id(big_id_data); anon_log("big id: (short) " << id); anon_log("big id: (long) " << ldisp(id)); anon_log("random big id: " << ldisp(big_rand_id())); anon_log("sha256 id: " << ldisp(sha256_id("hello world\n", strlen("hello world\n")))); uint8_t small_id_data[20] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; small_id sid(small_id_data); anon_log("small id: (short) " << sid); anon_log("small id: (long) " << ldisp(sid)); anon_log("small random id: " << ldisp(small_rand_id())); anon_log("sha1 id: " << ldisp(sha1_id("hello world\n", strlen("hello world\n")))); { int udp_port = 8617; int tcp_port = 8618; int http_port = 8619; io_dispatch::start(std::thread::hardware_concurrency(), false); dns_cache::initialize(); dns_lookup::start_service(); fiber::initialize(); epc_test_init(); auto m_udp = std::make_shared<my_udp>(udp_port); http_server my_http; #if 0 http2_handler my_http2(my_http,[](std::unique_ptr<fiber_pipe>&& read_pipe, http_server::pipe_t& write_pipe, uint32_t stream_id){ anon_log("started new stream " << stream_id << ", should be reading from fd " << read_pipe->get_fd() << ", but am closing it!"); }); #endif my_http.start(http_port, [](http_server::pipe_t &pipe, const http_request &request) { http_response response; response.add_header("content-type", "text/plain"); response << "hello browser!\n\n"; response << "src addr: " << *request.src_addr << "\n"; response << "http version major: " << request.http_major << "\n"; response << "http version minor: " << request.http_minor << "\n"; response << "method: " << request.method_str() << "\n\n"; response << "-- headers --\n"; for (auto it = request.headers.headers.begin(); it != request.headers.headers.end(); it++) response << " " << it->first << ": " << it->second << "\n"; response << "\n"; response << "url path: " << request.get_url_field(UF_PATH) << "\n"; response << "url query: " << request.get_url_field(UF_QUERY) << "\n"; pipe.respond(response); }); int num_pipe_pairs = 400; int num_read_writes = 10000; while (true) { // read a command from stdin char msgBuff[256]; auto bytes_read = read(0 /*stdin*/, &msgBuff[0], sizeof(msgBuff)); if (bytes_read > 1) { // truncate the return char to a 0 so we can compare to strings msgBuff[bytes_read - 1] = 0; if (!strcmp(&msgBuff[0], "q")) { anon_log("quitting"); break; } else if (!strcmp(&msgBuff[0], "h")) { anon_log("available commands:"); anon_log(" q - quit"); anon_log(" p - pause all io threads, print while paused, then resume"); anon_log(" s - send some udp packets to the udp handler"); anon_log(" h - display this menu"); anon_log(" t - install a one second timer, which when it expires prints a message"); anon_log(" tt - schedule, and then delete a timer before it has a chance to expire"); anon_log(" fs - run a fiber which executes the fiber sleep function for 1000 milliseconds"); anon_log(" e - execute a print statement once on each io thread"); anon_log(" o - execute a print statement once on a single io thread"); anon_log(" f - execute a print statement on a fiber"); anon_log(" ft - test how long it takes to fiber/context switch " << num_pipe_pairs * num_read_writes << " times"); anon_log(" ot - similar test to 'ft', except run in os threads to test thread dispatch speed"); anon_log(" fi - run a fiber that creates additional fibers using \"in-fiber\" start mechanism"); anon_log(" fr - run a fiber that creates additional fibers using \"run\" start mechanism"); anon_log(" or - similar to 'fr', except using threads instead of fibers"); anon_log(" d - dns cache lookup of \"www.google.com\", port 80 with \"lookup_and_run\""); anon_log(" df - same as 'd', except \"lookup_and_run\" is called from a fiber"); anon_log(" id - same as 'df', except calling the fiber-blocking \"get_addrinfo\""); anon_log(" c - tcp connect to \"www.google.com\", port 80 and print a message"); anon_log(" ic - same as 'c', except calling the fiber-blocking connect"); anon_log(" cp - tcp connect to \"www.google.com\", port 79 and print a message - fails slowly"); anon_log(" ch - tcp connect to \"nota.yyrealhostzz.com\", port 80 and print a message - fails quickly"); anon_log(" h2 - connect to localhost:" << http_port << " and send an HTTP/1.1 with Upgrade to HTTP/2 message"); anon_log(" dl - dns_lookup \"www.google.com\", port 80 and print all addresses"); anon_log(" ss - send a simple command to adobe's renga server"); anon_log(" et - execute the endpoint_cluster tests"); anon_log(" mc - execute the memcached tests"); } else if (!strcmp(&msgBuff[0], "p")) { anon_log("pausing io threads"); io_dispatch::while_paused([] { anon_log("all io threads now paused"); }); anon_log("resuming io threads"); } else if (!strcmp(&msgBuff[0], "s")) { int num_messages = 20; anon_log("sending " << num_messages << " udp packet" << (num_messages == 1 ? "" : "s") << " to my_udp on loopback addr"); struct sockaddr_in6 addr = {0}; addr.sin6_family = AF_INET6; addr.sin6_port = htons(udp_port); addr.sin6_addr = in6addr_loopback; for (int i = 0; i < num_messages; i++) { std::ostringstream msg; msg << "hello world (" << std::to_string(i) << ")" /*<< rand_id()*/; if (sendto(m_udp->get_sock(), msg.str().c_str(), strlen(msg.str().c_str()) + 1, 0, (struct sockaddr *)&addr, sizeof(addr)) == -1) anon_log_error("sendto failed with errno: " << errno_string()); } } else if (!strcmp(&msgBuff[0], "t")) { anon_log("queueing one second delayed task"); io_dispatch::schedule_task([] { anon_log("task completed"); }, cur_time() + 1); } else if (!strcmp(&msgBuff[0], "tt")) { anon_log("queueing one second delayed task and deleting it before it expires"); auto t = io_dispatch::schedule_task([] { anon_log("oops, task completed!"); }, cur_time() + 1); if (io_dispatch::remove_task(t)) { anon_log("removed the task " << t); } else anon_log("failed to remove the task " << t); } else if (!strcmp(&msgBuff[0], "fs")) { anon_log("run a fiber which executes the fiber sleep function for 1000 milliseconds"); fiber::run_in_fiber([] { anon_log("in fiber, calling msleep(1000)"); fiber::msleep(1000); anon_log("back from calling msleep(1000)"); }); } else if (!strcmp(&msgBuff[0], "e")) { anon_log("executing print statement on each io thread"); io_dispatch::on_each([] { anon_log("hello from io thread " << syscall(SYS_gettid)); }); } else if (!strcmp(&msgBuff[0], "o")) { anon_log("executing print statement on one io thread"); io_dispatch::on_one([] { anon_log("hello from io thread " << syscall(SYS_gettid)); }); } else if (!strcmp(&msgBuff[0], "f")) { anon_log("executing print statement from a fiber"); fiber::run_in_fiber([] { anon_log("hello from fiber " << get_current_fiber_id()); }); } else if (!strcmp(&msgBuff[0], "ft")) { anon_log("executing fiber dispatch timing test"); auto start_time = cur_time(); std::vector<int> fds(num_pipe_pairs * 2); for (int i = 0; i < num_pipe_pairs; i++) { if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, &fds[i * 2]) != 0) do_error("socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, sv)"); } for (int i = 0; i < num_pipe_pairs; i++) { fiber::run_in_fiber([fds, i, num_read_writes] { fiber_pipe pipe(fds[i * 2], fiber_pipe::unix_domain); for (int rc = 0; rc < num_read_writes; rc++) { int v; pipe.read(&v, sizeof(v)); if (v != rc) anon_log("fiber read " << v << " instead of " << rc); } }); } fiber::run_in_fiber([fds, num_pipe_pairs, num_read_writes] { std::vector<std::unique_ptr<fiber_pipe>> pipes; for (int pc = 0; pc < num_pipe_pairs; pc++) pipes.push_back(std::move(std::unique_ptr<fiber_pipe>(new fiber_pipe(fds[pc * 2 + 1], fiber_pipe::unix_domain)))); for (int wc = 0; wc < num_read_writes; wc++) { for (int pc = 0; pc < num_pipe_pairs; pc++) pipes[pc]->write(&wc, sizeof(wc)); } }); fiber::wait_for_zero_fibers(); anon_log("fiber test done, total time: " << cur_time() - start_time << " seconds"); } else if (!strcmp(&msgBuff[0], "ot")) { anon_log("executing thread dispatch timing test"); auto start_time = cur_time(); std::vector<int> fds(num_pipe_pairs * 2); std::vector<std::thread> threads; for (int i = 0; i < num_pipe_pairs; i++) { if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &fds[i * 2]) != 0) anon_log_error("socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) failed with errno: " << errno_string()); } for (int i = 0; i < num_pipe_pairs; i++) { threads.push_back(std::thread([fds, i, num_read_writes] { try { for (int rc = 0; rc < num_read_writes; rc++) { int v; auto bytes_read = read(fds[i * 2], &v, sizeof(v)); if (bytes_read != sizeof(v)) anon_log_error("read(" << fds[i * 2] << ",...) returned " << bytes_read << ", errno: " << errno_string()); else if (v != rc) anon_log_error("thread read " << v << " instead of " << rc); } close(fds[i * 2]); } catch (const std::exception &err) { anon_log_error("exception caught, what = " << err.what()); } catch (...) { anon_log_error("unknown exception caught"); } })); } threads.push_back(std::thread([fds, num_pipe_pairs, num_read_writes] { try { for (int wc = 0; wc < num_read_writes; wc++) { for (int pc = 0; pc < num_pipe_pairs; pc++) { if (write(fds[pc * 2 + 1], &wc, sizeof(wc)) != sizeof(wc)) anon_log_error("(write(fds[pc*2+1],&wc,sizeof(wc)) failed with errno: " << errno_string()); } } for (int pc = 0; pc < num_pipe_pairs; pc++) close(fds[pc * 2 + 1]); } catch (const std::exception &err) { anon_log_error("exception caught, what = " << err.what()); } catch (...) { anon_log_error("unknown exception caught"); } })); for (auto thread = threads.begin(); thread != threads.end(); ++thread) thread->join(); anon_log("thread test done, total time: " << cur_time() - start_time << " seconds"); } else if (!strcmp(&msgBuff[0], "fi")) { anon_log("starting fiber which starts other fibers using \"in-fiber\" mechanism"); fiber::run_in_fiber([] { fiber_mutex mutex; mutex.lock(); anon_log("start, mutex " << &mutex << " is locked"); // "in-fiber" start sf1 fiber sf1([&mutex] { anon_log("locking mutex " << &mutex); fiber_lock lock(mutex); anon_log("locked mutex, now unlocking and exiting"); }, fiber::k_default_stack_size, false, "sf1"); // "in-fiber" start sf2 fiber sf2([&mutex] { anon_log("locking mutex " << &mutex); fiber_lock lock(mutex); anon_log("locked mutex, now unlocking and exiting"); }, fiber::k_default_stack_size, false, "sf2"); anon_log("fibers " << sf1.get_fiber_id() << " and " << sf2.get_fiber_id() << " both running, now unlocking mutex " << &mutex); mutex.unlock(); // wait for sf1 and sf2 to exit sf1.join(); sf2.join(); anon_log("fibers " << sf1.get_fiber_id() << " and " << sf2.get_fiber_id() << " have exited"); }); fiber::wait_for_zero_fibers(); anon_log("all fibers done"); } else if (!strcmp(&msgBuff[0], "fr")) { anon_log("starting fiber which starts 10000 sub fibers using \"run\" mechanism"); auto start_time = cur_time(); fiber::run_in_fiber([] { fiber_mutex mutex; fiber_cond cond; int num_fibers = 10000; int started = 0; // "run" start for (int fc = 0; fc < num_fibers; fc++) { fiber::run_in_fiber([&mutex, &cond, &started, num_fibers] { fiber_lock lock(mutex); if (++started == num_fibers) { anon_log("last sub fiber, now notifying"); cond.notify_all(); } }); } fiber_lock lock(mutex); while (started != num_fibers) cond.wait(lock); }); fiber::wait_for_zero_fibers(); anon_log("fiber test done, total time: " << cur_time() - start_time << " seconds"); } else if (!strcmp(&msgBuff[0], "or")) { anon_log("starting thread which starts 10000 sub threads"); auto start_time = cur_time(); std::thread([] { std::mutex mutex; std::condition_variable cond; int num_threads = 10000; int started = 0; for (int tc = 0; tc < num_threads; tc++) { std::thread([&mutex, &cond, &started, num_threads] { anon::unique_lock<std::mutex> lock(mutex); if (++started == num_threads) { anon_log("last sub thread, now notifying"); cond.notify_all(); } }) .detach(); } anon::unique_lock<std::mutex> lock(mutex); while (started != num_threads) cond.wait(lock); }) .join(); anon_log("thread test done, total time: " << cur_time() - start_time << " seconds"); } else if (!strcmp(&msgBuff[0], "c")) { const char *host = "www.google.com"; int port = 80; anon_log("tcp connecting to \"" << host << "\", port " << port); tcp_client::connect_and_run(host, port, [host, port](int err_code, std::unique_ptr<fiber_pipe> &&pipe) { if (err_code == 0) anon_log("connected to \"" << host << "\", port " << port << ", now disconnecting"); else if (err_code > 0) anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << error_string(err_code)); else anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << gai_strerror(err_code)); }); } else if (!strcmp(&msgBuff[0], "ic")) { const char *host = "www.google.com"; int port = 80; anon_log("tcp connecting to \"" << host << "\", port " << port << ", with tcp_client::connect"); fiber::run_in_fiber([host, port] { auto c = tcp_client::connect(host, port); if (c.first == 0) anon_log("connected to \"" << host << "\", port " << port << ", now disconnecting"); else anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << (c.first > 0 ? error_string(c.first) : gai_strerror(c.first))); }); } else if (!strcmp(&msgBuff[0], "cp")) { const char *host = "www.google.com"; int port = 79; anon_log("trying to tcp connect to \"" << host << "\", port " << port); tcp_client::connect_and_run(host, port, [host, port](int err_code, std::unique_ptr<fiber_pipe> &&pipe) { if (err_code == 0) anon_log("connected to \"" << host << "\", port " << port << ", now disconnecting"); else anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); }); } else if (!strcmp(&msgBuff[0], "ch")) { const char *host = "nota.yyrealhostzz.com"; int port = 80; anon_log("trying to tcp connect to \"" << host << "\", port " << port); tcp_client::connect_and_run(host, port, [host, port](int err_code, std::unique_ptr<fiber_pipe> &&pipe) { if (err_code == 0) anon_log("connected to \"" << host << "\", port " << port << ", now disconnecting"); else anon_log("connection to \"" << host << "\", port " << port << " failed with error: (" << err_code << ") " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); }); } else if (!strcmp(&msgBuff[0], "d")) { const char *host = "www.google.com"; int port = 80; anon_log("looking up \"" << host << "\", port " << port << " (twice)"); for (int i = 0; i < 2; i++) dns_cache::lookup_and_run(host, port, [host, port](int err_code, const struct sockaddr *addr, socklen_t addrlen) { if (err_code == 0) anon_log("dns lookup for \"" << host << "\", port " << port << " found: " << *addr); else anon_log("dns lookup for \"" << host << "\", port " << port << " failed with error: " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); }); } else if (!strcmp(&msgBuff[0], "df")) { const char *host = "www.google.com"; int port = 80; anon_log("running a fiber which looks up \"" << host << "\", port " << port << " (twice)"); fiber::run_in_fiber([host, port] { for (int i = 0; i < 2; i++) dns_cache::lookup_and_run(host, port, [host, port](int err_code, const struct sockaddr *addr, socklen_t addrlen) { if (err_code == 0) anon_log("dns lookup for \"" << host << "\", port " << port << " found: " << *addr); else anon_log("dns lookup for \"" << host << "\", port " << port << " failed with error: " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); }); }); } else if (!strcmp(&msgBuff[0], "id")) { const char *host = "www.google.com"; int port = 80; anon_log("running a fiber which calls get_addrinfo on \"" << host << "\", port " << port << " (twice)"); fiber::run_in_fiber([host, port] { for (int i = 0; i < 2; i++) { struct sockaddr_in6 addr; socklen_t addrlen; int ret = dns_cache::get_addrinfo(host, port, &addr, &addrlen); if (ret == 0) anon_log("dns lookup for \"" << host << "\", port " << port << " found: " << addr); else anon_log("dns lookup for \"" << host << "\", port " << port << " failed with error: " << (ret > 0 ? error_string(ret) : gai_strerror(ret))); } }); } else if (!strcmp(&msgBuff[0], "h2")) { #if 0 run_http2_test(http_port); #endif } else if (!strcmp(&msgBuff[0], "dl")) { const char *host = "www.google.com"; int port = 80; anon_log("looking up \"" << host << "\", port " << port << ", and printing all ip addresses"); fiber::run_in_fiber([host, port] { auto addrs = dns_lookup::get_addrinfo(host, port); if (addrs.first != 0) anon_log("dns lookup for \"" << host << "\", port " << port << " failed with error: " << (addrs.first > 0 ? error_string(addrs.first) : gai_strerror(addrs.first))); else { anon_log("dns lookup for \"" << host << "\", port " << port << " found " << addrs.second.size() << " addresses"); for (auto addr : addrs.second) anon_log(" " << addr); } }); } else if (!strcmp(&msgBuff[0], "et")) { epc_test(); } else if (!strncmp(&msgBuff[0], "ss", 2)) { int total = 4; if (strlen(&msgBuff[0]) > 2) total = atoi(&msgBuff[2]); const char *host = "na1r-dev1.services.adobe.com"; int port = 443; std::atomic_int num_succeeded(0); std::atomic_int num_failed(0); std::atomic_int num_tls(0); std::atomic_int num_connected(0); std::atomic_int num_calls(0); anon_log("making " << total << " api calls to \"" << host << "\", port " << port); for (int i = 0; i < total; i++) { tcp_client::connect_and_run(host, port, [host, port, total, &num_succeeded, &num_failed, &num_tls, &num_connected, &num_calls](int err_code, std::unique_ptr<fiber_pipe> &&pipe) { if (err_code == 0) { if (++num_connected == 1) anon_log("tcp connected..."); pipe->limit_io_block_time(120); try { const char *user_name = "user@domain.com"; const char *password = "password"; tls_context ctx(true /*client*/, 0 /*verify_cert*/, "/etc/ssl/certs" /*verify_loc*/, 0, 0, 5); //anon_log("connected to \"" << host << "\", port " << port << ", (fd: " << fd << ") now starting tls handshake"); tls_pipe p(std::move(pipe), true /*client*/, true /*verify_peer*/, false /* doSNI */, host, ctx); ++num_tls; std::ostringstream body; body << "<ReqBody version=\"1.5\" clientId=\"anon_client\">\n"; body << " <req dest=\"UserManagement\" api=\"authUserWithCredentials\">\n"; body << " <string>" << user_name << "</string>\n"; body << " <string>" << password << "</string>\n"; body << " <AuthRequest/>\n"; body << " </req>\n"; body << "</ReqBody>\n"; std::string body_st = body.str(); std::ostringstream oss; oss << "POST /account/amfgateway2 HTTP/1.1\r\n"; oss << "host: " << host << "\r\n"; oss << "content-length: " << body_st.length() << "\r\n"; oss << "user-agent: anon_agent\r\n"; oss << "content-type: text/xml;charset=utf-8\r\n"; oss << "accept: text/xml;charset=utf-8\r\n"; oss << "\r\n"; oss << body_st.c_str(); std::string st = oss.str(); const char *buf = st.c_str(); size_t len = st.length(); #if 0 anon_log("tls handshake completed, certificates accepted, now sending (encrypted):\n\n" << buf); #endif p.write(st.c_str(), len); //anon_log("tls send completed, now reading"); char ret_buf[10250]; auto ret_len = p.read(&ret_buf[0], sizeof(ret_buf) - 1); //ret_buf[ret_len] = 0; //anon_log("server return starts with (encrypted):\n\n" << &ret_buf[0] << "\n"); //anon_log("closing connection to \"" << host << "\" (fd: " << fd << ")"); p.shutdown(); ++num_succeeded; } catch (...) { //anon_log("caught exception"); } } else { //anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); ++num_failed; } if (++num_calls == total) anon_log("finished " << total << " api calls:\n " << num_succeeded << " succeeded\n " << num_failed << " failed to connect\n " << num_connected - num_tls << " failed during tls handshake\n " << num_tls - num_succeeded << " failed after tls handshake"); }); } } else if (!strncmp(&msgBuff[0], "pp ", 3)) { auto sock = atoi(&msgBuff[3]); struct sockaddr_in6 addr6; socklen_t addr_len = sizeof(addr6); if (getpeername(sock, (struct sockaddr *)&addr6, &addr_len) != 0) anon_log("getpeername(" << sock << "...) failed with error " << errno_string()); else anon_log("getpeername(" << sock << ", ...) reported peer as " << &addr6); } else if (!strcmp(&msgBuff[0], "mc")) { std::condition_variable cond; std::mutex mtx; bool running = true; fiber::run_in_fiber([&cond, &mtx, &running] { struct unlocker { unlocker(std::condition_variable &cond, std::mutex &mtx, bool &running) : cond(cond), mtx(mtx), running(running) { } ~unlocker() { std::unique_lock<std::mutex> l(mtx); running = false; cond.notify_all(); } std::condition_variable &cond; std::mutex &mtx; bool &running; }; unlocker unl(cond, mtx, running); const char *host = "127.0.0.1"; int port = 11211; anon_log("memcached test to host: \"" << host << "\", port: " << port); const char *key = "key1"; const char *val = "this is the value for key1"; mcd_cluster c(host, port); anon_log(" setting value for \"" << key << "\" to: \"" << val << "\""); c.set(key, val, 1); anon_log(" fetching value for \"" << key << "\", got \"" << c.get(key) << "\""); }); std::unique_lock<std::mutex> l(mtx); while (running) cond.wait(l); } else anon_log("unknown command - \"" << &msgBuff[0] << "\", type \"h <return>\" for help"); } } } epc_test_term(); dns_lookup::end_service(); dns_cache::terminate(); io_dispatch::join(); fiber::terminate(); term_big_id_crypto(); anon_log("application exit"); return 0; }
39.908505
272
0.502406
pkholland
ce9fb266d61bf3c485015eabe0377a3c85b44d2d
37,377
cpp
C++
vnext/Desktop.IntegrationTests/HttpOriginPolicyIntegrationTest.cpp
iahmadwaqar/react-native-windows
2d128d8d3e51e4cba8f94965053c6b679602c87d
[ "MIT" ]
4,873
2017-03-09T22:58:40.000Z
2019-05-06T21:03:20.000Z
vnext/Desktop.IntegrationTests/HttpOriginPolicyIntegrationTest.cpp
iahmadwaqar/react-native-windows
2d128d8d3e51e4cba8f94965053c6b679602c87d
[ "MIT" ]
1,293
2017-03-09T15:57:29.000Z
2019-05-06T20:35:22.000Z
vnext/Desktop.IntegrationTests/HttpOriginPolicyIntegrationTest.cpp
iahmadwaqar/react-native-windows
2d128d8d3e51e4cba8f94965053c6b679602c87d
[ "MIT" ]
477
2017-03-10T06:39:32.000Z
2019-05-06T20:33:00.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <CppUnitTest.h> #include <CppRuntimeOptions.h> #include <Networking/IHttpResource.h> #include <Networking/OriginPolicy.h> #include <Test/HttpServer.h> // Standard Library #include <future> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace http = boost::beast::http; using Microsoft::React::Networking::IHttpResource; using Microsoft::React::Networking::OriginPolicy; using std::make_shared; using std::promise; using std::string; namespace { constexpr char s_serverHost[]{"http://localhost"}; constexpr char s_crossOriginUrl[]{"http://example.rnw"}; } // namespace // clang-format off namespace Microsoft::React::Test { TEST_CLASS(HttpOriginPolicyIntegrationTest) { static constexpr bool s_shouldSucceed{true}; static constexpr bool s_shouldFail{false}; static uint16_t s_port; struct ServerParams { uint16_t Port; string Url; EmptyResponse Preflight; StringResponse Response; ServerParams( uint16_t port) noexcept : Port{port} , Url{s_serverHost + string{":"} + std::to_string(port)} { Preflight.set(http::field::access_control_allow_methods, "GET, POST, DELETE, PATCH"); Response.result(http::status::unknown); Response.body() = "RESPONSE_CONTENT"; } }; struct ClientParams { promise<void> ContentPromise; string ErrorMessage; IHttpResource::Response Response; string ResponseContent; http::verb Method; IHttpResource::Headers RequestHeaders; bool WithCredentials{false}; ClientParams(http::verb method, IHttpResource::Headers&& headers) : Method{ method } , RequestHeaders{ std::move(headers) } { } }; std::shared_ptr<HttpServer> CreateServer(ServerParams& serverArgs, ClientParams& clientArgs) noexcept { auto server = make_shared<HttpServer>(serverArgs.Port); server->Callbacks().OnOptions = [&serverArgs](const DynamicRequest& request) -> ResponseWrapper { return { std::move(serverArgs.Preflight) }; }; auto reqHandler = [&serverArgs](const DynamicRequest& request) -> ResponseWrapper { return { std::move(serverArgs.Response) }; }; switch (clientArgs.Method) { case http::verb::get: server->Callbacks().OnGet = reqHandler; break; case http::verb::post: server->Callbacks().OnPost = reqHandler; break; case http::verb::patch: server->Callbacks().OnPatch = reqHandler; break; case http::verb::trace: server->Callbacks().OnTrace = reqHandler; break; case http::verb::connect: server->Callbacks().OnConnect = reqHandler; break; case http::verb::options: default: Assert::Fail(L"Unsupported request method"); } return server; } void TestOriginPolicyWithRedirect(ServerParams& server1Args, ServerParams& server2Args, ClientParams& clientArgs, bool shouldSucceed) { auto server1 = CreateServer(server1Args, clientArgs); auto server2 = CreateServer(server2Args, clientArgs); server1->Start(); server2->Start(); auto resource = IHttpResource::Make(); resource->SetOnResponse([&clientArgs](int64_t, IHttpResource::Response&& response) { clientArgs.Response = std::move(response); }); resource->SetOnData([&clientArgs](int64_t, string&& content) { clientArgs.ResponseContent = std::move(content); clientArgs.ContentPromise.set_value(); }); resource->SetOnError([&clientArgs](int64_t, string&& message) { clientArgs.ErrorMessage = std::move(message); clientArgs.ContentPromise.set_value(); }); resource->SendRequest( string{http::to_string(clientArgs.Method).data()}, string{server1Args.Url}, std::move(clientArgs.RequestHeaders), { IHttpResource::BodyData::Type::String, "REQUEST_CONTENT" }, "text", false, /*useIncrementalUpdates*/ 1000, /*timeout*/ clientArgs.WithCredentials, /*withCredentials*/ [](int64_t){} /*reactCallback*/ ); clientArgs.ContentPromise.get_future().wait(); server2->Stop(); server1->Stop(); if (shouldSucceed) { Assert::AreEqual({}, clientArgs.ErrorMessage); //TODO: chose server? // We assume 2-server tests will always redirect so the final response will come from server 2. Assert::AreEqual(server2Args.Response.result_int(), static_cast<unsigned int>(clientArgs.Response.StatusCode)); Assert::AreEqual({"RESPONSE_CONTENT"}, clientArgs.ResponseContent); } else { Assert::AreNotEqual({}, clientArgs.ErrorMessage); } } void TestOriginPolicy(ServerParams& serverArgs, ClientParams& clientArgs, bool shouldSucceed) { auto server = CreateServer(serverArgs, clientArgs); server->Start(); auto resource = IHttpResource::Make(); resource->SetOnResponse([&clientArgs](int64_t, IHttpResource::Response&& res) { clientArgs.Response = std::move(res); }); resource->SetOnData([&clientArgs](int64_t, string&& content) { clientArgs.ResponseContent = std::move(content); clientArgs.ContentPromise.set_value(); }); resource->SetOnError([&clientArgs](int64_t, string&& message) { clientArgs.ErrorMessage = std::move(message); clientArgs.ContentPromise.set_value(); }); resource->SendRequest( string{http::to_string(clientArgs.Method).data()}, string{serverArgs.Url}, std::move(clientArgs.RequestHeaders), { IHttpResource::BodyData::Type::String, "REQUEST_CONTENT" }, "text", false, /*useIncrementalUpdates*/ 1000, /*timeout*/ clientArgs.WithCredentials, /*withCredentials*/ [](int64_t) {} /*reactCallback*/ ); clientArgs.ContentPromise.get_future().wait(); server->Stop(); if (shouldSucceed) { Assert::AreEqual({}, clientArgs.ErrorMessage); Assert::AreEqual(serverArgs.Response.result_int(), static_cast<unsigned int>(clientArgs.Response.StatusCode)); Assert::AreEqual({"RESPONSE_CONTENT"}, clientArgs.ResponseContent); } else { Assert::AreNotEqual({}, clientArgs.ErrorMessage); } } TEST_METHOD_CLEANUP(MethodCleanup) { SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::None)); SetRuntimeOptionString("Http.GlobalOrigin", {}); // Bug in HttpServer does not correctly release TCP port between test methods. // Using a different por per test for now. s_port++; } //TODO: NoCors_InvalidMethod_Failed? BEGIN_TEST_METHOD_ATTRIBUTE(NoCorsForbiddenMethodSucceeds) // CONNECT, TRACE, and TRACK methods not supported by Windows.Web.Http // https://docs.microsoft.com/en-us/uwp/api/windows.web.http.httpmethod?view=winrt-19041#properties TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(NoCorsForbiddenMethodSucceeds) { SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::None)); constexpr uint16_t port{ 5556 }; constexpr char url[]{ "http://localhost:5556" }; string error; string getContent; IHttpResource::Response getResponse; promise<void> getDataPromise; auto server = make_shared<HttpServer>(port); server->Callbacks().OnOptions = [&url](const DynamicRequest& request) -> ResponseWrapper { EmptyResponse response; response.result(http::status::accepted); response.set(http::field::access_control_allow_credentials, "false"); response.set(http::field::access_control_allow_headers, "ValidHeader"); response.set(http::field::access_control_allow_methods, "GET, POST, DELETE, PATCH"); response.set(http::field::access_control_allow_origin, url); return { std::move(response) }; }; server->Callbacks().OnTrace = [](const DynamicRequest& request) -> ResponseWrapper { StringResponse response; response.result(http::status::ok); response.body() = "GET_CONTENT"; return { std::move(response) }; }; server->Start(); auto resource = IHttpResource::Make(); resource->SetOnResponse([&getResponse](int64_t, IHttpResource::Response&& res) { getResponse = std::move(res); }); resource->SetOnData([&getDataPromise, &getContent](int64_t, string&& content) { getContent = std::move(content); getDataPromise.set_value(); }); resource->SetOnError([&server, &error, &getDataPromise](int64_t, string&& message) { error = std::move(message); getDataPromise.set_value(); }); resource->SendRequest( "TRACE", url, { {"ValidHeader", "AnyValue"} }, {} /*bodyData*/, "text", false /*useIncrementalUpdates*/, 1000 /*timeout*/, false /*withCredentials*/, [](int64_t) {} /*callback*/ ); getDataPromise.get_future().wait(); server->Stop(); Assert::AreEqual({}, error); Assert::AreEqual(200, static_cast<int>(getResponse.StatusCode)); Assert::AreEqual({ "GET_CONTENT" }, getContent); }// NoCorsForbiddenMethodSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(SimpleCorsForbiddenMethodFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(SimpleCorsForbiddenMethodFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_allow_origin, serverArgs.Url); ClientParams clientArgs(http::verb::connect, {{"Content-Type", "text/plain"}}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::SimpleCrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// SimpleCorsForbiddenMethodFails //NoCors_ForbiddenMethodConnect_Failed BEGIN_TEST_METHOD_ATTRIBUTE(NoCorsCrossOriginFetchRequestSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(NoCorsCrossOriginFetchRequestSucceeds) { SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::None)); ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::ok); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// NoCorsCrossOriginFetchRequestSucceeds //NoCors_CrossOriginFetchRequestWithTimeout_Succeeded //TODO: Implement timeout BEGIN_TEST_METHOD_ATTRIBUTE(NoCorsCrossOriginPatchSucceededs) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(NoCorsCrossOriginPatchSucceededs) { SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::None)); ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::ok); ClientParams clientArgs(http::verb::patch, {{ "Content-Type", "text/plain" }}); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// NoCorsCrossOriginPatchSucceededs // Simple-Cors — Prevents the method from being anything other than HEAD, GET or POST, // and the headers from being anything other than simple headers (CORS safe listed headers). // If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. // In addition, JavaScript may not access any properties of the resulting Response. // This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains. BEGIN_TEST_METHOD_ATTRIBUTE(SimpleCorsSameOriginSucceededs) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(SimpleCorsSameOriginSucceededs) { ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::ok); ClientParams clientArgs(http::verb::patch, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::SimpleCrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// SimpleCorsSameOriginSucceededs BEGIN_TEST_METHOD_ATTRIBUTE(SimpleCorsCrossOriginFetchFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(SimpleCorsCrossOriginFetchFails) { ServerParams serverArgs(s_port); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/html" }}); // text/html is a non-simple value SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::SimpleCrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// SimpleCorsCrossOriginFetchFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsSameOriginRequestSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsSameOriginRequestSucceeds) { ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::ok); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); // text/plain is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// FullCorsSameOriginRequestSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginAllowOriginWildcardSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginAllowOriginWildcardSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, "*"); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Response.result(http::status::accepted); serverArgs.Response.set(http::field::access_control_allow_origin, "*"); serverArgs.Response.set(http::field::access_control_allow_credentials, "true"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); // text/plain is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// FullCorsCrossOriginAllowOriginWildcardSucceeds // With CORS, Cross-Origin Resource Sharing, the server can decide what origins are permitted to read information from the client. // Additionally, for non-simple requests, client should preflight the request through the HTTP Options request, and only send the // actual request after the server has responded that the desired headers are supported. BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginMatchingOriginSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginMatchingOriginSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Response.result(http::status::accepted); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Response.set(http::field::access_control_allow_credentials, "true"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); // text/plain is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// FullCorsCrossOriginMatchingOriginSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginWithCredentialsFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginWithCredentialsFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Preflight.set(http::field::access_control_allow_credentials, "true"); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); // application/text is a non-simple header clientArgs.WithCredentials = true; SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); SetRuntimeOptionBool("Http.OmitCredentials", true); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// FullCorsCrossOriginWithCredentialsFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginMissingCorsHeadersFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginMissingCorsHeadersFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.erase(http::field::access_control_allow_methods); serverArgs.Preflight.result(http::status::not_implemented); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); // application/text is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// FullCorsCrossOriginMissingCorsHeadersFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginMismatchedCorsHeaderFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginMismatchedCorsHeaderFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Response.result(http::status::accepted); serverArgs.Response.set(http::field::access_control_allow_origin, "http://other.example.rnw"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); // application/text is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// FullCorsCrossOriginMismatchedCorsHeaderFails // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSExternalRedirectNotAllowed BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginCheckFailsOnPreflightRedirectFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginCheckFailsOnPreflightRedirectFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Preflight.set(http::field::location, "http://any-host.extension"); serverArgs.Preflight.result(http::status::moved_permanently); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// FullCorsCrossOriginCheckFailsOnPreflightRedirectFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCorsCheckFailsOnResponseRedirectFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCorsCheckFailsOnResponseRedirectFails) { ServerParams serverArgs(s_port); // server1 allowed origin header includes http://example.com serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); // This is a CORS request to server1, but server1 redirects the request to server2 serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); // Redir server's URL serverArgs.Response.set(http::field::location, "http://localhost:6666"); serverArgs.Response.set(http::field::server, "BaseServer"); // Server2 does not set Access-Control-Allow-Origin for GET requests ServerParams redirServerArgs(++s_port); redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::server, "RedirectServer"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldFail); }// FullCorsCorsCheckFailsOnResponseRedirectFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsSameOriginToSameOriginRedirectSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsSameOriginToSameOriginRedirectSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::location, serverArgs.Url); serverArgs.Response.result(http::status::accepted); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldSucceed); } // FullCorsSameOriginToSameOriginRedirectSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsSameOriginToCrossOriginRedirectSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsSameOriginToCrossOriginRedirectSucceeds) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Preflight.set(http::field::access_control_allow_origin, serverArgs.Url); serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::access_control_allow_origin, serverArgs.Url); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldSucceed); } // FullCorsSameOriginToCrossOriginRedirectSucceeds //TODO: Seems to redirect to exact same resource. Implement second resource in same server. // Redirects a cross origin request to cross origin request on the same server BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToCrossOriginRedirectSucceeds) TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToCrossOriginRedirectSucceeds) { ServerParams serverArgs(s_port); //ServerParams redirServerArgs(++s_port); serverArgs.Preflight.set(http::field::access_control_allow_origin, serverArgs.Url); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, serverArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); //redirServerArgs.Response.result(http::status::accepted); //redirServerArgs.Response.set(http::field::access_control_allow_origin, serverArgs.Url); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, /*redirServerArgs, */clientArgs, s_shouldSucceed); } // FullCorsCrossOriginToCrossOriginRedirectSucceeds // The initial request gets redirected back to the original origin, // but it will lack the Access-Control-Allow-Origin header. BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToOriginalOriginRedirectFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToOriginalOriginRedirectFails) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, redirServerArgs.Url); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", redirServerArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldFail); } // FullCorsCrossOriginToOriginalOriginRedirectFails // Redirects cross origin request to server1 to cross origin request to server2 BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToAnotherCrossOriginRedirectSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToAnotherCrossOriginRedirectSucceeds) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::access_control_allow_origin, "*"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldSucceed); } // FullCorsCrossOriginToAnotherCrossOriginRedirectSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightSucceeds) // [0x80072f88] The HTTP redirect request must be confirmed by the user //TODO: Figure out manual redirection. TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightSucceeds) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); // server1 redirects the GET request to server2 serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); // Since redirect tainted the origin, the server has to allow all origins for CORS to succeed redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::access_control_allow_origin, "*"); // PATCH is not a simple method, so preflight is required for server1 ClientParams clientArgs(http::verb::patch, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldSucceed); } // FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightFails) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); // server1 redirects the GET request to server2 serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); // Since redirect tainted the origin, the server does not know what origin to allow through a single value. // Even if server successfully guessed the single value, it will still fail on the client side. redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); // PATCH is not a simple method, so preflight is required for server1 ClientParams clientArgs(http::verb::patch, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldFail); } // FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCors304ForSimpleGetFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCors304ForSimpleGetFails) { ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::not_modified); // PATCH is not a simple method, so preflight is required for server1 ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); } // FullCors304ForSimpleGetFails TEST_METHOD(FullCorsPreflightSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "ArbitraryHeader"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "ArbitraryHeader"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Response.result(http::status::ok); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); ClientParams clientArgs(http::verb::get, { {"Content-Type", "text/plain"}, {"ArbitraryHeader", "AnyValue"} }); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldSucceed); }// FullCorsPreflightSucceeds // The current implementation omits withCredentials flag from request and always sets it to false // Configure the responses for CORS request BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginWithCredentialsSucceeds) //TODO: Fails if run after FullCorsCrossOriginWithCredentialsFails TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginWithCredentialsSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Preflight.set(http::field::access_control_allow_credentials, "true"); serverArgs.Response.result(http::status::accepted); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); // application/text is a non-simple header clientArgs.WithCredentials = true; SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldSucceed); }// FullCorsCrossOriginWithCredentialsSucceeds // "Host" is one of the forbidden headers for fetch BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsRequestWithHostHeaderFails) // "Host" is not an accepted request header in WinRT. TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsRequestWithHostHeaderFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Response.result(http::status::accepted); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }, { "Host", "http://sub.example.rnw" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); Assert::Fail(L"FIX!!! Passes for the worng reason. Error: 0x80070057 : 'Invalid HTTP headers.'"); }// FullCorsRequestWithHostHeaderFails BEGIN_TEST_METHOD_ATTRIBUTE(RequestWithProxyAuthorizationHeaderFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(RequestWithProxyAuthorizationHeaderFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Response.result(http::status::accepted); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }, { "Proxy-Authorization", "Basic Zm9vOmJhcg==" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// RequestWithProxyAuthorizationHeaderFails BEGIN_TEST_METHOD_ATTRIBUTE(ExceedingRedirectLimitFails) TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(ExceedingRedirectLimitFails) { Assert::Fail(L"NOT IMPLEMENTED"); }// ExceedingRedirectLimitFails }; uint16_t HttpOriginPolicyIntegrationTest::s_port = 7777; }//namespace Microsoft::React::Test // clang-format on
44.655914
160
0.731439
iahmadwaqar
cea8b31c3435b2438bb81c8fba50ef1024968b54
753
cpp
C++
src/ECS/Detail/SystemHolder.cpp
Ethan13310/ECS
63aae52624b6468a7db078fdf7c32dd4caecaa70
[ "MIT" ]
12
2018-12-06T12:51:57.000Z
2022-03-20T14:31:28.000Z
src/ECS/Detail/SystemHolder.cpp
Ethan13310/ECS
63aae52624b6468a7db078fdf7c32dd4caecaa70
[ "MIT" ]
1
2021-07-15T08:33:16.000Z
2021-07-15T08:33:16.000Z
src/ECS/Detail/SystemHolder.cpp
Ethan13310/ECS
63aae52624b6468a7db078fdf7c32dd4caecaa70
[ "MIT" ]
3
2019-08-10T22:34:28.000Z
2021-07-14T09:19:36.000Z
// Copyright (c) 2021 Ethan Margaillan <contact@ethan.jp>. // Licensed under the MIT License - https://raw.githubusercontent.com/Ethan13310/ECS/master/LICENSE #include <ECS/Detail/SystemHolder.hpp> ecs::detail::SystemHolder::~SystemHolder() { removeAllSystems(); } void ecs::detail::SystemHolder::removeAllSystems() { for (auto &system : m_systems) { if (system.second != nullptr) { system.second->shutdownEvent(); system.second->detachAll(); } } m_systems.clear(); m_priorities.clear(); } void ecs::detail::SystemHolder::removeSystemPriority(detail::TypeId id) { for (auto it{ m_priorities.begin() }; it != m_priorities.end();) { if (it->second == id) { it = m_priorities.erase(it); } else { ++it; } } }
18.825
99
0.670651
Ethan13310
ceb30aa972be3cfb975cfbeb5fb41bbebe710e08
337
hpp
C++
Vesper/Vesper/Textures/UVTexture.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
6
2017-09-14T03:26:49.000Z
2021-09-18T05:40:59.000Z
Vesper/Vesper/Textures/UVTexture.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
Vesper/Vesper/Textures/UVTexture.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <string> #include <functional> #include <cmath> #include "Texture.hpp" namespace crisp { class UVTexture : public Texture<Spectrum> { public: UVTexture(const VariantMap& variantMap = VariantMap()); virtual Spectrum eval(const glm::vec2& uv) const override; }; }
17.736842
66
0.673591
FallenShard