blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
31b10eb8fd4b004b08a8efd2b6a42a7185a81825
c5973a3828a751474ab922bf463cd51d9de3a2fc
/Map.h
bd031b46d3131385a3aef46e2e5f5f0dbb896c06
[]
no_license
roquelopez/backtracking_search
047d44f972d20cdb2c235f71037919313592bb8d
b3d17091d167e5b25bd0d065ba7f2c3d1d4421c5
refs/heads/master
2021-01-09T20:26:38.648721
2018-08-17T12:54:46
2018-08-17T12:54:46
63,014,799
0
0
null
null
null
null
UTF-8
C++
false
false
1,003
h
Map.h
/* * Map.h * * Created on: May 4, 2013 * Author: roque */ #ifndef MAP_H_ #define MAP_H_ #include "Region.h" #include <cstdio> #include <cstdlib> #include <string> #include <vector> using namespace std; class Map { vector<Region> regionList; //Lista das regiões. vector<string> colors; //Lista com os cores Azul, Amarelo, Verde e Vermelho (domínio do problema). public: Map(); bool readInputs(string pathFile); void doGraph(vector<string>); void printMap(); void updateNeighbors(int variable, bool flag, string colorName); int backtracking(int assignments); int backtrackingFC(int assignments); int backtrackingMVR(int assignments); int backtrackingMVRDegree(int assignments); int findRegion(string regionName); int selectVariable(); int selectVariableMVR(); int selectVariableMVRDegree(); int getConstraints(int variable); vector<string>split(string s); bool hasConstraint(int variable, string colorName); bool forwardChecking(int variable); }; #endif /* MAP_H_ */
8886ea7b65e92affe909adaf8e790b158f566813
95ec22f669f54524c9c66c38e5e9912c48ee00c7
/source/chat/folder/element.h
af46c72a5bb18f1790f5f64bfe76e18f4c35b9b1
[ "MIT" ]
permissive
scapix-com/example1
35f027f5029747a34a21745813852e8b030594b9
8ececb6512edb5c0eff35900925e7a2cd174bca5
refs/heads/master
2023-09-01T04:56:28.623536
2023-08-24T19:30:19
2023-08-24T19:30:19
177,970,405
17
3
null
null
null
null
UTF-8
C++
false
false
459
h
element.h
/* chat/folder/element.h */ #ifndef CHAT_FOLDER_ELEMENT_H #define CHAT_FOLDER_ELEMENT_H #include <chat/folder/abstract_element.h> #include <chat/contact.h> namespace chat::folder { class element : public abstract_element { public: std::vector<std::string> func1(std::vector<std::string> s) override { s.push_back("element::func1"); return s; } void func4(std::shared_ptr<contact>) {} }; } // namespace chat::folder #endif // CHAT_FOLDER_ELEMENT_H
bd12a08751d97a5bef8bc968f76bda6480570793
f47447e0e752a40fbdcfabc39d0e6bdaa4c7b0e5
/osgTraits/Subtraction.h
a02ec4a8f613f107aa620b1378833993df396b0c
[]
no_license
lpberg/osgBoost
68145e6fac7f4dbe56f8013735675b6f053ae84c
a2eec3490c3c28742df71a072c3f7f90251a30c4
refs/heads/master
2021-01-15T19:44:30.063021
2013-03-08T17:59:10
2013-03-08T17:59:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,632
h
Subtraction.h
/** @file @brief Header @date 2012 @author Ryan Pavlik <rpavlik@iastate.edu> and <abiryan@ryand.net> http://academic.cleardefinition.com/ Iowa State University Virtual Reality Applications Center Human-Computer Interaction Graduate Program */ // Copyright Iowa State University 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #ifndef INCLUDED_Subtraction_h_GUID_fec3e459_c1e7_441b_9a1b_bc11a65a8336 #define INCLUDED_Subtraction_h_GUID_fec3e459_c1e7_441b_9a1b_bc11a65a8336 // Internal Includes #include "TypePredicates.h" #include "PromoteTypeWithScalar.h" #include "OperatorBase.h" // Library/third-party includes #include <boost/utility/enable_if.hpp> #include <boost/mpl/or.hpp> // Standard includes // - none namespace osgTraits { struct Subtraction; template<> struct OperatorVerb<Subtraction> { static const char * get() { return "subtract"; } }; namespace Subtraction_Tags { using boost::enable_if; using boost::mpl::or_; struct Componentwise; template<typename T1, typename T2, typename = void> struct Compute { typedef void type; }; template<typename T1, typename T2> struct Compute < T1, T2, typename enable_if < or_ < are_compatible_vectors<T1, T2>, are_compatible_quats<T1, T2> > >::type > { typedef Componentwise type; }; } namespace detail { template<typename Tag> struct Subtraction_impl; template<typename T1, typename T2> struct Subtraction_Specialization : Subtraction_impl<typename Subtraction_Tags::Compute<T1, T2>::type>::template apply<T1, T2>, BinarySpecializedOperator<Subtraction, T1, T2> {}; template<typename Tag> struct Subtraction_impl { template<typename T1, typename T2> struct apply { }; }; /// Two vectors: subtraction. template<> struct Subtraction_impl <Subtraction_Tags::Componentwise> { template<typename T1, typename T2> struct apply { typedef typename promote_type_with_scalar<T1, typename get_scalar<T2>::type>::type return_type; template<typename A, typename B> static return_type performOperation(A const& v1, B const& v2) { return return_type(v1) - return_type(v2); } }; }; } // end of namespace detail struct Subtraction : BinaryOperatorBase { template<typename T1, typename T2> struct apply { typedef detail::Subtraction_Specialization<T1, T2> type; }; }; } // end of namespace osgTraits #endif // INCLUDED_Subtraction_h_GUID_fec3e459_c1e7_441b_9a1b_bc11a65a8336
13fbfb74c2dbe0bdff17de9dbdeff5c1e7e3e373
bfe8cb3576ab78950a0a91b43876da0629fc6def
/17Graphs-1/temp.cpp
7731bd7272c08fd0bf4a9ae00fbf8b57b58196da
[]
no_license
avinesh2101/coding-ninjas-competitive-part-3
832afe630463b0e7865337331d7d565df1dd3f06
ee3cc6d3cdec59135b8390ce5fba2b2fea1dd11e
refs/heads/master
2023-07-08T01:57:34.758497
2021-08-16T17:44:12
2021-08-16T17:44:12
358,331,831
0
0
null
null
null
null
UTF-8
C++
false
false
1,046
cpp
temp.cpp
#include<bits/stdc++.h> using namespace std; void magic(int**edges_btw_verticies,int*visited,int start,int n) { cout<<start<<" "; visited[start]=1; for(int i=0;i<n;i++) { if(i==start) { continue; } if(edges_btw_verticies[start][i]==1) { if(visited[i]==1){ continue; } magic(edges_btw_verticies,visited,i,n); } } } int main() { int n,E;//no. of verticies and no. of edges cin>> n>>E; int**edges_btw_verticies = new int*[n]; for(int i=0;i<n;i++) { edges_btw_verticies[i] = new int [n]; for(int j=0;j<n;j++) { edges_btw_verticies[i][j]=0; } } for(int i=0;i<E;i++) { int f,s; cin>>f>>s; edges_btw_verticies[f][s]=1; edges_btw_verticies[s][f]=1; } int*visited = new int[n]; for(int i=0;i<n;n++) { visited[i]=0; } magic(edges_btw_verticies,visited,0,n); return 0; }
3ee35539d0f882f9b00f5ebfd60e0684df139641
83252aa52b2ec297a5ebe4bf4a9c0a68eb461c3f
/minimum-path-sum.cpp
8f51fc1198d4a8227b543ceafa968f369cab2143
[]
no_license
Kallaf/LeetCode
c399d22184412a931ecb0f3e741265abef628021
31ee8b66715505fdc4f2242aebc50a5c5071b382
refs/heads/master
2021-11-28T06:55:00.323453
2021-11-10T20:48:03
2021-11-10T20:48:03
192,792,659
2
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
minimum-path-sum.cpp
class Solution { public: int minPathSum(vector<vector<int>>& grid) { if(grid.empty() || grid[0].empty())return 0; int R = grid.size()-1,C = grid[0].size()-1; for(int i=R-1;i>=0;i--) grid[i][C] += grid[i+1][C]; for(int j=C-1;j>=0;j--) grid[R][j] += grid[R][j+1]; for(int i=R-1;i>=0;i--) for(int j=C-1;j>=0;j--) grid[i][j] += min(grid[i+1][j],grid[i][j+1]); return grid[0][0]; } };
b72c592b99ef9774104af11729046ef18d630f3e
4246003f5f9f2e42f60cf91867fa794baf6cf977
/main.hpp
b901217707cdf877f501e5ab961eafb425744078
[]
no_license
CourtlandCrouchet/Vitamin-CAP
f5cbc4f861a6a56ec3acb6834cfdca451d926538
a61e7d71b2a1d01ece89d93562153858ec92bcf8
refs/heads/master
2020-07-29T04:38:48.174673
2019-11-19T17:14:55
2019-11-19T17:14:55
209,672,524
1
1
null
2019-10-18T01:04:08
2019-09-20T00:34:51
null
UTF-8
C++
false
false
200
hpp
main.hpp
/* Author(s): Raphaela Updated: 10/20/19 Description: Main program of the application */ #include <iostream> #include "user.hpp" void title(); void login(); void reg(); void listener(); void menu();
f40c76ee7e3bcdc54e8d73c62f7b005e36c4e7fe
a335057fbc9dc7637c1d7cf840a18d197ce5f0bf
/fastpath/messages/Message.cpp
df4deddac0070a8227f6766bf19af9c7c11869e0
[]
no_license
wannabegeek/Fastpath
d6d78e0318a389720ceaa814c53c723e1a2866f3
8cc0c0c846deca7a7e693678c53995d37a868aac
refs/heads/master
2021-06-01T01:07:37.627557
2016-06-15T08:33:43
2016-06-15T08:33:43
51,838,238
2
0
null
null
null
null
UTF-8
C++
false
false
5,821
cpp
Message.cpp
/*************************************************************************** __FILE__ ------------------- copyright : Copyright (c) 2004-2016 Tom Fewster email : tom@wannabegeek.com date : 04/03/2016 ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ***************************************************************************/ #include "fastpath/utils/logger.h" #include "fastpath/messages/Message.h" #include "fastpath/messages/FieldAllocator.h" namespace fp { Message::Message() noexcept : m_hasAddressing(true), m_flags(-1) { m_subject[0] = '\0'; } Message::Message(Message &&other) noexcept : BaseMessage(std::move(other)), m_hasAddressing(other.m_hasAddressing), m_flags(other.m_flags) { std::strcpy(m_subject, other.m_subject); other.m_subject[0] = '\0'; } Message::~Message() noexcept { } const bool Message::operator==(const Message &other) const { return m_flags == other.m_flags && strncmp(m_subject, other.m_subject, max_subject_length) == 0 && BaseMessage::operator==(other); } void Message::clear() noexcept { m_flags = -1; m_subject[0] = '\0'; BaseMessage::clear(); } std::ostream &Message::output(std::ostream &out) const { if (m_hasAddressing) { if (m_subject[0] == '\0') { out << "<no subject>="; } else { out << m_subject << "="; } } return BaseMessage::output(out); } //#ifdef DEBUG // void Message::logMessageBufferDetails(const MessageBuffer::ByteStorageType &buffer) noexcept { // std::stringstream s; // s << "Buffer reports there are " << buffer.remainingReadLength() << " bytes remaining to read from a buffer of " << buffer.length() << " bytes" << std::endl; // // size_t subject_length = 0; // size_t msg_length = 0; // uint8_t flags = 0; // const char *subject = nullptr; // buffer.mark(); // auto status = Message::addressing_details(buffer, &subject, subject_length, flags, msg_length); // buffer.resetRead(); // if (status == CompleteMessage) { // MessageBuffer::ByteStorageType msg_buffer(buffer.readBytes(), msg_length, false); // s << "We have a complete message, consisting of;" << std::endl; // s << "\t Msg Length: " << msg_length << " bytes" << std::endl; // s << "\tSubject: " << std::string(subject, subject_length) << std::endl; // s << "Buffer content: " << msg_buffer << std::endl; // msg_buffer.advanceRead(MsgAddressing::size()); // msg_buffer.advanceRead(subject_length); // // MsgHeader::header_start chk = readScalar<MsgHeader::header_start>(msg_buffer.readBytes()); // msg_buffer.advanceRead(sizeof(MsgHeader::header_start)); // if (chk != 2) { // s << "*** Missing body flag ***"; // } else { // const MsgHeader::field_count field_count = readScalar<MsgHeader::field_count>(msg_buffer.readBytes()); // msg_buffer.advanceRead(sizeof(MsgHeader::field_count)); // s << "Field count: " << field_count << std::endl; // for (size_t i = 0; i < field_count; i++) { // MsgField::type type = unknown; // MsgField::identifier_length identifier_size = 0; // MsgField::data_length data_size = 0; // Field::peek_field_header(msg_buffer, type, identifier_size, data_size); // msg_buffer.advanceRead(MsgField::size()); // msg_buffer.advanceRead(identifier_size); // msg_buffer.advanceRead(data_size); // s << "\tField is type: " << StorageTypeDescription[static_cast<int>(type)] << std::endl; // s << "\tIdentifier Length: " << static_cast<int>(identifier_size) << std::endl; // s << "\tData Length : " << data_size << std::endl; // } // } // } else if (status == IncompleteMessage) { // s << "We have an incomplete message, we require " << msg_length << " bytes but have " << buffer.remainingReadLength() << " bytes" << std::endl; // } else if (status == CorruptMessage) { // s << "**** Received corrupt message ****"; // } // // INFO_LOG(s.str()); // } //#endif }
279ac123f6456a6c0b8c2f9a1c7dbb00fc1cfef6
e0d1bd0f94f07d278118b0ba2ea77f42315a4f0c
/worker.h
0eb58282ef740d995a54a92a9c13843680f1afa0
[ "MIT" ]
permissive
mkinsz/rtspview
e3fce7e94968e706f3f806414f1e8c0323363474
6b1a8d17a4c66afb51f9ca250cb87f5615cdc8e8
refs/heads/master
2023-02-28T22:21:46.360816
2021-02-04T07:33:54
2021-02-04T07:33:54
278,048,772
0
0
null
null
null
null
UTF-8
C++
false
false
709
h
worker.h
#ifndef WORKER_H #define WORKER_H #include <QString> #include <mutex> #include <thread> #include <condition_variable> class CFFmpeg; class Worker { typedef enum { INIT = 0, PLAY, STOP, RELEASE } WORK_STATE; typedef enum { IDLE = 0, WORK, QUIT } STATE; public: explicit Worker(); ~Worker(); void play(const QString &url); void pause(); void stop(); private: void work(); public: CFFmpeg* media() const; private: CFFmpeg *m_ppg; std::mutex m_mtx; std::thread *m_ptd; std::condition_variable m_cv; QString m_url; STATE m_state; WORK_STATE m_wstate; }; #endif // WORKER_H
5a9b60eae3481f1eaca0488cd90db8f93d42ace3
16271058f46a390750da48c340b315712c16ba35
/src/node.h
7fb645f057eedbf5c2ec421c98877afea6179532
[ "MIT" ]
permissive
anqurvanillapy/knoscript
dc0aaed231955eee172c245a4bf923830201949e
4df0e1a3d6c9d75d0676bfc22b224a9a2cc8801b
refs/heads/master
2021-01-11T14:06:16.795127
2017-06-23T15:00:55
2017-06-23T15:00:55
94,965,251
0
0
null
null
null
null
UTF-8
C++
false
false
466
h
node.h
#pragma once #include "tokentypes.h" namespace kno { class node { public: explicit node(const token_type& t, unsigned p) : ty_{t}, start_{p} { /* nop */ } ~node() = default; // Default copy and move. node(const node&) = default; node& operator=(const node&) = default; node(node&&) = default; node& operator=(node&&) = default; private: token_type ty_; unsigned start_; unsigned end_{0}; }; } /* namespace kno */
5ead35d094cf2bae7205ada0c32f9adeb06b0620
15a586ca780042ace62cb5a7bd8c37695e5c1027
/inc/KernelWriter_v2.h
963b5fa95ec7e2dafd3e6ca476c7637747b343b2
[]
no_license
feifei14119/TensileLite
74e76c21f3a2c31c87ebab1f53647d840838bd65
ee19f2b0af0d52520e8c6f276d1331d37658a3eb
refs/heads/master
2021-01-05T16:47:35.298223
2020-08-31T02:07:02
2020-08-31T02:07:02
241,079,369
2
1
null
null
null
null
UTF-8
C++
false
false
9,677
h
KernelWriter_v2.h
/************************************************************************/ /* 这里定义的是依赖于问题配置的相关生成kernel的函数 */ /* 比如group size,传入参数列表等等 */ /* 因此只需要include ProblemControl.h */ /************************************************************************/ #pragma once #include "IsaGenerater.h" namespace feifei { typedef enum class ArgKindEnum { Global = 1, Value = 2 }E_ArgKind; typedef struct KernelArgType { std::string name; size_t argSz; E_ArgKind argKind; bool isConst; }T_KernelArg; class KernelWriter : public IsaGenerater { public: KernelWriter() : IsaGenerater() { kernelArgs.clear(); ldsByteCount = 0; kernelDir = (GpuRuntime::GetInstance())->KernelTempDir(); ensure_dir(kernelDir.c_str()); } public: // TODO: where to clear LDS used byte??? E_ReturnState GenKernelString() { ChkErr(checkKernelParameters()); clearString(); en_dbg_print = true; ChkErr(writeContent()); en_dbg_print = false; clearString(); ChkErr(writeSignature()); ChkErr(writeContent()); ChkErr(writeMetadata()); if (createStatus != E_ReturnState::SUCCESS) return E_ReturnState::RTN_ERR; return E_ReturnState::SUCCESS; } void SaveKernelString2File() { ensure_dir(kernelDir.c_str()); kernelFile = kernelDir + DIR_SPT + kernelName + "_AutoGen.s"; dump2_txt_file(kernelFile, kernelString); } void KernelName(std::string name) { kernelName = name; } void KernelDirectory(std::string dir) { kernelDir = dir; ensure_dir(kernelDir.c_str()); } std::string KernelDirectory() { return kernelDir; } std::string KernelFile() { return kernelFile; } std::string KernelString() { return kernelString; } std::string KernelName() { return kernelName; } dim GroupSize() { return group_sz; } dim GlobalSize() { return global_sz; } E_ReturnState SetArg(std::string name = "", size_t argSz = 8, E_ArgKind kind = E_ArgKind::Global, bool isConst = false) { T_KernelArg arg; arg.argKind = kind; arg.argSz = argSz; arg.name = name; arg.isConst = isConst; kernelArgs.push_back(arg); return E_ReturnState::SUCCESS; } E_ReturnState SetDispatch(T_Dispatch disp) { global_sz = disp.global_size; group_sz = disp.group_size; group_num = global_sz / group_sz; dispatch = disp; } T_Dispatch GetDispatch() { return dispatch; } protected: std::string kernelName; std::string kernelDir; std::string kernelFile; dim group_sz; dim group_num; dim global_sz; T_Dispatch dispatch; std::vector<T_KernelArg> kernelArgs; // ======================================================================= // 默认寄存器和段名 // ======================================================================= //T_Var s_privateSeg; T_Var s_argsAddr; std::vector<T_Var> s_args; T_Var s_bid_x; T_Var s_bid_y; T_Var s_bid_z; T_Var v_tid_x; T_Var v_tid_y; T_Var v_tid_z; T_Var l_start_prog; T_Var l_end_prg; uint32_t dbg_data_cnt = 0; uint32_t dbg_buff_len = 2; // dword bool en_dbg_print = false; /************************************************************************/ /* kernel文件生成函数 */ /************************************************************************/ E_ReturnState writeSignature() { setTable(0); wrLine(".hsa_code_object_version 2, 1"); if (IsaArch == E_IsaArch::Gfx900) { wrLine(".hsa_code_object_isa 9, 0, 0, \"AMD\", \"AMDGPU\""); } else if (IsaArch == E_IsaArch::Gfx803) { wrLine(".hsa_code_object_isa 8, 0, 3, \"AMD\", \"AMDGPU\""); } else if (IsaArch == E_IsaArch::Gfx906) { wrLine(".hsa_code_object_isa 9, 0, 6, \"AMD\", \"AMDGPU\""); } else if (IsaArch == E_IsaArch::Gfx908) { wrLine(".hsa_code_object_isa 9, 0, 8, \"AMD\", \"AMDGPU\""); } wrLine(""); wrLine(".text"); wrLine(".globl " + kernelName); wrLine(".p2align 8"); wrLine(".type " + kernelName + ",@function"); wrLine(".amdgpu_hsa_kernel " + kernelName); wrLine(""); return E_ReturnState::SUCCESS; } virtual E_ReturnState checkKernelParameters() { return E_ReturnState::SUCCESS; }; E_ReturnState writeContent() { setTable(0); wrLine(kernelName + ":"); ChkErr(writeCodeObj()); clrVar(); dbg_data_cnt = 0; ChkErr(initialDefaultGprs()); ChkErr(writeProgramFrameWork()); return E_ReturnState::SUCCESS; } E_ReturnState writeMetadata() { int argSize = 0; for (T_KernelArg arg : kernelArgs) { argSize += arg.argSz; } setTable(0); wrLine(".amd_amdgpu_hsa_metadata"); wrLine("{ Version: [1, 0],"); wrLine(" Kernels :"); wrLine(" - { Name: " + kernelName + ","); wrLine(" SymbolName: " + kernelName + ","); if(GpuRuntime::GpuRtType() == E_GpuRt::HIP) wrLine(" Language: HCC, LanguageVersion: [ 1, 2 ],"); else if (GpuRuntime::GpuRtType() == E_GpuRt::OCL) wrLine(" Language: OpenCL C, LanguageVersion: [ 1, 2 ],"); wrLine(" Attrs: { ReqdWorkGroupSize: [ " + d2s(group_sz.x) + ", " + d2s(group_sz.y) + ", " + d2s(group_sz.z) + " ] }"); wrLine(" CodeProps: { KernargSegmentSize: " + d2s(argSize) + ", GroupSegmentFixedSize : 0, PrivateSegmentFixedSize : 0, KernargSegmentAlign : 8, WavefrontSize : 64, MaxFlatWorkGroupSize : " + d2s(group_sz.x * group_sz.y) + " }"); wrLine(" Args:"); for (T_KernelArg arg : kernelArgs) { std::string strtmp = " - {"; strtmp += " Name: " + arg.name + ","; strtmp += " Size: " + d2s(arg.argSz) + ","; strtmp += " Align: " + d2s(arg.argSz) + ","; if (arg.argKind == E_ArgKind::Global) strtmp += " ValueKind: GlobalBuffer,"; else if(arg.argKind == E_ArgKind::Value) strtmp += " ValueKind: ByValue,"; if(arg.argSz == 8 && arg.argKind == E_ArgKind::Value) strtmp += " ValueType: F64, TypeName: 'double',"; else strtmp += " ValueType: F32, TypeName: 'float*',"; if (arg.isConst == true) strtmp += " AddrSpaceQual: Global, IsConst: true"; else strtmp += " AddrSpaceQual: Global"; strtmp += " }"; wrLine(strtmp); } wrLine(" }"); wrLine("}"); wrLine(".end_amd_amdgpu_hsa_metadata"); wrLine(""); return E_ReturnState::SUCCESS; } /************************************************************************/ /* kernel 函数内容生成函数 */ /************************************************************************/ E_ReturnState initialDefaultGprs() { //s_privateSeg = newSgpr("s_privateSeg", 4); s_argsAddr = newSgpr("s_argsAddr", 2); s_bid_x = newSgpr("s_bid_x"); s_bid_y = newSgpr("s_bid_y"); s_bid_z = newSgpr("s_bid_z"); v_tid_x = newVgpr("v_tid_x"); v_tid_y = newVgpr("v_tid_y"); v_tid_z = newVgpr("v_tid_z"); l_start_prog = newLaber("START_PROG"); l_end_prg = newLaber("END_PROG"); return E_ReturnState::SUCCESS; } E_ReturnState writeCodeObj() { setTable(1); wrLine(".amd_kernel_code_t"); indent(); wrLine("amd_code_version_major = 1"); wrLine("amd_code_version_minor = 1"); wrLine("amd_machine_kind = 1"); wrLine("amd_machine_version_major = 8"); wrLine("amd_machine_version_minor = 0"); wrLine("amd_machine_version_stepping = 3"); wrLine("kernarg_segment_alignment = 4"); wrLine("group_segment_alignment = 4"); wrLine("private_segment_alignment = 4"); wrLine("wavefront_size = 6"); wrLine("call_convention = -1"); //wrLine("enable_sgpr_private_segment_buffer = 1"); wrLine("enable_sgpr_kernarg_segment_ptr = 1"); wrLine("enable_sgpr_workgroup_id_x = 1"); wrLine("enable_sgpr_workgroup_id_y = 1"); wrLine("enable_sgpr_workgroup_id_z = 1"); wrLine("enable_vgpr_workitem_id = 2"); wrLine("is_ptr64 = 1"); wrLine("float_mode = 192"); wrLine("granulated_wavefront_sgpr_count = " + d2s((sgprCountMax + 6 + 8 - 1) / 8 - 1)); wrLine("granulated_workitem_vgpr_count = " + d2s((vgprCountMax + 4 - 1) / 4 - 1)); wrLine("user_sgpr_count = 2"); // for kernel param list pointer wrLine("wavefront_sgpr_count = " + d2s(sgprCountMax + 6)); wrLine("workitem_vgpr_count = " + d2s(vgprCountMax)); wrLine("kernarg_segment_byte_size = 44"); wrLine("workgroup_group_segment_byte_size = " + d2s(ldsByteCount)); backSpace(); wrLine(".end_amd_kernel_code_t"); wrLine(""); if (sgprCountMax >= MAX_SGPR_COUNT) return E_ReturnState::RTN_ERR; if (vgprCountMax >= MAX_VGPR_COUNT) return E_ReturnState::RTN_ERR; if (ldsByteCount > MAX_LDS_SIZE) return E_ReturnState::RTN_ERR; static bool log_once = false; if (log_once == false) { log_once = true; } else { LOG("sgpr usage = %d.", sgprCountMax); LOG("vgpr usage = %d.", vgprCountMax); LOG("lds usage = %.3f(KB).", ldsByteCount / 1024.0); } return E_ReturnState::SUCCESS; } E_ReturnState writeProgramFrameWork() { setTable(0); wrLaber(l_start_prog); indent(); ChkErr(writeProgramDetail()); setTable(0); wrLaber(l_end_prg); indent(); wrLine("s_endpgm\n"); return E_ReturnState::SUCCESS; } virtual E_ReturnState writeProgramDetail() = 0; /************************************************************************/ /* 常用kernel函数 */ /************************************************************************/ void f_load_kernel_args() { s_args.clear(); uint32_t bias = 0; for (T_KernelArg arg : kernelArgs) { T_Var s_arg; if (arg.argSz == 4) { s_arg = newSgpr("s_arg"); s_load_dword(1, s_arg, s_argsAddr, bias); } else if (arg.argSz == 8) { s_arg = newSgpr("s_arg", 2, 2); s_load_dword(2, s_arg, s_argsAddr, bias); } bias += arg.argSz; s_args.push_back(s_arg); } s_wait_lgkmcnt(0); } }; }
d4f4072a9db7deb8148fe097ff678a5dfc15bc37
0337c1df871a431c6a8b03ad871d396826d7e210
/src/plugins/alsaout/AlsaOut.cpp
de4e2ef0b5192cd50492289c67782d641b1cb641
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
clangen/musikcube
be1ad8c1567c9e3cfbf71e1f595ede9aa0152a97
64485978ea2e4483499996a8e2304ce5566573d9
refs/heads/master
2023-08-28T00:52:06.905519
2023-08-02T02:47:41
2023-08-02T02:47:41
32,483,164
4,049
370
BSD-3-Clause
2023-09-08T05:05:44
2015-03-18T20:41:57
C++
UTF-8
C++
false
false
15,495
cpp
AlsaOut.cpp
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "AlsaOut.h" #include <musikcore/sdk/constants.h> #include <musikcore/sdk/IPreferences.h> static musik::core::sdk::IPreferences* prefs; #define BUFFER_COUNT 16 #define PCM_ACCESS_TYPE SND_PCM_ACCESS_RW_INTERLEAVED #define PCM_FORMAT SND_PCM_FORMAT_FLOAT_LE #define PREF_DEVICE_ID "device_id" #define LOCK(x) \ /*std::cerr << "locking " << x << "\n";*/ \ std::unique_lock<std::recursive_mutex> lock(this->stateMutex); \ /*std::cerr << "locked " << x << "\n";*/ \ #define WAIT() this->threadEvent.wait(lock); #define NOTIFY() this->threadEvent.notify_all(); #define CHECK_QUIT() if (this->quit) { return; } #define PRINT_ERROR(x) std::cerr << "AlsaOut: error! " << snd_strerror(x) << std::endl; #define WRITE_BUFFER(handle, context, samples) \ err = snd_pcm_writei(handle, context->buffer->BufferPointer(), samples); \ if (err < 0) { PRINT_ERROR(err); } static inline bool playable(snd_pcm_t* pcm) { if (!pcm) { return false; } snd_pcm_state_t state = snd_pcm_state(pcm); if (state == SND_PCM_STATE_RUNNING || state == SND_PCM_STATE_PREPARED) { return true; } std::cerr << "AlsaOut: invalid device state: " << (int) state << "\n"; return false; } using namespace musik::core::sdk; class AlsaDevice : public IDevice { public: AlsaDevice(const std::string& id, const std::string& name) { this->id = id; this->name = name; } virtual void Release() override { delete this; } virtual const char* Name() const override { return name.c_str(); } virtual const char* Id() const override { return id.c_str(); } private: std::string name, id; }; class AlsaDeviceList : public musik::core::sdk::IDeviceList { public: virtual void Release() override { delete this; } virtual size_t Count() const override { return devices.size(); } virtual const IDevice* At(size_t index) const override { return &devices.at(index); } void Add(const std::string& id, const std::string& name) { devices.push_back(AlsaDevice(id, name)); } private: std::vector<AlsaDevice> devices; }; extern "C" void SetPreferences(musik::core::sdk::IPreferences* prefs) { ::prefs = prefs; prefs->GetString(PREF_DEVICE_ID, nullptr, 0, ""); prefs->Save(); } static std::string getDeviceId() { return getPreferenceString<std::string>(prefs, PREF_DEVICE_ID, ""); } AlsaOut::AlsaOut() : pcmHandle(nullptr) , device("default") , channels(2) , rate(44100) , volume(1.0) , quit(false) , paused(false) , latency(0) , initialized(false) { std::cerr << "AlsaOut::AlsaOut() called" << std::endl; this->writeThread.reset(new std::thread(std::bind(&AlsaOut::WriteLoop, this))); } AlsaOut::~AlsaOut() { std::cerr << "AlsaOut: destructor\n"; { LOCK("dtor"); this->quit = true; NOTIFY(); } std::cerr << "AlsaOut: joining...\n"; this->writeThread->join(); std::cerr << "AlsaOut: closing device...\n"; this->CloseDevice(); std::cerr << "AlsaOut: destroyed.\n"; } void AlsaOut::CloseDevice() { LOCK("CloseDevice()"); if (this->pcmHandle) { std::cerr << "AlsaOut: closing PCM handle\n"; snd_pcm_close(this->pcmHandle); this->pcmHandle = nullptr; this->latency = 0.0; } } musik::core::sdk::IDevice* AlsaOut::GetDefaultDevice() { return findDeviceById<AlsaDevice, IOutput>(this, getDeviceId()); } bool AlsaOut::SetDefaultDevice(const char* deviceId) { return setDefaultDevice<IPreferences, AlsaDevice, IOutput>(prefs, this, PREF_DEVICE_ID, deviceId); } IDeviceList* AlsaOut::GetDeviceList() { AlsaDeviceList* result = new AlsaDeviceList(); /* https://stackoverflow.com/a/6870226 */ char** hints; if (snd_device_name_hint(-1, "pcm", (void***)&hints) == 0) { char** n = hints; while (*n != nullptr) { char *name = snd_device_name_get_hint(*n, "NAME"); if (name) { std::string stdName = name; if (stdName != "default") { result->Add(stdName, stdName); } free(name); } ++n; } snd_device_name_free_hint((void**) hints); } size_t n = result->Count(); return result; } std::string AlsaOut::GetPreferredDeviceId() { std::string result; if (prefs) { std::string storedDeviceId = getDeviceId(); auto deviceList = GetDeviceList(); if (deviceList) { for (size_t i = 0; i < deviceList->Count(); i++) { if (deviceList->At(i)->Id() == storedDeviceId) { result = storedDeviceId; break; } } deviceList->Release(); } } return result; } void AlsaOut::InitDevice() { int err, dir; unsigned int rate = (unsigned int) this->rate; std::string preferredDeviceId = this->GetPreferredDeviceId(); bool preferredOk = false; if (preferredDeviceId.size() > 0) { if ((err = snd_pcm_open(&this->pcmHandle, preferredDeviceId.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { std::cerr << "AlsaOut: cannot opened preferred device id " << preferredDeviceId << ": " << snd_strerror(err) << std::endl; } else { preferredOk = true; } } if (!preferredOk && (err = snd_pcm_open(&this->pcmHandle, this->device.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { std::cerr << "AlsaOut: cannot open audio device 'default' :" << snd_strerror(err) << std::endl; goto error; } if ((err = snd_pcm_hw_params_malloc(&hardware)) < 0) { std::cerr << "AlsaOut: cannot allocate hardware parameter structure " << snd_strerror(err) << std::endl; goto error; } if ((err = snd_pcm_hw_params_any(pcmHandle, hardware)) < 0) { std::cerr << "AlsaOut: cannot initialize hardware parameter structure " << snd_strerror(err) << std::endl; goto error; } if ((err = snd_pcm_hw_params_set_access(pcmHandle, hardware, PCM_ACCESS_TYPE)) < 0) { std::cerr << "AlsaOut: cannot set access type " << snd_strerror(err) << std::endl; goto error; } if ((err = snd_pcm_hw_params_set_format(pcmHandle, hardware, PCM_FORMAT)) < 0) { std::cerr << "AlsaOut: cannot set sample format " << snd_strerror(err) << std::endl; goto error; } if ((err = snd_pcm_hw_params_set_rate_near(pcmHandle, hardware, &rate, 0)) < 0) { std::cerr << "AlsaOut: cannot set sample rate " << snd_strerror(err) << std::endl; goto error; } if ((err = snd_pcm_hw_params_set_channels(pcmHandle, hardware, this->channels)) < 0) { std::cerr << "AlsaOut: cannot set channel count " << snd_strerror(err) << std::endl; goto error; } if ((err = snd_pcm_hw_params(pcmHandle, hardware)) < 0) { std::cerr << "AlsaOut: cannot set parameters " << snd_strerror(err) << std::endl; goto error; } snd_pcm_hw_params_free(hardware); if ((err = snd_pcm_prepare (pcmHandle)) < 0) { std::cerr << "AlsaOut: cannot prepare audio interface for use " << snd_strerror(err) << std::endl; goto error; } snd_pcm_nonblock(pcmHandle, 0); /* operate in blocking mode for simplicity */ std::cerr << "AlsaOut: device seems to be prepared for use!\n"; this->initialized = true; return; error: this->CloseDevice(); } void AlsaOut::Release() { delete this; } double AlsaOut::Latency() { if (latency <= 0.0f) { LOCK("latency_calc"); if (this->pcmHandle && this->rate && this->channels) { snd_pcm_uframes_t bufferSize = 0, periodSize = 0; snd_pcm_get_params(this->pcmHandle, &bufferSize, &periodSize); if (bufferSize) { this->latency = (double) bufferSize / (double) (this->rate * this->channels * sizeof(float)); } } } return this->latency; } void AlsaOut::Stop() { std::list<std::shared_ptr<BufferContext> > toNotify; { LOCK("stop"); std::swap(this->buffers, toNotify); if (this->pcmHandle) { snd_pcm_drop(this->pcmHandle); this->CloseDevice(); } } auto it = toNotify.begin(); while (it != toNotify.end()) { ((*it)->provider)->OnBufferProcessed((*it)->buffer); ++it; } } void AlsaOut::Pause() { LOCK("pause"); if (this->pcmHandle) { snd_pcm_pause(this->pcmHandle, 1); this->paused = true; } } void AlsaOut::Resume() { LOCK("resume"); if (this->pcmHandle) { snd_pcm_pause(this->pcmHandle, 0); this->paused = false; NOTIFY(); } } void AlsaOut::SetVolume(double volume) { LOCK("set volume"); this->volume = volume; } double AlsaOut::GetVolume() { return this->volume; } void AlsaOut::WriteLoop() { { LOCK("thread: init"); while (!quit && !initialized) { WAIT(); } } { while (!quit) { std::shared_ptr<BufferContext> next; { LOCK("thread: waiting for buffer"); while (!quit && (!playable(this->pcmHandle) || !this->buffers.size())) { WAIT(); } CHECK_QUIT(); next = this->buffers.front(); this->buffers.pop_front(); } int err; if (next) { size_t samples = next->buffer->Samples(); size_t channels = next->buffer->Channels(); size_t samplesPerChannel = samples / channels; float volume = (float) this->volume; /* software volume; alsa doesn't support this internally. this is about as terrible as an algorithm can be -- it's just a linear ramp. */ //std::cerr << "volume=" << volume << std::endl; if (volume != 1.0f) { float *buffer = next->buffer->BufferPointer(); for (size_t i = 0; i < samples; i++) { (*buffer) *= volume; ++buffer; } } { LOCK("WRITE_BUFFER()"); if (this->pcmHandle) { WRITE_BUFFER(this->pcmHandle, next, samplesPerChannel); /* sets 'err' */ if (err == -EINTR || err == -EPIPE || err == -ESTRPIPE) { if (!snd_pcm_recover(this->pcmHandle, err, 1)) { /* try one more time... */ WRITE_BUFFER(this->pcmHandle, next, samplesPerChannel); } } } } if (err > 0 && err < (int) samplesPerChannel) { std::cerr << "AlsaOut: short write. expected=" << samplesPerChannel << ", actual=" << err << std::endl; } next->provider->OnBufferProcessed(next->buffer); } } } std::cerr << "AlsaOut: thread finished\n"; } OutputState AlsaOut::Play(IBuffer *buffer, IBufferProvider* provider) { this->SetFormat(buffer); { LOCK("play"); if (this->paused) { return OutputState::InvalidState; } if (this->CountBuffersWithProvider(provider) >= BUFFER_COUNT) { return OutputState::BufferFull; } std::shared_ptr<BufferContext> context(new BufferContext()); context->buffer = buffer; context->provider = provider; this->buffers.push_back(context); if (!playable(this->pcmHandle)) { std::cerr << "AlsaOut: sanity check -- stream not playable. adding buffer to queue anyway\n"; } else { NOTIFY(); } } return OutputState::BufferWritten; } void AlsaOut::Drain() { LOCK("drain"); if (this->pcmHandle) { std::cerr << "draining...\n"; snd_pcm_drain(this->pcmHandle); std::cerr << "drained\n"; } } void AlsaOut::SetFormat(IBuffer *buffer) { LOCK("set format"); if (this->channels != buffer->Channels() || this->rate != buffer->SampleRate() || this->pcmHandle == nullptr) { this->channels = buffer->Channels(); this->rate = buffer->SampleRate(); this->CloseDevice(); this->InitDevice(); if (this->pcmHandle) { int err = snd_pcm_set_params( this->pcmHandle, PCM_FORMAT, PCM_ACCESS_TYPE, this->channels, this->rate, 1, /* allow resampling */ 500000); /* 0.5s latency */ if (err > 0) { std::cerr << "AlsaOut: set format error: " << snd_strerror(err) << std::endl; } else { this->SetVolume(this->volume); } } std::cerr << "AlsaOut: device format initialized from buffer\n"; } } size_t AlsaOut::CountBuffersWithProvider(IBufferProvider* provider) { LOCK("count"); size_t count = 0; auto it = this->buffers.begin(); while (it != this->buffers.end()) { if ((*it)->provider == provider) { ++count; } ++it; } return count; }
bee4f421ce179681717fe8a112bfd83b676b6172
d5a7db34f14c6d79b09bad6ee5e9c661d28aefb9
/camera.h
fb535dfb17750b5543bcb52a3909cda48b56d29e
[]
no_license
alvarosamudio/deepin-camera
29921a1d049949550ae2490c70334d49b4eefa3d
e348baea419fa512f09f08d1644d15efdbdcda38
refs/heads/master
2023-02-17T15:35:21.687854
2023-02-17T00:20:32
2023-02-17T00:20:32
262,725,812
3
0
null
null
null
null
UTF-8
C++
false
false
2,026
h
camera.h
#ifndef CAMERA_H #define CAMERA_H #include <QCamera> #include <QCameraImageCapture> #include <QMediaRecorder> #include <QScopedPointer> #include <QMainWindow> #include <DApplication> #include <DMainWindow> #include <DWidgetUtil> QT_BEGIN_NAMESPACE namespace Ui { class Camera; } QT_END_NAMESPACE class Camera : public QMainWindow { Q_OBJECT public: Camera(); private slots: void setCamera(const QCameraInfo &cameraInfo); void startCamera(); void stopCamera(); void record(); void pause(); void stop(); void setMuted(bool); void toggleLock(); void takeImage(); void displayCaptureError(int, QCameraImageCapture::Error, const QString &errorString); void configureCaptureSettings(); void configureVideoSettings(); void configureImageSettings(); void displayRecorderError(); void displayCameraError(); void updateCameraDevice(QAction *action); void updateCameraState(QCamera::State); void updateCaptureMode(); void updateRecorderState(QMediaRecorder::State state); void setExposureCompensation(int index); void updateRecordTime(); void processCapturedImage(int requestId, const QImage &img); void updateLockStatus(QCamera::LockStatus, QCamera::LockChangeReason); void displayViewfinder(); void displayCapturedImage(); void readyForCapture(bool ready); void imageSaved(int id, const QString &fileName); protected: void keyPressEvent(QKeyEvent *event) override; void keyReleaseEvent(QKeyEvent *event) override; void closeEvent(QCloseEvent *event) override; private: Ui::Camera *ui; QScopedPointer<QCamera> m_camera; QScopedPointer<QCameraImageCapture> m_imageCapture; QScopedPointer<QMediaRecorder> m_mediaRecorder; QImageEncoderSettings m_imageSettings; QAudioEncoderSettings m_audioSettings; QVideoEncoderSettings m_videoSettings; QString m_videoContainerFormat; bool m_isCapturingImage = false; bool m_applicationExiting = false; }; #endif
b682a624a4822d47201d3f554c49adb4451a374e
e8091f7b3b718e5bc643fe7b65496a68508eb8fa
/OGL_Application/src/Physics/physics.cpp
9f5e8a01bc33ef93645fcb378b1131aa7ad974c5
[]
no_license
AndreaLoforte/OGL_Application_20210909
45936a48345a946b7cba304aee0fd24e630e088f
019ab1c9353c530cbde90f95b7718f59cfd196f3
refs/heads/master
2023-08-14T08:39:21.046301
2021-09-09T01:01:42
2021-09-09T01:01:42
268,587,882
0
0
null
null
null
null
ISO-8859-1
C++
false
false
5,541
cpp
physics.cpp
#include<physics.h> #include<applicationObjectManager.h> #include<objectCollector.h> #include<sound.h> namespace myphysicsNS { unsigned CollisorePolimorfo::frameContactCounter = 0; CollisionData CollisorePolimorfo::cdata; ContactResolver CollisorePolimorfo::resolver; std::vector<myobjectNS::ApplicationObject*> CollisorePolimorfo::CPobjectslist; void CollisorePolimorfo::generateContacts() { typedef myobjectNS::ApplicationObjectManager AOManager; CPobjectslist.clear(); /*metto tutti gli oggetti in una lista lineare*/ for (int i = 0; i < myobjectNS::ApplicationObjectManager::ApplicationCollectorList.size(); i++) { for (int j = 0; j < myobjectNS::ApplicationObjectManager::ApplicationCollectorList[i]->getSize(); j++) { CPobjectslist.push_back(myobjectNS::ApplicationObjectManager::ApplicationCollectorList[i]->getSubObject(j)); } } /*invoco il collision detector su ogni coppia*/ for (int i = 0; i < CPobjectslist.size(); i++) for (int j = i + 1; j < CPobjectslist.size(); j++) CPinvokeCollisionDetector(CPobjectslist[i], CPobjectslist[j]); } void CollisorePolimorfo::CPinvokeCollisionDetector(myobjectNS::ApplicationObject* o1, myobjectNS::ApplicationObject* o2) { /*0 => SFERA 1 => HALF SPACE 2 => BOX 3 => TRUE PLANE*/ int CollisorID1 = o1->getCollisorID(); int CollisorID2 = o2->getCollisorID(); myobjectNS::ObjectSphere *sphere1, *sphere2; myobjectNS::ObjectPlane *plane1, *plane2; myobjectNS::ObjectBox *box1, *box2; //Poichè non sappiamo a priori come avverranno le chiamate a questa funzione dobbiamo considerare //tutte le possibili casistiche per chiamare il collision detector nell'ordine corretto using namespace myobjectNS; /*SFERA - SFERA*/ if (CollisorID1 == SPHERECOLLISORID && CollisorID2 == SPHERECOLLISORID) { sphere1 = dynamic_cast<myobjectNS::ObjectSphere*> (o1); sphere2 = dynamic_cast<myobjectNS::ObjectSphere*> (o2); if (sphere1->AOcollectorOwnershipID == sphere2->AOcollectorOwnershipID) return; CollisionDetector::ACD.sphereAndSphere(*sphere1, *sphere2, &cdata); } /* UNAVAILABLE */ if (CollisorID1 == SPHERECOLLISORID && CollisorID2 == PLANECOLLISORID) { sphere1 = dynamic_cast<myobjectNS::ObjectSphere*> (o1); plane1 = dynamic_cast<myobjectNS::ObjectPlane*> (o2); /*tutti i piani adesso vengono costruiti come collisionFinitePlane. Necessario creare nuovi oggetti per halfSpace e infinite Plane*/ //bool collide = CollisionDetector::sphereAndHalfSpace(*sphere1, *plane1, &cdata); } /*SFERA - PIANO FINITO*/ { if (CollisorID1 == SPHERECOLLISORID && CollisorID2 == FINITEPLANECOLLISORID) { sphere1 = dynamic_cast<myobjectNS::ObjectSphere*> (o1); plane1 = dynamic_cast<myobjectNS::ObjectPlane*> (o2); CollisionDetector::ACD.sphereAndFinitePlane(*sphere1, *plane1, &cdata); } if (CollisorID1 == FINITEPLANECOLLISORID && CollisorID2 == SPHERECOLLISORID) { sphere1 = dynamic_cast<myobjectNS::ObjectSphere*> (o2); plane1 = dynamic_cast<myobjectNS::ObjectPlane*> (o1); CollisionDetector::ACD.sphereAndFinitePlane(*sphere1, *plane1, &cdata); } } /*BOX - PIANO FINITO*/ { if (CollisorID1 == FINITEPLANECOLLISORID && CollisorID2 == BOXCOLLISORID) { box1 = dynamic_cast<myobjectNS::ObjectBox*> (o2); plane1 = dynamic_cast<myobjectNS::ObjectPlane*> (o1); CollisionDetector::ACD.boxAndFinitePlane(*box1, *plane1, &cdata); } if (CollisorID1 == BOXCOLLISORID && CollisorID2 == FINITEPLANECOLLISORID) { plane1 = dynamic_cast<myobjectNS::ObjectPlane*> (o2); box1 = dynamic_cast<myobjectNS::ObjectBox*> (o1); CollisionDetector::ACD.boxAndFinitePlane(*box1, *plane1, &cdata); } } /*BOX - SFERA*/ { if (CollisorID1 == SPHERECOLLISORID && CollisorID2 == BOXCOLLISORID) { sphere1 = dynamic_cast<myobjectNS::ObjectSphere*> (o1); box1 = dynamic_cast<myobjectNS::ObjectBox*> (o2); //CollisionDetector::ACD.BoxAndSphere(*box1, *sphere1, &cdata); CollisionDetector::boxAndSphere(*box1, *sphere1, &cdata); } if (CollisorID1 == BOXCOLLISORID && CollisorID2 == SPHERECOLLISORID) { box1 = dynamic_cast<myobjectNS::ObjectBox*> (o1); sphere1 = dynamic_cast<myobjectNS::ObjectSphere*> (o2); //CollisionDetector::ACD.BoxAndSphere(*box1, *sphere1, &cdata); CollisionDetector::boxAndSphere(*box1, *sphere1, &cdata); } } {//BOX - HALF SPACE---DISATTIVATO if (CollisorID1 == HALFSPACECOLLISORID && CollisorID2 == BOXCOLLISORID) { plane1 = dynamic_cast<myobjectNS::ObjectPlane*> (o1); box1 = dynamic_cast<myobjectNS::ObjectBox*> (o2); //CollisionDetector::boxAndHalfSpace(*box1, *plane1, &cdata); } if (CollisorID1 == BOXCOLLISORID && CollisorID2 == HALFSPACECOLLISORID) { box1 = dynamic_cast<myobjectNS::ObjectBox*> (o1); plane1 = dynamic_cast<myobjectNS::ObjectPlane*> (o2); //CollisionDetector::boxAndHalfSpace(*box1, *plane1, &cdata); } } //SFERA - HALF SPACE if (CollisorID1 == HALFSPACECOLLISORID && CollisorID2 == SPHERECOLLISORID) { plane1 = dynamic_cast<myobjectNS::ObjectPlane*> (o1); sphere1 = dynamic_cast<myobjectNS::ObjectSphere*> (o2); //CollisionDetector::sphereAndHalfSpace(*sphere1, *plane1, &cdata); } //BOX-BOX if (CollisorID1 == BOXCOLLISORID && CollisorID2 == BOXCOLLISORID) { box1 = dynamic_cast<myobjectNS::ObjectBox*> (o1); box2 = dynamic_cast<myobjectNS::ObjectBox*> (o2); CollisionDetector::boxAndBox(*box1, *box2, &cdata); } } }
3f10fb3c6ee8f0c6bd40033fddcf71e542a497ff
b7218ad097099bceca840ba069f62ed1ef12863d
/apiwidget.h
66bf1bad8ef71c116f476284c52088ad091cee86
[]
no_license
Gonglja/translate
631a034dd9a51e8f9c8d8ff8674a8c431b25a83b
cd04bcae1658e58cfcacc1f17da90b5ca2a7df2f
refs/heads/master
2022-06-24T05:14:36.892681
2020-05-12T06:24:32
2020-05-12T06:24:32
263,248,339
9
4
null
null
null
null
UTF-8
C++
false
false
716
h
apiwidget.h
#ifndef APIWIDGET_H #define APIWIDGET_H #include <QWidget> namespace Ui { class APIWidget; } class APIWidget : public QWidget { Q_OBJECT public: explicit APIWidget(QWidget *parent = nullptr); ~APIWidget(); bool readConfig(int &status); QString getAppid(); QString getKey(); QString getUrl(); private slots: void on_pushButton_clicked(); private: Ui::APIWidget *ui; QString m_appid;//appid 百度翻译中心注册得到 QString m_key; //key 百度翻译中心注册得到 QString m_url; //url bool m_configReadFlag; // 默认为false 使用默认配置, 当检测到用户设置api后,读取存入到config.json中的配置 }; #endif // APIWIDGET_H
b027fc17dec513075daadd82da6ea797cb32c030
7de5fbe39b41f16e53f11cff56bc289c181a1442
/Neurtal-network/video/util/common.h
a688845780520a379b33c648e41290e90ea87ebf
[]
no_license
xuetongWang/NVIDIA-tx2-
89eac541fa5d18d625626d1260a98041d6fa180b
9e03d056acfa558b61a16ecd6409ce1f496dfaec
refs/heads/master
2020-04-24T14:46:56.922467
2019-09-27T06:41:07
2019-09-27T06:41:07
172,036,476
0
0
null
null
null
null
UTF-8
C++
false
false
4,124
h
common.h
#pragma once #include <vector> #include <assert.h> #include <istream> #include <iostream> #include <experimental/filesystem> #include <fstream> #include <algorithm> #include <iomanip> #include <map> #include "../yolo/network/yolov3.h" namespace fs = std::experimental::filesystem; #define CHECK(status) \ { \ if (status != 0) \ { \ std::cout << "Cuda failure: " << cudaGetErrorString(status) << " in file " << __FILE__ \ << " at line " << __LINE__ << std::endl; \ abort(); \ } \ } #define LOG_GSTRM "[camer.cpp]" class common { public: common() {} static std::vector<std::string> loadListFromTextFile(const std::string filename) { assert(fileExists(filename)); std::vector<std::string> list; std::ifstream f(filename); if (!f) { std::cout << "failed to open " << filename; assert(0); } std::string line; while (std::getline(f, line)) { if (line.empty()) continue; else list.push_back(trim(line)); } return list; } static bool fileExists(const std::string fileName) { //fs::path file = fileName; if (!fs::exists(fs::path(fileName))) { std::cout << "File does not exist : " << fileName << std::endl; return false; } return true; } static void leftTrim(std::string& s) { s.erase(s.begin(), find_if(s.begin(), s.end(), [](int ch) { return !isspace(ch); })); } static void rightTrim(std::string& s) { s.erase(find_if(s.rbegin(), s.rend(), [](int ch) { return !isspace(ch); }).base(), s.end()); } static std::string trim(std::string s) { leftTrim(s); rightTrim(s); return s; } static bool splitCfgfile(int &batchsize , NetworkInfo &yoloInfo, InferParams &yoloInferParams,const std::vector<std::string> &config_Info) { std::map<std::string,std::string> map_config_info; for(int id=0;id < config_Info.size();id++) { std::string cur_string = config_Info[id]; int pos = cur_string.find('='); if(pos == std::string::npos) continue; std::string name_string = cur_string.substr(0,pos); map_config_info[name_string] = cur_string.substr(pos+1); } std::string network_type = map_config_info["network_type"]; std::string config_file_path = map_config_info["config_file_path"]; std::string wts_file_path = map_config_info["wts_file_path"]; std::string labels_file_path = map_config_info["labels_file_path"]; std::string precision = map_config_info["precision"]; std::string deviceType = map_config_info["deviceType"]; batchsize = std::stoi(map_config_info["batch_size"]); float prob_thresh = std::stof(map_config_info["prob_thresh"]); float nms_thresh = std::stof(map_config_info["nms_thresh"]); int npos = wts_file_path.find(".weights"); std::string dataPath = wts_file_path.substr(0, npos); std::string engine_file_path = dataPath + "-" + precision + "-" + deviceType + "-batch" + std::to_string(batchsize) + ".engine"; yoloInfo = NetworkInfo{network_type,config_file_path, wts_file_path, labels_file_path,precision,deviceType,"", engine_file_path, "data"}; yoloInferParams = InferParams{0, 0, "", "", prob_thresh,nms_thresh}; return true; } };
5a74c21307c8f2e8441493f7362c24b53bed7881
7fb115f50fab6ca25243551ce42819215b60578d
/src/ChessBoard.cpp
75806b7f0c6b8a0b191da91a0205b3ae2f41cdb0
[]
no_license
Doxterpepper/DChess
452063d5f2d8577e5ed4f63bdc22b197a57be509
6af61e3616e2dd620de16962aa9126fd55eaa999
refs/heads/master
2022-07-26T09:35:56.547198
2020-05-15T04:25:42
2020-05-15T04:25:42
264,093,288
0
0
null
null
null
null
UTF-8
C++
false
false
3,364
cpp
ChessBoard.cpp
#include "ChessBoard.h" #include <assert.h> namespace DChess { /** * Construct a new chessboard. Constructs an 8x8 board with white and black pieces. */ ChessBoard::ChessBoard() { // Initialize black pieces. board.push_back(new Piece(Rook, Black)); board.push_back(new Piece(Knight, Black)); board.push_back(new Piece(Bishop, Black)); board.push_back(new Piece(Queen, Black)); board.push_back(new Piece(King, Black)); board.push_back(new Piece(Bishop, Black)); board.push_back(new Piece(Knight, Black)); board.push_back(new Piece(Rook, Black)); board.push_back(new Piece(Pawn, Black)); board.push_back(new Piece(Pawn, Black)); board.push_back(new Piece(Pawn, Black)); board.push_back(new Piece(Pawn, Black)); board.push_back(new Piece(Pawn, Black)); board.push_back(new Piece(Pawn, Black)); board.push_back(new Piece(Pawn, Black)); board.push_back(new Piece(Pawn, Black)); // Fill empty spaces in the middle. for (int i = 0; i < 4 * 8; i++) { board.push_back(nullptr); } // Initialize White pieces. board.push_back(new Piece(Pawn, White)); board.push_back(new Piece(Pawn, White)); board.push_back(new Piece(Pawn, White)); board.push_back(new Piece(Pawn, White)); board.push_back(new Piece(Pawn, White)); board.push_back(new Piece(Pawn, White)); board.push_back(new Piece(Pawn, White)); board.push_back(new Piece(Pawn, White)); board.push_back(new Piece(Rook, White)); board.push_back(new Piece(Knight, White)); board.push_back(new Piece(Bishop, White)); board.push_back(new Piece(Queen, White)); board.push_back(new Piece(King, White)); board.push_back(new Piece(Bishop, White)); board.push_back(new Piece(Knight, White)); board.push_back(new Piece(Rook, White)); assert(board.size() == xdim*ydim); } /** * Move a chess piece from source to destination. Coordinates must be within the 8x8 board. */ void ChessBoard::move(Coordinate source, Coordinate dest) { COORD computedSource = source.y * xdim + source.x; COORD computedDest = dest.y * xdim + dest.x; assert((long unsigned int)computedSource < board.size()); assert((long unsigned int)computedDest < board.size()); board[computedDest] = board[computedSource]; board[computedSource] = nullptr; } /** * Get a chess piece at a given coordinate. */ Piece* ChessBoard::at(Coordinate coordinate) { COORD position = coordinate.y * xdim + coordinate.x; assert((long unsigned int)(position) < board.size()); return board[position]; } /** * Convert board to a string for visualization. */ std::string ChessBoard::str() { std::string boardString = ""; for (int i = 0; i < ydim; i++) { for (int j = 0; j < xdim; j++) { Piece* square = this->board[xdim * i + j]; if (square == nullptr) { boardString += ". "; } else { boardString += square->str(); } if (j < xdim-1) { boardString += " "; } } if (i < ydim-1) { boardString += "\n"; } } return boardString; } ChessBoard::~ChessBoard() { for (unsigned long int i = 0; i < this->board.size(); i++) { if (board[i] != nullptr) { delete this->board[i]; } } } }
adbf43592f9a5de595f31dd773b991ad63e2c372
09c5c4baed3d26701e866be100e4e52d9a34b856
/StudyAlone/StudyAlone/BOJ/BOJ3954.h
6286b14a6df316f845d55d33a928a3db81b93611
[]
no_license
sangdo913/Algorithms
556ac5fc789e35df2f65601e4439caca967edd7b
ee11265895d8ce3314f009df38166defc4b946c7
refs/heads/master
2022-09-11T12:00:58.615980
2022-07-31T11:11:04
2022-07-31T11:11:04
116,484,870
3
0
null
null
null
null
UTF-8
C++
false
false
2,198
h
BOJ3954.h
#include<iostream> using namespace std; unsigned char arr[100000]; unsigned char str[5000]; unsigned char comm[5000]; int p; int sp; int asize, csize, ssize; int jump[100000]; int st[100000]; int main(){ freopen("0Text.txt", "r", stdin); int cnt; cin >> cnt; while(cnt--){ int top = 0; int fcnt = 0; p = sp = 0; cin >> asize >> csize >> ssize; for(int i = 0; i < asize; ++i) arr[i] = 0;; for(int i = 0; i < csize; ++i) jump[i] = -1; cin >> comm; cin >> str; int cp = 0; int x = 1; while(cp != csize){ switch(comm[cp]){ case '-': arr[p]--; break; case '+': arr[p]++; break; case '<': p = (--p + asize) %asize; break; case '>': p = ++p %asize; break; case '[': if(arr[p]){ st[top++] = cp; } else{ int mycnt = 1; cp++; while(mycnt){ if(comm[cp] == ']') mycnt--; else if(comm[cp] == '[') mycnt++; cp++; } cp--; } break; case ']': if(fcnt >= 50000000){ cp = st[0]; cp++; top = 1; while(top){ if(comm[cp] == '[') top++; if(comm[cp] == ']') --top; cp++; } cout << "Loops " << st[0] << ' ' << cp-1 << endl; goto LOOPEND; } if(arr[p]){ cp = st[top-1]; } else top--; break; case ',': if(ssize == sp) arr[p] = 255; else arr[p] = str[sp++]; break; } fcnt++; cp++; } cout << "Terminates" << endl; LOOPEND: x=1; } return 0; }
83cb91c6ca2c838c80d7e4c10c825dd387ec5532
bc04ac4221bd533da6497d1f80150cdd211a7921
/test/Operation_or_test.h
311a44f9115fe4ce9b0c1f34c094c25d52c08e0a
[]
no_license
WarlockD/Mil-std-1750A-Emulator-C20
71e8e357c81a36fe39c5b42a1f76fa13ffef130d
93ed87966945351773107dc6cf3ad5fd50e9cdd4
refs/heads/master
2023-03-16T07:55:57.903908
2012-07-16T15:57:28
2012-07-16T15:57:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
395
h
Operation_or_test.h
#ifndef OPERATION_OR_TEST #define OPERATION_OR_TEST #include "AbstractTestOperation.h" class Operation_or_test : public AbstractTestOperation { public: Operation_or_test(); virtual ~Operation_or_test(); virtual bool testOperation() const; protected: bool test_orr() const; bool test_orb() const; bool test_orbx() const; bool test_or() const; bool test_orim() const; }; #endif
e805beb1951590d638e62905de88306b7d901c11
c2ac7e54b8a2f0087900740ca4ff04e7e027ecfb
/Lesson_7/HW/task2.cpp
be7179c6a22f97f1090cb7e9b226ca4bedc1358c
[]
no_license
XeniaRuban/CCourse
dd6f4736e8e98059ee98252dea03435d3e1e99bc
ac44d59848cb114c5afbb09db847c389a04ff92c
refs/heads/master
2021-09-15T04:39:24.111837
2018-05-26T08:11:50
2018-05-26T08:11:50
104,557,253
0
0
null
null
null
null
UTF-8
C++
false
false
461
cpp
task2.cpp
#include "stdafx.h" #include <stdlib.h> int main() { int *ptr_ad = NULL; int *ptr_v; int i = 0; int N = 0; scanf_s("%d", &N); ptr_v = (int *)malloc(N * sizeof(int)); for (int i = 0; i < N; i++) scanf_s("%d", (ptr_v + i)); for (int i = 0; i < N; i++) printf("%d\n", *(ptr_v + i)); int max = 0; for (int i = 0; i < N; i++) { if (ptr_v[i] > max) max = ptr_v[i]; } printf("%d\n", max); ptr_ad = &max; printf("%d\n", ptr_ad); return 0; }
61c909d59c98d99f4f3ac5f22b8d74df91dd120f
8d40333c5df9ea6d050a2690b0ed0c0eeb8a3edc
/LeetCode/66-Plus-One/plusone.cpp
583cee091c9593076a93f5ef79e0dcc8780056a1
[ "MIT" ]
permissive
maybeabhishek/CodingChallenges
34be3e308dd750ba81f16307e61dd0b311b46e4a
9b95bee1420cf1f817ec5e527089f98d44643e15
refs/heads/master
2020-12-07T19:24:01.395528
2020-10-18T16:20:28
2020-10-18T16:20:28
253,274,578
0
1
MIT
2020-10-18T16:20:29
2020-04-05T16:03:15
C++
UTF-8
C++
false
false
595
cpp
plusone.cpp
class Solution { public: vector<int> plusOne(vector<int>& digits) { int n = digits.size(); int index = n-1; int carry = 1; while(true){ if(index == -1) break; digits[index] += carry; if(digits[index] > 9){ digits[index] = 0; carry = 1; } else{ carry = 0; break; } index--; } if(carry == 1) digits.insert(digits.begin(), 1); return digits; } };
c846b99abbb4eaa9f23546b5dcb183803c3fb206
0f0add5e2c721c7a3381de612093a41bae0c190d
/Study/Game/Tham khao/Rockman_ver4/Rockman_ver4/Device.h
38204a276797d2cc0cdde4c51623a7aee2600126
[]
no_license
phanybien/University
9d5a8b0a8598823b6612e07980b820469223f7e1
409496c8c9feca3d8420d93d6a5d91ac583cb71a
refs/heads/master
2023-06-11T17:39:13.619405
2021-01-08T06:01:58
2021-01-08T06:01:58
80,742,472
1
4
null
2023-05-31T18:17:29
2017-02-02T16:11:05
C++
UTF-8
C++
false
false
429
h
Device.h
#pragma once #ifndef __CDEVICE_H__ #define __CDEVICE_H__ #include "Include.h" #include "CGlobal.h" #include "CSingleton.h" class CDevice : public CSingleton<CDevice> { friend class CSingleton<CDevice>; public: static LPDIRECT3D9 s_d3d; static LPDIRECT3DDEVICE9 s_d3ddv; static LPDIRECT3DSURFACE9 s_backBuffer; static LPD3DXSPRITE s_spriteHandle; bool InitDerect3D(); protected: CDevice(){}; }; #endif // !__CDEVICE_H__
a887519085e4aec7c28b8445621850cef7197c9e
4897474cfe0fee9a9c1e98f3bc24b1d432eaa1ba
/crun/main.cpp
29c678df22e2aa78c158ed101d6619388e1b93cd
[]
no_license
qazwsxedcrfvtg14/ck10227.website
11ad90ce3a88b8724812d9875a62c2b94e7461c6
63240752184f7e0d8f67c4b29a7b9796f67e04dc
refs/heads/master
2021-01-12T10:40:56.211267
2017-07-08T07:30:46
2017-07-08T07:30:46
72,604,732
0
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
main.cpp
#pragma GCC optimize ("O3") #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/hash_policy.hpp> //#include<ext/pb_ds/priority_queue.hpp> #include<ext/rope> #pragma GCC optimize ("O3") #define f first #define s second //#pragma GCC diagnostic error "-std=c++14" using namespace std; int main(){ printf("Hello~"); return 0; }
e9633d8c910a4306b2fe359541c9995ebccc9e98
38d4495215f682412ecea7184a00183f446a3eb3
/plugins/robots/generators/generatorBase/src/rules/simpleRules/simpleVisitedOneZoneRule.cpp
f59c9eacfe0813171dd7b6424c9bf3b9b380d3d2
[ "Apache-2.0", "BSD-3-Clause", "MIT", "CC-BY-4.0", "GPL-3.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Victor-Y-Fadeev/qreal
5e2e006e7f9bbe1fc84ee60324ddec693320c11b
c926e5640c96d74e45bc14fb83a2f57b5c535bae
refs/heads/iotik-v1-0
2020-12-03T03:41:58.006247
2020-04-16T18:14:28
2020-04-16T18:14:28
95,751,064
6
1
Apache-2.0
2019-08-08T18:06:31
2017-06-29T07:33:42
C++
UTF-8
C++
false
false
1,304
cpp
simpleVisitedOneZoneRule.cpp
/* Copyright 2007-2015 QReal Research Group * * 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 "simpleVisitedOneZoneRule.h" #include "generatorBase/semanticTree/loopNode.h" using namespace generatorBase::semantics; using namespace qReal; SimpleVisitedOneZoneRule::SimpleVisitedOneZoneRule(SemanticTree *tree, const Id &id , const LinkInfo &next) : SimpleVisitedRuleBase(tree, id, next) { } bool SimpleVisitedOneZoneRule::apply() { if (!SimpleVisitedRuleBase::apply()) { return false; } if (mNextNode->parentZone() != mThisNode->parentZone()) { // If we have backward edge to loop - it`s ok, simply ignoring it return mThisNode->parentZone()->parentNode() == mNextNode && dynamic_cast<LoopNode *>(mNextNode); } makeLoopStartingFrom(mNextNode); return true; }
7744c8c71b5f2dcd6de5bedb7ff2be6e4fdd3d48
0e13cc2353c1fd4ad5bfb9ca703f9557f93be51e
/src/node_libxml_xsd.cc
d44e55396f2bb5c76847ae1198203c90676568d4
[]
no_license
freerider7777/libxmljs2-xsd
8e2a364e1b041e2e139119a39c1e1f0eed4f01a6
4d00ab5505ac4e05e741261c9b3c588cda1a2d04
refs/heads/master
2023-08-06T12:23:20.005986
2021-09-03T15:27:43
2021-09-03T15:27:43
415,059,590
0
0
null
null
null
null
UTF-8
C++
false
false
3,545
cc
node_libxml_xsd.cc
#ifndef BUILDING_NODE_EXTENSION #define BUILDING_NODE_EXTENSION #endif #include <iostream> #include <list> #include <node.h> #include <nan.h> // includes from libxmljs #include <xml_syntax_error.h> #include <xml_document.h> #include "./node_libxml_xsd.h" #include "./schema.h" #include "./xml_errors.h" using namespace v8; void none(void *ctx, const char *msg, ...) { // do nothing return; } // Used to store a list or validation errors void errorFunc(void* errs, xmlError* error) { std::vector<xmlError*>* errors = reinterpret_cast<std::vector<xmlError*>*>(errs); errors->push_back(error); } NAN_METHOD(SchemaSync) { v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext(); Nan::HandleScope scope; libxmljs::XmlDocument* doc = Nan::ObjectWrap::Unwrap<libxmljs::XmlDocument>(info[0]->ToObject(context).ToLocalChecked()); xmlSchemaParserCtxtPtr parser_ctxt = xmlSchemaNewDocParserCtxt(doc->xml_obj); if (parser_ctxt == NULL) { return Nan::ThrowError("Could not create context for schema parser"); } xmlSchemaValidityErrorFunc err; xmlSchemaValidityWarningFunc warn; void* ctx; xmlSchemaGetParserErrors(parser_ctxt, &err, &warn, &ctx); xmlSchemaSetParserErrors(parser_ctxt, err, (xmlSchemaValidityWarningFunc) none, ctx); xmlSchemaPtr schema = xmlSchemaParse(parser_ctxt); if (schema == NULL) { return Nan::ThrowError("Invalid XSD schema"); } Local<Object> schemaWrapper = Schema::New(context, schema); info.GetReturnValue().Set(schemaWrapper); } NAN_METHOD(ValidateSync) { Nan::HandleScope scope; Local<Context> context = info.GetIsolate()->GetCurrentContext(); auto isolate = info.GetIsolate(); // Prepare the array of errors to be filled by validation // Local<Array> errors = Nan::New<Array>(); std::vector<xmlError*> errorsList; xmlResetLastError(); xmlSetStructuredErrorFunc(reinterpret_cast<void *>(&errorsList), errorFunc); // Extract schema an document to validate from their wrappers Schema* schema = Nan::ObjectWrap::Unwrap<Schema>(info[0]->ToObject(context).ToLocalChecked()); libxmljs::XmlDocument* doc = Nan::ObjectWrap::Unwrap<libxmljs::XmlDocument>(info[1]->ToObject(context).ToLocalChecked()); // Actual validation xmlSchemaValidCtxtPtr valid_ctxt = xmlSchemaNewValidCtxt(schema->schema_obj); if (valid_ctxt == NULL) { return Nan::ThrowError("Unable to create a validation context for the schema"); } xmlSchemaValidateDoc(valid_ctxt, doc->xml_obj); xmlSetStructuredErrorFunc(NULL, NULL); // Don't return the boolean result, instead return array of validation errors // will be empty if validation is ok Local<Array> errors = Array::New(isolate); for (unsigned int i = 0; i < errorsList.size(); i++ ) { errors->Set(context, i, BuildSyntaxError(errorsList.at(i))); } info.GetReturnValue().Set(errors); xmlSchemaFreeValidCtxt(valid_ctxt); } // Compose the module by assigning the methods previously prepared void InitAll(Local<Object> exports, Local<Object> module, Local<Context> context) { Schema::Init(exports, module, context); exports->Set(context, Nan::New<String>("schemaSync").ToLocalChecked(), Nan::New<FunctionTemplate>(SchemaSync)->GetFunction(context).ToLocalChecked()); exports->Set(context, Nan::New<String>("validateSync").ToLocalChecked(), Nan::New<FunctionTemplate>(ValidateSync)->GetFunction(context).ToLocalChecked()); } NODE_MODULE_CONTEXT_AWARE(node_libxml_xsd, InitAll);
38a5164562147a57fb2af677592107270e77b4cb
8e443e8ed1f1b2cf757573dd5e6cac2c1bc8091a
/Tests/BasicSubSocket.cpp
2a3044b164dec66746bebbc67eba41bab4bdf4fe
[]
no_license
zwells1/Networking
65038cd6bbe8bfb132e1b3475e080087fc50c133
e9cd7cd6e487da33f693c47dac99b14490842002
refs/heads/master
2023-04-23T07:52:16.995523
2021-05-13T01:46:06
2021-05-13T01:46:06
366,903,140
0
0
null
null
null
null
UTF-8
C++
false
false
1,972
cpp
BasicSubSocket.cpp
#include <Zmq/SubSocket.hpp> #include <zmq.hpp> #include <iostream> #include <stdexcept> //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void TestMessage(const std::string& MessageType, const std::string& MessageData) { if (MessageType == "Test") { std::cout << "Data: " << MessageData << std::endl; } else { std::cout << "Unknown message type: " << MessageType << " Message Data: " << MessageData << std::endl; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void SetupSubscribeSocket(net::CSubSocket& SubscribeSocket) { SubscribeSocket.mSignalMessage.connect( [&](const std::string& MessageType, const std::string& MessageData) { TestMessage(MessageType, MessageData); std::cout << "Received Message" << std::endl; }); SubscribeSocket.mSignalError.connect( [&](const std::string& ErrorMessage) { std::cout << ErrorMessage << std::endl; }); std::this_thread::sleep_for(std::chrono::seconds(1)); SubscribeSocket.SubscribeToEverything(); try { SubscribeSocket.Connect({"tcp://localhost:7999"}); std::cout << "Connecting to tcp://localhost:7999" << std::endl; } catch (const zmq::error_t& Error) { std::cerr << "Error: Subscribe Socket Connect" << Error.what() << std::endl; std::exit(1); } std::this_thread::sleep_for(std::chrono::seconds(1)); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int main() { net::CSubSocket SubscribeSocket(1); SetupSubscribeSocket(SubscribeSocket); while(true) { std::this_thread::sleep_for(std::chrono::seconds(5)); } return 0; }
174b88e9ab62549cfb43da2a2136f9f0d4fbcbbc
4efe4c7d278f75b4e2a8ae2c8dfb187a4d085e66
/CS4240/project2/expression_node_dots.h
9a53dce9981c1718a9ca218ec327c4fb3a25650c
[]
no_license
plotfi/GradSchoolCompilers
2a6faf06162a33a1f51ddd1e8513e10fe017b1f2
c7d379d749c11d51dcafebf6f92d71b59efeeda3
refs/heads/main
2023-07-30T18:38:07.767939
2021-09-25T17:49:23
2021-09-25T17:50:27
410,342,854
0
0
null
null
null
null
UTF-8
C++
false
false
994
h
expression_node_dots.h
#ifndef NODE_TYPE #define NODE_TYPE "dots" #endif #ifndef EXPRESSION_NODE_DOTS_H #define EXPRESSION_NODE_DOTS_H #include "base_node.h" #include "expression_node.h" #include <list> #include <iostream> #include <fstream> extern CSymbolTableNode globalSymbolTable; using namespace std; class CExpressionNodeDots : public CExpressionNode { public: CExpressionNodeDots(); virtual ~CExpressionNodeDots(); void PrintNode(ostream& file, int tabCount); virtual void GenerateSymbolTables(SymbolTableNode parent); virtual string GetNodeType() { return NODE_TYPE; } virtual string GetExpressionType(); Value* Codegen(IRBuilder<>* builder); protected: private: }; typedef CExpressionNodeDots* ExpressionNodeDots; typedef list<ExpressionNodeDots> CExpressionNodeDotsList; typedef CExpressionNodeDotsList* ExpressionNodeDotsList; typedef CExpressionNodeDotsList::iterator ExpressionNodeDotsIter; #endif // EXPRESSION_NODE_DOTS_H
eb017506ae67372f8991d3d9eaf8ae55c9a67806
0b69a011c9ffee099841c140be95ed93c704fb07
/problemsets/UVA/10371.cpp
54bcc9428bd9426d631a3785eff8b426aa390501
[ "Apache-2.0" ]
permissive
juarezpaulino/coderemite
4bd03f4f2780eb6013f07c396ba16aa7dbbceea8
a4649d3f3a89d234457032d14a6646b3af339ac1
refs/heads/main
2023-01-31T11:35:19.779668
2020-12-18T01:33:46
2020-12-18T01:33:46
320,931,351
0
0
null
null
null
null
UTF-8
C++
false
false
1,613
cpp
10371.cpp
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; int main() { map<string,int> TZ = { {"UTC", 0}, {"GMT", 0}, {"BST", 60}, {"IST", 60}, {"WET", 0}, {"WEST", 60}, {"CET", 60}, {"CEST", 120}, {"EET", 120}, {"EEST", 180}, {"MSK", 180}, {"MSD", 240}, {"AST", -240}, {"ADT", -180}, {"NST", -210}, {"NDT", -150}, {"EST", -300}, {"EDT", -240}, {"CST", -360}, {"CDT", -300}, {"MST", -420}, {"MDT", -360}, {"PST", -480}, {"PDT", -420}, {"HST", -600}, {"AKST", -540}, {"AKDT", -480}, {"AEST", 600}, {"AEDT", 660}, {"ACST", 570}, {"ACDT", 630}, {"AWST", 480}, }; int TT; scanf("%d ", &TT); char S[100]; while (TT--) { int h, m, t; char sc[100], tg[100], p[100]; gets(S); if (*S == 'm') { t = 0; sscanf(S, "%*s %s %s", sc, tg); } else if (*S == 'n') { t = 720; sscanf(S, "%*s %s %s", sc, tg); } else { sscanf(S, "%d:%d %s %s %s", &h, &m, p, sc, tg); h = (h==12)?0:h; t = h*60+m; if (*p == 'p') t += 720; } t += TZ[tg] - TZ[sc]; if (t < 0) t += 1440; t %=1440; // cout << t << endl; if (t == 0) puts("midnight"); else if (t == 720) puts("noon"); else if (t < 720) printf("%d:%02d a.m.\n", t<60?12:t/60, t%60); else { t -= 720; printf("%d:%02d p.m.\n", t<60?12:t/60, t%60); } } return 0; }
7c9ce169afedda3ae677a91b602663af5607c285
d695b5fac07f9cfd3886b12b1509f42f3a5e1083
/Remove Nth Node From End of List.cpp
861f4cf1002ce0b0244d19959a6128ee4bce1b8c
[]
no_license
mascure/LeetCode
7dc78e37e11f743873cb89544b02cf7894c71859
1c14f04b5de3040d243eb11fbf8e56094b2c4f40
refs/heads/master
2021-01-01T16:45:05.018130
2014-10-08T14:49:39
2014-10-08T14:49:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
588
cpp
Remove Nth Node From End of List.cpp
#include<iostream> #include<stdio.h> #include<string> #include<vector> #include<stack> #include<queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { ListNode *front=head,*p=head,*pre=NULL; while(n--){ front=front->next; } while(front){ pre=p; p=p->next; front=front->next; } if(pre){ pre->next=p->next; } else{ head=p->next; } delete p; return head; } }; int main() { return 0; }
dbccd21a770eac420353e26cf064678a660ab74d
057a475216e9beed41983481aafcaf109bbf58da
/src/Coordination/FourLetterCommand.cpp
1bec17f2050b9fd0937edd670c1f7c4b84f45d14
[ "Apache-2.0" ]
permissive
ClickHouse/ClickHouse
fece5204263a5b4d693854b6039699265f1bb27f
6649328db809d51a694c358571539bc5820464be
refs/heads/master
2023-08-31T18:48:36.615225
2023-08-31T17:51:24
2023-08-31T17:51:24
60,246,359
23,878
5,449
Apache-2.0
2023-09-14T20:10:52
2016-06-02T08:28:18
C++
UTF-8
C++
false
false
18,228
cpp
FourLetterCommand.cpp
#include <Coordination/FourLetterCommand.h> #include <Coordination/KeeperDispatcher.h> #include <Server/KeeperTCPHandler.h> #include <Common/ZooKeeper/IKeeper.h> #include <Common/logger_useful.h> #include <Poco/Environment.h> #include <Poco/Path.h> #include <Common/getCurrentProcessFDCount.h> #include <Common/getMaxFileDescriptorCount.h> #include <Common/StringUtils/StringUtils.h> #include "Coordination/KeeperFeatureFlags.h" #include <Coordination/Keeper4LWInfo.h> #include <IO/WriteHelpers.h> #include <IO/Operators.h> #include <boost/algorithm/string.hpp> #include <unistd.h> #include <bit> namespace { String formatZxid(int64_t zxid) { /// ZooKeeper print zxid in hex and String hex = getHexUIntLowercase(zxid); /// without leading zeros trimLeft(hex, '0'); return "0x" + hex; } } namespace DB { namespace ErrorCodes { extern const int LOGICAL_ERROR; } IFourLetterCommand::IFourLetterCommand(KeeperDispatcher & keeper_dispatcher_) : keeper_dispatcher(keeper_dispatcher_) { } int32_t IFourLetterCommand::code() { return toCode(name()); } String IFourLetterCommand::toName(int32_t code) { int reverted_code = std::byteswap(code); return String(reinterpret_cast<char *>(&reverted_code), 4); } int32_t IFourLetterCommand::toCode(const String & name) { int32_t res = *reinterpret_cast<const int32_t *>(name.data()); /// keep consistent with Coordination::read method by changing big endian to little endian. return std::byteswap(res); } IFourLetterCommand::~IFourLetterCommand() = default; FourLetterCommandFactory & FourLetterCommandFactory::instance() { static FourLetterCommandFactory factory; return factory; } void FourLetterCommandFactory::checkInitialization() const { if (!initialized) throw Exception(ErrorCodes::LOGICAL_ERROR, "Four letter command not initialized"); } bool FourLetterCommandFactory::isKnown(int32_t code) { checkInitialization(); return commands.contains(code); } FourLetterCommandPtr FourLetterCommandFactory::get(int32_t code) { checkInitialization(); return commands.at(code); } void FourLetterCommandFactory::registerCommand(FourLetterCommandPtr & command) { if (commands.contains(command->code())) throw Exception(ErrorCodes::LOGICAL_ERROR, "Four letter command {} already registered", command->name()); commands.emplace(command->code(), std::move(command)); } void FourLetterCommandFactory::registerCommands(KeeperDispatcher & keeper_dispatcher) { FourLetterCommandFactory & factory = FourLetterCommandFactory::instance(); if (!factory.isInitialized()) { FourLetterCommandPtr ruok_command = std::make_shared<RuokCommand>(keeper_dispatcher); factory.registerCommand(ruok_command); FourLetterCommandPtr mntr_command = std::make_shared<MonitorCommand>(keeper_dispatcher); factory.registerCommand(mntr_command); FourLetterCommandPtr conf_command = std::make_shared<ConfCommand>(keeper_dispatcher); factory.registerCommand(conf_command); FourLetterCommandPtr cons_command = std::make_shared<ConsCommand>(keeper_dispatcher); factory.registerCommand(cons_command); FourLetterCommandPtr brief_watch_command = std::make_shared<BriefWatchCommand>(keeper_dispatcher); factory.registerCommand(brief_watch_command); FourLetterCommandPtr data_size_command = std::make_shared<DataSizeCommand>(keeper_dispatcher); factory.registerCommand(data_size_command); FourLetterCommandPtr dump_command = std::make_shared<DumpCommand>(keeper_dispatcher); factory.registerCommand(dump_command); FourLetterCommandPtr envi_command = std::make_shared<EnviCommand>(keeper_dispatcher); factory.registerCommand(envi_command); FourLetterCommandPtr is_rad_only_command = std::make_shared<IsReadOnlyCommand>(keeper_dispatcher); factory.registerCommand(is_rad_only_command); FourLetterCommandPtr rest_conn_stats_command = std::make_shared<RestConnStatsCommand>(keeper_dispatcher); factory.registerCommand(rest_conn_stats_command); FourLetterCommandPtr server_stat_command = std::make_shared<ServerStatCommand>(keeper_dispatcher); factory.registerCommand(server_stat_command); FourLetterCommandPtr stat_command = std::make_shared<StatCommand>(keeper_dispatcher); factory.registerCommand(stat_command); FourLetterCommandPtr stat_reset_command = std::make_shared<StatResetCommand>(keeper_dispatcher); factory.registerCommand(stat_reset_command); FourLetterCommandPtr watch_by_path_command = std::make_shared<WatchByPathCommand>(keeper_dispatcher); factory.registerCommand(watch_by_path_command); FourLetterCommandPtr watch_command = std::make_shared<WatchCommand>(keeper_dispatcher); factory.registerCommand(watch_command); FourLetterCommandPtr recovery_command = std::make_shared<RecoveryCommand>(keeper_dispatcher); factory.registerCommand(recovery_command); FourLetterCommandPtr api_version_command = std::make_shared<ApiVersionCommand>(keeper_dispatcher); factory.registerCommand(api_version_command); FourLetterCommandPtr create_snapshot_command = std::make_shared<CreateSnapshotCommand>(keeper_dispatcher); factory.registerCommand(create_snapshot_command); FourLetterCommandPtr log_info_command = std::make_shared<LogInfoCommand>(keeper_dispatcher); factory.registerCommand(log_info_command); FourLetterCommandPtr request_leader_command = std::make_shared<RequestLeaderCommand>(keeper_dispatcher); factory.registerCommand(request_leader_command); FourLetterCommandPtr recalculate_command = std::make_shared<RecalculateCommand>(keeper_dispatcher); factory.registerCommand(recalculate_command); FourLetterCommandPtr clean_resources_command = std::make_shared<CleanResourcesCommand>(keeper_dispatcher); factory.registerCommand(clean_resources_command); FourLetterCommandPtr feature_flags_command = std::make_shared<FeatureFlagsCommand>(keeper_dispatcher); factory.registerCommand(feature_flags_command); factory.initializeAllowList(keeper_dispatcher); factory.setInitialize(true); } } bool FourLetterCommandFactory::isEnabled(int32_t code) { checkInitialization(); if (!allow_list.empty() && *allow_list.cbegin() == ALLOW_LIST_ALL) return true; return std::find(allow_list.begin(), allow_list.end(), code) != allow_list.end(); } void FourLetterCommandFactory::initializeAllowList(KeeperDispatcher & keeper_dispatcher) { const auto & keeper_settings = keeper_dispatcher.getKeeperConfigurationAndSettings(); String list_str = keeper_settings->four_letter_word_allow_list; Strings tokens; splitInto<','>(tokens, list_str); for (String token: tokens) { trim(token); if (token == "*") { allow_list.clear(); allow_list.push_back(ALLOW_LIST_ALL); return; } else { if (commands.contains(IFourLetterCommand::toCode(token))) { allow_list.push_back(IFourLetterCommand::toCode(token)); } else { auto * log = &Poco::Logger::get("FourLetterCommandFactory"); LOG_WARNING(log, "Find invalid keeper 4lw command {} when initializing, ignore it.", token); } } } } String RuokCommand::run() { return "imok"; } namespace { void print(IFourLetterCommand::StringBuffer & buf, const String & key, const String & value) { writeText("zk_", buf); writeText(key, buf); writeText('\t', buf); writeText(value, buf); writeText('\n', buf); } void print(IFourLetterCommand::StringBuffer & buf, const String & key, uint64_t value) { print(buf, key, toString(value)); } constexpr auto * SERVER_NOT_ACTIVE_MSG = "This instance is not currently serving requests"; } String MonitorCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; auto & stats = keeper_dispatcher.getKeeperConnectionStats(); Keeper4LWInfo keeper_info = keeper_dispatcher.getKeeper4LWInfo(); const auto & state_machine = keeper_dispatcher.getStateMachine(); StringBuffer ret; print(ret, "version", String(VERSION_DESCRIBE) + "-" + VERSION_GITHASH); print(ret, "avg_latency", stats.getAvgLatency()); print(ret, "max_latency", stats.getMaxLatency()); print(ret, "min_latency", stats.getMinLatency()); print(ret, "packets_received", stats.getPacketsReceived()); print(ret, "packets_sent", stats.getPacketsSent()); print(ret, "num_alive_connections", keeper_info.alive_connections_count); print(ret, "outstanding_requests", keeper_info.outstanding_requests_count); print(ret, "server_state", keeper_info.getRole()); print(ret, "znode_count", state_machine.getNodesCount()); print(ret, "watch_count", state_machine.getTotalWatchesCount()); print(ret, "ephemerals_count", state_machine.getTotalEphemeralNodesCount()); print(ret, "approximate_data_size", state_machine.getApproximateDataSize()); print(ret, "key_arena_size", state_machine.getKeyArenaSize()); print(ret, "latest_snapshot_size", state_machine.getLatestSnapshotBufSize()); #if defined(OS_LINUX) || defined(OS_DARWIN) print(ret, "open_file_descriptor_count", getCurrentProcessFDCount()); print(ret, "max_file_descriptor_count", getMaxFileDescriptorCount()); #endif if (keeper_info.is_leader) { print(ret, "followers", keeper_info.follower_count); print(ret, "synced_followers", keeper_info.synced_follower_count); } return ret.str(); } String StatResetCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; keeper_dispatcher.resetConnectionStats(); return "Server stats reset.\n"; } String NopCommand::run() { return ""; } String ConfCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; keeper_dispatcher.getKeeperConfigurationAndSettings()->dump(buf); keeper_dispatcher.getKeeperContext()->dumpConfiguration(buf); return buf.str(); } String ConsCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; KeeperTCPHandler::dumpConnections(buf, false); return buf.str(); } String RestConnStatsCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; KeeperTCPHandler::resetConnsStats(); return "Connection stats reset.\n"; } String ServerStatCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; auto write = [&buf](const String & key, const String & value) { writeText(key, buf); writeText(": ", buf); writeText(value, buf); writeText('\n', buf); }; auto & stats = keeper_dispatcher.getKeeperConnectionStats(); Keeper4LWInfo keeper_info = keeper_dispatcher.getKeeper4LWInfo(); write("ClickHouse Keeper version", String(VERSION_DESCRIBE) + "-" + VERSION_GITHASH); StringBuffer latency; latency << stats.getMinLatency() << "/" << stats.getAvgLatency() << "/" << stats.getMaxLatency(); write("Latency min/avg/max", latency.str()); write("Received", toString(stats.getPacketsReceived())); write("Sent", toString(stats.getPacketsSent())); write("Connections", toString(keeper_info.alive_connections_count)); write("Outstanding", toString(keeper_info.outstanding_requests_count)); write("Zxid", formatZxid(keeper_info.last_zxid)); write("Mode", keeper_info.getRole()); write("Node count", toString(keeper_info.total_nodes_count)); return buf.str(); } String StatCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; auto write = [&buf] (const String & key, const String & value) { buf << key << ": " << value << '\n'; }; auto & stats = keeper_dispatcher.getKeeperConnectionStats(); Keeper4LWInfo keeper_info = keeper_dispatcher.getKeeper4LWInfo(); write("ClickHouse Keeper version", String(VERSION_DESCRIBE) + "-" + VERSION_GITHASH); buf << "Clients:\n"; KeeperTCPHandler::dumpConnections(buf, true); buf << '\n'; StringBuffer latency; latency << stats.getMinLatency() << "/" << stats.getAvgLatency() << "/" << stats.getMaxLatency(); write("Latency min/avg/max", latency.str()); write("Received", toString(stats.getPacketsReceived())); write("Sent", toString(stats.getPacketsSent())); write("Connections", toString(keeper_info.alive_connections_count)); write("Outstanding", toString(keeper_info.outstanding_requests_count)); write("Zxid", formatZxid(keeper_info.last_zxid)); write("Mode", keeper_info.getRole()); write("Node count", toString(keeper_info.total_nodes_count)); return buf.str(); } String BriefWatchCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; const auto & state_machine = keeper_dispatcher.getStateMachine(); buf << state_machine.getSessionsWithWatchesCount() << " connections watching " << state_machine.getWatchedPathsCount() << " paths\n"; buf << "Total watches:" << state_machine.getTotalWatchesCount() << "\n"; return buf.str(); } String WatchCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; const auto & state_machine = keeper_dispatcher.getStateMachine(); state_machine.dumpWatches(buf); return buf.str(); } String WatchByPathCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; const auto & state_machine = keeper_dispatcher.getStateMachine(); state_machine.dumpWatchesByPath(buf); return buf.str(); } String DataSizeCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; buf << "snapshot_dir_size: " << keeper_dispatcher.getSnapDirSize() << '\n'; buf << "log_dir_size: " << keeper_dispatcher.getLogDirSize() << '\n'; return buf.str(); } String DumpCommand::run() { if (!keeper_dispatcher.isServerActive()) return SERVER_NOT_ACTIVE_MSG; StringBuffer buf; const auto & state_machine = keeper_dispatcher.getStateMachine(); state_machine.dumpSessionsAndEphemerals(buf); return buf.str(); } String EnviCommand::run() { using Poco::Environment; using Poco::Path; StringBuffer buf; buf << "Environment:\n"; buf << "clickhouse.keeper.version=" << VERSION_DESCRIBE << '-' << VERSION_GITHASH << '\n'; buf << "host.name=" << Environment::nodeName() << '\n'; buf << "os.name=" << Environment::osDisplayName() << '\n'; buf << "os.arch=" << Environment::osArchitecture() << '\n'; buf << "os.version=" << Environment::osVersion() << '\n'; buf << "cpu.count=" << Environment::processorCount() << '\n'; String os_user; os_user.resize(256, '\0'); if (0 == getlogin_r(os_user.data(), os_user.size() - 1)) os_user.resize(strlen(os_user.c_str())); else os_user.clear(); /// Don't mind if we cannot determine user login. buf << "user.name=" << os_user << '\n'; buf << "user.home=" << Path::home() << '\n'; buf << "user.dir=" << Path::current() << '\n'; buf << "user.tmp=" << Path::temp() << '\n'; return buf.str(); } String IsReadOnlyCommand::run() { if (keeper_dispatcher.isObserver()) return "ro"; else return "rw"; } String RecoveryCommand::run() { keeper_dispatcher.forceRecovery(); return "ok"; } String ApiVersionCommand::run() { return toString(static_cast<uint8_t>(KeeperApiVersion::WITH_MULTI_READ)); } String CreateSnapshotCommand::run() { auto log_index = keeper_dispatcher.createSnapshot(); return log_index > 0 ? std::to_string(log_index) : "Failed to schedule snapshot creation task."; } String LogInfoCommand::run() { KeeperLogInfo log_info = keeper_dispatcher.getKeeperLogInfo(); StringBuffer ret; auto append = [&ret] (String key, uint64_t value) -> void { writeText(key, ret); writeText('\t', ret); writeText(std::to_string(value), ret); writeText('\n', ret); }; append("first_log_idx", log_info.first_log_idx); append("first_log_term", log_info.first_log_idx); append("last_log_idx", log_info.last_log_idx); append("last_log_term", log_info.last_log_term); append("last_committed_log_idx", log_info.last_committed_log_idx); append("leader_committed_log_idx", log_info.leader_committed_log_idx); append("target_committed_log_idx", log_info.target_committed_log_idx); append("last_snapshot_idx", log_info.last_snapshot_idx); return ret.str(); } String RequestLeaderCommand::run() { return keeper_dispatcher.requestLeader() ? "Sent leadership request to leader." : "Failed to send leadership request to leader."; } String RecalculateCommand::run() { keeper_dispatcher.recalculateStorageStats(); return "ok"; } String CleanResourcesCommand::run() { keeper_dispatcher.cleanResources(); return "ok"; } String FeatureFlagsCommand::run() { const auto & feature_flags = keeper_dispatcher.getKeeperContext()->getFeatureFlags(); StringBuffer ret; auto append = [&ret] (const String & key, uint8_t value) -> void { writeText(key, ret); writeText('\t', ret); writeText(std::to_string(value), ret); writeText('\n', ret); }; for (const auto & [feature_flag, name] : magic_enum::enum_entries<KeeperFeatureFlag>()) { std::string feature_flag_string(name); boost::to_lower(feature_flag_string); append(feature_flag_string, feature_flags.isEnabled(feature_flag)); } return ret.str(); } }
e4724da83a65aed8860f41579793dc3725287ac9
1f55f1d8d4c3ea0d7e53eac5be778ba0bfaab304
/src/measurementsapp.cpp
363e50456c7a89d52510dc702ac06cb71391129b
[]
no_license
petii/efop-signalproc
ea3d1b5caafb43f2c96b0c1bfdf8ce965404fb86
988dfd3a03e6a97a1ca47380e2dd8c877a9e0233
refs/heads/master
2020-03-21T09:09:44.118611
2018-08-26T23:36:45
2018-08-26T23:36:45
138,385,141
0
0
null
null
null
null
UTF-8
C++
false
false
5,457
cpp
measurementsapp.cpp
#include "measurementsapp.h" #include <chrono> #include <fstream> #include <memory> #include <random> #include <thread> #include "pacpphandler.h" MeasurementsApp::MeasurementsApp(std::pair<int, int> range, int runs) : range(range), runs(runs) {} MeasurementsApp::~MeasurementsApp() {} void MeasurementsApp::exportResults( const std::string &file, const std::vector<std::vector<Measurement>> &mesr) { for (auto m : mesr) { std::ofstream out("./csvs/" + file + m.front().purpose + ".csv"); for (auto &a : m) { out << a.execSize << (a.execSize != m.back().execSize ? "," : ""); } out << std::endl; for (int i = 0; i < m.back().starts.size(); ++i) { for (auto &a : m) { out << std::chrono::duration_cast<std::chrono::nanoseconds>(a.ends[i] - a.starts[i]) .count() << (a.execSize != m.back().execSize ? "," : ""); } out << std::endl; } } } void MeasurementsApp::doMeasurements() { std::clog << range.first << '-' << range.second << std::endl; std::clog << "portaudiocpp" << std::endl; auto pacppResults = runAudioMeasurements(std::make_unique<PACppHandler>()); std::clog << "end of portaudiocpp" << std::endl; std::clog << "pulseaudio" << std::endl; auto pulseAudioResults = runAudioMeasurements(std::make_unique<PulseAudioHandler>()); std::clog << "end of pulseaudio" << std::endl; // std::clog << "running vulkan\n"; // auto vulkanFourierResults = // runFourierMeasurements(std::make_unique<VulkanFourier>()); // std::clog << "end of vulkan\n"; // std::clog << "running fftw++\n"; // auto fftwFourierResults = // runFourierMeasurements(std::make_unique<FFTWFourier>()); // std::clog << "end of fftw++\n"; // std::clog << "running fftw++ arrayless\n"; // auto arrlessFourierResults = // runFourierMeasurements(std::make_unique<ArraylessFFTW>()); // std::clog << "end of fftw++ arrayless\n"; // exportResults("vulkan", vulkanFourierResults); // exportResults("fftwpp", fftwFourierResults); // exportResults("arrless", arrlessFourierResults); // std::clog << "vulkan\t" << vulkanFourierResults.size() << std::endl; // for (int i = 0; i < vulkanFourierResults.size(); ++i) { // for (auto &i : vulkanFourierResults[i]) { // std::clog << i.toString() << std::endl; // } // std::clog << "fftwpp\t" << fftwFourierResults.size() << std::endl; // for (auto &i : fftwFourierResults[i]) { // std::clog << i.toString() << std::endl; // } // } } std::vector<std::vector<std::chrono::high_resolution_clock::duration>> MeasurementsApp::runAudioMeasurements( std::unique_ptr<AudioHandler> audioHandler) { std::vector<std::vector<std::chrono::high_resolution_clock::duration>> results; for (int r = range.first; r <= range.second; ++r) { std::clog << r << std::endl; audioHandler->setChunkSize(r * baseWindowSize); std::atomic<int> runNum = 0; std::vector<double> data; audioHandler->setCallback([&runNum, &data](auto audio) { data.insert(data.end(), audio.begin(), audio.end()); // TODO: move semantics? ++runNum; }); // std::cin.get(); // assert std::clog << std::boolalpha << "start record successful: " << (audioHandler->startRecording()) << std::endl; while (runNum < runs) ; // assert std::clog << "stop record successful: " << (audioHandler->stopRecording()) << std::endl; results.push_back(audioHandler->getMeasurements()); // for (auto r : results) { // std::clog << // std::chrono::duration_cast<std::chrono::milliseconds>(r).count() << // std::endl; // } } return results; } std::vector<std::vector<Measurement>> MeasurementsApp::runFourierMeasurements( std::unique_ptr<FourierHandler> fourierHandler) { std::random_device randomDevice{}; std::mt19937 generator(randomDevice()); std::normal_distribution<> dist{}; std::vector<std::vector<Measurement>> measurements; std::vector<Measurement> cmeasurements; std::vector<Measurement> rmeasurements; for (int size = range.first; size <= range.second; ++size) { auto dataSize = baseWindowSize * size; std::clog << dataSize << "\t"; Measurement copyMeasurement("datacopy", runs, dataSize); Measurement runMeasurement("transformation", runs, dataSize); fourierHandler->setWindowSize(dataSize); std::vector<std::vector<double>> randomData; randomData.resize(runs); for (auto &data : randomData) { for (int i = 0; i < dataSize; ++i) { data.push_back(dist(generator)); } } fourierHandler->addInput(randomData.front()); fourierHandler->setWindowSize(dataSize); auto start = std::chrono::high_resolution_clock::now(); for (auto &data : randomData) { copyMeasurement.add(); fourierHandler->addInput(data); copyMeasurement.end(); runMeasurement.add(); // fourierHandler->runTransform(); runMeasurement.end(); } auto end = std::chrono::high_resolution_clock::now(); copyMeasurement.overallRuntime = end - start; cmeasurements.push_back(copyMeasurement); rmeasurements.push_back(runMeasurement); } std::endl(std::clog); measurements.push_back(cmeasurements); measurements.push_back(rmeasurements); return measurements; }
79a3e5cc83bcaa49d61fb080d143ef6ea424cda5
c70e26f24f4f1fafdeed78755c91afef3e15a0aa
/GucchiFrameWork/GucchiLibrary/Common/DeviceResources.cpp
0f91ec11703216a9a2011b9603b517ee5f02f2d4
[]
no_license
yutaHiguchi0204/GucchiFrameWork
a73625e31bfc98c4878c2fef8c81cc97c3e869e2
c8a472153c98f43d01886b4638aa2331e9edeba3
refs/heads/master
2021-09-12T17:00:44.229399
2018-03-15T02:27:48
2018-03-15T02:27:48
105,857,321
4
0
null
2018-03-15T02:27:49
2017-10-05T06:39:03
C++
SHIFT_JIS
C++
false
false
16,246
cpp
DeviceResources.cpp
/* ===================================================================== //! @param 「DeviceResources」ソース //! @create 樋口 裕太 //! @date 17/10/09 ===================================================================== */ // ヘッダファイルのインクルード #include "DeviceResources.h" #include "Constant.h" // 名前空間 using namespace DirectX; using Microsoft::WRL::ComPtr; using namespace GucchiLibrary; using namespace std; inline void ThrowIfFailed(HRESULT hr) { if (FAILED(hr)) { // API エラーを捕捉する throw exception(); } } namespace { #if defined(_DEBUG) // SDK レイヤーのサポートがあるかどうか inline bool SdkLayersAvailable() { HRESULT hr = D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_NULL, // ハードウェアデバイスの作成不要 nullptr, D3D11_CREATE_DEVICE_DEBUG, // SDK レイヤーのチェック nullptr, // どの機能レベルでも利用可能 0, D3D11_SDK_VERSION, nullptr, // デバイスのリファレンスを保持する必要はない nullptr, // 機能レベルを知っている必要はない nullptr // デバイスコンテキストのリファレンスを保持する必要はない ); return SUCCEEDED(hr); } #endif }; // コンストラクタ DeviceResources::DeviceResources(DXGI_FORMAT backBufferFormat, DXGI_FORMAT depthBufferFormat, UINT backBufferCount, D3D_FEATURE_LEVEL minFeatureLevel) : screenViewport_{} , backBufferFormat_(backBufferFormat) , depthBufferFormat_(depthBufferFormat) , backBufferCount_(backBufferCount) , d3dMinFeatureLevel_(minFeatureLevel) , window_(nullptr) , d3dFeatureLevel_(D3D_FEATURE_LEVEL_9_1) , outputSize_{ 0, 0, 1, 1 } , deviceNotify_(nullptr) { } // 利用可能なハードウェアアダプタの設定 void DeviceResources::GetHardwareAdapter(IDXGIAdapter1** ppAdapter) { // 見つからなかった場合はnullptrを設定 *ppAdapter = nullptr; ComPtr<IDXGIFactory1> dxgiFactory; ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(dxgiFactory.GetAddressOf()))); ComPtr<IDXGIAdapter1> adapter; for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != dxgiFactory->EnumAdapters1(adapterIndex, adapter.ReleaseAndGetAddressOf()); adapterIndex++) { DXGI_ADAPTER_DESC1 desc; adapter->GetDesc1(&desc); if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) { // レンダリングドライバアダプタは基本的に選択しない continue; } #ifdef _DEBUG wchar_t buff[256] = {}; swprintf_s(buff, L"Direct3D Adapter (%u): VID:%04X, PID:%04X - %ls\n", adapterIndex, desc.VendorId, desc.DeviceId, desc.Description); OutputDebugStringW(buff); #endif break; } *ppAdapter = adapter.Detach(); } // Direct3Dのデバイスとコンテキストを構成し、ハンドルを格納する void DeviceResources::CreateDeviceResources() { UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #if defined(_DEBUG) if (SdkLayersAvailable()) { // デバッグビルドの場合はSDKレイヤーを介してデバッグを有効にする creationFlags |= D3D11_CREATE_DEVICE_DEBUG; } else { OutputDebugStringA("WARNING: Direct3D Debug Device is not available\n"); } #endif // DirectXハードウェア機能レベルの設定 static const D3D_FEATURE_LEVEL s_featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1, }; UINT featLevelCount = 0; for (; featLevelCount < _countof(s_featureLevels); ++featLevelCount) { if (s_featureLevels[featLevelCount] < d3dMinFeatureLevel_) break; } if (!featLevelCount) { throw out_of_range("minFeatureLevel too high"); } ComPtr<IDXGIAdapter1> adapter; GetHardwareAdapter(adapter.GetAddressOf()); // API デバイスオブジェクトとそれに対応するコンテキストの作成 HRESULT hr = E_FAIL; if (adapter) { hr = D3D11CreateDevice( adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, creationFlags, s_featureLevels, featLevelCount, D3D11_SDK_VERSION, d3dDevice_.ReleaseAndGetAddressOf(), // 作成されたDirect3Dデバイスの返却 &d3dFeatureLevel_, // 作成されたフューチャーレベルの返却 d3dContext_.ReleaseAndGetAddressOf() // デバイス即時コンテキストの返却 ); if (hr == E_INVALIDARG && featLevelCount > 1) { assert(s_featureLevels[0] == D3D_FEATURE_LEVEL_11_1); // DirectX11のプラットフォームは "D3D_FEATURE_LEVEL_11_1" を認識しないため、DirectX11のプラットフォームを使用せずに再試行する必要がある hr = D3D11CreateDevice( adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, creationFlags, &s_featureLevels[1], featLevelCount - 1, D3D11_SDK_VERSION, d3dDevice_.ReleaseAndGetAddressOf(), &d3dFeatureLevel_, d3dContext_.ReleaseAndGetAddressOf() ); } } #if defined(NDEBUG) else { throw exception("No Direct3D hardware device found"); } #else if (FAILED(hr)) { // 初期化が失敗した場合は、WARPデバイスにフォールバックする // WARPデバイスの詳細: http://go.microsoft.com/fwlink/?LinkId=286690 hr = D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, // ハードウェアデバイスの代わりにWARPデバイスを作成する nullptr, creationFlags, s_featureLevels, featLevelCount, D3D11_SDK_VERSION, d3dDevice_.ReleaseAndGetAddressOf(), &d3dFeatureLevel_, d3dContext_.ReleaseAndGetAddressOf() ); if (hr == E_INVALIDARG && featLevelCount > 1) { assert(s_featureLevels[0] == D3D_FEATURE_LEVEL_11_1); // DirectX11のプラットフォームは "D3D_FEATURE_LEVEL_11_1" を認識しないため、DirectX11のプラットフォームを使用せずに再試行する必要がある hr = D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, nullptr, creationFlags, &s_featureLevels[1], featLevelCount - 1, D3D11_SDK_VERSION, d3dDevice_.ReleaseAndGetAddressOf(), &d3dFeatureLevel_, d3dContext_.ReleaseAndGetAddressOf() ); } if (SUCCEEDED(hr)) { OutputDebugStringA("Direct3D Adapter - WARP\n"); } } #endif ThrowIfFailed(hr); #ifndef NDEBUG ComPtr<ID3D11Debug> d3dDebug; if (SUCCEEDED(d3dDevice_.As(&d3dDebug))) { ComPtr<ID3D11InfoQueue> d3dInfoQueue; if (SUCCEEDED(d3dDebug.As(&d3dInfoQueue))) { #ifdef _DEBUG d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true); d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true); #endif D3D11_MESSAGE_ID hide[] = { D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, }; D3D11_INFO_QUEUE_FILTER filter = {}; filter.DenyList.NumIDs = _countof(hide); filter.DenyList.pIDList = hide; d3dInfoQueue->AddStorageFilterEntries(&filter); } } #endif // 使用可能な場合、Direct3D 11.1 のインタフェースを入手する if (SUCCEEDED(d3dDevice_.As(&d3dDevice1_))) { (void)d3dContext_.As(&d3dContext1_); (void)d3dContext_.As(&d3dAnnotation_); } commonStates_ = make_unique<CommonStates>(d3dDevice_.Get()); } // これらのリソースはウインドウサイズが変更されるたびに再設定する費用がある void DeviceResources::CreateWindowSizeDependentResources() { if (!window_) { throw exception("Call SetWindow with a valid Win32 window handle"); } // 前のウィンドウサイズに特有のコンテキストをクリアする ID3D11RenderTargetView* nullViews[] = { nullptr }; d3dContext_->OMSetRenderTargets(_countof(nullViews), nullViews, nullptr); d3dRenderTargetView_.Reset(); d3dDepthStencilView_.Reset(); renderTarget_.Reset(); depthStencil_.Reset(); d3dContext_->Flush(); // Determine the render target size in pixels. UINT backBufferWidth = max<UINT>(outputSize_.right - outputSize_.left, 1); UINT backBufferHeight = max<UINT>(outputSize_.bottom - outputSize_.top, 1); if (swapChain_) { // スワップチェーンがすでに存在している場合は、サイズを変更する HRESULT hr = swapChain_->ResizeBuffers( backBufferCount_, backBufferWidth, backBufferHeight, backBufferFormat_, 0 ); if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { #ifdef _DEBUG char buff[64] = {}; sprintf_s(buff, "Device Lost on ResizeBuffers: Reason code 0x%08X\n", (hr == DXGI_ERROR_DEVICE_REMOVED) ? d3dDevice_->GetDeviceRemovedReason() : hr); OutputDebugStringA(buff); #endif // 何らかの理由でデバイスが削除された場合は、新しいデバイスとスワップチェーンを作成する費用がある HandleDeviceLost(); // メソッドの実行を継続しない // 新しいデバイスを正しくセットアップしてください return; } else { ThrowIfFailed(hr); } } else { // 既存のDirect3Dデバイスと同じアダプタを使用して新しいアダプタを作成 // Direct3Dデバイスの作成に使用されたDXGIファクトリの取得 ComPtr<IDXGIDevice1> dxgiDevice; ThrowIfFailed(d3dDevice_.As(&dxgiDevice)); ComPtr<IDXGIAdapter> dxgiAdapter; ThrowIfFailed(dxgiDevice->GetAdapter(dxgiAdapter.GetAddressOf())); ComPtr<IDXGIFactory1> dxgiFactory; ThrowIfFailed(dxgiAdapter->GetParent(IID_PPV_ARGS(dxgiFactory.GetAddressOf()))); ComPtr<IDXGIFactory2> dxgiFactory2; if (SUCCEEDED(dxgiFactory.As(&dxgiFactory2))) { // DirectX 11.1 か前のバージョンか DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {}; swapChainDesc.Width = backBufferWidth; swapChainDesc.Height = backBufferHeight; swapChainDesc.Format = backBufferFormat_; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = backBufferCount_; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Scaling = DXGI_SCALING_STRETCH; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; DXGI_SWAP_CHAIN_FULLSCREEN_DESC fsSwapChainDesc = { 0 }; fsSwapChainDesc.Windowed = TRUE; // Win32 ウインドウからスワップチェーンを作成 ThrowIfFailed(dxgiFactory2->CreateSwapChainForHwnd( d3dDevice_.Get(), window_, &swapChainDesc, &fsSwapChainDesc, nullptr, swapChain1_.ReleaseAndGetAddressOf() )); ThrowIfFailed(swapChain1_.As(&swapChain_)); } else { // DirectX 11.0 DXGI_SWAP_CHAIN_DESC swapChainDesc = {}; swapChainDesc.BufferDesc.Width = backBufferWidth; swapChainDesc.BufferDesc.Height = backBufferHeight; swapChainDesc.BufferDesc.Format = backBufferFormat_; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = backBufferCount_; swapChainDesc.OutputWindow = window_; swapChainDesc.Windowed = TRUE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; ThrowIfFailed(dxgiFactory->CreateSwapChain( d3dDevice_.Get(), &swapChainDesc, swapChain_.ReleaseAndGetAddressOf() )); } // 排他的なフルスクリーンモードをサポートしていないので、DXGIがALT + ENTERショートカットに応答しないようにする ThrowIfFailed(dxgiFactory->MakeWindowAssociation(window_, DXGI_MWA_NO_ALT_ENTER)); } // スワップチェーンバックバッファのレンダーターゲットビューの作成 ThrowIfFailed(swapChain_->GetBuffer(0, IID_PPV_ARGS(renderTarget_.ReleaseAndGetAddressOf()))); ThrowIfFailed(d3dDevice_->CreateRenderTargetView( renderTarget_.Get(), nullptr, d3dRenderTargetView_.ReleaseAndGetAddressOf() )); if (depthBufferFormat_ != DXGI_FORMAT_UNKNOWN) { // 必要に応じて、奥行きステンシルビューを作成 CD3D11_TEXTURE2D_DESC depthStencilDesc( depthBufferFormat_, backBufferWidth, backBufferHeight, 1, // この深度ステンシルにはテクスチャが1つしかない 1, // 単一のミップマップレベルを使用 D3D11_BIND_DEPTH_STENCIL ); ThrowIfFailed(d3dDevice_->CreateTexture2D( &depthStencilDesc, nullptr, depthStencil_.ReleaseAndGetAddressOf() )); CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D); ThrowIfFailed(d3dDevice_->CreateDepthStencilView( depthStencil_.Get(), &depthStencilViewDesc, d3dDepthStencilView_.ReleaseAndGetAddressOf() )); } // 3Dレンダリングビューポートを設定してウィンドウ全体をターゲットにする screenViewport_ = CD3D11_VIEWPORT( 0.0f, 0.0f, static_cast<float>(backBufferWidth), static_cast<float>(backBufferHeight) ); } // Win32ウィンドウが作成(または再作成)されたときに呼ばれる void DeviceResources::SetWindow(HWND window, int width, int height) { window_ = window; outputSize_.left = outputSize_.top = 0; outputSize_.right = width; outputSize_.bottom = height; } // Win32ウインドウのサイズが変更されたときに呼ばれる bool DeviceResources::WindowSizeChanged(int width, int height) { RECT newRc; newRc.left = newRc.top = 0; newRc.right = width; newRc.bottom = height; if (newRc == outputSize_) { return false; } outputSize_ = newRc; CreateWindowSizeDependentResources(); return true; } // すべてのデバイスリソースを再作成し、現在の状態まで戻す void DeviceResources::HandleDeviceLost() { if (deviceNotify_) { deviceNotify_->OnDeviceLost(); } d3dDepthStencilView_.Reset(); d3dRenderTargetView_.Reset(); renderTarget_.Reset(); depthStencil_.Reset(); swapChain_.Reset(); swapChain1_.Reset(); d3dContext_.Reset(); d3dContext1_.Reset(); d3dAnnotation_.Reset(); d3dDevice1_.Reset(); #ifdef _DEBUG { ComPtr<ID3D11Debug> d3dDebug; if (SUCCEEDED(d3dDevice_.As(&d3dDebug))) { d3dDebug->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY); } } #endif d3dDevice_.Reset(); CreateDeviceResources(); CreateWindowSizeDependentResources(); if (deviceNotify_) { deviceNotify_->OnDeviceRestored(); } } // IDeviceNotifyの登録 void DeviceResources::RegisterDeviceNotify(IDeviceNotify* deviceNotify) { deviceNotify_ = deviceNotify; } // スワップチェーンの内容を画面に表示 void DeviceResources::Present() { // VSyncまでブロックするようにDXGIに指示し、次のVSyncまでスリープ状態にする // これにより、スクリーンに表示されないフレームをレンダリングするサイクルを無駄にすることはない HRESULT hr = swapChain_->Present(1, 0); if (d3dContext1_) { // レンダーターゲットの内容を破棄 // ダーティまたはスクロール矩形が使用されている場合は、この呼び出しを削除する必要がある d3dContext1_->DiscardView(d3dRenderTargetView_.Get()); if (d3dDepthStencilView_) { // 深度ステンシルの内容を破棄 d3dContext1_->DiscardView(d3dDepthStencilView_.Get()); } } // 切断またはドライバのアップグレードによってデバイスが削除された場合は、すべてのデバイスリソースを再作成する必要がある if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { #ifdef _DEBUG char buff[64] = {}; sprintf_s(buff, "Device Lost on Present: Reason code 0x%08X\n", (hr == DXGI_ERROR_DEVICE_REMOVED) ? d3dDevice_->GetDeviceRemovedReason() : hr); OutputDebugStringA(buff); #endif HandleDeviceLost(); } else { ThrowIfFailed(hr); } } // デバイスツールの初期化 void DirectXToolKidResources::Initialize(ID3D11Device* device, ID3D11DeviceContext* context) { device_ = device; context_ = context; // スプライトバッチ spriteBatch_ = make_unique<SpriteBatch>(context_); // スプライトフォント wstring defaultFont = FILE_PATH_FONT + L"default_font" + EXT_SPRITEFONT; spriteFont_ = make_unique<SpriteFont>(device_, defaultFont.c_str()); } // フォント変更 void DirectXToolKidResources::SetFont(const wstring& fontName) { spriteFont_.reset(new SpriteFont(device_, fontName.c_str())); }
588f25153928661f4368f69c4e781988efb1b682
480e33f95eec2e471c563d4c0661784c92396368
/CondTools/SiPixel/test/SiPixelFakeGenErrorDBSourceReader.h
3f2cac8e79c276dd076532103a3071f84ecffabc
[ "Apache-2.0" ]
permissive
cms-nanoAOD/cmssw
4d836e5b76ae5075c232de5e062d286e2026e8bd
4eccb8a758b605875003124dd55ea58552b86af1
refs/heads/master-cmsswmaster
2021-01-23T21:19:52.295420
2020-08-27T08:01:20
2020-08-27T08:01:20
102,867,729
7
14
Apache-2.0
2022-05-23T07:58:09
2017-09-08T14:03:57
C++
UTF-8
C++
false
false
935
h
SiPixelFakeGenErrorDBSourceReader.h
#ifndef CondTools_SiPixel_SiPixelFakeGenErrorDBSourceReader_h #define CondTools_SiPixel_SiPixelFakeGenErrorDBSourceReader_h #include <memory> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESWatcher.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "CondFormats/DataRecord/interface/SiPixelGenErrorDBObjectRcd.h" class SiPixelFakeGenErrorDBSourceReader : public edm::EDAnalyzer { public: explicit SiPixelFakeGenErrorDBSourceReader(const edm::ParameterSet&); ~SiPixelFakeGenErrorDBSourceReader(); private: virtual void beginJob(); virtual void analyze(const edm::Event&, const edm::EventSetup&); virtual void endJob(); edm::ESWatcher<SiPixelGenErrorDBObjectRcd> SiPixelGenErrorDBObjectWatcher_; }; #endif
72b5196642fb59f19eaabeffd1c865fb9a4a8c85
7d4bb64b31f06e4a22f63c5944297c52d12285d6
/Competitive-Coding-Algorithms/Number Theory/primality.cpp
3aebf3cae36682bd84697f2bb50e8fcc08c1e2ff
[]
no_license
927tanmay/Coding-DSA
17e6eff710859d2f17f35e45883605c721f374f9
e173fbe64fbf39c11a4d32cda6f8f663757b5cb7
refs/heads/master
2023-01-12T15:55:06.984519
2020-10-31T16:10:36
2020-10-31T16:10:36
305,500,210
1
2
null
2020-10-31T16:10:37
2020-10-19T20:04:28
C++
UTF-8
C++
false
false
576
cpp
primality.cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define endl '\n' int main() { int t; cin >> t; while (t--) { int n, flag = 0; cin >> n; if (n == 1) { cout << "no" << endl; continue; } for (int i = 2; i*i <= n; i++) { if (n % i == 0) { flag = 1; break; } } if (flag == 0) cout << "yes" << endl; else cout << "no" << endl; } return 0; }
02f5a6583038f8bd80f019446d4e94b5b581dd7e
896dbaed5100c9adada8db6abb24c648cb1254da
/src/modules/dmxconsumer.h
03b2784b0e96ac1655295566a3dbece1d10d4fa4
[]
no_license
autoantwort/Lichtsteuerung
7fdd8a98718db50a4fea02973aac8c063422a259
ee1f494bec5617229b72cb49aec3083f87fce164
refs/heads/master
2023-08-27T15:07:48.925720
2023-07-14T00:32:18
2023-07-14T00:32:18
222,066,667
0
0
null
null
null
null
UTF-8
C++
false
false
1,049
h
dmxconsumer.h
#ifndef DMXCONSUMER_H #define DMXCONSUMER_H #include "consumer.hpp" #include "idbase.h" #include <vector> namespace Modules { /** * @brief Der DMXConsumer macht es möglich, in Moduleprogrammen dmx channel anzusprechen. Diese Daten werden dann in driver.cpp hier abgeholt und vom alten treiber angezeigt */ class DMXConsumer : public Modules::TypedConsumer<brightness_t> { NumericProperty<int> startDMXChannel; bool running = false; public: /** * @brief fillWithDMXConsumer füllt den data array mit den dmx daten aus dem DMXConsumern * @param data der daten array der an die DMX Geräte geht * @param length Die länge des Arrays */ static void fillWithDMXConsumer(unsigned char *data, size_t length); public: DMXConsumer(); ~DMXConsumer() override; void start() override; void show() override; void stop() override; void doStep(time_diff_t /*diff*/) override {} const char *getName() const override { return "DMXConsumer"; } }; } // namespace Modules #endif // DMXCONSUMER_H
f7c609fd42f6353c741fab34f3e5d4aa5f8377d4
a7cfc322cc5cf13c0db2e8b5d9aa9794b498b83c
/MatrixSetup.cpp
951eecca251db41e3c38fc70a362b288cd90acc9
[]
no_license
kocherzhenko/KMM_spectra
6829d62a6f68f2f6fa070169cceb5f8c12ced25a
d567c9ec471fac169a466e57fe5cf0ee9f5ea9c3
refs/heads/master
2022-08-04T02:56:51.822069
2020-05-21T18:12:29
2020-05-21T18:12:29
265,917,631
0
0
null
null
null
null
UTF-8
C++
false
false
5,659
cpp
MatrixSetup.cpp
// Setup of the Input Matrix for Linear Equation Solver - (c) Aleksey Kocherzhenko, 2012 #include <stdio.h> #include <stdlib.h> #include <math.h> #include "Initialize.h" #include "Common.h" #include "Setup.h" #define DEL 1.e-8 FILE *fp; // Calculate elements of A matrix (l.h.s. of Eq. (14B)) complex_t getLHS(double alpha, double beta, int UNITS, double COUP) { complex_t lhs, temp1, temp2, temp3; temp1.re = 0.0; temp1.im = alpha - beta; temp1 = cexp(temp1); temp1 = add(temp1, -1.0); temp1 = inv(temp1); temp2 = getTH(alpha, COUP); temp3 = getTH(beta, COUP); temp3 = inv(temp3); temp2 = prod(temp2, temp3); temp2 = add(temp2, 1.0); lhs = prod(temp1, temp2); lhs = prod(lhs, 1.0/UNITS); return lhs; } // Calculate elements of b vector(s) (r.h.s. of Eq. (14B)) complex_t getRHS(double alpha, double beta, double COUP) { complex_t rhs, temp1, temp2, temp3; temp1.re = 0.0; temp1.im = alpha + beta; temp1 = cexp(temp1); temp3 = temp1; temp1 = add(temp1, -1.0); temp1 = inv(temp1); temp1 = prod(temp1, temp3); temp2 = getTH(alpha, COUP); temp3 = getTH(beta, COUP); temp2 = prod(temp2, temp3); temp2 = inv(temp2); temp2 = add(temp2, -1.0); rhs = prod(temp1, temp2); return rhs; } // Infinite volume params, for comparison // 1/THETA(+) complex_t getTHpi(complex_t z, double a, double A) { complex_t THpi, temp; // for |2*b/epsilon| < 1 if (fabs(A) > 1) { THpi = add(z, a); THpi = inv(THpi); THpi = prod(THpi, a); THpi = csqrt(THpi); THpi = inv(THpi); } // for |2*b/epsilon| > 1 if (fabs(A) < 1) { THpi = prod(z, a); THpi = add(THpi, 1.0); THpi = csqrt(THpi); THpi = inv(THpi); } return THpi; } // 1/THETA(-) complex_t getTHmi(complex_t z, double ainv, double A) { complex_t THmi, temp; // for |2*b/epsilon| < 1 if (fabs(A) > 1) { THmi = add(z, ainv); temp = inv(z); THmi = prod(THmi, temp); THmi = csqrt(THmi); THmi = inv(THmi); } // for |2*b/epsilon| > 1 if (fabs(A) < 1) { THmi = add(z, 1.0/ainv); THmi = inv(THmi); THmi = prod(z, THmi); THmi = csqrt(THmi); THmi = inv(THmi); } return THmi;} // K(z1,z2) complex_t getK(complex_t z1, complex_t z2, double A) { complex_t temp1, temp2; complex_t K1; double a = A; double ainv = 1/A; // printf("z1.re = %10.8f; z1.im = %10.8f; z2.re = %10.8f; z2.im = %10.8f; %10.8f\n", z1.re, z1.im, z2.re, z2.im, DEL); if ((z1.re == z2.re) && (z1.im == -z2.im)) { z2.re = z2.re*cos(DEL) - z2.im*sin(DEL); z2.im = z2.im*cos(DEL) - z2.re*sin(DEL); } temp1 = getTHpi(z1, a, A); temp2 = getTHmi(z2, ainv, A); K1 = prod(temp1, temp2); temp1 = getTHmi(z1, ainv, A); temp2 = getTHpi(z2, a, A); temp1 = prod(temp1, temp2); temp1 = neg(temp1); K1 = add(K1, temp1); temp1 = prod(z1, z2); temp2 = add(temp1, -1.0); temp2 = inv(temp2); temp1 = prod(temp1, temp2); K1 = prod(temp1, K1); return K1; } // Start of the main program int main () { int i, j; int n; double *pkplus, *pkminus; double **pMatrOut; double **pInfKsRe, **pInfKsIm; double alpha; double temp; complex_t Theta; complex_t lhs, rhs; complex_t z1, z2; complex_t k1, k2; double ainv; int UNITS; double COUP, A; printf("Starting matrixSetup...\n"); fp = fopen("Input.in", "r"); fscanf(fp, " %d ", &UNITS); fscanf(fp, " %lf ", &COUP); fclose(fp); A = EPSILON/2.0/COUP; ainv = 1.0/A; n = UNITS*2; // pMatrOut = dmatrix(1,n, 1,n); pInfKsRe = dmatrix(1,UNITS, 1,UNITS); pInfKsIm = dmatrix(1,UNITS, 1,UNITS); // Set k values pkplus = dvector(1,UNITS); pkminus = dvector(1,UNITS); i = AlphaBetaVals(pkplus, pkminus, UNITS); // Set up A matrix and write to file printf("Setting up A matrix... \n"); fp = fopen("AMatrix.in", "w"); for (i=1; i<=UNITS; i++) { for (j=1; j<=UNITS; j++) { lhs = getLHS(pkplus[j], pkminus[i], UNITS, COUP); fprintf(fp, "%20.10f %20.10f \n", lhs.re, lhs.im); } fprintf(fp, "\n"); } fclose(fp); printf("AMatrix.in successfully written...\n"); // Set up B vectors (for all alpha2 values!) and write to file printf("Setting up b vector... \n"); fp = fopen("bVector.in", "w"); for (i=1; i<=UNITS; i++) { for (j=1; j<=UNITS; j++) { rhs = getRHS(pkplus[i], pkminus[j], COUP); fprintf(fp, "%20.10f %20.10f \n", rhs.re, rhs.im); } fprintf(fp, "\n"); } fclose(fp); printf("bVector.in successfully written...\n"); // Calculate infinite size limit Ks // Four-column output file: alpha1, alpha2, Re(K_inf), Im(K_inf) printf("Calculating infinite volume Ks... \n"); fp = fopen("InfKsVsAlpha.out", "w"); for (i=1; i<=UNITS; i++) { for (j=1; j<=UNITS; j++) { k1.re = k1.im = k2.re = k2.im = 0.0; z1.re = 0.0; z1.im = pkplus[i]; z2.re = 0.0; z2.im = pkplus[j]; z1 = cexp(z1); z2 = cexp(z2); k1 = getK(z1, z2, A); k2 = getK(z2, z1, A); fprintf(fp, " %20.10f %20.10f %20.10f %20.10f \n", pkplus[j], pkplus[i], k2.re, k2.im); } fprintf(fp,"\n"); } fclose(fp); printf("InfKsVsAlpha.out successfully written...\n"); // Calculate infinite size limit Js (same as K1!) // Three-column output file: alpha, Re(J_inf), Im(J_inf) if (fabs(A) > 1) { printf("Calculating infinite volume Js (K1s)... \n"); fp = fopen("InfJsVsAlpha.out", "w"); for (i=1; i<=UNITS; i++) { z1.re = 0.0; z1.im = pkplus[i]; z1 = cexp(z1); k1 = getTHmi(z1, ainv, A); fprintf(fp, " %20.10f %20.10f %20.10f \n", pkplus[i], k1.re, k1.im); } fclose(fp); printf("InfJsVsAlpha.out successfully written...\n"); } free_dvector(pkplus, 1,UNITS); free_dvector(pkminus, 1,UNITS); printf("matrixSetup successfully finished!\n\n"); return 0; }
76a50786788f314edf90ed05fcff67a87c4fc792
18acff2d48798aaf04f2771032c8d899b7957b76
/Chapter06/ex.06.02.cpp
18087aef13f19dd4b8f2762fcfd4e6423b68dde0
[]
no_license
lubo3751/CppPrimerPlus
67f0d99c2b4507b7633cca503d3ae920427166bf
8041d17f3179e80da120222ece45de332303b4c0
refs/heads/master
2022-12-10T00:37:24.390821
2017-06-23T11:15:47
2017-06-23T11:15:47
87,181,332
6
2
null
2023-01-14T22:15:27
2017-04-04T12:00:20
C++
UTF-8
C++
false
false
1,575
cpp
ex.06.02.cpp
/* ex.06.02.cpp Write a program that reads up to 10 donation values into an array of double. (Or, if you prefer, use an array template object.) The program should terminate input on non-numeric input. It should report the average of the numbers and also report how many numbers in the array are larger than the average. */ #include <iostream> #include <array> const int MAX = 10; int main() { using namespace std; // get data array<double, MAX> donations; cout << "Please enter the values of donations." << endl; cout << "You may enter up to " << MAX; cout << " values <non-numeric input to terminate>." << endl; cout << "Donation #1: "; int i = 0; while (i < MAX && cin >> donations[i]) { if (++i < MAX) { cout << "donation #" << i+1 << ": "; } } // calculate average double total = 0.0; for (int j = 0; j < i; j++) { total += donations[j]; } double average = total / i; // calculate number of values above average int aboves = 0; for (int j = 0; j < i; j++) { if (donations[j] > average) { ++aboves; } } // report results if (i == 0) { cout << "No donations" << endl; } else { cout << average << " = average value of " << i << " donations" << endl; if (aboves == 1) { cout << aboves << " value was above the average" << endl; } else { cout << aboves << " values were above the average" << endl; } } cout << "Done." << endl; return 0; }
01b2ee663f6094e8107dc5317ff4b6af9f700d6d
4352b5c9e6719d762e6a80e7a7799630d819bca3
/tutorials/eulerVortex.twitch/eulerVortex.cyclic.twitch.moving/1.07/p
44da6b59582dd919a28ef2e38e04f5ee65fa8c40
[]
no_license
dashqua/epicProject
d6214b57c545110d08ad053e68bc095f1d4dc725
54afca50a61c20c541ef43e3d96408ef72f0bcbc
refs/heads/master
2022-02-28T17:20:20.291864
2019-10-28T13:33:16
2019-10-28T13:33:16
184,294,390
1
0
null
null
null
null
UTF-8
C++
false
false
41,982
p
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "1.07"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -2 0 0 0 0]; internalField nonuniform List<scalar> 10000 ( 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 0.999999 0.999999 0.999999 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 0.999998 0.999998 0.999998 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999998 0.999998 0.999998 0.999997 0.999997 0.999997 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 0.999998 0.999997 0.999997 0.999996 0.999995 0.999995 0.999995 0.999995 0.999996 0.999997 0.999999 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 1 1 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999998 0.999997 0.999996 0.999994 0.999993 0.999992 0.999992 0.999991 0.999992 0.999994 0.999996 0.999998 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 0.999999 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999997 0.999996 0.999994 0.999991 0.999989 0.999987 0.999987 0.999987 0.999988 0.99999 0.999994 0.999997 1 1 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 1 1 0.999999 0.999998 0.999999 0.999998 0.999999 1 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999997 0.999994 0.99999 0.999986 0.999983 0.99998 0.999979 0.999979 0.999981 0.999985 0.99999 0.999995 1 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 0.999999 0.999999 0.999997 0.999997 0.999998 0.999997 0.999998 1 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999997 0.999992 0.999986 0.999979 0.999974 0.99997 0.999968 0.999967 0.999971 0.999976 0.999983 0.999992 1 1.00001 1.00002 1.00002 1.00002 1.00002 1.00002 1.00001 1.00001 1 1 0.999999 0.999997 0.999996 0.999997 0.999997 0.999997 0.999998 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00001 1.00001 1.00001 1.00001 1 0.999997 0.99999 0.999981 0.999971 0.999962 0.999955 0.99995 0.999949 0.999954 0.999962 0.999974 0.999987 1 1.00001 1.00002 1.00003 1.00003 1.00003 1.00003 1.00002 1.00001 1.00001 1 0.999998 0.999996 0.999995 0.999994 0.999996 0.999997 0.999996 0.999997 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 0.999999 0.999989 0.999975 0.999959 0.999945 0.999932 0.999925 0.999923 0.999929 0.999941 0.999958 0.99998 1 1.00002 1.00004 1.00005 1.00005 1.00005 1.00004 1.00003 1.00002 1.00001 1.00001 0.999999 0.999994 0.999994 0.999993 0.999993 0.999995 0.999996 0.999996 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00001 1.00001 1.00001 1.00002 1.00002 1.00002 1.00002 1.00002 1.00001 0.999989 0.999968 0.999945 0.999922 0.999902 0.99989 0.999886 0.999893 0.99991 0.999936 0.999967 1 1.00003 1.00006 1.00007 1.00008 1.00008 1.00007 1.00006 1.00004 1.00003 1.00001 1 0.999994 0.999992 0.99999 0.999989 0.999991 0.999993 0.999995 0.999997 0.999997 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1.00001 1.00001 1.00001 1.00002 1.00002 1.00003 1.00004 1.00004 1.00004 1.00003 1.00002 0.999993 0.999963 0.999929 0.999894 0.999863 0.999842 0.999835 0.999843 0.999868 0.999904 0.999951 0.999999 1.00005 1.00008 1.00011 1.00012 1.00012 1.00011 1.00009 1.00007 1.00004 1.00002 1.00001 0.999997 0.999989 0.999986 0.999986 0.999987 0.999989 0.999993 0.999995 0.999996 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1 1 1.00001 1.00001 1.00002 1.00003 1.00003 1.00005 1.00006 1.00006 1.00006 1.00006 1.00004 1 0.999962 0.999912 0.999861 0.999815 0.999783 0.99977 0.999779 0.999812 0.999864 0.999929 1 1.00007 1.00012 1.00016 1.00019 1.00019 1.00017 1.00015 1.00011 1.00008 1.00005 1.00002 1 0.999989 0.999983 0.999981 0.999982 0.999986 0.999989 0.999992 0.999994 0.999996 0.999998 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1 1.00001 1.00001 1.00002 1.00002 1.00004 1.00005 1.00007 1.00009 1.0001 1.0001 1.00009 1.00007 1.00003 0.99997 0.999901 0.999827 0.999762 0.999715 0.999693 0.999703 0.999747 0.999818 0.99991 1.00001 1.00011 1.00019 1.00025 1.00028 1.00028 1.00027 1.00023 1.00018 1.00013 1.00008 1.00004 1.00001 0.999992 0.999981 0.999976 0.999976 0.999979 0.999984 0.999988 0.999991 0.999994 0.999996 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999998 1 1 1 1 1 1 1.00001 1.00001 1.00002 1.00003 1.00005 1.00008 1.0001 1.00013 1.00015 1.00016 1.00015 1.00012 1.00007 0.999995 0.999902 0.999804 0.999714 0.999648 0.999616 0.999628 0.999685 0.999781 0.999905 1.00004 1.00018 1.00029 1.00038 1.00042 1.00043 1.00041 1.00035 1.00029 1.00021 1.00014 1.00008 1.00003 1 0.999981 0.999973 0.99997 0.999973 0.999978 0.999982 0.999987 0.999991 0.999995 0.999996 0.999998 0.999999 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 1 1 1 1 1 1.00001 1.00001 1.00002 1.00003 1.00005 1.00007 1.0001 1.00014 1.00018 1.00021 1.00023 1.00023 1.0002 1.00014 1.00005 0.999931 0.999806 0.999689 0.999603 0.999563 0.99958 0.999656 0.999784 0.999949 1.00013 1.00031 1.00046 1.00058 1.00064 1.00066 1.00062 1.00054 1.00045 1.00034 1.00024 1.00015 1.00007 1.00002 0.999989 0.999971 0.999964 0.999966 0.99997 0.999977 0.999983 0.999988 0.999991 0.999995 0.999998 0.999998 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1.00001 1.00001 1.00002 1.00004 1.00006 1.0001 1.00014 1.00019 1.00025 1.0003 1.00033 1.00034 1.00032 1.00025 1.00015 1.00001 0.999859 0.99972 0.99962 0.999577 0.999607 0.99971 0.999879 1.0001 1.00033 1.00056 1.00076 1.00091 1.00099 1.001 1.00094 1.00083 1.00069 1.00054 1.00038 1.00025 1.00014 1.00006 1.00001 0.999974 0.999962 0.999959 0.999963 0.999969 0.999977 0.999983 0.99999 0.999994 0.999995 0.999998 0.999999 0.999998 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1.00001 1.00002 1.00003 1.00005 1.00008 1.00013 1.00018 1.00025 1.00033 1.0004 1.00046 1.00049 1.00048 1.00042 1.00031 1.00016 1 0.999856 0.999754 0.999723 0.999781 0.999927 1.00015 1.00043 1.00073 1.00102 1.00126 1.00144 1.00153 1.00152 1.00143 1.00127 1.00106 1.00083 1.00061 1.00041 1.00025 1.00013 1.00004 0.99999 0.999963 0.999953 0.999954 0.999962 0.99997 0.99998 0.999986 0.999989 0.999995 0.999997 0.999997 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999998 1 1 1 1 1.00001 1.00001 1.00002 1.00003 1.00006 1.0001 1.00016 1.00023 1.00032 1.00042 1.00052 1.00061 1.00068 1.00069 1.00066 1.00057 1.00043 1.00029 1.00016 1.00008 1.00009 1.0002 1.00042 1.00071 1.00107 1.00144 1.0018 1.00209 1.00229 1.00237 1.00233 1.00217 1.00192 1.00161 1.00127 1.00095 1.00066 1.00042 1.00023 1.00011 1.00002 0.999973 0.999952 0.999949 0.999954 0.999964 0.999972 0.99998 0.999989 0.999993 0.999994 0.999998 0.999999 0.999998 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999998 1 1 1 1 1 1.00001 1.00001 1.00002 1.00004 1.00007 1.00012 1.00018 1.00028 1.00039 1.00052 1.00066 1.0008 1.00091 1.00097 1.00099 1.00095 1.00086 1.00077 1.0007 1.0007 1.00079 1.00099 1.00129 1.00169 1.00214 1.0026 1.00302 1.00337 1.00358 1.00365 1.00355 1.00329 1.0029 1.00243 1.00193 1.00145 1.00103 1.00067 1.0004 1.0002 1.00007 0.999996 0.999958 0.999945 0.999946 0.999954 0.999966 0.999978 0.999985 0.999989 0.999995 0.999997 0.999997 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1.00001 1.00001 1.00002 1.00005 1.00008 1.00014 1.00021 1.00032 1.00046 1.00063 1.00082 1.00101 1.00118 1.00132 1.00142 1.00147 1.00149 1.00152 1.00157 1.00169 1.00191 1.00223 1.00266 1.00316 1.00372 1.00428 1.00479 1.0052 1.00546 1.0055 1.00532 1.00492 1.00433 1.00363 1.00289 1.00219 1.00156 1.00105 1.00064 1.00035 1.00016 1.00003 0.99997 0.999943 0.999939 0.999946 0.99996 0.999971 0.99998 0.999988 0.999993 0.999994 0.999999 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 0.999999 1 1 1 1.00001 1.00001 1.00003 1.00005 1.00009 1.00015 1.00024 1.00037 1.00053 1.00074 1.00097 1.00123 1.00149 1.00174 1.00197 1.00217 1.00237 1.00258 1.00283 1.00314 1.00352 1.00398 1.00451 1.0051 1.00574 1.0064 1.00703 1.00756 1.00791 1.008 1.00776 1.00719 1.00635 1.00533 1.00426 1.00324 1.00233 1.00158 1.00099 1.00056 1.00028 1.00009 0.999992 0.999948 0.999933 0.999938 0.999951 0.999964 0.999977 0.999985 0.99999 0.999997 0.999999 0.999997 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00001 1.00001 1.00003 1.00005 1.00009 1.00016 1.00026 1.0004 1.00059 1.00084 1.00113 1.00147 1.00184 1.00222 1.00263 1.00305 1.0035 1.00399 1.00452 1.00506 1.0056 1.00612 1.00665 1.0072 1.00782 1.00853 1.0093 1.01006 1.01067 1.01097 1.01082 1.01016 1.00906 1.00766 1.00615 1.00469 1.00339 1.00231 1.00147 1.00086 1.00044 1.00017 1.00002 0.99995 0.999926 0.999926 0.999938 0.999956 0.99997 0.99998 0.99999 0.999995 0.999995 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1.00001 1.00001 1.00003 1.00005 1.00009 1.00016 1.00027 1.00042 1.00064 1.00092 1.00128 1.0017 1.0022 1.00276 1.0034 1.00411 1.0049 1.00576 1.0066 1.00736 1.00794 1.00833 1.00855 1.00872 1.00901 1.00959 1.0105 1.01164 1.01281 1.01371 1.01402 1.01357 1.01237 1.01063 1.00862 1.00662 1.0048 1.00329 1.00211 1.00124 1.00065 1.00028 1.00006 0.999953 0.999912 0.999909 0.999924 0.999943 0.99996 0.999976 0.999985 0.999989 0.999994 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00001 1.00001 1.00002 1.00005 1.00009 1.00015 1.00026 1.00043 1.00066 1.00098 1.0014 1.00192 1.00256 1.00333 1.00425 1.00532 1.00654 1.00781 1.00898 1.00983 1.01017 1.00992 1.00919 1.00826 1.00757 1.00755 1.00842 1.01012 1.01234 1.01455 1.01614 1.0166 1.01582 1.01401 1.01161 1.00902 1.0066 1.00455 1.00292 1.00173 1.00092 1.0004 1.0001 0.999949 0.999892 0.999886 0.999901 0.999925 0.99995 0.999967 0.999978 0.999989 0.999995 0.999997 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 1 1 1 1 1.00001 1.00002 1.00004 1.00008 1.00014 1.00025 1.00042 1.00066 1.00101 1.00149 1.00211 1.00291 1.00391 1.00515 1.00664 1.00833 1.01005 1.01146 1.01212 1.01164 1.00985 1.00698 1.00365 1.00074 0.999157 0.999474 1.00176 1.00564 1.01031 1.01459 1.0174 1.01819 1.01711 1.01472 1.01174 1.00872 1.00605 1.00391 1.00232 1.00123 1.00054 1.00013 0.999934 0.999858 0.999847 0.999868 0.999903 0.999932 0.999955 0.999975 0.999987 0.999992 0.999995 0.999997 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1.00001 1.00002 1.00003 1.00006 1.00012 1.00022 1.00038 1.00064 1.00101 1.00153 1.00225 1.00321 1.00446 1.00605 1.00799 1.01018 1.01232 1.01377 1.01374 1.01149 1.00672 0.999838 0.991984 0.984812 0.979971 0.978611 0.981154 0.987267 0.99587 1.00504 1.01261 1.01716 1.01844 1.01714 1.01431 1.01094 1.00772 1.00503 1.00299 1.00158 1.00068 1.00016 0.999901 0.999803 0.999794 0.999827 0.99987 0.99991 0.999944 0.999966 0.99998 0.999989 0.999994 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 0.999999 1 1 1.00001 1.00002 1.00005 1.00009 1.00018 1.00034 1.00058 1.00096 1.00153 1.00234 1.00346 1.00496 1.00691 1.0093 1.01198 1.01442 1.0156 1.01414 1.00876 0.998962 0.985427 0.970113 0.955772 0.945125 0.940197 0.942035 0.950609 0.964691 0.981524 0.997363 1.00913 1.01562 1.01739 1.01593 1.01283 1.00933 1.00618 1.0037 1.00194 1.00081 1.00017 0.999844 0.99973 0.999726 0.999771 0.99983 0.999884 0.999926 0.999955 0.999974 0.999987 0.999994 0.999997 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 0.999999 0.999998 1 1 1.00001 1.00003 1.00006 1.00014 1.00027 1.0005 1.00088 1.00147 1.00235 1.00363 1.00538 1.00767 1.0105 1.01361 1.01619 1.01666 1.01282 1.00262 0.985241 0.961825 0.935512 0.910542 0.891001 0.880029 0.879567 0.890182 0.910798 0.938009 0.966186 0.989738 1.00553 1.01347 1.01539 1.01374 1.01055 1.00719 1.00436 1.00229 1.00093 1.00015 0.999766 0.999636 0.99964 0.999704 0.999783 0.999853 0.999906 0.999944 0.999969 0.999984 0.999991 0.999995 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999998 0.999999 1 0.999998 0.999997 0.999996 0.999996 1 1.00003 1.00008 1.0002 1.0004 1.00077 1.00137 1.0023 1.00371 1.00568 1.00831 1.01153 1.01496 1.01747 1.01676 1.00952 0.992647 0.964951 0.928321 0.887531 0.848692 0.817436 0.798085 0.793515 0.805062 0.832184 0.871361 0.915326 0.95536 0.985269 1.00335 1.01145 1.01295 1.011 1.00789 1.0049 1.00258 1.00102 1.00011 0.999673 0.999529 0.999546 0.999632 0.999731 0.999818 0.999885 0.999933 0.999962 0.999979 0.999989 0.999995 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999998 0.999998 0.999996 0.999993 0.99999 0.999985 0.999984 0.999994 1.00003 1.00011 1.00029 1.00063 1.00122 1.00219 1.00369 1.00587 1.00879 1.01233 1.01597 1.01821 1.01587 1.00431 0.979091 0.938689 0.886125 0.828364 0.773683 0.729258 0.700344 0.690396 0.701401 0.733664 0.784329 0.845426 0.905231 0.953548 0.985849 1.00326 1.00994 1.0104 1.00813 1.00526 1.0028 1.00108 1.00007 0.999575 0.999422 0.999453 0.999559 0.999681 0.999786 0.999867 0.999921 0.999955 0.999977 0.999988 0.999995 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999997 0.999995 0.99999 0.999984 0.999975 0.999966 0.999962 0.999976 1.00003 1.00017 1.00047 1.00103 1.00201 1.00358 1.00593 1.0091 1.01292 1.01666 1.01843 1.01417 0.99768 0.963028 0.908425 0.838536 0.763053 0.692613 0.635675 0.597819 0.582371 0.591525 0.626558 0.686052 0.762689 0.842791 0.911897 0.961496 0.990933 1.00471 1.00873 1.00791 1.00544 1.00298 1.00114 1.00003 0.999493 0.99933 0.999372 0.999498 0.999638 0.99976 0.99985 0.999912 0.999951 0.999975 0.999988 0.999994 0.999997 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 1 0.999997 0.999995 0.999989 0.99998 0.999968 0.999952 0.999936 0.999932 0.999957 1.00006 1.00031 1.00083 1.00178 1.00339 1.00586 1.00925 1.01329 1.01705 1.01826 1.01201 0.990503 0.946211 0.877224 0.790315 0.698328 0.614247 0.547355 0.502731 0.482798 0.48939 0.524636 0.589071 0.677267 0.775177 0.864732 0.93277 0.975782 0.997932 1.00632 1.00739 1.00554 1.00315 1.00124 1.00004 0.999452 0.999273 0.999318 0.999456 0.999611 0.999743 0.999841 0.999907 0.999949 0.999973 0.999987 0.999994 0.999997 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999998 0.999996 0.999993 0.999988 0.999979 0.999964 0.999942 0.999916 0.999895 0.999895 0.999959 1.00016 1.00062 1.00153 1.00313 1.00567 1.00924 1.01348 1.01724 1.01789 1.00982 0.98382 0.930732 0.8486 0.746561 0.640772 0.546384 0.472904 0.424234 0.4014 0.405447 0.439033 0.504735 0.599715 0.711003 0.818193 0.903596 0.960117 0.990879 1.00384 1.00691 1.00571 1.00341 1.00142 1.00012 0.999475 0.999266 0.999304 0.999444 0.999602 0.999739 0.999839 0.999907 0.999949 0.999974 0.999987 0.999994 0.999997 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 0.999998 0.999998 0.999994 0.999988 0.999978 0.999961 0.999937 0.999906 0.999872 0.99985 0.999878 1.00002 1.00041 1.00125 1.00281 1.00538 1.00908 1.01351 1.01732 1.01754 1.00808 0.978625 0.918565 0.825778 0.711629 0.595403 0.494091 0.416962 0.366492 0.34222 0.344277 0.375488 0.440096 0.537917 0.657831 0.778431 0.878293 0.946638 0.98508 1.00208 1.00685 1.00613 1.00384 1.00172 1.00031 0.999577 0.999324 0.999339 0.999467 0.999618 0.999749 0.999847 0.999912 0.999952 0.999976 0.999988 0.999994 0.999997 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999997 0.999995 0.999989 0.999979 0.999963 0.999938 0.999903 0.99986 0.999823 0.99982 0.999916 1.00023 1.00098 1.00246 1.00499 1.00877 1.01339 1.01735 1.01739 1.00713 0.975662 0.911188 0.811155 0.688542 0.565206 0.459612 0.380668 0.329648 0.304886 0.30575 0.33496 0.39777 0.496117 0.620786 0.750277 0.860573 0.937754 0.981894 1.00173 1.00749 1.00692 1.00446 1.00215 1.00059 0.999764 0.999449 0.999423 0.999525 0.999657 0.999775 0.999863 0.999922 0.999958 0.999979 0.99999 0.999995 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999997 0.999995 0.99999 0.999981 0.999966 0.999941 0.999907 0.999861 0.999813 0.999787 0.999839 1.00008 1.00073 1.00208 1.00453 1.00831 1.01311 1.01736 1.01757 1.00723 0.975331 0.909368 0.806038 0.678906 0.551492 0.443372 0.363387 0.312177 0.287366 0.287861 0.316169 0.377824 0.475918 0.602635 0.736776 0.852925 0.935071 0.982151 1.0031 1.00893 1.00805 1.00526 1.00269 1.00096 1.00002 0.999635 0.999555 0.999616 0.999718 0.999814 0.999887 0.999936 0.999966 0.999983 0.999992 0.999997 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999998 0.999997 0.999992 0.999984 0.999972 0.999948 0.999916 0.999871 0.999819 0.999778 0.999795 0.999971 1.0005 1.00171 1.004 1.0077 1.01264 1.0173 1.01808 1.00845 0.97769 0.913158 0.810625 0.683061 0.554437 0.445077 0.364274 0.312785 0.288133 0.289078 0.317906 0.379781 0.477765 0.604546 0.739323 0.856423 0.939116 0.985936 1.00606 1.01097 1.00936 1.00611 1.00327 1.00138 1.00033 0.999866 0.999723 0.999734 0.999798 0.999865 0.999918 0.999954 0.999976 0.999988 0.999995 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999997 0.999994 0.999987 0.999977 0.999957 0.99993 0.999888 0.999837 0.999789 0.999778 0.999895 1.00031 1.00135 1.00343 1.00696 1.01193 1.01705 1.01878 1.01068 0.982519 0.922035 0.824156 0.700249 0.573411 0.464227 0.382916 0.331127 0.306918 0.309197 0.339963 0.403478 0.501616 0.626513 0.757779 0.870666 0.94925 0.992544 1.01 1.01317 1.01058 1.00684 1.00377 1.00177 1.00065 1.00012 0.999913 0.999869 0.999888 0.999922 0.999953 0.999974 0.999987 0.999994 0.999997 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 0.999996 0.999991 0.999983 0.999967 0.999945 0.999909 0.999863 0.999815 0.999787 0.999853 1.00017 1.00101 1.00283 1.0061 1.01096 1.01647 1.0194 1.01357 0.989334 0.935101 0.845208 0.728843 0.60707 0.500074 0.419207 0.367614 0.344451 0.349001 0.382817 0.448763 0.546621 0.667091 0.790319 0.893735 0.963732 1.00061 1.01397 1.01493 1.01135 1.00725 1.0041 1.00208 1.00093 1.00036 1.0001 1 0.999979 0.99998 0.999988 0.999994 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999998 0.999994 0.999988 0.999977 0.99996 0.999932 0.999895 0.99985 0.999814 0.999841 1.00006 1.00072 1.00224 1.00514 1.00974 1.01546 1.01962 1.01657 0.997341 0.951157 0.871971 0.766623 0.653391 0.551361 0.472841 0.422757 0.401683 0.409359 0.446646 0.514571 0.610312 0.722815 0.833185 0.922261 0.979979 1.00839 1.01696 1.0157 1.01137 1.00718 1.00413 1.00221 1.00111 1.00054 1.00025 1.00012 1.00006 1.00003 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 0.999998 0.999996 0.999993 0.999986 0.999974 0.999957 0.999927 0.999892 0.999854 0.999853 0.999992 1.00048 1.00169 1.00415 1.00831 1.01397 1.01914 1.01898 1.00545 0.968636 0.90226 0.810891 0.709663 0.615979 0.542628 0.496171 0.478549 0.489806 0.529878 0.597697 0.687827 0.787899 0.88084 0.951879 0.995099 1.01426 1.01815 1.01515 1.01053 1.00657 1.00383 1.00213 1.00116 1.00063 1.00034 1.00019 1.00011 1.00006 1.00004 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999997 0.999996 0.999992 0.999987 0.999976 0.999958 0.999933 0.9999 0.999885 0.999957 1.00029 1.00121 1.0032 1.00678 1.01207 1.01782 1.02023 1.01245 0.985624 0.933414 0.858314 0.772234 0.690442 0.625572 0.585208 0.572229 0.586702 0.627534 0.691646 0.771529 0.854625 0.926793 0.978133 1.00665 1.0172 1.0173 1.01331 1.00891 1.00549 1.00323 1.00186 1.00107 1.00062 1.00037 1.00022 1.00013 1.00008 1.00005 1.00003 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 0.999998 0.999999 0.999998 0.999997 0.999995 0.999989 0.999984 0.999967 0.999946 0.999924 0.999951 1.00016 1.00081 1.00234 1.00528 1.00994 1.01573 1.02 1.01732 1.00017 0.962435 0.904834 0.836216 0.769336 0.715917 0.683673 0.675747 0.692047 0.730561 0.78665 0.851815 0.91474 0.965126 0.997689 1.01334 1.01709 1.01475 1.0106 1.00685 1.00417 1.00247 1.00147 1.00088 1.00054 1.00034 1.00021 1.00013 1.00008 1.00005 1.00003 1.00002 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 0.999999 0.999999 0.999999 1 0.999999 0.999999 0.999996 0.999982 0.999964 0.999963 1.00008 1.00051 1.00163 1.00392 1.0078 1.01316 1.01838 1.0196 1.01081 0.986535 0.946182 0.895818 0.845489 0.805188 0.781863 0.77837 0.7944 0.82732 0.871715 0.919435 0.961671 0.992171 1.00925 1.01533 1.01469 1.01128 1.00762 1.00476 1.00287 1.00172 1.00106 1.00067 1.00043 1.00028 1.00018 1.00011 1.00007 1.00004 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 1 1 1 1 0.999999 1 0.999998 1 0.999999 1 1.00001 1.00001 1.00001 1.00001 0.999991 0.999981 1.00003 1.00029 1.00106 1.00277 1.00585 1.01047 1.01583 1.01944 1.01699 1.00392 0.97891 0.94565 0.911433 0.884009 0.868926 0.868477 0.882186 0.907138 0.938093 0.968461 0.992527 1.00745 1.0137 1.0139 1.01115 1.00776 1.00493 1.00298 1.00179 1.00111 1.00072 1.00048 1.00033 1.00022 1.00015 1.0001 1.00006 1.00004 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 0.999999 1 1 1 1.00001 1.00001 1.00002 1.00001 0.999995 1 1.00014 1.00064 1.00185 1.0042 1.00797 1.01289 1.01756 1.01916 1.01429 1.00136 0.982264 0.961735 0.945176 0.936585 0.937622 0.94763 0.963885 0.982139 0.998007 1.00858 1.01325 1.01328 1.01076 1.00756 1.0048 1.00287 1.00169 1.00103 1.00068 1.00047 1.00034 1.00025 1.00017 1.00012 1.00008 1.00005 1.00003 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 1 1 0.999999 1 1 0.999999 1 0.999999 0.999998 1 0.999997 1 1.00001 1.00001 1.00002 1.00001 0.999996 0.999983 1.00004 1.00033 1.00116 1.00288 1.00583 1.01002 1.01479 1.01844 1.01869 1.01404 1.00514 0.994696 0.986057 0.981841 0.983071 0.98903 0.997556 1.00585 1.01162 1.0139 1.01311 1.01047 1.00732 1.00458 1.00265 1.00148 1.00087 1.00057 1.00042 1.00032 1.00025 1.00019 1.00014 1.00009 1.00006 1.00004 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 0.999999 1 1 1 0.999998 1 1 0.999996 0.999999 0.999997 1 1.00001 1.00001 1.00001 0.999993 0.999969 0.999973 1.00014 1.00067 1.00188 1.00411 1.00751 1.0118 1.01608 1.01889 1.01902 1.01642 1.01235 1.00868 1.00693 1.00759 1.01006 1.01297 1.01486 1.01492 1.01318 1.0103 1.00714 1.00441 1.00246 1.00128 1.00068 1.00042 1.00032 1.00028 1.00024 1.00019 1.00015 1.00011 1.00007 1.00005 1.00003 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999998 0.999999 1 1 1 0.999995 1 0.999994 0.999998 0.999997 0.999998 1 0.999997 0.999987 0.999955 0.999935 1.00001 1.00034 1.00118 1.0028 1.00544 1.00902 1.01308 1.01672 1.019 1.01959 1.01891 1.01785 1.01718 1.01708 1.01717 1.01678 1.01544 1.01309 1.01008 1.00698 1.0043 1.00234 1.00113 1.00051 1.00027 1.00021 1.00021 1.0002 1.00018 1.00015 1.00012 1.00008 1.00006 1.00004 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 1 1 0.999997 1 0.999998 1 0.999996 0.999996 0.999992 0.999994 0.999995 0.999991 0.999987 0.999974 0.999945 0.999916 0.999933 1.00013 1.00069 1.00185 1.00383 1.00666 1.01009 1.01355 1.01637 1.01813 1.01885 1.01886 1.0185 1.01783 1.01669 1.01491 1.01249 1.00964 1.00675 1.00421 1.00229 1.00105 1.0004 1.00015 1.0001 1.00013 1.00015 1.00016 1.00014 1.00012 1.00009 1.00006 1.00004 1.00003 1.00002 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999998 1 1 0.999997 1 1 0.999999 1 0.999999 1 0.999994 1 0.999999 0.999997 0.999997 0.999991 0.999991 0.999988 0.999987 0.999982 0.999965 0.99994 0.999907 0.999899 1 1.00037 1.00118 1.00262 1.00475 1.00743 1.01029 1.01283 1.01468 1.0157 1.01597 1.01563 1.01473 1.01325 1.01124 1.00886 1.00638 1.00411 1.00229 1.00106 1.00036 1.00007 1.00001 1.00004 1.00009 1.00012 1.00012 1.00011 1.00009 1.00006 1.00004 1.00003 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 0.999999 1 0.999999 1 0.999997 0.999998 0.999999 0.999997 0.999992 0.999993 0.99998 0.999985 0.999975 0.999962 0.999941 0.999906 0.99989 0.99994 1.00017 1.00072 1.00173 1.00327 1.00524 1.00738 1.00935 1.01084 1.0117 1.01193 1.0116 1.01075 1.00942 1.00772 1.0058 1.00392 1.00231 1.00113 1.0004 1.00005 0.999947 0.999968 1.00002 1.00007 1.00009 1.00009 1.00008 1.00006 1.00004 1.00003 1.00002 1.00001 1.00001 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 0.999999 1 1 0.999999 1 1 1 0.999999 0.999999 1 1 0.999997 0.999997 0.999998 0.999993 0.99999 0.999983 0.99998 0.999972 0.999962 0.999945 0.999919 0.999892 0.999916 1.00005 1.00041 1.0011 1.00215 1.00352 1.00502 1.00639 1.00743 1.00803 1.00818 1.00792 1.00728 1.00629 1.00502 1.00363 1.00231 1.00123 1.0005 1.0001 0.999938 0.999924 0.999968 1.00002 1.00005 1.00007 1.00006 1.00005 1.00004 1.00003 1.00002 1.00001 1.00001 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999998 1 1 0.999998 1 1 0.999998 1 0.999999 1 1 0.999997 0.999996 0.999994 0.999992 0.999984 0.999979 0.999974 0.999966 0.999952 0.999931 0.999909 0.999912 0.999985 1.00021 1.00065 1.00134 1.00224 1.00322 1.0041 1.00476 1.00515 1.00526 1.00512 1.00472 1.00406 1.00319 1.00222 1.00133 1.00065 1.0002 0.99998 0.999916 0.999933 0.999977 1.00001 1.00003 1.00004 1.00004 1.00003 1.00002 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 0.999998 1 1 1 0.999998 1 1 1 0.999998 0.999995 0.999995 0.999992 0.999989 0.999981 0.999975 0.999972 0.99996 0.999948 0.999927 0.99992 0.999955 1.00008 1.00034 1.00077 1.00132 1.00192 1.00245 1.00285 1.0031 1.00322 1.0032 1.00301 1.0026 1.00202 1.00137 1.00077 1.00033 1.00007 0.999952 0.999929 0.99995 0.999981 1.00001 1.00002 1.00003 1.00003 1.00002 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 0.999999 1 0.999999 1 1 0.999999 1 0.999999 0.999999 0.999997 0.999999 0.999995 0.999991 0.999989 0.999986 0.999981 0.999977 0.999971 0.999963 0.999949 0.999938 0.999944 1 1.00014 1.00038 1.00069 1.00103 1.00133 1.00157 1.00176 1.00191 1.00198 1.00191 1.00168 1.0013 1.00086 1.00046 1.00018 1.00002 0.999954 0.999946 0.999961 0.999982 1 1.00001 1.00002 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 1 1 1 1 0.999999 1 1 0.999998 0.999999 1 0.999999 1 0.999998 0.999998 1 0.999996 0.999994 0.99999 0.999988 0.999987 0.999983 0.99998 0.999977 0.999965 0.999955 0.999945 0.99996 1.00002 1.00013 1.00029 1.00046 1.00062 1.00078 1.00094 1.0011 1.00122 1.00123 1.0011 1.00084 1.00055 1.00029 1.00011 1 0.999963 0.999958 0.999972 0.999988 0.999998 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 0.999999 1 1 0.999999 1 1 0.999999 1 0.999999 1 0.999999 1 0.999998 1 0.999997 0.999998 0.999998 0.999994 0.999989 0.999991 0.99999 0.999989 0.999988 0.99998 0.999968 0.999951 0.999942 0.999952 0.999988 1.00005 1.00012 1.00021 1.00032 1.00046 1.00063 1.00077 1.00081 1.00073 1.00056 1.00036 1.00018 1.00006 1 0.999976 0.999973 0.999981 0.99999 0.999998 1 1 1.00001 1 1 1 1 1 1 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 1 1 0.999999 1 1 0.999997 1 1 0.999998 1 0.999997 0.999998 0.999998 0.999996 0.999994 0.999993 0.999993 0.999996 0.999996 0.999991 0.999981 0.999961 0.999939 0.999921 0.999915 0.999923 0.999946 0.99999 1.00007 1.0002 1.00036 1.00049 1.00054 1.00049 1.00037 1.00024 1.00012 1.00004 1 0.999984 0.999983 0.999987 0.999992 0.999996 1 1 1 0.999999 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 0.999999 1 1 0.999999 1 1 0.999999 1 1 0.999999 0.999999 1 0.999998 0.999998 0.999997 0.999999 0.999998 0.999996 0.999996 0.999999 1 0.999998 0.99999 0.999971 0.999944 0.999914 0.999888 0.999871 0.999869 0.999894 0.99996 1.00007 1.00021 1.00032 1.00036 1.00033 1.00025 1.00015 1.00008 1.00003 1 0.999992 0.99999 0.999991 0.999995 0.999998 1 1 0.999998 0.999999 1 1 1 0.999998 0.999999 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 0.999999 1 1 1 1 1 1 0.999999 0.999999 1 0.999998 1 1 1 0.999998 1 0.999997 0.999999 0.999998 0.999999 1 1 1 1 0.999995 0.99998 0.999954 0.999923 0.99989 0.999865 0.999852 0.999868 0.999922 1.00002 1.00012 1.00021 1.00024 1.00022 1.00016 1.0001 1.00005 1.00002 1 0.999993 0.999993 0.999997 0.999999 1 0.999998 0.999997 1 1 1 0.999998 0.999998 1 1 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999998 1 0.999999 1 1 1 0.999999 1 1 1 0.999999 1 1 0.999998 1 1 0.999999 0.999998 0.999998 0.999999 1 1 1.00001 1 1 0.999988 0.999966 0.999938 0.999907 0.999881 0.999866 0.999876 0.99992 0.999992 1.00007 1.00014 1.00016 1.00014 1.00011 1.00007 1.00004 1.00001 1 0.999998 0.999997 0.999997 0.999996 0.999999 0.999998 1 1 1 0.999998 0.999999 1 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 1 0.999999 1 0.999999 1 1 1 0.999999 1 1 1 0.999999 0.999999 0.999999 1 0.999998 1 1 1 1 1.00001 1.00001 1 0.999992 0.999977 0.999953 0.999928 0.999905 0.999892 0.999901 0.999934 0.999988 1.00005 1.00009 1.0001 1.00009 1.00007 1.00004 1.00002 1.00001 1 1 0.999998 0.999997 1 1 1 1 0.999998 0.999998 1 1 0.999999 0.999998 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999998 1 1 1 1 1 0.999998 1 0.999999 1 0.999999 1 1 0.999998 1 1 1 1 1 1 1 1.00001 1.00001 1 0.999997 0.999985 0.999967 0.999948 0.99993 0.999921 0.999926 0.999951 0.999989 1.00003 1.00006 1.00007 1.00006 1.00004 1.00003 1.00002 1.00001 1 1 0.999998 1 1 0.999998 1 1 0.999999 1 1 0.999999 0.999999 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999991 0.999979 0.999965 0.999952 0.999945 0.999949 0.999967 0.999993 1.00002 1.00004 1.00004 1.00003 1.00003 1.00002 1.00001 1.00001 1 0.999999 1 1 0.999997 1 1 1 1 1 0.999999 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 0.999999 1 0.999999 1 0.999999 1 0.999999 1 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 0.999996 0.999988 0.999979 0.999969 0.999964 0.999967 0.999978 0.999996 1.00001 1.00002 1.00002 1.00002 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 0.999999 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 0.999999 1 1 0.999999 1 1 1 1 1 1 0.999999 1 0.999999 1 1 1 1 1 1 1 1 0.999998 0.999993 0.999988 0.999981 0.999978 0.99998 0.999988 0.999998 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 0.999998 1 0.999999 1 0.999999 0.999999 1 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.999993 0.999989 0.999987 0.999988 0.999993 0.999999 1 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999997 0.999994 0.999993 0.999994 0.999996 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 0.999999 1 1 0.999999 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1 0.999999 1 1 1 0.999999 0.999999 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999998 0.999996 0.999997 0.999998 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 0.999999 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 0.999999 1 0.999999 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 0.999999 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ) ; boundaryField { emptyPatches_empt { type empty; } top_cyc { type cyclic; } bottom_cyc { type cyclic; } inlet_cyc { type cyclic; } outlet_cyc { type cyclic; } } // ************************************************************************* //
b3185a1e8e35fa02ce4ec9384615f94a035c79c4
bcb2c17303c407ac811db8e3fa41eb10e1965454
/src/components/GuiGameList.cpp
50afbfcd970ece2c889c5cefab7864ceb9b91cf5
[]
no_license
jefflunt/glint-ui
d57314e6c1f3a7a1071da5a03ce2b0a9ad54a391
dc81661f2a6e95f3ef3ca47cb6be04b4f5077a96
refs/heads/master
2016-09-05T16:47:11.368899
2013-01-06T07:10:54
2013-01-06T07:10:54
7,474,806
1
1
null
null
null
null
UTF-8
C++
false
false
8,009
cpp
GuiGameList.cpp
#include "GuiGameList.h" #include "../InputManager.h" #include <iostream> #include "GuiMenu.h" #include "GuiFastSelect.h" #include <boost/filesystem.hpp> //this is just a default value; the true value is in mTheme->getListOffsetX(); const float GuiGameList::sInfoWidth = 0.5; GuiGameList::GuiGameList(bool useDetail) { //std::cout << "Creating GuiGameList\n"; mDetailed = useDetail; mTheme = new GuiTheme(); //not a child because it's rendered manually by GuiGameList::onRender (to make sure it's rendered first) //The GuiGameList can use the older, simple game list if so desired. //The old view only shows a list in the center of the screen; the new view can display an image and description. //Those with smaller displays may prefer the older view. if(mDetailed) { mList = new GuiList<FileData*>(Renderer::getScreenWidth() * sInfoWidth, Renderer::getDefaultFont(Renderer::SMALL)->getHeight() + 2, Renderer::getDefaultFont(Renderer::SMALL)); mScreenshot = new GuiImage(Renderer::getScreenWidth() * mTheme->getGameImageOffsetX(), Renderer::getScreenHeight() * mTheme->getGameImageOffsetY(), "", Renderer::getScreenWidth() * sInfoWidth * 0.7, 0, false); mScreenshot->setOrigin(mTheme->getGameImageOriginX(), mTheme->getGameImageOriginY()); //addChild(mScreenshot); //the animation renders the screenshot mImageAnimation = new GuiAnimation(); mImageAnimation->addChild(mScreenshot); addChild(mImageAnimation); }else{ mList = new GuiList<FileData*>(0, Renderer::getDefaultFont(Renderer::SMALL)->getHeight() + 2, Renderer::getDefaultFont(Renderer::SMALL)); mScreenshot = NULL; mImageAnimation = NULL; } addChild(mList); setSystemId(0); Renderer::registerComponent(this); InputManager::registerComponent(this); } GuiGameList::~GuiGameList() { Renderer::unregisterComponent(this); delete mList; if(mDetailed) { delete mImageAnimation; delete mScreenshot; delete mTheme; } InputManager::unregisterComponent(this); } void GuiGameList::setSystemId(int id) { if(SystemData::sSystemVector.size() == 0) { std::cerr << "Error - no systems found!\n"; return; } //make sure the id is within range if(id >= (int)SystemData::sSystemVector.size()) id -= SystemData::sSystemVector.size(); if(id < 0) id += SystemData::sSystemVector.size(); mSystemId = id; mSystem = SystemData::sSystemVector.at(mSystemId); //clear the folder stack while(mFolderStack.size()){ mFolderStack.pop(); } mFolder = mSystem->getRootFolder(); updateTheme(); updateList(); updateDetailData(); } void GuiGameList::onRender() { if(mTheme) mTheme->render(); //header if(!mTheme->getHeaderHidden()) Renderer::drawCenteredText(mSystem->getName(), 0, 1, 0xFF0000FF, Renderer::getDefaultFont(Renderer::MEDIUM)); if(mDetailed) { //divider if(!mTheme->getDividersHidden()) Renderer::drawRect(Renderer::getScreenWidth() * mTheme->getListOffsetX() - 4, Renderer::getDefaultFont(Renderer::MEDIUM)->getHeight() + 2, 8, Renderer::getScreenHeight(), 0x0000FFFF); //if we're not scrolling and we have selected a non-folder if(!mList->isScrolling() && mList->getSelectedObject() && !mList->getSelectedObject()->isFolder()) { GameData* game = (GameData*)mList->getSelectedObject(); std::string desc = game->getDescription(); if(!desc.empty()) Renderer::drawWrappedText(desc, Renderer::getScreenWidth() * 0.03, mScreenshot->getOffsetY() + mScreenshot->getHeight() + 12, Renderer::getScreenWidth() * (mTheme->getListOffsetX() - 0.03), mTheme->getDescColor(), mTheme->getDescriptionFont()); } } } void GuiGameList::onInput(InputManager::InputButton button, bool keyDown) { if(button == InputManager::BUTTON1 && mFolder->getFileCount() > 0) { if(!keyDown) { FileData* file = mList->getSelectedObject(); if(file->isFolder()) //if you selected a folder, add this directory to the stack, and use the selected one { mFolderStack.push(mFolder); mFolder = (FolderData*)file; updateList(); }else{ mList->stopScrolling(); mSystem->launchGame((GameData*)file); } } } //if there's something on the directory stack, return to it if(button == InputManager::BUTTON2 && keyDown && mFolderStack.size()) { mFolder = mFolderStack.top(); mFolderStack.pop(); updateList(); updateDetailData(); } //only allow switching systems if more than one exists (otherwise it'll reset your position when you switch and it's annoying) if(SystemData::sSystemVector.size() > 1) { if(button == InputManager::RIGHT && keyDown) { setSystemId(mSystemId + 1); } if(button == InputManager::LEFT && keyDown) { setSystemId(mSystemId - 1); } } //open the "start menu" if(button == InputManager::MENU && keyDown) { new GuiMenu(this); } //open the fast select menu if(button == InputManager::SELECT && keyDown) { new GuiFastSelect(this, mList, mList->getSelectedObject()->getName()[0], mTheme->getBoxData(), mTheme->getFastSelectColor()); } if(mDetailed) { if(button == InputManager::UP || button == InputManager::DOWN) { if(!keyDown) updateDetailData(); else clearDetailData(); } } } void GuiGameList::updateList() { if(mDetailed) mScreenshot->setImage(""); mList->clear(); for(unsigned int i = 0; i < mFolder->getFileCount(); i++) { FileData* file = mFolder->getFile(i); if(file->isFolder()) mList->addObject(file->getName(), file, mTheme->getSecondaryColor()); else mList->addObject(file->getName(), file, mTheme->getPrimaryColor()); } } void GuiGameList::updateTheme() { if(!mTheme) return; std::string defaultPath = getenv("HOME"); defaultPath += "/.glint-es/es_theme.xml"; std::string themePath = mSystem->getStartPath() + "/theme.xml"; if(boost::filesystem::exists(themePath)) mTheme->readXML(themePath); else if(boost::filesystem::exists(defaultPath)) mTheme->readXML(defaultPath); else mTheme->readXML(""); //clears any current theme mList->setSelectorColor(mTheme->getSelectorColor()); mList->setSelectedTextColor(mTheme->getSelectedTextColor()); //fonts mList->setFont(mTheme->getListFont()); if(mDetailed) { mList->setCentered(mTheme->getListCentered()); mList->setOffsetX(mTheme->getListOffsetX() * Renderer::getScreenWidth()); mList->setTextOffsetX(mTheme->getListTextOffsetX() * Renderer::getScreenWidth()); mScreenshot->setOffsetX(mTheme->getGameImageOffsetX() * Renderer::getScreenWidth()); mScreenshot->setOffsetY(mTheme->getGameImageOffsetY() * Renderer::getScreenHeight()); mScreenshot->setOrigin(mTheme->getGameImageOriginX(), mTheme->getGameImageOriginY()); mScreenshot->setResize(mTheme->getGameImageWidth(), mTheme->getGameImageHeight(), false); } } void GuiGameList::updateDetailData() { if(!mDetailed) return; if(mList->getSelectedObject() && !mList->getSelectedObject()->isFolder()) { mScreenshot->setOffset((mTheme->getGameImageOffsetX() - 0.05) * Renderer::getScreenWidth(), mTheme->getGameImageOffsetY() * Renderer::getScreenHeight()); if(((GameData*)mList->getSelectedObject())->getImagePath().empty()) mScreenshot->setImage(mTheme->getImageNotFoundPath()); else mScreenshot->setImage(((GameData*)mList->getSelectedObject())->getImagePath()); mImageAnimation->fadeIn(15); mImageAnimation->move((int)(0.05 * Renderer::getScreenWidth()), 0, 5); }else{ mScreenshot->setImage(""); } } void GuiGameList::clearDetailData() { if(mDetailed) { mImageAnimation->fadeOut(35); } } //these are called when the menu opens/closes void GuiGameList::onPause() { mList->stopScrolling(); InputManager::unregisterComponent(this); } void GuiGameList::onResume() { updateDetailData(); InputManager::registerComponent(this); } //called when the renderer shuts down/returns //we have to manually call init/deinit on mTheme because it is not our child void GuiGameList::onDeinit() { mTheme->deinit(); } void GuiGameList::onInit() { mTheme->init(); } GuiGameList* GuiGameList::create() { bool detailed = false; return new GuiGameList(detailed); }
cde967920321b4a3d6f91cdf76d4b50a6147420e
b3a265e1e85b32036c152fb11ef0d9f3bb9a3bd3
/src/VMS.h
b6331e7000e28eb014a20dc024ad49d1c342ca7a
[ "MIT" ]
permissive
Hengle/NarvalEngine
066a03729dad7bbf5e186876a03ad422c7fe4e1d
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
refs/heads/master
2023-07-28T01:55:16.152883
2021-09-15T18:00:31
2021-09-15T18:00:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,163
h
VMS.h
#pragma once #include "core/Renderer.h" #include "core/Settings.h" #include "primitives/InstancedModel.h" #include "core/VolumeBSDF.h" #include "core/Camera.h" namespace narvalengine { //VMS = Volumetric Methods Shaders class VMS { public: //Others RendererContext *renderCtx; Scene* scene; float dummyVar[3] = {-1, -1, -1}; int currentMethod = LOBE_SAMPLING; static const int maxUniforms = 50; float avgMeanPath = 0; //Shader Commons glm::mat4 proj = glm::mat4(1); glm::mat4 cam = glm::mat4(1); glm::mat4 model = glm::mat4(1); glm::vec3 cameraPosition; glm::vec3 *scattering; glm::vec3 *absorption; float *density; float *g; float time = 0; int numberOfLights = 0; int volTexBind = 0; int bgTexBind = 1; int bgDepthTexBind = 2; UniformHandler lightUniforms[maxUniforms]; glm::vec3 lightPos[maxUniforms / 6]; glm::vec3 lightSize[maxUniforms / 6]; //MS_rayMarching shader parameters //rm = Ray Marching ProgramHandler rmProgram; UniformHandler rmUniforms[maxUniforms]; int rmNumberOfSteps = 60; int rmNumberOfShadowSteps = 10; //MS_lobeSampling shader parameters //ls = Lobe Sampling ProgramHandler lsProgram; UniformHandler lsUniforms[maxUniforms]; UniformHandler lsPointUniforms[maxUniforms]; float lsStepSize = 0.1; int lsNumberOfSteps = 50; int lsnPointsToSample = 30; int lsMeanPathMult = 20; glm::vec3 *lsPoints; bool lshasPointsBeenGenerated = false; //MS_monterCarlo shader parameters //mc = Monte Carlo ProgramHandler mcProgram; UniformHandler mcUniforms[maxUniforms]; int mcPreviousFrameTexBind = 3; int mcMaxBounces; int mcSPP; int mcFrameCount = 0; VMS(RendererContext *renderCtx, Scene *scene) { this->renderCtx = renderCtx; this->scene = scene; initCommons(); initMonteCarloShader(); initRayMarchingShader(); initLobeSamplingShader(); }; void handPickLobeSampling() { lshasPointsBeenGenerated = true; //sphere points lsPoints[0] = glm::normalize(glm::vec3(1,0,0)); lsPoints[1] = glm::normalize(glm::vec3(0,1,0)); lsPoints[2] = glm::normalize(glm::vec3(-1,0,0)); lsPoints[3] = glm::normalize(glm::vec3(0,-1,0)); lsPoints[4] = glm::normalize(glm::vec3(0,1,1)); lsPoints[5] = glm::normalize(glm::vec3(0,-1,1)); lsPoints[6] = glm::normalize(glm::vec3(0,1,-1)); lsPoints[7] = glm::normalize(glm::vec3(0,-1,-1)); lsPoints[8] = glm::normalize(glm::vec3(0,0,1)); lsPoints[9] = glm::normalize(glm::vec3(0,0,-1)); } void updateLights() { numberOfLights = scene->lights.size(); for (int i = 0; i < numberOfLights; i++) { int index = 6 * i; InstancedModel* imLight = scene->lights.at(i); lightPos[i] = getTranslation(imLight->transformToWCS); Rectangle* r; if (r = dynamic_cast<Rectangle*>(scene->lights.at(i)->model->materials.at(0)->light->primitive)) { //volLightType = 0; } else { /*Sphere* s = dynamic_cast<Sphere*>(scene.lights.at(i)->model->materials.at(0)->light->primitive); volLightType = 1; renderCtx.updateUniform(volUniforms[16], { (uint8_t*)&lightPos[0], sizeof(glm::vec3) }); volLightRecSize = glm::vec3(s->radius); continue;*/ continue; } lightSize[i] = r->getSize(); renderCtx->updateUniform(lightUniforms[index], { (uint8_t*)&lightPos[0], sizeof(glm::vec3) }); renderCtx->updateUniform(lightUniforms[index + 1], { (uint8_t*)&scene->lights.at(i)->model->materials.at(0)->light->li, sizeof(glm::vec3) }); renderCtx->updateUniform(lightUniforms[index + 2], { (uint8_t*)r->vertexData[0], sizeof(glm::vec3) }); renderCtx->updateUniform(lightUniforms[index + 3], { (uint8_t*)r->vertexData[1], sizeof(glm::vec3) }); renderCtx->updateUniform(lightUniforms[index + 4], { (uint8_t*)&lightSize[i], sizeof(glm::vec3) }); renderCtx->updateUniform(lightUniforms[index + 5], { (uint8_t*)&scene->lights.at(i)->transformToWCS, sizeof(glm::mat4) }); } } void initCommons() { numberOfLights = scene->lights.size(); for (int i = 0; i < numberOfLights; i++) { InstancedModel* imLight = scene->lights.at(i); lightPos[i] = getTranslation(imLight->transformToWCS); int index = 6 * i; //TODO missing minVertex, maxVertex and size std::string name = "lights[" + std::to_string(i) + "]"; lightUniforms[index] = renderCtx->createUniform(std::string(name + ".position").c_str(), { (uint8_t*)&lightPos[0], sizeof(glm::vec3) }, UniformType::Vec3, 0); lightUniforms[index + 1] = renderCtx->createUniform(std::string(name + ".Li").c_str(), { (uint8_t*)&scene->lights.at(i)->model->materials.at(0)->light->li, sizeof(glm::vec3) }, UniformType::Vec3, 0); lightUniforms[index + 2] = renderCtx->createUniform(std::string(name + ".minVertex").c_str(), { (uint8_t*)&dummyVar[0], sizeof(glm::vec3) }, UniformType::Vec3, 0); lightUniforms[index + 3] = renderCtx->createUniform(std::string(name + ".maxVertex").c_str(), { (uint8_t*)&dummyVar[0], sizeof(glm::vec3) }, UniformType::Vec3, 0); lightUniforms[index + 4] = renderCtx->createUniform(std::string(name + ".size").c_str(), { (uint8_t*)&dummyVar[0], sizeof(glm::vec3) }, UniformType::Vec3, 0); lightUniforms[index + 5] = renderCtx->createUniform(std::string(name + ".transformWCS").c_str(), { (uint8_t*)&scene->lights.at(i)->transformToWCS, sizeof(glm::mat4) }, UniformType::Mat4, 0); } } void initMonteCarloShader() { Shader* shader = ResourceManager::getSelf()->getShader("MS_monteCarlo"); ShaderHandler shvertex = renderCtx->createShader(shader->vertexShader, NE_SHADER_TYPE_VERTEX); ShaderHandler shfragment = renderCtx->createShader(shader->fragmentShader, NE_SHADER_TYPE_FRAGMENT); mcProgram = renderCtx->createProgram(shvertex, shfragment); mcUniforms[0] = renderCtx->createUniform("model", { (uint8_t*)&model[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); mcUniforms[1] = renderCtx->createUniform("invmodel", { (uint8_t*)&model[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); mcUniforms[2] = renderCtx->createUniform("cam", { (uint8_t*)&cam[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); mcUniforms[3] = renderCtx->createUniform("proj", { (uint8_t*)&proj[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); mcUniforms[4] = renderCtx->createUniform("cameraPosition", { (uint8_t*)&dummyVar[0], sizeof(glm::vec3) }, UniformType::Vec3, 0); mcUniforms[5] = renderCtx->createUniform("volume", { (uint8_t*)&volTexBind, sizeof(int) }, UniformType::Sampler, 0); mcUniforms[6] = renderCtx->createUniform("background", { (uint8_t*)&bgTexBind, sizeof(int) }, UniformType::Sampler, 0); mcUniforms[7] = renderCtx->createUniform("backgroundDepth", { (uint8_t*)&bgDepthTexBind, sizeof(int) }, UniformType::Sampler, 0); mcUniforms[8] = renderCtx->createUniform("scattering", { (uint8_t*)&dummyVar, sizeof(glm::vec3) }, UniformType::Vec3, 0); mcUniforms[9] = renderCtx->createUniform("absorption", { (uint8_t*)&dummyVar, sizeof(glm::vec3) }, UniformType::Vec3, 0); mcUniforms[10] = renderCtx->createUniform("densityCoef", { (uint8_t*)&dummyVar, sizeof(float) }, UniformType::Float, 0); mcUniforms[11] = renderCtx->createUniform("g", { (uint8_t*)dummyVar, sizeof(float) }, UniformType::Float, 0); mcUniforms[12] = renderCtx->createUniform("previousFrame", { (uint8_t*)&mcPreviousFrameTexBind, sizeof(float) }, UniformType::Sampler, 0); mcUniforms[13] = renderCtx->createUniform("invMaxDensity", { (uint8_t*)&dummyVar, sizeof(int) }, UniformType::Float, 0); mcUniforms[14] = renderCtx->createUniform("time", { (uint8_t*)&time, sizeof(float) }, UniformType::Float, 0); mcUniforms[15] = renderCtx->createUniform("maxBounces", { (uint8_t*)&mcMaxBounces, sizeof(int) }, UniformType::Int, 0); mcUniforms[16] = renderCtx->createUniform("SPP", { (uint8_t*)&mcSPP, sizeof(int) }, UniformType::Int, 0); mcUniforms[17] = renderCtx->createUniform("frameCount", { (uint8_t*)&mcFrameCount, sizeof(int) }, UniformType::Int, 0); } void initLobeSamplingShader() { Shader* shader = ResourceManager::getSelf()->getShader("MS_lobeSampling"); ShaderHandler shvertex = renderCtx->createShader(shader->vertexShader, NE_SHADER_TYPE_VERTEX); ShaderHandler shfragment = renderCtx->createShader(shader->fragmentShader, NE_SHADER_TYPE_FRAGMENT); lsProgram = renderCtx->createProgram(shvertex, shfragment); lsUniforms[0] = renderCtx->createUniform("model", { (uint8_t*)&model[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); lsUniforms[1] = renderCtx->createUniform("invmodel", { (uint8_t*)&model[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); lsUniforms[2] = renderCtx->createUniform("cam", { (uint8_t*)&cam[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); lsUniforms[3] = renderCtx->createUniform("proj", { (uint8_t*)&proj[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); lsUniforms[4] = renderCtx->createUniform("cameraPosition", { (uint8_t*)&dummyVar[0], sizeof(glm::vec3) }, UniformType::Vec3, 0); lsUniforms[5] = renderCtx->createUniform("volume", { (uint8_t*)&volTexBind, sizeof(int) }, UniformType::Sampler, 0); lsUniforms[6] = renderCtx->createUniform("background", { (uint8_t*)&bgTexBind, sizeof(int) }, UniformType::Sampler, 0); lsUniforms[7] = renderCtx->createUniform("backgroundDepth", { (uint8_t*)&bgDepthTexBind, sizeof(int) }, UniformType::Sampler, 0); lsUniforms[8] = renderCtx->createUniform("scattering", { (uint8_t*)&dummyVar, sizeof(glm::vec3) }, UniformType::Vec3, 0); lsUniforms[9] = renderCtx->createUniform("absorption", { (uint8_t*)&dummyVar, sizeof(glm::vec3) }, UniformType::Vec3, 0); lsUniforms[10] = renderCtx->createUniform("densityCoef", { (uint8_t*)&dummyVar, sizeof(float) }, UniformType::Float, 0); lsUniforms[11] = renderCtx->createUniform("g", { (uint8_t*)dummyVar, sizeof(float) }, UniformType::Float, 0); lsUniforms[12] = renderCtx->createUniform("time", { (uint8_t*)&time, sizeof(float) }, UniformType::Float, 0); lsUniforms[13] = renderCtx->createUniform("invMaxDensity", { (uint8_t*)&dummyVar, sizeof(float) }, UniformType::Float, 0); lsUniforms[14] = renderCtx->createUniform("stepSize", { (uint8_t*)&lsStepSize, sizeof(float) }, UniformType::Float, 0); lsUniforms[15] = renderCtx->createUniform("numberOfSteps", { (uint8_t*)&lsNumberOfSteps, sizeof(int) }, UniformType::Int, 0); lsUniforms[16] = renderCtx->createUniform("nPointsToSample", { (uint8_t*)&lsnPointsToSample, sizeof(int) }, UniformType::Int, 0); lsUniforms[17] = renderCtx->createUniform("meanPathMult", { (uint8_t*)&lsMeanPathMult, sizeof(int) }, UniformType::Int, 0); lsPoints = new glm::vec3[lsnPointsToSample]; for (int i = 0; i < lsnPointsToSample; i++) { std::string name = "lobePoints[" + std::to_string(i) + "]"; lsPointUniforms[i] = renderCtx->createUniform(name.c_str(), { (uint8_t*)&lsPoints[i], sizeof(glm::vec3) }, UniformType::Vec3, 0); } } void initRayMarchingShader() { Shader* shader = ResourceManager::getSelf()->getShader("MS_rayMarching"); ShaderHandler shvertex = renderCtx->createShader(shader->vertexShader, NE_SHADER_TYPE_VERTEX); ShaderHandler shfragment = renderCtx->createShader(shader->fragmentShader, NE_SHADER_TYPE_FRAGMENT); rmProgram = renderCtx->createProgram(shvertex, shfragment); rmUniforms[0] = renderCtx->createUniform("model", { (uint8_t*)&model[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); rmUniforms[1] = renderCtx->createUniform("invmodel", { (uint8_t*)&model[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); rmUniforms[2] = renderCtx->createUniform("cam", { (uint8_t*)&cam[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); rmUniforms[3] = renderCtx->createUniform("proj", { (uint8_t*)&proj[0][0], sizeof(glm::mat4) }, UniformType::Mat4, 0); rmUniforms[4] = renderCtx->createUniform("cameraPosition", { (uint8_t*)&dummyVar[0], sizeof(glm::vec3) }, UniformType::Vec3, 0); rmUniforms[5] = renderCtx->createUniform("volume", { (uint8_t*)&volTexBind, sizeof(int) }, UniformType::Sampler, 0); rmUniforms[6] = renderCtx->createUniform("background", { (uint8_t*)&bgTexBind, sizeof(int) }, UniformType::Sampler, 0); rmUniforms[7] = renderCtx->createUniform("backgroundDepth", { (uint8_t*)&bgDepthTexBind, sizeof(int) }, UniformType::Sampler, 0); rmUniforms[8] = renderCtx->createUniform("scattering", { (uint8_t*)&dummyVar, sizeof(glm::vec3) }, UniformType::Vec3, 0); rmUniforms[9] = renderCtx->createUniform("absorption", { (uint8_t*)&dummyVar, sizeof(glm::vec3) }, UniformType::Vec3, 0); rmUniforms[10] = renderCtx->createUniform("densityCoef", { (uint8_t*)&dummyVar, sizeof(float) }, UniformType::Float, 0); rmUniforms[11] = renderCtx->createUniform("numberOfSteps", { (uint8_t*)&rmNumberOfSteps, sizeof(int) }, UniformType::Int, 0); rmUniforms[12] = renderCtx->createUniform("numberOfShadowSteps", { (uint8_t*)&rmNumberOfShadowSteps, sizeof(int) }, UniformType::Int, 0); rmUniforms[13] = renderCtx->createUniform("g", { (uint8_t*)dummyVar, sizeof(float) }, UniformType::Float, 0); } void prepareMonteCarlo(Camera* camera, ModelHandler mh, InstancedModel* im, FrameBufferHandler fbh, TextureHandler previousFrame, TextureHandler background, TextureHandler backgroundDepth) { updateLights(); //TODO should be invoked only once a changed has been detected time = glfwGetTime(); for (int i = 0; i < maxUniforms; i++) { if (mcUniforms[i].id == INVALID_HANDLE) break; renderCtx->setUniform(mcUniforms[i]); } for (int i = 0; i < maxUniforms; i++) { if (lightUniforms[i].id == INVALID_HANDLE) break; renderCtx->setUniform(lightUniforms[i]); } if (isHandleValid(mh.meshes.at(0).material.textures[ctz(TextureName::TEX_1)].id)) renderCtx->setTexture(mh.meshes.at(0).material.textures[ctz(TextureName::TEX_1)], mcUniforms[5]); //volume Tex Medium* m = im->model->materials.at(0)->medium; GridMedia* gm = (GridMedia*)m; VolumeBSDF* volbsdf = (VolumeBSDF*)im->model->materials.at(0)->bsdf->bxdf[0]; HG* hg = (HG*)volbsdf->phaseFunction; g = &hg->g; scattering = &gm->scattering; //TODO divide by gm->densityMultiplier absorption = &gm->absorption; density = &gm->density; renderCtx->updateUniform(mcUniforms[8], { (uint8_t*)scattering, sizeof(glm::vec3) }); renderCtx->updateUniform(mcUniforms[9], { (uint8_t*)absorption, sizeof(glm::vec3) }); renderCtx->updateUniform(mcUniforms[10], { (uint8_t*)density, sizeof(float) }); renderCtx->updateUniform(mcUniforms[13], { (uint8_t*)&gm->invMaxDensity, sizeof(float) }); renderCtx->updateUniform(mcUniforms[11], { (uint8_t*)g, sizeof(float) }); renderCtx->setTexture(background, mcUniforms[6]); //background Tex renderCtx->setTexture(backgroundDepth, mcUniforms[7]); //backgroundDepth Tex renderCtx->setTexture(previousFrame, mcUniforms[12]); //previousFrame Tex renderCtx->updateUniform(mcUniforms[0], { (uint8_t*)(&im->transformToWCS[0][0]), sizeof(im->transformToWCS) }); //model renderCtx->updateUniform(mcUniforms[1], { (uint8_t*)&im->invTransformToWCS[0][0], sizeof(glm::mat4) }); //invmodel renderCtx->updateUniform(mcUniforms[4], { (uint8_t*)(camera->getPosition()), sizeof(glm::vec3) }); renderCtx->setModel(mh); renderCtx->setFrameBuffer(fbh); glDisable(GL_DEPTH_TEST); //TODO temporary, should not expose GL here plus it should be enabled only on volRederingMode = 1 (PATH TRACING MODE) renderCtx->render(mcProgram); glEnable(GL_DEPTH_TEST); } void prepareLobeSampling(Camera* camera, ModelHandler mh, InstancedModel* im, FrameBufferHandler fbh, TextureHandler background, TextureHandler backgroundDepth) { updateLights(); //TODO should be invoked only once a changed has been detected time = glfwGetTime(); for (int i = 0; i < maxUniforms; i++) { if (lsUniforms[i].id == INVALID_HANDLE) break; renderCtx->setUniform(lsUniforms[i]); } for (int i = 0; i < maxUniforms; i++) { if (lsPointUniforms[i].id == INVALID_HANDLE) break; renderCtx->setUniform(lsPointUniforms[i]); } for (int i = 0; i < maxUniforms; i++) { if (lightUniforms[i].id == INVALID_HANDLE) break; renderCtx->setUniform(lightUniforms[i]); } if (isHandleValid(mh.meshes.at(0).material.textures[ctz(TextureName::TEX_1)].id)) renderCtx->setTexture(mh.meshes.at(0).material.textures[ctz(TextureName::TEX_1)], lsUniforms[5]); //volume Tex Medium* m = im->model->materials.at(0)->medium; GridMedia* gm = (GridMedia*)m; VolumeBSDF* volbsdf = (VolumeBSDF*)im->model->materials.at(0)->bsdf->bxdf[0]; HG* hg = (HG*)volbsdf->phaseFunction; g = &hg->g; avgMeanPath = 1.0f / (avg(gm->extinction) * gm->density); if (InputManager::getSelf()->eventTriggered("TESTING_KEY")) lshasPointsBeenGenerated = false; if (!lshasPointsBeenGenerated) { lshasPointsBeenGenerated = true; for (int i = 0; i < lsnPointsToSample; i++) lsPoints[i] = hg->sample(glm::vec3(0, 0, 1)); //handPickLobeSampling(); } scattering = &gm->scattering; //TODO divide by gm->densityMultiplier absorption = &gm->absorption; density = &gm->density; renderCtx->updateUniform(lsUniforms[8], { (uint8_t*)scattering, sizeof(glm::vec3) }); renderCtx->updateUniform(lsUniforms[9], { (uint8_t*)absorption, sizeof(glm::vec3) }); renderCtx->updateUniform(lsUniforms[10], { (uint8_t*)density, sizeof(float) }); renderCtx->updateUniform(lsUniforms[13], { (uint8_t*)&gm->invMaxDensity, sizeof(float) }); renderCtx->updateUniform(lsUniforms[11], { (uint8_t*)g, sizeof(float) }); renderCtx->setTexture(background, lsUniforms[6]); //background Tex renderCtx->setTexture(backgroundDepth, lsUniforms[7]); //backgroundDepth Tex renderCtx->updateUniform(lsUniforms[0], { (uint8_t*)(&im->transformToWCS[0][0]), sizeof(im->transformToWCS) }); //model renderCtx->updateUniform(lsUniforms[1], { (uint8_t*)&im->invTransformToWCS[0][0], sizeof(glm::mat4) }); //invmodel renderCtx->updateUniform(lsUniforms[4], { (uint8_t*)(camera->getPosition()), sizeof(glm::vec3) }); renderCtx->setModel(mh); renderCtx->setFrameBuffer(fbh); glDisable(GL_DEPTH_TEST); //TODO temporary, should not expose GL here plus it should be enabled only on volRederingMode = 1 (PATH TRACING MODE) renderCtx->render(lsProgram); glEnable(GL_DEPTH_TEST); } void prepareRayMarching(Camera *camera, ModelHandler mh, InstancedModel *im, FrameBufferHandler fbh,TextureHandler background, TextureHandler backgroundDepth) { updateLights(); //TODO should be invoked only once a changed has been detected for (int i = 0; i < maxUniforms; i++) { if (rmUniforms[i].id == INVALID_HANDLE) break; renderCtx->setUniform(rmUniforms[i]); } for (int i = 0; i < maxUniforms; i++) { if (lightUniforms[i].id == INVALID_HANDLE) break; renderCtx->setUniform(lightUniforms[i]); } if (isHandleValid(mh.meshes.at(0).material.textures[ctz(TextureName::TEX_1)].id)) renderCtx->setTexture(mh.meshes.at(0).material.textures[ctz(TextureName::TEX_1)], rmUniforms[5]); //volume Tex Medium* m = im->model->materials.at(0)->medium; GridMedia* gm = (GridMedia*)m; VolumeBSDF* volbsdf = (VolumeBSDF*)im->model->materials.at(0)->bsdf->bxdf[0]; HG* hg = (HG*)volbsdf->phaseFunction; g = &hg->g; scattering = &gm->scattering; //TODO divide by gm->densityMultiplier absorption = &gm->absorption; density = &gm->density; renderCtx->updateUniform(rmUniforms[8], { (uint8_t*)scattering, sizeof(glm::vec3) }); renderCtx->updateUniform(rmUniforms[9], { (uint8_t*)absorption, sizeof(glm::vec3) }); renderCtx->updateUniform(rmUniforms[10], { (uint8_t*)density, sizeof(float) }); renderCtx->updateUniform(rmUniforms[13], { (uint8_t*)g, sizeof(float) }); renderCtx->setTexture(background, rmUniforms[6]); //background Tex renderCtx->setTexture(backgroundDepth, rmUniforms[7]); //backgroundDepth Tex renderCtx->updateUniform(rmUniforms[0], { (uint8_t*)(&im->transformToWCS[0][0]), sizeof(im->transformToWCS) }); //model renderCtx->updateUniform(rmUniforms[1], { (uint8_t*)&im->invTransformToWCS[0][0], sizeof(glm::mat4) }); //invmodel renderCtx->updateUniform(rmUniforms[4], { (uint8_t*)(camera->getPosition()), sizeof(glm::vec3) }); renderCtx->setModel(mh); renderCtx->setFrameBuffer(fbh); glDisable(GL_DEPTH_TEST); //TODO temporary, should not expose GL here plus it should be enabled only on volRederingMode = 1 (PATH TRACING MODE) renderCtx->render(rmProgram); glEnable(GL_DEPTH_TEST); } void prepare(Camera* camera, ModelHandler mh, InstancedModel* im, FrameBufferHandler fbh, int frameCount, TextureHandler previousFrame, TextureHandler background, TextureHandler backgroundDepth) { this->mcFrameCount = frameCount; if (currentMethod == RAY_MARCHING) prepareRayMarching(camera, mh, im, fbh, background, backgroundDepth); else if(currentMethod == LOBE_SAMPLING) prepareLobeSampling(camera, mh, im, fbh, background, backgroundDepth); else if(currentMethod == MONTE_CARLO) prepareMonteCarlo(camera, mh, im, fbh, previousFrame, background, backgroundDepth); } }; }
9e191294c65a657cd2f43eaf838b6085d7028196
97bb7da626def8ad206be815c64348778f550d38
/166.fraction_to_recurring_decimal/FractionToRecurringDecimal.cpp
17be476433af7af4aac8e7fef64f54eea032041c
[]
no_license
songkey7/leetcode
c242daafe33cc6035461fc2f3e751489d8b2551e
2f72c821bd0551313813c9b745ddf5207e1cb71c
refs/heads/master
2021-05-14T09:50:35.570822
2020-04-10T01:20:11
2020-04-10T01:20:11
116,336,985
0
0
null
null
null
null
UTF-8
C++
false
false
1,660
cpp
FractionToRecurringDecimal.cpp
// // Created by Qi Song on 05/04/2018. // #include "FractionToRecurringDecimal.h" string FractionToRecurringDecimal::fraction_to_decimal(int numerator, int denominator) { if(numerator == 0) return "0"; unordered_map<int, int> numerator_map; bool flag = (numerator < 0) ^ (denominator < 0); string ret = flag ? "-" : ""; long l_numerator = abs(long(numerator)); long l_denominator = abs(long(denominator)); ret += itoa(l_numerator / l_denominator); l_numerator = (l_numerator % l_denominator); if(l_numerator == 0) return ret; ret += "."; string tmp = ""; int i = 0; while(1){ l_numerator *= 10; if(numerator_map.find(l_numerator) != numerator_map.end()){ tmp.insert(numerator_map[l_numerator], "("); return ret + tmp + ")"; } numerator_map[l_numerator] = i++; tmp += itoa(l_numerator / l_denominator); l_numerator = (l_numerator % l_denominator); if(l_numerator == 0) return ret + tmp; } } string FractionToRecurringDecimal::itoa(long num) { if(num == 0) return "0"; string ret; while(num){ ret += (num % 10) + '0'; num /= 10; } reverse(ret.begin(), ret.end()); return ret; } void FractionToRecurringDecimal::run() { assert(fraction_to_decimal(1,99) == "0.(01)"); assert(fraction_to_decimal(1,90) == "0.0(1)"); assert(fraction_to_decimal(1,6) == "0.1(6)"); assert(fraction_to_decimal(-2147483648,-1) == "2147483648"); assert(fraction_to_decimal(1,2) == "0.5"); assert(fraction_to_decimal(2,1) == "2"); assert(fraction_to_decimal(2,3) == "0.(6)"); }
cb66b0862ee2c1d169753d455eb44168969e9e21
67427bcdc72211ff1d084c057879fe7468e0edb6
/testdirectory/haberlik_hwprog4/globals.cc
7379cb41eeb4da6cd090d7825f6f1e598fcfa290
[]
no_license
haberlinkate/Interpreter
300a47ee1ffa0ea3a2fb9099e124af2b6dcc712b
58296e953a06ee1c8dc785733f4aafa33d0fa9ea
refs/heads/master
2021-01-24T09:49:32.249608
2018-03-01T15:04:16
2018-03-01T15:04:16
123,027,985
0
0
null
null
null
null
UTF-8
C++
false
false
2,566
cc
globals.cc
#include "globals.h" /**************************************************************** * Code file for the 'Globals' class for global constants and * functions. * * Documentation for the functions is in the header for those * functions. * * Author/copyright: Duncan Buell * Used with permission and modified by: Katherine Haberlin * Date: 31 October 2017 * **/ /****************************************************************************** * Function 'BitStringToDec'. * Convert a bit string to a decimal value. * Source: cplusplus.com * * Parameters: * thebits - the binary string to convert * Returns: * stoivalue - the decimal equivalent **/ int Globals::BitStringToDec(const string thebits) const { #ifdef EBUG Utils::log_stream << "enter BitStringToDec\n"; #endif // Remember that the second parameter is for positioning the pointer // after doing the conversion (so we don't care here) and the third // says we are converting from a string of digits in binary. //The decimal value starts at zero. //If the bit is one, add the power of 2 corresponding to the position. int stoivalue = 0; int size = thebits.length(); for (int i = 0; i < size; ++i) { if (thebits.substr(i, 1) == "1") { stoivalue += pow(2, (size - 1 - i)); } } #ifdef EBUG Utils::log_stream << "leave BitStringToDec\n"; #endif return stoivalue; } /****************************************************************************** * Function 'DecToBitString'. * This function converts a decimal 'int' to a string of 0s and 1s. * * We only allow conversion to a string of length 12 or of length 16 * because we only allow an address (lessequal 4096 = 2^12) or a hex * operand of 16 bits. * * Parameters: * value - the value to convert * how_many_bits - the length of the result * Return: * bitsetvalue - the binary representation of the decimal value **/ string Globals::DecToBitString(const int value, const int how_many_bits) const { #ifdef EBUG Utils::log_stream << "enter DecToBitString\n"; #endif int decimal = value; string bitsetvalue = ""; vector<int> storage; //Conver to Binary for (int i = 0; i < how_many_bits; ++i) { if (decimal > 0) { int remainder = decimal % 2; decimal /= 2; storage.push_back(remainder); } else { storage.push_back(0); } } for (int i = storage.size() - 1; i >= 0; --i) { bitsetvalue += Utils::Format(storage.at(i)); } #ifdef EBUG Utils::log_stream << "leave DecToBitString\n"; #endif return bitsetvalue; }
d89024902f1806a7eac2c313ca1d42628d46d29b
afb7006e47e70c1deb2ddb205f06eaf67de3df72
/third_party/libwebrtc/video/end_to_end_tests/ssrc_tests.cc
268da84b7e0924f552c376b4fec18682eee25f7c
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
marco-c/gecko-dev-wordified
a66383f85db33911b6312dd094c36f88c55d2e2c
3509ec45ecc9e536d04a3f6a43a82ec09c08dff6
refs/heads/master
2023-08-10T16:37:56.660204
2023-08-01T00:39:54
2023-08-01T00:39:54
211,297,590
1
0
null
null
null
null
UTF-8
C++
false
false
10,280
cc
ssrc_tests.cc
/ * * Copyright 2018 The WebRTC 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 < memory > # include " api / test / simulated_network . h " # include " call / fake_network_pipe . h " # include " call / packet_receiver . h " # include " call / simulated_network . h " # include " modules / rtp_rtcp / source / rtp_packet . h " # include " modules / rtp_rtcp / source / rtp_packet_received . h " # include " modules / rtp_rtcp / source / rtp_util . h " # include " rtc_base / task_queue_for_test . h " # include " test / call_test . h " # include " test / gtest . h " # include " test / rtcp_packet_parser . h " namespace webrtc { class SsrcEndToEndTest : public test : : CallTest { public : SsrcEndToEndTest ( ) { RegisterRtpExtension ( RtpExtension ( RtpExtension : : kTransportSequenceNumberUri 1 ) ) ; } protected : void TestSendsSetSsrcs ( size_t num_ssrcs bool send_single_ssrc_first ) ; } ; TEST_F ( SsrcEndToEndTest ReceiverUsesLocalSsrc ) { class SyncRtcpObserver : public test : : EndToEndTest { public : SyncRtcpObserver ( ) : EndToEndTest ( kDefaultTimeout ) { } Action OnReceiveRtcp ( const uint8_t * packet size_t length ) override { test : : RtcpPacketParser parser ; EXPECT_TRUE ( parser . Parse ( packet length ) ) ; EXPECT_EQ ( kReceiverLocalVideoSsrc parser . sender_ssrc ( ) ) ; observation_complete_ . Set ( ) ; return SEND_PACKET ; } void PerformTest ( ) override { EXPECT_TRUE ( Wait ( ) ) < < " Timed out while waiting for a receiver RTCP packet to be sent . " ; } } test ; RunBaseTest ( & test ) ; } TEST_F ( SsrcEndToEndTest UnknownRtpPacketTriggersUndemuxablePacketHandler ) { class PacketInputObserver : public PacketReceiver { public : explicit PacketInputObserver ( PacketReceiver * receiver ) : receiver_ ( receiver ) { } bool Wait ( ) { return undemuxable_packet_handler_triggered_ . Wait ( kDefaultTimeout ) ; } private : void DeliverRtpPacket ( MediaType media_type RtpPacketReceived packet OnUndemuxablePacketHandler undemuxable_packet_handler ) override { PacketReceiver : : OnUndemuxablePacketHandler handler = [ this ] ( const RtpPacketReceived & packet ) { undemuxable_packet_handler_triggered_ . Set ( ) ; / / No need to re - attempt deliver the packet . return false ; } ; receiver_ - > DeliverRtpPacket ( media_type std : : move ( packet ) std : : move ( handler ) ) ; } void DeliverRtcpPacket ( rtc : : CopyOnWriteBuffer packet ) override { } PacketReceiver * receiver_ ; rtc : : Event undemuxable_packet_handler_triggered_ ; } ; std : : unique_ptr < test : : DirectTransport > send_transport ; std : : unique_ptr < test : : DirectTransport > receive_transport ; std : : unique_ptr < PacketInputObserver > input_observer ; SendTask ( task_queue ( ) [ this & send_transport & receive_transport & input_observer ] ( ) { CreateCalls ( ) ; send_transport = std : : make_unique < test : : DirectTransport > ( task_queue ( ) std : : make_unique < FakeNetworkPipe > ( Clock : : GetRealTimeClock ( ) std : : make_unique < SimulatedNetwork > ( BuiltInNetworkBehaviorConfig ( ) ) ) sender_call_ . get ( ) payload_type_map_ GetRegisteredExtensions ( ) GetRegisteredExtensions ( ) ) ; receive_transport = std : : make_unique < test : : DirectTransport > ( task_queue ( ) std : : make_unique < FakeNetworkPipe > ( Clock : : GetRealTimeClock ( ) std : : make_unique < SimulatedNetwork > ( BuiltInNetworkBehaviorConfig ( ) ) ) receiver_call_ . get ( ) payload_type_map_ GetRegisteredExtensions ( ) GetRegisteredExtensions ( ) ) ; input_observer = std : : make_unique < PacketInputObserver > ( receiver_call_ - > Receiver ( ) ) ; send_transport - > SetReceiver ( input_observer . get ( ) ) ; receive_transport - > SetReceiver ( sender_call_ - > Receiver ( ) ) ; CreateSendConfig ( 1 0 0 send_transport . get ( ) ) ; CreateMatchingReceiveConfigs ( receive_transport . get ( ) ) ; CreateVideoStreams ( ) ; CreateFrameGeneratorCapturer ( kDefaultFramerate kDefaultWidth kDefaultHeight ) ; Start ( ) ; receiver_call_ - > DestroyVideoReceiveStream ( video_receive_streams_ [ 0 ] ) ; video_receive_streams_ . clear ( ) ; } ) ; / / Wait ( ) waits for a received packet . EXPECT_TRUE ( input_observer - > Wait ( ) ) ; SendTask ( task_queue ( ) [ this & send_transport & receive_transport ] ( ) { Stop ( ) ; DestroyStreams ( ) ; send_transport . reset ( ) ; receive_transport . reset ( ) ; DestroyCalls ( ) ; } ) ; } void SsrcEndToEndTest : : TestSendsSetSsrcs ( size_t num_ssrcs bool send_single_ssrc_first ) { class SendsSetSsrcs : public test : : EndToEndTest { public : SendsSetSsrcs ( const uint32_t * ssrcs size_t num_ssrcs bool send_single_ssrc_first TaskQueueBase * task_queue ) : EndToEndTest ( kDefaultTimeout ) num_ssrcs_ ( num_ssrcs ) send_single_ssrc_first_ ( send_single_ssrc_first ) ssrcs_to_observe_ ( num_ssrcs ) expect_single_ssrc_ ( send_single_ssrc_first ) send_stream_ ( nullptr ) task_queue_ ( task_queue ) { for ( size_t i = 0 ; i < num_ssrcs ; + + i ) valid_ssrcs_ [ ssrcs [ i ] ] = true ; } private : Action OnSendRtp ( const uint8_t * packet size_t length ) override { RtpPacket rtp_packet ; EXPECT_TRUE ( rtp_packet . Parse ( packet length ) ) ; EXPECT_TRUE ( valid_ssrcs_ [ rtp_packet . Ssrc ( ) ] ) < < " Received unknown SSRC : " < < rtp_packet . Ssrc ( ) ; if ( ! valid_ssrcs_ [ rtp_packet . Ssrc ( ) ] ) observation_complete_ . Set ( ) ; if ( ! is_observed_ [ rtp_packet . Ssrc ( ) ] ) { is_observed_ [ rtp_packet . Ssrc ( ) ] = true ; - - ssrcs_to_observe_ ; if ( expect_single_ssrc_ ) { expect_single_ssrc_ = false ; observation_complete_ . Set ( ) ; } } if ( ssrcs_to_observe_ = = 0 ) observation_complete_ . Set ( ) ; return SEND_PACKET ; } size_t GetNumVideoStreams ( ) const override { return num_ssrcs_ ; } void ModifyVideoConfigs ( VideoSendStream : : Config * send_config std : : vector < VideoReceiveStreamInterface : : Config > * receive_configs VideoEncoderConfig * encoder_config ) override { / / Set low simulcast bitrates to not have to wait for bandwidth ramp - up . encoder_config - > max_bitrate_bps = 50000 ; for ( auto & layer : encoder_config - > simulcast_layers ) { layer . min_bitrate_bps = 10000 ; layer . target_bitrate_bps = 15000 ; layer . max_bitrate_bps = 20000 ; } video_encoder_config_all_streams_ = encoder_config - > Copy ( ) ; if ( send_single_ssrc_first_ ) encoder_config - > number_of_streams = 1 ; } void OnVideoStreamsCreated ( VideoSendStream * send_stream const std : : vector < VideoReceiveStreamInterface * > & receive_streams ) override { send_stream_ = send_stream ; } void PerformTest ( ) override { EXPECT_TRUE ( Wait ( ) ) < < " Timed out while waiting for " < < ( send_single_ssrc_first_ ? " first SSRC . " : " SSRCs . " ) ; if ( send_single_ssrc_first_ ) { / / Set full simulcast and continue with the rest of the SSRCs . SendTask ( task_queue_ [ & ] ( ) { send_stream_ - > ReconfigureVideoEncoder ( std : : move ( video_encoder_config_all_streams_ ) ) ; } ) ; EXPECT_TRUE ( Wait ( ) ) < < " Timed out while waiting on additional SSRCs . " ; } } private : std : : map < uint32_t bool > valid_ssrcs_ ; std : : map < uint32_t bool > is_observed_ ; const size_t num_ssrcs_ ; const bool send_single_ssrc_first_ ; size_t ssrcs_to_observe_ ; bool expect_single_ssrc_ ; VideoSendStream * send_stream_ ; VideoEncoderConfig video_encoder_config_all_streams_ ; TaskQueueBase * task_queue_ ; } test ( kVideoSendSsrcs num_ssrcs send_single_ssrc_first task_queue ( ) ) ; RunBaseTest ( & test ) ; } TEST_F ( SsrcEndToEndTest SendsSetSsrc ) { TestSendsSetSsrcs ( 1 false ) ; } TEST_F ( SsrcEndToEndTest SendsSetSimulcastSsrcs ) { TestSendsSetSsrcs ( kNumSimulcastStreams false ) ; } TEST_F ( SsrcEndToEndTest CanSwitchToUseAllSsrcs ) { TestSendsSetSsrcs ( kNumSimulcastStreams true ) ; } TEST_F ( SsrcEndToEndTest DISABLED_RedundantPayloadsTransmittedOnAllSsrcs ) { class ObserveRedundantPayloads : public test : : EndToEndTest { public : ObserveRedundantPayloads ( ) : EndToEndTest ( kDefaultTimeout ) ssrcs_to_observe_ ( kNumSimulcastStreams ) { for ( size_t i = 0 ; i < kNumSimulcastStreams ; + + i ) { registered_rtx_ssrc_ [ kSendRtxSsrcs [ i ] ] = true ; } } private : Action OnSendRtp ( const uint8_t * packet size_t length ) override { RtpPacket rtp_packet ; EXPECT_TRUE ( rtp_packet . Parse ( packet length ) ) ; if ( ! registered_rtx_ssrc_ [ rtp_packet . Ssrc ( ) ] ) return SEND_PACKET ; const bool packet_is_redundant_payload = rtp_packet . payload_size ( ) > 0 ; if ( ! packet_is_redundant_payload ) return SEND_PACKET ; if ( ! observed_redundant_retransmission_ [ rtp_packet . Ssrc ( ) ] ) { observed_redundant_retransmission_ [ rtp_packet . Ssrc ( ) ] = true ; if ( - - ssrcs_to_observe_ = = 0 ) observation_complete_ . Set ( ) ; } return SEND_PACKET ; } size_t GetNumVideoStreams ( ) const override { return kNumSimulcastStreams ; } void ModifyVideoConfigs ( VideoSendStream : : Config * send_config std : : vector < VideoReceiveStreamInterface : : Config > * receive_configs VideoEncoderConfig * encoder_config ) override { / / Set low simulcast bitrates to not have to wait for bandwidth ramp - up . encoder_config - > max_bitrate_bps = 50000 ; for ( auto & layer : encoder_config - > simulcast_layers ) { layer . min_bitrate_bps = 10000 ; layer . target_bitrate_bps = 15000 ; layer . max_bitrate_bps = 20000 ; } send_config - > rtp . rtx . payload_type = kSendRtxPayloadType ; for ( size_t i = 0 ; i < kNumSimulcastStreams ; + + i ) send_config - > rtp . rtx . ssrcs . push_back ( kSendRtxSsrcs [ i ] ) ; / / Significantly higher than max bitrates for all video streams - > forcing / / padding to trigger redundant padding on all RTX SSRCs . encoder_config - > min_transmit_bitrate_bps = 100000 ; } void PerformTest ( ) override { EXPECT_TRUE ( Wait ( ) ) < < " Timed out while waiting for redundant payloads on all SSRCs . " ; } private : size_t ssrcs_to_observe_ ; std : : map < uint32_t bool > observed_redundant_retransmission_ ; std : : map < uint32_t bool > registered_rtx_ssrc_ ; } test ; RunBaseTest ( & test ) ; } } / / namespace webrtc
a1b639cd4533ed26c2526f671e28e23c37a73064
416108a9e20635b36f8e82de4ea3aaed00d9a3e7
/leetcode/0001 - Two Sum.cpp
d6cfa609545146ec0e52a853ea7ba5ad0f267934
[]
no_license
annoviko/sandbox
b2cfb11ce24bb477a188e1cc5f71a92835ff1b91
bc9d89f4b37984ffa052a252639e6535fb88a308
refs/heads/master
2023-08-30T23:43:12.940520
2023-08-19T11:20:10
2023-08-19T11:20:10
72,368,789
6
0
null
null
null
null
UTF-8
C++
false
false
546
cpp
0001 - Two Sum.cpp
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::unordered_map<int, std::size_t> addition; for (std::size_t i = 0; i < nums.size() - 1; i++) { int difference = target - nums[i]; auto iter_addition = addition.find(difference); if (iter_addition != addition.end() && iter_addition->second != i) { return { i, iter_addition->second }; } addition[nums[i]] = i; } } };
16a17130434a33877c43ac23515e8fa80e5ce470
e8b55a9afe3118fa0e84dc061582d698c686632d
/mainwindow.h
bec868cc215f6028b75a8ce77f3d45cbd7773662
[]
no_license
SamVadidar/QT_CCOR_NORMAL
152403f905bd0bd2d44f4e68c3411e5dacac6788
a04d0b17015999a57dfb5b256c2acb47823be270
refs/heads/master
2020-04-15T13:03:30.310481
2019-01-17T09:05:28
2019-01-17T09:05:28
164,699,968
0
0
null
null
null
null
UTF-8
C++
false
false
1,564
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #include <opencv2/imgcodecs.hpp> #include <QTimer> #include <iostream> #include <opencv2/face.hpp> #define COLOR cv::Scalar(255, 255, 255) namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_RUN_clicked(); private: Ui::MainWindow *ui; QTimer *timer; QImage qt_optic; QImage qt_IR; cv::Mat IR; cv::Mat optic; cv::Mat optic_grad_x, optic_grad_y; cv::Mat optic_abs_grad_x, optic_abs_grad_y; cv::Mat optic_grad; cv::Mat IR_grad_x, IR_grad_y; cv::Mat IR_abs_grad_x, IR_abs_grad_y; cv::Mat IR_grad; int xOffSet = 45; int yOffSet = 73; float scale_factor; float i; cv::Mat temp; int IR_rows, IR_cols; cv::Mat result; int result_rows, result_cols; double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc; double matchVal=0; cv::Point matchLoc; //Mat frame; cv::Ptr<cv::face::Facemark> facemark; bool success; std::vector<cv::Rect> faces; //cv::CascadeClassifier faceDetector; std::vector< std::vector<cv::Point2f> > landmarks; cv::CascadeClassifier *faceDetector; void drawLandmarks(cv::Mat &im, std::vector<cv::Point2f> &landmarks); float x_optic_nose, y_optic_nose; int x_IR_nose, y_IR_nose; }; #endif // MAINWINDOW_H
bdc3394ed75dbf291f1d835347808c47a7de7492
a0604bbb76abbb42cf83e99f673134c80397b92b
/fldserver/base/containers/checked_range.h
1f7abd1afe369f855ab7dddaa02a2bb9a09f147a
[ "BSD-3-Clause" ]
permissive
Hussam-Turjman/FLDServer
816910da39b6780cfd540fa1e79c84a03c57a488
ccc6e98d105cfffbf44bfd0a49ee5dcaf47e9ddb
refs/heads/master
2022-07-29T20:59:28.954301
2022-07-03T12:02:42
2022-07-03T12:02:42
461,034,667
2
0
null
null
null
null
UTF-8
C++
false
false
7,236
h
checked_range.h
// Copyright 2019 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. #ifndef BASE_CONTAINERS_CHECKED_RANGE_H_ #define BASE_CONTAINERS_CHECKED_RANGE_H_ #include "fldserver/base/containers/checked_iterators.h" #include "fldserver/base/stl_util.h" #include "fldserver/base/template_util.h" #include <stddef.h> #include <iterator> #include <type_traits> namespace base { // CheckedContiguousRange is a light-weight wrapper around a container modeling // the ContiguousContainer requirement [1, 2]. Effectively this means that the // container stores its elements contiguous in memory. Furthermore, it is // expected that base::data(container) and base::size(container) are valid // expressions, and that data() + idx is dereferenceable for all idx in the // range [0, size()). In the standard library this includes the containers // std::string, std::vector and std::array, but other containers like // std::initializer_list and C arrays are supported as well. // // In general this class is in nature quite similar to base::span, and its API // is inspired by it. Similarly to base::span (and other view-like containers // such as base::StringPiece) callers are encouraged to pass checked ranges by // value. // // However, one important difference is that this class stores a pointer to the // underlying container (as opposed to just storing its data() and size()), and // thus is able to deal with changes to the container, such as removing or // adding elements. // // Note however that this class still does not extend the life-time of the // underlying container, and thus callers need to make sure that the container // outlives the view to avoid dangling pointers and references. // // Lastly, this class leverages base::CheckedContiguousIterator to perform // bounds CHECKs, causing program termination when e.g. dereferencing the end // iterator. // // [1] https://en.cppreference.com/w/cpp/named_req/ContiguousContainer // [2] // https://eel.is/c++draft/container.requirements.general#def:contiguous_container template <typename ContiguousContainer> class CheckedContiguousRange { public: using element_type = std::remove_pointer_t<decltype(base::data(std::declval<ContiguousContainer&>()))>; using value_type = std::remove_cv_t<element_type>; using reference = element_type&; using const_reference = const element_type&; using pointer = element_type*; using const_pointer = const element_type*; using iterator = CheckedContiguousIterator<element_type>; using const_iterator = CheckedContiguousConstIterator<element_type>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using difference_type = typename iterator::difference_type; using size_type = size_t; static_assert(!std::is_reference<ContiguousContainer>::value, "Error: ContiguousContainer can not be a reference."); // Required for converting constructor below. template <typename Container> friend class CheckedContiguousRange; // Default constructor. Behaves as if the underlying container was empty. constexpr CheckedContiguousRange() noexcept = default; // Templated constructor restricted to possibly cvref qualified versions of // ContiguousContainer. This makes sure it does not shadow the auto generated // copy and move constructors. template <int&... ExplicitArgumentBarrier, typename Container, typename = std::enable_if_t<std::is_same<remove_cvref_t<ContiguousContainer>, remove_cvref_t<Container>>::value>> constexpr CheckedContiguousRange(Container&& container) noexcept : container_(&container) { } // Converting constructor allowing conversions like CCR<C> to CCR<const C>, // but disallowing CCR<const C> to CCR<C> or CCR<Derived[]> to CCR<Base[]>, // which are unsafe. Furthermore, this is the same condition as used by the // converting constructors of std::span<T> and std::unique_ptr<T[]>. // See https://wg21.link/n4042 for details. template <int&... ExplicitArgumentBarrier, typename Container, typename = std::enable_if_t<std::is_convertible< typename CheckedContiguousRange<Container>::element_type (*)[], element_type (*)[]>::value>> constexpr CheckedContiguousRange(CheckedContiguousRange<Container> range) noexcept : container_(range.container_) { } constexpr iterator begin() const noexcept { return iterator(data(), data(), data() + size()); } constexpr iterator end() const noexcept { return iterator(data(), data() + size(), data() + size()); } constexpr const_iterator cbegin() const noexcept { return begin(); } constexpr const_iterator cend() const noexcept { return end(); } constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator(end()); } constexpr reverse_iterator rend() const noexcept { return reverse_iterator(begin()); } constexpr const_reverse_iterator crbegin() const noexcept { return rbegin(); } constexpr const_reverse_iterator crend() const noexcept { return rend(); } constexpr reference front() const noexcept { return *begin(); } constexpr reference back() const noexcept { return *(end() - 1); } constexpr reference operator[](size_type idx) const noexcept { return *(begin() + idx); } constexpr pointer data() const noexcept { return container_ ? base::data(*container_) : nullptr; } constexpr const_pointer cdata() const noexcept { return data(); } constexpr size_type size() const noexcept { return container_ ? base::size(*container_) : 0; } constexpr bool empty() const noexcept { return container_ ? base::empty(*container_) : true; } private: ContiguousContainer* container_ = nullptr; }; // Utility functions helping to create const ranges and performing automatic // type deduction. template <typename ContiguousContainer> using CheckedContiguousConstRange = CheckedContiguousRange<const ContiguousContainer>; template <int&... ExplicitArgumentBarrier, typename ContiguousContainer> constexpr auto MakeCheckedContiguousRange(ContiguousContainer&& container) noexcept { return CheckedContiguousRange<std::remove_reference_t<ContiguousContainer>>( std::forward<ContiguousContainer>(container)); } template <int&... ExplicitArgumentBarrier, typename ContiguousContainer> constexpr auto MakeCheckedContiguousConstRange(ContiguousContainer&& container) noexcept { return CheckedContiguousConstRange<std::remove_reference_t<ContiguousContainer>>( std::forward<ContiguousContainer>(container)); } } // namespace base #endif // BASE_CONTAINERS_CHECKED_RANGE_H_
ced28b3351b676218c35521a3913306baf3f65ea
b1544145744f9443a609d219a25ec58b5ad9898a
/Sims/graphics/hw/vertex_array.cpp
8b8736b053419b1387dd61b47d42ea537e1a8b26
[]
no_license
mi2think/Sims
082ddb2b2f3f14ca7917e846c8bcfb237c3b8bca
38670724c2bea6723b13949537f0108a384435ea
refs/heads/master
2021-01-11T19:35:26.705960
2020-11-22T15:26:09
2020-11-22T15:26:09
66,848,431
0
0
null
null
null
null
UTF-8
C++
false
false
848
cpp
vertex_array.cpp
/******************************************************************** created: 2018/01/08 created: 8:1:2018 11:28 filename: D:\Code\Sims\Sims\graphics\hw\vertex_array.cpp file path: D:\Code\Sims\Sims\graphics\hw file base: vertex_array file ext: cpp author: mi2think@gmail.com purpose: Vertex Array *********************************************************************/ #include "vertex_array.h" #include "graphics_api/sims_sdk_hw.h" namespace sims { VertexArray::VertexArray(const VertexDeclarationRef& vertexDecl, const IndexBufferRef& indexBuffer, const vector<VertexBufferRef>& vertexBuffers) : vertexDecl_(vertexDecl) { indexBuffer_ = indexBuffer; vertexBuffers_ = vertexBuffers; } void VertexArray::Create() { if (HWResource_) { Release(); } HWResource_ = hw::CreateResource<VertexArrayResource>(); } }
032d556da1825febff50e73faecdfefb7f1d2853
3a5a2affe19853dd5089dc51e35cc974a80eb052
/Project4/main.cpp
7d3e2c3c0889545ce189b966d07f9f725430c2b6
[]
no_license
LiYingwei/CGpj
35c1a6393b5a795fdde40dc063cb62fabf495f36
6a7b6e626ded536d4a07ce519c284b234ee922f0
refs/heads/master
2021-08-31T11:23:41.323485
2017-12-20T07:31:15
2017-12-20T07:31:15
114,448,959
0
0
null
null
null
null
UTF-8
C++
false
false
6,413
cpp
main.cpp
#ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include <vector> std::vector<std::pair<int,int>> mouseList; int window_width = 320; int window_height = 320; typedef unsigned long DWORD; typedef unsigned short WORD; typedef unsigned char BYTE; #define EDGE_TABLE_SIZE 1025 #define RGB(r,g,b) ((DWORD)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) typedef struct _Edge { double dbX; double dbDelta; int inMaxY; _Edge* ptrNext; }Edge; Edge* g_ptrEdgeTable[EDGE_TABLE_SIZE]; Edge* g_ptrAELHead; int g_inMinY = 0x7fffffff; int g_inMaxY = -0x7fffffff; typedef struct { int x; int y; }Vector; #define GetMin(x,y) ((x)>(y)?(y):(x)) #define GetMax(x,y) ((x)>(y)?(x):(y)) void allocEdges() { int i; for (i = 0; i<EDGE_TABLE_SIZE; i++) { g_ptrEdgeTable[i] = new Edge; g_ptrEdgeTable[i]->ptrNext = NULL; } g_ptrAELHead = new Edge; g_ptrAELHead->ptrNext = NULL; } void deallocEdges() { delete g_ptrAELHead; g_ptrAELHead = NULL; int i; for (i = 0; i<EDGE_TABLE_SIZE; i++) { delete g_ptrEdgeTable[i]; g_ptrEdgeTable[i] = NULL; } } #define eps 0.00001 int ceilPixel(double xLeft) { return (int)(xLeft + 1.0 - eps); } int floorPixel(double xRight) { return (int)(xRight - eps); } void setPixel(int x, int y, DWORD color) { glBegin(GL_POINTS); glVertex2i(x, y); glEnd(); } void insertEdgeList(Edge* ptrHead, Edge* ptrEdge) { Edge* current = ptrHead, *next = ptrHead->ptrNext; while (next && next->dbX > ptrEdge->dbX) { current = next; next = current->ptrNext; } current->ptrNext = ptrEdge; ptrEdge->ptrNext = next; } void insertAEL(Edge* ptrHeadList, Edge* ptrInsertList) { if (!ptrInsertList->ptrNext) return; Edge* curInsert = ptrInsertList->ptrNext, *nextInsert = NULL; Edge* current = ptrHeadList, *next = current->ptrNext; while (curInsert != NULL) { nextInsert = curInsert->ptrNext; while (next && next->dbX < curInsert->dbX) { current = next; next = current->ptrNext; } current->ptrNext = curInsert; curInsert->ptrNext = next; next = curInsert; curInsert = nextInsert; } } void initEdgeTable(Vector* ptrPolygon, int inNumPoly) { int current = inNumPoly - 1, next = 0; Edge* edge = NULL; for (; next<inNumPoly; current = next, next++) { if (ptrPolygon[current].y == ptrPolygon[next].y) continue; int minY, maxY, x; if (ptrPolygon[current].y > ptrPolygon[next].y) { maxY = ptrPolygon[current].y; minY = ptrPolygon[next].y; x = ptrPolygon[next].x; } else { maxY = ptrPolygon[next].y; minY = ptrPolygon[current].y; x = ptrPolygon[current].x; } if (minY<g_inMinY) g_inMinY = minY; if (maxY>g_inMaxY) g_inMaxY = maxY; edge = new Edge; edge->ptrNext = NULL; edge->dbX = x; edge->inMaxY = maxY; edge->dbDelta = (double)(ptrPolygon[current].x - ptrPolygon[next].x) / (double)(ptrPolygon[current].y - ptrPolygon[next].y); insertEdgeList(g_ptrEdgeTable[minY], edge); } } void updateAEL(Edge* ptrHead, int inCurrentY) { Edge* remove = NULL; Edge* current = ptrHead, *next = ptrHead->ptrNext; while (next) { if (next->inMaxY <= inCurrentY) { remove = next; next = next->ptrNext; current->ptrNext = next; delete remove; } else { current = next; current->dbX += current->dbDelta; next = current->ptrNext; } } } void fillAELScanLine(Edge* ptrHead, int inY, DWORD inColor) { Edge* current = NULL, *next = ptrHead->ptrNext; do { current = next; next = current->ptrNext; int x = ceilPixel(current->dbX); int endX = floorPixel(next->dbX); for (; x <= endX; x++) setPixel(x, inY, inColor); current = next; next = current->ptrNext; } while (next); } void scanLineFill(Vector* ptrPolygon, int inNumPoly, DWORD inColor) { allocEdges(); initEdgeTable(ptrPolygon, inNumPoly); for (int y = g_inMinY; y<g_inMaxY; y++) { insertAEL(g_ptrAELHead, g_ptrEdgeTable[y]); fillAELScanLine(g_ptrAELHead, y, inColor); updateAEL(g_ptrAELHead, y + 1); } deallocEdges(); } void renderScene(void) { bool fill_flag = false; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, window_width, window_height, 0); /*if (mouseList.size() > 1) { int x0 = mouseList[mouseList.size() - 2].first; int y0 = mouseList[mouseList.size() - 2].second; glBegin(GL_LINES); glVertex2f(100, 100); glVertex2f(100, 200); glEnd(); }*/ for (int i = 1; i < mouseList.size(); i++) { std::pair<int, int> pos1 = mouseList[i - 1]; printf("(%d,%d)\n", pos1.first, pos1.second); std::pair<int, int> pos2 = mouseList[i]; glBegin(GL_LINES); glVertex2f(pos1.first, pos1.second); glVertex2f(pos2.first, pos2.second); glEnd(); if (pos1.first == pos2.first && pos1.second == pos2.second) { std::pair<int, int> pos0 = mouseList[0]; glBegin(GL_LINES); glVertex2f(pos1.first, pos1.second); glVertex2f(pos0.first, pos0.second); glEnd(); fill_flag = true; break; } } if (fill_flag) { static Vector polygon[1000]; int n = mouseList.size(); for (int i = 0; i < n - 1; i++) { polygon[i].x = mouseList[i].first; polygon[i].y = mouseList[i].second; } polygon[n - 1].x = mouseList[0].first; polygon[n - 1].y = mouseList[0].second; scanLineFill(polygon, n, RGB(255, 0, 0)); } //glPointSize(5.0f); glBegin(GL_POINTS); for (int i = 0; i < mouseList.size(); i++) { std::pair<int, int> pos = mouseList[i]; glVertex2i(pos.first, pos.second); } glEnd(); glutSwapBuffers(); } void detectMouse(int button, int state, int x, int y) { if (state != 1) return; if (button == GLUT_LEFT_BUTTON) { mouseList.push_back(std::make_pair(x, y)); } else if (button == GLUT_RIGHT_BUTTON) { mouseList.clear(); } glutPostRedisplay(); } void Resize(int width, int height) { window_width = width; window_height = height; glViewport(0, 0, (GLsizei)window_width, (GLsizei)window_height); glutPostRedisplay(); } int main(int argc, char **argv) { // init GLUT and create Window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100,100); glutInitWindowSize(window_width,window_height); glutCreateWindow("Lighthouse3D - GLUT Tutorial"); // register callbacks glutDisplayFunc(renderScene); glutMouseFunc(detectMouse); glutReshapeFunc(Resize); // enter GLUT event processing cycle glutMainLoop(); return 1; }
ae2766c1bc9e96ce870fb2fe3e493593a873042c
dbcae238751b9a1e906b6418b58ebe315aa27149
/programmer_view/floating_point/src/activations.cc
63ba94371a2f5acc8f4e6c589c851d64ea2806db
[]
no_license
WenqiJiang/Real-Time-FPGA-Accelerator-for-Robotic-Snakes
aca4252771a021ee63377e73bdeb40ab1d7a7afa
5ed1f0f307a10b61786a41e27e1eab809d89a7f7
refs/heads/master
2020-06-08T18:01:35.482203
2019-07-24T19:19:14
2019-07-24T19:19:14
193,278,035
0
0
null
null
null
null
UTF-8
C++
false
false
2,335
cc
activations.cc
#include "activations.h" #include <cmath> #include "constants.h" #include "types.h" template <const int lstm_state_size> void relu(FDATA_T* input_feature_map, FDATA_T* output_feature_map) { // for fixed length array (LSTM_SIZE), input and output can be the SAME array for (LDATA_T result_idx = 0; result_idx < lstm_state_size; result_idx++) { output_feature_map[result_idx] = input_feature_map[result_idx] > 0? input_feature_map[result_idx] : 0; } } template <const int lstm_state_size> void tanh(FDATA_T* input_feature_map, FDATA_T* output_feature_map) { // for fixed length array (LSTM_SIZE), input and output can be the SAME array for (LDATA_T result_idx = 0; result_idx < lstm_state_size; result_idx++) { output_feature_map[result_idx] = tanh(input_feature_map[result_idx]); } } template <const int lstm_state_size> void sigmoid(FDATA_T* input_feature_map, FDATA_T* output_feature_map) { // for fixed length array (LSTM_SIZE), input and output can be the SAME array for (LDATA_T result_idx = 0; result_idx < lstm_state_size; result_idx++) { output_feature_map[result_idx] = 1 / (1 + exp(-input_feature_map[result_idx])); } } template <> void softmax (FDATA_T* input_feature_map, FDATA_T* output_probability_distribution) { // for fixed length array (FC_OUTPUT_SIZE) // compute denominator FDATA_T denominator = 0; for (LDATA_T i = 0; i < FC_OUTPUT_SIZE; i++) { denominator += exp(input_feature_map[i]); } // compute probability distribution for (LDATA_T result_idx = 0; result_idx < FC_OUTPUT_SIZE; result_idx++) { output_probability_distribution[result_idx] = exp(input_feature_map[result_idx]) / denominator; } } template <> IDATA_T argmax(FDATA_T* input_array) { // for fixed length array (FC_OUTPUT_SIZE) // initialization IDATA_T max_idx = 0; FDATA_T max_val = input_array[0]; // find max for (LDATA_T i = 0; i < FC_OUTPUT_SIZE; i++) { if (input_array[i] > max_val) { max_val = input_array[i]; max_idx = i; } } return max_idx; } // instantiation template void tanh<LSTM_STATE_SIZE_1>( FDATA_T* input_feature_map, FDATA_T* output_feature_map); template void sigmoid<LSTM_STATE_SIZE_1>( FDATA_T* input_feature_map, FDATA_T* output_feature_map);
9e62aaa9186b2d0b18b7d7daad58c6142c457593
a7d08a1037c48bfa40d8687edde7b49f4e326def
/DesignPattern/05Adapter/Adaptee.cpp
290d23652789736336955ce2cdac9ff67d0bf165
[]
no_license
bigflyboy/GDesignPatterns
2dcc65c335491511688b9ce0b726bcb9e46fb679
2f02e252bffccb28be32737c410db1aa3fd8b77e
refs/heads/master
2021-01-23T06:16:02.825246
2017-04-07T02:55:10
2017-04-07T02:55:10
86,350,500
0
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
Adaptee.cpp
// // Adaptee.cpp // DesignPattern // // Created by 王志远 on 2017/3/30. // Copyright © 2017年 王志远. All rights reserved. // #include "Adaptee.hpp" Adaptee::Adaptee(){ } Adaptee::~Adaptee(){ } void Adaptee::specificRequest(){ cout << "specificRequest()|this is real Request from Adaptee!" << endl; }
a8e71174d18fac85c417641fdac44eb3991a59a7
adf253ebc9c3bb326a727d87ba2e071ded76d608
/wallet/qt/ui_addressbookpage.h
33a870593223d677bde5f1d73b93c575d142171a
[ "MIT" ]
permissive
NeblioTeam/neblio
5e0da815df7f1d69d04090fe5e7fed2445962dce
cebf9fcb1fb4e9935fcfdf459d5185488a2c04e5
refs/heads/master
2023-05-01T20:35:36.266611
2023-03-02T07:31:07
2023-03-02T07:31:07
98,357,215
143
71
MIT
2023-04-19T10:07:40
2017-07-25T23:06:34
C++
UTF-8
C++
false
false
7,805
h
ui_addressbookpage.h
/******************************************************************************** ** Form generated from reading UI file 'addressbookpage.ui' ** ** Created by: Qt User Interface Compiler version 5.7.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_ADDRESSBOOKPAGE_H #define UI_ADDRESSBOOKPAGE_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QTableView> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_AddressBookPage { public: QVBoxLayout *verticalLayout; QLabel *labelExplanation; QTableView *tableView; QHBoxLayout *horizontalLayout; QPushButton *newAddressButton; QPushButton *copyToClipboard; QPushButton *showQRCode; QPushButton *signMessage; QPushButton *verifyMessage; QPushButton *deleteButton; QSpacerItem *horizontalSpacer; QDialogButtonBox *buttonBox; void setupUi(QWidget *AddressBookPage) { if (AddressBookPage->objectName().isEmpty()) AddressBookPage->setObjectName(QStringLiteral("AddressBookPage")); AddressBookPage->resize(760, 380); verticalLayout = new QVBoxLayout(AddressBookPage); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); labelExplanation = new QLabel(AddressBookPage); labelExplanation->setObjectName(QStringLiteral("labelExplanation")); labelExplanation->setTextFormat(Qt::PlainText); labelExplanation->setWordWrap(true); verticalLayout->addWidget(labelExplanation); tableView = new QTableView(AddressBookPage); tableView->setObjectName(QStringLiteral("tableView")); tableView->setContextMenuPolicy(Qt::CustomContextMenu); tableView->setTabKeyNavigation(false); tableView->setAlternatingRowColors(true); tableView->setSelectionMode(QAbstractItemView::SingleSelection); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSortingEnabled(true); tableView->verticalHeader()->setVisible(false); verticalLayout->addWidget(tableView); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); newAddressButton = new QPushButton(AddressBookPage); newAddressButton->setObjectName(QStringLiteral("newAddressButton")); QIcon icon; icon.addFile(QStringLiteral(":/icons/add"), QSize(), QIcon::Normal, QIcon::Off); newAddressButton->setIcon(icon); horizontalLayout->addWidget(newAddressButton); copyToClipboard = new QPushButton(AddressBookPage); copyToClipboard->setObjectName(QStringLiteral("copyToClipboard")); QIcon icon1; icon1.addFile(QStringLiteral(":/icons/editcopy"), QSize(), QIcon::Normal, QIcon::Off); copyToClipboard->setIcon(icon1); horizontalLayout->addWidget(copyToClipboard); showQRCode = new QPushButton(AddressBookPage); showQRCode->setObjectName(QStringLiteral("showQRCode")); QIcon icon2; icon2.addFile(QStringLiteral(":/icons/qrcode"), QSize(), QIcon::Normal, QIcon::Off); showQRCode->setIcon(icon2); horizontalLayout->addWidget(showQRCode); signMessage = new QPushButton(AddressBookPage); signMessage->setObjectName(QStringLiteral("signMessage")); QIcon icon3; icon3.addFile(QStringLiteral(":/icons/edit"), QSize(), QIcon::Normal, QIcon::Off); signMessage->setIcon(icon3); horizontalLayout->addWidget(signMessage); verifyMessage = new QPushButton(AddressBookPage); verifyMessage->setObjectName(QStringLiteral("verifyMessage")); QIcon icon4; icon4.addFile(QStringLiteral(":/icons/transaction_0"), QSize(), QIcon::Normal, QIcon::Off); verifyMessage->setIcon(icon4); horizontalLayout->addWidget(verifyMessage); deleteButton = new QPushButton(AddressBookPage); deleteButton->setObjectName(QStringLiteral("deleteButton")); QIcon icon5; icon5.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); deleteButton->setIcon(icon5); horizontalLayout->addWidget(deleteButton); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); buttonBox = new QDialogButtonBox(AddressBookPage); buttonBox->setObjectName(QStringLiteral("buttonBox")); QSizePolicy sizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(buttonBox->sizePolicy().hasHeightForWidth()); buttonBox->setSizePolicy(sizePolicy); buttonBox->setStandardButtons(QDialogButtonBox::Ok); horizontalLayout->addWidget(buttonBox); verticalLayout->addLayout(horizontalLayout); retranslateUi(AddressBookPage); QMetaObject::connectSlotsByName(AddressBookPage); } // setupUi void retranslateUi(QWidget *AddressBookPage) { AddressBookPage->setWindowTitle(QApplication::translate("AddressBookPage", "Address Book", Q_NULLPTR)); labelExplanation->setText(QApplication::translate("AddressBookPage", "These are your neblio addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP tableView->setToolTip(QApplication::translate("AddressBookPage", "Double-click to edit address or label", Q_NULLPTR)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_TOOLTIP newAddressButton->setToolTip(QApplication::translate("AddressBookPage", "Create a new address", Q_NULLPTR)); #endif // QT_NO_TOOLTIP newAddressButton->setText(QApplication::translate("AddressBookPage", "&New Address", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP copyToClipboard->setToolTip(QApplication::translate("AddressBookPage", "Copy the currently selected address to the system clipboard", Q_NULLPTR)); #endif // QT_NO_TOOLTIP copyToClipboard->setText(QApplication::translate("AddressBookPage", "&Copy Address", Q_NULLPTR)); showQRCode->setText(QApplication::translate("AddressBookPage", "Show &QR Code", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP signMessage->setToolTip(QApplication::translate("AddressBookPage", "Sign a message to prove you own a neblio address", Q_NULLPTR)); #endif // QT_NO_TOOLTIP signMessage->setText(QApplication::translate("AddressBookPage", "Sign &Message", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP verifyMessage->setToolTip(QApplication::translate("AddressBookPage", "Verify a message to ensure it was signed with a specified neblio address", Q_NULLPTR)); #endif // QT_NO_TOOLTIP verifyMessage->setText(QApplication::translate("AddressBookPage", "&Verify Message", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP deleteButton->setToolTip(QApplication::translate("AddressBookPage", "Delete the currently selected address from the list", Q_NULLPTR)); #endif // QT_NO_TOOLTIP deleteButton->setText(QApplication::translate("AddressBookPage", "&Delete", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class AddressBookPage: public Ui_AddressBookPage {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_ADDRESSBOOKPAGE_H
fba7e53b9fecef4d9cd1aca45fcc748336a4a1aa
2d2102a4611ab46eaae200cbab0ed24812d37cd2
/tokens.h
87217c1fcd1e5a27c46ea432c797563b2fb3eed7
[ "MIT" ]
permissive
jackprogramsjp/CPP-Simple-Math-Interpreter-V2
8e98acf0389525285a3236909de0f459702763cc
c7033e614686408690d8f47937229a6f84019005
refs/heads/main
2023-02-07T07:17:09.783476
2020-12-23T04:03:55
2020-12-23T04:03:55
323,795,438
1
2
null
null
null
null
UTF-8
C++
false
false
758
h
tokens.h
#ifndef TOKENS_H #define TOKENS_H #include <string> #include <vector> namespace Math_Interpreter { enum class TokenType { NUMBER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, EOF_ }; class Token { public: TokenType type; double value; Token(TokenType type) : type(type) {} Token(TokenType type, double value) : type(type), value(value) {} explicit operator bool() const; // returns true if type != TokenType::EOF_ else returns false std::string str() const; operator std::string() const; // this will call str(), this is just to make kind of like a "__repr__" function in Python }; void print_tokens(const std::vector<Token>& tokens); } // namespace Math_Interpreter #endif // TOKENS_H
d3461b14e23fae95c11e1ae2a889d2fee812fed1
215111e92a3dfc535ce1c1ce25a35fb6003ab575
/cf/contest_educacional_UFMG_1/a.cpp
76055e372bf685694d641664d7615e01d0a3b01e
[]
no_license
emanueljuliano/Competitive_Programming
6e65aa696fb2bb0e2251e5a68657f4c79cd8f803
86fefe4d0e3ee09b5766acddc8c78ed8b60402d6
refs/heads/master
2023-06-23T04:52:43.910062
2021-06-26T11:34:42
2021-06-26T11:34:42
299,115,304
0
0
null
null
null
null
UTF-8
C++
false
false
442
cpp
a.cpp
#include <bits/stdc++.h> using namespace std; #define _ ios_base::sync_with_stdio(0);cin.tie(0); #define endl '\n' #define f first #define s second #define pb push_back typedef long long ll; typedef pair<int, int> ii; const int INF = 0x3f3f3f3f; const ll LINF = 0x3f3f3f3f3f3f3f3fll; int main(){ _ ll n, m, k, l; cin >> n >> m >>k >> l; if (n - (l+k+m-1)/m*m >= 0) cout << (l+k+m-1)/m << endl; else cout << -1 << endl; exit(0); }
1463830bca39db98679df9c1aeb38d3a02da4aff
5861fc92691252420ceb41577c62870e1c23f9d3
/chess/main.cpp
7f9be7c33c84624079208112df67b7886ea800e2
[]
no_license
JammyL/Chess
0eacdf397f7ff4675c6b4b52aa0cfa3fc42814be
1cc9076e218f66e43e19951638313c28d563bb81
refs/heads/master
2020-07-12T10:26:55.873758
2019-10-01T14:40:32
2019-10-01T14:40:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,972
cpp
main.cpp
#include <stdio.h> #include <iostream> #include <iterator> #include <string> #include <regex> #include "game/game.h" bool turn(string s, game* g) { bool valid_input = 1; bool move_success = 0; square* x[2]; string arr[3]; int square_length[2]; int square_height[2]; regex word_regex("(\\S+)"); auto words_begin = sregex_iterator(s.begin(), s.end(), word_regex); auto words_end = std::sregex_iterator(); int j = 0; // std::cout << "Words longer than " << N << " characters:\n"; for (sregex_iterator i = words_begin; i != words_end; ++i) { if(j > 2){ cout << "Expression is too long\n"; break; } else{ smatch match = *i; string match_str = match.str(); arr[j] = match_str; j++; } } for(int i = 0; i < 2; i ++){ square_length[i] = arr[i + 1][0] - 'A'; square_height[i] = arr[i + 1][1] - '1'; if(square_length[j] < 0 or square_length[i] > 7){ cout << "Invalid input. Square not on board.\n"; valid_input = 0; } if(square_height[j] < 0 or square_height[i] >7){ cout << "Invalid input. Square not on board.\n"; valid_input = 0; } if(valid_input == 1){ x[i] = g->get_board()->get_square(square_length[i], square_height[i]); } } if(arr[0] == "Move"){ if(valid_input == 1){ move_success = g->move(x[0], x[1]); } } return move_success; } int main() { game* g = new game(); string s; piece_color c; c = Black; bool checkmate = 0; bool turn_success = 0; char col, row; while(checkmate == 0){ cout << "\n"; for(int j = 7; j > -1; j--){ row = '1' + j; cout << row << " " << "|"; for(int i = 0; i < 8; i++){ if(g->get_board()->get_square(i,j)->get_occupied() == 1){ if(g->get_board()->get_square(i,j)->get_piece_occupying()->get_color() == White){ cout << "W:"; } else{ cout << "B:"; } switch(g->get_board()->get_square(i,j)->get_piece_occupying()->get_type()){ case Pawn: { cout << "P "; break; } case Bishop: { cout << "B "; break; } case Knight: { cout << "H "; break; } case Rook: { cout << "R "; break; } case Queen: { cout << "Q "; break; } case King: { cout << "K "; break; } } } else{ cout << " -- "; } } cout << "|\n\n"; } cout << " "; for(int i = 0; i < 8; i++){ col = 'A' + i; cout << " " << col << " "; } cout << "\n\n"; getline(cin, s); turn_success = turn(s, g); cout << "Move successful: " << turn_success << "\n"; try{ cout << "B6 Type: " << g->get_board()->get_square(1,5)->get_piece_occupying()->get_type(); } catch(string e){ cout << "An exception occured: " << e << "\n"; } //checkmate = g->checkmate_check(c); } cout << "White victorious\n"; return 0; }
b081d91e00cc463e123090a41f29e13d259b410c
78549596df6dea622a4a815f6568f97970b69118
/SDEngine/Source/3DShader.h
24a6835c77a466e2babfa87c836d4acd603ec405
[]
no_license
OscarGame/SDEngine
c9cf79e01ecbd0b953b8a2849d606c69c6f66cf2
4f17916c291f5ee24c919ca888309374b89f1d2f
refs/heads/master
2020-03-27T00:28:17.952199
2018-08-11T15:50:15
2018-08-11T15:50:15
null
0
0
null
null
null
null
GB18030
C++
false
false
871
h
3DShader.h
#ifndef _SHADER_H #define _SHADER_H #include "CoreMini.h" #include"Camera.h" using namespace std; using namespace DirectX; class Shader_3D { private: ID3D11VertexShader* m_pVertexShader; ID3D11PixelShader* m_pPixelShader; ID3D11InputLayout* m_pInputLayout; ID3D11Buffer* m_pCBCommon; ID3D11SamplerState *m_pWrapLinearSampler; ID3D11SamplerState *m_pClampPointSampler; protected: bool virtual Init(WCHAR* vsFilenPath, WCHAR* psFilenPath); //初始化Shader,用于创建InputLayout,VertexShader,PixelShader,常量缓存 bool virtual InitShader(WCHAR*, WCHAR*); //释放Shader void virtual ShutDown(); public: Shader_3D(WCHAR* vsFilenPath, WCHAR* psFilenPath); Shader_3D(const Shader_3D& other); virtual ~Shader_3D(); public: bool SetShaderCB(CXMMATRIX worldMatrix); bool SetShaderState(); bool SetShaderParams(CXMMATRIX worldMatrix); }; #endif
d3d16ccbef9a508d96499a5db01796023df87307
b46f65355d9a79e8d7ea7bd473a7d559ee601a1b
/src/aggregators/pr/captcha_solver.hpp
5e4044b16ccbe0bb24e19c6b95ab65c3a87d656d
[]
no_license
ekuiter/bsdl
8c50eba05f43a789fc58c2e92aa3cd0a6d62d52b
1f9d9cf5f1f55dab3480023456e244001a6a9eae
refs/heads/master
2020-04-05T15:16:29.337225
2018-10-16T19:40:46
2018-10-16T19:40:46
68,543,822
0
0
null
null
null
null
UTF-8
C++
false
false
1,821
hpp
captcha_solver.hpp
#pragma once #include <iostream> #include "../../app.hpp" #include "../../settings.hpp" #include "../../util/platform.hpp" #include "exception.hpp" using namespace std; namespace aggregators { namespace pr { class captcha_solver { chrono::seconds sleep_duration; captcha_solver(): sleep_duration(3) {} public: static captcha_solver& instance() { static captcha_solver captcha_solver; return captcha_solver; } bool has_captcha(const http::response& response) { unique_ptr<CDocument> document = response.parse(); return document->find(settings::get("pr_captcha_sel")).nodeNum() > 0; } http::response operator()(const http::request& request, http::response response) { if (has_captcha(response)) { if (!app::instance().confirm("Captcha detected, solve it?", true)) return response; cerr << "You need to visit " << settings::get("aggregator_pr") << " in your browser and solve the captcha once." << endl << "Visiting " << settings::get("aggregator_pr") << " ..." << endl; util::platform::browse(request.get_url()); cerr << "Waiting until the captcha is solved ..." << endl; util::platform::sleep(sleep_duration); while (has_captcha(response = request())) { cerr << "The captcha is still unsolved." << endl; util::platform::sleep(sleep_duration); } } return response; } }; } }
c67160678dd12359663b372f060b9d5c505237ae
04d9aaf7e635dbb46de2ed20b1e97dcdc85995f2
/D-Squared-Engine/source/Test.Library.Shared/XmlParseHelperScopeTest.cpp
d6638f66099490d2fb2f1acc4b423f29ab64e129
[ "MIT" ]
permissive
stropheum/D-Squared-Engine
0b3847edb416d233804d5900ba1af22b19930ac1
4e607f7cd6f5e7ffd9dc5207dc2b29ad6c4fa5b1
refs/heads/master
2022-04-19T19:58:29.697027
2019-06-12T03:43:07
2019-06-12T03:43:07
78,654,249
3
0
null
2017-09-30T18:39:26
2017-01-11T15:53:32
C++
UTF-8
C++
false
false
6,819
cpp
XmlParseHelperScopeTest.cpp
#include "pch.h" #include "CppUnitTest.h" #include "LeakDetector.h" #include "XmlParseMaster.h" #include "TestSharedData.h" #include "XmlParseHelperScope.h" #include "SharedDataScope.h" #include "Scope.h" #include "Datum.h" #include <glm/detail/type_vec4.hpp> #include <glm/mat4x4.hpp> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace TestLibraryDesktop { TEST_CLASS(XmlParseHelperScopeTest) { public: TEST_METHOD_INITIALIZE(InitializeMethod) { LeakDetector::Initialize(); } TEST_METHOD_CLEANUP(CleanupMethod) { LeakDetector::Finalize(); } TEST_METHOD(TestParse) { Library::SharedDataScope sharedData; Library::XmlParseMaster parseMaster(&sharedData); Library::XmlParseHelperScope helper; sharedData.SetXmlParseMaster(&parseMaster); parseMaster.AddHelper(helper); parseMaster.ParseFromFile("Grammar.xml"); Library::Scope scope = *sharedData.m_scope; Assert::IsTrue(scope["Name"] == "Dale"); Assert::IsTrue(scope["Health"] == 10); Assert::IsTrue(scope["Power"] == 57.3f); Assert::IsTrue(scope["Position"] == glm::vec4(1.0f, 2.0f, 3.0f, 4.0f)); glm::mat4 expectedMatrix( 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f ); Assert::IsTrue(scope["MyMatrix"] == expectedMatrix); Library::Scope& pets = scope["Pets"].Get<Library::Scope>(0); Assert::IsTrue(pets["Dog"] == "Dozer"); } TEST_METHOD(TestEqualityOperator) { std::string xml1 = " \ <Scope Name='Level 1'> \ <Matrix Name = 'MyMatrix'> \ <Vector X = '1.0' Y = '2.0' Z = '3.0' W = '4.0' /> \ <Vector X = '5.0' Y = '6.0' Z = '7.0' W = '8.0' /> \ <Vector X = '9.0' Y = '10.0' Z = '11.0' W = '12.0' /> \ <Vector X = '13.0' Y = '14.0' Z = '15.0' W = '16.0' /> \ </Matrix> \ </Scope> \\"; std::string xml2 = " \ <Scope Name='Level 1'> \ <Matrix Name = 'MyMatrix'> \ <Vector X = '11.0' Y = '12.0' Z = '13.0' W = '14.0' /> \ <Vector X = '15.0' Y = '16.0' Z = '17.0' W = '18.0' /> \ <Vector X = '19.0' Y = '20.0' Z = '21.0' W = '22.0' /> \ <Vector X = '23.0' Y = '24.0' Z = '25.0' W = '26.0' /> \ </Matrix> \ </Scope> \\"; Library::SharedDataScope sharedData1, sharedData2; Library::XmlParseMaster parseMaster1(&sharedData1); Library::XmlParseMaster parseMaster2(&sharedData2); Library::XmlParseHelperScope helper1, helper2; sharedData1.SetXmlParseMaster(&parseMaster1); parseMaster1.AddHelper(helper1); sharedData2.SetXmlParseMaster(&parseMaster2); parseMaster2.AddHelper(helper2); parseMaster1.Parse(const_cast<char*>(xml1.c_str()), static_cast<std::uint32_t>(xml1.length()), true); parseMaster2.Parse(const_cast<char*>(xml2.c_str()), static_cast<std::uint32_t>(xml1.length()), true); Assert::IsFalse(helper1 == helper2); } TEST_METHOD(TestHelperRTTI) { Library::SharedDataScope data; Library::XmlParseHelperScope helper1, helper2; Assert::IsFalse(helper1.Equals(&helper2)); Assert::IsTrue(helper1 == helper1); Assert::IsTrue(helper1 == helper2); Library::XmlParseMaster master(&data); helper1.Initialize(&master); Assert::IsFalse(helper1.Equals(&helper2)); helper2.Initialize(&master); Assert::IsFalse(helper1.Equals(&helper2)); auto val = helper1.ToString(); Assert::IsTrue(val == helper2.ToString()); } TEST_METHOD(TestHelperClone) { Library::XmlParseHelperScope helperOG; Library::IXmlParseHelper* helperClone = nullptr; Assert::IsFalse(helperOG.Equals(helperClone)); helperClone = helperOG.Clone(); Assert::IsFalse(helperOG.Equals(helperClone)); Library::SharedDataScope sharedData; Library::XmlParseMaster parseMaster(&sharedData); sharedData.SetXmlParseMaster(&parseMaster); parseMaster.AddHelper(helperOG); parseMaster.ParseFromFile("Grammar.xml"); Assert::IsFalse(helperOG.Equals(helperClone)); delete helperClone; } TEST_METHOD(TestDataClone) { Library::XmlParseHelperScope helper; Library::SharedDataScope sharedData; Library::XmlParseMaster::SharedData* sharedDataClone = nullptr; Assert::IsFalse(sharedData.Equals(sharedDataClone)); sharedDataClone = sharedData.Clone(); Assert::IsTrue(sharedData.Equals(sharedDataClone)); Library::XmlParseMaster parseMaster(&sharedData); sharedData.SetXmlParseMaster(&parseMaster); parseMaster.AddHelper(helper); parseMaster.ParseFromFile("Grammar.xml"); Assert::IsFalse(sharedData.Equals(sharedDataClone)); delete sharedDataClone; sharedDataClone = sharedData.Clone(); Assert::IsTrue(sharedData.Equals(sharedDataClone)); delete sharedDataClone; } TEST_METHOD(TestDataRTTI) { Library::SharedDataScope data1, data2; Assert::IsTrue(data1.Equals(&data1) && data2.Equals(&data2)); Assert::IsTrue(data1.Equals(&data2)); Assert::IsTrue(data1.ToString() == "Shared Data Scope" && data1.ToString() == data2.ToString()); Library::XmlParseMaster parseMaster(&data1); Library::XmlParseHelperScope helper; data1.SetXmlParseMaster(&parseMaster); parseMaster.AddHelper(helper); parseMaster.ParseFromFile("Grammar.xml"); Assert::IsFalse(data1.Equals(&data2)); Library::XmlParseMaster parseMaster2(&data2); Library::XmlParseHelperScope helper2; data2.SetXmlParseMaster(&parseMaster2); parseMaster2.AddHelper(helper2); parseMaster2.ParseFromFile("Grammar.xml"); Assert::IsTrue(data1.Equals(&data2)); Library::Scope& scope1 = *data1.m_scope; Library::Scope& scope2 = *data2.m_scope; Assert::IsTrue(scope1["Name"] == "Dale" && scope2["Name"] == "Dale"); } }; }
241372f7bc2840a0172ac21475322e0fb48685fb
d64f95e2f1a676db5a975517a16932ef48e3c5b8
/main.cpp
355913a1886241eee06fac0bbc6217e7c0b224d9
[]
no_license
shrechatterjee/OceanFoamImageProcessing
8770e422f056f49f309b24c2fd4f432390d29f2d
9b494fbdb9cbdee2d5c9d5bf85a5554bde9916e1
refs/heads/master
2020-03-15T11:38:39.598889
2018-05-04T10:29:28
2018-05-04T10:29:28
132,124,902
0
0
null
null
null
null
UTF-8
C++
false
false
5,994
cpp
main.cpp
/* skc105@ecs.soton.ac.uk */ #include <iostream> #include <fstream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <string> #include <cmath> #include "img_proc.h" #include "opdata.h" #ifdef _WIN32 #include <Windows.h> //skeleton code taken from http://stackoverflow.com/questions/20860822/finding-the-file-path-of-all-files-in-a-folder // folder must end with "/", e.g. "D:/images/" vector<string> get_all_files_full_path_within_folder(string folder) { vector<string> names; char search_path[200]; sprintf(search_path, "%s*.*", folder.c_str()); WIN32_FIND_DATA fd; HANDLE hFind = ::FindFirstFile(search_path, &fd); if(hFind != INVALID_HANDLE_VALUE) { do { // read all (real) files in current folder, delete '!' read other 2 default folder . and .. if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) { names.push_back(folder+fd.cFileName); } }while(::FindNextFile(hFind, &fd)); ::FindClose(hFind); } return names; } #endif // _WIN32 void showHelp(); bool process_img(string img_path, string op_path); ///*TODO* Add Boost Filesystem in order to get file timestamps (cross platform solution) ///*TODO* Make false whitecap detection less frequent (subimg corner type artefacts) static bool ONLY_UNDISTORT = false; int main(int argc, char *argv[]) { //string src_path = "E:/FoamCam Project/data/2013-11-02_12-01-24/000004/00004113.img"; string src_path;// = "ip_imgs.xml"; string op_path;// = "output_data.csv"; bool output_mode = false; //true for simple output, false for advanced output (file structure creation and image output) for(int i=1; i<argc; i++) { if((!strcmp(argv[i], "-s")) && (i+1 <= argc)) src_path = argv[i+1]; else if((!strcmp(argv[i], "-d")) && (i+1 <= argc)) op_path = argv[i+1]; /*else if((!strcmp(argv[i], "-m")) && (i+1 <= argc)) ///*TODO* add exception handling for invalid input output_mode = argv[i+1];*/ else if((!strcmp(argv[i], "-v")) && (i+1 <= argc)) set_output_mode(true); else if((!strcmp(argv[i], "-u")) && (i+1 <= argc)) ONLY_UNDISTORT = true; /*else if((!strcmp(argv[i], "-c")) && (i+1 <= argc)) { if(src_path.empty() || op_path.empty()) return -1; convertRaw(src_path, op_path, argv[i+1]); return 0; }*/ else if(!strcmp(argv[i], "-?")) { showHelp(); return 0; } } if(src_path == "") { cout << "No source path given, exiting." << endl; return 0; } size_t ext = src_path.find(".xml"); bool foundxml = (ext!=string::npos); ext = src_path.find(".img"); bool foundimg = (ext!=string::npos); bool founddir = (src_path[src_path.length()-1] == '/'); if(foundxml) cout << "Getting images from xml image list." << endl; else if(foundimg) cout << "Loading image from .img file." << endl; else if(founddir) cout << "Searching directory for images." << endl; else { cerr << "Invalid source. Exiting program." << endl; return 1; } if(foundimg) { process_img(src_path, op_path); } else if(foundxml) { FileStorage fs; fs.open(src_path, FileStorage::READ); if (!fs.isOpened()) { cerr << "Failed to open xml file " << src_path << endl; return 1; } FileNode n = fs["images"]; if (n.type() != FileNode::SEQ) { cerr << "Could not read image list" << endl; return 1; } FileNodeIterator it = n.begin(), it_end = n.end(); for (; it != it_end; ++it) { process_img((string)*it, op_path); } } else if(founddir) { vector<string> files = get_all_files_full_path_within_folder(src_path); for(int i=0; i<files.size(); i++) { size_t ext = files[i].find(".img"); if(ext!=string::npos) { cout << "Processing image: " << files[i] << endl; process_img(files[i], op_path); } } } return 0; } bool process_img(string img_path, string op_path) { Mat src = imreadRaw(img_path); if(!src.data) { cerr << "Invalid source image " << img_path << endl; return 1; } OpData data(img_path, src, false); data.addImg(data.getImgName(), src); showImg("Source", src); if(!ONLY_UNDISTORT) maskFrame(src); removeBarrelDist(src); data.addImg(data.getImgName() + "_undistorted", src); showImg("Source - Undistorted", src); if(!ONLY_UNDISTORT) extractWhitecaps(src, data); cout << "data writing: "; if(data.save(op_path)) cout << "success" << endl; else cout << "fail" << endl; if(SHOW_DEBUG_IMGS) waitKey(0);// wait for a keystroke in the window return 0; } void showHelp() { cout << endl << "Optional command line arguments:" << endl; cout << "-s [src] -d [dest] -v -u" << endl; cout << "-s: .img source file or .xml image list" << endl; cout << "-d: data output destination directory" << endl; // cout << "-c: convert .img file to specified format" << endl; //cout << "-m: output mode, 0 = advanced, 1 = simple (.dat file only, in source directory)" << endl; // cout << " Overrides other arguments" << endl; cout << "-v: view debug images" << endl; cout << "-u: only undistort image" << endl; cout << " Formats: " << SUPPORTED_IMG_FORMATS << endl; cout << "-?: help" << endl; }
41d34766c2168b9201e0bb3e914d753070714cc8
efd80acbef5552e2c01417457bba0c0a5aacb607
/AtCoder_PastProblems/ABC_013/D.cpp
e2f2b8a7296bd4120c98a7954c9eadfd7cceee59
[]
no_license
skyto0927/Programming-Contest
4e590a1f17ba61f58af91932f52bedeeff8039e8
5966bd843d9dec032e5b6ff20206d54c9cbf8b14
refs/heads/master
2021-06-04T05:02:58.491853
2020-10-06T21:55:14
2020-10-06T21:55:14
135,557,393
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
D.cpp
#include <bits/stdc++.h> using namespace std; #define REP(i, n) for(int i = 0; i < n; i++) #define REPR(i, n) for(int i = n; i >= 0; i--) #define FOR(i, m, n) for(int i = m; i < n; i++) #define ALL(obj) (obj).begin(), (obj).end() #define INF 1e9 #define LINF 1e18 typedef long long ll; int main() { int N,M,D; cin >> N >> M >> D; vector<int> A(N); REP(i,N) A[i] = i; REP(i,M){ int a; cin >> a; a--; swap(A[a], A[a+1]); } int K = 1; while((1<<K) <= D) K ++; vector<vector<int>> parent(K, vector<int>(N,-1)); REP(i,N) parent[0][A[i]] = i; REP(k,K-1){ REP(i,N){ if(parent[k][i]<0){ parent[k+1][i] = -1; }else{ parent[k+1][i] = parent[k][parent[k][i]]; } } } REP(i,N){ int ans = i; REPR(k,K){ if(1<<k & D){ ans = parent[k][ans]; } } cout << ans+1 << endl; } return 0; }
8b7c3a8ebfdf3f5e849158b996d04d5dfaeb0769
56f51614d678470c44114d822ac2e307c7551446
/VideoPlayerEngine/subtitlerenderer.h
76c6bbce982e721a2afcc68a04b1ab36e33d587a
[]
no_license
makrattaur/ogldesktop
b68381cc3d4141568cf765e49338ed935fa857ed
30a14b25b81f6935f992a293bcbf6d92563bdcb9
refs/heads/master
2021-01-20T13:49:55.276421
2014-11-07T01:41:23
2014-11-07T01:41:23
26,298,728
1
0
null
null
null
null
UTF-8
C++
false
false
1,002
h
subtitlerenderer.h
#ifndef H_SUBTITLERENDERER #define H_SUBTITLERENDERER extern "C" { #include <libavformat/avformat.h> } #include <SFML/Graphics/Font.hpp> #include "isubtitlequeue.h" #include <threadsafequeue.h> #include "textrenderer.h" class IClockSource; class SubtitleRenderer : public ISubtitleQueue { public: SubtitleRenderer(); void Init(AVFormatContext *formatCtx, unsigned int streamIndex); void Update(float deltaTime); void Draw(); virtual void QueueSubtitle(std::unique_ptr<QueuedSubtitle> frame); virtual void OnSeek(); void SetMasterClock(IClockSource &source); private: void DequeueSubtitle(); double GetSubtitleTime(std::unique_ptr<QueuedSubtitle> &frame); AVFormatContext *m_formatCtx; unsigned int m_subtitileStreamIndex; ThreadSafeQueue<std::unique_ptr<QueuedSubtitle>> m_subtitleQueue; TextRenderer m_textRenderer; sf::Font m_font; IClockSource *m_masterClock; std::unique_ptr<QueuedSubtitle> m_currentSubtitle; bool m_displaySubtitile; float m_displayTimer; }; #endif
be69a40021cc490df5cf9495cdc2165bdcfe4ab1
ec36770c86b536f11969b9b2e9a8cdf969e3708c
/LeetCode67.cpp
445edef87512360acc5af07319f77ed4a1f44661
[]
no_license
siluhuayu/LeetCode
0b93013bb724cf62b04c1932a1128428f1f4589f
b84861317f71166762990fe88e4267f3272ad8e9
refs/heads/main
2023-03-11T11:31:28.626787
2021-03-02T12:00:15
2021-03-02T12:00:15
333,050,950
0
0
null
null
null
null
UTF-8
C++
false
false
930
cpp
LeetCode67.cpp
#include<iostream> #include<string> using namespace std; string addBinary(string a, string b){ int lena = a.size(),lenb = b.size(); int res[100000] = {0}; string mul_res; int min_len = min(lena,lenb); for(int i = 0; i < min_len; ++i) res[i] = a[lena-1-i] - 48 + b[lenb-1-i] - 48; if(min_len < lena){ for(int i = min_len; i < lena; ++i){ res[i] = a[lena-1-i] - 48; } } else if(min_len < lenb){ for(int i = min_len; i < lenb; ++i){ res[i] = b[lenb-1-i] - 48; } } int len = max(lena,lenb); for(int k = 0; k < len; k++) { if(res[k] > 1){ int temp = res[k]; res[k] = temp % 2; res[k+1] += temp / 2; } } int st = (res[len] == 0 ? len-1:len); for(st; st >= 0; --st) mul_res = mul_res + to_string(res[st]); return mul_res; } int main(){ string a,b; cin >> a >> b; string res = addBinary(a,b); cout << res << endl; system("pause"); return 0; }
509aa0f7e146126af4015212099785181e9bfc92
28c651deb42b7e1d5b0a73b923ae5f35a8bcd506
/FordFulkersonAlgorithm/BreadthFirstSearch.cpp
15e1916a2346cba2da617e93cf7bc36acb53d1b8
[]
no_license
myyychal/AdvancedAlgorithms
8c56bfddda9c2b1c885d9a08cd0376eb07de543d
79945b3a241ad345b527abbb6597076ed28cb91e
refs/heads/master
2021-01-15T10:47:18.486194
2014-12-31T08:39:29
2014-12-31T08:39:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
BreadthFirstSearch.cpp
#include "BreadthFirstSearch.h" bool BreadthFirstSearch::isPath(float **graph, int length, int start, int dest, bool visited[], std::vector<int>& path) { std::queue<float> queue; queue.push(start); visited[start] = true; int parent[length]; parent[start] = -1; while (!queue.empty()){ int v = queue.front(); queue.pop(); for (int i=0; i<length; i++){ if (graph[v][i] == 0 || visited[i] == true){ continue; } queue.push(i); visited[i] = true; parent[i] = v; if (visited[dest]){ int tempDest = dest; while(parent[tempDest] != -1){ path.push_back(tempDest); tempDest = parent[tempDest]; } path.push_back(tempDest); return true; } } } return visited[dest]; }
9bd5c88ad8a74921c2b79c0dc254408958efe8b2
1eb8fa36c7c2367beb73f9bfc2f2a1b5edefb9c0
/MyRobotWar/MyRobotWar/Model/RobotData.cpp
1c8d8059cb666e6ff4d9d4c8772004c22fa4cf65
[]
no_license
hgs-19-2/RobotWar
3e03e106b04c64a08aaad74798940cfbd1b7c28f
c5d3b947a9e6f5f3353c72bd8d9071c6767a5464
refs/heads/master
2020-06-17T15:20:11.144244
2019-09-15T15:09:49
2019-09-15T15:09:49
195,961,789
0
0
null
2019-07-12T18:00:13
2019-07-09T08:02:32
C++
UTF-8
C++
false
false
1,214
cpp
RobotData.cpp
#include"Model.h" //#include"RobotData.h" //#include<string> Robotdata::Robotdata(string na, int mhp, int nhp, int range, int sp, int de) { //strcpy(name, na); name = na; maxhp = nhp; nowhp = nhp; moverange = range; canmove = range; speed = sp; defense = de; } int Robotdata::changehp(int change) { nowhp = nowhp - change; if (nowhp < 0) nowhp = 0; else if (nowhp > maxhp) nowhp = maxhp; return nowhp; } void Robotdata::Move(int m) { canmove = m; } int Robotdata::getcanmove() { return canmove; } string Robotdata::getname() { return name; } int Robotdata::getdefense() { return defense; } int Robotdata::getmaxhp() { return maxhp; } int Robotdata::getmoverange() { return moverange; } int Robotdata::getnowhp() { return nowhp; } int Robotdata::getspeed() { return speed; } int Robotdata::getskillnum() { return skill.size(); } Robotskill&Robotdata::getskillinfo(int num) { return skill[num]; } // void Robotdata::setskill(vector<int> skilltype){ int size = skilltype.size(); for(int i=0;i<size;i++) skill.push_back(Robotskilllist[skilltype[i]]); } void Robotdata::reset() { canmove = moverange; }
83774994b18cd6bb795d07e68c674a4071d6865f
b1b71db27033ecfd18f077128b3883c5b366ccd8
/src/kickClass.h
96994ed134c37330548b403fff81359cb055b418
[]
no_license
janisso/smart_move
3692203684844efb751b08209a3a00f288df48b4
93122439b9d09ced5767ddd9b3e25a5c089e30c2
refs/heads/master
2021-05-02T17:37:46.451371
2018-04-07T17:26:09
2018-04-07T17:26:09
120,647,924
0
0
null
null
null
null
UTF-8
C++
false
false
2,260
h
kickClass.h
// // kickClass.h // receiveSensors // // Created by Janis on 07/02/2018. // // #ifndef __receiveSensors__kickClass__ #define __receiveSensors__kickClass__ //#include <stdio.h> #include "ofMain.h" #include "features.h" class kickClass{ public: void setup(); void update(double ElapsedTime_, float a_x_, float a_y_, float a_z_, float azimuth_); void kick(); float kick_vel_send; bool is_kick, send_kick, new_kick; double ElapsedTime; float a_x, a_y, a_z; // For the object "kick" float acc_last_three[3][3] = {{0., 0., 0.}, {0., 0., 0.}, {0., 0., 0.}}; float acc_intensity_last_two[3][2] = {{0., 0.}, {0., 0.}, {0., 0.}}; float acc_intensity_x, acc_intensity_y, acc_intensity_z; float acc_intensity_norm; float kick_intensity;// = 0.0f; double LastKick; //Time of the last sample of the last kick in milliseconds bool isKicking;// = 0.0f; //Median computation over N running points (N odd): //- Insert current value at the location of the value to be ejected, using a fifo //- Move it to the right place & update the indices concurrently using a layer to establish the link with fifo indices //- End of loop: median array is sorted, median value is median_values[N/2] float median_values[KICK_MEDIAN_FILTERSIZE] = {0., 0., 0., 0., 0., 0., 0., 0., 0.}; //sorted array of the 9 latest intensity values int median_linking[KICK_MEDIAN_FILTERSIZE] = {3, 4, 1, 5, 7, 8, 0, 2, 6}; //linking layer int median_fifo[KICK_MEDIAN_FILTERSIZE] = {6, 2, 7, 0, 1, 3, 8, 4, 5}; //fifo buffer for the corresponding indices, to update every time an element is moved in the median array //The initialization of median_linking and median_fifo must comply with the following invariant property: median_fifo[median_linking[i]] == median_linking[median_fifo[i]] == i for all i in [0, MEDIAN_FILTER_SIZE-1] // int i1, i2, i3; float acc_intensity_norm_median;// = 0.f; unsigned short int LoopIndex;// = 0; unsigned short int LoopIndexPeriod;// = lcm(lcm(2, 3), KICK_MEDIAN_FILTERSIZE); float azimuth; float kick_vel[10] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0.}; int kick_count; }; #endif /* defined(__receiveSensors__kickClass__) */
1b5bc9a069318c1a7938372630886282b2dbed28
ef7eabdd5f9573050ef11d8c68055ab6cdb5da44
/eolimp/page27/q2619/Main.cpp
c462ba7d1f9960b7a332275f7b58a7c3b97e9e1f
[ "WTFPL" ]
permissive
gauravsingh58/algo
cdbf68e28019ba7c3e4832e373d32c71902c9c0d
397859a53429e7a585e5f6964ad24146c6261326
refs/heads/master
2022-12-28T01:08:32.333111
2020-09-30T19:37:53
2020-09-30T19:37:53
300,037,652
1
1
WTFPL
2020-10-15T09:26:32
2020-09-30T19:29:29
Java
UTF-8
C++
false
false
453
cpp
Main.cpp
#include <cstdio> int main() { int n, ns[1000000], sum1 = 0, sum2 = 0; scanf("%d", &n); for(int i=0; i<n; i++) { scanf("%d", &ns[i]); sum1 += ns[i]; } if(sum1%2 == 0) { for(int i=0; i<n; i++) { sum1 -= ns[i]; sum2 += ns[i]; if(sum1 == sum2) { printf("%d\n", i+1); break; } else if(sum1 < sum2) { printf("%d\n", -1); break; } } } else printf("%d\n", -1); }
488147b0a521411edcc9f368df76f7109580be7c
965d5c861dd321c5414bf6b1cc708dc08fad7c40
/cs488-proj/material.cpp
11af8f8d595d9347f45f7445f5ec9459051f39d9
[]
no_license
franklixuefei/cs488-project
480762f96fccc0664ec79827fb4d0d0a993b20f1
6aa637252217b0873869ed90b23bb229bffc527e
refs/heads/master
2020-06-03T21:57:31.608619
2014-04-05T02:14:16
2014-04-05T02:14:16
18,223,186
1
0
null
null
null
null
UTF-8
C++
false
false
6,326
cpp
material.cpp
#include "material.hpp" #include "primitive.hpp" #include "formulas.hpp" #include <cassert> PhongMaterial::PhongMaterial(const Colour& ks, const Colour &kt, double shininess, double refractive_index, const string &bump_name) : m_ks(ks), m_kt(kt), m_shininess(shininess), m_refractive_index(refractive_index), m_bump_map(NULL) { if (bump_name != "" ){ m_bump_map = new Image(); if (!m_bump_map->loadPng(bump_name)) { cerr << "bump map " << bump_name << " not found." << endl; exit(1); } } } PhongMaterial::~PhongMaterial() { } Colour PhongMaterial::getSpecular() const { return m_ks; } Colour PhongMaterial::getTransmittedColour() const { return m_kt; } Colour PhongMaterial::getShininess() const { return m_shininess; } Colour PhongMaterial::getColour( const Vector3D& view_dir, const std::list<Light*>& lights, const Colour& ambient, const IntersectionPoint &ip, const Vector3D &normal, Primitive *primitive) const { Vector3D view = view_dir; view.normalize(); Colour kd = getDiffuse(primitive, ip.m_orig_point); Colour c = kd * ambient; for (std::list<Light*>::const_iterator it = lights.begin(); it != lights.end(); ++it) { Vector3D light_dir = (*it)->getPosition() - ip.m_point; // Note this needs to point towards the light. double dist = light_dir.length(); light_dir.normalize(); Vector3D r = Formulas::perfectReflection(normal, -1.0 * light_dir); Colour contribution = (kd + m_ks * ( pow(r.dot(view), m_shininess) / normal.dot(light_dir) )) * (*it)->getColour() * light_dir.dot(normal) * (1 / ((*it)->getAttenuation()[0] + (*it)->getAttenuation()[1] * dist + (*it)->getAttenuation()[2] * dist * dist)); if (contribution.R() >= 0 && contribution.G() >= 0 && contribution.B() >= 0) { c = c + contribution; } } return c; } double PhongMaterial::getRefractiveIndex() const { return m_refractive_index; } bool PhongMaterial::getMapCoords(Primitive *primitive, const Point3D &p, Point2D& mapCoords, Image *map) const { Point2D uvCoords = primitive->get2DTextureMapCoordinates(p); int texture_width = map->width(); int texture_height = map->height(); mapCoords = Point2D( uvCoords[0] * (double)((double)texture_width - 1.0), uvCoords[1] * (double)((double)texture_height - 1.0) ); if (mapCoords[0] < -EPSILON || mapCoords[0] > (double)texture_width + EPSILON || mapCoords[1] < -EPSILON || mapCoords[1] > (double)texture_height + EPSILON) { return false; } return true; } Vector3D PhongMaterial::getNormal(const Vector3D &normal, Primitive *primitive, const Point3D &p) const { Vector3D n = normal; if (m_bump_map) { Point2D mapCoords(-1,-1); if (!getMapCoords(primitive, p, mapCoords, m_bump_map)) { cerr << "bump map coords out of bound" << endl; return n; } int x = mapCoords[0]; int y = mapCoords[1]; n[0] += 2.0 * (*m_bump_map)(x, y, 0) - 1.0; n[1] += 2.0 * (*m_bump_map)(x, y, 1) - 1.0; n[2] += 2.0 * (*m_bump_map)(x, y, 2) - 1.0; if (!isZero(n.length2() - 1.0, SMALL_EPSILON)) { n.normalize(); } } return n; } BasicPhongMaterial::BasicPhongMaterial(const Colour &kd, const Colour &ks, const Colour &kt, double shininess, double refractive_index, const string& bump_name) : PhongMaterial(ks, kt, shininess, refractive_index, bump_name), m_kd(kd) { } BasicPhongMaterial::~BasicPhongMaterial() { } Colour BasicPhongMaterial::getDiffuse(Primitive *primitive, const Point3D &p) const { return m_kd; } ImageTextureMaterial::ImageTextureMaterial(const string &filename, const Colour &ks, const Colour &kt, double shininess, double refractive_index, const string& bump_name) : PhongMaterial(ks, kt, shininess, refractive_index, bump_name), m_texture_map(new Image()) { if (!m_texture_map->loadPng(filename)) { cerr << "texture map " << filename << " not found." << endl; exit(1); } } ImageTextureMaterial::~ImageTextureMaterial() { delete m_texture_map; } Colour ImageTextureMaterial::getDiffuse(Primitive *primitive, const Point3D &p) const { Point2D mapCoords(-1,-1); if (!getMapCoords(primitive, p, mapCoords, m_texture_map)) { cerr << "texture map coords out of bound" << endl; return Colour(1,0,0); } // bilinear interpolation int x0 = int(mapCoords[0]); int y0 = int(mapCoords[1]); double dx = mapCoords[0] - x0; double dy = mapCoords[1] - y0; double omdx = 1.0 - dx; double omdy = 1.0 - dy; Colour c00, c01, c10, c11; #warning using supersamping to make the texture smooth if (x0 < m_texture_map->width() && y0 < m_texture_map->height()) { c00 = Colour( (*m_texture_map)(x0, y0, 0), (*m_texture_map)(x0, y0, 1), (*m_texture_map)(x0, y0, 2) ); } if (x0 < m_texture_map->width() && y0+1 < m_texture_map->height()) { c01 = Colour( (*m_texture_map)(x0, y0+1, 0), (*m_texture_map)(x0, y0+1, 1), (*m_texture_map)(x0, y0+1, 2) ); } if (x0+1 < m_texture_map->width() && y0 < m_texture_map->height()) { c10 = Colour( (*m_texture_map)(x0+1, y0, 0), (*m_texture_map)(x0+1, y0, 1), (*m_texture_map)(x0+1, y0, 2) ); } if (x0+1 < m_texture_map->width() && y0+1 < m_texture_map->height()) { c11 = Colour( (*m_texture_map)(x0+1, y0+1, 0), (*m_texture_map)(x0+1, y0+1, 1), (*m_texture_map)(x0+1, y0+1, 2) ); } Colour ret = omdx * omdy * c00 + omdx * dy * c01 + dx * omdy * c10 + dx * dy * c11; return ret; }
f97a2f7f526a61abb21f74c7618f3d1ff90f520e
10bf5b1e12c65435c69b7ac17bd8adec13634897
/Algorithm of Notes/ch04/MergeSortNoRecursive.cpp
0a07f3859a802ac9e155db675da610ef61578b63
[]
no_license
Sinking-Stone/LearningNotes
6d666e684250d0bcf772ff51841379fb2ccf749b
9e4424afc506bbb860b55f2635b026bee58966aa
refs/heads/main
2023-07-24T03:48:48.597958
2021-09-04T03:56:26
2021-09-04T03:56:26
397,807,723
0
0
null
null
null
null
UTF-8
C++
false
false
1,152
cpp
MergeSortNoRecursive.cpp
// // Created by SinkingStone on 2021/8/31. // #include <stdio.h> const int manx = 100; void merge(int A[], int L1, int R1, int L2, int R2) { int i = L1, j = L2; int temp[manx], index = 0; while (i <= R1 && j <= R2) { if (A[i] <= A[j]) temp[index++] = A[i++]; else temp[index++] = A[j++]; } while (i <= R1) temp[index++] = A[i++]; while (j <= R2) temp[index++] = A[j++]; for (int i = 0; i < index; i++) { A[L1 + i] = temp[i]; } } void mergeSort(int A[]) { int n=sizeof(A)/sizeof(A[0]); for(int step=2;step/2<n;step*=2){ for(int i=1;i<=n;i++){ int mid=i+step/2-1; if(mid+1<=n) merge(A,i,mid,mid+1,i+step-1>n?i+step-1:n); } } } void mergeSort2(int A[], int left, int right) { if (left < right) { int mid = (left + right) / 2; mergeSort2(A, left, mid); mergeSort2(A, mid + 1, right); merge(A, left, mid, mid + 1, right); } } int main() { int a[] = {9, 7, 5, 3, 1, 2, 4, 6, 8, 0}; // mergeSort(a, 0, 9); mergeSort(a); for (int i = 0; i < 10; ++i) { printf("%d", a[i]); } }
f96d68c17b877f7111eb1bbe90cea89f9c2444c4
c12fba29b0cbb5071dca39ddbe67da9607b77d65
/Engine/Include/Entities/Creation/StaticModelInitializationData.h
6454a5dc3ac8fe93bac4d8afd347e39387be0489
[]
no_license
satellitnorden/Catalyst-Engine
55666b2cd7f61d4e5a311297ccbad754e901133e
c8064856f0be6ed81a5136155ab6b9b3352dca5c
refs/heads/master
2023-08-08T04:59:54.887284
2023-08-07T13:33:08
2023-08-07T13:33:08
116,288,917
21
3
null
null
null
null
UTF-8
C++
false
false
870
h
StaticModelInitializationData.h
#pragma once //Core. #include <Core/Essential/CatalystEssential.h> //Entities. #include <Entities/Creation/EntityInitializationData.h> //Physics. #include <Physics/Native/ModelCollisionConfiguration.h> //Resources. #include <Resources/Core/MaterialResource.h> #include <Resources/Core/ModelResource.h> #include <Resources/Core/ResourcePointer.h> //World. #include <World/Core/WorldTransform.h> class StaticModelInitializationData final : public EntityInitializationData { public: //The world transform. WorldTransform _WorldTransform; //The model resource. ResourcePointer<ModelResource> _ModelResource; //The material resources. StaticArray<ResourcePointer<MaterialResource>, RenderingConstants::MAXIMUM_NUMBER_OF_MESHES_PER_MODEL> _MaterialResources; //The model collision configuration. ModelCollisionConfiguration _ModelCollisionConfiguration; };
dd76b4ec2633283400cb7759c7725bd81c3ac65e
64bb79337ab4da58a45bbfb322f054f196825b4f
/Data Structure Full/05_Linked_list/Apna College/01_prac.cpp
5fc2a473f6c60ccd1e34df27c122426056f7e3e5
[]
no_license
kokfahad/Problems-Solving-
08f2caa9344e53f0aab10af121563c43207c0ab6
4e0eca18c6b609d8d9eb13d2bb6591b425e58fa2
refs/heads/main
2023-06-07T15:57:51.366088
2021-05-28T17:30:33
2021-05-28T17:30:33
371,772,636
1
0
null
null
null
null
UTF-8
C++
false
false
842
cpp
01_prac.cpp
#include<bits/stdc++.h> using namespace std; class node{ public: int data; node * next; node(int x){ data=x; next=NULL; } }; void insertAtHead(node* &head,int val) { node *n=new node(val); n->next=head; head=n; } void insertAtTail(node* &head,int val) { node* n=new node(val); if(head==NULL) { head=n; return; } node* tmp=head; while(tmp->next!=NULL) { tmp=tmp->next; } tmp->next=n; } void display(node* head) { node *tmp=head; while(tmp!=NULL) { cout<<tmp->data<<"->"; tmp=tmp->next; } cout<<"NULL"<<endl; } int main() { node* head=NULL; // insertAtTail(head,1); // insertAtTail(head,2); // insertAtTail(head,3); // display(head); insertAtHead(head,4); display(head); }
bbb71e0cd8f279936ba9c1829cf5f565f34b885a
17292fe87e3850f45facbff8b6c2b542539f3f35
/libgalois/src/analytics/triangle_count/triangle_count.cpp
a999340c2b9553c604b4cc2c56796d4e3f1f83ce
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
DataBoyTX/katana
f76f43bb073589f8c67c2f4af92307a66083f8eb
ebf166bd24c84fd2aa433d68784eb5d53c84f310
refs/heads/master
2023-06-29T15:53:44.241021
2021-07-21T17:13:45
2021-08-03T16:54:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,590
cpp
triangle_count.cpp
/* * This file belongs to the Galois project, a C++ library for exploiting * parallelism. The code is being released under the terms of the 3-Clause BSD * License (a copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #include "katana/analytics/triangle_count/triangle_count.h" #include "katana/analytics/Utils.h" using namespace katana::analytics; using PropertyGraph = katana::PropertyGraph; using Node = katana::PropertyGraph::Node; constexpr static const unsigned kChunkSize = 64U; /** * Like std::lower_bound but doesn't dereference iterators. Returns the first * element for which comp is not true. */ template <typename Iterator, typename Compare> Iterator LowerBound(Iterator first, Iterator last, Compare comp) { using difference_type = typename std::iterator_traits<Iterator>::difference_type; Iterator it; difference_type count; difference_type half; count = std::distance(first, last); while (count > 0) { it = first; half = count / 2; std::advance(it, half); if (comp(it)) { first = ++it; count -= half + 1; } else { count = half; } } return first; } /** * std::set_intersection over edge_iterators. */ template <typename G> size_t CountEqual( const G& g, typename G::edge_iterator aa, typename G::edge_iterator ea, typename G::edge_iterator bb, typename G::edge_iterator eb) { size_t retval = 0; while (aa != ea && bb != eb) { typename G::Node a = *g.GetEdgeDest(aa); typename G::Node b = *g.GetEdgeDest(bb); if (a < b) { ++aa; } else if (b < a) { ++bb; } else { retval += 1; ++aa; ++bb; } } return retval; } template <typename G> struct LessThan { const G& g; typename G::Node n; LessThan(const G& g, typename G::Node n) : g(g), n(n) {} bool operator()(typename G::edge_iterator it) { return *g.GetEdgeDest(it) < n; } }; template <typename G> struct GreaterThanOrEqual { const G& g; typename G::Node n; GreaterThanOrEqual(const G& g, typename G::Node n) : g(g), n(n) {} bool operator()(typename G::edge_iterator it) { return n >= *g.GetEdgeDest(it); } }; template <typename G> struct GetDegree { typedef typename G::Node N; const G& g; GetDegree(const G& g) : g(g) {} ptrdiff_t operator()(const N& n) const { return g.edges(n).size(); } }; template <typename Node, typename EdgeTy> struct IdLess { bool operator()( const katana::EdgeSortValue<Node, EdgeTy>& e1, const katana::EdgeSortValue<Node, EdgeTy>& e2) const { return e1.dst < e2.dst; } }; /** * Node Iterator algorithm for counting triangles. * <code> * for (v in G) * for (all pairs of neighbors (a, b) of v) * if ((a,b) in G and a < v < b) * triangle += 1 * </code> * * Thomas Schank. Algorithmic Aspects of Triangle-Based Network Analysis. PhD * Thesis. Universitat Karlsruhe. 2007. */ size_t NodeIteratingAlgo(katana::PropertyGraph* graph) { katana::GAccumulator<size_t> numTriangles; katana::do_all( katana::iterate(*graph), [&](const PropertyGraph::Node& n) { // Partition neighbors // [first, ea) [n] [bb, last) PropertyGraph::edge_iterator first = graph->edges(n).begin(); PropertyGraph::edge_iterator last = graph->edges(n).end(); PropertyGraph::edge_iterator ea = LowerBound(first, last, LessThan<PropertyGraph>(*graph, n)); PropertyGraph::edge_iterator bb = LowerBound( first, last, GreaterThanOrEqual<PropertyGraph>(*graph, n)); for (; bb != last; ++bb) { Node B = *graph->GetEdgeDest(bb); for (auto aa = first; aa != ea; ++aa) { Node A = *graph->GetEdgeDest(aa); PropertyGraph::edge_iterator vv = graph->edges(A).begin(); PropertyGraph::edge_iterator ev = graph->edges(A).end(); PropertyGraph::edge_iterator it = LowerBound(vv, ev, LessThan<PropertyGraph>(*graph, B)); if (it != ev && *graph->GetEdgeDest(it) == B) { numTriangles += 1; } } } }, katana::chunk_size<kChunkSize>(), katana::steal(), katana::loopname("TriangleCount_NodeIteratingAlgo")); return numTriangles.reduce(); } /** * Lambda function to count triangles */ void OrderedCountFunc( PropertyGraph* graph, Node n, katana::GAccumulator<size_t>& numTriangles) { size_t numTriangles_local = 0; for (auto it_v : graph->edges(n)) { auto v = *graph->GetEdgeDest(it_v); if (v > n) { break; } PropertyGraph::edge_iterator it_n = graph->edges(n).begin(); for (auto it_vv : graph->edges(v)) { auto vv = *graph->GetEdgeDest(it_vv); if (vv > v) { break; } while (*graph->GetEdgeDest(it_n) < vv) { it_n++; } if (vv == *graph->GetEdgeDest(it_n)) { numTriangles_local += 1; } } } numTriangles += numTriangles_local; } /* * Simple counting loop, instead of binary searching. */ size_t OrderedCountAlgo(PropertyGraph* graph) { katana::GAccumulator<size_t> numTriangles; katana::do_all( katana::iterate(*graph), [&](const Node& n) { OrderedCountFunc(graph, n, numTriangles); }, katana::chunk_size<kChunkSize>(), katana::steal(), katana::loopname("TriangleCount_OrderedCountAlgo")); return numTriangles.reduce(); } /** * Edge Iterator algorithm for counting triangles. * <code> * for ((a, b) in E) * if (a < b) * for (v in intersect(neighbors(a), neighbors(b))) * if (a < v < b) * triangle += 1 * </code> * * Thomas Schank. Algorithmic Aspects of Triangle-Based Network Analysis. PhD * Thesis. Universitat Karlsruhe. 2007. */ size_t EdgeIteratingAlgo(PropertyGraph* graph) { struct WorkItem { Node src; Node dst; WorkItem(const Node& a1, const Node& a2) : src(a1), dst(a2) {} }; katana::InsertBag<WorkItem> items; katana::GAccumulator<size_t> numTriangles; katana::do_all( katana::iterate(*graph), [&](Node n) { for (auto edge : graph->edges(n)) { auto dest = graph->GetEdgeDest(edge); if (n < *dest) { items.push(WorkItem(n, *dest)); } } }, katana::loopname("TriangleCount_Initialize")); katana::do_all( katana::iterate(items), [&](const WorkItem& w) { // Compute intersection of range (w.src, w.dst) in neighbors of // w.src and w.dst PropertyGraph::edge_iterator abegin = graph->edges(w.src).begin(); PropertyGraph::edge_iterator aend = graph->edges(w.src).end(); PropertyGraph::edge_iterator bbegin = graph->edges(w.dst).begin(); PropertyGraph::edge_iterator bend = graph->edges(w.dst).end(); PropertyGraph::edge_iterator aa = LowerBound( abegin, aend, GreaterThanOrEqual<PropertyGraph>(*graph, w.src)); PropertyGraph::edge_iterator ea = LowerBound(abegin, aend, LessThan<PropertyGraph>(*graph, w.dst)); PropertyGraph::edge_iterator bb = LowerBound( bbegin, bend, GreaterThanOrEqual<PropertyGraph>(*graph, w.src)); PropertyGraph::edge_iterator eb = LowerBound(bbegin, bend, LessThan<PropertyGraph>(*graph, w.dst)); numTriangles += CountEqual(*graph, aa, ea, bb, eb); }, katana::loopname("TriangleCount_EdgeIteratingAlgo"), katana::chunk_size<kChunkSize>(), katana::steal()); return numTriangles.reduce(); } katana::Result<uint64_t> katana::analytics::TriangleCount( katana::PropertyGraph* pg, TriangleCountPlan plan) { katana::StatTimer timer_graph_read("GraphReadingTime", "TriangleCount"); katana::StatTimer timer_auto_algo("AutoRelabel", "TriangleCount"); bool relabel; timer_graph_read.start(); switch (plan.relabeling()) { case TriangleCountPlan::kNoRelabel: relabel = false; break; case TriangleCountPlan::kRelabel: relabel = true; break; case TriangleCountPlan::kAutoRelabel: timer_auto_algo.start(); relabel = IsApproximateDegreeDistributionPowerLaw(*pg); timer_auto_algo.stop(); break; default: return katana::ErrorCode::AssertionFailed; } std::unique_ptr<katana::PropertyGraph> mutable_pfg; if (relabel || !plan.edges_sorted()) { // Copy the graph so we don't mutate the users graph. auto mutable_pfg_result = pg->Copy({}, {}); if (!mutable_pfg_result) { return mutable_pfg_result.error(); } mutable_pfg = std::move(mutable_pfg_result.value()); pg = mutable_pfg.get(); } if (relabel) { katana::StatTimer timer_relabel("GraphRelabelTimer", "TriangleCount"); timer_relabel.start(); if (auto r = katana::SortNodesByDegree(pg); !r) { return r.error(); } timer_relabel.stop(); } // If we relabel we must also sort. Relabeling will break the sorting. if (relabel || !plan.edges_sorted()) { if (auto r = katana::SortAllEdgesByDest(pg); !r) { return r.error(); } } timer_graph_read.stop(); katana::EnsurePreallocated(1, 16 * (pg->num_nodes() + pg->num_edges())); katana::ReportPageAllocGuard page_alloc; size_t total_count; katana::StatTimer execTime("TriangleCount", "TriangleCount"); execTime.start(); switch (plan.algorithm()) { case TriangleCountPlan::kNodeIteration: total_count = NodeIteratingAlgo(pg); break; case TriangleCountPlan::kEdgeIteration: total_count = EdgeIteratingAlgo(pg); break; case TriangleCountPlan::kOrderedCount: total_count = OrderedCountAlgo(pg); break; default: return katana::ErrorCode::InvalidArgument; } execTime.stop(); return total_count; }
b6bdb3486cacd2ff973e23b23e93095d9e3a6c59
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/InnerDetector/InDetConditions/PixelCoralClientUtils/src/fixTimewalk.cc
e7cc99d363d39b3ee9a4baf7e34b0e52e57d748d
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
4,271
cc
fixTimewalk.cc
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #include "PixelCoralClientUtils/PixelCalibData.hh" #include<string> #include<map> #include<fstream> using namespace std; int load_pcd(map<unsigned int, PixelCoralClientUtils::PixelCalibData>& pcdmap, const char* filename) { ifstream in(filename); if (!in.is_open()) return 1; while (in) { unsigned int idmod; in >> idmod; if (in.eof()) break; PixelCoralClientUtils::PixelCalibData pcd; for (int i = 0; i<16; ++i) { char dummy; in >> dummy; if (dummy!='I') break; int idchip; in >> idchip; if (idchip!=i) break; PixelCoralClientUtils::PixelCalibData::PixelChipSummaryData pcsd; pcsd.setChipID(idchip); int thres, sigma, noise, timewalk; in >> thres >> sigma >> noise >> timewalk; pcsd.setThreshold(0, thres, sigma, noise, timewalk); in >> thres >> sigma >> noise >> timewalk; pcsd.setThreshold(1, thres, sigma, noise, timewalk); in >> thres >> sigma >> noise >> timewalk; pcsd.setThreshold(2, thres, sigma, noise, timewalk); float A, E, C; in >> A >> E >> C; pcsd.setQ2Tot(0, A, E, C); in >> A >> E >> C; pcsd.setQ2Tot(2, A, E, C); float p1, p2; in >> p1 >> p2; pcsd.setTotRes(p1, p2); pcd.add(pcsd); } pcdmap.insert(make_pair(idmod,pcd)); } return 0; } //int main(int argc, char **argv){ int main(int, char **){ // // load pcd from text file // map<unsigned int, PixelCoralClientUtils::PixelCalibData> pcdmap_old; if (load_pcd(pcdmap_old, "pcd_old.dat")) return 1; map<unsigned int, PixelCoralClientUtils::PixelCalibData> pcdmap; if (load_pcd(pcdmap, "pcd.dat")) return 1; cout << "pix cal data size: " << pcdmap_old.size() << "/" << pcdmap.size() << endl; // // recalculate timewalk according to the formula // new_timewalk = old_timewalk - old_threshold + new_threshold // for (map<unsigned int, PixelCoralClientUtils::PixelCalibData>::iterator ipcd = pcdmap.begin(); ipcd != pcdmap.end(); ++ipcd) { PixelCoralClientUtils::PixelCalibData& pcd = ipcd->second; PixelCoralClientUtils::PixelCalibData& pcd_old = pcdmap_old[ipcd->first]; for (int i = 0; i<16; ++i) { PixelCoralClientUtils::PixelCalibData::PixelChipSummaryData& pcsd = *pcd.findChipID(i); PixelCoralClientUtils::PixelCalibData::PixelChipSummaryData& pcsd_old = *pcd_old.findChipID(i); // replace the parameter in the table for (int type = 0; type<3; ++type) { int old_threshold = pcsd_old.getThreshold(type); int new_threshold = pcsd.getThreshold(type); int sigma = pcsd.getThresholdSigma(type); int noise = pcsd.getNoise(type); int old_timewalk = pcsd_old.getTimeWalk(type); int new_timewalk = old_timewalk - old_threshold + new_threshold; pcsd.setThreshold(type, new_threshold, sigma, noise, new_timewalk); } } } // // save pcd back to text file // ofstream out("pcd.sav"); for (map<unsigned int, PixelCoralClientUtils::PixelCalibData>::const_iterator ipcd = pcdmap.begin(); ipcd != pcdmap.end(); ++ipcd) { out << ipcd->first << endl; const PixelCoralClientUtils::PixelCalibData& pcd = ipcd->second; for (int i = 0; i<16; ++i) { const PixelCoralClientUtils::PixelCalibData::PixelChipSummaryData& pcsd = *pcd.getPixelChipSummaryData(i); out << "I" << pcsd.getChipID() << " " << pcsd.getThreshold(0) << " " << pcsd.getThresholdSigma(0) << " " << pcsd.getNoise(0) << " " << pcsd.getTimeWalk(0) << " " << pcsd.getThreshold(1) << " " << pcsd.getThresholdSigma(1) << " " << pcsd.getNoise(1) << " " << pcsd.getTimeWalk(1) << " " << pcsd.getThreshold(2) << " " << pcsd.getThresholdSigma(2) << " " << pcsd.getNoise(2) << " " << pcsd.getTimeWalk(2) << " " << pcsd.getQ2TotA(0) << " " << pcsd.getQ2TotE(0) << " " << pcsd.getQ2TotC(0) << " " << pcsd.getQ2TotA(2) << " " << pcsd.getQ2TotE(2) << " " << pcsd.getQ2TotC(2) << " " << pcsd.getTotP1() << " " << pcsd.getTotP2() << endl; } } out.close(); return 0; }
d076ab7b9904a5ec1a469e6ce8db06a26dfabe1f
20f8b4b25c5e689269ea1abd57b698e906cdc65a
/dspemul_mt/Semaphore.hpp
72785e1d6423d173c83edeec6e44d3010d5353cf
[]
no_license
bvarga92/dsp
801706dc9f74c5ed379abba6132a40d7ac3c2e54
50a0d5270ecec2ee5f6fea92ecc776f9634308c5
refs/heads/main
2023-08-31T03:07:29.758322
2023-08-30T09:25:06
2023-08-30T09:25:06
69,767,155
4
3
null
null
null
null
UTF-8
C++
false
false
823
hpp
Semaphore.hpp
#ifndef _SEMAPHORE_HPP_ #define _SEMAPHORE_HPP_ #include <mutex> #include <condition_variable> #include <chrono> class Semaphore{ private: std::mutex m; std::condition_variable cv; int cntr = 0; public: inline void notify(){ std::lock_guard<std::mutex> lock(m); cntr++; cv.notify_one(); } inline void wait(){ std::unique_lock<std::mutex> lock(m); cv.wait(lock, [&]{ return cntr > 0; }); cntr--; } inline bool wait_for_ms(int millis){ std::unique_lock<std::mutex> lock(m); bool finished = cv.wait_for(lock, std::chrono::milliseconds(millis), [&]{ return cntr > 0; }); if(finished) cntr--; return finished; } }; #endif
f988ef42fe155fb4aa4f225f9b4013440dfbc009
ba86aa615a1455fd79ac3732b77d07f935a04ae3
/c++程序/考试H.cpp
592a13bd02aa87e51b59b3246036b80e1692462f
[]
no_license
300I/jjj
ce0c64bd3a535e593ec38f8b498b77e5ec71e334
942c708fc5994ae75cf96e254dac00ba00b94e88
refs/heads/master
2020-07-10T01:20:30.600985
2019-09-16T12:50:09
2019-09-16T12:50:09
204,130,261
1
0
null
null
null
null
UTF-8
C++
false
false
122
cpp
考试H.cpp
#include<iostream> using namespace std; int main() { int n,m,k; cin>>n>>m; k=(m-1)+(n-1)*m; cout<<k<<endl; }
203f621f1e2a766f0d389732d5d86804336b0b71
b4c74a2dafcfe784e5c4cf8c1ef2605b21b90d5a
/objloader.cpp
b900e31746e3fb807215f9c358a4dc736a4cdcd1
[ "CC-BY-2.5" ]
permissive
aredsani/abhas
a40d6a7a5f651961d8ce432fab7231c44738953a
9011fe3c2ccf8e8c3d9cf98daa9ec28d4ededca7
refs/heads/master
2016-09-06T15:48:35.741134
2014-08-31T05:15:03
2014-08-31T05:15:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,928
cpp
objloader.cpp
#include <vector> #include <stdio.h> #include <cstring> #include <string> #include <vector> #include <iostream> using namespace std; #include<objloader.hpp> #include<shapes.hpp> bool loadOBJ(const char * path,vector<vertex> & out_vertices, vector<vertex> & out_uvs,vector<vertex> & out_normals){ printf("Loading OBJ file %s...\n", path); vector<unsigned int> vertexIndices, uvIndices, normalIndices; vector<vertex> temp_vertices; vector<vertex> temp_uvs; vector<vertex> temp_normals; FILE * file = fopen(path, "r"); if( file == NULL ){ printf("Unable to open the file!\n"); return false; } while( 1 ){ char lineHeader[128]; int res = fscanf(file, "%s", lineHeader); if (res == EOF) break; if(strcmp(lineHeader,"v")==0){ vertex temp; //cout<<"yeah"<<endl; double a; fscanf(file, "%f %f %f\n", &temp.position.x, &temp.position.y, &temp.position.z ); temp_vertices.push_back(temp); //cout<<"This is happning"<<endl; } else if(strcmp(lineHeader,"vt")==0){ vertex temp; fscanf(file, "%f %f\n", &temp.position.x, &temp.position.y ); temp.position.z=0; temp_uvs.push_back(temp); } else if ( strcmp( lineHeader, "vn" ) == 0 ){ vertex temp; fscanf(file, "%f %f %f\n", &temp.position.x, &temp.position.y, &temp.position.z ); temp_normals.push_back(temp); }else if ( strcmp( lineHeader, "f" ) == 0 ){ string vertex1, vertex2, vertex3; unsigned int vertexIndex[3], uvIndex[3], normalIndex[3]; int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2] ); if (matches != 9){ printf("File can't be read by our simple parser :-( Try exporting with other options\n"); return false; } vertexIndices.push_back(vertexIndex[0]); vertexIndices.push_back(vertexIndex[1]); vertexIndices.push_back(vertexIndex[2]); uvIndices .push_back(uvIndex[0]); uvIndices .push_back(uvIndex[1]); uvIndices .push_back(uvIndex[2]); normalIndices.push_back(normalIndex[0]); normalIndices.push_back(normalIndex[1]); normalIndices.push_back(normalIndex[2]); }else{ // Probably a comment, eat up the rest of the line char stupidBuffer[1000]; fgets(stupidBuffer, 1000, file); } } // For each triangle for( unsigned int v=0; v<vertexIndices.size(); v+=3 ){ // For each vertex of the triangle for ( unsigned int i=0; i<3; i+=1 ){ unsigned int vertexIndex = vertexIndices[v+i]; vertex tempVertex = temp_vertices[ vertexIndex-1 ]; unsigned int uvIndex = uvIndices[v+i]; vertex tempUV = temp_uvs[ uvIndex-1 ]; unsigned int normalIndex = normalIndices[v+i]; vertex tempNormal = temp_normals[normalIndex-1]; out_vertices.push_back(tempVertex); out_uvs .push_back(tempUV); out_normals .push_back(tempNormal); } } return true; }
2cc3f7c92b9a4008d31b9e15d80ea70235562ea3
36093cadb4c7bce04ddec1bc8b24a13636b63f38
/day2/57.cpp
a5ac2e60e0e3023b0f4cb5b34b3fe033d196b6e6
[]
no_license
justttmollly/practice
b6e1115ce813c4c67de94a0d77d9c52a7bd9ab85
24caa08da6827509d3308a7d5c18c27d4dcfa5af
refs/heads/master
2020-09-13T01:56:17.453932
2019-11-24T12:08:55
2019-11-24T12:08:55
222,626,768
0
0
null
null
null
null
UTF-8
C++
false
false
639
cpp
57.cpp
#include<iostream> using namespace std; int main(){ int day , month , year; cin >> day >> month >> year; if ( day < 1 || month > 12 || year < 0){ cout << "Invalid date"; return 0; } if ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){ if ( day > 0 && day < 32) cout << "Yes"; else cout << "No"; } else if ( month == 4 || month == 6 || month == 9 || month == 11 ){ if ( day > 0 && day < 31) cout << "Yes"; else cout << "No"; } else if ( month == 2){ if ( day > 0 && day < 29) cout << "Yes"; else cout << "No"; } return 0; }
de6a506fdf4fb76c309235e19907ed658e9e2b5e
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/components/sync_device_info/local_device_info_provider_impl_unittest.cc
46e55d4f1720c4afd6a2cea29213aafa152e3ab4
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
14,033
cc
local_device_info_provider_impl_unittest.cc
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync_device_info/local_device_info_provider_impl.h" #include "base/memory/ptr_util.h" #include "build/chromeos_buildflags.h" #include "components/sync/base/model_type.h" #include "components/sync/base/sync_util.h" #include "components/sync/protocol/device_info_specifics.pb.h" #include "components/sync/protocol/sync_enums.pb.h" #include "components/sync_device_info/device_info.h" #include "components/sync_device_info/device_info_sync_client.h" #include "components/version_info/version_string.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { namespace { const char kLocalDeviceGuid[] = "foo"; const char kLocalDeviceClientName[] = "bar"; const char kLocalDeviceManufacturerName[] = "manufacturer"; const char kLocalDeviceModelName[] = "model"; const char kLocalFullHardwareClass[] = "test_full_hardware_class"; const char kSharingVapidFCMRegistrationToken[] = "test_vapid_fcm_token"; const char kSharingVapidP256dh[] = "test_vapid_p256_dh"; const char kSharingVapidAuthSecret[] = "test_vapid_auth_secret"; const char kSharingSenderIdFCMRegistrationToken[] = "test_sender_id_fcm_token"; const char kSharingSenderIdP256dh[] = "test_sender_id_p256_dh"; const char kSharingSenderIdAuthSecret[] = "test_sender_id_auth_secret"; const sync_pb::SharingSpecificFields::EnabledFeatures kSharingEnabledFeatures[] = { sync_pb::SharingSpecificFields::CLICK_TO_CALL_V2}; using testing::NiceMock; using testing::NotNull; using testing::Return; class MockDeviceInfoSyncClient : public DeviceInfoSyncClient { public: MockDeviceInfoSyncClient() = default; MockDeviceInfoSyncClient(const MockDeviceInfoSyncClient&) = delete; MockDeviceInfoSyncClient& operator=(const MockDeviceInfoSyncClient&) = delete; ~MockDeviceInfoSyncClient() override = default; MOCK_METHOD(std::string, GetSigninScopedDeviceId, (), (const override)); MOCK_METHOD(bool, GetSendTabToSelfReceivingEnabled, (), (const override)); MOCK_METHOD(absl::optional<DeviceInfo::SharingInfo>, GetLocalSharingInfo, (), (const override)); MOCK_METHOD(DeviceInfo::PhoneAsASecurityKeyInfo::StatusOrInfo, GetPhoneAsASecurityKeyInfo, (), (const override)); MOCK_METHOD(absl::optional<std::string>, GetFCMRegistrationToken, (), (const override)); MOCK_METHOD(absl::optional<ModelTypeSet>, GetInterestedDataTypes, (), (const override)); MOCK_METHOD(bool, IsUmaEnabledOnCrOSDevice, (), (const override)); }; class LocalDeviceInfoProviderImplTest : public testing::Test { public: LocalDeviceInfoProviderImplTest() = default; ~LocalDeviceInfoProviderImplTest() override = default; void SetUp() override { provider_ = std::make_unique<LocalDeviceInfoProviderImpl>( version_info::Channel::UNKNOWN, version_info::GetVersionStringWithModifier("UNKNOWN"), &device_info_sync_client_); } void TearDown() override { provider_.reset(); } protected: void InitializeProvider() { InitializeProvider(kLocalDeviceGuid); } void InitializeProvider(const std::string& guid) { provider_->Initialize(guid, kLocalDeviceClientName, kLocalDeviceManufacturerName, kLocalDeviceModelName, kLocalFullHardwareClass, /*device_info_restored_from_store=*/nullptr); } DeviceInfo::PhoneAsASecurityKeyInfo SamplePhoneAsASecurityKeyInfo() { DeviceInfo::PhoneAsASecurityKeyInfo paask_info; paask_info.tunnel_server_domain = 123; paask_info.contact_id = {1, 2, 3, 4}; paask_info.secret = {5, 6, 7, 8}; paask_info.id = 321; paask_info.peer_public_key_x962 = {10, 11, 12, 13}; return paask_info; } testing::NiceMock<MockDeviceInfoSyncClient> device_info_sync_client_; std::unique_ptr<LocalDeviceInfoProviderImpl> provider_; }; #if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(LocalDeviceInfoProviderImplTest, UmaToggleFullHardwareClass) { InitializeProvider(kLocalDeviceGuid); // Tests that |full_hardware_class| maintains correct values on toggling UMA // from ON -> OFF, OFF -> ON ON_CALL(device_info_sync_client_, IsUmaEnabledOnCrOSDevice) .WillByDefault(Return(true)); EXPECT_EQ(provider_->GetLocalDeviceInfo()->full_hardware_class(), kLocalFullHardwareClass); ON_CALL(device_info_sync_client_, IsUmaEnabledOnCrOSDevice) .WillByDefault(Return(false)); EXPECT_EQ(provider_->GetLocalDeviceInfo()->full_hardware_class(), ""); ON_CALL(device_info_sync_client_, IsUmaEnabledOnCrOSDevice) .WillByDefault(Return(true)); EXPECT_EQ(provider_->GetLocalDeviceInfo()->full_hardware_class(), kLocalFullHardwareClass); } #else // NOT BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(LocalDeviceInfoProviderImplTest, UmaEnabledNonChromeOSHardwareClassEmpty) { // Tests that the |full_hardware_class| doesn't get updated when on // non-chromeos device. IsUmaEnabledOnCrOSDevice() returns false on non-cros. ON_CALL(device_info_sync_client_, IsUmaEnabledOnCrOSDevice) .WillByDefault(Return(false)); InitializeProvider(kLocalDeviceGuid); const DeviceInfo* local_device_info = provider_->GetLocalDeviceInfo(); // |kLocalFullHardwareClass| is reset after retrieving |local_device_info| EXPECT_EQ(local_device_info->full_hardware_class(), ""); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(LocalDeviceInfoProviderImplTest, GetLocalDeviceInfo) { ASSERT_EQ(nullptr, provider_->GetLocalDeviceInfo()); InitializeProvider(); const DeviceInfo* local_device_info = provider_->GetLocalDeviceInfo(); ASSERT_NE(nullptr, local_device_info); EXPECT_EQ("", local_device_info->full_hardware_class()); EXPECT_EQ(std::string(kLocalDeviceGuid), local_device_info->guid()); EXPECT_EQ(kLocalDeviceClientName, local_device_info->client_name()); EXPECT_EQ(kLocalDeviceManufacturerName, local_device_info->manufacturer_name()); EXPECT_EQ(kLocalDeviceModelName, local_device_info->model_name()); EXPECT_EQ(MakeUserAgentForSync(provider_->GetChannel()), local_device_info->sync_user_agent()); provider_->Clear(); ASSERT_EQ(nullptr, provider_->GetLocalDeviceInfo()); } TEST_F(LocalDeviceInfoProviderImplTest, GetSigninScopedDeviceId) { const std::string kSigninScopedDeviceId = "device_id"; EXPECT_CALL(device_info_sync_client_, GetSigninScopedDeviceId()) .WillOnce(Return(kSigninScopedDeviceId)); InitializeProvider(); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); EXPECT_EQ(kSigninScopedDeviceId, provider_->GetLocalDeviceInfo()->signin_scoped_device_id()); } TEST_F(LocalDeviceInfoProviderImplTest, SendTabToSelfReceivingEnabled) { ON_CALL(device_info_sync_client_, GetSendTabToSelfReceivingEnabled()) .WillByDefault(Return(true)); InitializeProvider(); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); EXPECT_TRUE( provider_->GetLocalDeviceInfo()->send_tab_to_self_receiving_enabled()); ON_CALL(device_info_sync_client_, GetSendTabToSelfReceivingEnabled()) .WillByDefault(Return(false)); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); EXPECT_FALSE( provider_->GetLocalDeviceInfo()->send_tab_to_self_receiving_enabled()); } TEST_F(LocalDeviceInfoProviderImplTest, SharingInfo) { ON_CALL(device_info_sync_client_, GetLocalSharingInfo()) .WillByDefault(Return(absl::nullopt)); InitializeProvider(); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); EXPECT_FALSE(provider_->GetLocalDeviceInfo()->sharing_info()); std::set<sync_pb::SharingSpecificFields::EnabledFeatures> enabled_features( std::begin(kSharingEnabledFeatures), std::end(kSharingEnabledFeatures)); absl::optional<DeviceInfo::SharingInfo> sharing_info = absl::make_optional<DeviceInfo::SharingInfo>( DeviceInfo::SharingTargetInfo{kSharingVapidFCMRegistrationToken, kSharingVapidP256dh, kSharingVapidAuthSecret}, DeviceInfo::SharingTargetInfo{kSharingSenderIdFCMRegistrationToken, kSharingSenderIdP256dh, kSharingSenderIdAuthSecret}, enabled_features); ON_CALL(device_info_sync_client_, GetLocalSharingInfo()) .WillByDefault(Return(sharing_info)); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); const absl::optional<DeviceInfo::SharingInfo>& local_sharing_info = provider_->GetLocalDeviceInfo()->sharing_info(); ASSERT_TRUE(local_sharing_info); EXPECT_EQ(kSharingVapidFCMRegistrationToken, local_sharing_info->vapid_target_info.fcm_token); EXPECT_EQ(kSharingVapidP256dh, local_sharing_info->vapid_target_info.p256dh); EXPECT_EQ(kSharingVapidAuthSecret, local_sharing_info->vapid_target_info.auth_secret); EXPECT_EQ(kSharingSenderIdFCMRegistrationToken, local_sharing_info->sender_id_target_info.fcm_token); EXPECT_EQ(kSharingSenderIdP256dh, local_sharing_info->sender_id_target_info.p256dh); EXPECT_EQ(kSharingSenderIdAuthSecret, local_sharing_info->sender_id_target_info.auth_secret); EXPECT_EQ(enabled_features, local_sharing_info->enabled_features); } TEST_F(LocalDeviceInfoProviderImplTest, ShouldPopulateFCMRegistrationToken) { InitializeProvider(); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); EXPECT_TRUE( provider_->GetLocalDeviceInfo()->fcm_registration_token().empty()); const std::string kFCMRegistrationToken = "token"; EXPECT_CALL(device_info_sync_client_, GetFCMRegistrationToken()) .WillRepeatedly(Return(kFCMRegistrationToken)); EXPECT_EQ(provider_->GetLocalDeviceInfo()->fcm_registration_token(), kFCMRegistrationToken); } TEST_F(LocalDeviceInfoProviderImplTest, ShouldPopulateInterestedDataTypes) { InitializeProvider(); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); EXPECT_TRUE(provider_->GetLocalDeviceInfo()->interested_data_types().Empty()); const ModelTypeSet kTypes = {BOOKMARKS}; EXPECT_CALL(device_info_sync_client_, GetInterestedDataTypes()) .WillRepeatedly(Return(kTypes)); EXPECT_EQ(provider_->GetLocalDeviceInfo()->interested_data_types(), kTypes); } TEST_F(LocalDeviceInfoProviderImplTest, ShouldKeepStoredInvalidationFields) { const std::string kFCMRegistrationToken = "fcm_token"; const ModelTypeSet kInterestedDataTypes = {BOOKMARKS}; DeviceInfo::PhoneAsASecurityKeyInfo paask_info = SamplePhoneAsASecurityKeyInfo(); auto device_info_restored_from_store = std::make_unique<DeviceInfo>( kLocalDeviceGuid, "name", "chrome_version", "user_agent", sync_pb::SyncEnums_DeviceType_TYPE_LINUX, DeviceInfo::OsType::kLinux, DeviceInfo::FormFactor::kDesktop, "device_id", "manufacturer", "model", "full_hardware_class", base::Time(), base::Days(1), /*send_tab_to_self_receiving_enabled=*/true, /*sharing_info=*/absl::nullopt, paask_info, kFCMRegistrationToken, kInterestedDataTypes); // |kFCMRegistrationToken|, |kInterestedDataTypes|, // and |paask_info| should be taken from |device_info_restored_from_store| // when |device_info_sync_client_| returns nullopt. provider_->Initialize(kLocalDeviceGuid, kLocalDeviceClientName, kLocalDeviceManufacturerName, kLocalDeviceModelName, kLocalFullHardwareClass, std::move(device_info_restored_from_store)); EXPECT_CALL(device_info_sync_client_, GetFCMRegistrationToken()) .WillRepeatedly(Return(absl::nullopt)); EXPECT_CALL(device_info_sync_client_, GetInterestedDataTypes()) .WillRepeatedly(Return(absl::nullopt)); EXPECT_CALL(device_info_sync_client_, GetPhoneAsASecurityKeyInfo()) .WillOnce(Return(DeviceInfo::PhoneAsASecurityKeyInfo::NotReady())); const DeviceInfo* local_device_info = provider_->GetLocalDeviceInfo(); EXPECT_EQ(local_device_info->interested_data_types(), kInterestedDataTypes); EXPECT_EQ(local_device_info->fcm_registration_token(), kFCMRegistrationToken); EXPECT_TRUE( local_device_info->paask_info()->NonRotatingFieldsEqual(paask_info)); // `GetPhoneAsASecurityKeyInfo` can erase the field too. EXPECT_CALL(device_info_sync_client_, GetPhoneAsASecurityKeyInfo()) .WillOnce(Return(DeviceInfo::PhoneAsASecurityKeyInfo::NoSupport())); const DeviceInfo* local_device_info2 = provider_->GetLocalDeviceInfo(); EXPECT_FALSE(local_device_info2->paask_info().has_value()); } TEST_F(LocalDeviceInfoProviderImplTest, PhoneAsASecurityKeyInfo) { ON_CALL(device_info_sync_client_, GetPhoneAsASecurityKeyInfo()) .WillByDefault(Return(DeviceInfo::PhoneAsASecurityKeyInfo::NoSupport())); InitializeProvider(); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); EXPECT_FALSE(provider_->GetLocalDeviceInfo()->paask_info()); DeviceInfo::PhoneAsASecurityKeyInfo paask_info = SamplePhoneAsASecurityKeyInfo(); ON_CALL(device_info_sync_client_, GetPhoneAsASecurityKeyInfo()) .WillByDefault(Return(paask_info)); ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); const absl::optional<DeviceInfo::PhoneAsASecurityKeyInfo>& result_paask_info = provider_->GetLocalDeviceInfo()->paask_info(); ASSERT_TRUE(result_paask_info); EXPECT_EQ(paask_info.tunnel_server_domain, result_paask_info->tunnel_server_domain); EXPECT_EQ(paask_info.contact_id, result_paask_info->contact_id); EXPECT_EQ(paask_info.secret, result_paask_info->secret); EXPECT_EQ(paask_info.id, result_paask_info->id); EXPECT_EQ(paask_info.peer_public_key_x962, result_paask_info->peer_public_key_x962); } } // namespace } // namespace syncer
26ab4cdfd8aae4f25628e76571c9aff4deb6dbbb
22c55209918a6c0f758f6d553fc77e0f740e2913
/bmp.h
a009de619442565319199c345ed7326e3abb96a0
[]
no_license
sapphire-al2o3/hdr_loader
dff9a495a7ae9cb985ba4b7cb7b4a356b8f4ae38
6a2bc161f17d396641f9843addb129a32760b802
refs/heads/master
2020-04-22T05:39:44.793544
2019-02-27T17:19:08
2019-02-27T17:19:08
170,163,663
0
1
null
null
null
null
UTF-8
C++
false
false
2,684
h
bmp.h
#ifndef _BMP_H #define _BMP_H #include <stdio.h> #include "image.h" struct BGR { unsigned char b; unsigned char g; unsigned char r; }; template <typename T> int SaveBitmap(const char *fileName, const Image<T> *src); #pragma pack(1) struct BitmapFileHeader { unsigned short bfType; // "BM" unsigned int bfSize; // ファイルサイズ unsigned short bfReserved1; // 0 unsigned short bfReserved2; // 0 unsigned int bfOffBits; // 画像データまでのオフセット }; struct BitmapInfoHeader { unsigned int biSize; // 構造体のサイズ long biWidth; // 幅 long biHeight; // 高さ unsigned short biPlanes; // 1 unsigned short biBitCount; // ビット数 unsigned int biCompression; // 圧縮方式 unsigned int biSizeImage; // 画像データのサイズ long biXPelsPerMeter; // 水平解像度 long biYPelsPerMeter; // 垂直解像度 unsigned int biClrUsed; // 色数 unsigned int biClrImportant; // 重要な色数 }; #pragma pack() inline void WriteLine24(const BGR *src, FILE *fp, int length) { fwrite(src, sizeof(BGR), length, fp); } /* * Save Bitmap file by 24 bit */ template <typename T> int SaveBitmap(const char *fileName, const Image<T>& src) { int i, linemod, linebyte; BitmapFileHeader head; BitmapInfoHeader info; FILE *fp; if(src.lines == nullptr) { printf("%s save failed!\n", fileName); return 0; } linemod = src.width * 3 % 4; if(linemod == 0) linebyte = src.width * 3; else linebyte = src.width * 3 + (4 - linemod); // write bitmap file header head.bfType = 'B' | 'M' << 8; head.bfSize = sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + linebyte * src.height; head.bfReserved1 = 0; head.bfReserved2 = 0; head.bfOffBits = sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader); // write bitmap info header info.biSize = sizeof(BitmapInfoHeader); info.biWidth = src.width; info.biHeight = src.height; info.biPlanes = 1; info.biBitCount = 24; info.biCompression = 0; info.biSizeImage = linebyte * src.height; info.biXPelsPerMeter = 0; info.biYPelsPerMeter = 0; info.biClrUsed = 0; info.biClrImportant= 0; fopen_s(&fp, fileName, "wb"); if(fileName == nullptr || fp == nullptr) return 0; // write header fwrite(&head, sizeof(BitmapFileHeader), 1, fp); fwrite(&info, sizeof(BitmapInfoHeader), 1, fp); const int padding = 0; // write data for(i = 0; i < src.height; i++) { WriteLine24(src.lines[info.biHeight - i - 1], fp, info.biWidth); // 4byteの境界にあわせて0を書き込む if(linemod != 0) fwrite(&padding, 4 - linemod, 1, fp); } fclose(fp); return 1; } #endif //_BMP_H
c0b40aedb4e57ef60f6b7a3f0c5ec835ff50b513
05921d088a80fd20cc8af38a24603ea97458f313
/src/parse.cpp
00e806877f43f5c5a24935ada2ea5b0e0d0bdeb8
[]
no_license
Delta-in-hub/C--
55b9a222f1526f36369c2b44f56038ff15831c11
74456eef351d7bb28659d73616187077d22593b6
refs/heads/master
2023-06-24T17:32:21.006945
2021-07-20T08:22:39
2021-07-20T08:22:39
381,202,516
1
1
null
null
null
null
UTF-8
C++
false
false
39,700
cpp
parse.cpp
#include "parse.h" static std::vector<Var*> paraVar; static int pos = 0; // tokenArr pos Program* prog = nullptr; Env *env = nullptr, *global = nullptr; void translation_unit(); Node* fun_declarator(); std::vector<Type*>* parameter_list(); void parameter_declaration(std::vector<Type*>* arr); Type* type_specifier(); Type* struct_declaration(Type* base); void struct_declaration_list(Type* base); Type* pointer(Type* base); Node* l_expression(); std::vector<Node*>* expression_list(); Node* unary_operator(); Node* selection_statement(); Node* iteration_statement(); std::vector<Var*>* declaration_list(bool flag); void declaration(std::vector<Var*>* arr, bool flag); void declarator_list(std::vector<Var*>* arr); Var* declarator(); Node* declaratorInit(); Node* constant_expression(); Node* compound_statement(); std::vector<Node*>* statement_list(); Node* statement(); Node* assignment_statement(); Node* expression(); Node* logical_and_expression(); Node* equality_expression(); Node* relational_expression(); Node* additive_expression(); Node* multiplicative_expression(); Node* unary_expression(); Node* postfix_expression(); Node* primary_expression(); //希望当前token类型是tokentype //否的话,直接报错,结束程序 void expect(const std::string& tokentype, const std::string& error = "Universal Error") { if (debugMode) { if (not(pos >= 0 and pos < int(tokenArr.size()))) { std::printf("%d out of range of TokenArr", pos); getchar(); exit(1); } if (tokenType.find(tokentype) == tokenType.end()) { std::printf("%s does not in tokenType unordreed map", tokentype.c_str()); getchar(); exit(1); } } auto&& t = tokenArr[pos]; if (t.type == tokenType.at(tokentype)) { pos++; return; } std::string s("Expect "); s += tokentype; errorParse(t, s); } //希望当前token类型是tokentype //是,pos++,返回true //否,返回false //向前展望一个符号 bool consume(const std::string& tokentype) { if (debugMode) { if (not(pos >= 0 and pos < int(tokenArr.size()))) { std::printf("%d out of range of TokenArr", pos); getchar(); exit(1); } if (tokenType.find(tokentype) == tokenType.end()) { std::printf("%s does not in tokenType unordreed map", tokentype.c_str()); getchar(); exit(1); } } auto&& t = tokenArr[pos]; if (t.type != tokenType.at(tokentype)) return false; pos++; return true; } Token& nowToken(int p = 0) { if (debugMode) { if (not(pos + p >= 0 and pos + p < int(tokenArr.size()))) { std::printf("%d out of range of TokenArr", pos); getchar(); exit(1); } } return tokenArr.at(pos + p); } std::string nowName(int p = 0) { return std::string(nowToken(p).start, nowToken(p).end); } /* 节点相关 */ //进入新的作用域 void initScope(Env* prev) { env = new Env{}; env->prev = prev; } //离开当前作用域 void exitScope() { auto t = env; env = env->prev; if (env == nullptr) env = t; else delete t; } Var* findVar(const std::string& name) { auto t = env; while (t) { if (t->vars.find(name) != t->vars.end()) return t->vars.at(name); else t = t->prev; } errorParse(nowToken(), "undefined variable"); return nullptr; } Type* findStruct(const std::string& name) { auto t = env; while (t) { if (t->structs.find(name) != t->structs.end()) return t->structs.at(name); else t = t->prev; } errorParse(nowToken(), "undefined struct"); return nullptr; } Function* findFuncion(const std::string& name) { for (auto&& i : prog->funcs) { if (i->name == name) return i; } errorParse(nowToken(), "undefined Function"); return nullptr; } Node* newNode() { auto t = new Node{}; t->name = std::string(nowToken().start, nowToken().end); t->token = &nowToken(); return t; } void addVar(Var* v) { if (env->vars.find(v->name) != env->vars.end()) { errorParse(nowToken(), "Multi Variable Definition"); } else { env->vars[v->name] = v; } } void addStruct(Type* ty, const std::string& name) { if (env->vars.find(name) != env->vars.end() or env->structs.find(name) != env->structs.end()) { errorParse(nowToken(), "Multi Struct Definition"); } else { env->structs[name] = ty; } } void addFunction(Function* f) { for (auto&& i : prog->funcs) { if (i->name == f->name) errorParse(nowToken(-1), "Multi Function Definition"); } prog->funcs.push_back(f); } // ta,tb是否为同一类型 bool isSameType(const Type* ta, const Type* tb) { //若类型相同,能有释放掉一个内存? if (ta == tb) return true; switch (ta->ty) { case VarType::ARY: if (tb->ty != ARY or ta->len != tb->len) return false; return isSameType(ta->ary_of, ta->ary_of); break; case VarType::BOOL: if (tb->ty == BOOL) return true; else return false; break; case VarType::CHAR: if (tb->ty == CHAR) return true; else return false; break; case VarType::DOUBLE: if (tb->ty == DOUBLE) return true; else return false; break; // case VarType::FUNC: // break; case VarType::INT: if (tb->ty == INT) return true; else return false; break; case VarType::PTR: if (tb->ty != PTR) return false; return isSameType(ta->ptr_to, tb->ptr_to); break; case VarType::STRUCT: if (tb->ty != STRUCT) return false; return ta->members == tb->members; //存疑 break; case VarType::VOID: if (tb->ty == VOID) return true; else return false; break; default: errorParse(nowToken(), "Type Not Found"); break; } return false; } // tb进行隐形类型转换后是否和ta类型相同 bool isMatchType(const Type* ta, const Type* tb) { if (ta == tb) return true; switch (ta->ty) { case VarType::ARY: if (tb->ty != ARY or ta->len != tb->len) return false; return isSameType(ta->ary_of, ta->ary_of); break; case VarType::BOOL: if (tb->ty == BOOL or tb->ty == CHAR or tb->ty == INT) return true; else return false; break; case VarType::CHAR: if (tb->ty == CHAR or tb->ty == INT) return true; else return false; break; case VarType::DOUBLE: if (tb->ty == DOUBLE or tb->ty == INT or tb->ty == CHAR) return true; else return false; break; // case VarType::FUNC: // break; case VarType::INT: if (tb->ty == INT or tb->ty == CHAR or tb->ty == DOUBLE) return true; else return false; break; case VarType::PTR: if (tb->ty == ARY) { if (isSameType(ta->ptr_to, tb->ary_of)) return true; else return false; } else if (tb->ty != PTR) return false; else return isSameType(ta->ptr_to, tb->ptr_to); break; case VarType::STRUCT: if (tb->ty != STRUCT) return false; return ta->members == tb->members; //存疑 break; case VarType::VOID: if (tb->ty == VOID) return true; else return false; break; default: errorParse(nowToken(), "Type Not Found"); break; } return false; } bool isCalAble(Type* ta) { switch (ta->ty) { case VarType::ARY: case VarType::BOOL: case VarType::VOID: case VarType::STRUCT: return false; break; case VarType::PTR: case VarType::DOUBLE: case VarType::INT: case VarType::CHAR: return true; default: break; } return false; } Type* topType(Type* ta, Type* tb) { if (ta->ty == PTR) { if (tb->ty == INT) return ta; else return nullptr; } if (tb->ty == PTR) { if (ta->ty == INT) return tb; else return nullptr; } if (ta->ty == DOUBLE) return ta; if (tb->ty == DOUBLE) return tb; if (ta->ty == INT) return ta; if (tb->ty == INT) return tb; return nullptr; } // Var* findVar(const std::string& name); // Type* struct_declaration(Type* base); /* 递归下降 */ void parse() { initScope(nullptr); global = env; prog = new Program{}; while (nowToken().type != "TK_EOF") { translation_unit(); } if (debugMode) { std::cout << "Complier done" << std::endl; } } /* translation_unit | type_specifier fun_declarator compound_statement | type_specifier declarator_list ';' ; */ void translation_unit() { auto t = type_specifier(); // if (nowToken().type != tokenType.at("id")) // { // errorParse(nowToken(), "Expect IDENTIFIER"); // } if (nowToken(1).type == tokenType.at("(") and nowToken().type == tokenType.at("id")) { Function* f = new Function{}; auto fun = fun_declarator(); f->name = fun->name; f->params = fun->params; f->returnType = t; f->paraName = new std::vector<std::string>; for (auto&& i : paraVar) { f->paraName->push_back(i->name); } /* //变量名视作为变量的一种 auto nv = new Var{}; nv->name = fun->name; auto ny = new Type{}; ny->ty = FUNC; nv->ty = ny; addVar(nv); */ // expect(")"); addFunction(f); // prog->funcs.push_back(f); // for recursive f->compound = compound_statement(); } else { std::vector<Var*>* arr = new std::vector<Var*>{}; /* before:struct A{}; error after:struct A{}; done */ if (consume(";")) --pos; else declarator_list(arr); expect(";"); for (auto&& i : *arr) { if (i->isArray) { auto ty2 = new Type{}; ty2->ty = VarType::ARY; ty2->ary_of = t; ty2->len = i->arrLen; ty2->size = i->arrLen * (t->size); i->ty = ty2; } else { i->ty = t; } addVar(i); prog->gvars.push_back(i); if (i->data != nullptr) { if (not isMatchType(i->ty, i->data->ctype)) { errorParse(nowToken(-1), "Unmatched type in Initialization"); } } } } } /* 返回函数名(形参列表仅类型) 返回值类型,函数体待填充 fun_declarator : IDENTIFIER '(' parameter_list ')' | IDENTIFIER '(' ')' ; */ Node* fun_declarator() { /* 1.node->type = ND_FUNC 2.node->name = funName 3.params列表,此时将数组退化为指针Type */ auto t = newNode(); t->type = ND_FUNC; std::string name(nowToken().start, nowToken().end); t->name = name; expect("id"); expect("("); if (consume(")")) { t->params = new std::vector<Type*>{}; } else { t->params = parameter_list(); expect(")"); } return t; } /* parameter_list : parameter_declaration | parameter_list ',' parameter_declaration ; */ std::vector<Type*>* parameter_list() { std::vector<Type*>* arr = new std::vector<Type*>{}; parameter_declaration(arr); while (consume(",")) { parameter_declaration(arr); } return arr; } /* parameter_declaration : type_specifier declarator ; */ void parameter_declaration(std::vector<Type*>* arr) { auto ty = type_specifier(); auto t = declarator(); if (t->isArray) { auto nty = new Type{}; nty->size = 8; nty->ty = VarType::PTR; nty->ptr_to = ty; t->ty = nty; } else { t->ty = ty; } arr->push_back(t->ty); paraVar.push_back(t); } /* type_specifier : VOID pointer? | INT pointer? | FLOAT pointer? | char pointer? | double pointer? | bool pointer? | struct-declaration pointer? ; */ Type* voidType() { static Type* t = nullptr; if (t == nullptr) { t = new Type{}; t->size = 1; t->ty = VarType::VOID; } return t; } Type* intType() { static Type* t = nullptr; if (t == nullptr) { t = new Type{}; t->size = 4; t->ty = VarType::INT; } return t; } Type* doubleType() { static Type* t = nullptr; if (t == nullptr) { t = new Type{}; t->size = 8; t->ty = VarType::DOUBLE; } return t; } Type* charType() { static Type* t = nullptr; if (t == nullptr) { t = new Type{}; t->size = 1; t->ty = VarType::CHAR; } return t; } Type* boolType() { static Type* t = nullptr; if (t == nullptr) { t = new Type{}; t->size = 1; t->ty = VarType::BOOL; } return t; } Type* type_specifier() { Type* t = nullptr; if (consume("void")) { t = voidType(); } else if (consume("int")) { t = intType(); } else if (consume("float") or consume("double")) { t = doubleType(); } else if (consume("char")) { t = charType(); } else if (consume("_Bool")) { t = boolType(); } else if (consume("struct")) { --pos; t = new Type{}; t = struct_declaration(t); } else errorParse(nowToken(), "Expect type_specifier"); if (consume("*")) { --pos; t = pointer(t); } return t; } /* struct-declaration : : 'struct' IDENTIFIER //声明 | 'struct' IDENTIFIER? '{' struct-declaration-list '}' //定义 */ Type* struct_declaration(Type* base) { /* 1.VarType::STRUCT 2.填充members 3.计算size */ expect("struct"); base->ty = VarType::STRUCT; std::string name; if (consume("id")) { --pos; name = std::string(nowToken().start, nowToken().end); ++pos; } if (consume("{")) //定义 { base->size = 0; struct_declaration_list(base); addStruct(base, name); expect("}"); } else //声明 { if (name.empty()) errorParse(nowToken(), "Expect struct name"); else return findStruct(name); } return base; } /* struct-declaration-list : : declaration_list ; */ void struct_declaration_list(Type* base) { auto arr = declaration_list(false); for (auto&& i : *arr) { base->size += i->size; base->members[i->name] = i->ty; } } /* pointer : | '*' | '*' pointer */ Type* pointer(Type* base) { expect("*"); auto t = new Type{}; t->size = 8; t->ty = VarType::PTR; t->ptr_to = base; while (consume("*")) { --pos; t = pointer(t); } return t; } /* l_expression : IDENTIFIER | IDENTIFIER '[' expression ']' | IDENTIFIER '.' IDENTIFIER | * l_expression ; */ Node* l_expression() { if (consume("*")) { auto t = newNode(); t->type = NodeType::ND_DEREF; //类型检查在之后 t->lhs = l_expression(); if (t->lhs->ctype->ty != VarType::PTR) errorParse(nowToken(), "invalid type argument of unary *"); t->ctype = t->lhs->ctype->ptr_to; return t; } Node* t = newNode(); std::string name(nowToken().start, nowToken().end); expect("id"); if (consume("[")) { t->var = findVar(t->name); if (t->var->ty->ty != ARY) errorParse(nowToken(-2), name + " is not array type"); t->expresson = expression(); expect("]"); t->type = ND_ARRDEREF; t->ctype = t->var->ty->ary_of; } else if (consume(".")) { t->type = ND_DOT; t->var = findVar(name); if (t->var->ty->ty != VarType::STRUCT) { errorParse(nowToken(), name + " is not a struct"); } std::string name2(nowToken().start, nowToken().end); expect("id"); if (t->var->ty->members.find(name2) == t->var->ty->members.end()) { errorParse(nowToken(), name2 + " is not a member of " + name + " struct"); } t->name = name2; t->ctype = t->var->ty->members[name2]; } else { t->type = ND_VARREF; t->var = findVar(t->name); t->ctype = t->var->ty; } return t; } /* Function call 实参(argument) std::vector<Node*>* args; expression_list : expression | exprssion_list ',' expression */ std::vector<Node*>* expression_list() { auto v = new std::vector<Node*>{}; auto t = expression(); v->push_back(t); while (consume(",")) { t = expression(); v->push_back(t); } return v; } /* unary_operator : "-" "!" "&" ; */ Node* unary_operator() { auto n = newNode(); if (consume("-")) { n->type = ND_NEG; } else if (consume("!")) { n->type = ND_NOT; } else if (consume("&")) { n->type = ND_ADDR; } else { errorParse(nowToken(), "Expect unary operator"); } return n; } /* selection_statement : IF '(' expression ')' statement ELSE statement | IF '(' expression ')' statement ; */ Node* selection_statement() { auto n = newNode(); n->type = ND_IF; expect("if"); expect("("); n->condition = expression(); if (not isMatchType(boolType(), n->condition->ctype)) { errorParse(nowToken(), "Condition expression must be boolean"); } expect(")"); n->then = statement(); if (consume("else")) { n->els = statement(); } return n; } /* iteration_statement : WHILE '(' expression ')' statement | FOR '(' expression ';' expression ';' expression ')' statement //modified this production ; */ Node* iteration_statement() { auto n = newNode(); if (consume("while")) { n->type = ND_DO_WHILE; expect("("); n->condition = expression(); expect(")"); if (not isMatchType(boolType(), n->condition->ctype)) { errorParse(nowToken(), "Condition expression must be boolean"); } n->body = statement(); } else if (consume("for")) { n->type = ND_FOR; expect("("); n->init = expression(); expect(";"); n->condition = expression(); if (not isMatchType(boolType(), n->condition->ctype)) { errorParse(nowToken(), "Condition expression must be boolean"); } expect(";"); n->inc = expression(); expect(")"); n->body = statement(); } else errorParse(nowToken(), "Expect while or for"); return n; } /* 返回包含所有变量的vector declaration_list : declaration | declaration_list declaration ; */ std::vector<Var*>* declaration_list(bool flag) { std::vector<Var*>* arr = new std::vector<Var*>{}; declaration(arr, flag); while (consume("void") or consume("char") or consume("_Bool") or consume("int") or consume("double") or consume("struct")) { --pos; declaration(arr, flag); } return arr; } /* 局部变量定义 declaration : type_specifier declarator_list ';' ; */ void declaration(std::vector<Var*>* arr, bool flag) { auto ty = type_specifier(); auto be = arr->size(); declarator_list(arr); expect(";"); for (; be != arr->size(); be++) { auto&& i = (*arr)[be]; if (i->isArray) { auto ty2 = new Type{}; ty2->ty = VarType::ARY; ty2->ary_of = ty; ty2->len = i->arrLen; ty2->size = i->arrLen * ty->size; i->ty = ty2; } else { i->ty = ty; } if (flag) //临时变量要立即加入符号表,struct中不用加 addVar(i); if (i->data != nullptr) { if (not isMatchType(i->ty, i->data->ctype)) { errorParse(nowToken(-1), "Unmatched type in Initialization"); } } } } /* 返回 说明符vector ,其他信息待填充 仅包含变量名,是否为数组/数组长度, declarator_list : declarator | declarator_list ',' declarator ; */ void declarator_list(std::vector<Var*>* arr) { auto t = declarator(); arr->push_back(t); while (consume(",")) { t = declarator(); arr->push_back(t); } } //--------------wyd的分割线---------------- /* declarator : IDENTIFIER declaratorInit? | IDENTIFIER '[' constant_expression ']' ; */ Var* declarator() { auto t = new Var{}; t->name = std::string(nowToken().start, nowToken().end); t->isArray = false; expect("id"); if (consume("[")) { t->isArray = true; auto tmp = constant_expression(); if (tmp->type == ND_DNUM) { errorParse(nowToken(), "Length of array can not be float number"); } t->arrLen = tmp->val; expect("]"); } else if (consume("=")) { --pos; t->data = declaratorInit(); } return t; } /* declaratorInit : '=' expression */ Node* declaratorInit() { expect("="); return expression(); } /* constant_expression : INT_CONSTANT : DOUBLE_CONSTANT ; */ Node* constant_expression() { auto t = newNode(); if (consume("num")) { t->type = ND_NUM; t->val = nowToken(-1).val; } else if (consume("dnum")) { t->type = ND_DNUM; t->dval = nowToken(-1).dval; } else { errorParse(nowToken(), "Expect unary_operator"); } return t; } /* compound_statement : '{' '}' | '{' statement_list '}' | '{' declaration_list statement_list '}' ; */ Node* compound_statement() { expect("{"); initScope(env); for (auto&& i : paraVar) { addVar(i); } paraVar.clear(); //!!内存泄露 auto t = newNode(); t->type = ND_COMP_STMT; while (not consume("}")) { if (consume("return") || consume("{") || consume("if") || consume("while") || consume("for") || consume(";") || consume("id") || consume("*")) { --pos; t->statementList = statement_list(); } else if (consume("void") || consume("char") || consume("_Bool") || consume("int") || consume("double") || consume("struct")) { --pos; auto decl = declaration_list(true); //局部变量 if (t->statementList == nullptr) t->statementList = new std::vector<Node*>; for (auto&& i : *decl) { auto nd = new Node{}; nd->type = ND_VARDEF; nd->ctype = i->ty; nd->name = i->name; nd->var = i; t->statementList->push_back(nd); } if (consume("}")) { --pos; } else { auto arr = statement_list(); //函数调用 for (auto&& i : *arr) { t->statementList->push_back(i); } delete arr; } } else { errorParse(nowToken(), "Expect statement or declaration"); } } exitScope(); return t; } /* 返回语句的vector statement_list : statement | statement_list statement ; */ std::vector<Node*>* statement_list() { auto v = new std::vector<Node*>{}; auto t = statement(); v->push_back(t); while (consume("return") || consume("{") || consume("if") || consume("while") || consume("for") || consume(";") || consume("id") || consume("*")) { pos--; t = statement(); v->push_back(t); } return v; } /* statement : compound_statement //作用域嵌套 {{}} | selection_statement // if | iteration_statement //while for | assignment_statement //赋值,空语句 | 'RETURN' expression ';' ; */ Node* statement() { if (consume("{")) { --pos; return compound_statement(); } else if (consume("if")) { --pos; return selection_statement(); } else if (consume("while") || consume("for")) { --pos; return iteration_statement(); } else if (consume(";") || consume("id") || consume("*") || consume("(")) { --pos; return assignment_statement(); } else if (consume("return")) { // --pos; auto t = newNode(); t->type = NodeType::ND_RETURN; t->expresson = expression(); expect(";"); t->ctype = t->expresson->ctype; if (not isMatchType(prog->funcs.back()->returnType, t->expresson->ctype)) { errorParse(nowToken(-1), "Error return type"); } return t; } else { errorParse(nowToken(), "Expect statement"); } return nullptr; } /* 单行语句 assignment_statement : ';' ; postfix_expression ";" // | l_expression '=' expression ';' */ Node* assignment_statement() { if (consume(";")) { auto t = newNode(); t->type = NodeType::ND_NULL; t->ctype = voidType(); t->expresson = nullptr; //表示空语句 return t; } auto t = postfix_expression(); expect(";"); return t; } /* expression : logical_and_expression | expression OR_OP logical_and_expression ; */ Node* expression() { auto t = logical_and_expression(); int flag = 0; while (consume("||")) { auto orll = newNode(); orll->type = ND_LOGOR; orll->ctype = boolType(); if (flag == 0) { orll->lhs = t; orll->rhs = logical_and_expression(); t = orll; // flag = (flag + 1) % 2; //涉及到短路求值,运算顺序不能变 } else if (flag == 1) { orll->lhs = logical_and_expression(); orll->rhs = t; t = orll; flag = (flag + 1) % 2; } if ((not isMatchType(boolType(), orll->lhs->ctype)) or (not isMatchType(boolType(), orll->rhs->ctype))) { errorParse(nowToken(), "invalid type argument of || "); } } return t; } //--------------wyd的分割线---------------- //--------------cc的分割线---------------- /*logical_and_expression : equality_expression | logical_and_expression AND_OP equality_expression ; */ Node* logical_and_expression() { auto t = equality_expression(); int flag = 0; while (consume("&&")) { auto orll = newNode(); orll->type = ND_LOGAND; orll->ctype = boolType(); if (flag == 0) { orll->lhs = t; orll->rhs = equality_expression(); t = orll; // flag = (flag + 1) % 2; } else if (flag == 1) { orll->lhs = equality_expression(); orll->rhs = t; t = orll; flag = (flag + 1) % 2; } if ((not isMatchType(boolType(), orll->lhs->ctype)) or (not isMatchType(boolType(), orll->rhs->ctype))) { errorParse(nowToken(), "invalid type argument of && "); } } return t; } /* equality_expression //等式 : relational_expression | equality_expression EQ_OP relational_expression | equality_expression NE_OP relational_expression ; */ Node* equality_expression() { auto t = relational_expression(); int flag = 0; while (consume("==") || consume("!=")) { auto orll = newNode(); orll->ctype = boolType(); pos--; if (consume("==")) { orll->type = ND_EQ; } else if (consume("!=")) { orll->type = ND_NE; } if (flag == 0) { orll->lhs = t; orll->rhs = relational_expression(); t = orll; // flag = (flag + 1) % 2; } else if (flag == 1) { orll->lhs = relational_expression(); orll->rhs = t; t = orll; flag = (flag + 1) % 2; } if (not isMatchType(orll->lhs->ctype, orll->rhs->ctype)) { errorParse(nowToken(), "invalid type argument of ==/!= "); } } return t; } /* relational_expression //关系表达式 : additive_expression | relational_expression '<' additive_expression | relational_expression '>' additive_expression | relational_expression LE_OP additive_expression | relational_expression GE_OP additive_expression ; */ Node* relational_expression() { auto t = additive_expression(); int flag = 0; while (consume("<") || consume(">") || consume("<=") || consume(">=")) { auto orll = newNode(); orll->ctype = boolType(); pos--; if (consume("<")) { orll->type = ND_LESS; } else if (consume(">")) { orll->type = ND_GREAT; } else if (consume("<=")) { orll->type = ND_LE; } else if (consume(">=")) { orll->type = ND_GE; } if (flag == 0) { orll->lhs = t; orll->rhs = additive_expression(); t = orll; // flag = (flag + 1) % 2; } else if (flag == 1) { orll->lhs = additive_expression(); orll->rhs = t; t = orll; flag = (flag + 1) % 2; } if (not isMatchType(orll->lhs->ctype, orll->rhs->ctype)) { errorParse(nowToken(), "invalid type argument of < <= > >= "); } } return t; } /* additive_expression //加减 : multiplicative_expression | additive_expression '+' multiplicative_expression | additive_expression '-' multiplicative_expression ; */ Node* additive_expression() { auto t = multiplicative_expression(); int flag = 0; while (consume("+") || consume("-")) { auto orll = newNode(); pos--; if (consume("+")) { orll->type = ND_ADD; } else if (consume("-")) { orll->type = ND_SUB; } if (flag == 0) { orll->rhs = multiplicative_expression(); orll->lhs = t; t = orll; // flag = (flag + 1) % 2; } else if (flag == 1) { orll->lhs = multiplicative_expression(); orll->rhs = t; t = orll; flag = (flag + 1) % 2; } if (not(isCalAble(orll->lhs->ctype) and isCalAble(orll->rhs->ctype))) { errorParse(nowToken(), "invalid type argument of + / - "); } orll->ctype = topType(orll->lhs->ctype, orll->rhs->ctype); if (orll->ctype == nullptr) { errorParse(nowToken(), "invalid type argument of + / - "); } } return t; } /* multiplicative_expression //乘除 : unary_expression | multiplicative_expression '*' unary_expression | multiplicative_expression '/' unary_expression ; */ Node* multiplicative_expression() { auto t = unary_expression(); int flag = 0; while (consume("*") || consume("/") || consume("%")) { auto orll = newNode(); pos--; if (consume("*")) { orll->type = ND_MUL; } else if (consume("/")) { orll->type = ND_DIV; } else if (consume("%")) { orll->type = ND_MOD; } if (flag == 0) { orll->rhs = unary_expression(); orll->lhs = t; t = orll; // flag = (flag + 1) % 2; } else if (flag == 1) { orll->lhs = unary_expression(); orll->rhs = t; t = orll; flag = (flag + 1) % 2; } if (not(isCalAble(orll->lhs->ctype) and isCalAble(orll->rhs->ctype))) { errorParse(nowToken(), "invalid type argument of * / % "); } orll->ctype = topType(orll->lhs->ctype, orll->rhs->ctype); if (orll->ctype == nullptr) { errorParse(nowToken(), "invalid type argument of * / % "); } } return t; } /* unary_expression //一元操作符 : postfix_expression | unary_operator postfix_expression ; */ Node* unary_expression() { if (consume("-") or consume("!") or consume("&")) //取地址符 & { pos--; auto t = unary_operator(); // wait for & and type t->lhs = postfix_expression(); Type* nt = nullptr; switch (t->type) { case ND_NEG: //- case ND_NOT: //! t->ctype = t->lhs->ctype; break; case ND_ADDR: //& nt = new Type{}; nt->size = 8; nt->ty = VarType::PTR; nt->ptr_to = t->lhs->ctype; t->ctype = nt; break; default: break; } if (not isCalAble(t->lhs->ctype)) { errorParse(nowToken(), "invalid type argument of unary expression"); } return t; } else { return postfix_expression(); } } /* postfix_expression : primary_expression | IDENTIFIER '(' ')' //函数调用 | IDENTIFIER '(' expression_list ')' //函数调用 ; */ Node* postfix_expression() { if (nowToken().type == tokenType.at("id") and nowToken(1).type == tokenType.at("(")) { auto t = newNode(); t->type = ND_CALL; auto name = nowName(); t->fun = findFuncion(name); t->ctype = t->fun->returnType; consume("id"); consume("("); if (consume(")")) { if (t->fun->params == nullptr or t->fun->params->empty()) t->args = new std::vector<Node*>{}; else errorParse(nowToken(-3), "Arguments do not match parameters"); } else { t->args = expression_list(); auto&& argarr = *(t->args); if (t->args->size() != t->fun->params->size()) errorParse(nowToken(), "Arguments do not match parameters"); for (size_t i = 0; i < t->fun->params->size(); i++) { if (not isMatchType(t->fun->params->at(i), argarr[i]->ctype)) { errorParse(nowToken(), "Arguments do not match parameters"); } } expect(")"); } return t; } else { return primary_expression(); } } /* primary_expression : l_expression | l_expression '++'/'--' | l_expression = expression // added this production | INT_CONSTANT | FLOAT_CONSTANT | STRING_LITERAL | CHAR_CONSTANT | '(' expression ')' ; */ Node* primary_expression() { auto t = newNode(); if (consume("num")) { t->type = ND_NUM; t->ctype = intType(); t->val = nowToken(-1).val; } else if (consume("lchar")) { t->type = ND_CHAR; t->ctype = charType(); t->val = nowToken(-1).val; } else if (consume("dnum")) { t->type = ND_DNUM; t->ctype = doubleType(); t->dval = nowToken(-1).dval; } else if (consume("str")) //要特别判断 { t->type = ND_STR; t->name = nowName(-1); // prog->stringlit.push_back(t->name); auto charp = new Type{}; charp->size = 8; charp->ty = PTR; charp->ptr_to = charType(); t->ctype = charp; } else if (consume("(")) { delete t; t = expression(); expect(")"); } else { delete t; t = l_expression(); if (consume("=")) { auto orll = newNode(); orll->lhs = t; orll->rhs = expression(); orll->type = ND_ASSIGN; orll->ctype = orll->lhs->ctype; t = orll; if (not isMatchType(orll->lhs->ctype, orll->rhs->ctype)) errorParse(nowToken(), "invalid type argument of = "); } else if (consume("++") or consume("--")) { pos--; auto orll = newNode(); orll->ctype = t->ctype; orll->lhs = t; if (consume("++")) { switch (orll->ctype->ty) { case VarType::ARY: case VarType::BOOL: case VarType::VOID: case VarType::STRUCT: errorParse(nowToken(), "invalid type argument of ++"); break; case VarType::PTR: case VarType::DOUBLE: case VarType::INT: case VarType::CHAR: default: break; } orll->type = ND_INC; } else if (consume("--")) { switch (orll->ctype->ty) { case VarType::ARY: case VarType::BOOL: case VarType::VOID: case VarType::STRUCT: errorParse(nowToken(), "invalid type argument of --"); break; case VarType::PTR: case VarType::DOUBLE: case VarType::INT: case VarType::CHAR: default: break; } orll->type = ND_DEC; } t = orll; } } return t; } //--------------cc的分割线----------------
47976f296055594996adffc3b698625d318a3438
1a102a7a691996e2db7084f464a7c02662d1f23e
/PolynomialProject/Polynomial.h
c91621a8472b197f6bcc3c4970f0a142c78dd7ae
[]
no_license
JyeStillitano/DSP-PolynomialProject
b1fcd9864510f305f7034747171f80c9f67d9fe0
c1e718452091b061a20b6cdb689caa0c8337fcf8
refs/heads/master
2021-03-28T21:03:17.150752
2020-03-20T03:45:59
2020-03-20T03:45:59
247,896,129
0
0
null
null
null
null
UTF-8
C++
false
false
1,071
h
Polynomial.h
#pragma once #include <iostream> #define MAX_DEGREE 20+1 // Maximum degree = 10 + 10 + 1 (0 - 20) class Polynomial { private: int fDegree; // the maximum degree of the polynomial double fCoeffs[MAX_DEGREE]; // the coefficients (0..10, 0..20) public: // the default constructor (initializes all member variables) Polynomial(); // binary operator* to multiply two polynomials // arguments are read-only, signified by const // the operator* returns a fresh polynomial with degree i+j Polynomial operator* ( const Polynomial& aRHS) const; // binary operator==to compare two polynomials // arguments are read-only, signified by const // the operator== returns trueif this polynomial is // structurally equivalent to the aRHS polynomial bool operator== ( const Polynomial& aRHS ) const; // input operator for polynomials friend std::istream& operator>> ( std::istream& aIStream, Polynomial& aObject ); // output operator for polynomials friend std::ostream& operator<< ( std::ostream& aOStream, const Polynomial& aObject ); };
62beac7c9da5a536379700de897183becccee535
da05aa7953d34d7d8303c961482e79dc63679b50
/simple_graph.hpp
0e6ceffdc0c16981efefa140ef3bd4abc104d8f1
[]
no_license
kyletreleaven/roadbm-cpp
18a1dfa70a9432df833997afb3c1e7e6f0dbc5c1
9d6d2110a2d73b9868d965ef614d8a6854a4e37a
refs/heads/master
2020-12-24T13:44:17.138959
2013-09-16T22:51:18
2013-09-16T22:51:18
12,672,521
1
0
null
2013-09-16T22:51:19
2013-09-07T22:22:51
C++
UTF-8
C++
false
false
2,675
hpp
simple_graph.hpp
#pragma once // stdc #include "stdlib.h" #include "stdio.h" #include "assert.h" // stdc++ #include <iostream> #include <utility> #include <iterator> //#include <numeric> // for accumulate //#include <vector> #include <list> #include <map> /* notes about map iterators * only the iterators of *erased* map items are invalidated!! */ #include <set> #include <algorithm> #include "boost/shared_ptr.hpp" // utility #include "printcontainer.hpp" // objects //#include "Interval.hpp" using namespace std ; using namespace boost ; struct no_graph_data {} ; template < typename VertexType, typename EdgeType, class VDataType = no_graph_data, class EDataType = no_graph_data > struct simple_graph { struct Vertex ; struct Edge ; typedef map<VertexType, Vertex> vertex_container ; typedef typename vertex_container::iterator vertex_iterator ; typedef map<EdgeType,Edge> edge_container ; typedef typename edge_container::iterator edge_iterator ; // class vertex_iterator : public typename map<VertexType,Vertex>::iterator {} ; //class edge_iterator : public typename map<EdgeType,Edge>::iterator {} ; // containers vertex_container V ; edge_container E ; struct Vertex { list< edge_iterator > out_edges ; VDataType local_data ; }; struct Edge { vertex_iterator tail, head ; EDataType local_data ; }; vertex_iterator find_vertex( const VertexType & u ) { return V.find( u ) ; } vertex_iterator vertex( const VertexType & u ) { V[u] ; // create one if it does not exist return find_vertex( u ) ; } edge_iterator find_edge( const EdgeType & e ) { return E.find( e ) ; } edge_iterator edge( const EdgeType & e, vertex_iterator u, vertex_iterator v ) { edge_iterator it = find_edge( e ) ; assert( it == E.end() ) ; Edge & edge = E[e] ; // creates edge.tail = u ; edge.head = v ; it = find_edge( e ) ; Vertex & t = u->second ; t.out_edges.push_back( it ) ; return it ; } void remove_edge( edge_iterator it ) { Edge & edge = it->second ; Vertex & t = edge.tail->second ; t.out_edges.erase( it ) ; E.erase( it ) ; } void remove_vertex( vertex_iterator it ) { Vertex & u = it->second ; for ( edge_iterator e_it = u.out_edges.begin() ; e_it != u.out_edges.end() ; ++e_it ) { remove_edge( e_it ) ; } V.erase( it ) ; } friend ostream & operator<< ( ostream & out, simple_graph & graph ) { out << "{ " ; for ( edge_iterator it = graph.E.begin() ; it != graph.E.end() ; ++it ) { out << it->first << " => (" << it->second.tail->first << ',' << it->second.head->first << "), " ; } out << " }" ; return out ; } };
f08de60efc65e9680c74d90767e3878da2da2908
d64e2243d9b326ae9fa5614d335eff01dce4161f
/src/sound/sfml_sound.h
950277a41d397458e57c36aa04c6a68058278519
[ "Artistic-2.0" ]
permissive
skadge/table-lumineuse
e010b8435eb1f4321fe71fee85150861cdd49b9d
90b357d3c3e34f4f6df2f834c7060fd41a03eb4f
refs/heads/master
2021-03-13T00:01:17.891671
2020-10-30T22:17:55
2020-10-30T22:17:55
24,863,375
0
0
null
null
null
null
UTF-8
C++
false
false
466
h
sfml_sound.h
#ifndef SFML_SOUND_H #define SFML_SOUND_H #include <SFML/Audio.hpp> #include "sound.h" class SFMLSound : public SoundSource { private: sf::SoundBuffer buffer; sf::Sound sound; bool _sound_loaded; void load_sound(); public: SFMLSound(const std::string& path, bool loop=false); ~SFMLSound() { stop(); } bool playing() const; void volume(float vol); void play(); void pause(); void stop(); }; #endif
c3f7e0e5d6b9559fb4741beddbf9cf6c33a6f9c1
f588635240479cb0411e1514e006dfccc2002d2e
/Classes/network/HttpLoader.cpp
d2267eaf90eff14551e4660bef2a5811c8c3b5c1
[]
no_license
youssefmyh/ThreadPoolcommandObserver
fe9459063bf73d7b0e10f4fcb5a358cf5c6af004
0aaeafd4713d7a82811222e7595812bfe188cd14
refs/heads/master
2023-02-27T12:54:37.712225
2021-02-09T10:26:05
2021-02-09T10:26:05
253,470,981
3
2
null
2020-09-13T10:55:18
2020-04-06T10:58:53
C++
UTF-8
C++
false
false
967
cpp
HttpLoader.cpp
// // HttpLoader.cpp // myGame // // Created by Youssef Hanna on 9/6/19. // #include "HttpLoader.hpp" HttpLoader *HttpLoader::m_instance = nullptr; void HttpLoader::sendRequest(cocos2d::network::HttpRequest *httpRequest) { httpRequest->setResponseCallback(this, httpresponse_selector(HttpLoader::onResponseCompleted)); cocos2d::network::HttpClient::getInstance()->send(httpRequest); m_requestList->pushBack(httpRequest); } void HttpLoader::onResponseCompleted(cocos2d::network::HttpClient* client, cocos2d::network::HttpResponse* response){ if(response == nullptr){ return; } } HttpLoader::HttpLoader() { m_requestList = new cocos2d::Vector<cocos2d::network::HttpRequest*>(); } HttpLoader::~HttpLoader(){ std::vector<cocos2d::network::HttpRequest*>::iterator iterator = m_requestList->end(); while(iterator != m_requestList->begin()){ delete *iterator; iterator--; } }
81e4ccbd0abc194a43befc79f25673a42ef0c64d
72d01ddc408f90a45d4db4643124f76791c89ba3
/src/tools/RGBDLogger.cpp
60ce0997cdaaff74ab664eb2d9c9b30d7630812b
[]
no_license
caomw/idSLAM
4d26e5a302ec165e2957ba2d7dd99088f0f73b7d
6ea2823905fa342216916fffb2d2ab26190a36a9
refs/heads/master
2021-01-21T20:33:26.622699
2015-07-23T02:00:02
2015-07-23T02:00:02
66,874,264
0
1
null
2016-08-29T19:31:27
2016-08-29T19:31:27
null
UTF-8
C++
false
false
4,381
cpp
RGBDLogger.cpp
/* * RGBDLogger.cpp * * Created on: Feb 16, 2011 * Author: scherer */ #include <cv_bridge/cv_bridge.h> #include <image_geometry/pinhole_camera_model.h> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <opencv2/imgproc/imgproc.hpp> #include <ros/ros.h> #include <sensor_msgs/CameraInfo.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/image_encodings.h> #include <highgui.h> #include <iostream> #include <fstream> #include <sstream> #include <string> using namespace cv; namespace rgbdslam { //The policy merges kinect messages with approximately equal timestamp into one callback typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image,sensor_msgs::Image> MySyncPolicy; class RGBDLogger { public: RGBDLogger() : frameId_(0), sub_rgb_(nh_, "/camera/rgb/image_color", 1), sub_depth_(nh_, "/camera/depth/image_raw", 1), sync_(MySyncPolicy(20), sub_rgb_, sub_depth_) { // Set maximum time difference between depth and rgb to 0.02s. MySyncPolicy* policy = static_cast<MySyncPolicy*>(sync_.getPolicy()); policy->setMaxIntervalDuration(ros::Duration(0.03)); namedWindow("rgb"); namedWindow("depth"); sync_.registerCallback(boost::bind(&RGBDLogger::cameraCallback, this, _1, _2)); } ~RGBDLogger() { } void cameraCallback(const sensor_msgs::ImageConstPtr& rgb_img_msg, const sensor_msgs::ImageConstPtr& depth_img_msg) { frameId_++; cv_bridge::CvImagePtr cv_ptr_rgb; cv_bridge::CvImagePtr cv_ptr_depth; try { cv_ptr_rgb = cv_bridge::toCvCopy(rgb_img_msg, sensor_msgs::image_encodings::BGR8); if (depth_img_msg->encoding == "16SC1") { cv_ptr_depth = cv_bridge::toCvCopy(depth_img_msg, sensor_msgs::image_encodings::TYPE_16SC1); } else if (depth_img_msg->encoding == "16UC1") { cv_ptr_depth = cv_bridge::toCvCopy(depth_img_msg, sensor_msgs::image_encodings::TYPE_16UC1); } else { std::cerr << __PRETTY_FUNCTION__ << "unknown depth encoding: " << depth_img_msg->encoding << std::endl; } imshow("rgb",cv_ptr_rgb->image); imshow("depth",cv_ptr_depth->image); int key = waitKey(20); if (key > 0) { std::cout << "Key pressed, saving frame." << std::endl; std::stringstream rgbname, depthname, pointsname; rgbname << rgb_img_msg->header.stamp << ".png"; depthname << rgb_img_msg->header.stamp << ".yml"; pointsname << rgb_img_msg->header.stamp << ".csv"; imwrite(rgbname.str(),cv_ptr_rgb->image); FileStorage fs(depthname.str(), FileStorage::WRITE); fs << "depth" << cv_ptr_depth->image; fs.release(); // std::ofstream of(pointsname.str().c_str()); // cam_model_.fromCameraInfo(camera_info_msg); // for (int y = 0; y < depth_img.rows; y++) { // for (int x = 0; x < depth_img.cols; x++) { // cv::Point p2i(x,y); // double d = depth_img.at<float>(cv::Point(x,y)); // if (!isnan(d)) { // cv::Point3d p3d = cam_model_.projectPixelTo3dRay(p2i)*d; // of << p3d.x << " " << p3d.y << " " << p3d.z << std::endl; // } // } // } // of.close(); } // if key pressed } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // end catch } private: int frameId_; ros::NodeHandle nh_; message_filters::Subscriber<sensor_msgs::Image> sub_rgb_; message_filters::Subscriber<sensor_msgs::Image> sub_depth_; message_filters::Subscriber<sensor_msgs::CameraInfo> sub_rgb_info_; message_filters::Synchronizer<MySyncPolicy> sync_; image_geometry::PinholeCameraModel cam_model_; }; } // namespace rgbdslam int main(int argc, char **argv) { ros::init(argc, argv, "rgbdlogger"); rgbdslam::RGBDLogger node; ros::spin(); return 0; }
b149e4e7a16bdfa61fb4865f5f918fcdf85ab9e4
602e0f4bae605f59d23688cab5ad10c21fc5a34f
/MyToolKit/CostEngineer/CostEngineerView.h
c407247a40810fcad47ce4e0acab31f608ce96f4
[]
no_license
yanbcxf/cpp
d7f26056d51f85254ae1dd2c4e8e459cfefb2fb6
e059b02e7f1509918bbc346c555d42e8d06f4b8f
refs/heads/master
2023-08-04T04:40:43.475657
2023-08-01T14:03:44
2023-08-01T14:03:44
172,408,660
8
5
null
null
null
null
UTF-8
C++
false
false
2,619
h
CostEngineerView.h
 // CostEngineerView.h: CCostEngineerView 类的接口 // #pragma once class CCostEngineerCntrItem; class CCostEngineerView : public CBaseMessageFormView { protected: // 仅从序列化创建 CCostEngineerView() noexcept; DECLARE_DYNCREATE(CCostEngineerView) // 特性 public: CCostEngineerDoc* GetDocument() const; // m_pSelection 将所选内容保存在当前 CCostEngineerCntrItem 中。 // 对于许多应用程序,这种成员变量不足以 // 表示某个选择,例如在不属于 // CCostEngineerCntrItem 的对象中选定的一个或多个对象。提供这种选择 // 机制的目的只是帮助入门 // TODO: 用适合应用程序的选择机制替换此选择机制 CCostEngineerCntrItem* m_pSelection; string m_strMenuCode; int m_nChildrenCode; // 操作 public: // 重写 public: virtual void OnDraw(CDC* pDC); // 重写以绘制该视图 virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void OnInitialUpdate(); // 构造后第一次调用 virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); virtual BOOL IsSelected(const CObject* pDocItem) const;// 容器支持 // 实现 public: virtual ~CCostEngineerView(); void RedrawView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: afx_msg void OnDestroy(); afx_msg void OnSetFocus(CWnd* pOldWnd); afx_msg void OnInsertObject(); afx_msg void OnCancelEditCntr(); afx_msg void OnFilePrint(); afx_msg void OnFilePrintPreview(); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); DECLARE_MESSAGE_MAP() virtual void OnUpdate(CView* /*pSender*/, LPARAM /*lHint*/, CObject* /*pHint*/); virtual void PostGridClick(int gridId, int nRow, int nCol); virtual void CCostEngineerView::PostAddNodeToGraph(int x, int y); virtual void CCostEngineerView::PostAddEdgeToGraph(int from ,int to); virtual void CCostEngineerView::PostMoveNodeInGraph(int idx, int x, int y); virtual void CCostEngineerView::PostEditNodeInGraph(int idx); virtual void CCostEngineerView::PostEditEdgeInGraph(int idx); virtual void CCostEngineerView::PostDelNodeInGraph(int idx); virtual void CCostEngineerView::PostDelEdgeInGraph(int idx); }; #ifndef _DEBUG // CostEngineerView.cpp 中的调试版本 inline CCostEngineerDoc* CCostEngineerView::GetDocument() const { return reinterpret_cast<CCostEngineerDoc*>(m_pDocument); } #endif
1ea9f17f9ab956c7bc1e1f0ec2c96f5376959271
e74287342dadc173c26500285d216110a6ede5fe
/计算导论与C语言基础/week_6/Assignment2/苹果和虫子.cpp
d35fcddbb9f322e27a53588110bb8c4587220a9d
[]
no_license
JiahongHe/Program-Design-and-Alogorithms
f481fe67863d836e3fde96b683854f1570fdd8a2
3ddec8b6ef6c7d433fe8855fef9b490480979ac2
refs/heads/master
2020-03-25T15:18:13.268218
2018-08-20T09:17:18
2018-08-20T09:17:18
143,876,725
0
0
null
null
null
null
UTF-8
C++
false
false
408
cpp
苹果和虫子.cpp
#include <iostream> using namespace std; int main(int argc, const char * argv[]) { int total; int hour_per_apple; int time; cin >> total >> hour_per_apple >> time; int count = (int)time / hour_per_apple; if (count * hour_per_apple < time) { count += 1; } int left = total - count; if (left < 0) { left = 0; } cout << left << endl; return 0; }
040dbee7414f7bb5c452f6a5ac2d7c42555aefaa
d2190cbb5ea5463410eb84ec8b4c6a660e4b3d0e
/hydra2-4.9w/rpc/hrpcslewingpar.h
781a490f90b32f8e8cbdb7d51dba837064283728
[]
no_license
wesmail/hydra
6c681572ff6db2c60c9e36ec864a3c0e83e6aa6a
ab934d4c7eff335cc2d25f212034121f050aadf1
refs/heads/master
2021-07-05T17:04:53.402387
2020-08-12T08:54:11
2020-08-12T08:54:11
149,625,232
0
0
null
null
null
null
UTF-8
C++
false
false
1,551
h
hrpcslewingpar.h
#ifndef HRPCHSLEWINGPAR_H #define HRPCHSLEWINGPAR_H #include "TArrayF.h" #include "hparcond.h" class HParamList; class HRpcSlewingPar : public HParCond { protected: TArrayF fExpo1; // Parameters of the exponential describing behaviour below fQcut TArrayF fExpo2; // Parameters of the exponential describing behaviour above fQcut Float_t fQcut; // Cut value for the two parameterizations. Limit region of both pars public: HRpcSlewingPar(const Char_t* name ="RpcSlewingPar", const Char_t* title ="Slewing correciton parameters for the Rpc Detector", const Char_t* context="RpcSlewingParProduction"); ~HRpcSlewingPar(); const Float_t* getExpo1(Int_t sec, Int_t col, Int_t cell) { return &fExpo1[ 576*sec + 96*col + 3*cell ];} const Float_t* getExpo2(Int_t sec, Int_t col, Int_t cell) { return &fExpo2[ 576*sec + 96*col + 3*cell ];} Float_t getQcut() { return fQcut;} void setExpo1par(Int_t sec, Int_t col, Int_t cell, Int_t index, Float_t par) { fExpo1[ 576*sec + 96*col + 3*cell + index] = par; } void setExpo2par(Int_t sec, Int_t col, Int_t cell, Int_t index, Float_t par) { fExpo2[ 576*sec + 96*col + 3*cell + index] = par; } void setQcut(Float_t q) { fQcut = q; } void putParams(HParamList*); Bool_t getParams(HParamList*); void clear(); ClassDef(HRpcSlewingPar,1) // Container for the RPC hit finder parameters }; #endif /*!HRPCSLEWINGPAR_H*/
e2d785673052fc6c21139e6600bb6becaf3beed1
79709e837ec78881d84dbbdfa1c624fd7bb055f5
/src/Physics/Box.h
cf72761870172ff2da276722f2e0bc496f962b39
[ "MIT" ]
permissive
JanDupal/magnum
dd517717119b9b20113c875a67da141ae2feb00a
a21fd0df078c3c6245370de69b6016acd2d222da
refs/heads/master
2020-12-25T00:02:35.698909
2013-05-04T11:35:52
2013-05-04T12:15:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,495
h
Box.h
#ifndef Magnum_Physics_Box_h #define Magnum_Physics_Box_h /* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** @file * @brief Class Magnum::Physics::Box, typedef Magnum::Physics::Box2D, Magnum::Physics::Box3D */ #include "Math/Matrix3.h" #include "Math/Matrix4.h" #include "AbstractShape.h" #include "corradeCompatibility.h" namespace Magnum { namespace Physics { /** @brief Unit-size box with assigned transformation matrix Unit-size means that half extents are equal to 1, equivalent to e.g. sphere radius. @todo Use quat + position + size instead? @see Box2D, Box3D @todo Assert for skew */ template<UnsignedInt dimensions> class MAGNUM_PHYSICS_EXPORT Box: public AbstractShape<dimensions> { public: /** * @brief Default constructor * * Creates zero-sized box positioned at origin. */ inline explicit Box(): _transformation(DimensionTraits<dimensions>::MatrixType::Zero), _transformedTransformation(DimensionTraits<dimensions>::MatrixType::Zero) {} /** @brief Constructor */ inline explicit Box(const typename DimensionTraits<dimensions>::MatrixType& transformation): _transformation(transformation), _transformedTransformation(transformation) {} inline typename AbstractShape<dimensions>::Type type() const override { return AbstractShape<dimensions>::Type::Box; } void applyTransformationMatrix(const typename DimensionTraits<dimensions>::MatrixType& matrix) override; /** @brief Transformation */ inline typename DimensionTraits<dimensions>::MatrixType transformation() const { return _transformation; } /** @brief Set transformation */ inline void setTransformation(const typename DimensionTraits<dimensions>::MatrixType& transformation) { _transformation = transformation; } /** @brief Transformed transformation */ inline typename DimensionTraits<dimensions>::MatrixType transformedTransformation() const { return _transformedTransformation; } private: typename DimensionTraits<dimensions>::MatrixType _transformation, _transformedTransformation; }; /** @brief Two-dimensional box */ typedef Box<2> Box2D; /** @brief Three-dimensional box */ typedef Box<3> Box3D; }} #endif
e429e063bf07f4e0ee26fb41c5687eed1a40f895
4addcb3a69a03af9c55c5673ad3ef6851ccc9aef
/datastructure/stack.cpp
dcbcd1ee1a26002a0c75b29a2295247187aefe90
[]
no_license
PrasanthChettri/competitivecode
367cf2e01f0c1342d12730ec4562831103c95ee7
4250de2f4b6061ab63caae959b9ba71099b4928b
refs/heads/master
2022-11-14T07:10:32.582144
2020-07-09T09:35:19
2020-07-09T09:35:19
278,323,014
1
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
stack.cpp
#include<iostream> using namespace std ; class Node { public : int data ; Node * next ; }*node; void push(int item){ Node * new_n = new Node(); new_n->data = item; new_n->next = node ; node = new_n ; } bool pop(){ Node * temp = node ; if(node){ node = node->next ; delete temp ; return true ; } return false; } void see(){ for(Node * i = node ; i ; i = i->next) std::cout<<i->data <<std::endl ; }; int main(){ node = NULL ; push(320); push(0); see(); cout<<!node ; }
f340d3c3b2b0294ec3525d3f02e6c71bdcedef04
51099872722a72b1e9c59c8a0bd022d009dbba2c
/game/sources/gui/bitmap-font-renderer.cc
68a7e2461f978cf297a7de474640882d3797d894
[]
no_license
perpetual24/fps-game
37d22759967916a3f6b5d656e3d63e1f02a64b6b
8e4cc02a7139a1575f8a618b408c22cbfc4cc09a
refs/heads/master
2023-07-12T09:27:26.847169
2020-04-19T12:09:34
2020-04-19T12:09:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,523
cc
bitmap-font-renderer.cc
#include "game/headers/gui/bitmap-font-renderer.hh" #include "external/glad/glad.h" BitmapFontRenderer::BitmapFontRenderer(const BitmapFont& font, const Shader& bitmap_shader, float screen_width_height): _font{font}, _bitmap_shader{bitmap_shader}, _screen_width_height{screen_width_height} { glGenVertexArrays(1, &_vao); glGenBuffers(1, &_vbo); glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); GLfloat vertices[6][4]{ {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 1.0f, 1.0f}, {1.0f, 1.0f, 1.0f, 0.0f} }; glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void BitmapFontRenderer::draw(std::string_view text, float scale, glm::vec2 position, glm::vec3 color) const { _bitmap_shader.use(); _bitmap_shader.setVec3("color", color); _bitmap_shader.setInt("tex", 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _font.getTextureId()); glBindVertexArray(_vao); glDisable(GL_DEPTH_TEST); // Enable the blending for text rendering glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); float offset_x{0.0f}; const float tex_w{1.0f / _font.getColumns()}; const float tex_h{1.0f / _font.getRows()}; const float cell_h{scale}; const float cell_w{cell_h * static_cast<float>(_font.getRows()) / (_font.getColumns() * _screen_width_height)}; for (std::string_view::const_iterator c{text.cbegin()}; c != text.end(); ++c) { float tex_x, tex_y; _font.getCharPosition(*c, &tex_x, &tex_y); // Update the position matrix uniform glm::mat3 pos_matrix( cell_w, 0.0f, 0.0f, 0.0f, cell_h, 0.0f, position.x + offset_x, position.y, 1.0f ); _bitmap_shader.setMat3("pos_matrix", pos_matrix); // Update the texture matrix uniform glm::mat3 tex_matrix( tex_w, 0.0f, 0.0f, 0.0f, tex_h, 0.0f, tex_x, tex_y, 1.0f ); _bitmap_shader.setMat3("tex_matrix", tex_matrix); glDrawArrays(GL_TRIANGLES, 0, 6); offset_x += (_font.getWidthHeight() * scale / _screen_width_height); } glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } float BitmapFontRenderer::getStringLength(std::string_view text, float scale) const { return (text.length() * _font.getWidthHeight() * scale) / _screen_width_height; }
c3ba231bc4287f430b39cd6d9123cbfd119f8628
3bb4044e98cc6816801c755f0e7894dde1a2a361
/4_4_led_matrix1.ino
2da517b1de41553c16c20fd80602cfd44364239c
[]
no_license
biplab5464/Arduino
a2a9a37fde71cea1711a0734c1bbb2b5a0038676
9a7c66a83c5de4549aff31fe87a0c82259218128
refs/heads/master
2023-03-12T06:30:36.183357
2021-03-01T16:49:33
2021-03-01T16:49:33
270,916,956
0
0
null
null
null
null
UTF-8
C++
false
false
5,467
ino
4_4_led_matrix1.ino
int a = 11,b=10,c=9,d=8 ,n1=2,n2=3, n3=4,n4 =5; void setup() { pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); pinMode(d, OUTPUT); pinMode(n1, OUTPUT); pinMode(n2, OUTPUT); pinMode(n3, OUTPUT); pinMode(n4, OUTPUT); } void allLed() { digitalWrite(a,0); digitalWrite(b,0); digitalWrite(c,0); digitalWrite(d,0); digitalWrite(n1,1); digitalWrite(n2,1); digitalWrite(n3,1); digitalWrite(n4,1); } void ledOff() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,0); } void leda1() { digitalWrite(a,0); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,1); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,0); } void leda2() { digitalWrite(a,0); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,1); digitalWrite(n3,0); digitalWrite(n4,0); } void leda3() { digitalWrite(a,0); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,1); digitalWrite(n4,0); } void leda4() { digitalWrite(a,0); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,1); } void ledb1() { digitalWrite(a,1); digitalWrite(b,0); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,1); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,0); } void ledb2() { digitalWrite(a,1); digitalWrite(b,0); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,1); digitalWrite(n3,0); digitalWrite(n4,0); } void ledb3() { digitalWrite(a,1); digitalWrite(b,0); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,1); digitalWrite(n4,0); } void ledb4() { digitalWrite(a,1); digitalWrite(b,0); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,1); } void ledc1() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,0); digitalWrite(d,1); digitalWrite(n1,1); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,0); } void ledc2() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,0); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,1); digitalWrite(n3,0); digitalWrite(n4,0); } void ledc3() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,0); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,1); digitalWrite(n4,0); } void ledc4() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,0); digitalWrite(d,1); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,1); } void ledd1() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,0); digitalWrite(n1,1); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,0); } void ledd2() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,0); digitalWrite(n1,0); digitalWrite(n2,1); digitalWrite(n3,0); digitalWrite(n4,0); } void ledd3() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,0); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,1); digitalWrite(n4,0); } void ledd4() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,0); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,1); } void ledr1() { digitalWrite(a,0); digitalWrite(b,0); digitalWrite(c,0); digitalWrite(d,0); digitalWrite(n1,1); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,0); } void ledr2() { digitalWrite(a,0); digitalWrite(b,0); digitalWrite(c,0); digitalWrite(d,0); digitalWrite(n1,0); digitalWrite(n2,1); digitalWrite(n3,0); digitalWrite(n4,0); } void ledr3() { digitalWrite(a,0); digitalWrite(b,0); digitalWrite(c,0); digitalWrite(d,0); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,1); digitalWrite(n4,0); } void ledr4() { digitalWrite(a,0); digitalWrite(b,0); digitalWrite(c,0); digitalWrite(d,0); digitalWrite(n1,0); digitalWrite(n2,0); digitalWrite(n3,0); digitalWrite(n4,1); } void leds1() { digitalWrite(a,0); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,1); digitalWrite(n2,1); digitalWrite(n3,1); digitalWrite(n4,1); } void leds2() { digitalWrite(a,1); digitalWrite(b,0); digitalWrite(c,1); digitalWrite(d,1); digitalWrite(n1,1); digitalWrite(n2,1); digitalWrite(n3,1); digitalWrite(n4,1); } void leds3() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,0); digitalWrite(d,1); digitalWrite(n1,1); digitalWrite(n2,1); digitalWrite(n3,1); digitalWrite(n4,1); } void leds4() { digitalWrite(a,1); digitalWrite(b,1); digitalWrite(c,1); digitalWrite(d,0); digitalWrite(n1,1); digitalWrite(n2,1); digitalWrite(n3,1); digitalWrite(n4,1); } void loop() { ledr1(); delay(80); ledr2(); delay(80); ledr3(); delay(80); ledr4(); delay(80); leds1(); delay(80); leds2(); delay(80); leds3(); delay(80); leds4(); delay(80); }
6b77ec77821197c5109bf36b43c32346e9d1dd5c
b469bab1734a60fc495df1e8b8e8b45eb8425f32
/src/cloth.cpp
9e67b1b4c9fdd0d0828b8f25b8ed8f91aabac061
[]
no_license
augustt198/cloth
2f47f68470cd11e8b98e0e44b657b94af7f3e976
b9ab77602b6d8558734755c66e97c12cfb639f12
refs/heads/master
2021-01-01T20:04:16.451958
2017-08-14T20:02:00
2017-08-14T20:02:02
98,761,008
7
1
null
null
null
null
UTF-8
C++
false
false
7,948
cpp
cloth.cpp
#include "cloth.h" #include <cstdio> #include <cmath> // call this inside a Cloth method #define IDX(__x, __y) (__x+__y*this->width) Cloth::Cloth(int width, int height, float pointMass) : width(width), height(height), pointMass(pointMass) { pointMass = 3; gravityConstant = 3.0; springConstant = 15.0; airResistance = 0.015; enableMaxStretch = true; position = new glm::vec3[width*height]; prevPosition = new glm::vec3[width*height]; initPosition = new glm::vec3[width*height]; velocity = new glm::vec3[width*height]; accel = new glm::vec3[width*height]; // initialize positions for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int idx = IDX(x, y); position[idx] = glm::vec3((x-width/2)/2.0, (y-height/2)/2.0, 0); prevPosition[idx] = position[idx]; initPosition[idx] = position[idx]; velocity[idx] = glm::vec3(0.0f); accel[idx] = glm::vec3(0.0f); } } } glm::vec3 Cloth::calcSpringForce(int x1, int y1, int x2, int y2) { glm::vec3 pos1 = position[IDX(x1, y1)]; glm::vec3 pos2 = position[IDX(x2, y2)]; glm::vec3 diff = pos2 - pos1; float rest = glm::length(initPosition[IDX(x2,y2)] - initPosition[IDX(x1,y1)]); return springConstant * (glm::length(diff) - rest) * glm::normalize(diff); } void Cloth::fixElongation(float factor, int x1, int y1, int x2, int y2) { int idx1 = IDX(x1, y1); int idx2 = IDX(x2, y2); glm::vec3 pos1 = position[idx1], pos2 = position[idx2]; glm::vec3 diff = pos2 - pos1; float rest = glm::length(initPosition[idx2] - initPosition[idx1]); if (glm::length(diff) > factor * rest) { glm::vec3 mid = (pos1 + pos2)/2.0f; glm::vec3 diff_n = normalize(diff); position[idx1] = mid - diff_n * rest * factor/2.0f; position[idx2] = mid + diff_n * rest * factor/2.0f; } } void Cloth::maxElongation(float factor) { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (y == 0) continue; if (x < width - 1) fixElongation(factor, x, y, x+1, y); if (x > 0) fixElongation(factor, x, y, x-1, y); if (y < height - 1) fixElongation(factor, x, y, x, y+1); if (y > 0) fixElongation(factor, x, y, x, y-1); if (x < width - 1 && y < height - 1) fixElongation(factor, x, y, x+1, y+1); if (x < width - 1 && y > 0) fixElongation(factor, x, y, x+1, y-1); if (x > 0 && y < height - 1) fixElongation(factor, x, y, x-1, y+1); if (x > 0 && y > 0) fixElongation(factor, x, y, x-1, y-1); } } } void Cloth::step(float dt) { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { // the top should be fixed if (y == 0 && x == 0) continue; if (y == 0 && x == width-1) continue; if (y == height-1 && x == 0) continue; if (y == height-1 && x == width-1) continue; //if (y == 0) continue; glm::vec3 prevPos = prevPosition[IDX(x, y)]; glm::vec3 currPos = position[IDX(x, y)]; glm::vec3 Fgravity(0.0f, 0.0f, -gravityConstant * pointMass); glm::vec3 Fspring(0.0f, 0.0f, 0.0f); if (x < width - 1) Fspring += calcSpringForce(x, y, x+1, y); if (x > 0) Fspring += calcSpringForce(x, y, x-1, y); if (y < height - 1) Fspring += calcSpringForce(x, y, x, y+1); if (y > 0) Fspring += calcSpringForce(x, y, x, y-1); if (x < width - 1 && y < height - 1) Fspring += calcSpringForce(x, y, x+1, y+1); if (x < width - 1 && y > 0) Fspring += calcSpringForce(x, y, x+1, y-1); if (x > 0 && y < height - 1) Fspring += calcSpringForce(x, y, x-1, y+1); if (x > 0 && y > 0) Fspring += calcSpringForce(x, y, x-1, y-1); glm::vec3 v = velocity[IDX(x, y)]; float vMag = glm::length(v); glm::vec3 Fdrag; if (vMag != 0) Fdrag = -airResistance * (vMag*vMag) * normalize(v); else Fdrag = glm::vec3(0.0f); glm::vec3 a = (Fgravity + Fspring + Fdrag) / pointMass; accel[IDX(x, y)] = a; glm::vec3 newPos = 2.0f*currPos - prevPos + a*(dt*dt); prevPosition[IDX(x, y)] = currPos; for (int i = 0; i < obstacles.size(); i++) { //std::printf("inside!\n"); if (obstacles[i]->isInside(newPos)) newPos = obstacles[i]->project(newPos); } position[IDX(x, y)] = newPos; velocity[IDX(x, y)] += a * dt; accel[IDX(x, y)] = a; } } if (enableMaxStretch) { for (int i = 1; i <= 7; i++) maxElongation(1.25); } //glm::vec3 v = accel[IDX(width-1, height-1)]; //printf("vert %.03f %.03f %.03f\n", v[0], v[1], v[2]); } void Cloth::reset() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { position[IDX(x, y)] = glm::vec3((x-width/2)/2.0, (y-height/2)/2.0, 0); prevPosition[IDX(x, y)] = position[IDX(x, y)]; velocity[IDX(x, y)] = glm::vec3(0.0f); accel[IDX(x, y)] = glm::vec3(0.0f); } } } ClothMesh::ClothMesh(Cloth *cloth) : cloth(cloth) { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // generate element buffer int width = cloth->width, height = cloth->height; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); indicesCount = 3 * 2 * (width - 1) * (height - 1); int *indices = new int[indicesCount]; int i = 0; for (int x = 0; x < width - 1; x++) { for (int y = 0; y < height - 1; y++) { indices[i++] = x + y*width; indices[i++] = (x+1) + (y+1)*width; indices[i++] = x + (y+1)*width; indices[i++] = x + y*width; indices[i++] = (x+1) + y*width; indices[i++] = (x+1) + (y+1) * width; } } glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesCount * sizeof(int), indices, GL_STATIC_DRAW); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, false, 5*sizeof(float), (void*) 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, false, 5*sizeof(float), (void*) (3*sizeof(float))); glBindVertexArray(0); } void ClothMesh::updateVertexBuffer() { glBindBuffer(GL_ARRAY_BUFFER, VBO); float *data = new float[5 * cloth->width * cloth->height]; int j = 0; for (int i = 0; i < cloth->width * cloth->height; i++) { data[j++] = cloth->position[i].x; data[j++] = cloth->position[i].y; data[j++] = cloth->position[i].z; data[j++] = i % 2; data[j++] = 0.0f; } glBufferData(GL_ARRAY_BUFFER, 5 * cloth->width * cloth->height * sizeof(float), data, GL_STREAM_DRAW); } void ClothMesh::draw() { glBindVertexArray(VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glDrawElements(GL_TRIANGLES, indicesCount, GL_UNSIGNED_INT, NULL); glBindVertexArray(0); } SphereObstacle::SphereObstacle(glm::vec3 center, float radius) : center(center), radius(radius) {} bool SphereObstacle::isInside(glm::vec3 pt) { return glm::length(pt - center) <= 1.001f*radius; } glm::vec3 SphereObstacle::project(glm::vec3 pt) { glm::vec3 dir = glm::normalize(pt - center); return center + radius * dir; }
0f432f368ba6776f375b44eb4afba2e7e88371dc
f4c24ee933ccaaf95847d595c1c3c71f92bace44
/Registry/main.cpp
6d89585da3d65a2a996e6469eb67a04097911594
[]
no_license
shehab-as/Distributed-Systems
626a4e777234e7bd8cafe9f95014e3b79e22cd9e
55b9675eae678036edc8b32fdc9f09cab7da72ff
refs/heads/master
2022-11-01T02:46:06.977019
2018-09-24T22:17:42
2018-09-24T22:17:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
main.cpp
#include <SQLiteCpp/Database.h> #include <iostream> #include <fstream> #include "Registry.h" int main() { //FOR FOREIGN KEY CONSTRAINT TO WORK, MUST WRITE -> PRAGMA foreign_keys = ON; IN SQLITE TERMINAL Registry Reg(NULL, 1234, 10, "/home/farida/Final_Dist.db"); }
eec7eb0d1defbee35a255e7fd1eaa663151df961
12104346ddf50cacdc5b27e783d4b4c69f8e6e9f
/src/Accelerators/NNPA/Conversion/ZHighToZLow/ZHighToZLow.cpp
91d8e26e621527a15e3a56c929956c8109aaf0b7
[ "Apache-2.0" ]
permissive
doru1004/onnx-mlir
4aab522ddea723300b482a2ba28926e50c6a290c
47e4f391b9f1eff5835039093c7d4f5b76841125
refs/heads/master
2022-06-01T09:09:26.912295
2022-05-13T20:27:48
2022-05-13T20:27:48
243,586,266
0
0
Apache-2.0
2020-02-27T18:20:36
2020-02-27T18:20:35
null
UTF-8
C++
false
false
56,398
cpp
ZHighToZLow.cpp
/* * SPDX-License-Identifier: Apache-2.0 */ //====------ ZHighToZLow.cpp - ZHigh dialect to ZLow lowering -------------===// // // Copyright 2019-2022 The IBM Research Authors. // // ============================================================================= // // This file implements the lowering of ZHigh operations to ZLow operations. // //===----------------------------------------------------------------------===// #include "mlir/Dialect/Affine/Analysis/Utils.h" #include "mlir/Dialect/Affine/Utils.h" #include "src/Accelerators/NNPA/Conversion/ZHighToZLow/ZHighToZLow.hpp" #include "src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.hpp" #include "src/Accelerators/NNPA/Dialect/ZHigh/ZHighOps.hpp" #include "src/Accelerators/NNPA/Dialect/ZHigh/ZHighShapeHelper.hpp" #include "src/Accelerators/NNPA/Dialect/ZLow/ZLowOps.hpp" #include "src/Accelerators/NNPA/Pass/NNPAPasses.hpp" #include "src/Conversion/ONNXToKrnl/ONNXToKrnlCommon.hpp" #include "src/Dialect/Krnl/KrnlHelper.hpp" using namespace mlir; using namespace onnx_mlir::zlow; // A global variable to indicate whether this pass will emit dealloc for // allocated memrefs or not. extern bool ONNXToKrnl_gEmitDealloc; namespace onnx_mlir { namespace zhigh { /// A list of layouts associated with newly allocated MemRefs. /// When lowering an operation, its output Tensor (e.g. /// `tensor<1x3x5x7xf32, #zhigh.encoding<{dataLayout = "NHWC"}>>`) will be /// converted to a Memref (e.g. `memref<1x3x5x7xf16, #map>`), and we lost the /// layout `NHWC`. Thus, make sure to put the new MemRef and its associated /// layout into this map, so that we can obtain the layout for the MemRef later /// when lowering other ops. llvm::SmallMapVector<mlir::Value, mlir::StringAttr, 4> stickedLayouts; mlir::StringAttr readLayout(mlir::Value val) { return stickedLayouts[val]; } void storeLayout(mlir::Value val, mlir::StringAttr layout) { stickedLayouts[val] = layout; } //===----------------------------------------------------------------------===// // Helper function of Zhigh to Zlow lowering // Insert an allocation and deallocation for the given dimensions and layout. // By default, set aligment to 4K. //===----------------------------------------------------------------------===// Value insertAllocAndDeallocZMemRefByDim(ArrayRef<IndexExpr> dims, ZTensorEncodingAttr::DataLayout layout, Operation *op, PatternRewriter &rewriter, int64_t alignment = gAlignment) { // Construct a MemRefType for the given dimensions and element type. SmallVector<int64_t, 4> shape; for (IndexExpr d : dims) shape.emplace_back((d.isLiteral() ? d.getLiteral() : -1)); RankedTensorType tensorType = RankedTensorType::get(shape, rewriter.getF32Type(), ZTensorEncodingAttr::get(op->getContext(), layout)); ZMemRefType zMemRefType = convertZTensorToMemRefType(tensorType); // Insert alloc and dealloc. Value alloc = insertAllocAndDeallocZMemRef(zMemRefType, dims, op, rewriter, alignment); return alloc; } //===----------------------------------------------------------------------===// // Helper function of Zhigh to Zlow lowering // Insert an allocation and deallocation for the given ZMemRefType. // By default, set aligment to 4K. //===----------------------------------------------------------------------===// Value insertAllocAndDeallocZMemRef(ZMemRefType zType, ArrayRef<IndexExpr> dims, Operation *op, PatternRewriter &rewriter, int64_t alignment = gAlignment) { Location loc = op->getLoc(); MemRefType resType = zType.value; // Insert alloc and dealloc. Value alloc = insertAllocAndDeallocSimple(rewriter, op, resType, loc, SmallVector<IndexExpr>(dims.begin(), dims.end()), /*insertDealloc*/ ONNXToKrnl_gEmitDealloc, alignment); // Store the buffer's layout. Otherwise, we lost the layout. storeLayout(alloc, zType.layout); return alloc; } /// Insert allocation and deallocation for a 4K-aligned buffer of type /// <sizexi8> to be used as work_area in LSTM/GRU, where size is computed as /// follows. // /// Enough contiguous storage for the following stickified ztensors /// dimensions: /// Fused ztensor /// dim1 = hidden_state_size /// dim2 = batch /// dim3 = 1 /// dim4 = numOfGates * timestep /// /// Bias Add ztensor /// dim1 = hidden_state_size /// dim2 = batch /// dim3 = 1 /// dim4 = numOfGates /// /// C output ztensor /// dim1 = hidden_state_size /// dim2 = batch /// dim3 = 1 /// dim4 = 2 /// /// For bidirectional, twice the amount of contiguous storage is required. /// /// The start of the buffer must be 4k aligned. The work area size is /// computed as follows. /// zdnn_tensor_desc desc; /// desc.dim4 = (numOfGates * timestep) + numOfGates + 2; /// desc.dim3 = 1; /// desc.dim2 = batch; /// desc.dim1 = hidden_state_size; /// uint64_t work_area_size = zdnn_getsize_ztensor(&desc); /// /// It is unfolded to: /// work_area_size in bytes = dim4 * dim3 * /// CEIL(dim2, AIU_STICKS_PER_PAGE) * /// CEIL(dim1, AIU_2BYTE_CELLS_PER_STICK) * /// AIU_PAGESIZE_IN_BYTES; /// where CEIL(a, b) = (a + b - 1) / b, /// AIU_STICKS_PER_PAGE = 32, /// AIU_2BYTE_CELLS_PER_STICK = 64, /// AIU_PAGESIZE_IN_BYTES = 4K. /// /// timestep and batchsize are obtained from the LSTM/GRU input tensor. /// hidden_size is obtained from the LSTM/GRU initial hidden tensor. static Value insertAllocAndDeallocWorkAreaForRNNOps(PatternRewriter &rewriter, Location loc, Value rnnInput, Value rnnHiddenWeight, unsigned numOfGates, bool isDouble) { Value alloc; MemRefBoundsIndexCapture inputBounds(rnnInput); MemRefBoundsIndexCapture hiddenWeightBounds(rnnHiddenWeight); IndexExprScope scope(&rewriter, loc); DimIndexExpr timestepExp(inputBounds.getDim(0)); IndexExpr Lit2 = LiteralIndexExpr(2); IndexExpr NumOfGatesLit = LiteralIndexExpr(numOfGates); DimIndexExpr dim1(hiddenWeightBounds.getDim(1)); DimIndexExpr dim2(inputBounds.getDim(1)); IndexExpr dim3 = LiteralIndexExpr(1); IndexExpr dim4 = NumOfGatesLit * timestepExp + NumOfGatesLit + Lit2; IndexExpr Lit1 = LiteralIndexExpr(1); IndexExpr Lit32 = LiteralIndexExpr(32); IndexExpr Lit64 = LiteralIndexExpr(64); IndexExpr Lit4K = LiteralIndexExpr(4096); IndexExpr ceilDim2 = (dim2 + Lit32 - Lit1).floorDiv(Lit32); IndexExpr ceilDim1 = (dim1 + Lit64 - Lit1).floorDiv(Lit64); IndexExpr sizeExpr = dim4 * dim3 * ceilDim2 * ceilDim1 * Lit4K; // Double the work area if required. if (isDouble) sizeExpr = sizeExpr * Lit2; // Emit alloc and dealloc ops. int64_t size = sizeExpr.isLiteral() ? sizeExpr.getLiteral() : -1; MemRefType resultType = MemRefType::get({size}, rewriter.getIntegerType(8)); SmallVector<IndexExpr> dims(1, sizeExpr); alloc = insertAllocAndDeallocSimple(rewriter, nullptr, resultType, loc, dims, /*insertDealloc*/ ONNXToKrnl_gEmitDealloc, gAlignment); return alloc; } /// This function emits a buffer of zero elements for the given dimensions and /// layout. If the given dimensions are static, then a stickified constant is /// returned. Value insertAllocOrEmitZeroConstant(ArrayRef<IndexExpr> dims, ZTensorEncodingAttr::DataLayout layout, Operation *op, PatternRewriter &rewriter, Location loc) { Value res; bool allStaticDims = llvm::all_of(dims, [](IndexExpr ie) { return ie.isLiteral(); }); if (allStaticDims) { // Construct a MemRefType for the given dimensions and element type. SmallVector<int64_t, 4> shape; for (IndexExpr d : dims) shape.emplace_back(d.getLiteral()); RankedTensorType tensorType = RankedTensorType::get(shape, rewriter.getF32Type(), ZTensorEncodingAttr::get(op->getContext(), layout)); ZMemRefType zMemRefType = convertZTensorToMemRefType(tensorType); MemRefType resType = normalizeMemRefType(zMemRefType.value.cast<MemRefType>(), rewriter, /*numSymbolicOperands=*/0); // Create a ZHighStickifiedConstantOp. ZHighStickifiedConstantOp stickifiedConstant = rewriter.create<ZHighStickifiedConstantOp>(loc, resType, /*value=*/nullptr, /*alignment=*/rewriter.getI64IntegerAttr(4096)); // Use an opaque attribute to store stickified data. // Attribute type: tensor<sizeInBytes x i8> int64_t sizeInBytes = getMemRefSizeInBytes(resType).getValue(); char *rawData = (char *)malloc(sizeInBytes); memset(rawData, 0, sizeInBytes); OpaqueElementsAttr valueAttr = OpaqueElementsAttr::get(stickifiedConstant.getOperation()->getDialect(), RankedTensorType::get({sizeInBytes}, rewriter.getI8Type()), StringRef(rawData, sizeInBytes)); stickifiedConstant.valueAttr(valueAttr); free(rawData); res = stickifiedConstant.getResult(); } else { MultiDialectBuilder<KrnlBuilder, MathBuilder> create(rewriter, loc); res = insertAllocAndDeallocZMemRefByDim(dims, layout, op, rewriter); Value initValue = create.math.constant(rewriter.getF16Type(), 0); create.krnl.memset(res, initValue); } return res; } /// Emit instructions to allocate a buffer to store original dimensions. Value insertShapeMemRefI64( PatternRewriter &rewriter, Location loc, ArrayRef<IndexExpr> originalDims) { MultiDialectBuilder<KrnlBuilder, MathBuilder> create(rewriter, loc); MemRefType shapeMemRefType = MemRefType::get( {(int64_t)originalDims.size()}, rewriter.getIntegerType(64)); Value shapeMemRef = insertAllocAndDealloc( shapeMemRefType, loc, rewriter, ONNXToKrnl_gEmitDealloc); for (uint64_t i = 0; i < originalDims.size(); ++i) { Value dim = create.math.cast(rewriter.getI64Type(), originalDims[i].getValue()); create.krnl.storeIE(dim, shapeMemRef, {LiteralIndexExpr(i)}); } return shapeMemRef; } /// Get the corresponding MemRefType and layout of a given ZTensorType. ZMemRefType convertZTensorToMemRefType(Type type) { ZMemRefType resZMemRefType; if (type.isa<TensorType>()) { OpBuilder b(type.getContext()); RankedTensorType tensorType = type.dyn_cast<RankedTensorType>(); assert(tensorType && "expected only ranked shapes"); ArrayRef<int64_t> shape = tensorType.getShape(); Type elementType = tensorType.getElementType(); int64_t rank = shape.size(); if (tensorType.getEncoding()) { // Obtain element type and affine map. AffineExpr constExpr0 = getAffineConstantExpr(0, b.getContext()); AffineExpr constExpr31 = getAffineConstantExpr(31, b.getContext()); AffineExpr constExpr32 = getAffineConstantExpr(32, b.getContext()); AffineExpr constExpr64 = getAffineConstantExpr(64, b.getContext()); unsigned e4, e3, e2, e1; AffineExpr n, c, h, w, res32, res64; SmallVector<AffineExpr, 6> dimExpr; ZTensorEncodingAttr::DataLayout layout = getZTensorLayout(tensorType); if (layout == ZTensorEncodingAttr::DataLayout::_1D) { // (e1) -> (1, 1, 1, e1) -> (1, ceil(e1/64), 1, 1, 32, 64) e1 = 0; n = constExpr0; h = b.getAffineDimExpr(e1).floorDiv(constExpr64); w = constExpr0; c = constExpr0; res32 = constExpr31; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::_2D) { // (e2, e1) -> (1, 1, e2, e1) -> (1, ceil(e1/64), 1, ceil(e2/32), 32 // 64) e2 = 0; e1 = 1; n = constExpr0; h = b.getAffineDimExpr(e1).floorDiv(constExpr64); w = constExpr0; c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::_3D) { // (e3, e2, e1) -> (1, e3, e2, e1) // -> (1, ceil(e1/64), e3, ceil(e2/32), 32, 64) e3 = 0; e2 = 1; e1 = 2; n = constExpr0; h = b.getAffineDimExpr(e1).floorDiv(constExpr64); w = b.getAffineDimExpr(e3); c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::_4D) { // (e4, e3, e2, e1) -> (e4, ceil(e1/64), e3, ceil(e2/32), 32, 64) e4 = 0; e3 = 1; e2 = 2; e1 = 3; n = b.getAffineDimExpr(e4); h = b.getAffineDimExpr(e1).floorDiv(constExpr64); w = b.getAffineDimExpr(e3); c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::_2DS) { // (e4, e1) -> (e4, 1, 1, e1) -> (e4, ceil(e1/64), 1, 1, 32, 64) e4 = 0; e1 = 1; n = b.getAffineDimExpr(e4); h = b.getAffineDimExpr(e1).floorDiv(constExpr64); w = constExpr0; c = constExpr0; res32 = constExpr31; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::_3DS) { // (e4, e2, e1) -> (e4, 1, e2, e1) // -> (e4, ceil(e1/64), 1, ceil(e2/32), 32, 64) e4 = 0; e2 = 1; e1 = 2; n = b.getAffineDimExpr(e4); h = b.getAffineDimExpr(e1).floorDiv(constExpr64); w = constExpr0; c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::_4DS) { // for normal // (e4, e3, e2, e1) -> (e4, e3, e2, e1) // -> (e4, ceil(e1/64), e3, ceil(e2/32), 32, 64) // for bidirectional rnn // (e4, e3, e2, e1) -> (e4, 1, e2, e3 * PADDED(e1)) // -> (e4, ceil((e3 * PADDED(e1))/64), e3, ceil(e2/32), 32, 64) assert((shape[1] == 1) && "bidirectional lstm/gru not supported yet"); e4 = 0; e3 = 1; e2 = 2; e1 = 3; n = b.getAffineDimExpr(e4); h = b.getAffineDimExpr(e1).floorDiv(constExpr64); w = b.getAffineDimExpr(e3); c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::NHWC) { // (e4, e3, e2, e1) -> (e4, ceil(e1/64), e3, ceil(e2/32), 32, 64) e4 = 0; e3 = 1; e2 = 2; e1 = 3; n = b.getAffineDimExpr(e4); h = b.getAffineDimExpr(e1).floorDiv(constExpr64); w = b.getAffineDimExpr(e3); c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::NCHW) { // (e4, e3, e2, e1) -> (e4, ceil(e2/64), e1, ceil(e3/32), 32, 64) llvm_unreachable("Not tested yet"); e4 = 0; e3 = 1; e2 = 2; e1 = 3; n = b.getAffineDimExpr(e4); h = b.getAffineDimExpr(e2).floorDiv(constExpr64); w = b.getAffineDimExpr(e1); c = b.getAffineDimExpr(e3).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e3) % constExpr32; res64 = b.getAffineDimExpr(e2) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::HWCK) { // HWCK (e4, e3, e2, e1) -> KHWC (ceil(e1/64), e4,, e3, ceil(e2/32), // 32, 64) e4 = 0; e3 = 1; e2 = 2; e1 = 3; n = b.getAffineDimExpr(e1).floorDiv(constExpr64); h = b.getAffineDimExpr(e4); w = b.getAffineDimExpr(e3); c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = b.getAffineDimExpr(e1) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::FICO) { // (e4, e3, e2, e1) -> (e4, 4*ceil(e1/4/64), e3, ceil(e2/32), 32, 64) assert(shape[rank - 1] != -1 && (shape[rank - 1] % 4) == 0 && "wrong concatenated dimension size"); int64_t s = shape[rank - 1] / 4; // ((s + 64 - 1) / 64) * 64; int64_t s_pad = ceil((double)s / 64) * 64; int64_t pad_size = s_pad - s; AffineExpr constExprS = getAffineConstantExpr(s, b.getContext()); if (rank == 2) { e2 = 0; e1 = 1; w = constExpr0; } else if (rank == 3) { e3 = 0; e2 = 1; e1 = 2; w = b.getAffineDimExpr(e3); } else { llvm_unreachable("Unsupported rank in ZDNN_FICO layout"); } n = constExpr0; h = (b.getAffineDimExpr(e1) + pad_size * (b.getAffineDimExpr(e1).floorDiv(constExprS))) .floorDiv(constExpr64); c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = (b.getAffineDimExpr(e1) + pad_size * (b.getAffineDimExpr(e1).floorDiv(constExprS))) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::ZRH) { // (e4, e3, e2, e1) -> (e4, 3*ceil(e1/4/64), e3, ceil(e2/32), 32, 64) int64_t hidden_size = shape[rank - 1]; assert(hidden_size > 0 && "Dynamic dimension in hidden_size not supported " "in affine_map generation."); assert((hidden_size % 3) == 0 && "wrong concatenated dimension size."); int64_t s = hidden_size / 3; int64_t s_pad = ceil((float)s / 64) * 64; // ((s + 64 - 1) / 64) * 64; int64_t pad_size = s_pad - s; AffineExpr constExprS = getAffineConstantExpr(s, b.getContext()); if (rank == 2) { e2 = 0; e1 = 1; w = constExpr0; } else if (rank == 3) { e3 = 0; e2 = 1; e1 = 2; w = b.getAffineDimExpr(e3); } else { llvm_unreachable("Unsupported rank in ZDNN_ZRH layout"); } n = constExpr0; h = (b.getAffineDimExpr(e1) + pad_size * (b.getAffineDimExpr(e1).floorDiv(constExprS))) .floorDiv(constExpr64); c = b.getAffineDimExpr(e2).floorDiv(constExpr32); res32 = b.getAffineDimExpr(e2) % constExpr32; res64 = (b.getAffineDimExpr(e1) + pad_size * (b.getAffineDimExpr(e1).floorDiv(constExprS))) % constExpr64; } else if (layout == ZTensorEncodingAttr::DataLayout::BFICO) { llvm_unreachable("Unsupported layout yet"); } else if (layout == ZTensorEncodingAttr::DataLayout::BZRH) { llvm_unreachable("Unsupported layout yet"); } else llvm_unreachable("Unsupported layout"); dimExpr.emplace_back(n); dimExpr.emplace_back(h); dimExpr.emplace_back(w); dimExpr.emplace_back(c); dimExpr.emplace_back(res32); dimExpr.emplace_back(res64); AffineMap smap = AffineMap::get(rank, 0, dimExpr, b.getContext()); // Output type is F16 for zAIU. MemRefType outType = MemRefType::get(shape, b.getF16Type()); resZMemRefType.value = MemRefType::Builder(outType).setLayout(AffineMapAttr::get(smap)); resZMemRefType.layout = convertDataLayoutToStringAttr(b, layout); } else { resZMemRefType.value = MemRefType::get(shape, elementType); } } else { resZMemRefType.value = type.dyn_cast<MemRefType>(); } return resZMemRefType; } //===----------------------------------------------------------------------===// // Lower ZHigh Stick to ZLow Stick //===----------------------------------------------------------------------===// struct ZHighToZLowStickOpLowering : public ConversionPattern { ZHighToZLowStickOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighStickOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighStickOpAdaptor operandAdaptor(operands); Value input = operandAdaptor.In(); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. MemRefBoundsIndexCapture inputBounds(input); IndexExprScope scope(&rewriter, loc); SmallVector<IndexExpr, 4> dims; inputBounds.getDimList(dims); Value alloc = insertAllocAndDeallocZMemRef(zMemRefType, dims, op, rewriter); // Emit a ZLow operation. rewriter.create<ZLowStickOp>(loc, input, alloc, zMemRefType.layout); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh StickForLSTM to ZLow StickForLSTM //===----------------------------------------------------------------------===// struct ZHighToZLowStickForLSTMOpLowering : public ConversionPattern { ZHighToZLowStickForLSTMOpLowering( TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighStickForLSTMOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighStickForLSTMOp stickOp = llvm::dyn_cast<ZHighStickForLSTMOp>(op); ZHighStickForLSTMOpAdaptor operandAdaptor(operands); ZHighStickForLSTMOpShapeHelper shapeHelper(&stickOp, &rewriter); LogicalResult shapecomputed = shapeHelper.computeShape(operandAdaptor); assert(succeeded(shapecomputed) && "Could not compute output shape"); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. Value alloc = insertAllocAndDeallocZMemRef( zMemRefType, shapeHelper.dimsForOutput(0), op, rewriter); // Emit a ZLow operation. rewriter.create<ZLowStickForLSTMOp>(loc, operandAdaptor.f_gate(), operandAdaptor.i_gate(), operandAdaptor.c_gate(), operandAdaptor.o_gate(), alloc); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh StickForGRU to ZLow StickForGRU //===----------------------------------------------------------------------===// struct ZHighToZLowStickForGRUOpLowering : public ConversionPattern { ZHighToZLowStickForGRUOpLowering( TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighStickForGRUOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighStickForGRUOp stickOp = llvm::dyn_cast<ZHighStickForGRUOp>(op); ZHighStickForGRUOpAdaptor operandAdaptor(operands); ZHighStickForGRUOpShapeHelper shapeHelper(&stickOp, &rewriter); LogicalResult shapecomputed = shapeHelper.computeShape(operandAdaptor); assert(succeeded(shapecomputed) && "Could not compute output shape"); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. Value alloc = insertAllocAndDeallocZMemRef( zMemRefType, shapeHelper.dimsForOutput(0), op, rewriter); // Emit a ZLow operation. rewriter.create<ZLowStickForGRUOp>(loc, operandAdaptor.z_gate(), operandAdaptor.r_gate(), operandAdaptor.h_gate(), alloc); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh Unstick to ZLow Unstick //===----------------------------------------------------------------------===// struct ZHighToZLowUnstickOpLowering : public ConversionPattern { ZHighToZLowUnstickOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighUnstickOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighUnstickOpAdaptor operandAdaptor(operands); Value input = operandAdaptor.In(); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. MemRefBoundsIndexCapture inputBounds(input); IndexExprScope scope(&rewriter, loc); SmallVector<IndexExpr, 4> dims; inputBounds.getDimList(dims); Value alloc = insertAllocAndDeallocZMemRef( zMemRefType, dims, op, rewriter, /*alignment=*/-1); // Emit a ZLow operation. rewriter.create<ZLowUnstickOp>(loc, input, alloc, readLayout(input)); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh Stickified Constant to KrnlGlobal //===----------------------------------------------------------------------===// struct ZHighToZLowStickifiedConstantOpLowering : public ConversionPattern { static int constantID; ZHighToZLowStickifiedConstantOpLowering( TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern(typeConverter, ZHighStickifiedConstantOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighStickifiedConstantOp stickifiedConstOp = llvm::dyn_cast<ZHighStickifiedConstantOp>(op); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Normalize MemRefType to get a static shape. assert(zMemRefType.value.cast<MemRefType>().getNumDynamicDims() == 0 && "MemRefType has dynamic dimensions"); MemRefType normalizedType = normalizeMemRefType(zMemRefType.value.cast<MemRefType>(), rewriter, /*numSymbolicOperands=*/0); ArrayRef<int64_t> normalizedShape = normalizedType.getShape(); // Get Opaque attribute. StringRef data = stickifiedConstOp.value() .getValue() .cast<OpaqueElementsAttr>() .getValue(); // Validate the stickified tensor. int64_t memRefSizeInBytes = getMemRefEltSizeInBytes(normalizedType); memRefSizeInBytes *= normalizedType.getNumElements(); assert((data.size() == (uint64_t)memRefSizeInBytes) && "The stickied tensor's buffer size and MemRef's size mismatched"); // Create a KrnlGlobalOp. KrnlGlobalOp constantGlobal = rewriter.create<KrnlGlobalOp>(loc, zMemRefType.value, /*shape=*/ rewriter.getI64ArrayAttr(normalizedShape), /*name=*/ rewriter.getStringAttr( "constant_stickify_" + std::to_string(constantID)), /*value=*/stickifiedConstOp.valueAttr(), /*offset=*/nullptr, /*alignment=*/stickifiedConstOp.alignmentAttr()); // Increment constant ID: constantID++; rewriter.replaceOp(op, constantGlobal.getResult()); return success(); } }; int ZHighToZLowStickifiedConstantOpLowering::constantID = 0; template <typename OP_TYPE> struct ZLowOpFor { using Op = void; }; //===----------------------------------------------------------------------===// // Lower ZHigh binary ops to ZLow. //===----------------------------------------------------------------------===// template <> struct ZLowOpFor<ZHighAddOp> { using Op = ZLowAddOp; }; template <> struct ZLowOpFor<ZHighSubOp> { using Op = ZLowSubOp; }; template <> struct ZLowOpFor<ZHighMulOp> { using Op = ZLowMulOp; }; template <> struct ZLowOpFor<ZHighDivOp> { using Op = ZLowDivOp; }; template <> struct ZLowOpFor<ZHighMinOp> { using Op = ZLowMinOp; }; template <> struct ZLowOpFor<ZHighMaxOp> { using Op = ZLowMaxOp; }; template <typename OP_TYPE> struct ZHighToZLowBinaryOpLowering : public ConversionPattern { ZHighToZLowBinaryOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern(typeConverter, OP_TYPE::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); Value inputA = operands[0]; Value inputB = operands[1]; // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. MemRefBoundsIndexCapture inputBounds(inputA); IndexExprScope scope(&rewriter, loc); SmallVector<IndexExpr, 4> dims; inputBounds.getDimList(dims); Value alloc = insertAllocAndDeallocZMemRef(zMemRefType, dims, op, rewriter); // Get the original shape before it is vanished by lower passes. Value shape = insertShapeMemRefI64(rewriter, loc, dims); rewriter.create<typename ZLowOpFor<OP_TYPE>::Op>( loc, inputA, inputB, shape, alloc, zMemRefType.layout); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh unary ops to ZLow. //===----------------------------------------------------------------------===// template <> struct ZLowOpFor<ZHighLogOp> { using Op = ZLowLogOp; }; template <> struct ZLowOpFor<ZHighExpOp> { using Op = ZLowExpOp; }; template <> struct ZLowOpFor<ZHighReluOp> { using Op = ZLowReluOp; }; template <> struct ZLowOpFor<ZHighTanhOp> { using Op = ZLowTanhOp; }; template <> struct ZLowOpFor<ZHighSigmoidOp> { using Op = ZLowSigmoidOp; }; template <typename OP_TYPE> struct ZHighToZLowUnaryOpLowering : public ConversionPattern { ZHighToZLowUnaryOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern(OP_TYPE::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); Value input = operands[0]; // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. MemRefBoundsIndexCapture inputBounds(input); IndexExprScope scope(&rewriter, loc); SmallVector<IndexExpr, 4> dims; inputBounds.getDimList(dims); Value alloc = insertAllocAndDeallocZMemRef(zMemRefType, dims, op, rewriter); // Get the original shape before it is vanished by lower passes. Value shape = insertShapeMemRefI64(rewriter, loc, dims); // Emit a ZLow operation. rewriter.create<typename ZLowOpFor<OP_TYPE>::Op>( loc, input, shape, alloc, zMemRefType.layout); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh Softmax to ZLow Softmax //===----------------------------------------------------------------------===// struct ZHighToZLowSoftmaxOpLowering : public ConversionPattern { ZHighToZLowSoftmaxOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighSoftmaxOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighSoftmaxOp softmaxOp = llvm::dyn_cast<ZHighSoftmaxOp>(op); ZHighSoftmaxOpAdaptor operandAdaptor(operands); Value input = operands[0]; // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. MemRefBoundsIndexCapture inputBounds(input); IndexExprScope scope(&rewriter, loc); SmallVector<IndexExpr, 4> dims; inputBounds.getDimList(dims); Value alloc = insertAllocAndDeallocZMemRef(zMemRefType, dims, op, rewriter); // Get the original shape before it is vanished by lower passes. Value shape = insertShapeMemRefI64(rewriter, loc, dims); // Emit 'alloc' and 'dealloc' for work_area that is of 4K-aligned 8K bytes. Value workArea = insertAllocAndDealloc( MemRefType::get({8 * 1024}, rewriter.getIntegerType(8)), loc, rewriter, /*insertDealloc=*/ONNXToKrnl_gEmitDealloc, {}, /*alignment=*/gAlignment); // Emit ZLow.softmax. rewriter.create<ZLowSoftmaxOp>( loc, input, workArea, shape, alloc, softmaxOp.act_funcAttr()); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh MeanReduce2D to ZLow MeanReduce2D //===----------------------------------------------------------------------===// struct ZHighToZLowMeanReduce2DOpLowering : public ConversionPattern { ZHighToZLowMeanReduce2DOpLowering( TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighMeanReduce2DOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighMeanReduce2DOpAdaptor operandAdaptor(operands); Value input = operandAdaptor.input(); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. MemRefBoundsIndexCapture inputBounds(input); IndexExprScope scope(&rewriter, loc); SmallVector<IndexExpr, 4> dims; inputBounds.getDimList(dims); // Get the original shape before it is vanished by lower passes. Value shape = insertShapeMemRefI64(rewriter, loc, dims); // Input is NHWC, and H and W are reduction dimensions. dims[1] = LiteralIndexExpr(1); dims[2] = LiteralIndexExpr(1); Value alloc = insertAllocAndDeallocZMemRef(zMemRefType, dims, op, rewriter); rewriter.create<ZLowMeanReduce2DOp>(loc, input, shape, alloc); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh Pool2D to ZLow Pool2D //===----------------------------------------------------------------------===// template <typename ZHIGHPOOLOP, typename ZHIGHADAPTOR, typename ZLOWPOOLOP> struct ZHighToZLowPool2DOpLowering : public ConversionPattern { ZHighToZLowPool2DOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHIGHPOOLOP::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHIGHPOOLOP pool2dOp = llvm::dyn_cast<ZHIGHPOOLOP>(op); ZHIGHADAPTOR operandAdaptor(operands); // Helper builders. MultiDialectBuilder<KrnlBuilder, MathBuilder> create(rewriter, loc); IndexExprScope scope(create.krnl); // Infer shape. ZHighPoolingOpShapeHelper<ZHIGHPOOLOP, ZHIGHADAPTOR> shapeHelper( &pool2dOp, &rewriter); LogicalResult shapecomputed = shapeHelper.computeShape(operandAdaptor); assert(succeeded(shapecomputed) && "Could not compute output shape"); // Convert type. ZMemRefType zMemRefType = convertZTensorToMemRefType(pool2dOp.getResult().getType()); // Allocate result buffers. Value alloc = insertAllocAndDeallocZMemRef( zMemRefType, shapeHelper.dimsForOutput(0), op, rewriter); // Create a buffer to store the original shape information. Value shapeMemRef = insertShapeMemRefI64(rewriter, loc, shapeHelper.allOriginalDims); // Create a zLow op. rewriter.create<ZLOWPOOLOP>(loc, operandAdaptor.input(), shapeMemRef, alloc, pool2dOp.kernel_shapeAttr(), pool2dOp.stridesAttr(), pool2dOp.padding_typeAttr()); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh MatMul to ZLow MatMul //===----------------------------------------------------------------------===// struct ZHighToZLowMatMulOpLowering : public ConversionPattern { ZHighToZLowMatMulOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighMatMulOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighMatMulOp matmulOp = llvm::dyn_cast<ZHighMatMulOp>(op); ZHighMatMulOpAdaptor operandAdaptor(operands); MultiDialectBuilder<KrnlBuilder, MathBuilder> create(rewriter, loc); IndexExprScope scope(create.krnl); ZHighMatMulOpShapeHelper shapeHelper(&matmulOp, &rewriter); LogicalResult shapecomputed = shapeHelper.computeShape(operandAdaptor); assert(succeeded(shapecomputed) && "Could not compute output shape"); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); Value alloc = insertAllocAndDeallocZMemRef( zMemRefType, shapeHelper.dimsForOutput(0), op, rewriter); // Get the original shape before it is vanished by lower passes. // Create a 1D MemRef containing necessary dimensions for construcing // original shapes. // - In case of unstacked: X(m, n) * Y(n, p) + Bias(p) // shape is a 1D MemRef (memref<3xindex>) whose items are: // - 1st item: m // - 2nd item: n // - 3rd item: p // - In case of stacked: X(s, m, n) * Y(s, n, p) + Bias(s, p) // or broadcasting: X(s, m, n) * Y(n, p) + Bias(p) // shape is a 1D MemRef (memref<4xindex>) whose items are: // - 1st item: s // - 2nd item: m // - 3rd item: n // - 4th item: p Value shapeMemRef = insertShapeMemRefI64(rewriter, loc, shapeHelper.allOriginalDims); // Prepare optional bias. Value bias = operandAdaptor.B(); if (bias.getType().isa<NoneType>()) { MemRefBoundsIndexCapture resBounds(alloc); SmallVector<IndexExpr, 2> biasDims; ZTensorEncodingAttr::DataLayout biasLayout; if (shapeHelper.isStacked) { // Bias type is 2DS. biasDims.emplace_back(resBounds.getDim(0)); biasDims.emplace_back(resBounds.getDim(2)); biasLayout = ZTensorEncodingAttr::DataLayout::_2DS; } else { // Bias type is 1D. Get the last dim size. biasDims.emplace_back(resBounds.getDim(resBounds.getRank() - 1)); biasLayout = ZTensorEncodingAttr::DataLayout::_1D; } // Allocate bias. bias = insertAllocOrEmitZeroConstant( biasDims, biasLayout, op, rewriter, loc); } // Attributes. int64_t bcast = (shapeHelper.isBroadcasted) ? -1 : 0; int64_t stacked = (shapeHelper.isStacked) ? -1 : 0; IntegerAttr is_bcastAttr = rewriter.getIntegerAttr(rewriter.getIntegerType(64, true), bcast); IntegerAttr is_stackedAttr = rewriter.getIntegerAttr(rewriter.getIntegerType(64, true), stacked); // Emit zlow.matmul. rewriter.create<ZLowMatMulOp>(loc, operandAdaptor.X(), operandAdaptor.Y(), bias, shapeMemRef, alloc, is_bcastAttr, is_stackedAttr); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh LSTM to ZLow LSTM //===----------------------------------------------------------------------===// struct ZHighToZLowLSTMOpLowering : public ConversionPattern { ZHighToZLowLSTMOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighLSTMOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighLSTMOp lstmOp = llvm::dyn_cast<ZHighLSTMOp>(op); ZHighLSTMOpAdaptor operandAdaptor(operands); // Helper builders. MultiDialectBuilder<KrnlBuilder, MathBuilder> create(rewriter, loc); IndexExprScope scope(create.krnl); // Infer shape. ZHighLSTMOpShapeHelper shapeHelper(&lstmOp, &rewriter); LogicalResult shapecomputed = shapeHelper.computeShape(operandAdaptor); assert(succeeded(shapecomputed) && "Could not compute output shape"); // Convert type. ZMemRefType hnZMemRefType = convertZTensorToMemRefType(lstmOp.getResults()[0].getType()); ZMemRefType cfZMemRefType = convertZTensorToMemRefType(lstmOp.getResults()[1].getType()); // Allocate result buffers. Value allocHnOutput = insertAllocAndDeallocZMemRef( hnZMemRefType, shapeHelper.dimsForOutput(0), op, rewriter); Value allocCfOutput = insertAllocAndDeallocZMemRef( cfZMemRefType, shapeHelper.dimsForOutput(1), op, rewriter); // Get the original shape before it is vanished by lower passes. // Create a 1D MemRef containing necessary dimensions for construcing // original shapes. // shapeMemRef :: memref<5xindex> // - 1st item: direction // - 2nd item: timestep // - 3rd item: batchSize // - 4th item: featureSize // - 5th item: hiddenSize Value shapeMemRef = insertShapeMemRefI64(rewriter, loc, shapeHelper.allOriginalDims); // Prepare optional values: input_bias, hidden_bias, initial_h, initial_c. Value initial_h = operandAdaptor.h0(); Value initial_c = operandAdaptor.c0(); Value input_bias = operandAdaptor.input_bias(); Value hidden_bias = operandAdaptor.hidden_bias(); if (initial_h.getType().isa<NoneType>()) { initial_h = insertAllocOrEmitZeroConstant(shapeHelper.hc0Shape, ZTensorEncodingAttr::DataLayout::_3DS, op, rewriter, loc); } if (initial_c.getType().isa<NoneType>()) { initial_c = insertAllocOrEmitZeroConstant(shapeHelper.hc0Shape, ZTensorEncodingAttr::DataLayout::_3DS, op, rewriter, loc); } if (input_bias.getType().isa<NoneType>()) { input_bias = insertAllocOrEmitZeroConstant(shapeHelper.biasShape, ZTensorEncodingAttr::DataLayout::FICO, op, rewriter, loc); } if (hidden_bias.getType().isa<NoneType>()) { hidden_bias = insertAllocOrEmitZeroConstant(shapeHelper.biasShape, ZTensorEncodingAttr::DataLayout::FICO, op, rewriter, loc); } // Prepare work area. Double the area for the bidirectional mode. bool isDouble = lstmOp.directionAttr().getValue().equals_insensitive("bidirectional"); Value workArea = insertAllocAndDeallocWorkAreaForRNNOps(rewriter, loc, operandAdaptor.input(), operandAdaptor.hidden_weights(), /*numOfGates=*/4, /*isDouble=*/isDouble); // Emit zlow.lstm. rewriter.create<ZLowLSTMOp>(loc, operandAdaptor.input(), initial_h, initial_c, operandAdaptor.input_weights(), input_bias, operandAdaptor.hidden_weights(), hidden_bias, workArea, shapeMemRef, allocHnOutput, allocCfOutput, lstmOp.directionAttr(), lstmOp.return_all_stepsAttr()); std::vector<Value> outputs = {allocHnOutput, allocCfOutput}; rewriter.replaceOp(op, outputs); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh GRU to ZLow GRU //===----------------------------------------------------------------------===// struct ZHighToZLowGRUOpLowering : public ConversionPattern { ZHighToZLowGRUOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighGRUOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighGRUOp gruOp = llvm::dyn_cast<ZHighGRUOp>(op); ZHighGRUOpAdaptor operandAdaptor(operands); // Helper builders. MultiDialectBuilder<KrnlBuilder, MathBuilder> create(rewriter, loc); IndexExprScope scope(create.krnl); // Infer shape. ZHighGRUOpShapeHelper shapeHelper(&gruOp, &rewriter); LogicalResult shapecomputed = shapeHelper.computeShape(operandAdaptor); assert(succeeded(shapecomputed) && "Could not compute output shape"); // Convert type. ZMemRefType hnZMemRefType = convertZTensorToMemRefType(gruOp.getResult().getType()); // Allocate result buffers. Value allocHnOutput = insertAllocAndDeallocZMemRef( hnZMemRefType, shapeHelper.dimsForOutput(0), op, rewriter); // Get the original shape before it is vanished by lower passes. // Create a 1D MemRef containing necessary dimensions for construcing // original shapes. // shapeMemRef :: memref<5xindex> // - 1st item: direction // - 2nd item: timestep // - 3rd item: batchSize // - 4th item: featureSize // - 5th item: hiddenSize Value shapeMemRef = insertShapeMemRefI64(rewriter, loc, shapeHelper.allOriginalDims); // Prepare optional values: input_bias, hidden_bias, initial_h. Value initial_h = operandAdaptor.h0(); Value input_bias = operandAdaptor.input_bias(); Value hidden_bias = operandAdaptor.hidden_bias(); if (initial_h.getType().isa<NoneType>()) { initial_h = insertAllocOrEmitZeroConstant(shapeHelper.h0Shape, ZTensorEncodingAttr::DataLayout::_3DS, op, rewriter, loc); } if (input_bias.getType().isa<NoneType>()) { input_bias = insertAllocOrEmitZeroConstant(shapeHelper.biasShape, ZTensorEncodingAttr::DataLayout::ZRH, op, rewriter, loc); } if (hidden_bias.getType().isa<NoneType>()) { hidden_bias = insertAllocOrEmitZeroConstant(shapeHelper.biasShape, ZTensorEncodingAttr::DataLayout::ZRH, op, rewriter, loc); } // Prepare work area. Double the area for the bidirectional mode. bool isDouble = gruOp.directionAttr().getValue().equals_insensitive("bidirectional"); Value workArea = insertAllocAndDeallocWorkAreaForRNNOps(rewriter, loc, operandAdaptor.input(), operandAdaptor.hidden_weights(), /*numOfGates=*/3, /*isDouble=*/isDouble); // Emit zlow.gru. rewriter.create<ZLowGRUOp>(loc, operandAdaptor.input(), initial_h, operandAdaptor.input_weights(), input_bias, operandAdaptor.hidden_weights(), hidden_bias, workArea, shapeMemRef, allocHnOutput, gruOp.directionAttr(), gruOp.return_all_stepsAttr()); rewriter.replaceOp(op, allocHnOutput); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh Conv2D to ZLow Conv2D //===----------------------------------------------------------------------===// struct ZHighToZLowConv2DOpLowering : public ConversionPattern { ZHighToZLowConv2DOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighConv2DOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighConv2DOp conv2dOp = llvm::dyn_cast<ZHighConv2DOp>(op); ZHighConv2DOpAdaptor operandAdaptor(operands); // Helper builders. MultiDialectBuilder<KrnlBuilder, MathBuilder> create(rewriter, loc); IndexExprScope scope(create.krnl); // Infer shape. ZHighConv2DOpShapeHelper shapeHelper(&conv2dOp, &rewriter); LogicalResult shapecomputed = shapeHelper.computeShape(operandAdaptor); assert(succeeded(shapecomputed) && "Could not compute output shape"); // Convert type. ZMemRefType zMemRefType = convertZTensorToMemRefType(conv2dOp.getResult().getType()); // Allocate result buffers. Value alloc = insertAllocAndDeallocZMemRef( zMemRefType, shapeHelper.dimsForOutput(0), op, rewriter); // Create a buffer to store the original shape information. Value shapeMemRef = insertShapeMemRefI64(rewriter, loc, shapeHelper.allOriginalDims); // Prepare optional values: input_bias. Value bias = operandAdaptor.input_bias(); if (bias.getType().isa<NoneType>()) { // Bias's shape is [Channel_out]. SmallVector<IndexExpr> dims(1, shapeHelper.allOriginalDims[4]); bias = insertAllocOrEmitZeroConstant( dims, ZTensorEncodingAttr::DataLayout::_1D, op, rewriter, loc); } // Create a zLow op. rewriter.create<ZLowConv2DOp>(loc, operandAdaptor.input(), operandAdaptor.input_kernel(), bias, shapeMemRef, alloc, conv2dOp.kernel_shapeAttr(), conv2dOp.stridesAttr(), conv2dOp.padding_typeAttr(), conv2dOp.act_funcAttr()); rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // Lower ZHigh BatchNorm to ZLow BatchNorm //===----------------------------------------------------------------------===// struct ZHighToZLowBatchNormOpLowering : public ConversionPattern { ZHighToZLowBatchNormOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighBatchNormOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { Location loc = op->getLoc(); ZHighBatchNormOpAdaptor operandAdaptor(operands); Value input = operandAdaptor.input(); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. MemRefBoundsIndexCapture inputBounds(input); IndexExprScope scope(&rewriter, loc); SmallVector<IndexExpr, 4> dims; inputBounds.getDimList(dims); Value alloc = insertAllocAndDeallocZMemRef(zMemRefType, dims, op, rewriter); // Get the original shape before it is vanished by lower passes. Value shape = insertShapeMemRefI64(rewriter, loc, dims); rewriter.create<ZLowBatchNormOp>(loc, operandAdaptor.input(), operandAdaptor.a(), operandAdaptor.b(), shape, alloc); rewriter.replaceOp(op, alloc); return success(); } }; struct ZHighToZLowConcatOpLowering : public ConversionPattern { ZHighToZLowConcatOpLowering(TypeConverter &typeConverter, MLIRContext *ctx) : ConversionPattern( typeConverter, ZHighConcatOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { // Gather info. auto loc = op->getLoc(); ZHighConcatOpAdaptor operandAdaptor(operands); ZHighConcatOp concatOp = llvm::cast<ZHighConcatOp>(op); ZHighConcatOpShapeHelper shapeHelper(&concatOp, &rewriter, krnl::getDenseElementAttributeFromKrnlValue, krnl::loadDenseElementArrayValueAtIndex); auto shapecomputed = shapeHelper.computeShape(operandAdaptor); (void)shapecomputed; assert(succeeded(shapecomputed) && "Could not compute output shape"); auto axis = concatOp.axis(); unsigned int inputNum = operands.size(); // Convert ZTensor type to MemRefType. ZMemRefType zMemRefType = convertZTensorToMemRefType(*op->result_type_begin()); // Allocate a buffer for the result MemRef. Value alloc = insertAllocAndDeallocZMemRef( zMemRefType, shapeHelper.dimsForOutput(), op, rewriter); unsigned int rank = zMemRefType.value.getRank(); MultiDialectBuilder<KrnlBuilder> create(rewriter, loc); // Creates loops, one for each input. KrnlBuilder createKrnl(rewriter, loc); for (unsigned int i = 0; i < inputNum; ++i) { OpBuilder::InsertionGuard insertGuard(rewriter); // Create loop. ValueRange loopDef = createKrnl.defineLoops(rank); SmallVector<IndexExpr, 4> lbs(rank, LiteralIndexExpr(0)); MemRefBoundsIndexCapture bounds(operands[i]); SmallVector<IndexExpr, 4> ubs; bounds.getDimList(ubs); createKrnl.iterateIE(loopDef, loopDef, lbs, ubs, [&](KrnlBuilder &createKrnl, ValueRange loopInd) { // Indices for the read and write. SmallVector<Value, 4> readIndices, writeIndices; for (unsigned int r = 0; r < rank; ++r) { if (r != axis || i == 0) writeIndices.emplace_back(loopInd[r]); else { IndexExprScope IEScope(&rewriter, loc); IndexExpr writeOffset = DimIndexExpr(loopInd[r]); for (unsigned int j = 0; j < i; j++) { MemRefBoundsIndexCapture operandJBounds(operands[j]); writeOffset = writeOffset + operandJBounds.getDim(r); } writeIndices.emplace_back(writeOffset.getValue()); } } // Insert copy. Value loadData = createKrnl.load(operands[i], loopInd); createKrnl.store(loadData, alloc, writeIndices); }); } rewriter.replaceOp(op, alloc); return success(); } }; void populateZHighToZLowConversionPattern(mlir::RewritePatternSet &patterns, mlir::TypeConverter &typeConverter, mlir::MLIRContext *ctx) { patterns.insert<ZHighToZLowStickifiedConstantOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowStickOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowStickForLSTMOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowStickForGRUOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowUnstickOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowBinaryOpLowering<ZHighAddOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowBinaryOpLowering<ZHighSubOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowBinaryOpLowering<ZHighMulOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowBinaryOpLowering<ZHighDivOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowBinaryOpLowering<ZHighMinOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowBinaryOpLowering<ZHighMaxOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowUnaryOpLowering<ZHighLogOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowUnaryOpLowering<ZHighExpOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowUnaryOpLowering<ZHighReluOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowUnaryOpLowering<ZHighTanhOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowUnaryOpLowering<ZHighSigmoidOp>>( typeConverter, ctx); patterns.insert<ZHighToZLowSoftmaxOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowMeanReduce2DOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowMatMulOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowLSTMOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowGRUOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowBatchNormOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowConv2DOpLowering>(typeConverter, ctx); patterns.insert<ZHighToZLowPool2DOpLowering<ZHighMaxPool2DOp, ZHighMaxPool2DOpAdaptor, ZLowMaxPool2DOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowPool2DOpLowering<ZHighAvgPool2DOp, ZHighAvgPool2DOpAdaptor, ZLowAvgPool2DOp>>(typeConverter, ctx); patterns.insert<ZHighToZLowConcatOpLowering>(typeConverter, ctx); } } // namespace zhigh } // namespace onnx_mlir
635f9b7c4cfa4f18b41edc4b878711064bf31412
83d47b2a4aab88aa95c3a8742bb069088846e9c0
/repository/0209.cpp
73c02394f303f76a15718f0ba1590fe5a9f08100
[]
no_license
motxx/AOJ
9285ef7c51c866bab479759a68d3dcac1d3e2abe
3ac7c25d2cb51bf852706b603a5c936a57400b64
refs/heads/master
2021-01-09T20:40:11.522538
2016-07-13T21:00:27
2016-07-13T21:00:27
61,233,346
0
0
null
null
null
null
UTF-8
C++
false
false
3,721
cpp
0209.cpp
#include <algorithm> #include <bitset> #include <cctype> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <vector> using namespace std; #define INF (1 << 29) // math #define Sq(x) ((x) * (x)) // container utility #define ALL(x) (x).begin(), (x).end() #define MP make_pair #define PB push_back #define EACH(it, c) \ for (__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++) // rep #define REP(i, a, b) for (int i = a; i < b; i++) #define rep(i, n) REP(i, 0, n) // debug #define dump(x) cerr << #x << " = " << (x) << endl; #define debug(x) \ cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \ << " " << __FILE__ << endl; // typedef typedef pair<int, int> PII; typedef vector<int> VI; typedef vector<PII> VII; typedef vector<VI> VVI; typedef long long ll; // useful #define FST first #define SND second #define CK(n, a, b) (a <= n && n < b) // conversion template <class T> inline string toStr(T a) { ostringstream oss; oss << a; return oss.str(); } inline int toInt(string s) { return atoi(s.c_str()); } // prime bool isPrime(int a) { for (int i = 2; i * i <= a; i++) if (a % i == 0) return false; return true; } // !!! set SSIEVVE_MAX_L number !!! #define SSIEVE_MAX_L (1000001) #define SSIEVE_MAX_SQRT_B ((int)sqrt(INT_MAX) + 1) bool is_prime[SSIEVE_MAX_L]; vector<bool> is_prime_small(SSIEVE_MAX_SQRT_B); void segment_sieve(ll a, ll b) { for (int i = 0; (ll)i * i < b; i++) is_prime_small[i] = true; for (int i = 0; i < b - a; i++) is_prime[i] = true; if (a == 1) { is_prime[0] = false; } for (int i = 2; (ll)i * i < b; i++) { if (is_prime_small[i]) { for (int j = 2 * i; (ll)j * j < b; j += i) is_prime_small[j] = false; for (ll j = max(2LL, (a + i - 1) / i) * i; j < b; j += i) is_prime[j - a] = false; } } } int const dx[] = {-1, 0, 1, 0, -1, 1, 1, -1}; int const dy[] = {0, -1, 0, 1, -1, -1, 1, 1}; ////////////////////////////////////////////////////////////// int M[120][120]; int G[4][30][30]; int main() { int n, m; while (cin >> n >> m && (n | m)) { rep(i, n) rep(j, n) cin >> M[i][j]; rep(i, m) rep(j, m) cin >> G[0][i][j]; rep(k, 3) rep(i, m) rep(j, m) G[k + 1][m - 1 - j][i] = G[k][i][j]; VII data; rep(k, 4) { int ax = INF, ay; rep(i, m) { rep(j, m) { if (G[k][i][j] != -1) { ax = j, ay = i; break; } } if (ax != INF) { break; } } data.PB(PII(ax, ay)); } int ax = INF, ay = INF; rep(i, n - m + 1) { rep(j, n - m + 1) { rep(k, 4) { bool ok = 1; rep(a, m) { rep(b, m) { if (G[k][a][b] == -1) { continue; } if (G[k][a][b] != M[i + a][j + b]) { ok = 0; break; } } if (!ok) { break; } } if (!ok) continue; if (ay > i + data[k].SND) { ax = j + data[k].FST, ay = i + data[k].SND; } else if (ay == i + data[k].SND) { if (ax > j + data[k].FST) { ax = j + data[k].FST; } } } } } if (ax == INF) { cout << "NA" << endl; } else { cout << ax + 1 << ' ' << ay + 1 << endl; } } return 0; }
af4516729406a4340e693c98595b7f8273a914fd
47ff8543c73dab22c7854d9571dfc8d5f467ee8c
/BOJ/10835/10835.cpp
e7760a1d4d70d674b996728df81a8db667caa8ae
[]
no_license
eldsg/BOJ
4bb0c93dc60783da151e685530fa9a511df3a141
6bd15e36d69ce1fcf208d193d5e9067de9bb405e
refs/heads/master
2020-04-16T02:18:55.808362
2017-11-28T11:02:37
2017-11-28T11:02:37
55,879,791
2
0
null
null
null
null
UTF-8
C++
false
false
777
cpp
10835.cpp
#include<iostream> #include<vector> #include<algorithm> #include<string.h> #include<stdio.h> using namespace std; int N, A, B; vector<int> cardleft; vector<int> cardright; vector< vector <int> > dp; int solve(int a, int b){ if(a >= N || b >= N) return 0; if(dp[a][b] != -1) return dp[a][b]; int result = 0; result = max(result, solve(a+1,b)); result = max(result, solve(a+1,b+1)); if(cardleft[a] > cardright[b]){ result = max(result, cardright[b]+solve(a, b+1)); } dp[a][b] = result; return result; } int main(){ scanf("%d", &N); dp = vector < vector<int> >(N, vector<int>(N,-1)); for(int i = 0; i<N; i++){ scanf("%d", &A); cardleft.push_back(A); } for(int i = 0; i<N; i++){ scanf("%d", &B); cardright.push_back(B); } cout << solve(0,0) << endl; }
31dd2913561af70b7d4f77b8fe0c67c4daca2636
b73eec3a26bdcffb6a19dec6b8b048079befe04c
/3rdparty/meshlab-master/src/external/CoMISo/NSolver/NProblemInterface.hh
260b9511d7744f7742f21897ff6ca5b5d024a06b
[ "GPL-3.0-only", "MIT", "GPL-1.0-or-later" ]
permissive
HoEmpire/slambook2
c876494174e7f636bdf5b5743fab7d9918c52898
96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4
refs/heads/master
2020-07-24T02:35:39.488466
2019-11-25T03:08:17
2019-11-25T03:08:17
207,775,582
0
0
MIT
2019-09-11T09:35:56
2019-09-11T09:35:56
null
UTF-8
C++
false
false
2,519
hh
NProblemInterface.hh
//============================================================================= // // CLASS NProblemGmmInterface // //============================================================================= #ifndef COMISO_NPROBLEMINTERFACE_HH #define COMISO_NPROBLEMINTERFACE_HH //== COMPILE-TIME PACKAGE REQUIREMENTS ======================================== #include <CoMISo/Config/config.hh> #if COMISO_EIGEN3_AVAILABLE //== INCLUDES ================================================================= #include <Eigen/Eigen> #if !(EIGEN_VERSION_AT_LEAST(3,1,0)) #define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET #endif #include <Eigen/Sparse> #include <CoMISo/Config/CoMISoDefines.hh> //== FORWARDDECLARATIONS ====================================================== //== NAMESPACES =============================================================== namespace COMISO { //== CLASS DEFINITION ========================================================= /** \class NProblemGmmInterface NProblemGmmInterface.hh <ACG/.../NPRoblemGmmInterface.hh> Brief Description. A more elaborate description follows. */ class COMISODLLEXPORT NProblemInterface { public: // Sparse Matrix Type #if EIGEN_VERSION_AT_LEAST(3,1,0) typedef Eigen::SparseMatrix<double,Eigen::ColMajor> SMatrixNP; #else typedef Eigen::DynamicSparseMatrix<double,Eigen::ColMajor> SMatrixNP; #endif /// Default constructor NProblemInterface(); /// Destructor virtual ~NProblemInterface(); // problem definition virtual int n_unknowns ( ) = 0; virtual void initial_x ( double* _x ) = 0; virtual double eval_f ( const double* _x ) = 0; virtual void eval_gradient( const double* _x, double* _g) = 0; virtual void eval_hessian ( const double* _x, SMatrixNP& _H) = 0; virtual void store_result ( const double* _x ) = 0; // advanced properties virtual bool constant_gradient() const { return false; } virtual bool constant_hessian() const { return false; } }; //============================================================================= } // namespace COMISO //============================================================================= #endif // COMISO_EIGEN3_AVAILABLE //============================================================================= #endif // COMISO_NPROBLEMGMMINTERFACE_HH defined //=============================================================================
31befe5d29d885b706e91aa900f80fa7cdaf2e2f
d8a31f35fadc056a36670d6572def108857d3534
/chapter 4/HSring.cpp
871747d64e9073edf506963ecaac24a4f97b210f
[]
no_license
ZhangChengmin99/DS_yan
3477afce32ba85cea9f9785a843d278e0d29843d
9644bf5340f133684047a48c720ff668a36366b7
refs/heads/master
2020-07-16T11:23:28.445395
2017-01-01T14:25:02
2017-01-01T14:25:02
null
0
0
null
null
null
null
GB18030
C++
false
false
4,518
cpp
HSring.cpp
#include <stdlib.h> #include <stdio.h> #include "HString.h" Status StrAssign(HString &T, char *chars){ // 生成一个其值等于串常量chars的串T int i; char *c; if (T.ch) free(T.ch); for (i = 0, c = chars; *c; ++i, ++c); if (!i){ T.ch = NULL; T.length = 0; } else{ if (!(T.ch = (char *)malloc(i * sizeof(char)))) exit(OVERFLOW); for (int j = 0; j < i; j++) T.ch[j] = chars[j]; T.length = i; } return OK; }// StrAssign Status StrCopy(HString &T, HString S){ // 若串S存在,由串S复制得串T,并返回OK,否则返回ERROR int i = 0; if (!S.ch) return ERROR; if (T.ch) free(T.ch); if (!(T.ch = (char *)malloc(S.length * sizeof(char)))) exit(OVERFLOW); T.length = S.length; for (i = 0; i < T.length; i++) T.ch[i] = S.ch[i]; return OK; }// StrCopy Status StrEmpty(HString S){ // 若S为空串,则返回TRUE,否则返回FALSE if (!S.ch) return ERROR; if (S.length == 0){ return TRUE; } else{ return FALSE; } }// StrEmpty int StrLength(HString S){ // 返回S的元素个数,称为串的长度 return S.length; }// StrLength int StrCompare(HString S, HString T){ // 若S > T,则返回值 > 0,若S = T,则返回值 = 0,若S < T,则返回值 < 0 int i; for (i = 0; i < S.length && i < T.length; ++i) if (S.ch[i] != T.ch[i]) return S.ch[i] - T.ch[i]; return S.length - T.length; }// StrCompare Status ClearString(HString &S){ // 将S清为空串 if (S.ch){ free(S.ch); S.ch = NULL; } S.length = 0; return OK; }// ClearString Status Concat(HString &T, HString S1, HString S2){ // 用T返回由S1与S2联结而成的新串 int i; if (T.ch) free(T.ch); if (!(T.ch = (char *)malloc((S1.length + S2.length)*sizeof(char)))) exit(OVERFLOW); for (i = 0; i < S1.length; i++) T.ch[i] = S1.ch[i]; T.length = S1.length + S2.length; for (i = 0; i < S2.length; i++) T.ch[i + S1.length] = S2.ch[i]; return OK; }// Concat Status SubString(HString &Sub, HString S, int pos, int len){ // 用Sub返回串S的第pos个字符起长度为len的子串 // 其中,1 <= pos <= StrLength(S) 且 0 <= len <= StrLength(S)-pos+1 if (pos < 1 || pos > StrLength(S) || len < 0 || len > StrLength(S) - pos + 1) return ERROR; if (Sub.ch) free(Sub.ch); if (!len){ Sub.ch = NULL; Sub.length = 0; } else{ Sub.ch = (char *)malloc(len * sizeof(char)); for (int i = 0; i < len; i++){ Sub.ch[i] = S.ch[pos - 1 + i]; } Sub.length = len; } return OK; }// SubString int Index(HString S, HString T, int pos){ // 串S与T存在,T为非空串,1 <= pos <= StrLength(S) // 若主串S中存在和串T值相同的值,则返回它在主串S中第pos个字符之后第一次出现的 // 位置,否则返回0 int n, m, i; HString sub; if (pos < 1 || pos > StrLength(S)) return ERROR; if (pos > 0){ n = StrLength(S); m = StrLength(T); i = pos; while (i <= n - m + 1){ SubString(sub, S, i, m); if (StrCompare(sub, T) != 0){ ++i; } else{ return i; } }// while }// if return 0; }// Index Status Replace(HString &S, HString T, HString V){ // 串S,T和V存在,T非空 // 用V替代主串S中存现的所有与T相等的不重叠的子串 int n, i=1; HString Sub; Sub.ch = NULL; if (!S.ch || !V.ch || !T.ch || !T.length) return ERROR; n = T.length; while (i <= S.length){ if (!(SubString(Sub, S, i, n))){ break; } if (StrCompare(T, Sub)){ i++; continue; } StrDelete(S, i, n); StrInsert(S, i, V); i += StrLength(V) - n; } return OK; }// Replace Status StrInsert(HString &S, int pos, HString T){ // 串S与T存在,1 <= pos <= StrLength(S)+1 // 在串S的第pos个字符前插入串T if (pos < 1 || pos >StrLength(S) + 1) return ERROR; HString SubFront, SubRear, Temp; SubFront.ch = SubRear.ch = Temp.ch = NULL; SubString(SubFront, S, 1, pos - 1); SubString(SubRear, S, pos, StrLength(S) - pos + 1); Concat(Temp, SubFront, T); Concat(S, Temp, SubRear); return OK; }// StrInsert Status StrDelete(HString &S, int pos, int len){ // 串S存在,1 <= pos <= StrLength(S)-len+1 // 从串S中删除第pos个字符起长度为len的子串 if (pos < 1 || pos > StrLength(S) - len + 1) return ERROR; HString Sub, T; Sub.ch = T.ch = NULL; SubString(Sub, S, 1, pos - 1); Sub.length = pos - 1; SubString(T, S, pos + len , StrLength(S) - len - pos +1); T.length = StrLength(S) - len - pos + 1; Concat(S, Sub, T); return OK; }// StrDelete Status Destroy(HString &S){ // 销毁S if (!S.ch) return ERROR; free(S.ch); return OK; }// Destroy
2afad3a09d754681fa7beedad77466cc449b8790
ed7707d688179fb85db081a6df62efa757f5eaa7
/BibleMap/test.cpp
a9446e3ec20aac2c15cf0a449833152cac729821
[]
no_license
jeremyc61298/BibleMap
ed352e95d45f3973f75bed67286bd2810761dbe3
da00fbdee0bd3fa0608e20376f784518c9d35a49
refs/heads/master
2021-03-22T02:59:28.241082
2018-03-23T22:33:05
2018-03-23T22:33:05
123,375,726
1
0
null
null
null
null
UTF-8
C++
false
false
708
cpp
test.cpp
#include "Map.hpp" #include <iostream> using util::Map; using std::cout; using std::endl; void main() { Map<int, float> myNums; // adding key/value pairs myNums[1] = 1.1; myNums[5] = 5.5; // retrieving values cout << myNums[1] << " was added into the map. " << endl; cout << myNums[5] << " was added into the map." << endl; // updating values cout << myNums[5] << " was changed to "; myNums[5] = 55.5; cout << myNums[5] << endl; // exceptions are thrown when no value is matched to the key try { float f = myNums[4]; } catch (std::range_error e) { cout << e.what() << endl; } try { float * pf = &myNums[4]; } catch (std::range_error e) { cout << e.what() << endl; } }
4b8754f2a2ee1a92901fe03825f3596206d17e07
cf907178b934ac221a300124cf01bdeb51010183
/OOP_CPP/ChapterTen.cpp
7754cfa5283e951181f4ed50403e857056ef6e23
[]
no_license
bence7999/OOP_CPP
a375893a1e8fcefae2450849ce4f111f2b65312b
3644bb9ce0ff296f6be9d6b58916d309a2e28063
refs/heads/master
2021-09-16T20:05:18.654051
2018-06-24T09:41:33
2018-06-24T09:41:33
117,330,313
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
12,592
cpp
ChapterTen.cpp
#include "ChapterTen.h" using namespace std; namespace ChapterTen { // Write a program to display a digital clock. Use the principle of multiple inheritance for class clock. class Time1 { protected: int hr; int min; int sec; public: Time1(int h, int m, int s); void showTime(); }; class Date { protected: int date, month, year; public: Date(int d, int m, int y); void showDate(); }; Time1::Time1(int h, int m, int s) { hr = h; min = m; sec = s; } class Clock : public Time1, public Date { private: char strg[5]; public: Clock(int h, int m, int s, int da, int mo, int ye); void show(); }; void Dclock1() { class Clock t(11, 59, 40, 15, 8, 2010); cout << "DIGITAL CLOCK" << endl; t.show(); } void Time1::showTime() { cout << hr << " :"; cout << min << " : "; cout << sec << "\n"; } Clock::Clock(int h, int m, int s, int da, int mo, int ye) :Time1(h, m, s), Date(da, mo, ye) { if (h >= 12) strcpy_s(strg, "PM"); else strcpy_s(strg, "AM"); }; void Clock::show() { cout << setw(2) << hr << " : "; cout << setw(2) << min << " : "; cout << setw(2) << sec << " "; cout << strg << endl; cout << date << " : " << month << " : " << year << endl; } Date::Date(int d, int m, int y) { date = d; month = m; year = y; } void Date::showDate() { cout << date << " : " << month << " : " << year << "\n"; } // Write a program to demonstrate multilevel inheritance with data members declared “protected”. class NameBook { protected: char name[40]; public: NameBook(char * st1) { strcpy_s(name, st1); } void show() { cout << "name" << endl; } }; class TeleBook : public NameBook { protected: long telephone; public: TeleBook(char * st1, long tn); void show() { cout << name << " " << telephone << endl; } }; TeleBook::TeleBook(char * stx, long tn) : NameBook(stx) { telephone = tn; }; class AddressBook : public TeleBook { public: char city[40]; AddressBook(char * st1, long n, char * st3) : TeleBook(st1, n) { strcpy_s(city, st3); } void show() { cout << name << " " << telephone << " " << city << endl; } }; void Multi2() { cout << "<-- - multi2.cpp--->" << endl; class AddressBook me("prof", 24567890, "Mumbai"); me.show(); // cout « me.telephone « endl; } // Hybrid inheritance typedef char string[20]; class PlainTicket { protected: int fare; int classT; //class is reserved word string sStation; public: PlainTicket(int fare, int classT, string sStation); void print(); //show() }; class SimpleTicket : public PlainTicket { protected: string dStation; public: // void print() ; //For testing overloaded SimpleTicket(string dStation, int fare, int classT, string sStation); }; class PaxInfo // passenger information { protected: string name; int age; char sex; //‘M’ or ‘F’ public: PaxInfo(string name, int age, char sex); }; class ReservedTicket : public SimpleTicket, public PaxInfo { protected: long pnrNo; int trainNo; public: ReservedTicket(long PNR, int train, string dStation, int fare, int classT, string sStation, string name, int age, char sex); void print(); //overloaded }; void Hybrid2() { cout << "<-hybrid2.cpp--->" <<endl; ReservedTicket rt1(500001, 12124, "Dadar", 270, 1, "Pune", "Shahid kapoor", 30, 'M'); rt1.print(); } PlainTicket::PlainTicket(int fare, int classT, string sStation) { this->fare = fare; this->classT = classT; strcpy_s(this->sStation, sStation); } void PlainTicket::print() { cout << "***Plain Ticket***" << endl; cout << " fare Rs : " << fare << " Class" << endl; } PaxInfo::PaxInfo(string name, int age, char sex) { strcpy_s(this->name, name); this->age = age; this->sex = sex; } SimpleTicket::SimpleTicket(string dStation, int fare, int classT, string sStation) : PlainTicket(fare, classT, sStation) { strcpy_s(this->dStation, dStation); } ReservedTicket::ReservedTicket(long PNR, int train, string dStation, int fare, int classT, string sStation, string name, int age, char sex): SimpleTicket(dStation, fare, classT, sStation), PaxInfo(name, age, sex) { pnrNo = PNR; trainNo = train; strcpy_s(this->dStation, dStation); this->fare = fare; this->classT = classT; strcpy_s(this->sStation, sStation); strcpy_s(this->name, name); this->age = age; this->sex = sex; } void ReservedTicket::print() { cout << "***** Reserved Ticket *****" << endl; cout << "PNR No : " << pnrNo << "train No : " << trainNo << endl; cout << "From: " << sStation << " To : " << dStation << endl; cout << " fare Rs : " << fare << " Class " << classT << endl; cout << " Passenger Name Age Sex " << endl; cout << setw(15) << name << setw(6) << age << " " << sex << endl; }; // Write a program to illustrate the concept of virtual base class. class Employee { protected: int emp_code; public: Employee(); void display(); }; class Faculty : public virtual Employee { protected: char sub[10]; public: Faculty(); void display(); }; class LabStaff : public virtual Employee { protected: float Lb; public: LabStaff(); void display(); }; class Instructor : public Faculty, public LabStaff { public: Instructor(); void display(); }; void Vbase1() { cout << "<-- - vbase1.cpp--->" << endl; Instructor inst1; cout << "Display result " << endl; inst1.display(); cout << "-------------------------" << endl; Faculty ft; ft.display(); LabStaff ls; ls.display(); } Employee::Employee() { cout << "Enter Employee code : "; cin >> emp_code; } void Employee::display() { cout << "Employee code : " << emp_code << endl; } Faculty::Faculty() { cout << "Enter subject name : "; cin >> sub; } void Faculty::display() { Employee::display(); cout << "Subject taught : " << sub << endl; } LabStaff::LabStaff() { cout << "Enter Labcode real no : "; cin >> Lb; } void LabStaff::display() { Employee::display(); cout << "Lab code : " << Lb << endl; } Instructor::Instructor() { // no assignment statements // as no attributes to initialize } void Instructor::display() { cout << "emp_code : " << emp_code << endl; cout << "subject : " << sub << endl; cout << "Lab code : " << Lb << endl; } // Define a class Quadrangle. It should contain a method for finding the centre of gravity. Derive a class Rectangle from class Quadrangle. class Quadrangle { protected: int px1, py1, px2, py2, px3, py3, px4, py4; public: Quadrangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); void show(); void centreOfGravity(int &X, int &Y); }; class Rectangle : public Quadrangle { public: Rectangle(int x1, int y1, int x3, int y3); }; void Is_a() { cout << "<-- - is_a.cpp--->" << endl; int cgx, cgy; class Rectangle rect1(125, 125, 250, 250); cout << "showing rectangle" << endl; rect1.show(); rect1.centreOfGravity(cgx, cgy); cout << "its center of gravity is at " << endl; cout << "(" << cgx << ", " << cgy << ")" << endl; } Quadrangle::Quadrangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { px1 = x1; py1 = y1; px2 = x2; py2 = y2; px3 = x3; py3 = y3; px4 = x4; py4 = y4; } void Quadrangle::show() { cout << "The points are : " << endl; cout << "(" << px1 << ", " << py1 << ")" << endl; cout << "(" << px2 << ", " << py2 << ")" << endl; cout << "(" << px3 << ", " << py3 << ")" << endl; cout << "(" << px4 << ", " << py4 << ")" << endl; } void Quadrangle::centreOfGravity(int & X, int & Y) { X = (px1 + px2 + px3 + px4) / 4; Y = (py1 + py2 + py3 + py4) / 4; return; }; Rectangle::Rectangle(int x1, int y1, int x3, int y3): Quadrangle(x1, y1, x1, y3, x3, y3, x3, y1) { // interesting point to note is that // this constructor has no body }; // Define a class Point. Define a class Quadrangle. It should contain class Point. Create an object of type Quadrangle. Find the centre of gravity for this Quadrangle. class Quadrangle_2; class Point { int xc, yc; public: void setpoint(int i, int j); void show(); friend class Quadrangle_2; }; class Quadrangle_2 { Point p1, p2, p3, p4; public: Quadrangle_2(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); void show(); Point centre_of_gravity(); }; void Has_a() { Quadrangle_2 abc(50, 150, 200, 150, 100, 80, 180, 100); Point PT1; cout << "<-- - has_a.cpp--->" << endl; abc.show(); PT1 = abc.centre_of_gravity(); cout << "center of gravity at " << endl; PT1.show(); } Quadrangle_2::Quadrangle_2(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { p1.setpoint(x1, y1); p2.setpoint(x2, y2); p3.setpoint(x3, y3); p4.setpoint(x4, y4); } void Quadrangle_2::show() { cout << "A quadrangle consists of following points" << endl; p1.show(); p2.show(); p3.show(); p4.show(); cout << endl; } void Point::setpoint(int i, int j) { xc = i; yc = j; } void Point::show() { cout << "Point = "; cout << "(" << xc; cout << ", " << yc << ")" << endl; } Point Quadrangle_2::centre_of_gravity() { Point temp; int xg, yg; xg = p1.xc + p2.xc + p3.xc + p4.xc; xg = xg / 4; yg = p1.yc + p2.yc + p3.yc + p4.yc; yg = yg / 4; temp.xc = xg; temp.yc = yg; return temp; }; /////////////////////////// //// TASKS //// /////////////////////////// // 1. What do you understand by the term multiple inheritance? // 2. Why access specifier protected is useful in multilevel inheritance? // 3. Explain ‘Ambiguity Resolution in Multiple Inheritances’. // 4. What is the practical problem (difficulty) with multipath inheritance? How is it solved? // 5. Write a detailed note on classification of inheritance. // 6. What are the different forms of inheritance supported by C++? Explain by writing statements of each type. // 7. What type of relationship exists between class StraightLine and class Point? Write a simple program to illustrate your answer. class Pont { public: int x, y; Pont(); Pont(int, int); void setPoint(int, int); ~Pont(); }; Pont::Pont() { x = 0; y = 0; } Pont::Pont(int x, int y){ this->x = x; this->y = y; } void Pont::setPoint(int x, int y) { this->x = x; this->y = y; } Pont::~Pont() { } class StraightLine { public: StraightLine(int x1, int y1, int x2, int y2); ~StraightLine(); void getEquation(); private: Pont p1, p2; }; StraightLine::StraightLine(int x1, int y1, int x2, int y2){ this->p1.setPoint(x1, y1); this->p2.setPoint(x2, y2); } StraightLine::~StraightLine(){} void StraightLine::getEquation() { int x1 = this->p1.x; int y1 = this->p1.y; int x2 = this->p2.x; int y2 = this->p2.y; //cout << "x1: " << x1 << " y1: " << y1 << " x2: " << x2 << " y2: " << y2 << endl; int ivx = x2 - x1; int ivy = y2 - y1; //cout << "iranyvec x: " << ivx << " iranyvec y: " << ivy << endl; int nvx = ivy; int nvy = -1 * ivx; //cout << "normalcev x: " << nvx << " normalvec y" << nvy << endl; cout << nvx << "x + " << nvy << "y = " << nvx * x1 + nvy * y1 << endl; } void PointInLine() { StraightLine sl(-4, 3, 5, -2); sl.getEquation(); StraightLine sl2(1, 2, 3, 4); sl2.getEquation(); StraightLine sl3(6, -11, 8, 5); sl3.getEquation(); } // 8. What type of relationship exists between class Manager and class Employee? Write a simple program to illustrate your answer. class Employee2 { public: Employee2(int); ~Employee2(); private: int emp_id; }; Employee2::Employee2(int id){ emp_id = id; } Employee2::~Employee2() { } class Manager: public Employee2 { public: Manager(int, int); ~Manager(); private: int salary; }; Manager::Manager(int id, int sal):Employee2(id){ salary = sal; } Manager::~Manager() { } // 9. Consider a case of university having the disciplines of Engineering, Medicine, Management, and Science. // There are many colleges in the university. Assuming a college can run a course pertaining to only one discipline, draw the class diagram. // To which type does this structure belong? How will you classify it? // 10. In the above problem, assume that a college can run courses pertaining to any two disciplines. Draw the class diagram. What will be the type of this structure? How will you classify it? // 11. Redesign class “ReservedTicket” such that it has it has object(s) of class paxInfo as is member(has–a relationship). }
aa422cf4a56e3ee6fe1840b38b23c28a6dc9956a
21220c2f2319f9e6a45c5de2fb54d9d00e57eb28
/myTime.h
4a1ae47aefc7232d9b0f5c98f1a9555acc30c37d
[]
no_license
rimand/myTime
119c965822449121e17becce1031b7461374d611
430608d347a7ed8c639588050e43d305f8127ee6
refs/heads/master
2021-01-19T06:47:06.529556
2016-06-15T18:39:00
2016-06-15T18:39:00
61,231,025
0
0
null
null
null
null
UTF-8
C++
false
false
450
h
myTime.h
/** * @file myTime.h * @date 16-Jun-2016 * @author Vichagorn lupponglung * * * Rimand (c) by Vichagorn lupponglung */ #ifndef _MY_TIME_H_ #define _MY_TIME_H_ #include <Arduino.h> #include <time.h> class myTime{ public: myTime(void); bool begin(int timeZone,int dst); char* getTime(); int getTime_hour(); int getTime_min(); int getTime_sec(); private: time_t _now; struct tm* p_tm; }; #endif
13a321ff05e79d3b031d385a1fc414de22561bdd
bbeaadef08cccb872c9a1bb32ebac7335d196318
/Fontes/Rede/VTSuprimento.h
ad20b1fea3a64de4e5f1ebc3d010d4ff956d6fe8
[]
no_license
danilodesouzapereira/plataformasinap_exportaopendss
d0e529b493f280aefe91b37e893359a373557ef8
c624e9e078dce4b9bcc8e5b03dd4d9ea71c29b3f
refs/heads/master
2023-03-20T20:37:21.948550
2021-03-12T17:53:12
2021-03-12T17:53:12
347,150,304
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,143
h
VTSuprimento.h
//--------------------------------------------------------------------------- #ifndef VTSuprimentoH #define VTSuprimentoH //arquivos incluídos----------------------------------------------------------- #include <Classes.hpp> #include "Estrutura.h" #include "TEqbar.h" #include "..\Constante\Const.h" //--------------------------------------------------------------------------- class VTCurva; class VTResFlowSup; //--------------------------------------------------------------------------- class VTSuprimento : public TEqbar { public: //property __property bool Reducao = {read=PD_SUP.reducao, write=PD_SUP.reducao}; __property int Fases = {read=PD_SUP.fases, write=PD_SUP.fases}; __property bool DefinidoPorFase = {read=PM_GetDefinidoPorFase}; public: __fastcall VTSuprimento(void) {}; virtual __fastcall ~VTSuprimento(void) {}; virtual VTSuprimento* __fastcall Clone(void) = 0; virtual void __fastcall DefineCurva(VTCurva *curva)=0; protected: //métodos acessados via property virtual bool __fastcall PM_GetDefinidoPorFase(void) = 0; public: //dados locais int tiposup; //tipo do suprimento{supPV, supPQ, supVF} float vnom; //kV float smax; //capacidade máxima de fornecimento (MVA) strPOT pcc_3f, pcc_ft; //pot.curto em MVA strIMP zeq0, zeq1; //impedância equivalentes em pu, Sb=100MVA VTCurva *curva; VTResFlowSup *resflow; protected: //dados acessados via property struct { bool reducao; //suprimento de redução int fases; } PD_SUP; }; //--------------------------------------------------------------------------- //função global p/ criar objeto da classe Suprimento //--------------------------------------------------------------------------- VTSuprimento* __fastcall NewObjSuprimento(int num_pat); //--------------------------------------------------------------------------- #endif //eof